class EmptySlot(): MOUNT = 0 UNMOUNT = 1 def __init__(self, Contents, callback): self.callback = callback self.container = Console() (self.firstslot, self.numberofslots, self.mtdboot) = SystemInfo["canMultiBoot"] self.slot = Contents if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.phase = self.MOUNT self.run() def run(self): self.container.ePopen( 'mount /dev/SystemInfo["canMultiBoot"][2]%s /tmp/testmount' % str(self.slot * 2 + self.firstslot) if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): os.rename('/tmp/testmount/usr/bin/enigma2', '/tmp/testmount/usr/bin/enigmax.bin') self.phase = self.UNMOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback()
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.phase = self.MOUNT self.run() else: callback({}) def run(self): self.container.ePopen('mount /dev/mmcblk0p%s /tmp/testmount' % str(self.slot * 2 + 1) if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): self.imagelist[self.slot] = { 'imagename': open("/tmp/testmount/etc/issue").readlines()[-2].capitalize().strip()[:-6] } self.phase = self.UNMOUNT self.run() elif self.slot < 4: self.slot += 1 self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class EmptySlot(): MOUNT = 0 UNMOUNT = 1 def __init__(self, Contents, callback): self.callback = callback self.container = Console() (self.firstslot, self.numberofslots, self.mtdboot) = SystemInfo["canMultiBoot"] self.slot = Contents if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') if SystemInfo["HasSDmmc"]: # allow for mmc & SDcard in passed slot number, so SDcard slot -1 self.slot -= 1 self.part = "%s%s" %(self.mtdboot, str(self.slot * 2 + self.firstslot)) if SystemInfo["HasSDmmc"] and self.slot == 0: # this is the mmc slot, so pick up from MtdRoot self.part = getMachineMtdRoot() self.phase = self.MOUNT self.run() def run(self): self.container.ePopen('mount /dev/%s /tmp/testmount' %self.part if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): os.rename('/tmp/testmount/usr/bin/enigma2', '/tmp/testmount/usr/bin/enigmax.bin') self.phase = self.UNMOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback()
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def collectDataForInterface(self, iface): w = Wireless(iface) wsconfig = {} simpleConfigs = ( ("essid", w.getEssid, "off"), ("frequency", w.getFrequency, ""), ("accesspoint", w.getAPaddr, "Not-Associated"), ("bitrate", w.getBitrate, "0"), ("encryption", w.getEncryption, "off"), ) for name, func, default in simpleConfigs: try: wsconfig[name] = func() except: wsconfig[name] = default try: wsconfig["quality"] = str( Iwstats("wlan0").qual.quality) + "/" + str( w.getQualityMax().quality) except: wsconfig["quality"] = "" try: wsconfig["signal"] = str(w.getQualityAvg().siglevel - 128) + " dBm" except: wsconfig["signal"] = "" return wsconfig def getDataForInterface(self, iface, callback=None): wsconfig = self.collectDataForInterface(iface) self.wlaniface[iface] = wsconfig self.backupwlaniface = self.wlaniface if callback is not None: callback(True, self.wlaniface) return self.wlaniface def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.iface in self.wlaniface and attribute in self.wlaniface[ self.iface]: return self.wlaniface[self.iface][attribute] return None
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots) = SystemInfo["canMultiBoot"][:2] self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.phase = self.MOUNT self.run() else: callback({}) def run(self): if SystemInfo["HasRootSubdir"]: if self.slot == 1: self.container.ePopen('mount /dev/block/by-name/linuxrootfs /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.container.ePopen('mount /dev/block/by-name/userdata /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.container.ePopen('mount /dev/%sp%s /tmp/testmount' % (SystemInfo["canMultiBoot"][2], str(self.slot * 2 + self.firstslot)) if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if SystemInfo["HasRootSubdir"]: if os.path.isfile("/tmp/testmount/linuxrootfs1/usr/bin/enigma2"): import datetime self.imagelist[self.slot] = { 'imagename': "%s (%s)" % (open("/tmp/testmount/linuxrootfs1/etc/issue").readlines()[-2].capitalize().strip()[:-6], datetime.datetime.fromtimestamp(os.stat("/tmp/testmount/linuxrootfs1/usr/share/bootlogo.mvi").st_mtime).strftime('%Y-%m-%d'))} elif os.path.isfile("/tmp/testmount/linuxrootfs%s/usr/bin/enigma2" % self.slot): import datetime self.imagelist[self.slot] = { 'imagename': "%s (%s)" % (open("/tmp/testmount/linuxrootfs%s/etc/issue" % self.slot).readlines()[-2].capitalize().strip()[:-6], datetime.datetime.fromtimestamp(os.stat("/tmp/testmount/linuxrootfs%s/usr/share/bootlogo.mvi" % self.slot).st_mtime).strftime('%Y-%m-%d'))} else: self.imagelist[self.slot] = { 'imagename': _("Empty slot")} else: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): import datetime self.imagelist[self.slot] = { 'imagename': "%s (%s)" % (open("/tmp/testmount/etc/issue").readlines()[-2].capitalize().strip()[:-6], datetime.datetime.fromtimestamp(os.stat("/tmp/testmount/usr/share/bootlogo.mvi").st_mtime).strftime('%Y-%m-%d'))} else: self.imagelist[self.slot] = { 'imagename': _("Empty slot")} self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.imagelist[self.slot] = { 'imagename': _("Empty slot")} self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def collectDataForInterface(self, iface): w = Wireless(iface) wsconfig = { } simpleConfigs = ( ("essid", w.getEssid, "off"), ("frequency", w.getFrequency, ""), ("accesspoint", w.getAPaddr, "Not-Associated"), ("bitrate", w.getBitrate, "0"), ("encryption", w.getEncryption, "off"), ) for name, func, default in simpleConfigs: try: wsconfig[name] = func() except: wsconfig[name] = default try: wsconfig["quality"] = str(Iwstats("wlan0").qual.quality) + "/" + str(w.getQualityMax().quality) except: wsconfig["quality"] = "" try: wsconfig["signal"] = str(w.getQualityAvg().siglevel-128) + " dBm" except: wsconfig["signal"] = "" return wsconfig def getDataForInterface(self, iface, callback = None): wsconfig = self.collectDataForInterface(iface) self.wlaniface[iface] = wsconfig self.backupwlaniface = self.wlaniface if callback is not None: callback(True, self.wlaniface) return self.wlaniface def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.iface in self.wlaniface: if attribute in self.wlaniface[self.iface]: return self.wlaniface[self.iface][attribute] return None
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: self.slots = sorted(SystemInfo["canMultiBoot"].keys()) self.callback = callback self.imagelist = {} if not os.path.isdir(TMP_MOUNT): os.mkdir(TMP_MOUNT) self.container = Console() self.phase = self.MOUNT self.run() else: callback({}) def run(self): if self.phase == self.UNMOUNT: self.container.ePopen('umount %s' % TMP_MOUNT, self.appClosed) else: self.slot = self.slots.pop(0) self.container.ePopen('mount %s %s' % (SystemInfo["canMultiBoot"][self.slot]['device'], TMP_MOUNT), self.appClosed) def appClosed(self, data="", retval=0, extra_args=None): if retval: self.imagelist[self.slot] = { 'imagename': _("Empty slot") } if retval == 0 and self.phase == self.MOUNT: imagedir = os.sep.join(filter(None, [TMP_MOUNT, SystemInfo["canMultiBoot"][self.slot].get('rootsubdir', '')])) if os.path.isfile(os.path.join(imagedir, 'usr/bin/enigma2')): try: from datetime import datetime date = datetime.fromtimestamp(os.stat(os.path.join(imagedir, "var/lib/opkg/status")).st_mtime).strftime('%Y-%m-%d') if date.startswith("1970"): date = datetime.fromtimestamp(os.stat(os.path.join(imagedir, "usr/share/bootlogo.mvi")).st_mtime).strftime('%Y-%m-%d') date = max(date, datetime.fromtimestamp(os.stat(os.path.join(imagedir, "usr/bin/enigma2")).st_mtime).strftime('%Y-%m-%d')) except: date = _("Unknown") self.imagelist[self.slot] = { 'imagename': "%s (%s)" % (open(os.path.join(imagedir, "etc/issue")).readlines()[-2].capitalize().strip()[:-6], date) } else: self.imagelist[self.slot] = { 'imagename': _("Empty slot") } if self.slots and SystemInfo["canMultiBoot"][self.slot]['device'] == SystemInfo["canMultiBoot"][self.slots[0]]['device']: self.slot = self.slots.pop(0) self.appClosed() else: self.phase = self.UNMOUNT self.run() elif self.slots: self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount(TMP_MOUNT): os.rmdir(TMP_MOUNT) self.callback(self.imagelist)
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots) = SystemInfo["canMultiBoot"][:2] self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.phase = self.MOUNT self.run() else: callback({}) def run(self): self.container.ePopen( 'mount /dev/%sp%s /tmp/testmount' % (SystemInfo["canMultiBoot"][2], str(self.slot * 2 + self.firstslot)) if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): import datetime self.imagelist[self.slot] = { 'imagename': "%s (%s)" % (open("/tmp/testmount/etc/issue").readlines() [-2].capitalize().strip()[:-6], datetime.datetime.fromtimestamp( os.stat("/tmp/testmount/usr/share/bootlogo.mvi"). st_mtime).strftime('%Y-%m-%d')) } else: self.imagelist[self.slot] = {'imagename': _("Empty slot")} self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.imagelist[self.slot] = {'imagename': _("Empty slot")} self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class Ceparted(Screen): skin = """<screen position="center,center" size="600,200" title="eParted v0.13"> <widget name="list" position="5,5" size="590,190" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.Exit, "ok": self.Ok }, -1) self["list"] = MenuList(list=[]) self.Console = Console() global rereaddevices rereaddevices = True self.__readDev() def Ok(self): sel = self["list"].getCurrent() if sel and sel[1]: global rereaddevices rereaddevices = False self.session.openWithCallback(self.__readDev, Cpart, sel[1]) def __readDev(self): global rereaddevices if rereaddevices: self.Console.ePopen("parted -m -l", self.__FinishedConsole) def Exit(self): self.Console.killAll() self.close() #cleanexit(__name__) def __FinishedConsole(self, result, retval, extra_args=None): result = six.ensure_str(result) if retval == 0 and '\n' in result: list = [] for x in parseCmd(result): if x[0][LIST_TYPE] == LIST_TYPE_DEV: name = x[0][DEV_NAME] if len(name) == 0: name = x[0][DEV_PATH] tstr = name tstr += " (%s - %d %s %s)" % (x[0][DEV_SIZE], len(x) - 1, _("partition(s)"), x[0][DEV_PATH]) list.append((tstr, (name, x[0][DEV_PATH], x[0][DEV_SIZE]))) self["list"].setList(list)
class Ceparted(Screen): skin = """<screen position="center,center" size="820,320" title="eParted v0.13"> <widget name="list" position="10,10" size="800,300" enableWrapAround="1" scrollbarMode="showOnDemand"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.Exit, "ok": self.Ok }, -1) self["list"] = MenuList(list=[]) self.Console = Console() global rereaddevices rereaddevices = True self.__readDev() def Ok(self): sel = self["list"].getCurrent() if sel and sel[1]: global rereaddevices rereaddevices = False self.session.openWithCallback(self.__readDev, Cpart, sel[1]) def __readDev(self): global rereaddevices if rereaddevices: self.Console.ePopen("parted -m -l", self.__FinishedConsole) def Exit(self): self.Console.killAll() self.close() #cleanexit(__name__) def __FinishedConsole(self, result, retval, extra_args=None): if retval == 0 and '\n' in result: list = [] for x in parseCmd(result): if x[0][LIST_TYPE] == LIST_TYPE_DEV: name = x[0][DEV_NAME] if len(name) == 0: name = x[0][DEV_PATH] tstr = name tstr += " (%s - %d %s %s)" % (x[0][DEV_SIZE], len(x) - 1, _("partition(s)"), x[0][DEV_PATH]) list.append((tstr, (name, x[0][DEV_PATH], x[0][DEV_SIZE]))) self["list"].setList(list)
class EmptySlot(): MOUNT = 0 UNMOUNT = 1 def __init__(self, Contents, callback): if SystemInfo["canMultiBoot"]: self.slots = sorted(SystemInfo["canMultiBoot"].keys()) self.callback = callback self.imagelist = {} self.slot = Contents if not path.isdir(Imagemount): mkdir(Imagemount) self.container = Console() self.phase = self.MOUNT self.run() else: callback({}) def run(self): if self.phase == self.UNMOUNT: self.container.ePopen("umount %s" % Imagemount, self.appClosed) else: self.container.ePopen( "mount %s %s" % (SystemInfo["canMultiBoot"][self.slot]["device"], Imagemount), self.appClosed) def appClosed(self, data="", retval=0, extra_args=None): if retval == 0 and self.phase == self.MOUNT: if SystemInfo["HasRootSubdir"] and SystemInfo["canMultiBoot"][ self.slot]["rootsubdir"] != None: imagedir = ( '%s/%s' % (Imagemount, SystemInfo["canMultiBoot"][self.slot]["rootsubdir"])) else: imagedir = Imagemount if path.isfile("%s/usr/bin/enigma2" % imagedir): rename("%s/usr/bin/enigma2" % imagedir, "%s/usr/bin/enigmax.bin" % imagedir) rename("%s/etc" % imagedir, "%s/etcx" % imagedir) self.phase = self.UNMOUNT self.run() else: self.container.killAll() if not path.ismount(Imagemount): rmdir(Imagemount) self.callback()
class EmptySlot(): MOUNT = 0 UNMOUNT = 1 def __init__(self, Contents, callback): self.callback = callback self.container = Console() self.slot = Contents if not path.isdir("/tmp/testmount"): mkdir("/tmp/testmount") self.phase = self.MOUNT self.run() def run(self): if SystemInfo["HasRootSubdir"] and SystemInfo["canMultiBoot"][ self.slot]["rootsubdir"] != None: self.container.ePopen( "mount /dev/block/by-name/userdata /tmp/testmount" if self.phase == self.MOUNT else "umount /tmp/testmount", self.appClosed) else: self.container.ePopen( "mount %s /tmp/testmount" % (SystemInfo["canMultiBoot"][self.slot]["root"]) if self.phase == self.MOUNT else "umount /tmp/testmount", self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: if SystemInfo["HasRootSubdir"] and SystemInfo["canMultiBoot"][ self.slot]["rootsubdir"] != None: rootsub = SystemInfo["canMultiBoot"][self.slot]["rootsubdir"] if path.isfile("/tmp/testmount/%s/usr/bin/enigma2" % rootsub): rename("/tmp/testmount/%s/usr/bin/enigma2" % rootsub, "/tmp/testmount/%s/usr/bin/enigmax.bin" % rootsub) elif path.isfile("/tmp/testmount/usr/bin/enigma2"): rename("/tmp/testmount/usr/bin/enigma2", "/tmp/testmount/usr/bin/enigmax.bin") else: print "[multiboot2] NO enigma2 found to rename" self.phase = self.UNMOUNT self.run() else: self.container.killAll() if not path.ismount("/tmp/testmount"): rmdir("/tmp/testmount") self.callback()
class Network: def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "ethtool" self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.PingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: import Harddisk for parts in Harddisk.getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'sys0') def getInterfaces(self, callback = None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [ int(n) for n in ip.split('.') ] def getAddrInet(self, iface, callback): if not self.Console: self.Console = Console() cmd = "ip -o addr show dev " + iface self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback]) def IPaddrFinished(self, result, retval, extra_args): (iface, callback ) = extra_args data = { 'up': False, 'dhcp': False, 'preup' : False, 'predown' : False } globalIPpattern = re.compile("scope global") ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' netRegexp = '[0-9]{1,2}' macRegexp = '[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}' ipLinePattern = re.compile('inet ' + ipRegexp + '/') ipPattern = re.compile(ipRegexp) netmaskLinePattern = re.compile('/' + netRegexp) netmaskPattern = re.compile(netRegexp) bcastLinePattern = re.compile(' brd ' + ipRegexp) upPattern = re.compile('UP') macPattern = re.compile(macRegexp) macLinePattern = re.compile('link/ether ' + macRegexp) for line in result.splitlines(): split = line.strip().split(' ',2) if (split[1][:-1] == iface) or (split[1][:-1] == (iface + '@sys0')): up = self.regExpMatch(upPattern, split[2]) mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2])) if up is not None: data['up'] = True if iface is not 'lo': self.configuredInterfaces.append(iface) if mac is not None: data['mac'] = mac if (split[1] == iface): if re.search(globalIPpattern, split[2]): ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2])) netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2]))) bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2])) if ip is not None: data['ip'] = self.convertIP(ip) if netmask is not None: data['netmask'] = self.convertIP(netmask) if bcast is not None: data['bcast'] = self.convertIP(bcast) if not data.has_key('ip'): data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] cmd = "route -n | grep " + iface self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback]) def routeFinished(self, result, retval, extra_args): (iface, data, callback) = extra_args ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = re.compile(ipRegexp) ipLinePattern = re.compile(ipRegexp) for line in result.splitlines(): print line[0:7] if line[0:7] == "0.0.0.0": gateway = self.regExpMatch(ipPattern, line[16:31]) if gateway: data['gateway'] = self.convertIP(gateway) self.ifaces[iface] = data self.loadNetworkConfig(iface,callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") for ifacename, iface in self.ifaces.items(): if iface['up'] == True: fp.write("auto " + ifacename + "\n") self.configuredInterfaces.append(ifacename) if iface['dhcp'] == True: fp.write("iface "+ ifacename +" inet dhcp\n") if iface['dhcp'] == False: fp.write("iface "+ ifacename +" inet static\n") if iface.has_key('ip'): print tuple(iface['ip']) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if iface.has_key('gateway'): fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if iface.has_key("configStrings"): fp.write(iface["configStrings"]) if iface["preup"] is not False and not iface.has_key("configStrings"): fp.write(iface["preup"]) if iface["predown"] is not False and not iface.has_key("configStrings"): fp.write(iface["predown"]) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): fp = file('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() def loadNetworkConfig(self,iface,callback = None): interfaces = [] # parse the interfaces-file try: fp = file('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print "[Network.py] interfaces - opening failed" ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if (split[0] == "iface"): currif = split[1] ifaces[currif] = {} if (len(split) == 4 and split[3] == "dhcp"): ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if (currif == iface): #read information only for available interfaces if (split[0] == "address"): ifaces[currif]["address"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("ip"): if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = map(int, split[1].split('.')) if (split[0] == "netmask"): ifaces[currif]["netmask"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("netmask"): if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = map(int, split[1].split('.')) if (split[0] == "gateway"): ifaces[currif]["gateway"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("gateway"): if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = map(int, split[1].split('.')) if (split[0] == "pre-up"): if self.ifaces[currif].has_key("preup"): self.ifaces[currif]["preup"] = i if (split[0] in ("pre-down","post-down")): if self.ifaces[currif].has_key("predown"): self.ifaces[currif]["predown"] = i for ifacename, iface in ifaces.items(): if self.ifaces.has_key(ifacename): self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if self.Console: if len(self.Console.appContainers) == 0: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() print "read configured interface:", ifaces print "self.ifaces after loading:", self.ifaces self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = re.compile("nameserver +" + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = file('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print "[Network.py] resolv.conf - opening failed" for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) print "nameservers:", self.nameservers def getInstalledAdapters(self): return [x for x in os.listdir('/sys/class/net') if not self.isBlacklisted(x)] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _("WLAN connection") if len(self.wlan_interfaces): name += " " + str(len(self.wlan_interfaces)+1) self.wlan_interfaces.append(iface) else: if iface not in self.lan_interfaces: if iface == "eth1": name = _("VLAN connection") else: name = _("LAN connection") if len(self.lan_interfaces) and not iface == "eth1": name += " " + str(len(self.lan_interfaces)+1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = os.path.basename(os.path.realpath(moduledir)) if name.startswith('ath') or name.startswith('carl'): name = 'Atheros' elif name.startswith('rt2') or name.startswith('rt3') or name.startswith('rt5') or name.startswith('rt6') or name.startswith('rt7'): name = 'Ralink' elif name.startswith('zd'): name = 'Zydas' elif name.startswith('rtl') or name.startswith('r8'): name = 'Realtek' elif name.startswith('smsc'): name = 'SMSC' elif name.startswith('peg'): name = 'Pegasus' elif name.startswith('rn'): name = 'RNDIS' elif name.startswith('mw') or name.startswith('libertas'): name = 'Marvel' elif name.startswith('p5'): name = 'Prism' elif name.startswith('as') or name.startswith('ax'): name = 'ASIX' elif name.startswith('dm'): name = 'Davicom' elif name.startswith('mcs'): name = 'MosChip' elif name.startswith('at'): name = 'Atmel' elif name.startswith('iwm'): name = 'Intel' else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return self.ifaces.keys() def getAdapterAttribute(self, iface, attribute): return self.ifaces.get(iface, {}).get(attribute) def setAdapterAttribute(self, iface, attribute, value): print "setting for adapter", iface, "attribute", attribute, " to value", value if self.ifaces.has_key(iface): self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if self.ifaces.has_key(iface): if self.ifaces[iface].has_key(attribute): del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback = None): self.resetNetworkConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ip addr flush dev " + iface) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self,mode='lan', callback = None): fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.resetNetworkConsole = Console() self.commands = [] if mode == 'wlan': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig ath0 down") self.commands.append("ifconfig wlan0 up") if mode == 'wlan-mpci': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 up") if mode == 'lan': self.commands.append("ifconfig eth0 up") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 down") self.commands.append("/etc/init.d/avahi-daemon start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True) def resetNetworkFinished(self,extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: if callback is not None: callback(True,mode) def checkNetworkState(self,statecallback): self.NetworkState = 0 cmd1 = "ping -c 1 www.openpli.org" cmd2 = "ping -c 1 www.google.nl" cmd3 = "ping -c 1 www.google.com" self.PingConsole = Console() self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback) self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback) self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback) def checkNetworkStateFinished(self, result, retval,extra_args): (statecallback) = extra_args if self.PingConsole is not None: if retval == 0: self.PingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if len(self.PingConsole.appContainers) == 0: statecallback(self.NetworkState) def restartNetwork(self,callback = None): self.restartConsole = Console() self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self,extra_args): ( callback ) = extra_args if callback is not None: callback(True) def getLinkState(self,iface,callback): cmd = self.ethtool_bin + " " + iface self.LinkConsole = Console() self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback) def getLinkStateFinished(self, result, retval,extra_args): (callback) = extra_args if self.LinkConsole is not None: if len(self.LinkConsole.appContainers) == 0: callback(result) def stopPingConsole(self): if self.PingConsole is not None: if len(self.PingConsole.appContainers): for name in self.PingConsole.appContainers.keys(): self.PingConsole.kill(name) def stopLinkStateConsole(self): if self.LinkConsole is not None: if len(self.LinkConsole.appContainers): for name in self.LinkConsole.appContainers.keys(): self.LinkConsole.kill(name) def stopDNSConsole(self): if self.DnsConsole is not None: if len(self.DnsConsole.appContainers): for name in self.DnsConsole.appContainers.keys(): self.DnsConsole.kill(name) def stopRestartConsole(self): if self.restartConsole is not None: if len(self.restartConsole.appContainers): for name in self.restartConsole.appContainers.keys(): self.restartConsole.kill(name) def stopGetInterfacesConsole(self): if self.Console is not None: if len(self.Console.appContainers): for name in self.Console.appContainers.keys(): self.Console.kill(name) def stopDeactivateInterfaceConsole(self): if self.deactivateInterfaceConsole is not None: self.deactivateInterfaceConsole.killAll() self.deactivateInterfaceConsole = None def stopActivateInterfaceConsole(self): if self.activateInterfaceConsole is not None: self.activateInterfaceConsole.killAll() self.activateInterfaceConsole = None def checkforInterface(self, iface): return self.getAdapterAttribute(iface, 'up') def checkDNSLookup(self,statecallback): cmd1 = "nslookup www.dream-multimedia-tv.de" cmd2 = "nslookup www.heise.de" cmd3 = "nslookup www.google.de" self.DnsConsole = Console() self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback) self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback) self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback) def checkDNSLookupFinished(self, result, retval,extra_args): (statecallback) = extra_args if self.DnsConsole is not None: if retval == 0: self.DnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if len(self.DnsConsole.appContainers) == 0: statecallback(self.DnsState) def deactivateInterface(self,ifaces,callback = None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append("ifdown " + iface) commands.append("ip addr flush dev " + iface) #wpa_supplicant sometimes doesn't quit properly on SIGTERM if os.path.exists('/var/run/wpa_supplicant/'+ iface): commands.append("wpa_cli -i" + iface + " terminate") if not self.deactivateInterfaceConsole: self.deactivateInterfaceConsole = Console() if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces,callback], debug=True) def deactivateInterfaceFinished(self,extra_args): (ifaces, callback) = extra_args def checkCommandResult(iface): if self.deactivateInterfaceConsole and self.deactivateInterfaceConsole.appResults.has_key("ifdown " + iface): result = str(self.deactivateInterfaceConsole.appResults.get("ifdown " + iface)).strip("\n") if result == "ifdown: interface " + iface + " not configured": return False else: return True #ifdown sometimes can't get the interface down. if isinstance(ifaces, (list, tuple)): for iface in ifaces: if checkCommandResult(iface) is False: Console().ePopen(("ifconfig " + iface + " down" )) else: if checkCommandResult(ifaces) is False: Console().ePopen(("ifconfig " + ifaces + " down" )) if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def activateInterface(self,iface,callback = None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return if not self.activateInterfaceConsole: self.activateInterfaceConsole = Console() commands = [] commands.append("ifup " + iface) self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self,extra_args): callback = extra_args if self.activateInterfaceConsole: if len(self.activateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def sysfsPath(self, iface): return '/sys/class/net/' + iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True if os.path.isdir(self.sysfsPath(iface) + '/wireless'): return True # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless device = re.compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass if iface in ifnames: return True return False def getWlanModuleDir(self, iface = None): devicedir = self.sysfsPath(iface) + '/device' if not os.path.isdir(devicedir): return None moduledir = devicedir + '/driver/module' if os.path.isdir(moduledir): return moduledir # identification is not possible over default moduledir for x in os.listdir(devicedir): # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx if x.startswith("1-"): moduledir = devicedir + '/' + x + '/driver/module' if os.path.isdir(moduledir): return moduledir # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here moduledir = devicedir + '/driver' if os.path.isdir(moduledir): return moduledir return None def detectWlanModule(self, iface = None): if not self.isWirelessInterface(iface): return None devicedir = self.sysfsPath(iface) + '/device' if os.path.isdir(devicedir + '/ieee80211'): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = os.path.basename(os.path.realpath(moduledir)) if module in ('ath_pci','ath5k'): return 'madwifi' if module in ('rt73','rt73'): return 'ralink' if module == 'zd1211b': return 'zydas' return 'wext' def calc_netmask(self,nmask): from struct import pack, unpack from socket import inet_ntoa, inet_aton mask = 1L<<31 xnet = (1L<<32)-1 cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print 'cidr invalid: %d' % cidr return None else: nm = ((1L<<cidr)-1)<<(32-cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == "add": print "[Network] Add new interface:", interface self.getAddrInet(interface, None) elif action == "remove": print "[Network] Removed interface:", interface try: del self.ifaces[interface] except KeyError: pass
class MultibootSelection(SelectImage): def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "SelectImage" self.session = session self.imagesList = None self.expanded = [] self.setTitle(_("Select Multiboot")) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Reboot")) self["list"] = ChoiceList(list=[ChoiceEntryComponent('',((_("Retrieving image slots - Please wait...")), "Waiter"))]) self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions"], { "ok": self.keyOk, "cancel": boundFunction(self.close, None), "red": boundFunction(self.close, None), "green": self.keyOk, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.delay = eTimer() self.delay.callback.append(self.getImagesList) self.delay.start(0, True) def getImagesList(self, reply=None): self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagesdict): list = [] currentimageslot = GetCurrentImage() mode = GetCurrentImageMode() or 0 for x in sorted(imagesdict.keys()): if imagesdict[x]["imagename"] != _("Empty slot"): list.append(ChoiceEntryComponent('',((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagesdict[x]['imagename']), x))) if SystemInfo["canMode12"]: list.append(ChoiceEntryComponent('',((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagesdict[x]['imagename']), x + 12))) self["list"].setList(list) def keyOk(self): self.currentSelected = self["list"].l.getCurrentSelection() if self.currentSelected[0][1] != "Waiter": self.container = Console() if os.path.isdir('/tmp/startupmount'): self.ContainterFallback() else: os.mkdir('/tmp/startupmount') self.container.ePopen('mount /dev/mmcblk0p1 /tmp/startupmount', self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot = self.currentSelected[0][1] model = HardwareInfo().get_machine_name() if 'coherent_poll=2M' in open("/proc/cmdline", "r").read(): #when Gigablue do something else... this needs to be improved later!!! It even looks that the GB method is better :) shutil.copyfile("/tmp/startupmount/STARTUP_%s" % slot, "/tmp/startupmount/STARTUP") else: if slot < 12: startupFileContents = "boot emmcflash0.kernel%s 'root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=1'\n" % (slot, slot * 2 + 1, model) else: slot -= 12 startupFileContents = "boot emmcflash0.kernel%s 'brcm_cma=520M@248M brcm_cma=%s@768M root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=12'\n" % (slot, SystemInfo["canMode12"], slot * 2 + 1, model) open('/tmp/startupmount/STARTUP', 'w').write(startupFileContents) from Screens.Standby import TryQuitMainloop self.session.open(TryQuitMainloop, 2) def selectionChanged(self): pass
class Network: def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "/usr/sbin/ethtool" self.console = Console() self.linkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.dnsConsole = Console() self.pingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: from Components.Harddisk import getProcMounts for parts in getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'sys0', 'p2p0') def getInterfaces(self, callback=None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [int(n) for n in ip.split('.')] def getAddrInet(self, iface, callback): data = {'up': False, 'dhcp': False, 'preup': False, 'predown': False} try: data['up'] = int( open('/sys/class/net/%s/flags' % iface).read().strip(), 16) & 1 == 1 if data['up']: self.configuredInterfaces.append(iface) nit = ni.ifaddresses(iface) data['ip'] = self.convertIP(nit[ni.AF_INET][0]['addr']) # ipv4 data['netmask'] = self.convertIP(nit[ni.AF_INET][0]['netmask']) data['bcast'] = self.convertIP(nit[ni.AF_INET][0]['broadcast']) data['mac'] = nit[ni.AF_LINK][0]['addr'] # mac data['gateway'] = self.convertIP( ni.gateways()['default'][ni.AF_INET][0]) # default gw except: data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] self.ifaces[iface] = data self.loadNetworkConfig(iface, callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = open('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") for ifacename, iface in self.ifaces.items(): if iface['up']: fp.write("auto " + ifacename + "\n") self.configuredInterfaces.append(ifacename) if iface['dhcp']: fp.write("iface " + ifacename + " inet dhcp\n") fp.write("udhcpc_opts -T1 -t9\n") fp.write(" hostname $(hostname)\n") if not iface['dhcp']: fp.write("iface " + ifacename + " inet static\n") fp.write(" hostname $(hostname)\n") if 'ip' in iface: # print tuple(iface['ip']) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if 'gateway' in iface: fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if "configStrings" in iface: fp.write(iface["configStrings"]) if iface["preup"] is not False and "configStrings" not in iface: fp.write(iface["preup"]) if iface["predown"] is not False and "configStrings" not in iface: fp.write(iface["predown"]) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): fp = open('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() def loadNetworkConfig(self, iface, callback=None): interfaces = [] # parse the interfaces-file try: fp = open('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print("[Network] interfaces - opening failed") ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if split[0] == "iface": currif = split[1] ifaces[currif] = {} if len(split) == 4 and split[3] == "dhcp": ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if currif == iface: #read information only for available interfaces if split[0] == "address": ifaces[currif]["address"] = list( map(int, split[1].split('.'))) if "ip" in self.ifaces[currif]: if self.ifaces[currif]["ip"] != ifaces[currif][ "address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = list( map(int, split[1].split('.'))) if split[0] == "netmask": ifaces[currif]["netmask"] = list( map(int, split[1].split('.'))) if "netmask" in self.ifaces[currif]: if self.ifaces[currif]["netmask"] != ifaces[currif][ "netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = list( map(int, split[1].split('.'))) if split[0] == "gateway": ifaces[currif]["gateway"] = list( map(int, split[1].split('.'))) if "gateway" in self.ifaces[currif]: if self.ifaces[currif]["gateway"] != ifaces[currif][ "gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = list( map(int, split[1].split('.'))) if split[0] == "pre-up": if "preup" in self.ifaces[currif]: self.ifaces[currif]["preup"] = i if split[0] in ("pre-down", "post-down"): if "predown" in self.ifaces[currif]: self.ifaces[currif]["predown"] = i for ifacename, iface in ifaces.items(): if ifacename in self.ifaces: self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if not self.console.appContainers: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() print("[Network] read configured interface:", ifaces) print("[Network] self.ifaces after loading:", self.ifaces) self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = re.compile("nameserver +" + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = open('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print("[Network] resolv.conf - opening failed") for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) # print "nameservers:", self.nameservers def getInstalledAdapters(self): return [ x for x in listdir('/sys/class/net') if not self.isBlacklisted(x) ] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get( x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _("WLAN connection") if len(self.wlan_interfaces): name += " " + str(len(self.wlan_interfaces) + 1) self.wlan_interfaces.append(iface) else: if iface not in self.lan_interfaces: if iface == "eth1": name = _("VLAN connection") else: name = _("LAN connection") if len(self.lan_interfaces) and not iface == "eth1": name += " " + str(len(self.lan_interfaces) + 1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = path.basename(path.realpath(moduledir)) if name in ('ath_pci', 'ath5k'): name = 'Atheros' elif name in ('rt73', 'rt73usb', 'rt3070sta'): name = 'Ralink' elif name == 'zd1211b': name = 'Zydas' elif name == 'r871x_usb_drv': name = 'Realtek' elif path.exists("/tmp/bcm/%s" % iface): name = 'Broadcom' else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return list(self.ifaces.keys()) def getAdapterAttribute(self, iface, attribute): if iface in self.ifaces: if attribute in self.ifaces[iface]: return self.ifaces[iface][attribute] return None def setAdapterAttribute(self, iface, attribute, value): # print "setting for adapter", iface, "attribute", attribute, " to value", value if iface in self.ifaces: self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if iface in self.ifaces and attribute in self.ifaces[iface]: del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback=None): self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("/sbin/ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: self.writeDefaultNetworkConfig(mode, callback) def resetWiFiMac(self, Mac=None, wlan=None, callback=None): if Mac is not None: mode = wlan self.commands = [] self.commands.append("ifconfig %s down" % wlan) self.commands.append("ifconfig %s hw ether %s" % (wlan, Mac)) self.commands.append("ifconfig %s up" % wlan) self.resetNetworkConsole.eBatch(self.commands, self.resetWiFiMacFinishedCB, [mode, callback], debug=True) def resetWiFiMacFinishedCB(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self, mode='lan', callback=None): fp = open('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode in ("wlan0", "wlan3"): fp.write("auto %s\n" % mode) fp.write("iface %s inet dhcp\n" % mode) if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.commands = [] if mode in ("wlan0", "wlan3"): self.commands.append("/sbin/ifconfig eth0 down") self.commands.append("/sbin/ifconfig ath0 down") self.commands.append("/sbin/ifconfig %s up" % mode) if mode == 'wlan-mpci': self.commands.append("/sbin/ifconfig eth0 down") self.commands.append("/sbin/ifconfig wlan0 down") self.commands.append("/sbin/ifconfig ath0 up") if mode == 'lan': self.commands.append("/sbin/ifconfig eth0 up") self.commands.append("/sbin/ifconfig wlan0 down") self.commands.append("/sbin/ifconfig ath0 down") self.commands.append("/etc/init.d/avahi-daemon start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode, callback], debug=True) def resetNetworkFinished(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: if callback is not None: callback(True, mode) def checkNetworkState(self, statecallback): self.NetworkState = 0 self.pingConsole = Console() for server in ("www.microsoft.com", "www.google.com"): self.pingConsole.ePopen( ("/bin/ping", "/bin/ping", "-c", "1", server), self.checkNetworkStateFinished, statecallback) def checkNetworkStateFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.pingConsole is not None: if retval == 0: self.pingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if not self.pingConsole.appContainers: statecallback(self.NetworkState) def restartNetwork(self, callback=None): self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append(("/sbin/ifdown", "/sbin/ifdown", iface)) self.commands.append("/sbin/ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self, extra_args): (callback) = extra_args if callback is not None: callback(True) def getLinkState(self, iface, callback): self.linkConsole.ePopen((self.ethtool_bin, self.ethtool_bin, iface), self.getLinkStateFinished, callback) def getLinkStateFinished(self, result, retval, extra_args): (callback) = extra_args if not self.linkConsole.appContainers: callback(result) def stopPingConsole(self): if self.pingConsole is not None: self.pingConsole.killAll() def stopLinkStateConsole(self): self.linkConsole.killAll() def stopDNSConsole(self): if self.dnsConsole is not None: self.dnsConsole.killAll() def stopRestartConsole(self): self.restartConsole.killAll() def stopGetInterfacesConsole(self): self.console.killAll() def stopDeactivateInterfaceConsole(self): self.deactivateInterfaceConsole.killAll() def stopActivateInterfaceConsole(self): self.activateInterfaceConsole.killAll() def checkforInterface(self, iface): if self.getAdapterAttribute(iface, 'up') is True: return True else: ret = system("ifconfig " + iface + " up") system("ifconfig " + iface + " down") if ret == 0: return True else: return False def checkDNSLookup(self, statecallback): self.DnsState = 0 self.dnsConsole = Console() for server in ("www.microsoft.com", "www.google.com"): self.dnsConsole.ePopen( ("/usr/bin/nslookup", "/usr/bin/nslookup", server), self.checkDNSLookupFinished, statecallback) def checkDNSLookupFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.dnsConsole is not None: if retval == 0: self.dnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if not self.dnsConsole.appContainers: statecallback(self.DnsState) def deactivateInterface(self, ifaces, callback=None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append(("/sbin/ifdown", "/sbin/ifdown", "-f", iface)) commands.append(("/sbin/ip", "/sbin/ip", "addr", "flush", "dev", iface, "scope", "global")) #wpa_supplicant sometimes doesn't quit properly on SIGTERM if path.exists('/var/run/wpa_supplicant/' + iface): commands.append("wpa_cli -i" + iface + " terminate") if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch( commands, self.deactivateInterfaceFinished, (ifaces, callback), debug=True) def deactivateInterfaceFinished(self, extra_args): (ifaces, callback) = extra_args if not self.deactivateInterfaceConsole.appContainers: if callback is not None: callback(True) def activateInterface(self, iface, callback=None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return if not self.activateInterfaceConsole: self.activateInterfaceConsole = Console() commands = ["/sbin/ifup " + iface] self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self, extra_args): callback = extra_args if not self.activateInterfaceConsole.appContainers: if callback is not None: callback(True) def sysfsPath(self, iface): return '/sys/class/net/' + iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True if path.isdir(self.sysfsPath(iface) + '/wireless'): return True # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless device = re.compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass fp.close() if iface in ifnames: return True return False def getWlanModuleDir(self, iface=None): devicedir = self.sysfsPath(iface) + '/device' if not path.isdir(devicedir): return None moduledir = devicedir + '/driver/module' if path.isdir(moduledir): return moduledir # identification is not possible over default moduledir for x in listdir(devicedir): # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx if x.startswith("1-"): moduledir = devicedir + '/' + x + '/driver/module' if path.isdir(moduledir): return moduledir # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here moduledir = devicedir + '/driver' if path.isdir(moduledir): return moduledir return None def detectWlanModule(self, iface=None): if not self.isWirelessInterface(iface): return None devicedir = self.sysfsPath(iface) + '/device' if path.isdir(devicedir + '/ieee80211'): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = path.basename(path.realpath(moduledir)) if module in ('ath_pci', 'ath5k'): return 'madwifi' if module in ('rt73', 'rt73'): return 'ralink' if module == 'zd1211b': return 'zydas' return 'wext' def calc_netmask(self, nmask): from struct import pack from socket import inet_ntoa mask = 1 << 31 xnet = (1 << 32) - 1 cidr_range = list(range(0, 32)) cidr = int(nmask) if cidr not in cidr_range: print("[Network] cidr invalid: %d" % cidr) return None else: nm = ((1 << cidr) - 1) << (32 - cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins( PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == "add": print("[Network] Add new interface:", interface) self.getAddrInet(interface, None) elif action == "remove": print("[Network] Removed interface:", interface) try: del self.ifaces[interface] except KeyError: pass
class SoftwareTools(PackageInfoHandler): lastDownloadDate = None NetworkConnectionAvailable = None list_updating = False available_updates = 0 available_updatelist = [] available_packetlist = [] installed_packetlist = {} def __init__(self): aboutInfo = about.getImageVersionString() if aboutInfo.startswith("dev-"): self.ImageVersion = 'Experimental' else: self.ImageVersion = 'Stable' self.language = language.getLanguage( )[:2] # getLanguage returns e.g. "fi_FI" for "language_country" PackageInfoHandler.__init__(self, self.statusCallback, neededTag='ALL_TAGS', neededFlag=self.ImageVersion) self.directory = resolveFilename(SCOPE_METADIR) self.list = List([]) self.NotifierCallback = None self.Console = Console() self.UpdateConsole = Console() self.cmdList = [] self.unwanted_extensions = ('-dbg', '-dev', '-doc', '-staticdev', '-src') self.opkg = OpkgComponent() self.opkg.addCallback(self.opkgCallback) def statusCallback(self, status, progress): pass def startSoftwareTools(self, callback=None): if callback is not None: self.NotifierCallback = callback iNetwork.checkNetworkState(self.checkNetworkCB) def checkNetworkCB(self, data): if data is not None: if data <= 2: self.NetworkConnectionAvailable = True self.getUpdates() else: self.NetworkConnectionAvailable = False self.getUpdates() def getUpdates(self, callback=None): if self.lastDownloadDate is None: if self.NetworkConnectionAvailable == True: self.lastDownloadDate = time() if self.list_updating is False and callback is None: self.list_updating = True self.opkg.startCmd(OpkgComponent.CMD_UPDATE) elif self.list_updating is False and callback is not None: self.list_updating = True self.NotifierCallback = callback self.opkg.startCmd(OpkgComponent.CMD_UPDATE) elif self.list_updating is True and callback is not None: self.NotifierCallback = callback else: self.list_updating = False if callback is not None: callback(False) elif self.NotifierCallback is not None: self.NotifierCallback(False) else: if self.NetworkConnectionAvailable == True: self.lastDownloadDate = time() if self.list_updating is False and callback is None: self.list_updating = True self.opkg.startCmd(OpkgComponent.CMD_UPDATE) elif self.list_updating is False and callback is not None: self.list_updating = True self.NotifierCallback = callback self.opkg.startCmd(OpkgComponent.CMD_UPDATE) elif self.list_updating is True and callback is not None: self.NotifierCallback = callback else: if self.list_updating and callback is not None: self.NotifierCallback = callback self.startOpkgListAvailable() else: self.list_updating = False if callback is not None: callback(False) elif self.NotifierCallback is not None: self.NotifierCallback(False) def opkgCallback(self, event, param): if event == OpkgComponent.EVENT_ERROR: self.list_updating = False if self.NotifierCallback is not None: self.NotifierCallback(False) elif event == OpkgComponent.EVENT_DONE: if self.list_updating: self.startOpkgListAvailable() pass def startOpkgListAvailable(self, callback=None): if callback is not None: self.list_updating = True if self.list_updating: if not self.UpdateConsole: self.UpdateConsole = Console() cmd = self.opkg.opkg + " list" self.UpdateConsole.ePopen(cmd, self.OpkgListAvailableCB, callback) def OpkgListAvailableCB(self, result, retval, extra_args=None): (callback) = extra_args if result: if self.list_updating: self.available_packetlist = [] for x in result.splitlines(): tokens = x.split(' - ') name = tokens[0].strip() if not any( name.endswith(x) for x in self.unwanted_extensions): l = len(tokens) version = l > 1 and tokens[1].strip() or "" descr = l > 2 and tokens[2].strip() or "" self.available_packetlist.append( [name, version, descr]) if callback is None: self.startInstallMetaPackage() else: if self.UpdateConsole: if not self.UpdateConsole.appContainers: callback(True) else: self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(False) def startInstallMetaPackage(self, callback=None): if callback is not None: self.list_updating = True if self.list_updating: if self.NetworkConnectionAvailable == True: if not self.UpdateConsole: self.UpdateConsole = Console() cmd = self.opkg.opkg + " install enigma2-meta enigma2-plugins-meta enigma2-skins-meta" self.UpdateConsole.ePopen(cmd, self.InstallMetaPackageCB, callback) else: self.InstallMetaPackageCB(True) def InstallMetaPackageCB(self, result, retval=None, extra_args=None): (callback) = extra_args if result: self.fillPackagesIndexList() if callback is None: self.startOpkgListInstalled() else: if self.UpdateConsole: if not self.UpdateConsole.appContainers: callback(True) else: self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(False) def startOpkgListInstalled(self, callback=None): if callback is not None: self.list_updating = True if self.list_updating: if not self.UpdateConsole: self.UpdateConsole = Console() cmd = self.opkg.opkg + " list_installed" self.UpdateConsole.ePopen(cmd, self.OpkgListInstalledCB, callback) def OpkgListInstalledCB(self, result, retval, extra_args=None): (callback) = extra_args if result: self.installed_packetlist = {} for x in result.splitlines(): tokens = x.split(' - ') name = tokens[0].strip() if not any(name.endswith(x) for x in self.unwanted_extensions): l = len(tokens) version = l > 1 and tokens[1].strip() or "" self.installed_packetlist[name] = version for package in self.packagesIndexlist[:]: if not self.verifyPrerequisites(package[0]["prerequisites"]): self.packagesIndexlist.remove(package) for package in self.packagesIndexlist[:]: attributes = package[0]["attributes"] if "packagetype" in attributes: if attributes["packagetype"] == "internal": self.packagesIndexlist.remove(package) if callback is None: self.countUpdates() else: if self.UpdateConsole: if not self.UpdateConsole.appContainers: callback(True) else: self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(False) def countUpdates(self, callback=None): self.available_updates = 0 self.available_updatelist = [] for package in self.packagesIndexlist[:]: attributes = package[0]["attributes"] packagename = attributes["packagename"] for x in self.available_packetlist: if x[0] == packagename: if packagename in self.installed_packetlist: if self.installed_packetlist[packagename] != x[1]: self.available_updates += 1 self.available_updatelist.append([packagename]) self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(True) callback = None elif self.NotifierCallback is not None: self.NotifierCallback(True) self.NotifierCallback = None def startOpkgUpdate(self, callback=None): if not self.Console: self.Console = Console() cmd = self.opkg.opkg + " update" self.Console.ePopen(cmd, self.OpkgUpdateCB, callback) def OpkgUpdateCB(self, result, retval, extra_args=None): (callback) = extra_args if result: if self.Console: if not self.Console.appContainers: if callback is not None: callback(True) callback = None def cleanupSoftwareTools(self): self.list_updating = False if self.NotifierCallback is not None: self.NotifierCallback = None self.opkg.stop() if self.Console is not None: self.Console.killAll() if self.UpdateConsole is not None: self.UpdateConsole.killAll() def verifyPrerequisites(self, prerequisites): if "hardware" in prerequisites: hardware_found = False for hardware in prerequisites["hardware"]: if hardware == getBoxType(): hardware_found = True if not hardware_found: return False return True
class MultiBootSelector(Screen): skin = """ <screen name="Multiboot Image Selector" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="description" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="options" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="200,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <eLabel position="20,200" size="6,40" backgroundColor="#00e61700" /> <!-- Should be a pixmap --> <eLabel position="190,200" size="6,40" backgroundColor="#0061e500" /> <!-- Should be a pixmap --> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) screentitle = _("Multiboot Image Selector") self["key_red"] = StaticText(_("Cancel")) if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists( '/dev/%s4' % (SystemInfo["canMultiBoot"][2])): self["description"] = StaticText( _("Use the cursor keys to select an installed image and then Reboot button." )) else: self["description"] = StaticText( _("SDcard is not initialised for multiboot - Exit and use MultiBoot Image Manager to initialise" )) self["options"] = StaticText(_(" ")) self["key_green"] = StaticText(_("Reboot")) if SystemInfo["canMode12"]: self["options"] = StaticText( _("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work." )) self["config"] = ChoiceList(list=[ ChoiceEntryComponent('', ( (_("Retrieving image startups - Please wait...")), "Queued")) ]) imagedict = [] self.getImageList = None self.mountDir = "/tmp/startupmount" self.callLater(self.getBootOptions) self.title = screentitle self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "red": boundFunction(self.close, None), "green": self.reboot, "ok": self.reboot, "cancel": boundFunction(self.close, None), "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def cancel(self, value=None): self.container = Console() self.container.ePopen("umount %s" % self.mountDir, boundFunction(self.unmountCallback, value)) def unmountCallback(self, value, data=None, retval=None, extra_args=None): self.container.killAll() if not path.ismount(self.mountDir): rmdir(self.mountDir) self.close(value) def getBootOptions(self, value=None): self.container = Console() if path.isdir(self.mountDir) and path.ismount(self.mountDir): self.getImagesList() else: if not path.isdir(self.mountDir): mkdir(self.mountDir) self.container.ePopen( "mount %s %s" % (SystemInfo["MBbootdevice"], self.mountDir), self.getImagesList) def getImagesList(self, data=None, retval=None, extra_args=None): self.container.killAll() self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagedict): _list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() print("[MultiBootSelector] reboot1 slot:", currentimageslot) current = " %s" % _("(current image)") slotSingle = _("Slot %s: %s%s") slotMulti = _("Slot %s: %s - Mode %d%s") if imagedict: indextot = 0 for index, x in enumerate(sorted(list(imagedict.keys()))): if imagedict[x]["imagename"] != _("Empty slot"): if SystemInfo["canMode12"]: _list.insert( index, ChoiceEntryComponent( "", (slotMulti % (x, imagedict[x]["imagename"], 1, current if x == currentimageslot and mode != 12 else ""), (x, 1)))) _list.append( ChoiceEntryComponent("", ( slotMulti % (x, imagedict[x]["imagename"], 12, current if x == currentimageslot and mode == 12 else ""), (x, 12)))) indextot = index + 1 else: _list.append( ChoiceEntryComponent( "", (slotSingle % (x, imagedict[x]["imagename"], current if x == currentimageslot else ""), (x, 1)))) if SystemInfo["canMode12"]: _list.insert(indextot, " ") else: _list.append( ChoiceEntryComponent("", ((_("No images found")), "Waiter"))) self["config"].setList(_list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() if self.currentSelected[0][1] != "Queued": slot = self.currentSelected[0][1][0] boxmode = self.currentSelected[0][1][1] message = _( "Do you want to reboot now the image in startup %s?") % slot print("[MultiBootSelector] reboot2 reboot slot = %s, " % slot) print("[MultiBootSelector] reboot2 reboot boxmode = %s, " % boxmode) print("[MultiBootSelector] reboot3 slotinfo = %s" % SystemInfo["canMultiBoot"]) if SystemInfo["canMode12"]: if "BOXMODE" in SystemInfo["canMultiBoot"][slot][ 'startupfile']: startupfile = path.join( self.mountDir, "%s_%s" % (SystemInfo["canMultiBoot"][slot] ['startupfile'].rsplit('_', 1)[0], boxmode)) copyfile(startupfile, path.join(self.mountDir, "STARTUP")) else: f = open( path.join( self.mountDir, SystemInfo["canMultiBoot"][slot]['startupfile']), "r").read() if boxmode == 12: f = f.replace("boxmode=1'", "boxmode=12'").replace( "%s" % SystemInfo["canMode12"][0], "%s" % SystemInfo["canMode12"][1]) open(path.join(self.mountDir, "STARTUP"), "w").write(f) else: copyfile( path.join(self.mountDir, SystemInfo["canMultiBoot"][slot]["startupfile"]), path.join(self.mountDir, "STARTUP")) self.session.openWithCallback(self.restartImage, MessageBox, message, MessageBox.TYPE_YESNO, timeout=20) def restartImage(self, answer): if answer is True: self.session.open(TryQuitMainloop, 2) else: self.close() def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback = None): self.WlanConsole = Console() cmd = "iwconfig " + iface self.WlanConsole.ePopen(cmd, self.iwconfigFinished, [iface, callback]) def iwconfigFinished(self, result, retval, extra_args): (iface, callback) = extra_args data = { 'essid': False, 'frequency': False, 'acesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False } for line in result.splitlines(): line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = _("No Connection") else: if "Nickname" in line: tmpssid=(line[line.index('ESSID')+7:line.index('" Nickname')]) if tmpssid == '': ssid = _("Hidden networkname") elif tmpssid ==' ': ssid = _("Hidden networkname") else: ssid = tmpssid else: tmpssid=(line[line.index('ESSID')+7:len(line)-1]) if tmpssid == '': ssid = _("Hidden networkname") elif tmpssid ==' ': ssid = _("Hidden networkname") else: ssid = tmpssid if ssid is not None: data['essid'] = ssid if 'Frequency' in line: frequency = line[line.index('Frequency')+10 :line.index(' GHz')] if frequency is not None: data['frequency'] = frequency if "Access Point" in line: ap=line[line.index('Access Point')+14:len(line)] if ap is not None: data['acesspoint'] = ap if ap == "Not-Associated": data['essid'] = _("No Connection") if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate')+9 :line.index(' kb/s')] if br == '0': br = _("Unsupported") else: br += " Mb/s" else: br = line[line.index('Bit Rate')+9 :line.index(' Mb/s')] + " Mb/s" if br is not None: data['bitrate'] = br if 'Encryption key' in line: if ":off" in line: if data['acesspoint'] is not "Not-Associated": enc = _("Unsupported") else: enc = _("Disabled") else: enc = line[line.index('Encryption key')+15 :line.index(' Security')] if enc is not None: enc = _("Enabled") if enc is not None: data['encryption'] = enc if 'Quality' in line: if "/100" in line: #qual = line[line.index('Quality')+8:line.index('/100')] qual = line[line.index('Quality')+8:line.index(' Signal')] else: qual = line[line.index('Quality')+8:line.index('Sig')] if qual is not None: data['quality'] = qual if 'Signal level' in line: if "dBm" in line: signal = line[line.index('Signal level')+13 :line.index(' dBm')] signal += " dBm" elif "/100" in line: if "Noise" in line: signal = line[line.index('Signal level')+13:line.index(' Noise')] else: signal = line[line.index('Signal level')+13:len(line)] else: if "Noise" in line: signal = line[line.index('Signal level')+13:line.index(' Noise')] else: signal = line[line.index('Signal level')+13:len(line)] if signal is not None: data['signal'] = signal self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if len(self.WlanConsole.appContainers) == 0: print "self.wlaniface after loading:", self.wlaniface if callback is not None: callback(True,self.wlaniface) def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.wlaniface.has_key(self.iface): if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 NoRun = 0 # receivers only uses 1 media for multiboot FirstRun = 1 # receiver uses eMMC and SD card for multiboot - so handle SDcard slots 1st via SystemInfo(canMultiBoot) LastRun = 2 # receiver uses eMMC and SD card for multiboot - and then handle eMMC (currently one time) def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots) = SystemInfo["canMultiBoot"][:2] if SystemInfo["HasSDmmc"]: self.numberofslots -= 1 self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.slot2 = 1 if SystemInfo["HasSDmmc"]: self.SDmmc = self.FirstRun # process SDcard slots else: self.SDmmc = self.NoRun # only mmc slots self.phase = self.MOUNT self.part = SystemInfo["canMultiBoot"][2] # pick up slot type self.run() else: callback({}) def run(self): if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.islink("/dev/block/by-name/linuxrootfs"): self.part2 = os.readlink("/dev/block/by-name/linuxrootfs")[5:] self.container.ePopen('mount /dev/block/by-name/linuxrootfs /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.part2 = os.readlink("/dev/block/by-name/userdata")[5:] self.container.ePopen('mount /dev/block/by-name/userdata /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' %self.part2 } else: if self.SDmmc == self.LastRun: self.part2 = getMachineMtdRoot() # process mmc slot self.slot2 = 1 else: self.part2 = "%s" %(self.part + str(self.slot * 2 + self.firstslot)) if self.SDmmc == self.FirstRun: self.slot2 += 1 # allow for mmc slot" if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' %self.part2 } self.container.ePopen('mount /dev/%s /tmp/testmount' %self.part2 if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: BuildVersion = " " Build = " " Dev = " " Creator = " " Date = " " BuildType = " " self.OsPath = "NoPath" if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.isfile("/tmp/testmount/linuxrootfs1/usr/bin/enigma2"): self.OsPath = "/tmp/testmount/linuxrootfs1" elif os.path.isfile("/tmp/testmount/linuxrootfs%s/usr/bin/enigma2" % self.slot): self.OsPath = "/tmp/testmount/linuxrootfs%s" % self.slot print "multiboot tools 1 slots", self.slot, self.slot2 else: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): self.OsPath = '/tmp/testmount' print "Tools/Multiboot OsPath %s " %self.OsPath if self.OsPath != "NoPath": try: Creator = open("%s/etc/issue" %self.OsPath).readlines()[-2].capitalize().strip()[:-6].replace("-release", " rel") except: Creator = _("unknow") print "Tools/Multiboot Creator %s" %Creator if Creator.startswith("Openpli"): build = [x.split("-")[-2:-1][0][-8:] for x in open("%s/var/lib/opkg/info/openpli-bootlogo.control" %self.OsPath).readlines() if x.startswith("Version:")] Date = "%s-%s-%s" % (build[0][6:], build[0][4:6], build[0][2:4]) BuildVersion = "%s %s" % (Creator, Date) elif Creator.startswith("Openvix"): reader = boxbranding_reader(self.OsPath) BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild() or '' BuildVersion = "%s %s %s %s" % (Creator, BuildType[0:3], Build, Dev) else: st = os.stat('%s/var/lib/opkg/status' %self.OsPath) tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: Date = time.strftime("%d-%m-%Y", tm) BuildVersion = _("%s build date %s") % (Creator, Date) self.imagelist[self.slot2] = { 'imagename': '%s' %BuildVersion, 'part': '%s' %self.part2 } self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.slot2 = self.slot self.phase = self.MOUNT self.run() elif self.SDmmc == self.FirstRun: self.phase = self.MOUNT self.SDmmc = self.LastRun # processed SDcard now process mmc slot self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class MultibootSelection(SelectImage): def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "SelectImage" self.session = session self.imagesList = None self.expanded = [] self.setTitle(_("Select Multiboot")) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Reboot")) self["list"] = ChoiceList(list=[ ChoiceEntryComponent('', ( (_("Retrieving image slots - Please wait...")), "Waiter")) ]) self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "ok": self.keyOk, "cancel": boundFunction(self.close, None), "red": boundFunction(self.close, None), "green": self.keyOk, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.delay = eTimer() self.delay.callback.append(self.getImagesList) self.delay.start(0, True) def getImagesList(self, reply=None): self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagesdict): list = [] currentimageslot = GetCurrentImage() mode = GetCurrentImageMode() or 0 for x in sorted(imagesdict.keys()): if imagesdict[x]["imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagesdict[x]['imagename']), x))) if SystemInfo["canMode12"]: list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagesdict[x]['imagename']), x + 12))) self["list"].setList(list) def keyOk(self): self.currentSelected = self["list"].l.getCurrentSelection() if self.currentSelected[0][1] != "Waiter": self.container = Console() if os.path.isdir('/tmp/startupmount'): self.ContainterFallback() else: os.mkdir('/tmp/startupmount') self.container.ePopen('mount /dev/mmcblk0p1 /tmp/startupmount', self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot = self.currentSelected[0][1] model = HardwareInfo().get_machine_name() if 'coherent_poll=2M' in open("/proc/cmdline", "r").read(): #when Gigablue do something else... this needs to be improved later!!! It even looks that the GB method is better :) shutil.copyfile("/tmp/startupmount/STARTUP_%s" % slot, "/tmp/startupmount/STARTUP") else: if slot < 12: startupFileContents = "boot emmcflash0.kernel%s 'root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=1'\n" % ( slot, slot * 2 + 1, model) else: slot -= 12 startupFileContents = "boot emmcflash0.kernel%s 'brcm_cma=520M@248M brcm_cma=%s@768M root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=12'\n" % ( slot, SystemInfo["canMode12"], slot * 2 + 1, model) open('/tmp/startupmount/STARTUP', 'w').write(startupFileContents) from Screens.Standby import TryQuitMainloop self.session.open(TryQuitMainloop, 2) def selectionChanged(self): pass
class MultiBootSelector(Screen): skin = """ <screen name="Multiboot Image Selector" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="description" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="options" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="200,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <eLabel position="20,200" size="6,40" backgroundColor="#00e61700" /> <!-- Should be a pixmap --> <eLabel position="190,200" size="6,40" backgroundColor="#0061e500" /> <!-- Should be a pixmap --> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) screentitle = _("Multiboot Image Selector") self["key_red"] = StaticText(_("Cancel")) if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists('/dev/%s4' %(SystemInfo["canMultiBoot"][2])): self["description"] = StaticText(_("Use the cursor keys to select an installed image and then Reboot button.")) else: self["description"] = StaticText(_("SDcard is not initialised for multiboot - Exit and use MultiBoot Image Manager to initialise")) self["options"] = StaticText(_(" ")) self["key_green"] = StaticText(_("Reboot")) if SystemInfo["canMode12"]: self["options"] = StaticText(_("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work.")) self["config"] = ChoiceList(list=[ChoiceEntryComponent('',((_("Retrieving image startups - Please wait...")), "Queued"))]) imagedict = [] self.mtdboot = "%s1" % SystemInfo["canMultiBoot"][2] if SystemInfo["canMultiBoot"][2] == "sda": self.mtdboot = "%s3" %getMachineMtdRoot()[0:8] self.getImageList = None self.title = screentitle if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists('/dev/%s4' %(SystemInfo["canMultiBoot"][2])): self.startit() self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions"], { "red": boundFunction(self.close, None), "green": self.reboot, "ok": self.reboot, "cancel": boundFunction(self.close, None), "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def startit(self): self.getImageList = GetImagelist(self.ImageList) def ImageList(self, imagedict): list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() or 1 if imagedict: if not SystemInfo["canMode12"]: for x in sorted(imagedict.keys()): if imagedict[x]["imagename"] != _("Empty startup"): list.append(ChoiceEntryComponent('',((_("startup %s -%s - %s (current image)") if x == currentimageslot else _("startup %s -%s- %s ")) % (x, imagedict[x]['part'][0:3], imagedict[x]['imagename']), x))) else: for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if imagedict[x]["imagename"] != _("Empty startup"): list.append(ChoiceEntryComponent('',((_("startup %s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("startup %s - %s mode 1")) % (x, imagedict[x]['imagename']), x))) list.append(" ") list.append(" ") for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if SystemInfo["canMode12"] and imagedict[x]["imagename"] != _("Empty startup"): list.append(ChoiceEntryComponent('',((_("startup %s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("startup %s - %s mode 12")) % (x, imagedict[x]['imagename']), x))) else: list.append(ChoiceEntryComponent('',((_("No images found")), "Waiter"))) self["config"].setList(list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() if self.currentSelected[0][1] != "Queued": self.container = Console() if pathExists('/tmp/startupmount'): self.ContainterFallback() else: mkdir('/tmp/startupmount') if SystemInfo["HasRootSubdir"]: if fileExists("/dev/block/by-name/bootoptions"): self.container.ePopen('mount /dev/block/by-name/bootoptions /tmp/startupmount', self.ContainterFallback) elif fileExists("/dev/block/by-name/boot"): self.container.ePopen('mount /dev/block/by-name/boot /tmp/startupmount', self.ContainterFallback) else: self.container.ePopen('mount /dev/%s /tmp/startupmount' % self.mtdboot, self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot = self.currentSelected[0][1] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() or 1 if pathExists("/tmp/startupmount/%s" %GetSTARTUPFile()): if currentimageslot == slot and SystemInfo["canMode12"]: if mode == 12: startupFileContents = ReadSTARTUP().replace("boxmode=12'","boxmode=1'").replace(SystemInfo["canMode12"][1],SystemInfo["canMode12"][0]) open('/tmp/startupmount/%s'%GetSTARTUPFile(), 'w').write(startupFileContents) else: startupFileContents = ReadSTARTUP().replace("boxmode=1'","boxmode=12'").replace(SystemInfo["canMode12"][0],SystemInfo["canMode12"][1]) open('/tmp/startupmount/%s'%GetSTARTUPFile(), 'w').write(startupFileContents) elif fileExists("/tmp/startupmount/STARTUP_1"): copyfile("/tmp/startupmount/STARTUP_%s" % slot, "/tmp/startupmount/%s" %GetSTARTUPFile()) elif fileExists("/tmp/startupmount/STARTUP_LINUX_4_BOXMODE_12"): if mode == 1: copyfile("/tmp/startupmount/STARTUP_LINUX_%s_BOXMODE_1" % slot, "/tmp/startupmount/%s" %GetSTARTUPFile()) else: copyfile("/tmp/startupmount/STARTUP_LINUX_%s_BOXMODE_12" % slot, "/tmp/startupmount/%s" %GetSTARTUPFile()) elif fileExists("/tmp/startupmount/STARTUP_LINUX_4"): copyfile("/tmp/startupmount/STARTUP_LINUX_%s" % slot, "/tmp/startupmount/%s" %GetSTARTUPFile()) message = _("Do you want to reboot now the image in startup %s?") %slot self.session.openWithCallback(self.restartImage,MessageBox, message, MessageBox.TYPE_YESNO, timeout=20) else: self.session.open(MessageBox, _("Multiboot ERROR! - no %s in boot partition.") %GetSTARTUPFile(), MessageBox.TYPE_INFO, timeout=20) def restartImage(self, answer): if answer is True: self.session.open(TryQuitMainloop, 2) else: self.close() def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface) def iwconfigFinished(self, result, retval, extra_args): iface = extra_args data = { "essid": False, "frequency": False, "accesspoint": False, "bitrate": False, "encryption": False, "quality": False, "signal": False, } for line in result.splitlines(): line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = "off" else: if "Nickname" in line: ssid = line[line.index("ESSID") + 7 : line.index('" Nickname')] else: ssid = line[line.index("ESSID") + 7 : len(line) - 1] if ssid is not None: data["essid"] = ssid if "Frequency" in line: frequency = line[line.index("Frequency") + 10 : line.index(" GHz")] if frequency is not None: data["frequency"] = frequency if "Access Point" in line: if "Sensitivity" in line: ap = line[line.index("Access Point") + 14 : line.index(" Sensitivity")] else: ap = line[line.index("Access Point") + 14 : len(line)] if ap is not None: data["accesspoint"] = ap if "Bit Rate" in line: if "kb" in line: br = line[line.index("Bit Rate") + 9 : line.index(" kb/s")] else: br = line[line.index("Bit Rate") + 9 : line.index(" Mb/s")] if br is not None: data["bitrate"] = br if "Encryption key" in line: if ":off" in line: enc = "off" elif "Security" in line: enc = line[line.index("Encryption key") + 15 : line.index(" Security")] if enc is not None: enc = "on" else: enc = line[line.index("Encryption key") + 15 : len(line)] if enc is not None: enc = "on" if enc is not None: data["encryption"] = enc if "Quality" in line: if "/100" in line: qual = line[line.index("Quality") + 8 : line.index(" Signal")] else: qual = line[line.index("Quality") + 8 : line.index("Sig")] if qual is not None: data["quality"] = qual if "Signal level" in line: if "dBm" in line: signal = line[line.index("Signal level") + 13 : line.index(" dBm")] + " dBm" elif "/100" in line: if "Noise" in line: signal = line[line.index("Signal level") + 13 : line.index(" Noise")] else: signal = line[line.index("Signal level") + 13 : len(line)] else: if "Noise" in line: signal = line[line.index("Signal level") + 13 : line.index(" Noise")] else: signal = line[line.index("Signal level") + 13 : len(line)] if signal is not None: data["signal"] = signal self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if len(self.WlanConsole.appContainers) == 0: print "[Wlan.py] self.wlaniface after loading:", self.wlaniface if self.statusCallback is not None: self.statusCallback(True, self.wlaniface) self.statusCallback = None def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.wlaniface.has_key(self.iface): if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None
class SDswap(Screen): skin = """ <screen name="H9SDswap" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="labe14" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="labe15" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="230,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_yellow" render="Label" position="430,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <ePixmap pixmap="skin_default/buttons/red.png" position="30,200" size="40,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="230,200" size="40,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="430,200" size="40,40" alphatest="on" /> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "SDswap" screentitle = _("switch Nand and SDcard") self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("SwaptoNand")) self["key_yellow"] = StaticText(_("SwaptoSD")) self.title = screentitle self.switchtype = " " self["actions"] = ActionMap(["ColorActions"], { "red": boundFunction(self.close, None), "green": self.SwaptoNand, "yellow": self.SwaptoSD, }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def SwaptoNand(self): self.switchtype = "Nand" f = open('/proc/cmdline', 'r').read() if "root=/dev/mmcblk0p1" in f: self.container = Console() self.container.ePopen("dd if=/usr/share/bootargs-nand.bin of=/dev/mtdblock1", self.Unm) else: self.session.open(MessageBox, _("SDcard switch ERROR! - already on Nand"), MessageBox.TYPE_INFO, timeout=20) def SwaptoSD(self): self.switchtype = "mmc" f = open('/proc/cmdline', 'r').read() print "[H9SDswap] switchtype %s cmdline %s" %(self.switchtype, f) if "root=/dev/mmcblk0p1" in f: self.session.open(MessageBox, _("SDcard switch ERROR! - already on mmc"), MessageBox.TYPE_INFO, timeout=20) elif os.path.isfile("/media/mmc/usr/bin/enigma2"): self.container = Console() self.container.ePopen("dd if=/usr/share/bootargs-mmc.bin of=/dev/mtdblock1", self.Unm) else: self.session.open(MessageBox, _("SDcard switch ERROR! - H9 root files not transferred to SD card"), MessageBox.TYPE_INFO, timeout=20) def SwaptoUSB(self): self.switchtype = "usb" f = open('/proc/cmdline', 'r').read() print "[H9SDswap] switchtype %s cmdline %s" %(self.switchtype, f) if "root=/dev/SDA1" in f: self.session.open(MessageBox, _("USB switch ERROR! - already on USB"), MessageBox.TYPE_INFO, timeout=20) elif os.path.isfile("/media/mmc/usr/bin/enigma2"): self.container = Console() self.container.ePopen("dd if=/usr/share/bootargs-usb.bin of=/dev/mtdblock1", self.Unm) else: self.session.open(MessageBox, _("USB switch ERROR! - root files not transferred to USB"), MessageBox.TYPE_INFO, timeout=20) def Unm(self, data=None, retval=None, extra_args=None): self.container.killAll() self.session.open(TryQuitMainloop, 2)
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print("[iStatus] killing self.WlanConsole") self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface) def iwconfigFinished(self, result, retval, extra_args): iface = extra_args ssid = "off" data = { 'essid': False, 'frequency': False, 'accesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False, 'channel': False, 'encryption_type': False, 'frequency': False, 'frequency_norm': False } for line in result.splitlines(): line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = "off" else: if "Nickname" in line: ssid = (line[line.index('ESSID') + 7:line.index('" Nickname')]) else: ssid = (line[line.index('ESSID') + 7:len(line) - 1]) if ssid != "off": data['essid'] = ssid if "Frequency" in line: frequency = line[line.index('Frequency') + 10:line.index(' GHz')] if frequency is not None: data['frequency'] = frequency if "Access Point" in line: if "Sensitivity" in line: ap = line[line.index('Access Point') + 14:line.index(' Sensitivity')] else: ap = line[line.index('Access Point') + 14:len(line)] if ap is not None: data['accesspoint'] = ap if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate') + 9:line.index(' kb/s')] elif "Gb" in line: br = line[line.index('Bit Rate') + 9:line.index(' Gb/s')] else: br = line[line.index('Bit Rate') + 9:line.index(' Mb/s')] if br is not None: data['bitrate'] = br if "Encryption key" in line: if ":off" in line: enc = "off" elif "Security" in line: enc = line[line.index('Encryption key') + 15:line.index(' Security')] if enc is not None: enc = "on" else: enc = line[line.index('Encryption key') + 15:len(line)] if enc is not None: enc = "on" if enc is not None: data['encryption'] = enc if 'Quality' in line: if "/100" in line: qual = line[line.index('Quality') + 8:line.index(' Signal')] else: qual = line[line.index('Quality') + 8:line.index('Sig')] if qual is not None: data['quality'] = qual if 'Signal level' in line: if "dBm" in line: signal = line[line.index('Signal level') + 13:line.index(' dBm')] + " dBm" elif "/100" in line: if "Noise" in line: signal = line[line.index('Signal level') + 13:line.index(' Noise')] else: signal = line[line.index('Signal level') + 13:len(line)] else: if "Noise" in line: signal = line[line.index('Signal level') + 13:line.index(' Noise')] else: signal = line[line.index('Signal level') + 13:len(line)] if signal is not None: data['signal'] = signal if ssid != None and ssid != "off" and ssid != "": try: scanresults = list(Cell.all(iface, 5)) print("[Wlan.py] scanresults2 = %s" % scanresults) except: scanresults = None print("[Wlan.py] No wireless networks could be found") aps = {} if scanresults is not None: config.misc.networkenabled.value = True print("[NetworkWizard] networkenabled value = %s" % config.misc.networkenabled.value) for i in range(len(scanresults)): bssid = scanresults[i].ssid aps[bssid] = { 'active': True, 'bssid': scanresults[i].ssid, 'essid': scanresults[i].ssid, 'channel': scanresults[i].channel, 'encrypted': scanresults[i].encrypted, 'encryption_type': scanresults[i].encryption_type if scanresults[i].encrypted else "n/a", 'iface': iface, 'maxrate': scanresults[i].bitrates, 'mode': scanresults[i].mode, 'quality': scanresults[i].quality, 'signal': scanresults[i].signal, 'frequency': scanresults[i].frequency, 'frequency_norm': scanresults[i].frequency_norm, 'address': scanresults[i].address, 'noise': scanresults[i].noise, 'pairwise_ciphers': scanresults[i].pairwise_ciphers, 'authentication_suites': scanresults[i].authentication_suites, } #data['bitrate'] = aps[ssid]["maxrate"] data['encryption'] = aps[ssid]["encrypted"] data['quality'] = aps[ssid]["quality"] data['signal'] = aps[ssid]["signal"] data['channel'] = aps[ssid]["channel"] data['encryption_type'] = aps[ssid]["encryption_type"] #data['frequency'] = aps[ssid]["frequency"] data['frequency_norm'] = aps[ssid]["frequency_norm"] print("[Wlan.py] apsresults2 = %s" % data) self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if not self.WlanConsole.appContainers: print("[Wlan.py] self.wlaniface after loading:", self.wlaniface) if self.statusCallback is not None: self.statusCallback(True, self.wlaniface) self.statusCallback = None def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.iface in self.wlaniface: if attribute in self.wlaniface[self.iface]: return self.wlaniface[self.iface][attribute] return None
class SoftwareTools(PackageInfoHandler): lastDownloadDate = None NetworkConnectionAvailable = None list_updating = False available_updates = 0 available_updatelist = [] available_packetlist = [] installed_packetlist = {} def __init__(self): aboutInfo = about.getImageVersionString() if aboutInfo.startswith("dev-"): self.ImageVersion = 'Experimental' else: self.ImageVersion = 'Stable' self.language = language.getLanguage()[:2] # getLanguage returns e.g. "fi_FI" for "language_country" PackageInfoHandler.__init__(self, self.statusCallback, neededTag = 'ALL_TAGS', neededFlag = self.ImageVersion) self.directory = resolveFilename(SCOPE_METADIR) self.list = List([]) self.NotifierCallback = None self.Console = Console() self.UpdateConsole = Console() self.cmdList = [] self.unwanted_extensions = ('-dbg', '-dev', '-doc', '-staticdev', '-src') self.ipkg = IpkgComponent() self.ipkg.addCallback(self.ipkgCallback) def statusCallback(self, status, progress): pass def startSoftwareTools(self, callback = None): if callback is not None: self.NotifierCallback = callback iNetwork.checkNetworkState(self.checkNetworkCB) def checkNetworkCB(self,data): if data is not None: if data <= 2: self.NetworkConnectionAvailable = True self.getUpdates() else: self.NetworkConnectionAvailable = False self.getUpdates() def getUpdates(self, callback = None): if self.lastDownloadDate is None: if self.NetworkConnectionAvailable == True: self.lastDownloadDate = time() if self.list_updating is False and callback is None: self.list_updating = True self.ipkg.startCmd(IpkgComponent.CMD_UPDATE) elif self.list_updating is False and callback is not None: self.list_updating = True self.NotifierCallback = callback self.ipkg.startCmd(IpkgComponent.CMD_UPDATE) elif self.list_updating is True and callback is not None: self.NotifierCallback = callback else: self.list_updating = False if callback is not None: callback(False) elif self.NotifierCallback is not None: self.NotifierCallback(False) else: if self.NetworkConnectionAvailable == True: self.lastDownloadDate = time() if self.list_updating is False and callback is None: self.list_updating = True self.ipkg.startCmd(IpkgComponent.CMD_UPDATE) elif self.list_updating is False and callback is not None: self.list_updating = True self.NotifierCallback = callback self.ipkg.startCmd(IpkgComponent.CMD_UPDATE) elif self.list_updating is True and callback is not None: self.NotifierCallback = callback else: if self.list_updating and callback is not None: self.NotifierCallback = callback self.startIpkgListAvailable() else: self.list_updating = False if callback is not None: callback(False) elif self.NotifierCallback is not None: self.NotifierCallback(False) def ipkgCallback(self, event, param): if event == IpkgComponent.EVENT_ERROR: self.list_updating = False if self.NotifierCallback is not None: self.NotifierCallback(False) elif event == IpkgComponent.EVENT_DONE: if self.list_updating: self.startIpkgListAvailable() pass def startIpkgListAvailable(self, callback = None): if callback is not None: self.list_updating = True if self.list_updating: if not self.UpdateConsole: self.UpdateConsole = Console() cmd = self.ipkg.ipkg + " list" self.UpdateConsole.ePopen(cmd, self.IpkgListAvailableCB, callback) def IpkgListAvailableCB(self, result, retval, extra_args = None): (callback) = extra_args if result: if self.list_updating: self.available_packetlist = [] for x in result.splitlines(): tokens = x.split(' - ') name = tokens[0].strip() if not any(name.endswith(x) for x in self.unwanted_extensions): l = len(tokens) version = l > 1 and tokens[1].strip() or "" descr = l > 2 and tokens[2].strip() or "" self.available_packetlist.append([name, version, descr]) if callback is None: self.startInstallMetaPackage() else: if self.UpdateConsole: if not self.UpdateConsole.appContainers: callback(True) else: self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(False) def startInstallMetaPackage(self, callback = None): if callback is not None: self.list_updating = True if self.list_updating: if self.NetworkConnectionAvailable == True: if not self.UpdateConsole: self.UpdateConsole = Console() cmd = self.ipkg.ipkg + " install enigma2-meta enigma2-plugins-meta enigma2-skins-meta" self.UpdateConsole.ePopen(cmd, self.InstallMetaPackageCB, callback) else: self.InstallMetaPackageCB(True) def InstallMetaPackageCB(self, result, retval = None, extra_args = None): (callback) = extra_args if result: self.fillPackagesIndexList() if callback is None: self.startIpkgListInstalled() else: if self.UpdateConsole: if not self.UpdateConsole.appContainers: callback(True) else: self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(False) def startIpkgListInstalled(self, callback = None): if callback is not None: self.list_updating = True if self.list_updating: if not self.UpdateConsole: self.UpdateConsole = Console() cmd = self.ipkg.ipkg + " list_installed" self.UpdateConsole.ePopen(cmd, self.IpkgListInstalledCB, callback) def IpkgListInstalledCB(self, result, retval, extra_args = None): (callback) = extra_args if result: self.installed_packetlist = {} for x in result.splitlines(): tokens = x.split(' - ') name = tokens[0].strip() if not any(name.endswith(x) for x in self.unwanted_extensions): l = len(tokens) version = l > 1 and tokens[1].strip() or "" self.installed_packetlist[name] = version for package in self.packagesIndexlist[:]: if not self.verifyPrerequisites(package[0]["prerequisites"]): self.packagesIndexlist.remove(package) for package in self.packagesIndexlist[:]: attributes = package[0]["attributes"] if "packagetype" in attributes: if attributes["packagetype"] == "internal": self.packagesIndexlist.remove(package) if callback is None: self.countUpdates() else: if self.UpdateConsole: if not self.UpdateConsole.appContainers: callback(True) else: self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(False) def countUpdates(self, callback = None): self.available_updates = 0 self.available_updatelist = [] for package in self.packagesIndexlist[:]: attributes = package[0]["attributes"] packagename = attributes["packagename"] for x in self.available_packetlist: if x[0] == packagename: if packagename in self.installed_packetlist: if self.installed_packetlist[packagename] != x[1]: self.available_updates +=1 self.available_updatelist.append([packagename]) self.list_updating = False if self.UpdateConsole: if not self.UpdateConsole.appContainers: if callback is not None: callback(True) callback = None elif self.NotifierCallback is not None: self.NotifierCallback(True) self.NotifierCallback = None def startIpkgUpdate(self, callback = None): if not self.Console: self.Console = Console() cmd = self.ipkg.ipkg + " update" self.Console.ePopen(cmd, self.IpkgUpdateCB, callback) def IpkgUpdateCB(self, result, retval, extra_args = None): (callback) = extra_args if result: if self.Console: if not self.Console.appContainers: if callback is not None: callback(True) callback = None def cleanupSoftwareTools(self): self.list_updating = False if self.NotifierCallback is not None: self.NotifierCallback = None self.ipkg.stop() if self.Console is not None: self.Console.killAll() if self.UpdateConsole is not None: self.UpdateConsole.killAll() def verifyPrerequisites(self, prerequisites): if "hardware" in prerequisites: hardware_found = False for hardware in prerequisites["hardware"]: if hardware == HardwareInfo().device_name: hardware_found = True if not hardware_found: return False return True
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 NoRun = 0 # receivers only uses 1 media for multiboot FirstRun = 1 # receiver uses eMMC and SD card for multiboot - so handle SDcard slots 1st via SystemInfo(canMultiBoot) LastRun = 2 # receiver uses eMMC and SD card for multiboot - and then handle eMMC (currently one time) def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots, self.mtdboot) = SystemInfo["canMultiBoot"] self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.slot2 = 1 if SystemInfo["HasSDmmc"]: self.SDmmc = self.FirstRun # process SDcard slots else: self.SDmmc = self.NoRun # only mmc slots self.phase = self.MOUNT self.part = SystemInfo["canMultiBoot"][2] # pick up slot type self.run() else: callback({}) def run(self): if self.SDmmc == self.LastRun: self.part2 = getMachineMtdRoot() # process mmc slot self.slot2 = 1 else: self.part2 = "%s" %(self.part + str(self.slot * 2 + self.firstslot)) if self.SDmmc == self.FirstRun: self.slot2 += 1 # allow for mmc slot" if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' %self.part2 } self.container.ePopen('mount /dev/%s /tmp/testmount' %self.part2 if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: BuildVersion = " " Build = " " #ViX Build No.# Dev = " " #ViX Dev No.# Creator = " " #Openpli Openvix Openatv etc # Date = " " BuildType = " " #release etc # if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): if os.path.isfile('/tmp/testmount/etc/issue'): Creator = open("/tmp/testmount/etc/issue").readlines()[-2].capitalize().strip()[:-6].replace("-release", " rel") if Creator.startswith("Openpli"): build = [x.split("-")[-2:-1][0][-8:] for x in open("/tmp/testmount/var/lib/opkg/info/openpli-bootlogo.control").readlines() if x.startswith("Version:")] Date = "%s-%s-%s" % (build[0][6:], build[0][4:6], build[0][2:4]) BuildVersion = "%s %s" % (Creator, Date) elif Creator.startswith("Openvix"): reader = boxbranding_reader() BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild() or '' BuildVersion = "%s %s %s %s" % (Creator, BuildType[0:3], Build, Dev) else: st = os.stat('/tmp/testmount/var/lib/opkg/status') tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: Date = time.strftime("%d-%m-%Y", tm).replace("-20", "-") BuildVersion = "%s rel %s" % (Creator, Date) self.imagelist[self.slot2] = { 'imagename': '%s' %BuildVersion, 'part': '%s' %self.part2 } self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.slot2 = self.slot self.phase = self.MOUNT self.run() elif self.SDmmc == self.FirstRun: self.phase = self.MOUNT self.SDmmc = self.LastRun # process mmc slot self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class H9SDswap(Screen): if esHD(): skin = '\n\t\t<screen name="H9SDswap" position="400,75" size="1125,1250" flags="wfNoBorder" backgroundColor="transparent">\n\t\t<eLabel name="b" position="0,0" size="1125,950" backgroundColor="#00ffffff" zPosition="-2" />\n\t\t<eLabel name="a" position="1,1" size="1122,947" backgroundColor="#00000000" zPosition="-1" />\n\t\t<widget source="Title" render="Label" position="90,15" foregroundColor="#00ffffff" size="720,75" halign="left" font="RegularHD; 28" backgroundColor="#00000000" />\n\t\t<eLabel name="line" position="1,90" size="1122,1" backgroundColor="#00ffffff" zPosition="1" />\n\t\t<eLabel name="line2" position="1,375" size="1122,6" backgroundColor="#00ffffff" zPosition="1" />\n\t\t<widget name="config" position="3,420" size="1095,570" halign="center" font="RegularHD; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" />\n\t\t<widget source="labe14" render="Label" position="3,120" size="1095,45" halign="center" font="RegularHD; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="labe15" render="Label" position="3,195" size="1095,90" halign="center" font="RegularHD; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="key_red" render="Label" position="65,300" size="225,45" noWrap="1" zPosition="1" valign="center" font="RegularHD; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="key_green" render="Label" position="340,300" size="265,45" noWrap="1" zPosition="1" valign="center" font="RegularHD; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="key_yellow" render="Label" position="685,300" size="225,45" noWrap="1" zPosition="1" valign="center" font="RegularHD; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<ePixmap pixmap="buttons/red_HD.png" position="25,300" size="225,60" alphatest="on" />\n\t\t<ePixmap pixmap="buttons/green_HD.png" position="360,300" size="225,60" alphatest="on" />\n\t\t<ePixmap pixmap="buttons/yellow_HD.png" position="690,300" size="225,60" alphatest="on" />\n\t</screen>' else: skin = '\n\t\t<screen name="H9SDswap" position="250,50" size="750,850" flags="wfNoBorder" backgroundColor="transparent">\n\t\t<eLabel name="b" position="0,0" size="750,650" backgroundColor="#00ffffff" zPosition="-2" />\n\t\t<eLabel name="a" position="1,1" size="748,648" backgroundColor="#00000000" zPosition="-1" />\n\t\t<widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" />\n\t\t<eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" />\n\t\t<eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" />\n\t\t<widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" />\n\t\t<widget source="labe14" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="labe15" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="key_green" render="Label" position="230,200" size="180,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<widget source="key_yellow" render="Label" position="460,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" />\n\t\t<ePixmap pixmap="buttons/red.png" position="15,200" size="110,40" alphatest="on" />\n\t\t<ePixmap pixmap="buttons/green.png" position="245,200" size="210,40" alphatest="on" />\n\t\t<ePixmap pixmap="buttons/yellow.png" position="465,200" size="210,40" alphatest="on" />\n\t</screen>\n\t' def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = 'H9SDswap' screentitle = _('H9 switch Nand and SDcard') self['key_red'] = StaticText(_('Cancel')) self['key_green'] = StaticText(_('SwaptoNand')) self['key_yellow'] = StaticText(_('SwaptoSD')) self.title = screentitle self.switchtype = ' ' self['actions'] = ActionMap( ['ColorActions', 'OkCancelActions'], { 'cancel': boundFunction(self.close, None), 'red': boundFunction(self.close, None), 'green': self.SwaptoNand, 'yellow': self.SwaptoSD }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def SwaptoNand(self): self.switchtype = 'Nand' f = open('/proc/cmdline', 'r').read() if 'root=/dev/mmcblk0p1' in f: self.container = Console() self.container.ePopen( 'dd if=/usr/share/bootargs-nand.bin of=/dev/mtdblock1', self.Unm) else: self.session.open(MessageBox, _('H9 SDcard switch ERROR! - already on Nand'), MessageBox.TYPE_INFO, timeout=20) def SwaptoSD(self): self.switchtype = 'mmc' f = open('/proc/cmdline', 'r').read() print '[H9SDswap] switchtype %s cmdline %s' % (self.switchtype, f) if 'root=/dev/mmcblk0p1' in f: self.session.open(MessageBox, _('H9 SDcard switch ERROR! - already on mmc'), MessageBox.TYPE_INFO, timeout=20) elif os.path.isfile('/media/mmc/usr/bin/enigma2'): self.container = Console() self.container.ePopen( 'dd if=/usr/share/bootargs-mmc.bin of=/dev/mtdblock1', self.Unm) else: self.session.open( MessageBox, _('H9 SDcard switch ERROR! - H9 root files not transferred to SD card' ), MessageBox.TYPE_INFO, timeout=20) def SwaptoUSB(self): self.switchtype = 'usb' f = open('/proc/cmdline', 'r').read() print '[H9SDswap] switchtype %s cmdline %s' % (self.switchtype, f) if 'root=/dev/SDA1' in f: self.session.open(MessageBox, _('H9 USB switch ERROR! - already on USB'), MessageBox.TYPE_INFO, timeout=20) elif os.path.isfile('/media/mmc/usr/bin/enigma2'): self.container = Console() self.container.ePopen( 'dd if=/usr/share/bootargs-usb.bin of=/dev/mtdblock1', self.Unm) else: self.session.open( MessageBox, _('H9 USB switch ERROR! - H9 root files not transferred to USB' ), MessageBox.TYPE_INFO, timeout=20) def Unm(self, data=None, retval=None, extra_args=None): self.container.killAll() self.session.open(TryQuitMainloop, 2)
class H9SDswap(Screen): skin = """ <screen name="H9SDswap" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="labe14" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="labe15" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="230,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_yellow" render="Label" position="430,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_blue" render="Label" position="630,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="630,200" size="40,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/red.png" position="30,200" size="40,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="230,200" size="40,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="430,200" size="40,40" alphatest="on" /> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "H9SDswap" screentitle = _("H9 switch Nand to SDcard/USB") self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("SwaptoNand")) self["key_yellow"] = StaticText(_("SwaptoSD")) self["key_blue"] = StaticText(_("SwaptoUSB")) self.title = screentitle self.switchtype = " " self["actions"] = ActionMap( ["ColorActions"], { "red": boundFunction(self.close, None), "green": self.SwaptoNand, "yellow": self.SwaptoSD, "blue": self.SwaptoUSB, }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def SwaptoNand(self): if "root=/dev/mmcblk0p1" in open('/proc/cmdline', 'r').read(): self.container = Console() self.container.ePopen( "dd if=/usr/share/bootargs-nand.bin of=/dev/mtdblock1", self.Unm) else: self.session.open(MessageBox, _("H9 SDcard switch ERROR! - already on Nand"), MessageBox.TYPE_INFO, timeout=20) def SwaptoSD(self): if "root=/dev/mmcblk0p1" in open('/proc/cmdline', 'r').read(): self.session.open(MessageBox, _("H9 SDcard switch ERROR! - already on mmc"), MessageBox.TYPE_INFO, timeout=20) elif os.path.isfile("/media/H9-ROOTFS/usr/bin/enigma2"): self.container = Console() self.container.ePopen( "dd if=/usr/share/bootargs-mmc.bin of=/dev/mtdblock1", self.Unm) else: self.session.open( MessageBox, _("H9 SDcard switch ERROR! - H9 root files not transferred to SD card" ), MessageBox.TYPE_INFO, timeout=20) def SwaptoUSB(self): self.switchtype = "usb" f = open('/proc/cmdline', 'r').read() print "[H9SDswap] switchtype %s cmdline %s" % (self.switchtype, f) if "root=/dev/SDA1" in f: self.session.open(MessageBox, _("H9 USB switch ERROR! - already on USB"), MessageBox.TYPE_INFO, timeout=20) elif os.path.isfile("/media/H9-ROOTFS/usr/bin/enigma2"): self.container = Console() self.container.ePopen( "dd if=/usr/share/bootargs-usb.bin of=/dev/mtdblock1", self.Unm) else: self.session.open( MessageBox, _("H9 USB switch ERROR! - H9 root files not transferred to USB" ), MessageBox.TYPE_INFO, timeout=20) def Unm(self, data=None, retval=None, extra_args=None): self.container.killAll() self.session.open(TryQuitMainloop, 2)
class Network(): def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = 'ethtool' self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.PingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: import Harddisk for parts in Harddisk.getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'tap0') def getInterfaces(self, callback = None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) def regExpMatch(self, pattern, string): if string is None: return try: return pattern.search(string).group() except AttributeError: return def convertIP(self, ip): return [ int(n) for n in ip.split('.') ] def getAddrInet(self, iface, callback): if not self.Console: self.Console = Console() cmd = 'ip -o addr show dev ' + iface self.Console.ePopen(cmd, self.IPaddrFinished, [iface, callback]) def IPaddrFinished(self, result, retval, extra_args): iface, callback = extra_args data = {'up': False, 'dhcp': False, 'preup': False, 'predown': False} globalIPpattern = re.compile('scope global') ipRegexp = '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' netRegexp = '[0-9]{1,2}' macRegexp = '[0-9a-fA-F]{2}\\:[0-9a-fA-F]{2}\\:[0-9a-fA-F]{2}\\:[0-9a-fA-F]{2}\\:[0-9a-fA-F]{2}\\:[0-9a-fA-F]{2}' ipLinePattern = re.compile('inet ' + ipRegexp + '/') ipPattern = re.compile(ipRegexp) netmaskLinePattern = re.compile('/' + netRegexp) netmaskPattern = re.compile(netRegexp) bcastLinePattern = re.compile(' brd ' + ipRegexp) upPattern = re.compile('UP') macPattern = re.compile(macRegexp) macLinePattern = re.compile('link/ether ' + macRegexp) for line in result.splitlines(): split = line.strip().split(' ', 2) if split[1][:-1] == iface: up = self.regExpMatch(upPattern, split[2]) mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2])) if up is not None: data['up'] = True if iface is not 'lo': self.configuredInterfaces.append(iface) if mac is not None: data['mac'] = mac if split[1] == iface: if re.search(globalIPpattern, split[2]): ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2])) netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2]))) bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2])) if ip is not None: data['ip'] = self.convertIP(ip) if netmask is not None: data['netmask'] = self.convertIP(netmask) if bcast is not None: data['bcast'] = self.convertIP(bcast) if not data.has_key('ip'): data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] cmd = 'route -n | grep ' + iface self.Console.ePopen(cmd, self.routeFinished, [iface, data, callback]) def routeFinished(self, result, retval, extra_args): iface, data, callback = extra_args ipRegexp = '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' ipPattern = re.compile(ipRegexp) ipLinePattern = re.compile(ipRegexp) for line in result.splitlines(): print line[0:7] if line[0:7] == '0.0.0.0': gateway = self.regExpMatch(ipPattern, line[16:31]) if gateway: data['gateway'] = self.convertIP(gateway) self.ifaces[iface] = data self.loadNetworkConfig(iface, callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = file('/etc/network/interfaces', 'w') fp.write('# automatically generated by enigma2\n# do NOT change manually!\n\n') fp.write('auto lo\n') fp.write('iface lo inet loopback\n\n') for ifacename, iface in self.ifaces.items(): if iface['up']: fp.write('auto ' + ifacename + '\n') self.configuredInterfaces.append(ifacename) if iface['dhcp']: fp.write('iface ' + ifacename + ' inet dhcp\n') fp.write(' hostname $(hostname)\n') if not iface['dhcp']: fp.write('iface ' + ifacename + ' inet static\n') fp.write(' hostname $(hostname)\n') if iface.has_key('ip'): fp.write('\taddress %d.%d.%d.%d\n' % tuple(iface['ip'])) fp.write('\tnetmask %d.%d.%d.%d\n' % tuple(iface['netmask'])) if iface.has_key('gateway'): fp.write('\tgateway %d.%d.%d.%d\n' % tuple(iface['gateway'])) if iface.has_key('configStrings'): fp.write(iface['configStrings']) if iface['preup'] is not False and not iface.has_key('configStrings'): fp.write(iface['preup']) if iface['predown'] is not False and not iface.has_key('configStrings'): fp.write(iface['predown']) fp.write('\n') fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): try: os.system('rm -rf /etc/resolv.conf') fp = file('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write('nameserver %d.%d.%d.%d\n' % tuple(nameserver)) fp.close() except: print '[Network.py] interfaces - resolv.conf write failed' def loadNetworkConfig(self, iface, callback = None): interfaces = [] try: fp = file('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print '[Network.py] interfaces - opening failed' ifaces = {} currif = '' for i in interfaces: split = i.strip().split(' ') if split[0] == 'iface': currif = split[1] ifaces[currif] = {} if len(split) == 4 and split[3] == 'dhcp': ifaces[currif]['dhcp'] = True else: ifaces[currif]['dhcp'] = False if currif == iface: if split[0] == 'address': ifaces[currif]['address'] = map(int, split[1].split('.')) if self.ifaces[currif].has_key('ip'): if self.ifaces[currif]['ip'] != ifaces[currif]['address'] and ifaces[currif]['dhcp'] == False: self.ifaces[currif]['ip'] = map(int, split[1].split('.')) if split[0] == 'netmask': ifaces[currif]['netmask'] = map(int, split[1].split('.')) if self.ifaces[currif].has_key('netmask'): if self.ifaces[currif]['netmask'] != ifaces[currif]['netmask'] and ifaces[currif]['dhcp'] == False: self.ifaces[currif]['netmask'] = map(int, split[1].split('.')) if split[0] == 'gateway': ifaces[currif]['gateway'] = map(int, split[1].split('.')) if self.ifaces[currif].has_key('gateway'): if self.ifaces[currif]['gateway'] != ifaces[currif]['gateway'] and ifaces[currif]['dhcp'] == False: self.ifaces[currif]['gateway'] = map(int, split[1].split('.')) if split[0] == 'pre-up': if self.ifaces[currif].has_key('preup'): self.ifaces[currif]['preup'] = i if split[0] in ('pre-down', 'post-down'): if self.ifaces[currif].has_key('predown'): self.ifaces[currif]['predown'] = i for ifacename, iface in ifaces.items(): if self.ifaces.has_key(ifacename): self.ifaces[ifacename]['dhcp'] = iface['dhcp'] if self.Console: if len(self.Console.appContainers) == 0: self.configuredNetworkAdapters = self.configuredInterfaces self.loadNameserverConfig() self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' nameserverPattern = re.compile('nameserver +' + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = file('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print '[Network.py] resolv.conf - opening failed' for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) def getInstalledAdapters(self): return [ x for x in os.listdir('/sys/class/net') if not self.isBlacklisted(x) ] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get(x, x) def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _('WLAN connection') if len(self.wlan_interfaces): name += ' ' + str(len(self.wlan_interfaces) + 1) self.wlan_interfaces.append(iface) elif iface not in self.lan_interfaces: if getBoxType() == 'et10000' and iface == 'eth1': name = _('VLAN connection') else: name = _('LAN connection') if len(self.lan_interfaces) and not getBoxType() == 'et10000' and not iface == 'eth1': name += ' ' + str(len(self.lan_interfaces) + 1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = os.path.basename(os.path.realpath(moduledir)) if name in ('ath_pci', 'ath5k'): name = 'Atheros' elif name in ('rt73', 'rt73usb', 'rt3070sta'): name = 'Ralink' elif name == 'zd1211b': name = 'Zydas' elif name == 'r871x_usb_drv': name = 'Realtek' else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return self.ifaces.keys() def getAdapterAttribute(self, iface, attribute): if self.ifaces.has_key(iface): if self.ifaces[iface].has_key(attribute): return self.ifaces[iface][attribute] def setAdapterAttribute(self, iface, attribute, value): if self.ifaces.has_key(iface): self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if self.ifaces.has_key(iface): if self.ifaces[iface].has_key(attribute): del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode = 'lan', callback = None): self.resetNetworkConsole = Console() self.commands = [] self.commands.append('/etc/init.d/avahi-daemon stop') for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append('ip addr flush dev ' + iface + ' scope global') self.commands.append('/etc/init.d/networking stop') self.commands.append('killall -9 udhcpc') self.commands.append('rm /var/run/udhcpc*') self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): mode, callback = extra_args if len(self.resetNetworkConsole.appContainers) == 0: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self, mode = 'lan', callback = None): fp = file('/etc/network/interfaces', 'w') fp.write('# automatically generated by enigma2\n# do NOT change manually!\n\n') fp.write('auto lo\n') fp.write('iface lo inet loopback\n\n') if mode == 'wlan': fp.write('auto wlan0\n') fp.write('iface wlan0 inet dhcp\n') if mode == 'wlan-mpci': fp.write('auto ath0\n') fp.write('iface ath0 inet dhcp\n') if mode == 'lan': fp.write('auto eth0\n') fp.write('iface eth0 inet dhcp\n') fp.write('\n') fp.close() self.resetNetworkConsole = Console() self.commands = [] if mode == 'wlan': self.commands.append('ifconfig eth0 down') self.commands.append('ifconfig ath0 down') self.commands.append('ifconfig wlan0 up') if mode == 'wlan-mpci': self.commands.append('ifconfig eth0 down') self.commands.append('ifconfig wlan0 down') self.commands.append('ifconfig ath0 up') if mode == 'lan': self.commands.append('ifconfig eth0 up') self.commands.append('ifconfig wlan0 down') self.commands.append('ifconfig ath0 down') self.commands.append('/etc/init.d/avahi-daemon start') self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode, callback], debug=True) def resetNetworkFinished(self, extra_args): mode, callback = extra_args if len(self.resetNetworkConsole.appContainers) == 0: if callback is not None: callback(True, mode) def checkNetworkState(self, statecallback): self.NetworkState = 0 cmd1 = 'ping -c 1 www.openpli.org' cmd2 = 'ping -c 1 www.google.nl' cmd3 = 'ping -c 1 www.google.com' self.PingConsole = Console() self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished, statecallback) self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished, statecallback) self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished, statecallback) def checkNetworkStateFinished(self, result, retval, extra_args): statecallback = extra_args if self.PingConsole is not None: if retval == 0: self.PingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if len(self.PingConsole.appContainers) == 0: statecallback(self.NetworkState) def restartNetwork(self, callback = None): self.restartConsole = Console() self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append('/etc/init.d/avahi-daemon stop') for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append('ifdown ' + iface) self.commands.append('ip addr flush dev ' + iface + ' scope global') self.commands.append('/etc/init.d/networking stop') self.commands.append('killall -9 udhcpc') self.commands.append('rm /var/run/udhcpc*') self.commands.append('/etc/init.d/networking start') self.commands.append('/etc/init.d/avahi-daemon start') self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self, extra_args): callback = extra_args if callback is not None: try: callback(True) except: pass def getLinkState(self, iface, callback): cmd = self.ethtool_bin + ' ' + iface self.LinkConsole = Console() self.LinkConsole.ePopen(cmd, self.getLinkStateFinished, callback) def getLinkStateFinished(self, result, retval, extra_args): callback = extra_args if self.LinkConsole is not None: if len(self.LinkConsole.appContainers) == 0: callback(result) def stopPingConsole(self): if self.PingConsole is not None: if len(self.PingConsole.appContainers): for name in self.PingConsole.appContainers.keys(): self.PingConsole.kill(name) def stopLinkStateConsole(self): if self.LinkConsole is not None: if len(self.LinkConsole.appContainers): for name in self.LinkConsole.appContainers.keys(): self.LinkConsole.kill(name) def stopDNSConsole(self): if self.DnsConsole is not None: if len(self.DnsConsole.appContainers): for name in self.DnsConsole.appContainers.keys(): self.DnsConsole.kill(name) def stopRestartConsole(self): if self.restartConsole is not None: if len(self.restartConsole.appContainers): for name in self.restartConsole.appContainers.keys(): self.restartConsole.kill(name) def stopGetInterfacesConsole(self): if self.Console is not None: if len(self.Console.appContainers): for name in self.Console.appContainers.keys(): self.Console.kill(name) def stopDeactivateInterfaceConsole(self): if self.deactivateInterfaceConsole is not None: self.deactivateInterfaceConsole.killAll() self.deactivateInterfaceConsole = None def stopActivateInterfaceConsole(self): if self.activateInterfaceConsole is not None: self.activateInterfaceConsole.killAll() self.activateInterfaceConsole = None def checkforInterface(self, iface): if self.getAdapterAttribute(iface, 'up') is True: return True ret = os.system('ifconfig ' + iface + ' up') os.system('ifconfig ' + iface + ' down') if ret == 0: return True else: return False def checkDNSLookup(self, statecallback): cmd1 = 'nslookup www.dream-multimedia-tv.de' cmd2 = 'nslookup www.heise.de' cmd3 = 'nslookup www.google.de' self.DnsConsole = Console() self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished, statecallback) self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished, statecallback) self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished, statecallback) def checkDNSLookupFinished(self, result, retval, extra_args): statecallback = extra_args if self.DnsConsole is not None: if retval == 0: self.DnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if len(self.DnsConsole.appContainers) == 0: statecallback(self.DnsState) def deactivateInterface(self, ifaces, callback = None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append('ifdown ' + iface) commands.append('ip addr flush dev ' + iface + ' scope global') if os.path.exists('/var/run/wpa_supplicant/' + iface): commands.append('wpa_cli -i' + iface + ' terminate') if not self.deactivateInterfaceConsole: self.deactivateInterfaceConsole = Console() if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces, callback], debug=True) def deactivateInterfaceFinished(self, extra_args): ifaces, callback = extra_args def checkCommandResult(iface): if self.deactivateInterfaceConsole and self.deactivateInterfaceConsole.appResults.has_key('ifdown ' + iface): result = str(self.deactivateInterfaceConsole.appResults.get('ifdown ' + iface)).strip('\n') if result == 'ifdown: interface ' + iface + ' not configured': return False else: return True if isinstance(ifaces, (list, tuple)): for iface in ifaces: if checkCommandResult(iface) is False: Console().ePopen('ifconfig ' + iface + ' down') elif checkCommandResult(ifaces) is False: Console().ePopen('ifconfig ' + ifaces + ' down') if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def activateInterface(self, iface, callback = None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return if not self.activateInterfaceConsole: self.activateInterfaceConsole = Console() commands = ['ifup ' + iface] self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self, extra_args): callback = extra_args if self.activateInterfaceConsole: if len(self.activateInterfaceConsole.appContainers) == 0: if callback is not None: try: callback(True) except: pass def sysfsPath(self, iface): return '/sys/class/net/' + iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True try: if os.path.isdir(self.sysfsPath(iface) + '/wireless'): return True except: os.system('rm /etc/enigma2/settings;killall enigma2') device = re.compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass fp.close() if iface in ifnames: return True return False def getWlanModuleDir(self, iface = None): devicedir = self.sysfsPath(iface) + '/device' moduledir = devicedir + '/driver/module' if os.path.isdir(moduledir): return moduledir for x in os.listdir(devicedir): if x.startswith('1-'): moduledir = devicedir + '/' + x + '/driver/module' if os.path.isdir(moduledir): return moduledir moduledir = devicedir + '/driver' if os.path.isdir(moduledir): return moduledir def detectWlanModule(self, iface = None): if not self.isWirelessInterface(iface): return None devicedir = self.sysfsPath(iface) + '/device' if os.path.isdir(devicedir + '/ieee80211'): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = os.path.basename(os.path.realpath(moduledir)) if module in ('ath_pci', 'ath5k'): return 'madwifi' if module in ('rt73', 'rt73'): return 'ralink' if module == 'zd1211b': return 'zydas' return 'wext' def calc_netmask(self, nmask): from struct import pack from socket import inet_ntoa mask = 2147483648L xnet = 4294967295L cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print 'cidr invalid: %d' % cidr return None else: nm = (1L << cidr) - 1 << 32 - cidr netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == 'add': print '[Network] Add new interface:', interface self.getAddrInet(interface, None) elif action == 'remove': print '[Network] Removed interface:', interface try: del self.ifaces[interface] except KeyError: pass
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback = None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface) def iwconfigFinished(self, result, retval, extra_args): iface = extra_args data = { 'essid': False, 'frequency': False, 'accesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False } for line in result.splitlines(): line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = "off" else: if "Nickname" in line: ssid=(line[line.index('ESSID')+7:line.index('" Nickname')]) else: ssid=(line[line.index('ESSID')+7:len(line)-1]) if ssid is not None: data['essid'] = ssid if "Frequency" in line: frequency = line[line.index('Frequency')+10 :line.index(' GHz')] if frequency is not None: data['frequency'] = frequency if "Access Point" in line: if "Sensitivity" in line: ap=line[line.index('Access Point')+14:line.index(' Sensitivity')] else: ap=line[line.index('Access Point')+14:len(line)] if ap is not None: data['accesspoint'] = ap if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate')+9 :line.index(' kb/s')] else: br = line[line.index('Bit Rate')+9 :line.index(' Mb/s')] if br is not None: data['bitrate'] = br if "Encryption key" in line: if ":off" in line: enc = "off" elif "Security" in line: enc = line[line.index('Encryption key')+15 :line.index(' Security')] if enc is not None: enc = "on" else: enc = line[line.index('Encryption key')+15 :len(line)] if enc is not None: enc = "on" if enc is not None: data['encryption'] = enc if 'Quality' in line: if "/100" in line: qual = line[line.index('Quality')+8:line.index(' Signal')] else: qual = line[line.index('Quality')+8:line.index('Sig')] if qual is not None: data['quality'] = qual if 'Signal level' in line: if "dBm" in line: signal = line[line.index('Signal level')+13 :line.index(' dBm')] + " dBm" elif "/100" in line: if "Noise" in line: signal = line[line.index('Signal level')+13:line.index(' Noise')] else: signal = line[line.index('Signal level')+13:len(line)] else: if "Noise" in line: signal = line[line.index('Signal level')+13:line.index(' Noise')] else: signal = line[line.index('Signal level')+13:len(line)] if signal is not None: data['signal'] = signal self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if len(self.WlanConsole.appContainers) == 0: print "[Wlan.py] self.wlaniface after loading:", self.wlaniface if self.statusCallback is not None: self.statusCallback(True,self.wlaniface) self.statusCallback = None def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.wlaniface.has_key(self.iface): if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None
class MultibootSelection(SelectImage): def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "SelectImage" self.session = session self.imagesList = None self.expanded = [] self.setTitle(_("Select Multiboot")) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Reboot")) self["list"] = ChoiceList(list=[ ChoiceEntryComponent('', ( (_("Retrieving image slots - Please wait...")), "Waiter")) ]) self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "ok": self.keyOk, "cancel": self.cancel, "red": self.cancel, "green": self.keyOk, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.cancel, True), }, -1) self.callLater(self.getBootOptions) def cancel(self, value=None): self.container = Console() self.container.ePopen('umount /tmp/startupmount', boundFunction(self.unmountCallback, value)) def unmountCallback(self, value, data=None, retval=None, extra_args=None): self.container.killAll() if not os.path.ismount('/tmp/startupmount'): os.rmdir('/tmp/startupmount') self.close(value) def getBootOptions(self, value=None): self.container = Console() if os.path.isdir('/tmp/startupmount'): self.getImagesList() else: if os.path.islink("/dev/block/by-name/bootoptions"): os.mkdir('/tmp/startupmount') self.container.ePopen( 'mount /dev/block/by-name/bootoptions /tmp/startupmount', self.getImagesList) elif os.path.islink("/dev/block/by-name/boot"): os.mkdir('/tmp/startupmount') self.container.ePopen( 'mount /dev/block/by-name/boot /tmp/startupmount', self.getImagesList) else: os.mkdir('/tmp/startupmount') self.container.ePopen( 'mount /dev/%sp1 /tmp/startupmount' % SystemInfo["canMultiBoot"][2], self.getImagesList) def getImagesList(self, data=None, retval=None, extra_args=None): self.container.killAll() self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagesdict): list = [] currentimageslot = GetCurrentImage() mode = GetCurrentImageMode() or 0 if imagesdict: for index, x in enumerate(sorted(imagesdict.keys())): if imagesdict[x]["imagename"] != _("Empty slot"): if SystemInfo["canMode12"]: list.insert( index, ChoiceEntryComponent( '', ((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagesdict[x]['imagename']), x))) list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagesdict[x]['imagename']), x + 12))) else: list.append( ChoiceEntryComponent( '', ((_("slot%s - %s (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s")) % (x, imagesdict[x]['imagename']), x))) if os.path.isfile("/tmp/startupmount/STARTUP_RECOVERY"): list.append( ChoiceEntryComponent( '', ((_("Boot to Recovery menu")), "Recovery"))) if os.path.isfile("/tmp/startupmount/STARTUP_ANDROID"): list.append( ChoiceEntryComponent( '', ((_("Boot to Android image")), "Android"))) if not list: list.append( ChoiceEntryComponent('', ((_("No images found")), "Waiter"))) self["list"].setList(list) def keyOk(self): self.currentSelected = self["list"].l.getCurrentSelection() self.slot = self.currentSelected[0][1] if self.slot != "Waiter": self.session.openWithCallback( self.doReboot, MessageBox, "%s:\n%s" % (_("Are you sure to reboot to"), self.currentSelected[0][0]), simple=True) def doReboot(self, answer): if answer: if self.slot == "Recovery": shutil.copyfile("/tmp/startupmount/STARTUP_RECOVERY", "/tmp/startupmount/STARTUP") elif self.slot == "Android": shutil.copyfile("/tmp/startupmount/STARTUP_ANDROID", "/tmp/startupmount/STARTUP") else: model = getBoxType() if SystemInfo["canMultiBoot"][3]: shutil.copyfile("/tmp/startupmount/STARTUP_%s" % self.slot, "/tmp/startupmount/STARTUP") elif os.path.isfile( "/tmp/startupmount/STARTUP_LINUX_4_BOXMODE_12"): if self.slot < 12: shutil.copyfile( "/tmp/startupmount/STARTUP_LINUX_%s_BOXMODE_1" % self.slot, "/tmp/startupmount/STARTUP") else: self.slot -= 12 shutil.copyfile( "/tmp/startupmount/STARTUP_LINUX_%s_BOXMODE_12" % self.slot, "/tmp/startupmount/STARTUP") elif os.path.isfile("/tmp/startupmount/STARTUP_LINUX_4"): shutil.copyfile( "/tmp/startupmount/STARTUP_LINUX_%s" % self.slot, "/tmp/startupmount/STARTUP") elif os.path.isfile("/tmp/startupmount/STARTUP_4"): shutil.copyfile("/tmp/startupmount/STARTUP_%s" % self.slot, "/tmp/startupmount/STARTUP") else: if self.slot < 12: startupFileContents = "boot emmcflash0.kernel%s 'root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=1'\n" % ( self.slot, self.slot * 2 + 1, model) else: self.slot -= 12 startupFileContents = "boot emmcflash0.kernel%s 'brcm_cma=520M@248M brcm_cma=%s@768M root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=12'\n" % ( self.slot, SystemInfo["canMode12"], self.slot * 2 + 1, model) open('/tmp/startupmount/STARTUP', 'w').write(startupFileContents) from Screens.Standby import TryQuitMainloop self.session.open(TryQuitMainloop, 2) def selectionChanged(self): pass
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print("[iStatus] killing self.WlanConsole") self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface) def iwconfigFinished(self, result, retval, extra_args): result = six.ensure_str(result) iface = extra_args ssid = "off" data = { 'essid': False, 'frequency': False, 'accesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False, 'channel': False, 'encryption_type': False, 'frequency': False, 'frequency_norm': False } for line in result.splitlines(): line = line.strip() if "ESSID" in line: if "off/any" in line: ssid = "off" else: if "Nickname" in line: ssid = (line[line.index('ESSID') + 7:line.index('" Nickname')]) else: ssid = (line[line.index('ESSID') + 7:len(line) - 1]) if ssid != "off": data['essid'] = ssid if "Access Point" in line: if "Sensitivity" in line: ap = line[line.index('Access Point') + 14:line.index(' Sensitivity')] else: ap = line[line.index('Access Point') + 14:len(line)] if ap is not None: data['accesspoint'] = ap if "Frequency" in line: frequency = line[line.index('Frequency') + 10:line.index(' GHz')] if frequency is not None: data['frequency'] = frequency if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate') + 9:line.index(' kb/s')] elif "Gb" in line: br = line[line.index('Bit Rate') + 9:line.index(' Gb/s')] else: br = line[line.index('Bit Rate') + 9:line.index(' Mb/s')] if br is not None: data['bitrate'] = br if ssid != None and ssid != "off": scanresults = list(Cell.all(iface)) aps = {} if scanresults is not None: for i in range(len(scanresults)): bssid = scanresults[i].ssid aps[bssid] = { 'active': True, 'bssid': scanresults[i].ssid, 'essid': scanresults[i].ssid, 'channel': scanresults[i].channel, 'encrypted': scanresults[i].encrypted, 'encryption_type': scanresults[i].encryption_type if scanresults[i].encrypted else "none", 'iface': iface, 'maxrate': scanresults[i].bitrates, 'mode': scanresults[i].mode, 'quality': scanresults[i].quality, 'signal': scanresults[i].signal, 'frequency': scanresults[i].frequency, 'frequency_norm': scanresults[i].frequency_norm, 'address': scanresults[i].address, 'noise': scanresults[i].noise, 'pairwise_ciphers': scanresults[i].pairwise_ciphers, 'authentication_suites': scanresults[i].authentication_suites, } #data['bitrate'] = aps[ssid]["maxrate"] data['encryption'] = aps[ssid]["encrypted"] data['quality'] = aps[ssid]["quality"] data['signal'] = aps[ssid]["signal"] data['channel'] = aps[ssid]["channel"] data['encryption_type'] = aps[ssid]["encryption_type"] #data['frequency'] = aps[ssid]["frequency"] data['frequency_norm'] = aps[ssid]["frequency_norm"] self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if not self.WlanConsole.appContainers: print("[Wlan.py] self.wlaniface after loading:", self.wlaniface) if self.statusCallback is not None: self.statusCallback(True, self.wlaniface) self.statusCallback = None def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.iface in self.wlaniface: if attribute in self.wlaniface[self.iface]: return self.wlaniface[self.iface][attribute] return None
class Cpart(Screen): PA_TYPE_USE = 1 PA_TYPE_LAST = 2 PA_TYPE_FREE = 4 skin = """<screen position="center,center" size="820,320" title="eParted"> <widget name="PixmapRed" pixmaps="skin_default/buttons/button_off.png,skin_default/buttons/button_red.png" position="10,12" size="25,25" alphatest="on" /> <widget name="PixmapGreen" pixmaps="skin_default/buttons/button_off.png,skin_default/buttons/button_green.png" position="290,12" size="25,25" alphatest="on" /> <widget name="PixmapBlue" pixmaps="skin_default/buttons/button_off.png,skin_default/buttons/button_blue.png" position="570,12" size="25,25" alphatest="on" /> <widget name="LabelRed" position="50,5" size="200,40" valign="center" backgroundColor="background" font="Regular;21" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" /> <widget name="LabelGreen" position="330,5" size="200,40" valign="center" backgroundColor="background" font="Regular;21" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" /> <widget name="LabelBlue" position="610,5" size="200,40" valign="center" backgroundColor="background" font="Regular;21" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" /> <eLabel position="10,50" size="800,1" backgroundColor="grey" /> <widget source="list" render="Listbox" position="10,60" size="800,240" enableWrapAround="1" scrollbarMode="showOnDemand"> <convert type="TemplatedMultiContent"> {"template": [ MultiContentEntryText(pos = (10,2), size = (60, 30), font=0, flags = RT_HALIGN_LEFT, text=0), MultiContentEntryText(pos = (80,2), size = (170, 30), font=0, flags = RT_HALIGN_LEFT, text=1), MultiContentEntryText(pos = (260,2), size = (170, 30), font=0, flags = RT_HALIGN_LEFT, text=2), MultiContentEntryText(pos = (440,2), size = (170, 30), font=0, flags = RT_HALIGN_LEFT, text=3), MultiContentEntryText(pos = (620,2), size = (180, 30), font=0, flags = RT_HALIGN_LEFT, text=4) ], "fonts": [gFont("Regular", 21)], "itemHeight": 30 } </convert> </widget> </screen>""" def __init__(self, session, entry): Screen.__init__(self, session) self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "cancel": self.Exit, "green": self.KeyGreen, "blue": self.KeyBlue, "red": self.KeyRed }, -1) self["list"] = List(list=[]) self["list"].onSelectionChanged.append(self.__SetLabels) self["PixmapRed"] = MultiPixmap() self["PixmapGreen"] = MultiPixmap() self["PixmapBlue"] = MultiPixmap() self["LabelRed"] = Label() self["LabelGreen"] = Label() self["LabelBlue"] = Label() self.__devpath = entry[DEV_PATH] self.__fullsize = 0 self.__old_part_list = [] self.__new_part_list = [] self.__comlist = [] self.__unit = entry[2][len(entry[2]) - 2:] self.Console = Console() self.__getPartInfo() def Exit(self): self.Console.killAll() self.close() def __getPartInfo(self, val=None): self.Console.ePopen("parted -m %s unit %s print" % (self.__devpath, self.__unit), self.__FinishedConsole) def __Filllist(self): list = [] index = self["list"].getIndex() for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: #print x p0 = "%s: %s" % (_("Nr"), x[PA_NR]) p1 = "%s: %d%s" % (_("Start"), x[PA_START], self.__unit) p2 = "%s: %d%s" % (_("End"), x[PA_END], self.__unit) p3 = "%s: %d%s" % (_("Size"), x[PA_SIZE], self.__unit) p4 = "%s: %s" % (_("Type"), x[PA_FS]) list.append((p0, p1, p2, p3, p4, x)) self["list"].setList(list) self["list"].setIndex(index) self.__createCommandList() def __SetLabels(self): sel = self["list"].getCurrent() self["LabelGreen"].setText("") self["LabelRed"].setText("") if sel and sel[5]: if sel[5][PA_TYPE] & self.PA_TYPE_FREE and len(self.__new_part_list) < 6: self["PixmapGreen"].setPixmapNum(1) self["LabelGreen"].setText(_("add")) else: self["PixmapGreen"].setPixmapNum(0) if sel[5][PA_TYPE] & self.PA_TYPE_LAST and bool(sel[5][PA_TYPE] & self.PA_TYPE_FREE) == False: self["PixmapRed"].setPixmapNum(1) self["LabelRed"].setText(_("delete")) else: self["PixmapRed"].setPixmapNum(0) def __addFreePart(self, plist, lastPartEnd): x = [LIST_TYPE_PAR, str(len(plist)), lastPartEnd, self.__fullsize, 0, _("free"), (self.PA_TYPE_FREE | self.PA_TYPE_LAST), ";"] plist.append(x) def __FinishedConsole(self, result, retval, extra_args=None): if retval == 0 and '\n' in result: tlist = parseCmd(result) if len(tlist): self.__old_part_list = tlist[0][:] self.__new_part_list = tlist[0][:] lastPartEnd = 0 count = 2 for x in self.__old_part_list: if x[LIST_TYPE] == LIST_TYPE_DEV: self.__fullsize = getInt_epart(x[DEV_SIZE]) name = x[DEV_NAME] if len(name) == 0: name = x[DEV_PATH] name += " (%s)" % x[DEV_SIZE] self.setTitle(name) else: lastPartEnd = x[PA_END] x[PA_TYPE] = self.PA_TYPE_USE if count == len(self.__old_part_list):#is letzte part x[PA_TYPE] |= self.PA_TYPE_LAST count += 1 if lastPartEnd < self.__fullsize:#Wenn noch Frei, Part erstellen self.__addFreePart(self.__old_part_list, lastPartEnd) self.__addFreePart(self.__new_part_list, lastPartEnd) self.__Filllist() def KeyBlue(self): if len(self.__comlist): self.session.openWithCallback(self.__getPartInfo, Cpartexe, self.__comlist) def KeyRed(self): sel = self["list"].getCurrent() if sel and sel[1] and sel[5][PA_TYPE] & self.PA_TYPE_LAST and bool(sel[5][PA_TYPE] & self.PA_TYPE_FREE) == False: try: self.__new_part_list.remove(sel[5])#aktuelle part löschen for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: if x[PA_TYPE] & self.PA_TYPE_FREE:#letzte Freie suchen und auch löschen self.__new_part_list.remove(x) break else: x[PA_TYPE] = self.PA_TYPE_USE lastPartEnd = 0 if len(self.__new_part_list) > 1:#von letzter Part, TYp setzen und Ende ermitteln self.__new_part_list[len(self.__new_part_list) - 1][PA_TYPE] = self.PA_TYPE_USE | self.PA_TYPE_LAST lastPartEnd = self.__new_part_list[len(self.__new_part_list) - 1][PA_END] if lastPartEnd < self.__fullsize:#Wenn noch Frei, Part erstellen self.__addFreePart(self.__new_part_list, lastPartEnd) #for x in self.__new_part_list: # if x[LIST_TYPE]==LIST_TYPE_PAR: # print x except: print "[eParted] <remove part>" self.__Filllist() def KeyGreen(self): sel = self["list"].getCurrent() if sel and sel[5] and sel[5][PA_TYPE] & self.PA_TYPE_FREE and sel[5][PA_START] < sel[5][PA_END] and len(self.__new_part_list) < 6: self.session.openWithCallback(self.__CallbackAddPart, AddPart, sel[5][PA_END] - sel[5][PA_START], self.__unit, len(self.__new_part_list) - 1) def __CallbackAddPart(self, val=None): if val: for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: if x[PA_TYPE] & self.PA_TYPE_FREE: x[PA_SIZE] = val[0] x[PA_FS] = val[1] x[PA_END] = x[PA_START] + x[PA_SIZE] x[PA_TYPE] = self.PA_TYPE_USE | self.PA_TYPE_LAST if x[PA_END] < self.__fullsize:#Wenn noch Frei, Part erstellen self.__addFreePart(self.__new_part_list, x[PA_END]) break else: x[PA_TYPE] = self.PA_TYPE_USE self.__Filllist() def __addPart2Comlist(self, list, val, mkpart=True): #print val partnr = val[PA_NR] if mkpart: fs = val[PA_FS] com = "parted -s -a optimal %s mkpart primary %s %s%s %s%s" % (self.__devpath, fs, val[PA_START], self.__unit, val[PA_END], self.__unit) list.append((com , _("create partition %s") % partnr, None)) mountdev = None if val[PA_FS] == "linux-swap": mkfs = "/sbin/mkswap" elif val[PA_FS] == "fat16": mkfs = "/usr/sbin/mkfs.msdos -F 16" elif val[PA_FS] == "fat32": mkfs = "/sbin/mkfs.vfat" else: mkfs = "/sbin/mkfs." + val[PA_FS] mountdev = self.__devpath + partnr if val[PA_FS] == "xfs": mkfs += " -f" com = "%s %s%s" % (mkfs, self.__devpath, partnr) list.append((com , _("make filesystem '%s' on partition %s (%d %s)") % (val[PA_FS], partnr, val[PA_SIZE], self.__unit), mountdev)) def __delPart2Comlist(self, list, val): partnr = val[PA_NR] dev = "%s%s" % (self.__devpath, partnr) mp = ismounted(dev) if mp is not None: if myExecute("umount %s" % mp, self.session): return list.insert(0, ("parted -s -a none %s rm %s" % (self.__devpath, partnr), _("delete partition %s") % partnr, None)) def __createCommandList(self): self.__comlist = [] #welche parts sollen gelöscht werden for x in range(len(self.__old_part_list)): if self.__old_part_list[x][LIST_TYPE] == LIST_TYPE_PAR: if bool(self.__old_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if len(self.__new_part_list) > x: if self.__old_part_list[x][PA_SIZE] != self.__new_part_list[x][PA_SIZE]: #print self.__old_part_list[x], self.__new_part_list[x] self.__delPart2Comlist(self.__comlist, self.__old_part_list[x]) else: self.__delPart2Comlist(self.__comlist, self.__old_part_list[x]) #welche parts sollen erstellt werden for x in range(len(self.__new_part_list)): if self.__new_part_list[x][LIST_TYPE] == LIST_TYPE_PAR: if bool(self.__new_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if len(self.__old_part_list) > x and bool(self.__old_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if self.__new_part_list[x][PA_SIZE] != self.__old_part_list[x][PA_SIZE]: #print self.__new_part_list[x], self.__old_part_list[x] self.__addPart2Comlist(self.__comlist, self.__new_part_list[x]) else: if self.__new_part_list[x][PA_FS] != self.__old_part_list[x][PA_FS]: self.__addPart2Comlist(self.__comlist, self.__new_part_list[x], False) else: self.__addPart2Comlist(self.__comlist, self.__new_part_list[x]) #for x in self.__comlist: print "[eParted] com =",x if len(self.__comlist): self["PixmapBlue"].setPixmapNum(1) self["LabelBlue"].setText(_("execute")) else: self["PixmapBlue"].setPixmapNum(0) self["LabelBlue"].setText("")
class FlashImage(Screen): skin = """<screen position="center,center" size="640,150" flags="wfNoBorder" backgroundColor="#54242424"> <widget name="header" position="5,10" size="e-10,50" font="Regular;40" backgroundColor="#54242424"/> <widget name="info" position="5,60" size="e-10,130" font="Regular;24" backgroundColor="#54242424"/> <widget name="progress" position="5,e-39" size="e-10,24" backgroundColor="#54242424"/> </screen>""" BACKUP_SCRIPT = "/usr/lib/enigma2/python/Plugins/Extensions/AutoBackup/settings-backup.sh" def __init__(self, session, imagename, source): Screen.__init__(self, session) self.containerbackup = None self.containerofgwrite = None self.getImageList = None self.downloader = None self.source = source self.imagename = imagename self["header"] = Label(_("Backup settings")) self["info"] = Label(_("Save settings and EPG data")) self["progress"] = ProgressBar() self["progress"].setRange((0, 100)) self["progress"].setValue(0) self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "cancel": self.abort, "red": self.abort, "ok": self.ok, "green": self.ok, }, -1) self.delay = eTimer() self.delay.callback.append(self.confirmation) self.delay.start(0, True) self.hide() def confirmation(self): recordings = self.session.nav.getRecordings() if not recordings: next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime() if recordings or (next_rec_time > 0 and (next_rec_time - time.time()) < 360): self.message = _("Recording(s) are in progress or coming up in few seconds!\nDo you still want to flash image\n%s?") % self.imagename else: self.message = _("Do you want to flash image\n%s") % self.imagename if SystemInfo["canMultiBoot"]: self.getImageList = GetImagelist(self.getImagelistCallback) else: choices = [(_("Yes, with backup"), "with backup"), (_("Yes, without backup"), "without backup"), (_("No, do not flash image"), False)] self.session.openWithCallback(self.checkMedia, MessageBox, self.message , list=choices, default=False, simple=True) def getImagelistCallback(self, imagedict): self.getImageList = None choices = [] currentimageslot = GetCurrentImage() for x in range(1, SystemInfo["canMultiBoot"][1] + 1): choices.append(((_("slot%s - %s (current image) with, backup") if x == currentimageslot else _("slot%s - %s, with backup")) % (x, imagedict[x]['imagename']), (x, "with backup"))) for x in range(1, SystemInfo["canMultiBoot"][1] + 1): choices.append(((_("slot%s - %s (current image), without backup") if x == currentimageslot else _("slot%s - %s, without backup")) % (x, imagedict[x]['imagename']), (x, "without backup"))) choices.append((_("No, do not flash image"), False)) self.session.openWithCallback(self.checkMedia, MessageBox, self.message, list=choices, default=currentimageslot, simple=True) def checkMedia(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" def findmedia(path): def avail(path): if not '/mmc' in path and os.access(path, os.W_OK): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / (1 << 20) except: pass def checkIfDevice(path, diskstats): st_dev = os.stat(path).st_dev return (os.major(st_dev), os.minor(st_dev)) in diskstats diskstats = [(int(x[0]), int(x[1])) for x in [x.split()[0:3] for x in open('/proc/diskstats').readlines()] if x[2].startswith("sd")] if os.path.isdir(path) and checkIfDevice(path, diskstats) and avail(path) > 500: return (path, True) mounts = [] devices = [] for path in ['/media/%s' % x for x in os.listdir('/media')] + ['/media/net/%s' % x for x in os.listdir('/media/net')]: if checkIfDevice(path, diskstats): devices.append((path, avail(path))) else: mounts.append((path, avail(path))) devices.sort(key=lambda x: x[1], reverse=True) mounts.sort(key=lambda x: x[1], reverse=True) return ((devices[0][1] > 500 and (devices[0][0], True)) if devices else mounts and mounts[0][1] > 500 and (mounts[0][0], False)) or (None, None) self.destination, isDevice = findmedia(os.path.isfile(self.BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = os.path.join(self.destination, 'downloaded_images') self.zippedimage = "://" in self.source and os.path.join(destination, self.imagename) or self.source self.unzippedimage = os.path.join(destination, '%s.unzipped' % self.imagename[:-4]) if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if isDevice: self.startBackupsettings(True) else: self.session.openWithCallback(self.startBackupsettings, MessageBox, _("Can only find a network drive to store the backup this means after the flash the autorestore will not work. Alternativaly you can mount the network drive after the flash and perform a manufacurer reset to autorestore"), simple=True) else: self.startDownload() else: self.session.openWithCallback(self.abort, MessageBox, _("Could not find suitable media - Please remove some downloaded images or insert a media (e.g. USB stick) with sufficiant free space and try again!"), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort() def startBackupsettings(self, retval): if retval: if os.path.isfile(self.BACKUP_SCRIPT): self["info"].setText(_("Backing up to: %s") % self.destination) configfile.save() if config.plugins.autobackup.epgcache.value: eEPGCache.getInstance().save() self.containerbackup = Console() self.containerbackup.ePopen("%s%s'%s' %s" % (self.BACKUP_SCRIPT, config.plugins.autobackup.autoinstall.value and " -a " or " ", self.destination, int(config.plugins.autobackup.prevbackup.value)), self.backupsettingsDone) else: self.session.openWithCallback(self.startDownload, MessageBox, _("Unable to backup settings as the AutoBackup plugin is missing, do you want to continue?"), default=False, simple=True) else: self.abort() def backupsettingsDone(self, data, retval, extra_args): self.containerbackup = None if retval == 0: self.startDownload() else: self.session.openWithCallback(self.abort, MessageBox, _("Error during backup settings\n%s") % reval, type=MessageBox.TYPE_ERROR, simple=True) def startDownload(self, reply=True): self.show() if reply: if "://" in self.source: from Tools.Downloader import downloadWithProgress self["header"].setText(_("Downloading Image")) self["info"].setText(self.imagename) self.downloader = downloadWithProgress(self.source, self.zippedimage) self.downloader.addProgress(self.downloadProgress) self.downloader.addEnd(self.downloadEnd) self.downloader.addError(self.downloadError) self.downloader.start() else: self.unzip() else: self.abort() def downloadProgress(self, current, total): self["progress"].setValue(int(100 * current / total)) def downloadError(self, reason, status): self.downloader.stop() self.session.openWithCallback(self.abort, MessageBox, _("Error during downloading image\n%s\n%s") % (self.imagename, reason), type=MessageBox.TYPE_ERROR, simple=True) def downloadEnd(self): self.downloader.stop() self.unzip() def unzip(self): self["header"].setText(_("Unzipping Image")) self["info"].setText("%s\n%s"% (self.imagename, _("Please wait"))) self["progress"].hide() self.delay.callback.remove(self.confirmation) self.delay.callback.append(self.doUnzip) self.delay.start(0, True) def doUnzip(self): try: zipfile.ZipFile(self.zippedimage, 'r').extractall(self.unzippedimage) self.flashimage() except: self.session.openWithCallback(self.abort, MessageBox, _("Error during unzipping image\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def flashimage(self): self["header"].setText(_("Flashing Image")) def findimagefiles(path): for path, subdirs, files in os.walk(path): if not subdirs and files: return checkimagefiles(files) and path imagefiles = findimagefiles(self.unzippedimage) if imagefiles: if SystemInfo["canMultiBoot"]: command = "/usr/bin/ofgwrite -k -r -m%s '%s'" % (self.multibootslot, imagefiles) else: command = "/usr/bin/ofgwrite -k -r '%s'" % imagefiles self.containerofgwrite = Console() self.containerofgwrite.ePopen(command, self.FlashimageDone) else: self.session.openWithCallback(self.abort, MessageBox, _("Image to install is invalid\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def FlashimageDone(self, data, retval, extra_args): self.containerofgwrite = None if retval == 0: self["header"].setText(_("Flashing image succesfull")) self["info"].setText(_("%s\nPress ok for multiboot selection\nPress exit to close") % self.imagename) else: self.session.openWithCallback(self.abort, MessageBox, _("Flashing image was not succesfull\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def abort(self, reply=None): if self.getImageList or self.containerofgwrite: return 0 if self.downloader: self.downloader.stop() if self.containerbackup: self.containerbackup.killAll() self.close() def ok(self): if self["header"].text == _("Flashing image succesfull"): self.session.openWithCallback(self.abort, MultibootSelection) else: return 0
class MultiBootSelector(Screen, HelpableScreen): skinTemplate = """ <screen title="MultiBoot Image Selector" position="center,center" size="%d,%d"> <widget name="config" position="%d,%d" size="%d,%d" font="Regular;%d" itemHeight="%d" scrollbarMode="showOnDemand" /> <widget source="options" render="Label" position="%d,e-160" size="%d,%d" font="Regular;%d" halign="center" valign="center" /> <widget source="description" render="Label" position="%d,e-90" size="%d,%d" font="Regular;%d" /> <widget source="key_red" render="Label" position="%d,e-50" size="%d,%d" backgroundColor="key_red" font="Regular;%d" foregroundColor="key_text" halign="center" noWrap="1" valign="center" /> <widget source="key_green" render="Label" position="%d,e-50" size="%d,%d" backgroundColor="key_green" font="Regular;%d" foregroundColor="key_text" halign="center" noWrap="1" valign="center" /> </screen>""" scaleData = [ 800, 485, 10, 10, 780, 306, 24, 34, 10, 780, 60, 20, 10, 780, 30, 22, 10, 140, 40, 20, 160, 140, 40, 20 ] skin = None def __init__(self, session, *args): Screen.__init__(self, session) HelpableScreen.__init__(self) if MultiBootSelector.skin is None: # The skin template is designed for a HD screen so the scaling factor is 720. MultiBootSelector.skin = MultiBootSelector.skinTemplate % tuple([ x * getDesktop(0).size().height() / 720 for x in MultiBootSelector.scaleData ]) Screen.setTitle(self, _("MultiBoot Image Selector")) self["config"] = ChoiceList(list=[ ChoiceEntryComponent("", ( (_("Retrieving image slots - Please wait...")), "Queued")) ]) self["options"] = StaticText( _("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work." ) if SystemInfo["canMode12"] else "") self["description"] = StaticText( _("Use the cursor keys to select an installed image and then Reboot button." )) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Reboot")) self["actions"] = HelpableActionMap( self, [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "red": (boundFunction(self.close, None), _("Cancel the image selection and exit")), "green": (self.reboot, _("Select the highlighted image and reboot")), "ok": (self.reboot, _("Select the highlighted image and reboot")), "cancel": (boundFunction(self.close, None), _("Cancel the image selection and exit")), "up": (self.keyUp, _("Move up a line")), "down": (self.keyDown, _("Move down a line")), "left": (self.keyLeft, _("Move up a line")), "right": (self.keyRight, _("Move down a line")), "upRepeated": (self.keyUp, _("Move up a line")), "downRepeated": (self.keyDown, _("Move down a line")), "leftRepeated": (self.keyLeft, _("Move up a line")), "rightRepeated": (self.keyRight, _("Move down a line")), "menu": (boundFunction(self.close, True), _("Cancel the image selection and exit all menus")) }, -1, description=_("MultiBootSelector Actions")) imagedict = [] self.getImageList = None self.mountDir = "/tmp/startupmount" self.callLater(self.getBootOptions) def cancel(self, value=None): self.container = Console() self.container.ePopen("umount %s" % self.mountDir, boundFunction(self.unmountCallback, value)) def unmountCallback(self, value, data=None, retval=None, extra_args=None): self.container.killAll() if not path.ismount(self.mountDir): rmdir(self.mountDir) self.close(value) def getBootOptions(self, value=None): self.container = Console() if path.isdir(self.mountDir) and path.ismount(self.mountDir): self.getImagesList() else: if not path.isdir(self.mountDir): mkdir(self.mountDir) self.container.ePopen( "mount %s %s" % (SystemInfo["MBbootdevice"], self.mountDir), self.getImagesList) def getImagesList(self, data=None, retval=None, extra_args=None): self.container.killAll() self.getImageList = GetImagelist(self.getImagelistCallback) def getImagelistCallback(self, imagedict): list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() current = " %s" % _("(Current image)") slotSingle = _("Slot %s: %s%s") slotMulti = _("Slot %s: %s - Mode %d%s") if imagedict: indextot = 0 for index, x in enumerate(sorted(imagedict.keys())): if imagedict[x]["imagename"] != _("Empty slot"): if SystemInfo["canMode12"]: list.insert( index, ChoiceEntryComponent( "", (slotMulti % (x, imagedict[x]["imagename"], 1, current if x == currentimageslot and mode != 12 else ""), x))) list.append( ChoiceEntryComponent("", ( slotMulti % (x, imagedict[x]["imagename"], 12, current if x == currentimageslot and mode == 12 else ""), x + 12))) indextot = index + 1 else: list.append( ChoiceEntryComponent( "", (slotSingle % (x, imagedict[x]["imagename"], current if x == currentimageslot else ""), x))) if SystemInfo["canMode12"]: list.insert(indextot, " ") else: list.append( ChoiceEntryComponent("", ((_("No images found")), "Waiter"))) self["config"].setList(list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() self.slot = self.currentSelected[0][1] if self.currentSelected[0][1] != "Queued": print "[MultiBootSelector] reboot2 rebootslot = %s, " % self.slot print "[MultiBootSelector] reboot3 slotinfo = %s" % SystemInfo[ "canMultiBoot"] if self.slot < 12: copyfile( path.join( self.mountDir, SystemInfo["canMultiBoot"][self.slot]["startupfile"]), path.join(self.mountDir, "STARTUP")) else: self.slot -= 12 startupfile = path.join( self.mountDir, SystemInfo["canMultiBoot"][self.slot] ["startupfile"].replace("BOXMODE_1", "BOXMODE_12")) print "[MultiBootSelector] reboot5 startupfile = %s" % startupfile if "BOXMODE" in startupfile: copyfile(startupfile, path.join(self.mountDir, "STARTUP")) else: f = open(startupfile, "r").read().replace( "boxmode=1'", "boxmode=12'").replace( "%s" % SystemInfo["canMode12"][0], "%s" % SystemInfo["canMode12"][1]) open(path.join(self.mountDir, "STARTUP"), "w").write(f) self.session.open(TryQuitMainloop, QUIT_REBOOT) self.session.open(TryQuitMainloop, QUIT_REBOOT) def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
class MultiBoot(Screen): skin = """ <screen name="MultiBoot" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="labe14" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="labe15" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="200,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <eLabel position="20,200" size="6,40" backgroundColor="#00e61700" /> <!-- Should be a pixmap --> <eLabel position="190,200" size="6,40" backgroundColor="#0061e500" /> <!-- Should be a pixmap --> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "MultiBoot" screentitle = _("Multiboot Image Restart") self["key_red"] = StaticText(_("Cancel")) if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists('/dev/%s4' %(SystemInfo["canMultiBoot"][2])): self["labe14"] = StaticText(_("Use the cursor keys to select an installed image and then Reboot button.")) else: self["labe14"] = StaticText(_("SDcard is not initialised for multiboot - Exit and use ViX MultiBoot Manager to initialise")) self["labe15"] = StaticText(_(" ")) self["key_green"] = StaticText(_("Reboot")) if SystemInfo["canMode12"]: self["labe15"] = StaticText(_("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work.")) self["config"] = ChoiceList(list=[ChoiceEntryComponent('',((_("Retrieving image slots - Please wait...")), "Queued"))]) imagedict = [] self.mtdboot = "%s1" % SystemInfo["canMultiBoot"][2] if SystemInfo["canMultiBoot"][2] == "sda": self.mtdboot = "%s3" %getMachineMtdRoot()[0:8] self.getImageList = None self.title = screentitle if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists('/dev/%s4' %(SystemInfo["canMultiBoot"][2])): self.startit() self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions"], { "red": boundFunction(self.close, None), "green": self.reboot, "ok": self.reboot, "cancel": boundFunction(self.close, None), "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def startit(self): self.getImageList = GetImagelist(self.ImageList) def ImageList(self, imagedict): list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() if SystemInfo["HasSDmmc"]: currentimageslot += 1 #allow for mmc as 1st slot, then SDCard slots if not SystemInfo["canMode12"]: for x in sorted(imagedict.keys()): if imagedict[x]["imagename"] != _("Empty slot"): list.append(ChoiceEntryComponent('',((_("slot%s -%s - %s (current image)") if x == currentimageslot else _("slot%s -%s- %s ")) % (x, imagedict[x]['part'][0:3], imagedict[x]['imagename']), x))) else: for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if imagedict[x]["imagename"] != _("Empty slot"): list.append(ChoiceEntryComponent('',((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagedict[x]['imagename']), x))) list.append(" ") list.append(" ") for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if SystemInfo["canMode12"] and imagedict[x]["imagename"] != _("Empty slot"): list.append(ChoiceEntryComponent('',((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagedict[x]['imagename']), x + 12))) self["config"].setList(list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() if self.currentSelected[0][1] != "Queued": self.container = Console() if pathExists('/tmp/startupmount'): self.ContainterFallback() else: mkdir('/tmp/startupmount') self.container.ePopen('mount /dev/%s /tmp/startupmount' % self.mtdboot, self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot = self.currentSelected[0][1] print "[MultiBoot Restart] reboot3 slot:", slot if pathExists("/tmp/startupmount/STARTUP"): if slot < 12: copyfile("/tmp/startupmount/STARTUP_%s" % self.currentSelected[0][1], "/tmp/startupmount/STARTUP") else: slot -= 12 model = getMachineBuild() startupFileContents = "boot emmcflash0.kernel%s 'brcm_cma=%s root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=12'\n" % (slot, SystemInfo["canMode12"][1], slot * 2 + SystemInfo["canMultiBoot"][0], model) open('/tmp/startupmount/STARTUP', 'w').write(startupFileContents) self.session.open(TryQuitMainloop, 2) else: self.session.open(MessageBox, _("Multiboot ERROR! - no STARTUP in boot partition."), MessageBox.TYPE_INFO, timeout=20) def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
class FlashImage(Screen): skin = """<screen position="center,center" size="640,150" flags="wfNoBorder" backgroundColor="#54242424"> <widget name="header" position="5,10" size="e-10,50" font="Regular;40" backgroundColor="#54242424"/> <widget name="info" position="5,60" size="e-10,130" font="Regular;24" backgroundColor="#54242424"/> <widget name="progress" position="5,e-39" size="e-10,24" backgroundColor="#54242424"/> </screen>""" BACKUP_SCRIPT = resolveFilename(SCOPE_PLUGINS, "Extensions/AutoBackup/settings-backup.sh") def __init__(self, session, imagename, source): Screen.__init__(self, session) self.containerbackup = None self.containerofgwrite = None self.getImageList = None self.downloader = None self.source = source self.imagename = imagename self.reasons = getReasons(session) self["header"] = Label(_("Backup settings")) self["info"] = Label(_("Save settings and EPG data")) self["progress"] = ProgressBar() self["progress"].setRange((0, 100)) self["progress"].setValue(0) self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "cancel": self.abort, "red": self.abort, "ok": self.ok, "green": self.ok, }, -1) self.callLater(self.confirmation) def confirmation(self): if self.reasons: self.message = _("%s\nDo you still want to flash image\n%s?") % (self.reasons, self.imagename) else: self.message = _("Do you want to flash image\n%s") % self.imagename if SystemInfo["canMultiBoot"]: imagesList = getImagelist() currentimageslot = getCurrentImage() choices = [] slotdict = {k: v for k, v in SystemInfo["canMultiBoot"].items() if not v['device'].startswith('/dev/sda')} for x in range(1, len(slotdict) + 1): choices.append(((_("slot%s - %s (current image) with, backup") if x == currentimageslot else _("slot%s - %s, with backup")) % (x, imagesList[x]['imagename']), (x, "with backup"))) for x in range(1, len(slotdict) + 1): choices.append(((_("slot%s - %s (current image), without backup") if x == currentimageslot else _("slot%s - %s, without backup")) % (x, imagesList[x]['imagename']), (x, "without backup"))) choices.append((_("No, do not flash image"), False)) self.session.openWithCallback(self.checkMedia, MessageBox, self.message, list=choices, default=currentimageslot, simple=True) else: choices = [(_("Yes, with backup"), "with backup"), (_("Yes, without backup"), "without backup"), (_("No, do not flash image"), False)] self.session.openWithCallback(self.checkMedia, MessageBox, self.message, list=choices, default=False, simple=True) def checkMedia(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" def findmedia(path): def avail(path): if not path.startswith('/mmc') and os.path.isdir(path) and os.access(path, os.W_OK): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / (1 << 20) except: pass def checkIfDevice(path, diskstats): st_dev = os.stat(path).st_dev return (os.major(st_dev), os.minor(st_dev)) in diskstats diskstats = [(int(x[0]), int(x[1])) for x in [x.split()[0:3] for x in open('/proc/diskstats').readlines()] if x[2].startswith("sd")] if os.path.isdir(path) and checkIfDevice(path, diskstats) and avail(path) > 500: return (path, True) mounts = [] devices = [] for path in ['/media/%s' % x for x in os.listdir('/media')] + (['/media/net/%s' % x for x in os.listdir('/media/net')] if os.path.isdir('/media/net') else []): if checkIfDevice(path, diskstats): devices.append((path, avail(path))) else: mounts.append((path, avail(path))) devices.sort(key=lambda x: x[1], reverse=True) mounts.sort(key=lambda x: x[1], reverse=True) return ((devices[0][1] > 500 and (devices[0][0], True)) if devices else mounts and mounts[0][1] > 500 and (mounts[0][0], False)) or (None, None) self.destination, isDevice = findmedia(os.path.isfile(self.BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = os.path.join(self.destination, 'downloaded_images') self.zippedimage = "://" in self.source and os.path.join(destination, self.imagename) or self.source self.unzippedimage = os.path.join(destination, '%s.unzipped' % self.imagename[:-4]) try: if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if isDevice: self.startBackupsettings(True) else: self.session.openWithCallback(self.startBackupsettings, MessageBox, _("Can only find a network drive to store the backup this means after the flash the autorestore will not work. Alternativaly you can mount the network drive after the flash and perform a manufacurer reset to autorestore"), simple=True) else: self.startDownload() except: self.session.openWithCallback(self.abort, MessageBox, _("Unable to create the required directories on the media (e.g. USB stick or Harddisk) - Please verify media and try again!"), type=MessageBox.TYPE_ERROR, simple=True) else: self.session.openWithCallback(self.abort, MessageBox, _("Could not find suitable media - Please remove some downloaded images or insert a media (e.g. USB stick) with sufficiant free space and try again!"), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort() def startBackupsettings(self, retval): if retval: if os.path.isfile(self.BACKUP_SCRIPT): self["info"].setText(_("Backing up to: %s") % self.destination) configfile.save() if config.plugins.autobackup.epgcache.value: eEPGCache.getInstance().save() self.containerbackup = Console() self.containerbackup.ePopen("%s%s'%s' %s" % (self.BACKUP_SCRIPT, config.plugins.autobackup.autoinstall.value and " -a " or " ", self.destination, int(config.plugins.autobackup.prevbackup.value)), self.backupsettingsDone) else: self.session.openWithCallback(self.startDownload, MessageBox, _("Unable to backup settings as the AutoBackup plugin is missing, do you want to continue?"), default=False, simple=True) else: self.abort() def backupsettingsDone(self, data, retval, extra_args): self.containerbackup = None if retval == 0: self.startDownload() else: self.session.openWithCallback(self.abort, MessageBox, _("Error during backup settings\n%s") % retval, type=MessageBox.TYPE_ERROR, simple=True) def startDownload(self, reply=True): self.show() if reply: if "://" in self.source: from Tools.Downloader import downloadWithProgress self["header"].setText(_("Downloading Image")) self["info"].setText(self.imagename) self.downloader = downloadWithProgress(self.source, self.zippedimage) self.downloader.addProgress(self.downloadProgress) self.downloader.addEnd(self.downloadEnd) self.downloader.addError(self.downloadError) self.downloader.start() else: self.unzip() else: self.abort() def downloadProgress(self, current, total): self["progress"].setValue(int(100 * current / total)) def downloadError(self, reason, status): self.downloader.stop() self.session.openWithCallback(self.abort, MessageBox, _("Error during downloading image\n%s\n%s") % (self.imagename, reason), type=MessageBox.TYPE_ERROR, simple=True) def downloadEnd(self): self.downloader.stop() self.unzip() def unzip(self): self["header"].setText(_("Unzipping Image")) self["info"].setText("%s\n%s" % (self.imagename, _("Please wait"))) self["progress"].hide() self.callLater(self.doUnzip) def doUnzip(self): try: zipfile.ZipFile(self.zippedimage, 'r').extractall(self.unzippedimage) self.flashimage() except: self.session.openWithCallback(self.abort, MessageBox, _("Error during unzipping image\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def flashimage(self): self["header"].setText(_("Flashing Image")) def findimagefiles(path): for path, subdirs, files in os.walk(path): if not subdirs and files: return checkimagefiles(files) and path imagefiles = findimagefiles(self.unzippedimage) if imagefiles: if SystemInfo["canMultiBoot"]: command = "/usr/bin/ofgwrite -k -r -m%s '%s'" % (self.multibootslot, imagefiles) else: command = "/usr/bin/ofgwrite -k -r '%s'" % imagefiles self.containerofgwrite = Console() self.containerofgwrite.ePopen(command, self.FlashimageDone) else: self.session.openWithCallback(self.abort, MessageBox, _("Image to install is invalid\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def FlashimageDone(self, data, retval, extra_args): self.containerofgwrite = None if retval == 0: self["header"].setText(_("Flashing image successful")) self["info"].setText(_("%s\nPress ok for multiboot selection\nPress exit to close") % self.imagename) else: self.session.openWithCallback(self.abort, MessageBox, _("Flashing image was not successful\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def abort(self, reply=None): if self.getImageList or self.containerofgwrite: return 0 if self.downloader: self.downloader.stop() if self.containerbackup: self.containerbackup.killAll() self.close() def ok(self): if self["header"].text == _("Flashing image successful"): self.session.openWithCallback(self.abort, MultibootSelection) else: return 0
class Cpart(Screen): PA_TYPE_USE = 1 PA_TYPE_LAST = 2 PA_TYPE_FREE = 4 skin = """<screen position="center,center" size="670,200" title="eParted"> <widget source="list" render="Listbox" position="0,0" size="670,160" scrollbarMode="showOnDemand" enableWrapAround="on"> <convert type="TemplatedMultiContent"> {"template": [ MultiContentEntryText(pos = (0,5), size = (50, 30), font=0, flags = RT_HALIGN_LEFT, text=0), MultiContentEntryText(pos = (60,5), size = (150, 30), font=0, flags = RT_HALIGN_LEFT, text=1), MultiContentEntryText(pos = (210,5), size = (150, 30), font=0, flags = RT_HALIGN_LEFT, text=2), MultiContentEntryText(pos = (360,5), size = (150, 30), font=0, flags = RT_HALIGN_LEFT, text=3), MultiContentEntryText(pos = (510,5), size = (160, 30), font=0, flags = RT_HALIGN_LEFT, text=4) ], "fonts": [gFont("Regular", 20)], "itemHeight": 35 } </convert> </widget> <widget name="PixmapRed" position="25,170" size="15,16" pixmaps="skin_default/buttons/button_red_off.png,skin_default/buttons/button_red.png" transparent="1" alphatest="on" /> <widget name="LabelRed" position="50,160" size="150,40" font="Regular;19" valign="center" /> <widget name="PixmapGreen" position="225,170" size="15,16" pixmaps="skin_default/buttons/button_green_off.png,skin_default/buttons/button_green.png" transparent="1" alphatest="on" /> <widget name="LabelGreen" position="250,160" size="150,40" font="Regular;19" valign="center" /> <widget name="PixmapBlue" position="425,170" size="15,16" pixmaps="skin_default/buttons/button_blue_off.png,skin_default/buttons/button_blue.png" transparent="1" alphatest="on" /> <widget name="LabelBlue" position="450,160" size="150,40" font="Regular;19" valign="center" /> </screen>""" def __init__(self, session, entry): Screen.__init__(self, session) self["actions"] = ActionMap( ["OkCancelActions", "ColorActions"], { "cancel": self.Exit, "green": self.KeyGreen, "blue": self.KeyBlue, "red": self.KeyRed }, -1) self["list"] = List(list=[]) self["list"].onSelectionChanged.append(self.__SetLabels) self["PixmapRed"] = MultiPixmap() self["PixmapGreen"] = MultiPixmap() self["PixmapBlue"] = MultiPixmap() self["LabelRed"] = Label() self["LabelGreen"] = Label() self["LabelBlue"] = Label() self.__devpath = entry[DEV_PATH] self.__fullsize = 0 self.__old_part_list = [] self.__new_part_list = [] self.__comlist = [] self.__unit = entry[2][len(entry[2]) - 2:] self.Console = Console() self.__getPartInfo() def Exit(self): self.Console.killAll() self.close() def __getPartInfo(self, val=None): self.Console.ePopen( "parted -m %s unit %s print" % (self.__devpath, self.__unit), self.__FinishedConsole) def __Filllist(self): list = [] index = self["list"].getIndex() for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: #print x p0 = "%s: %s" % (_("Nr"), x[PA_NR]) p1 = "%s: %d%s" % (_("Start"), x[PA_START], self.__unit) p2 = "%s: %d%s" % (_("End"), x[PA_END], self.__unit) p3 = "%s: %d%s" % (_("Size"), x[PA_SIZE], self.__unit) p4 = "%s: %s" % (_("Type"), x[PA_FS]) list.append((p0, p1, p2, p3, p4, x)) self["list"].setList(list) self["list"].setIndex(index) self.__createCommandList() def __SetLabels(self): sel = self["list"].getCurrent() self["LabelGreen"].setText("") self["LabelRed"].setText("") if sel and sel[5]: if sel[5][PA_TYPE] & self.PA_TYPE_FREE and len( self.__new_part_list) < 6: self["PixmapGreen"].setPixmapNum(1) self["LabelGreen"].setText(_("add")) else: self["PixmapGreen"].setPixmapNum(0) if sel[5][PA_TYPE] & self.PA_TYPE_LAST and bool( sel[5][PA_TYPE] & self.PA_TYPE_FREE) == False: self["PixmapRed"].setPixmapNum(1) self["LabelRed"].setText(_("delete")) else: self["PixmapRed"].setPixmapNum(0) def __addFreePart(self, plist, lastPartEnd): x = [ LIST_TYPE_PAR, str(len(plist)), lastPartEnd, self.__fullsize, 0, _("free"), (self.PA_TYPE_FREE | self.PA_TYPE_LAST), ";" ] plist.append(x) def __FinishedConsole(self, result, retval, extra_args=None): if retval == 0 and '\n' in result: tlist = parseCmd(result) if len(tlist): self.__old_part_list = tlist[0][:] self.__new_part_list = tlist[0][:] lastPartEnd = 0 count = 2 for x in self.__old_part_list: if x[LIST_TYPE] == LIST_TYPE_DEV: self.__fullsize = getInt_epart(x[DEV_SIZE]) name = x[DEV_NAME] if len(name) == 0: name = x[DEV_PATH] name += " (%s)" % x[DEV_SIZE] self.setTitle(name) else: lastPartEnd = x[PA_END] x[PA_TYPE] = self.PA_TYPE_USE if count == len(self.__old_part_list): #is letzte part x[PA_TYPE] |= self.PA_TYPE_LAST count += 1 if lastPartEnd < self.__fullsize: #Wenn noch Frei, Part erstellen self.__addFreePart(self.__old_part_list, lastPartEnd) self.__addFreePart(self.__new_part_list, lastPartEnd) self.__Filllist() def KeyBlue(self): if len(self.__comlist): self.session.openWithCallback(self.__getPartInfo, Cpartexe, self.__comlist) def KeyRed(self): sel = self["list"].getCurrent() if sel and sel[1] and sel[5][PA_TYPE] & self.PA_TYPE_LAST and bool( sel[5][PA_TYPE] & self.PA_TYPE_FREE) == False: try: self.__new_part_list.remove(sel[5]) #aktuelle part löschen for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: if x[PA_TYPE] & self.PA_TYPE_FREE: #letzte Freie suchen und auch löschen self.__new_part_list.remove(x) break else: x[PA_TYPE] = self.PA_TYPE_USE lastPartEnd = 0 if len(self.__new_part_list ) > 1: #von letzter Part, TYp setzen und Ende ermitteln self.__new_part_list[ len(self.__new_part_list) - 1][PA_TYPE] = self.PA_TYPE_USE | self.PA_TYPE_LAST lastPartEnd = self.__new_part_list[ len(self.__new_part_list) - 1][PA_END] if lastPartEnd < self.__fullsize: #Wenn noch Frei, Part erstellen self.__addFreePart(self.__new_part_list, lastPartEnd) #for x in self.__new_part_list: # if x[LIST_TYPE]==LIST_TYPE_PAR: # print x except: print("[eParted] <remove part>") self.__Filllist() def KeyGreen(self): sel = self["list"].getCurrent() if sel and sel[5] and sel[5][PA_TYPE] & self.PA_TYPE_FREE and sel[5][ PA_START] < sel[5][PA_END] and len(self.__new_part_list) < 6: self.session.openWithCallback(self.__CallbackAddPart, AddPart, sel[5][PA_END] - sel[5][PA_START], self.__unit, len(self.__new_part_list) - 1) def __CallbackAddPart(self, val=None): if val: for x in self.__new_part_list: if x[LIST_TYPE] == LIST_TYPE_PAR: if x[PA_TYPE] & self.PA_TYPE_FREE: x[PA_SIZE] = val[0] x[PA_FS] = val[1] x[PA_END] = x[PA_START] + x[PA_SIZE] x[PA_TYPE] = self.PA_TYPE_USE | self.PA_TYPE_LAST if x[PA_END] < self.__fullsize: #Wenn noch Frei, Part erstellen self.__addFreePart(self.__new_part_list, x[PA_END]) break else: x[PA_TYPE] = self.PA_TYPE_USE self.__Filllist() def __addPart2Comlist(self, list, val, mkpart=True): #print val partnr = val[PA_NR] if mkpart: fs = val[PA_FS] com = "parted -s -a optimal %s mkpart primary %s %s%s %s%s" % ( self.__devpath, fs, val[PA_START], self.__unit, val[PA_END], self.__unit) list.append((com, _("create partition %s") % partnr, None)) mountdev = None if val[PA_FS] == "linux-swap": mkfs = "/sbin/mkswap" elif val[PA_FS] == "fat16": mkfs = "/usr/sbin/mkfs.msdos -F 16" elif val[PA_FS] == "fat32": mkfs = "/sbin/mkfs.vfat" else: mkfs = "/sbin/mkfs." + val[PA_FS] mountdev = self.__devpath + partnr if val[PA_FS] == "xfs": mkfs += " -f" com = "%s %s%s" % (mkfs, self.__devpath, partnr) list.append( (com, _("make filesystem '%s' on partition %s (%d %s)") % (val[PA_FS], partnr, val[PA_SIZE], self.__unit), mountdev)) def __delPart2Comlist(self, list, val): partnr = val[PA_NR] dev = "%s%s" % (self.__devpath, partnr) mp = ismounted(dev) if mp is not None: if myExecute("umount %s" % mp, self.session): return list.insert(0, ("parted -s -a none %s rm %s" % (self.__devpath, partnr), _("delete partition %s") % partnr, None)) def __createCommandList(self): self.__comlist = [] #welche parts sollen gelöscht werden for x in range(len(self.__old_part_list)): if self.__old_part_list[x][LIST_TYPE] == LIST_TYPE_PAR: if bool(self.__old_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if len(self.__new_part_list) > x: if self.__old_part_list[x][ PA_SIZE] != self.__new_part_list[x][PA_SIZE]: #print self.__old_part_list[x], self.__new_part_list[x] self.__delPart2Comlist(self.__comlist, self.__old_part_list[x]) else: self.__delPart2Comlist(self.__comlist, self.__old_part_list[x]) #welche parts sollen erstellt werden for x in range(len(self.__new_part_list)): if self.__new_part_list[x][LIST_TYPE] == LIST_TYPE_PAR: if bool(self.__new_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if len(self.__old_part_list) > x and bool( self.__old_part_list[x][PA_TYPE] & self.PA_TYPE_FREE) == False: if self.__new_part_list[x][ PA_SIZE] != self.__old_part_list[x][PA_SIZE]: #print self.__new_part_list[x], self.__old_part_list[x] self.__addPart2Comlist(self.__comlist, self.__new_part_list[x]) else: if self.__new_part_list[x][ PA_FS] != self.__old_part_list[x][PA_FS]: self.__addPart2Comlist(self.__comlist, self.__new_part_list[x], False) else: self.__addPart2Comlist(self.__comlist, self.__new_part_list[x]) #for x in self.__comlist: print "[eParted] com =",x if len(self.__comlist): self["PixmapBlue"].setPixmapNum(1) self["LabelBlue"].setText(_("execute")) else: self["PixmapBlue"].setPixmapNum(0) self["LabelBlue"].setText("")
class FlashImage(Screen): skin = """<screen position="center,center" size="640,150" flags="wfNoBorder" backgroundColor="#54242424"> <widget name="header" position="5,10" size="e-10,50" font="Regular;40" backgroundColor="#54242424"/> <widget name="info" position="5,60" size="e-10,130" font="Regular;24" backgroundColor="#54242424"/> <widget name="progress" position="5,e-39" size="e-10,24" backgroundColor="#54242424"/> </screen>""" def __init__(self, session, imagename, source): Screen.__init__(self, session) self.containerbackup = None self.containerofgwrite = None self.getImageList = None self.downloader = None self.source = source self.imagename = imagename self["header"] = Label(_("Backup settings")) self["info"] = Label(_("Save settings and EPG data")) self["progress"] = ProgressBar() self["progress"].setRange((0, 100)) self["progress"].setValue(0) self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "cancel": self.abort, "red": self.abort, }, -1) self.delay = eTimer() self.delay.callback.append(self.confirmation) self.delay.start(0, True) self.hide() def confirmation(self): recordings = self.session.nav.getRecordings() if not recordings: next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime() if recordings or (next_rec_time > 0 and (next_rec_time - time.time()) < 360): self.message = _("Recording(s) are in progress or coming up in few seconds!\nDo you still want to flash image\n%s?") % self.imagename else: self.message = _("Do you want to flash image\n%s") % self.imagename if SystemInfo["canMultiBoot"]: self.getImageList = GetImagelist(self.getImagelistCallback) else: choices = [(_("Yes, with backup"), "with backup"), (_("No, do not flash image"), False), (_("Yes, without backup"), "without backup")] self.session.openWithCallback(self.backupsettings, MessageBox, self.message , list=choices, default=False, simple=True) def getImagelistCallback(self, imagedict): self.getImageList = None choices = [] currentimageslot = GetCurrentImage() for x in range(1,5): if x in imagedict: choices.append(((_("slot%s - %s (current image) with, backup") if x == currentimageslot else _("slot%s - %s, with backup")) % (x, imagedict[x]['imagename']), (x, "with backup"))) else: choices.append((_("slot%s - empty, with backup") % x, (x, "with backup"))) choices.append((_("No, do not flash image"), False)) for x in range(1,5): if x in imagedict: choices.append(((_("slot%s - %s (current image), without backup") if x == currentimageslot else _("slot%s - %s, without backup")) % (x, imagedict[x]['imagename']), (x, "without backup"))) else: choices.append((_("slot%s - empty, without backup") % x, (x, "without backup"))) self.session.openWithCallback(self.backupsettings, MessageBox, self.message, list=choices, default=currentimageslot, simple=True) def backupsettings(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" BACKUP_SCRIPT = "/usr/lib/enigma2/python/Plugins/Extensions/AutoBackup/settings-backup.sh" def findmedia(destination): def avail(path): if not(SystemInfo["HasMMC"] and '/mmc' in path) and not os.path.islink(path): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / (1 << 20) >= 500 and path except: pass for path in [destination] + getNonNetworkMediaMounts(): if avail(path): return path self.destination = findmedia(os.path.isfile(BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = "/".join([self.destination, 'downloaded_images']) self.zippedimage = "://" in self.source and "/".join([destination, self.imagename]) or self.source self.unzippedimage = "/".join([destination, '%s.unzipped' % self.imagename[:-4]]) if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if os.path.isfile(BACKUP_SCRIPT): self["info"].setText(_("Backing up to: %s") % self.destination) configfile.save() if config.plugins.autobackup.epgcache.value: eEPGCache.getInstance().save() self.containerbackup = Console() self.containerbackup.ePopen("%s%s'%s' %s" % (BACKUP_SCRIPT, config.plugins.autobackup.autoinstall.value and " -a " or " ", self.destination, int(config.plugins.autobackup.prevbackup.value)), self.backupsettingsDone) else: self.session.openWithCallback(self.startDownload, MessageBox, _("Unable to backup settings as the AutoBackup plugin is missing, do you want to continue?"), default=False, simple=True) else: self.startDownload() else: self.session.openWithCallback(self.abort, MessageBox, _("Could not find suitable media - Please insert a media (e.g. USB stick) and try again!"), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort() def backupsettingsDone(self, data, retval, extra_args): self.containerbackup = None if retval == 0: self.startDownload() else: self.session.openWithCallback(self.abort, MessageBox, _("Error during backup settings\n%s") % reval, type=MessageBox.TYPE_ERROR, simple=True) def startDownload(self, reply=True): self.show() if reply: if "://" in self.source: from Tools.Downloader import downloadWithProgress self["header"].setText(_("Downloading Image")) self["info"].setText(self.imagename) self.downloader = downloadWithProgress(self.source, self.zippedimage) self.downloader.addProgress(self.downloadProgress) self.downloader.addEnd(self.downloadEnd) self.downloader.addError(self.downloadError) self.downloader.start() else: self.unzip() else: self.abort() def downloadProgress(self, current, total): self["progress"].setValue(int(100 * current / total)) def downloadError(self, reason, status): self.downloader.stop() self.session.openWithCallback(self.abort, MessageBox, _("Error during downloading image\n%s\n%s") % (self.imagename, reason), type=MessageBox.TYPE_ERROR, simple=True) def downloadEnd(self): self.downloader.stop() self.unzip() def unzip(self): try: zipfile.ZipFile(self.zippedimage, 'r').extractall(self.unzippedimage) self.flashimage() except: self.session.openWithCallback(self.abort, MessageBox, _("Error during unzipping image\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def flashimage(self): def findimagefiles(path): for path, subdirs, files in os.walk(path): if not subdirs and files: return checkimagefiles(files) and path imagefiles = findimagefiles(self.unzippedimage) if imagefiles: if SystemInfo["canMultiBoot"]: command = "/usr/bin/ofgwrite -k -r -m%s '%s'" % (self.multibootslot, imagefiles) else: command = "/usr/bin/ofgwrite -k -r '%s'" % imagefiles self.containerofgwrite = Console() self.containerofgwrite.ePopen(command, self.FlashimageDone) else: self.session.openWithCallback(self.abort, MessageBox, _("Image to install is invalid\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def FlashimageDone(self, data, retval, extra_args): self.containerofgwrite = None if retval == 0: self["header"].setText(_("Flashing image succesfull")) self["info"].setText(_("%s\nPress exit to close") % self.imagename) self["progress"].hide() else: self.session.openWithCallback(self.abort, MessageBox, _("Flashing image was not succesfull\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def abort(self, reply=None): if self.getImageList or self.containerofgwrite: return 0 if self.downloader: self.downloader.stop() if self.containerbackup: self.containerbackup.killAll() self.close()
class MultiBoot(Screen): skin = """ <screen name="MultiBoot" position="center,center" size="750,900" flags="wfNoBorder" backgroundColor="transparent"> <eLabel name="b" position="0,0" size="750,700" backgroundColor="#00ffffff" zPosition="-2" /> <eLabel name="a" position="1,1" size="748,698" backgroundColor="#00000000" zPosition="-1" /> <widget source="Title" render="Label" position="60,10" foregroundColor="#00ffffff" size="480,50" halign="left" font="Regular; 28" backgroundColor="#00000000" /> <eLabel name="line" position="1,60" size="748,1" backgroundColor="#00ffffff" zPosition="1" /> <eLabel name="line2" position="1,250" size="748,4" backgroundColor="#00ffffff" zPosition="1" /> <widget name="config" position="2,280" size="730,380" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00e5b243" /> <widget source="labe14" render="Label" position="2,80" size="730,30" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="labe15" render="Label" position="2,130" size="730,60" halign="center" font="Regular; 22" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_red" render="Label" position="30,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <widget source="key_green" render="Label" position="200,200" size="150,30" noWrap="1" zPosition="1" valign="center" font="Regular; 20" halign="left" backgroundColor="#00000000" foregroundColor="#00ffffff" /> <eLabel position="20,200" size="6,40" backgroundColor="#00e61700" /> <!-- Should be a pixmap --> <eLabel position="190,200" size="6,40" backgroundColor="#0061e500" /> <!-- Should be a pixmap --> </screen> """ def __init__(self, session, *args): Screen.__init__(self, session) self.skinName = "MultiBoot" screentitle = _("Multiboot Image Restart") self["key_red"] = StaticText(_("Cancel")) if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists( '/dev/%s4' % (SystemInfo["canMultiBoot"][2])): self["labe14"] = StaticText( _("Use the cursor keys to select an installed image and then Reboot button." )) else: self["labe14"] = StaticText( _("SDcard is not initialised for multiboot - Exit and use ViX MultiBoot Manager to initialise" )) self["labe15"] = StaticText(_(" ")) self["key_green"] = StaticText(_("Reboot")) if SystemInfo["canMode12"]: self["labe15"] = StaticText( _("Mode 1 suppports Kodi, PiP may not work.\nMode 12 supports PiP, Kodi may not work." )) self["config"] = ChoiceList(list=[ ChoiceEntryComponent('', ( (_("Retrieving image slots - Please wait...")), "Queued")) ]) imagedict = [] self.getImageList = None self.title = screentitle if not SystemInfo["HasSDmmc"] or SystemInfo["HasSDmmc"] and pathExists( '/dev/%s4' % (SystemInfo["canMultiBoot"][2])): self.startit() self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "red": boundFunction(self.close, None), "green": self.reboot, "ok": self.reboot, "cancel": boundFunction(self.close, None), "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "menu": boundFunction(self.close, True), }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.title) def startit(self): self.getImageList = GetImagelist(self.ImageList) def ImageList(self, imagedict): list = [] mode = GetCurrentImageMode() or 0 currentimageslot = GetCurrentImage() if SystemInfo["HasSDmmc"]: currentimageslot += 1 #allow for mmc as 1st slot, then SDCard slots if not SystemInfo["canMode12"]: for x in sorted(imagedict.keys()): if imagedict[x]["imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s -%s - %s (current image)") if x == currentimageslot else _("slot%s -%s- %s ")) % (x, imagedict[x]['part'][0:3], imagedict[x]['imagename']), x))) else: for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if imagedict[x]["imagename"] != _("Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 1 (current image)") if x == currentimageslot and mode != 12 else _("slot%s - %s mode 1")) % (x, imagedict[x]['imagename']), x))) list.append(" ") list.append(" ") for x in range(1, SystemInfo["canMultiBoot"][1] + 1): if SystemInfo["canMode12"] and imagedict[x]["imagename"] != _( "Empty slot"): list.append( ChoiceEntryComponent( '', ((_("slot%s - %s mode 12 (current image)") if x == currentimageslot and mode == 12 else _("slot%s - %s mode 12")) % (x, imagedict[x]['imagename']), x + 12))) self["config"].setList(list) def reboot(self): self.currentSelected = self["config"].l.getCurrentSelection() if self.currentSelected[0][1] != "Queued": self.container = Console() if pathExists('/tmp/startupmount'): self.ContainterFallback() else: mkdir('/tmp/startupmount') self.container.ePopen( 'mount /dev/%s1 /tmp/startupmount' % SystemInfo["canMultiBoot"][2], self.ContainterFallback) def ContainterFallback(self, data=None, retval=None, extra_args=None): self.container.killAll() slot = self.currentSelected[0][1] print "[MultiBoot Restart] reboot3 slot:", slot if pathExists("/tmp/startupmount/STARTUP"): if slot < 12: copyfile( "/tmp/startupmount/STARTUP_%s" % self.currentSelected[0][1], "/tmp/startupmount/STARTUP") else: slot -= 12 model = getMachineBuild() startupFileContents = "boot emmcflash0.kernel%s 'brcm_cma=%s root=/dev/mmcblk0p%s rw rootwait %s_4.boxmode=12'\n" % ( slot, SystemInfo["canMode12"][1], slot * 2 + SystemInfo["canMultiBoot"][0], model) open('/tmp/startupmount/STARTUP', 'w').write(startupFileContents) self.session.open(TryQuitMainloop, 2) else: self.session.open( MessageBox, _("Multiboot ERROR! - no STARTUP in boot partition."), MessageBox.TYPE_INFO, timeout=20) def selectionChanged(self): currentSelected = self["config"].l.getCurrentSelection() def keyLeft(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyRight(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged() def keyUp(self): self["config"].instance.moveSelection(self["config"].instance.moveUp) self.selectionChanged() def keyDown(self): self["config"].instance.moveSelection(self["config"].instance.moveDown) self.selectionChanged()
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: self.slots = sorted(SystemInfo["canMultiBoot"].keys()) self.callback = callback self.imagelist = {} if not path.isdir(Imagemount): mkdir(Imagemount) self.container = Console() self.phase = self.MOUNT self.run() else: callback({}) def run(self): if self.phase == self.UNMOUNT: self.container.ePopen("umount %s" % Imagemount, self.appClosed) else: self.slot = self.slots.pop(0) self.container.ePopen( "mount %s %s" % (SystemInfo["canMultiBoot"][self.slot]["device"], Imagemount), self.appClosed) def appClosed(self, data="", retval=0, extra_args=None): BuildVersion = " " Build = " " # ViX Openhdf Build No. Dev = " " # ViX Dev No. Creator = " " # Openpli Openvix Openatv Openhdf etc Date = " " BuildType = " " # release etc if retval: self.imagelist[self.slot] = {"imagename": _("Empty slot")} if retval == 0 and self.phase == self.MOUNT: if SystemInfo["HasRootSubdir"] and SystemInfo["canMultiBoot"][ self.slot]["rootsubdir"] != None: imagedir = ( '%s/%s' % (Imagemount, SystemInfo["canMultiBoot"][self.slot]["rootsubdir"])) else: imagedir = Imagemount if path.isfile("%s/usr/bin/enigma2" % imagedir): Creator = open("%s/etc/issue" % imagedir).readlines( )[-2].capitalize().strip()[:-6].replace("-release", " rel") if Creator.startswith("Openhdf"): reader = boxbranding_reader(imagedir) BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild( ) or '' BuildVersionHDF = "%s %s %s" % (Creator, BuildType[0:3], Build) BuildVersionHDF = BuildVersionHDF.replace("rel", "#") if Creator.startswith("Openvix"): reader = boxbranding_reader(imagedir) BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild( ) or "" BuildVersion = "%s %s %s %s" % (Creator, BuildType[0:3], Build, Dev) else: try: from datetime import datetime date = datetime.fromtimestamp( stat(path.join( imagedir, "var/lib/opkg/status")).st_mtime).strftime( "%Y-%m-%d") if date.startswith("1970"): date = datetime.fromtimestamp( stat( path.join(imagedir, "usr/share/bootlogo.mvi")). st_mtime).strftime("%Y-%m-%d") date = max( date, datetime.fromtimestamp( stat(path.join( imagedir, "usr/bin/enigma2")).st_mtime).strftime( "%Y-%m-%d")) except Exception: date = _("Unknown") BuildVersion = "%s (%s)" % (open( path.join(imagedir, "etc/issue")).readlines( )[-2].capitalize().strip()[:-6], date) if Creator.startswith("Openhdf"): BuildVersion = _("%s release %s") % (BuildVersionHDF, date) self.imagelist[self.slot] = {"imagename": "%s" % BuildVersion} else: self.imagelist[self.slot] = {"imagename": _("Empty slot")} if self.slots and SystemInfo["canMultiBoot"][ self.slot]["device"] == SystemInfo["canMultiBoot"][ self.slots[0]]["device"]: self.slot = self.slots.pop(0) self.appClosed() else: self.phase = self.UNMOUNT self.run() elif self.slots: self.phase = self.MOUNT self.run() else: self.container.killAll() if not path.ismount(Imagemount): rmdir(Imagemount) self.callback(self.imagelist)
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots) = SystemInfo["canMultiBoot"][:2] self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.phase = self.MOUNT self.run() else: callback({}) def run(self): if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.islink( "/dev/block/by-name/linuxrootfs"): self.container.ePopen( 'mount /dev/block/by-name/linuxrootfs /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.container.ePopen( 'mount /dev/block/by-name/userdata /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.container.ePopen( 'mount /dev/%sp%s /tmp/testmount' % (SystemInfo["canMultiBoot"][2], str(self.slot * 2 + self.firstslot)) if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: def getImagename(target): from datetime import datetime date = datetime.fromtimestamp( os.stat(os.path.join( target, "var/lib/opkg/status")).st_mtime).strftime('%Y-%m-%d') if date.startswith("1970"): try: date = datetime.fromtimestamp( os.stat( os.path.join(target, "usr/share/bootlogo.mvi") ).st_mtime).strftime('%Y-%m-%d') except: pass date = max( date, datetime.fromtimestamp( os.stat(os.path.join( target, "usr/bin/enigma2")).st_mtime).strftime( '%Y-%m-%d')) return "%s (%s)" % (open(os.path.join( target, "etc/issue")).readlines()[-2].capitalize().strip()[:-6], date) if SystemInfo["HasRootSubdir"]: if os.path.isfile( "/tmp/testmount/linuxrootfs%s/usr/bin/enigma2" % self.slot): self.imagelist[self.slot] = { 'imagename': getImagename("/tmp/testmount/linuxrootfs%s" % self.slot) } else: self.imagelist[self.slot] = {'imagename': _("Empty slot")} else: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): self.imagelist[self.slot] = { 'imagename': getImagename("/tmp/testmount") } else: self.imagelist[self.slot] = {'imagename': _("Empty slot")} self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.imagelist[self.slot] = {'imagename': _("Empty slot")} self.phase = self.MOUNT self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class Status: def __init__(self): self.wlaniface = {} self.backupwlaniface = {} self.statusCallback = None self.WlanConsole = Console() def stopWlanConsole(self): if self.WlanConsole is not None: print "[iStatus] killing self.WlanConsole" self.WlanConsole.killAll() self.WlanConsole = None def getDataForInterface(self, iface, callback=None): self.WlanConsole = Console() cmd = "iwconfig " + iface if callback is not None: self.statusCallback = callback self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface) def iwconfigFinished(self, result, retval, extra_args): iface = extra_args data = { 'essid': False, 'frequency': False, 'accesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False } for line in result.splitlines(): line = line.strip() # print "[Wlan.py] line -->",line if "ESSID" in line: if "off/any" in line: ssid = "off" else: if "Nickname" in line: ssid = (line[line.index('ESSID') + 7:line.index('" Nickname')]) else: ssid = (line[line.index('ESSID') + 7:len(line) - 1]) if ssid is not None: data['essid'] = ssid if "Frequency" in line: frequency = line[line.index('Frequency') + 10:line.index(' GHz')] if frequency is not None: data['frequency'] = frequency if "Access Point" in line: if "Sensitivity" in line: ap = line[line.index('Access Point') + 14:line.index(' Sensitivity')] else: ap = line[line.index('Access Point') + 14:len(line)] if ap is not None: data['accesspoint'] = ap if "Bit Rate" in line: if "kb" in line: br = line[line.index('Bit Rate') + 9:line.index(' kb/s')] elif "Gb" in line: br = line[line.index('Bit Rate') + 9:line.index(' Gb/s')] else: br = line[line.index('Bit Rate') + 9:line.index(' Mb/s')] if br is not None: data['bitrate'] = br if "Encryption key" in line: if ":off" in line: enc = "off" elif "Security" in line: enc = line[line.index('Encryption key') + 15:line.index(' Security')] if enc is not None: enc = "on" else: enc = line[line.index('Encryption key') + 15:len(line)] if enc is not None: enc = "on" if enc is not None: data['encryption'] = enc if 'Quality' in line: if "/100" in line: qual = line[line.index('Quality') + 8:line.index(' Signal')] else: qual = line[line.index('Quality') + 8:line.index('Sig')] if qual is not None: data['quality'] = qual if 'Signal level' in line: if "dBm" in line: signal = line[line.index('Signal level') + 13:line.index(' dBm')] + " dBm" elif "/100" in line: if "Noise" in line: signal = line[line.index('Signal level') + 13:line.index(' Noise')] else: signal = line[line.index('Signal level') + 13:len(line)] else: if "Noise" in line: signal = line[line.index('Signal level') + 13:line.index(' Noise')] else: signal = line[line.index('Signal level') + 13:len(line)] if signal is not None: data['signal'] = signal self.wlaniface[iface] = data self.backupwlaniface = self.wlaniface if self.WlanConsole is not None: if not self.WlanConsole.appContainers: print "[Wlan.py] self.wlaniface after loading:", self.wlaniface if self.statusCallback is not None: self.statusCallback(True, self.wlaniface) self.statusCallback = None def getAdapterAttribute(self, iface, attribute): self.iface = iface if self.wlaniface.has_key(self.iface): if self.wlaniface[self.iface].has_key(attribute): return self.wlaniface[self.iface][attribute] return None
class GetImagelist(): MOUNT = 0 UNMOUNT = 1 NoRun = 0 # receivers only uses 1 media for multiboot FirstRun = 1 # receiver uses eMMC and SD card for multiboot - so handle SDcard slots 1st via SystemInfo(canMultiBoot) LastRun = 2 # receiver uses eMMC and SD card for multiboot - and then handle eMMC (currently one time) def __init__(self, callback): if SystemInfo["canMultiBoot"]: (self.firstslot, self.numberofslots) = SystemInfo["canMultiBoot"][:2] self.callback = callback self.imagelist = {} if not os.path.isdir('/tmp/testmount'): os.mkdir('/tmp/testmount') self.container = Console() self.slot = 1 self.slot2 = 1 if SystemInfo["HasSDmmc"]: self.SDmmc = self.FirstRun # process SDcard slots else: self.SDmmc = self.NoRun # only mmc slots self.phase = self.MOUNT self.part = SystemInfo["canMultiBoot"][2] # pick up slot type self.run() else: callback({}) def run(self): if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.islink( "/dev/block/by-name/linuxrootfs"): self.part2 = os.readlink("/dev/block/by-name/linuxrootfs")[5:] self.container.ePopen( 'mount /dev/block/by-name/linuxrootfs /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) else: self.part2 = os.readlink("/dev/block/by-name/userdata")[5:] self.container.ePopen( 'mount /dev/block/by-name/userdata /tmp/testmount' if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' % self.part2 } else: if self.SDmmc == self.LastRun: self.part2 = getMachineMtdRoot() # process mmc slot self.slot2 = 1 else: self.part2 = "%s" % (self.part + str(self.slot * 2 + self.firstslot)) if self.SDmmc == self.FirstRun: self.slot2 += 1 # allow for mmc slot" if self.phase == self.MOUNT: self.imagelist[self.slot2] = { 'imagename': _("Empty slot"), 'part': '%s' % self.part2 } self.container.ePopen( 'mount /dev/%s /tmp/testmount' % self.part2 if self.phase == self.MOUNT else 'umount /tmp/testmount', self.appClosed) def appClosed(self, data, retval, extra_args): if retval == 0 and self.phase == self.MOUNT: BuildVersion = " " Build = " " #ViX Build No.# Dev = " " #ViX Dev No.# Creator = " " #Openpli Openvix Openatv etc # Date = " " BuildType = " " #release etc # self.OsPath = "NoPath" if SystemInfo["HasRootSubdir"]: if self.slot == 1 and os.path.isfile( "/tmp/testmount/linuxrootfs1/usr/bin/enigma2"): self.OsPath = "/tmp/testmount/linuxrootfs1" elif os.path.isfile( "/tmp/testmount/linuxrootfs%s/usr/bin/enigma2" % self.slot): self.OsPath = "/tmp/testmount/linuxrootfs%s" % self.slot print "multiboot tools 1 slots", self.slot, self.slot2 else: if os.path.isfile("/tmp/testmount/usr/bin/enigma2"): self.OsPath = '/tmp/testmount' print "Tools/Multiboot OsPath %s " % self.OsPath if self.OsPath != "NoPath": Creator = open("%s/etc/issue" % self.OsPath).readlines( )[-2].capitalize().strip()[:-6].replace("-release", " rel") if Creator.startswith("Openvix"): reader = boxbranding_reader(self.OsPath) BuildType = reader.getImageType() Build = reader.getImageBuild() Dev = BuildType != "release" and " %s" % reader.getImageDevBuild( ) or '' BuildVersion = "%s %s %s %s" % (Creator, BuildType[0:3], Build, Dev) else: from datetime import datetime Date = datetime.fromtimestamp( os.stat("%s/var/lib/opkg/status" % self.OsPath).st_mtime).strftime("%d-%m-%Y") if Date.endswith("1970"): try: Date = datetime.fromtimestamp( os.stat( "%s/usr/share/bootlogo.mvi" % self.OsPath).st_mtime).strftime("%d-%m-%Y") except: pass Date = max( Date, datetime.fromtimestamp( os.stat("%s/usr/bin/enigma2" % self.OsPath).st_mtime).strftime( "%d-%m-%Y")) BuildVersion = "%s build date %s" % (Creator, Date) self.imagelist[self.slot2] = { 'imagename': '%s' % BuildVersion, 'part': '%s' % self.part2 } self.phase = self.UNMOUNT self.run() elif self.slot < self.numberofslots: self.slot += 1 self.slot2 = self.slot self.phase = self.MOUNT self.run() elif self.SDmmc == self.FirstRun: self.phase = self.MOUNT self.SDmmc = self.LastRun self.run() else: self.container.killAll() if not os.path.ismount('/tmp/testmount'): os.rmdir('/tmp/testmount') self.callback(self.imagelist)
class FlashImage(Screen): skin = """<screen position="center,center" size="640,150" flags="wfNoBorder" backgroundColor="#54242424"> <widget name="header" position="5,10" size="e-10,50" font="Regular;40" backgroundColor="#54242424"/> <widget name="info" position="5,60" size="e-10,130" font="Regular;24" backgroundColor="#54242424"/> <widget name="progress" position="5,e-39" size="e-10,24" backgroundColor="#54242424"/> </screen>""" def __init__(self, session, imagename, source): Screen.__init__(self, session) self.containerbackup = None self.containerofgwrite = None self.getImageList = None self.downloader = None self.source = source self.imagename = imagename self["header"] = Label(_("Backup settings")) self["info"] = Label(_("Save settings and EPG data")) self["progress"] = ProgressBar() self["progress"].setRange((0, 100)) self["progress"].setValue(0) self["actions"] = ActionMap( ["OkCancelActions", "ColorActions"], { "cancel": self.abort, "red": self.abort, "ok": self.ok, "green": self.ok, }, -1) self.delay = eTimer() self.delay.callback.append(self.confirmation) self.delay.start(0, True) self.hide() def confirmation(self): recordings = self.session.nav.getRecordings() if not recordings: next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime() if recordings or (next_rec_time > 0 and (next_rec_time - time.time()) < 360): self.message = _( "Recording(s) are in progress or coming up in few seconds!\nDo you still want to flash image\n%s?" ) % self.imagename else: self.message = _("Do you want to flash image\n%s") % self.imagename if SystemInfo["canMultiBoot"]: self.getImageList = GetImagelist(self.getImagelistCallback) else: choices = [(_("Yes, with backup"), "with backup"), (_("No, do not flash image"), False), (_("Yes, without backup"), "without backup")] self.session.openWithCallback(self.backupsettings, MessageBox, self.message, list=choices, default=False, simple=True) def getImagelistCallback(self, imagedict): self.getImageList = None choices = [] currentimageslot = GetCurrentImage() for x in range(1, SystemInfo["canMultiBoot"][1] + 1): choices.append( ((_("slot%s - %s (current image) with, backup") if x == currentimageslot else _("slot%s - %s, with backup")) % (x, imagedict[x]['imagename']), (x, "with backup"))) choices.append((_("No, do not flash image"), False)) for x in range(1, SystemInfo["canMultiBoot"][1] + 1): choices.append( ((_("slot%s - %s (current image), without backup") if x == currentimageslot else _("slot%s - %s, without backup")) % (x, imagedict[x]['imagename']), (x, "without backup"))) self.session.openWithCallback(self.backupsettings, MessageBox, self.message, list=choices, default=currentimageslot, simple=True) def backupsettings(self, retval): if retval: if SystemInfo["canMultiBoot"]: self.multibootslot = retval[0] doBackup = retval[1] == "with backup" else: doBackup = retval == "with backup" BACKUP_SCRIPT = "/usr/lib/enigma2/python/Plugins/Extensions/AutoBackup/settings-backup.sh" def findmedia(destination): def avail(path): if not (SystemInfo["HasMMC"] and '/mmc' in path) and not os.path.islink(path): try: statvfs = os.statvfs(path) return (statvfs.f_bavail * statvfs.f_frsize) / ( 1 << 20) >= 500 and path except: pass for path in [destination] + getNonNetworkMediaMounts(): if avail(path): return path self.destination = findmedia( os.path.isfile(BACKUP_SCRIPT) and config.plugins.autobackup.where.value or "/media/hdd") if self.destination: destination = os.path.join(self.destination, 'downloaded_images') self.zippedimage = "://" in self.source and os.path.join( destination, self.imagename) or self.source self.unzippedimage = os.path.join( destination, '%s.unzipped' % self.imagename[:-4]) if os.path.isfile(destination): os.remove(destination) if not os.path.isdir(destination): os.mkdir(destination) if doBackup: if os.path.isfile(BACKUP_SCRIPT): self["info"].setText( _("Backing up to: %s") % self.destination) configfile.save() if config.plugins.autobackup.epgcache.value: eEPGCache.getInstance().save() self.containerbackup = Console() self.containerbackup.ePopen( "%s%s'%s' %s" % (BACKUP_SCRIPT, config.plugins.autobackup.autoinstall.value and " -a " or " ", self.destination, int(config.plugins.autobackup.prevbackup.value)), self.backupsettingsDone) else: self.session.openWithCallback( self.startDownload, MessageBox, _("Unable to backup settings as the AutoBackup plugin is missing, do you want to continue?" ), default=False, simple=True) else: self.startDownload() else: self.session.openWithCallback( self.abort, MessageBox, _("Could not find suitable media - Please remove some downloaded images or insert a media (e.g. USB stick) with sufficiant free space and try again!" ), type=MessageBox.TYPE_ERROR, simple=True) else: self.abort() def backupsettingsDone(self, data, retval, extra_args): self.containerbackup = None if retval == 0: self.startDownload() else: self.session.openWithCallback( self.abort, MessageBox, _("Error during backup settings\n%s") % reval, type=MessageBox.TYPE_ERROR, simple=True) def startDownload(self, reply=True): self.show() if reply: if "://" in self.source: from Tools.Downloader import downloadWithProgress self["header"].setText(_("Downloading Image")) self["info"].setText(self.imagename) self.downloader = downloadWithProgress(self.source, self.zippedimage) self.downloader.addProgress(self.downloadProgress) self.downloader.addEnd(self.downloadEnd) self.downloader.addError(self.downloadError) self.downloader.start() else: self.unzip() else: self.abort() def downloadProgress(self, current, total): self["progress"].setValue(int(100 * current / total)) def downloadError(self, reason, status): self.downloader.stop() self.session.openWithCallback( self.abort, MessageBox, _("Error during downloading image\n%s\n%s") % (self.imagename, reason), type=MessageBox.TYPE_ERROR, simple=True) def downloadEnd(self): self.downloader.stop() self.unzip() def unzip(self): self["header"].setText(_("Unzipping Image")) self["info"].setText("%s\n%s" % (self.imagename, _("Please wait"))) self["progress"].hide() self.delay.callback.remove(self.confirmation) self.delay.callback.append(self.doUnzip) self.delay.start(0, True) def doUnzip(self): try: zipfile.ZipFile(self.zippedimage, 'r').extractall(self.unzippedimage) self.flashimage() except: self.session.openWithCallback( self.abort, MessageBox, _("Error during unzipping image\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def flashimage(self): self["header"].setText(_("Flashing Image")) def findimagefiles(path): for path, subdirs, files in os.walk(path): if not subdirs and files: return checkimagefiles(files) and path imagefiles = findimagefiles(self.unzippedimage) if imagefiles: if SystemInfo["canMultiBoot"]: command = "/usr/bin/ofgwrite -k -r -m%s '%s'" % ( self.multibootslot, imagefiles) else: command = "/usr/bin/ofgwrite -k -r '%s'" % imagefiles self.containerofgwrite = Console() self.containerofgwrite.ePopen(command, self.FlashimageDone) else: self.session.openWithCallback( self.abort, MessageBox, _("Image to install is invalid\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def FlashimageDone(self, data, retval, extra_args): self.containerofgwrite = None if retval == 0: self["header"].setText(_("Flashing image succesfull")) self["info"].setText( _("%s\nPress ok for multiboot selection\nPress exit to close") % self.imagename) else: self.session.openWithCallback( self.abort, MessageBox, _("Flashing image was not succesfull\n%s") % self.imagename, type=MessageBox.TYPE_ERROR, simple=True) def abort(self, reply=None): if self.getImageList or self.containerofgwrite: return 0 if self.downloader: self.downloader.stop() if self.containerbackup: self.containerbackup.killAll() self.close() def ok(self): if self["header"].text == _("Flashing image succesfull"): self.session.openWithCallback(self.abort, MultibootSelection) else: return 0
class Network: def __init__(self): self.ifaces = {} self.onlyWoWifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "ethtool" self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.PingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: from Components.Harddisk import getProcMounts for parts in getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'tap0', 'sys0', 'p2p0', 'tunl0') def getInterfaces(self, callback=None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [int(n) for n in ip.split('.')] def getAddrInet(self, iface, callback): data = {'up': False, 'dhcp': False, 'preup': False, 'predown': False} try: data['up'] = int( open('/sys/class/net/%s/flags' % iface).read().strip(), 16) & 1 == 1 if data['up']: self.configuredInterfaces.append(iface) nit = ni.ifaddresses(iface) data['ip'] = self.convertIP(nit[ni.AF_INET][0]['addr']) # ipv4 data['netmask'] = self.convertIP(nit[ni.AF_INET][0]['netmask']) data['bcast'] = self.convertIP(nit[ni.AF_INET][0]['broadcast']) data['mac'] = nit[ni.AF_LINK][0]['addr'] # mac data['gateway'] = self.convertIP( ni.gateways()['default'][ni.AF_INET][0]) # default gw except: data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] self.ifaces[iface] = data self.loadNetworkConfig(iface, callback) def routeFinished(self, result, retval, extra_args): (iface, data, callback) = extra_args ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = compile(ipRegexp) ipLinePattern = compile(ipRegexp) for line in result.splitlines(): print(line[0:7]) if line[0:7] == "0.0.0.0": gateway = self.regExpMatch(ipPattern, line[16:31]) if gateway: data['gateway'] = self.convertIP(gateway) self.ifaces[iface] = data self.loadNetworkConfig(iface, callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = open('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") print("[%s] writeNetworkConfig onlyWoWifaces = %s" % (DEFAULT_MODULE_NAME, str(self.onlyWoWifaces))) for ifacename, iface in list(self.ifaces.items()): print("[%s] writeNetworkConfig %s = %s" % (DEFAULT_MODULE_NAME, ifacename, str(iface))) if 'dns-nameservers' in iface and iface['dns-nameservers']: dns = [] for s in iface['dns-nameservers'].split()[1:]: dns.append((self.convertIP(s))) if dns: self.nameservers = dns WoW = False if ifacename in self.onlyWoWifaces: WoW = self.onlyWoWifaces[ifacename] if WoW == False and iface['up'] == True: fp.write("auto %s\n" % ifacename) self.configuredInterfaces.append(ifacename) self.onlyWoWifaces[ifacename] = False elif WoW == True: self.onlyWoWifaces[ifacename] = True fp.write("#only WakeOnWiFi %s\n" % ifacename) if iface['dhcp']: fp.write("iface %s inet dhcp\n" % ifacename) if not iface['dhcp']: fp.write("iface %s inet static\n" % ifacename) fp.write(" hostname $(hostname)\n") if 'ip' in iface: # print tuple(iface['ip']) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if 'gateway' in iface: fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if "configStrings" in iface: fp.write(iface["configStrings"]) if iface["preup"] is not False and "configStrings" not in iface: fp.write(iface["preup"]) if iface["predown"] is not False and "configStrings" not in iface: fp.write(iface["predown"]) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): try: Console().ePopen('rm -f /etc/resolv.conf') fp = open('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() if config.usage.dns.value.lower() not in ("dhcp-router"): Console().ePopen('rm -f /etc/enigma2/nameserversdns.conf') fp = open('/etc/enigma2/nameserversdns.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() #self.restartNetwork() except: print( "[Network] resolv.conf or nameserversdns.conf - writing failed" ) def loadNetworkConfig(self, iface, callback=None): interfaces = [] # parse the interfaces-file try: fp = open('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print("[Network.py] interfaces - opening failed") ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if split[0] == "iface" and split[2] != "inet6": currif = split[1] ifaces[currif] = {} if len(split) == 4 and split[3] == "dhcp": ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if currif == iface: #read information only for available interfaces if split[0] == "address": ifaces[currif]["address"] = list( map(int, split[1].split('.'))) if "ip" in self.ifaces[currif]: if self.ifaces[currif]["ip"] != ifaces[currif][ "address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = list( map(int, split[1].split('.'))) if split[0] == "netmask": ifaces[currif]["netmask"] = map(int, split[1].split('.')) if "netmask" in self.ifaces[currif]: if self.ifaces[currif]["netmask"] != ifaces[currif][ "netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = list( map(int, split[1].split('.'))) if split[0] == "gateway": ifaces[currif]["gateway"] = map(int, split[1].split('.')) if "gateway" in self.ifaces[currif]: if self.ifaces[currif]["gateway"] != ifaces[currif][ "gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = list( map(int, split[1].split('.'))) if split[0] == "pre-up": if "preup" in self.ifaces[currif]: self.ifaces[currif]["preup"] = i if split[0] in ("pre-down", "post-down"): if "predown" in self.ifaces[currif]: self.ifaces[currif]["predown"] = i for ifacename, iface in list(ifaces.items()): if ifacename in self.ifaces: self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if self.Console: if len(self.Console.appContainers) == 0: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() if config.usage.dns.value.lower() not in ("dhcp-router"): self.writeNameserverConfig() # print "read configured interface:", ifaces # print "self.ifaces after loading:", self.ifaces self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = compile("nameserver +" + ipRegexp) ipPattern = compile(ipRegexp) resolv = [] try: if config.usage.dns.value.lower() in ("dhcp-router"): fp = open('/etc/resolv.conf', 'r') else: fp = open('/etc/enigma2/nameserversdns.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print( "[Network] resolv.conf or nameserversdns.conf - opening failed" ) for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) # print "nameservers:", self.nameservers def getInstalledAdapters(self): return [ x for x in listdir('/sys/class/net') if not self.isBlacklisted(x) ] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in list(self.friendlyNames.keys()): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get( x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _("WLAN connection") if len(self.wlan_interfaces): name += " " + str(len(self.wlan_interfaces) + 1) self.wlan_interfaces.append(iface) else: if iface not in self.lan_interfaces: if getBoxType() == "et10000" and iface == "eth1": name = _("VLAN connection") else: name = _("LAN connection") if len( self.lan_interfaces ) and not getBoxType() == "et10000" and not iface == "eth1": name += " " + str(len(self.lan_interfaces) + 1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = basename(realpath(moduledir)) if name in ('ath_pci', 'ath5k', 'ar6k_wlan'): name = 'Atheros' elif name in ('rt73', 'rt73usb', 'rt3070sta'): name = 'Ralink' elif name == 'zd1211b': name = 'Zydas' elif name == 'r871x_usb_drv': name = 'Realtek' elif name == 'brcm-systemport': name = 'Broadcom' elif name == 'wlan': name = name.upper() else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return list(self.ifaces.keys()) def getAdapterAttribute(self, iface, attribute): if iface in self.ifaces: if attribute in self.ifaces[iface]: return self.ifaces[iface][attribute] return None def setAdapterAttribute(self, iface, attribute, value): # print "setting for adapter", iface, "attribute", attribute, " to value", value if iface in self.ifaces: self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if iface in self.ifaces: if attribute in self.ifaces[iface]: del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in list(range(len(self.nameservers))): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback=None): self.resetNetworkConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in list(self.ifaces.keys()): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ip addr flush dev %s scope global" % iface) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self, mode='lan', callback=None): fp = open('/etc/network/interfaces', 'w') fp.write( "# automatically generated by enigma2\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.resetNetworkConsole = Console() self.commands = [] if mode == 'wlan': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig ath0 down") self.commands.append("ifconfig wlan0 up") if mode == 'wlan-mpci': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 up") if mode == 'lan': self.commands.append("ifconfig eth0 up") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 down") self.commands.append("/etc/init.d/avahi-daemon start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode, callback], debug=True) def resetNetworkFinished(self, extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: if callback is not None: callback(True, mode) def checkNetworkState(self, statecallback): self.NetworkState = 0 cmd1 = "ping -c 1 www.openpli.org" cmd2 = "ping -c 1 www.google.nl" cmd3 = "ping -c 1 www.google.com" self.PingConsole = Console() self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished, statecallback) self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished, statecallback) self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished, statecallback) def checkNetworkStateFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.PingConsole is not None: if retval == 0: self.PingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if len(self.PingConsole.appContainers) == 0: statecallback(self.NetworkState) def restartNetwork(self, callback=None): self.restartConsole = Console() self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in list(self.ifaces.keys()): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ifdown %s" % iface) self.commands.append("ip addr flush dev %s scope global" % iface) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self, extra_args): (callback) = extra_args if callback is not None: try: callback(True) except: pass def getLinkState(self, iface, callback): cmd = "%s %s" % (self.ethtool_bin, iface) self.LinkConsole = Console() self.LinkConsole.ePopen(cmd, self.getLinkStateFinished, callback) def getLinkStateFinished(self, result, retval, extra_args): (callback) = extra_args if PY3 and isinstance(result, bytes): result = result.decode() if self.LinkConsole is not None: if len(self.LinkConsole.appContainers) == 0: callback(result) def stopPingConsole(self): if self.PingConsole is not None: if len(self.PingConsole.appContainers): for name in list(self.PingConsole.appContainers.keys()): self.PingConsole.kill(name) def stopLinkStateConsole(self): if self.LinkConsole is not None: if len(self.LinkConsole.appContainers): for name in list(self.LinkConsole.appContainers.keys()): self.LinkConsole.kill(name) def stopDNSConsole(self): if self.DnsConsole is not None: if len(self.DnsConsole.appContainers): for name in list(self.DnsConsole.appContainers.keys()): self.DnsConsole.kill(name) def stopRestartConsole(self): if self.restartConsole is not None: if len(self.restartConsole.appContainers): for name in list(self.restartConsole.appContainers.keys()): self.restartConsole.kill(name) def stopGetInterfacesConsole(self): if self.Console is not None: if len(self.Console.appContainers): for name in list(self.Console.appContainers.keys()): self.Console.kill(name) def stopDeactivateInterfaceConsole(self): if self.deactivateInterfaceConsole is not None: self.deactivateInterfaceConsole.killAll() self.deactivateInterfaceConsole = None def stopActivateInterfaceConsole(self): if self.activateInterfaceConsole is not None: self.activateInterfaceConsole.killAll() self.activateInterfaceConsole = None def checkforInterface(self, iface): if self.getAdapterAttribute(iface, 'up') is True: return True else: ret = os_system("ifconfig %s up" % iface) os_system("ifconfig %s down" % iface) if ret == 0: return True else: return False def checkDNSLookup(self, statecallback): cmd1 = "nslookup www.cloudflare.com" cmd2 = "nslookup www.google.com" cmd3 = "nslookup www.microsoft.com" self.DnsConsole = Console() self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished, statecallback) self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished, statecallback) self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished, statecallback) def checkDNSLookupFinished(self, result, retval, extra_args): (statecallback) = extra_args if self.DnsConsole is not None: if retval == 0: self.DnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if len(self.DnsConsole.appContainers) == 0: statecallback(self.DnsState) def deactivateInterface(self, ifaces, callback=None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append("ifdown %s" % iface) commands.append("ip addr flush dev %s scope global" % iface) #wpa_supplicant sometimes doesn't quit properly on SIGTERM if path_exists('/var/run/wpa_supplicant/%s' % iface): commands.append("wpa_cli -i%s terminate" % iface) if not self.deactivateInterfaceConsole: self.deactivateInterfaceConsole = Console() if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch( commands, self.deactivateInterfaceFinished, [ifaces, callback], debug=True) def deactivateInterfaceFinished(self, extra_args): (ifaces, callback) = extra_args def checkCommandResult(iface): if self.deactivateInterfaceConsole and "ifdown %s" % iface in self.deactivateInterfaceConsole.appResults: result = str( self.deactivateInterfaceConsole.appResults.get( "ifdown %s" % iface)).strip("\n") if result == "ifdown: interface %s not configured" % iface: return False else: return True #ifdown sometimes can't get the interface down. if isinstance(ifaces, (list, tuple)): for iface in ifaces: if checkCommandResult(iface) is False: Console().ePopen(("ifconfig %s down" % iface)) else: if checkCommandResult(ifaces) is False: Console().ePopen(("ifconfig %s down" % ifaces)) if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def activateInterface(self, iface, callback=None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return if not self.activateInterfaceConsole: self.activateInterfaceConsole = Console() commands = ["ifup %s" % iface] self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self, extra_args): callback = extra_args if self.activateInterfaceConsole: if len(self.activateInterfaceConsole.appContainers) == 0: if callback is not None: try: callback(True) except: pass def sysfsPath(self, iface): return '/sys/class/net/%s' % iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True if isdir("%s/wireless" % self.sysfsPath(iface)): return True # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless device = compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass fp.close() if iface in ifnames: return True return False def canWakeOnWiFi(self, iface): if self.sysfsPath(iface) == "/sys/class/net/wlan3" and path_exists( "/tmp/bcm/%s" % iface): return True def getWlanModuleDir(self, iface=None): if self.sysfsPath(iface) == "/sys/class/net/wlan3" and path_exists( "/tmp/bcm/%s" % iface): devicedir = "%s/device" % self.sysfsPath("sys0") else: devicedir = "%s/device" % self.sysfsPath(iface) moduledir = "%s/driver/module" % devicedir if isdir(moduledir): return moduledir # identification is not possible over default moduledir try: for x in listdir(devicedir): # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx if x.startswith("1-"): moduledir = "%s/%s/driver/module" % (devicedir, x) if isdir(moduledir): return moduledir # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here moduledir = "%s/driver" % devicedir if isdir(moduledir): return moduledir except: pass return None def detectWlanModule(self, iface=None): if not self.isWirelessInterface(iface): return None devicedir = "%s/device" % self.sysfsPath(iface) if isdir("%s/ieee80211" % devicedir): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = basename(realpath(moduledir)) if module in ('brcm-systemport', ): return 'brcm-wl' if module in ('ath_pci', 'ath5k'): return 'madwifi' if module in ('rt73', 'rt73'): return 'ralink' if module == 'zd1211b': return 'zydas' return 'wext' def calc_netmask(self, nmask): mask = 1 << 31 xnet = (1 << 32) - 1 cidr_range = range(0, 32) cidr = int(nmask) if cidr not in list(cidr_range): print('cidr invalid: %d' % cidr) return None else: nm = ((1 << cidr) - 1) << (32 - cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins( PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == "add": print("[Network] Add new interface: %s" % interface) self.getAddrInet(interface, None) elif action == "remove": print("[Network] Removed interface: %s" % interface) try: del self.ifaces[interface] except KeyError: pass def getInterfacesNameserverList(self, iface): result = [] nameservers = self.getAdapterAttribute(iface, "dns-nameservers") if nameservers: ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = compile(ipRegexp) for x in nameservers.split()[1:]: ip = self.regExpMatch(ipPattern, x) if ip: result.append([int(n) for n in ip.split('.')]) if len( self.nameservers ) and not result: # use also global nameserver if we got no one from interface result.extend(self.nameservers) return result
class Network: def __init__(self): self.ifaces = {} self.configuredInterfaces = [] self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "ethtool" self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.PingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: import Harddisk for parts in Harddisk.getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0') def getInterfaces(self, callback = None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [ int(n) for n in ip.split('.') ] def getAddrInet(self, iface, callback): if not self.Console: self.Console = Console() cmd = "ip -o addr show dev " + iface self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback]) def IPaddrFinished(self, result, retval, extra_args): (iface, callback ) = extra_args data = { 'up': False, 'dhcp': False, 'preup' : False, 'predown' : False } globalIPpattern = re.compile("scope global") ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' netRegexp = '[0-9]{1,2}' macRegexp = '[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}' ipLinePattern = re.compile('inet ' + ipRegexp + '/') ipPattern = re.compile(ipRegexp) netmaskLinePattern = re.compile('/' + netRegexp) netmaskPattern = re.compile(netRegexp) bcastLinePattern = re.compile(' brd ' + ipRegexp) upPattern = re.compile('UP') macPattern = re.compile(macRegexp) macLinePattern = re.compile('link/ether ' + macRegexp) for line in result.splitlines(): split = line.strip().split(' ',2) if (split[1][:-1] == iface): up = self.regExpMatch(upPattern, split[2]) mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2])) if up is not None: data['up'] = True if iface is not 'lo': self.configuredInterfaces.append(iface) if mac is not None: data['mac'] = mac if (split[1] == iface): if re.search(globalIPpattern, split[2]): ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2])) netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2]))) bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2])) if ip is not None: data['ip'] = self.convertIP(ip) if netmask is not None: data['netmask'] = self.convertIP(netmask) if bcast is not None: data['bcast'] = self.convertIP(bcast) if not data.has_key('ip'): data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] cmd = "route -n | grep " + iface self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback]) def routeFinished(self, result, retval, extra_args): (iface, data, callback) = extra_args ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = re.compile(ipRegexp) ipLinePattern = re.compile(ipRegexp) for line in result.splitlines(): print line[0:7] if line[0:7] == "0.0.0.0": gateway = self.regExpMatch(ipPattern, line[16:31]) if gateway: data['gateway'] = self.convertIP(gateway) self.ifaces[iface] = data self.loadNetworkConfig(iface,callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") for ifacename, iface in self.ifaces.items(): if iface['up'] == True: fp.write("auto " + ifacename + "\n") self.configuredInterfaces.append(ifacename) if iface['dhcp'] == True: fp.write("iface "+ ifacename +" inet dhcp\n") if iface['dhcp'] == False: fp.write("iface "+ ifacename +" inet static\n") if iface.has_key('ip'): print tuple(iface['ip']) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if iface.has_key('gateway'): fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if iface.has_key("configStrings"): fp.write(iface["configStrings"]) if iface["preup"] is not False and not iface.has_key("configStrings"): fp.write(iface["preup"]) if iface["predown"] is not False and not iface.has_key("configStrings"): fp.write(iface["predown"]) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): fp = file('/etc/resolv.conf', 'w') fp.write("options rotate timeout:3\n") for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() def loadNetworkConfig(self,iface,callback = None): interfaces = [] # parse the interfaces-file try: fp = file('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print "[Network.py] interfaces - opening failed" ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if (split[0] == "iface"): currif = split[1] ifaces[currif] = {} if (len(split) == 4 and split[3] == "dhcp"): ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if (currif == iface): #read information only for available interfaces if (split[0] == "address"): ifaces[currif]["address"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("ip"): if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = map(int, split[1].split('.')) if (split[0] == "netmask"): ifaces[currif]["netmask"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("netmask"): if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = map(int, split[1].split('.')) if (split[0] == "gateway"): ifaces[currif]["gateway"] = map(int, split[1].split('.')) if self.ifaces[currif].has_key("gateway"): if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = map(int, split[1].split('.')) if (split[0] == "pre-up"): if self.ifaces[currif].has_key("preup"): self.ifaces[currif]["preup"] = i if (split[0] in ("pre-down","post-down")): if self.ifaces[currif].has_key("predown"): self.ifaces[currif]["predown"] = i for ifacename, iface in ifaces.items(): if self.ifaces.has_key(ifacename): self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if self.Console: if len(self.Console.appContainers) == 0: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() print "read configured interface:", ifaces print "self.ifaces after loading:", self.ifaces self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = re.compile("nameserver +" + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = file('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print "[Network.py] resolv.conf - opening failed" for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) print "nameservers:", self.nameservers def getInstalledAdapters(self): return [x for x in os.listdir('/sys/class/net') if not self.isBlacklisted(x)] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if self.isWirelessInterface(iface): if iface not in self.wlan_interfaces: name = _("WLAN connection") if len(self.wlan_interfaces): name += " " + str(len(self.wlan_interfaces)+1) self.wlan_interfaces.append(iface) else: if iface not in self.lan_interfaces: name = _("LAN connection") if len(self.lan_interfaces): name += " " + str(len(self.lan_interfaces)+1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): if not self.isWirelessInterface(iface): return _('Ethernet network interface') moduledir = self.getWlanModuleDir(iface) if moduledir: name = os.path.basename(os.path.realpath(moduledir)) if name in ('ath_pci','ath5k'): name = 'Atheros' elif name in ('rt73','rt73usb','rt3070sta'): name = 'Ralink' elif name == 'zd1211b': name = 'Zydas' elif name == 'r871x_usb_drv': name = 'Realtek' else: name = _('Unknown') return name + ' ' + _('wireless network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return self.ifaces.keys() def getAdapterAttribute(self, iface, attribute): return self.ifaces.get(iface, {}).get(attribute) def setAdapterAttribute(self, iface, attribute, value): print "setting for adapter", iface, "attribute", attribute, " to value", value if self.ifaces.has_key(iface): self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if self.ifaces.has_key(iface): if self.ifaces[iface].has_key(attribute): del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback = None): self.resetNetworkConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self,mode='lan', callback = None): fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.resetNetworkConsole = Console() self.commands = [] if mode == 'wlan': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig ath0 down") self.commands.append("ifconfig wlan0 up") if mode == 'wlan-mpci': self.commands.append("ifconfig eth0 down") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 up") if mode == 'lan': self.commands.append("ifconfig eth0 up") self.commands.append("ifconfig wlan0 down") self.commands.append("ifconfig ath0 down") self.commands.append("/etc/init.d/avahi-daemon start") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True) def resetNetworkFinished(self,extra_args): (mode, callback) = extra_args if len(self.resetNetworkConsole.appContainers) == 0: if callback is not None: callback(True,mode) def checkNetworkState(self,statecallback): self.NetworkState = 0 cmd1 = "ping -c 1 www.openpli.org" cmd2 = "ping -c 1 www.google.nl" cmd3 = "ping -c 1 www.google.com" self.PingConsole = Console() self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback) self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback) self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback) def checkNetworkStateFinished(self, result, retval,extra_args): (statecallback) = extra_args if self.PingConsole is not None: if retval == 0: self.PingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if len(self.PingConsole.appContainers) == 0: statecallback(self.NetworkState) def restartNetwork(self,callback = None): self.restartConsole = Console() self.config_ready = False self.msgPlugins() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self,extra_args): ( callback ) = extra_args if callback is not None: callback(True) def getLinkState(self,iface,callback): cmd = self.ethtool_bin + " " + iface self.LinkConsole = Console() self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback) def getLinkStateFinished(self, result, retval,extra_args): (callback) = extra_args if self.LinkConsole is not None: if len(self.LinkConsole.appContainers) == 0: callback(result) def stopPingConsole(self): if self.PingConsole is not None: if len(self.PingConsole.appContainers): for name in self.PingConsole.appContainers.keys(): self.PingConsole.kill(name) def stopLinkStateConsole(self): if self.LinkConsole is not None: if len(self.LinkConsole.appContainers): for name in self.LinkConsole.appContainers.keys(): self.LinkConsole.kill(name) def stopDNSConsole(self): if self.DnsConsole is not None: if len(self.DnsConsole.appContainers): for name in self.DnsConsole.appContainers.keys(): self.DnsConsole.kill(name) def stopRestartConsole(self): if self.restartConsole is not None: if len(self.restartConsole.appContainers): for name in self.restartConsole.appContainers.keys(): self.restartConsole.kill(name) def stopGetInterfacesConsole(self): if self.Console is not None: if len(self.Console.appContainers): for name in self.Console.appContainers.keys(): self.Console.kill(name) def stopDeactivateInterfaceConsole(self): if self.deactivateInterfaceConsole is not None: self.deactivateInterfaceConsole.killAll() self.deactivateInterfaceConsole = None def stopActivateInterfaceConsole(self): if self.activateInterfaceConsole is not None: self.activateInterfaceConsole.killAll() self.activateInterfaceConsole = None def checkforInterface(self, iface): return self.getAdapterAttribute(iface, 'up') def checkDNSLookup(self,statecallback): cmd1 = "nslookup www.dream-multimedia-tv.de" cmd2 = "nslookup www.heise.de" cmd3 = "nslookup www.google.de" self.DnsConsole = Console() self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback) self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback) self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback) def checkDNSLookupFinished(self, result, retval,extra_args): (statecallback) = extra_args if self.DnsConsole is not None: if retval == 0: self.DnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if len(self.DnsConsole.appContainers) == 0: statecallback(self.DnsState) def deactivateInterface(self,ifaces,callback = None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append("ifdown " + iface) commands.append("ip addr flush dev " + iface + " scope global") #wpa_supplicant sometimes doesn't quit properly on SIGTERM if os.path.exists('/var/run/wpa_supplicant/'+ iface): commands.append("wpa_cli -i" + iface + " terminate") if not self.deactivateInterfaceConsole: self.deactivateInterfaceConsole = Console() if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces,callback], debug=True) def deactivateInterfaceFinished(self,extra_args): (ifaces, callback) = extra_args def checkCommandResult(iface): if self.deactivateInterfaceConsole and self.deactivateInterfaceConsole.appResults.has_key("ifdown " + iface): result = str(self.deactivateInterfaceConsole.appResults.get("ifdown " + iface)).strip("\n") if result == "ifdown: interface " + iface + " not configured": return False else: return True #ifdown sometimes can't get the interface down. if isinstance(ifaces, (list, tuple)): for iface in ifaces: if checkCommandResult(iface) is False: Console().ePopen(("ifconfig " + iface + " down" )) else: if checkCommandResult(ifaces) is False: Console().ePopen(("ifconfig " + ifaces + " down" )) if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def activateInterface(self,iface,callback = None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return if not self.activateInterfaceConsole: self.activateInterfaceConsole = Console() commands = [] commands.append("ifup " + iface) self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self,extra_args): callback = extra_args if self.activateInterfaceConsole: if len(self.activateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def sysfsPath(self, iface): return '/sys/class/net/' + iface def isWirelessInterface(self, iface): if iface in self.wlan_interfaces: return True if os.path.isdir(self.sysfsPath(iface) + '/wireless'): return True # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless device = re.compile('[a-z]{2,}[0-9]*:') ifnames = [] fp = open('/proc/net/wireless', 'r') for line in fp: try: ifnames.append(device.search(line).group()[:-1]) except AttributeError: pass if iface in ifnames: return True return False def getWlanModuleDir(self, iface = None): devicedir = self.sysfsPath(iface) + '/device' if not os.path.isdir(devicedir): return None moduledir = devicedir + '/driver/module' if os.path.isdir(moduledir): return moduledir # identification is not possible over default moduledir for x in os.listdir(devicedir): # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx if x.startswith("1-"): moduledir = devicedir + '/' + x + '/driver/module' if os.path.isdir(moduledir): return moduledir # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here moduledir = devicedir + '/driver' if os.path.isdir(moduledir): return moduledir return None def detectWlanModule(self, iface = None): if not self.isWirelessInterface(iface): return None devicedir = self.sysfsPath(iface) + '/device' if os.path.isdir(devicedir + '/ieee80211'): return 'nl80211' moduledir = self.getWlanModuleDir(iface) if moduledir: module = os.path.basename(os.path.realpath(moduledir)) if module in ('ath_pci','ath5k'): return 'madwifi' if module in ('rt73','rt73'): return 'ralink' if module == 'zd1211b': return 'zydas' return 'wext' def calc_netmask(self,nmask): from struct import pack, unpack from socket import inet_ntoa, inet_aton mask = 1L<<31 xnet = (1L<<32)-1 cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print 'cidr invalid: %d' % cidr return None else: nm = ((1L<<cidr)-1)<<(32-cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready)
class Network: def __init__(self): self.ifaces = {} self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "/usr/sbin/ethtool" self.console = Console() self.linkConsole = Console() self.restartConsole = Console() self.deactivateInterfaceConsole = Console() self.activateInterfaceConsole = Console() self.resetNetworkConsole = Console() self.dnsConsole = Console() self.pingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.remoteRootFS = None self.getInterfaces() def onRemoteRootFS(self): if self.remoteRootFS is None: import Harddisk for parts in Harddisk.getProcMounts(): if parts[1] == '/' and parts[2] == 'nfs': self.remoteRootFS = True break else: self.remoteRootFS = False return self.remoteRootFS def isBlacklisted(self, iface): return iface in ('lo', 'wifi0', 'wmaster0', 'sit0', 'tun0', 'sys0') def getInterfaces(self, callback = None): self.configuredInterfaces = [] for device in self.getInstalledAdapters(): self.getAddrInet(device, callback) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: return None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): return [ int(n) for n in ip.split('.') ] def getAddrInet(self, iface, callback): cmd = ("/sbin/ip", "/sbin/ip", "-o", "addr", "show", "dev", iface) self.console.ePopen(cmd, self.IPaddrFinished, [iface, callback]) def IPaddrFinished(self, result, retval, extra_args): (iface, callback ) = extra_args data = { 'up': False, 'dhcp': False, 'preup' : False, 'predown' : False } globalIPpattern = re.compile("scope global") ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' netRegexp = '[0-9]{1,2}' macRegexp = '[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}' ipLinePattern = re.compile('inet ' + ipRegexp + '/') ipPattern = re.compile(ipRegexp) netmaskLinePattern = re.compile('/' + netRegexp) netmaskPattern = re.compile(netRegexp) bcastLinePattern = re.compile(' brd ' + ipRegexp) upPattern = re.compile('UP') macPattern = re.compile(macRegexp) macLinePattern = re.compile('link/ether ' + macRegexp) for line in result.splitlines(): split = line.strip().split(' ',2) if (split[1][:-1] == iface) or (split[1][:-1] == (iface + '@sys0')): up = self.regExpMatch(upPattern, split[2]) mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2])) if up is not None: data['up'] = True if iface is not 'lo': self.configuredInterfaces.append(iface) if mac is not None: data['mac'] = mac if split[1] == iface: if re.search(globalIPpattern, split[2]): ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2])) netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2]))) bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2])) if ip is not None: data['ip'] = self.convertIP(ip) if netmask is not None: data['netmask'] = self.convertIP(netmask) if bcast is not None: data['bcast'] = self.convertIP(bcast) if 'ip' not in data: data['dhcp'] = True data['ip'] = [0, 0, 0, 0] data['netmask'] = [0, 0, 0, 0] data['gateway'] = [0, 0, 0, 0] cmd = "route -n | grep " + iface self.console.ePopen(cmd,self.routeFinished, [iface, data, callback]) def routeFinished(self, result, retval, extra_args): (iface, data, callback) = extra_args ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ipPattern = re.compile(ipRegexp) ipLinePattern = re.compile(ipRegexp) for line in result.splitlines(): print line[0:7] if line[0:7] == "0.0.0.0": gateway = self.regExpMatch(ipPattern, line[16:31]) if gateway: data['gateway'] = self.convertIP(gateway) self.ifaces[iface] = data self.loadNetworkConfig(iface,callback) def writeNetworkConfig(self): self.configuredInterfaces = [] fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") for ifacename, iface in self.ifaces.items(): if iface['up']: fp.write("auto " + ifacename + "\n") self.configuredInterfaces.append(ifacename) if iface['dhcp']: fp.write("iface "+ ifacename +" inet dhcp\n") if not iface['dhcp']: fp.write("iface "+ ifacename +" inet static\n") if 'ip' in iface: print tuple(iface['ip']) fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if 'gateway' in iface: fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if "configStrings" in iface: fp.write(iface["configStrings"]) if iface["preup"] is not False and "configStrings" not in iface: fp.write(iface["preup"]) if iface["predown"] is not False and "configStrings" not in iface: fp.write(iface["predown"]) fp.write("\n") fp.close() self.configuredNetworkAdapters = self.configuredInterfaces self.writeNameserverConfig() def writeNameserverConfig(self): fp = file('/etc/resolv.conf', 'w') for nameserver in self.nameservers: fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver)) fp.close() def loadNetworkConfig(self,iface,callback = None): interfaces = [] # parse the interfaces-file try: fp = file('/etc/network/interfaces', 'r') interfaces = fp.readlines() fp.close() except: print "[Network.py] interfaces - opening failed" ifaces = {} currif = "" for i in interfaces: split = i.strip().split(' ') if split[0] == "iface": currif = split[1] ifaces[currif] = {} if len(split) == 4 and split[3] == "dhcp": ifaces[currif]["dhcp"] = True else: ifaces[currif]["dhcp"] = False if currif == iface: #read information only for available interfaces if split[0] == "address": ifaces[currif]["address"] = map(int, split[1].split('.')) if "ip" in self.ifaces[currif]: if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["ip"] = map(int, split[1].split('.')) if split[0] == "netmask": ifaces[currif]["netmask"] = map(int, split[1].split('.')) if "netmask" in self.ifaces[currif]: if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["netmask"] = map(int, split[1].split('.')) if split[0] == "gateway": ifaces[currif]["gateway"] = map(int, split[1].split('.')) if "gateway" in self.ifaces[currif]: if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False: self.ifaces[currif]["gateway"] = map(int, split[1].split('.')) if split[0] == "pre-up": if "preup" in self.ifaces[currif]: self.ifaces[currif]["preup"] = i if split[0] in ("pre-down","post-down"): if "predown" in self.ifaces[currif]: self.ifaces[currif]["predown"] = i for ifacename, iface in ifaces.items(): if ifacename in self.ifaces: self.ifaces[ifacename]["dhcp"] = iface["dhcp"] if not self.console.appContainers: # save configured interfacelist self.configuredNetworkAdapters = self.configuredInterfaces # load ns only once self.loadNameserverConfig() print "read configured interface:", ifaces print "self.ifaces after loading:", self.ifaces self.config_ready = True self.msgPlugins() if callback is not None: callback(True) def loadNameserverConfig(self): ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" nameserverPattern = re.compile("nameserver +" + ipRegexp) ipPattern = re.compile(ipRegexp) resolv = [] try: fp = file('/etc/resolv.conf', 'r') resolv = fp.readlines() fp.close() self.nameservers = [] except: print "[Network.py] resolv.conf - opening failed" for line in resolv: if self.regExpMatch(nameserverPattern, line) is not None: ip = self.regExpMatch(ipPattern, line) if ip: self.nameservers.append(self.convertIP(ip)) print "nameservers:", self.nameservers def getInstalledAdapters(self): return [x for x in os.listdir('/sys/class/net') if not self.isBlacklisted(x)] def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): if x in self.friendlyNames.keys(): return self.friendlyNames.get(x, x) self.friendlyNames[x] = self.getFriendlyAdapterNaming(x) return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name def getFriendlyAdapterNaming(self, iface): name = None if iface not in self.lan_interfaces: if iface == "eth1": name = _("VLAN connection") else: name = _("LAN connection") if len(self.lan_interfaces) and not iface == "eth1": name += " " + str(len(self.lan_interfaces)+1) self.lan_interfaces.append(iface) return name def getFriendlyAdapterDescription(self, iface): return _('Ethernet network interface') def getAdapterName(self, iface): return iface def getAdapterList(self): return self.ifaces.keys() def getAdapterAttribute(self, iface, attribute): return self.ifaces.get(iface, {}).get(attribute) def setAdapterAttribute(self, iface, attribute, value): print "setting for adapter", iface, "attribute", attribute, " to value", value if iface in self.ifaces: self.ifaces[iface][attribute] = value def removeAdapterAttribute(self, iface, attribute): if iface in self.ifaces and attribute in self.ifaces[iface]: del self.ifaces[iface][attribute] def getNameserverList(self): if len(self.nameservers) == 0: return [[0, 0, 0, 0], [0, 0, 0, 0]] else: return self.nameservers def clearNameservers(self): self.nameservers = [] def addNameserver(self, nameserver): if nameserver not in self.nameservers: self.nameservers.append(nameserver) def removeNameserver(self, nameserver): if nameserver in self.nameservers: self.nameservers.remove(nameserver) def changeNameserver(self, oldnameserver, newnameserver): if oldnameserver in self.nameservers: for i in range(len(self.nameservers)): if self.nameservers[i] == oldnameserver: self.nameservers[i] = newnameserver def resetNetworkConfig(self, mode='lan', callback = None): self.commands = [] for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append("/sbin/ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True) def resetNetworkFinishedCB(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: self.writeDefaultNetworkConfig(mode, callback) def writeDefaultNetworkConfig(self,mode='lan', callback = None): fp = file('/etc/network/interfaces', 'w') fp.write("# automatically generated by enigma2\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") if mode == 'wlan': fp.write("auto wlan0\n") fp.write("iface wlan0 inet dhcp\n") if mode == 'wlan-mpci': fp.write("auto ath0\n") fp.write("iface ath0 inet dhcp\n") if mode == 'lan': fp.write("auto eth0\n") fp.write("iface eth0 inet dhcp\n") fp.write("\n") fp.close() self.commands = [] if mode == 'wlan': self.commands.append("/sbin/ifconfig eth0 down") self.commands.append("/sbin/ifconfig ath0 down") self.commands.append("/sbin/ifconfig wlan0 up") if mode == 'wlan-mpci': self.commands.append("/sbin/ifconfig eth0 down") self.commands.append("/sbin/ifconfig wlan0 down") self.commands.append("/sbin/ifconfig ath0 up") if mode == 'lan': self.commands.append("/sbin/ifconfig eth0 up") self.commands.append("/sbin/ifconfig wlan0 down") self.commands.append("/sbin/ifconfig ath0 down") self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True) def resetNetworkFinished(self, extra_args): (mode, callback) = extra_args if not self.resetNetworkConsole.appContainers: if callback is not None: callback(True, mode) def checkNetworkState(self,statecallback): self.NetworkState = 0 self.pingConsole = Console() for server in ("www.openpli.org", "www.google.nl", "www.google.com"): self.pingConsole.ePopen(("/bin/ping", "/bin/ping", "-c", "1", server), self.checkNetworkStateFinished,statecallback) def checkNetworkStateFinished(self, result, retval,extra_args): (statecallback) = extra_args if self.pingConsole is not None: if retval == 0: self.pingConsole = None statecallback(self.NetworkState) else: self.NetworkState += 1 if not self.pingConsole.appContainers: statecallback(self.NetworkState) def restartNetwork(self,callback = None): self.config_ready = False self.msgPlugins() self.commands = [] for iface in self.ifaces.keys(): if iface != 'eth0' or not self.onRemoteRootFS(): self.commands.append(("/sbin/ifdown", "/sbin/ifdown", iface)) self.commands.append("/sbin/ip addr flush dev " + iface + " scope global") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.commands.append("rm /var/run/ifstate*") self.commands.append("/etc/init.d/networking start") self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True) def restartNetworkFinished(self,extra_args): ( callback ) = extra_args if callback is not None: callback(True) def getLinkState(self,iface,callback): self.linkConsole.ePopen((self.ethtool_bin, self.ethtool_bin, iface), self.getLinkStateFinished,callback) def getLinkStateFinished(self, result, retval, extra_args): (callback) = extra_args if not self.linkConsole.appContainers: callback(result) def stopPingConsole(self): if self.pingConsole is not None: self.pingConsole.killAll() def stopLinkStateConsole(self): self.linkConsole.killAll() def stopDNSConsole(self): if self.dnsConsole is not None: self.dnsConsole.killAll() def stopRestartConsole(self): self.restartConsole.killAll() def stopGetInterfacesConsole(self): self.console.killAll() def stopDeactivateInterfaceConsole(self): self.deactivateInterfaceConsole.killAll() def stopActivateInterfaceConsole(self): self.activateInterfaceConsole.killAll() def checkforInterface(self, iface): return self.getAdapterAttribute(iface, 'up') def checkDNSLookup(self,statecallback): self.DnsState = 0 self.dnsConsole = Console() for server in ("www.openpli.org", "www.google.nl", "www.google.com"): self.dnsConsole.ePopen(("/usr/bin/nslookup", "/usr/bin/nslookup", server), self.checkDNSLookupFinished, statecallback) def checkDNSLookupFinished(self, result, retval,extra_args): (statecallback) = extra_args if self.dnsConsole is not None: if retval == 0: self.dnsConsole = None statecallback(self.DnsState) else: self.DnsState += 1 if not self.dnsConsole.appContainers: statecallback(self.DnsState) def deactivateInterface(self,ifaces,callback = None): self.config_ready = False self.msgPlugins() commands = [] def buildCommands(iface): commands.append(("/sbin/ifdown", "/sbin/ifdown", "-f", iface)) commands.append(("/sbin/ip", "/sbin/ip", "addr", "flush", "dev", iface, "scope", "global")) #wpa_supplicant sometimes doesn't quit properly on SIGTERM if os.path.exists('/var/run/wpa_supplicant/'+ iface): commands.append("wpa_cli -i" + iface + " terminate") if isinstance(ifaces, (list, tuple)): for iface in ifaces: if iface != 'eth0' or not self.onRemoteRootFS(): buildCommands(iface) else: if ifaces == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return buildCommands(ifaces) self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, (ifaces,callback), debug=True) def deactivateInterfaceFinished(self,extra_args): (ifaces, callback) = extra_args if not self.deactivateInterfaceConsole.appContainers: if callback is not None: callback(True) def activateInterface(self,iface,callback = None): if self.config_ready: self.config_ready = False self.msgPlugins() if iface == 'eth0' and self.onRemoteRootFS(): if callback is not None: callback(True) return commands = [] commands.append(("/sbin/ifup", "/sbin/ifup", iface)) self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True) def activateInterfaceFinished(self,extra_args): callback = extra_args if not self.activateInterfaceConsole.appContainers: if callback is not None: callback(True) def sysfsPath(self, iface): return '/sys/class/net/' + iface def calc_netmask(self,nmask): from struct import pack from socket import inet_ntoa mask = 1L<<31 xnet = (1L<<32)-1 cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print 'cidr invalid: %d' % cidr return None else: nm = ((1L<<cidr)-1)<<(32-cidr) netmask = str(inet_ntoa(pack('>L', nm))) return netmask def msgPlugins(self): if self.config_ready is not None: for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=self.config_ready) def hotplug(self, event): interface = event['INTERFACE'] if self.isBlacklisted(interface): return action = event['ACTION'] if action == "add": print "[Network] Add new interface:", interface self.getAddrInet(interface, None) elif action == "remove": print "[Network] Removed interface:", interface try: del self.ifaces[interface] except KeyError: pass