class WirelessAccessPoint(Screen, ConfigListScreen): skin = """ <screen position="center,center" size="590,450" title="Wireless Access Point" > <ePixmap pixmap="buttons/red.png" position="20,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/green.png" position="160,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/yellow.png" position="300,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/blue.png" position="440,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" /> <widget source="key_blue" render="Label" position="440,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" /> <widget name="config" zPosition="2" position="20,70" size="550,270" scrollbarMode="showOnDemand" transparent="1" /> <widget source="current_settings" render="Label" position="10,340" size="570,20" font="Regular;19" halign="center" valign="center" transparent="1" /> <widget source="IPAddress_text" render="Label" position="130,370" size="190,21" font="Regular;19" transparent="1" /> <widget source="Netmask_text" render="Label" position="130,395" size="190,21" font="Regular;19" transparent="1" /> <widget source="Gateway_text" render="Label" position="130,420" size="190,21" font="Regular;19" transparent="1" /> <widget source="IPAddress" render="Label" position="340,370" size="240,21" font="Regular;19" transparent="1" /> <widget source="Netmask" render="Label" position="340,395" size="240,21" font="Regular;19" transparent="1" /> <widget source="Gateway" render="Label" position="340,420" size="240,21" font="Regular;19" transparent="1" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) self.session = session self["shortcuts"] = ActionMap( ["ShortcutActions", "SetupActions"], { "ok": self.doConfigMsg, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.doConfigMsg, }, -2) self.list = [] ConfigListScreen.__init__(self, self.list, session=self.session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Ok")) self["key_yellow"] = StaticText(_(" ")) self["key_blue"] = StaticText(_(" ")) self["current_settings"] = StaticText( _("Current settings (interface : br0)")) self["IPAddress_text"] = StaticText(_("IP Address")) self["Netmask_text"] = StaticText(_("Netmask")) self["Gateway_text"] = StaticText(_("Gateway")) self["IPAddress"] = StaticText(_("N/A")) self["Netmask"] = StaticText(_("N/A")) self["Gateway"] = StaticText(_("N/A")) self.makeConfig() self.apModeChanged = False self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.currentNetworkSettings) self.onLayoutFinish.append(self.checkConfigError) self.configErrorTimer = eTimer() self.configErrorTimer.callback.append(self.configErrorMsg) self.configStartMsg = None def makeConfig(self): self.msg = "" if self.checkWirelessDevices(): return self.checkRunHostapd() self.makeConfigList() self.loadInterfacesConfig() self.loadHostapConfig() self.setupCurrentEncryption() self.createConfigEntry() self.createConfig() def checkConfigError(self): if self.msg: self.configErrorTimer.start(100, True) def configErrorMsg(self): self.session.openWithCallback(self.close, MessageBox, _(self.msg), MessageBox.TYPE_ERROR) def checkwlanDeviceList(self): if len(self.wlanDeviceList) == 0: self.checkwlanDeviceListTimer.start(100, True) def currentNetworkSettings(self): self["IPAddress"].setText( self.formatAddr(iNetwork.getAdapterAttribute("br0", "ip"))) self["Netmask"].setText( self.formatAddr(iNetwork.getAdapterAttribute("br0", "netmask"))) self["Gateway"].setText( self.formatAddr(iNetwork.getAdapterAttribute("br0", "gateway"))) def formatAddr(self, address=[0, 0, 0, 0]): if address is None: return "N/A" return "%d:%d:%d:%d" % (address[0], address[1], address[2], address[3]) def checkRunHostapd(self): global apModeConfig if fileExists("/var/run/hostapd", 0): apModeConfig.useap.value = True def checkWirelessDevices(self): global apModeConfig self.wlanDeviceList = [] wlanIfaces = [] for x in iNetwork.getInstalledAdapters(): if x.startswith('eth') or x.startswith('br') or x.startswith( 'mon'): continue elif os_path.exists("/tmp/bcm/%s" % x): continue wlanIfaces.append(x) description = self.getAdapterDescription(x) if description == "Unknown network adapter": self.wlanDeviceList.append((x, x)) else: self.wlanDeviceList.append((x, description + " (%s)" % x)) if len(self.wlanDeviceList) == 0: self.msg = "Can not find wireless lan devices that support AP mode." return -1 apModeConfig.wirelessdevice = ConfigSelection( choices=self.wlanDeviceList) return 0 def makeConfigList(self): global apModeConfig self.hostapdConf = {} self.hostapdConf["interface"] = apModeConfig.wirelessdevice self.hostapdConf["bridge"] = apModeConfig.branch # "br0" self.hostapdConf["driver"] = apModeConfig.driver # "nl80211" self.hostapdConf["hw_mode"] = apModeConfig.wirelessmode self.hostapdConf["channel"] = apModeConfig.channel self.hostapdConf["ssid"] = apModeConfig.ssid self.hostapdConf["beacon_int"] = apModeConfig.beacon self.hostapdConf["rts_threshold"] = apModeConfig.rts_threshold self.hostapdConf["fragm_threshold"] = apModeConfig.fragm_threshold self.hostapdConf["preamble"] = apModeConfig.preamble # self.hostapdConf["macaddr_acl"] = "" # fix to add Access Control List Editer # self.hostapdConf["accept_mac_file"] = "" # fix to add Access Control List Editer # self.hostapdConf["deny_mac_file"] = "" # fix to add Access Control List Editer self.hostapdConf[ "ignore_broadcast_ssid"] = apModeConfig.ignore_broadcast_ssid # self.hostapdConf["wmm_enabled"] = "" # self.hostapdConf["ieee80211n"] = "" # self.hostapdConf["ht_capab"] = "" self.hostapdConf["wep_default_key"] = apModeConfig.wep_default_key self.hostapdConf["wep_key0"] = apModeConfig.wep_key0 self.hostapdConf["wpa"] = apModeConfig.wpa self.hostapdConf["wpa_passphrase"] = apModeConfig.wpa_passphrase self.hostapdConf[ "wpa_key_mgmt"] = apModeConfig.wpa_key_mgmt # "WPA-PSK" self.hostapdConf[ "wpa_pairwise"] = apModeConfig.wpa_pairwise # "TKIP CCMP" self.hostapdConf["rsn_pairwise"] = apModeConfig.rsn_pairwise # "CCMP" self.hostapdConf["wpa_group_rekey"] = apModeConfig.wpagrouprekey def loadInterfacesConfig(self): global apModeConfig try: fp = file('/etc/network/interfaces', 'r') datas = fp.readlines() fp.close() except: printDebugMsg("Read failed, /etc/network/interfaces.") return -1 current_iface = "" try: for line in datas: split = line.strip().split(' ') if (split[0] == "iface"): current_iface = split[1] if (current_iface == "br0" or current_iface == "eth0"): if (len(split) == 4 and split[3] == "dhcp"): apModeConfig.usedhcp.value = True if (split[0] == "address"): apModeConfig.address.value = map( int, split[1].split('.')) if (split[0] == "netmask"): apModeConfig.netmask.value = map( int, split[1].split('.')) if (split[0] == "gateway"): apModeConfig.gateway.value = map( int, split[1].split('.')) if (split[0] == "dns-nameservers"): apModeConfig.nameserver.value = map( int, split[1].split('.')) except: printDebugMsg("Parsing failed, /etc/network/interfaces.") return -1 return 0 def setupCurrentEncryption(self): global apModeConfig if len(apModeConfig.wep_key0.value) > 10: apModeConfig.wepType.value = "128" if apModeConfig.wpa.value is not "0" and apModeConfig.wpa_passphrase.value: # (1,WPA), (2,WPA2), (3,WPA/WPA2) apModeConfig.encrypt.value = True apModeConfig.method.value = apModeConfig.wpa.value elif apModeConfig.wep.value and apModeConfig.wep_key0.value: apModeConfig.encrypt.value = True apModeConfig.method.value = "0" # wep else: apModeConfig.encrypt.value = False def createConfigEntry(self): global apModeConfig #hostap settings self.useApEntry = getConfigListEntry(_("Use AP Mode"), apModeConfig.useap) self.setupModeEntry = getConfigListEntry(_("Setup Mode"), apModeConfig.setupmode) self.wirelessDeviceEntry = getConfigListEntry( _("AP Device"), apModeConfig.wirelessdevice) self.wirelessModeEntry = getConfigListEntry(_("AP Mode"), apModeConfig.wirelessmode) self.channelEntry = getConfigListEntry(_("Channel (1~13)"), apModeConfig.channel) self.ssidEntry = getConfigListEntry(_("SSID (1~32 Characters)"), apModeConfig.ssid) self.beaconEntry = getConfigListEntry(_("Beacon (15~65535)"), apModeConfig.beacon) self.rtsThresholdEntry = getConfigListEntry( _("RTS Threshold (0~2347)"), apModeConfig.rts_threshold) self.fragmThresholdEntry = getConfigListEntry( _("FRAGM Threshold (256~2346)"), apModeConfig.fragm_threshold) self.prambleEntry = getConfigListEntry(_("Preamble"), apModeConfig.preamble) self.ignoreBroadcastSsid = getConfigListEntry( _("Ignore Broadcast SSID"), apModeConfig.ignore_broadcast_ssid) # hostap encryption self.encryptEntry = getConfigListEntry(_("Encrypt"), apModeConfig.encrypt) self.methodEntry = getConfigListEntry(_("Method"), apModeConfig.method) self.wepKeyTypeEntry = getConfigListEntry(_("KeyType"), apModeConfig.wepType) self.wepKey0Entry = getConfigListEntry(_("WEP Key (HEX)"), apModeConfig.wep_key0) self.wpaKeyEntry = getConfigListEntry(_("KEY (8~63 Characters)"), apModeConfig.wpa_passphrase) self.groupRekeyEntry = getConfigListEntry(_("Group Rekey Interval"), apModeConfig.wpagrouprekey) # interface settings self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), apModeConfig.usedhcp) self.ipEntry = getConfigListEntry(_("IP Address"), apModeConfig.address) self.netmaskEntry = getConfigListEntry(_("NetMask"), apModeConfig.netmask) self.gatewayEntry = getConfigListEntry(_("Gateway"), apModeConfig.gateway) self.nameserverEntry = getConfigListEntry(_("Nameserver"), apModeConfig.nameserver) def createConfig(self): global apModeConfig apModeConfig.address.value = iNetwork.getAdapterAttribute( apModeConfig.branch.value, "ip") or [0, 0, 0, 0] apModeConfig.netmask.value = iNetwork.getAdapterAttribute( apModeConfig.branch.value, "netmask") or [255, 0, 0, 0] apModeConfig.gateway.value = iNetwork.getAdapterAttribute( apModeConfig.branch.value, "gateway") or [0, 0, 0, 0] self.configList = [] self.configList.append(self.useApEntry) if apModeConfig.useap.value is True: self.configList.append(self.setupModeEntry) self.configList.append(self.wirelessDeviceEntry) self.configList.append(self.wirelessModeEntry) self.configList.append(self.channelEntry) self.configList.append(self.ssidEntry) if apModeConfig.setupmode.value is "advanced": self.configList.append(self.beaconEntry) self.configList.append(self.rtsThresholdEntry) self.configList.append(self.fragmThresholdEntry) self.configList.append(self.prambleEntry) self.configList.append(self.ignoreBroadcastSsid) self.configList.append(self.encryptEntry) if apModeConfig.encrypt.value is True: self.configList.append(self.methodEntry) if apModeConfig.method.value is "0": # wep self.configList.append(self.wepKeyTypeEntry) self.configList.append(self.wepKey0Entry) else: self.configList.append(self.wpaKeyEntry) if apModeConfig.setupmode.value is "advanced": self.configList.append(self.groupRekeyEntry) ## set network interfaces self.configList.append(self.usedhcpEntry) if apModeConfig.usedhcp.value is False: self.configList.append(self.ipEntry) self.configList.append(self.netmaskEntry) self.configList.append(self.gatewayEntry) self.configList.append(self.nameserverEntry) self["config"].list = self.configList self["config"].l.setList(self.configList) def keyLeft(self): ConfigListScreen.keyLeft(self) self.newConfig() def keyRight(self): ConfigListScreen.keyRight(self) self.newConfig() def newConfig(self): if self["config"].getCurrent() in [ self.encryptEntry, self.methodEntry, self.useApEntry, self.usedhcpEntry, self.setupModeEntry ]: self.createConfig() # 0 : legacy module activated, 1 : kernel module activated, -1 : None def checkProcModules(self): proc_path = "/proc/modules" legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta") kernel_modules = ("rt2800usb", "rt2800lib") fd = open(proc_path, "r") data = fd.readlines() fd.close() for line in data: module = line.split()[0].strip() if module in legacy_modules: return 0 elif module in kernel_modules: return 1 return -1 def isRalinkModule(self): global apModeConfig iface = apModeConfig.wirelessdevice.value # check vendor ID for lagacy driver vendorID = "148f" # ralink vendor ID idVendorPath = "/sys/class/net/%s/device/idVendor" % iface if access(idVendorPath, R_OK): fd = open(idVendorPath, "r") data = fd.read().strip() fd.close() printDebugMsg("Vendor ID : %s" % data) if data == vendorID: return True # check sys driver path for kernel driver ralinkKmod = "rt2800usb" # ralink kernel driver name driverPath = "/sys/class/net/%s/device/driver/" % iface if os_path.exists(driverPath): driverName = os_path.basename(os_path.realpath(driverPath)) printDebugMsg("driverName : %s" % driverName) if driverName == ralinkKmod: return True return False def doConfigMsg(self): global apModeConfig msg = "Are you sure you want to setup AP?\n" isRainkIface = self.isRalinkModule() isApMode = apModeConfig.useap.value is True isRalinkKmodUploaded = self.checkProcModules() == 1 if isRainkIface and isApMode and (not isRalinkKmodUploaded): msg += "( STB should be reboot to enable AP mode. )\n" else: msg += ("\n") self.session.openWithCallback(self.doConfig, MessageBox, (_(msg))) def doConfig(self, ret=False): global apModeConfig if ret is not True: return if apModeConfig.useap.value is True and apModeConfig.encrypt.value is True: if not self.checkEncrypKey(): return if not self.checkConfig(): return self.configStartMsg = self.session.openWithCallback( self.ConfigFinishedMsg, MessageBox, _("Please wait for AP Configuration....\n"), type=MessageBox.TYPE_INFO, enable_input=False) if apModeConfig.useap.value is True: self.networkRestart(nextFunc=self.makeConf) else: self.networkRestart(nextFunc=self.removeConf) def checkEncrypKey(self): global apModeConfig if apModeConfig.method.value == "0": if self.checkWep(apModeConfig.wep_key0.value) is False: self.session.open(MessageBox, _("Invalid WEP key\n\n"), type=MessageBox.TYPE_ERROR, timeout=10) else: return True else: if not len(apModeConfig.wpa_passphrase.value) in range(8, 65): self.session.open(MessageBox, _("Invalid WPA key\n\n"), type=MessageBox.TYPE_ERROR, timeout=10) else: return True return False def checkWep(self, key): global apModeConfig length = len(key) if length == 0: return False elif apModeConfig.wepType.value == "64" and length == 10: return True elif apModeConfig.wepType.value == "128" and length == 26: return True else: return False def checkConfig(self): global apModeConfig # ssid Check if len(apModeConfig.ssid.value) == 0 or len( apModeConfig.ssid.value) > 32: self.session.open(MessageBox, _("Invalid SSID\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.channel.value not in range(1, 14): self.session.open(MessageBox, _("Invalid channel\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.beacon.value < 15 or apModeConfig.beacon.value > 65535: self.session.open(MessageBox, _("Invalid beacon\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.rts_threshold.value < 0 or apModeConfig.rts_threshold.value > 2347: self.session.open(MessageBox, _("Invalid RTS Threshold\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.fragm_threshold.value < 256 or apModeConfig.fragm_threshold.value > 2346: self.session.open(MessageBox, _("Invalid Fragm Threshold\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.wpagrouprekey.value < 0 or apModeConfig.wpagrouprekey.value > 3600: self.session.open(MessageBox, _("Invalid wpagrouprekey\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False return True def networkRestart(self, nextFunc=None): self.networkRestart_stop(nextFunc=nextFunc) def networkRestart_stop(self, nextFunc=None): printDebugMsg("networkRestart_stop") self.msgPlugins(False) self.commands = [] # stop current network self.networkRestartConsole = Console() self.commands.append("/etc/init.d/avahi-daemon stop") for iface in iNetwork.getAdapterList(): if iface != 'eth0' or not iNetwork.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface) self.commands.append("/etc/init.d/hostapd stop") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.networkRestartConsole.eBatch(self.commands, nextFunc, debug=True) def makeConf(self, extra_args): printDebugMsg("makeConf") self.writeNetworkInterfaces() result = self.writeHostapdConfig() if result == -1: self.configStartMsg.close(False) self.configErrorTimer.start(100, True) return self.setIpForward(1) self.networkRestart_start() def removeConf(self, extra_args): global apModeConfig printDebugMsg("removeConf") if fileExists("/etc/hostapd.conf", 'f'): Console().ePopen( "mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back") fp = file("/etc/network/interfaces", 'w') fp.write( "# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") if apModeConfig.usedhcp.value is True: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value)) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value)) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value)) fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value)) fp.close() self.setIpForward(0) self.networkRestart_start() def networkRestart_start(self): global apModeConfig printDebugMsg("networkRestart_start") self.restartConsole = Console() self.commands = [] self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") if apModeConfig.useap.value is True: self.commands.append("/etc/init.d/hostapd start") self.restartConsole.eBatch(self.commands, self.networkRestartFinished, debug=True) def networkRestartFinished(self, data): printDebugMsg("networkRestartFinished") iNetwork.ifaces = {} iNetwork.getInterfaces(self.getInterfacesDataAvail) def getInterfacesDataAvail(self, data): self.blacklist_legacy_drivers() if data is True and self.configStartMsg is not None: self.configStartMsg.close(True) def ConfigFinishedMsg(self, ret): if ret is True: self.session.openWithCallback( self.ConfigFinishedMsgCallback, MessageBox, _("Configuration your AP is finished"), type=MessageBox.TYPE_INFO, timeout=5, default=False) def needRalinkKmod(self): global apModeConfig isRainkIface = self.isRalinkModule() ApMode = apModeConfig.useap.value is True if isRainkIface and ApMode: return True else: return False def ConfigFinishedMsgCallback(self, data): isRalinkKmodUploaded = self.checkProcModules() == 1 needRalinkKmod_ = self.needRalinkKmod() if needRalinkKmod_: # ralink device is activated in AP Mode. if not isRalinkKmodUploaded: # reboot to loading kernel module. msg = "You should now reboot your STB in order to ralink device operate in AP mode.\n\nReboot now ?\n\n" self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type=MessageBox.TYPE_YESNO, default=True) else: self.close() elif isRalinkKmodUploaded: msg = "You should now reboot your STB to better performance of ralink device in STA mode.\n\nReboot now ?\n\n" self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type=MessageBox.TYPE_YESNO, default=True) else: self.close() def blacklist_legacy_drivers(self): blacklist_conf_dir = "/etc/modprobe.d" blacklist_conf_file = blacklist_conf_dir + "/blacklist-wlan.conf" legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta") kernel_modules = ("rt2800usb", "rt2800lib") blacklist = "" need_ralink_kmod = self.needRalinkKmod() if access(blacklist_conf_file, R_OK) is True: fd = open(blacklist_conf_file, "r") data = fd.read() fd.close() if need_ralink_kmod: # check legacy modules in blacklist for mod in legacy_modules: if data.find(mod) != -1: return else: for mod in kernel_modules: # check kernel modules in blacklist if data.find(mod) != -1: return if not os_path.exists(blacklist_conf_dir): makedirs(blacklist_conf_dir) if need_ralink_kmod: blacklist_modules = legacy_modules else: blacklist_modules = kernel_modules for module in blacklist_modules: blacklist += "blacklist %s\n" % module f = open(blacklist_conf_file, "w+") f.write(blacklist) f.close() self.apModeChanged = True def doReboot(self, res): if res: self.session.open(TryQuitMainloop, 2) else: self.close() def msgPlugins(self, reason=False): for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=reason) def writeNetworkInterfaces(self): global apModeConfig fp = file("/etc/network/interfaces", 'w') fp.write( "# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") fp.write("iface eth0 inet manual\n") fp.write(" up ip link set $IFACE up\n") fp.write(" down ip link set $IFACE down\n\n") # branch setup fp.write("auto br0\n") if apModeConfig.usedhcp.value is True: fp.write("iface br0 inet dhcp\n") else: fp.write("iface br0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value)) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value)) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value)) fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value)) fp.write(" pre-up brctl addbr br0\n") fp.write(" pre-up brctl addif br0 eth0\n") fp.write(" post-down brctl delif br0 eth0\n") fp.write(" post-down brctl delbr br0\n\n") fp.write("\n") fp.close() def setIpForward(self, setValue=0): ipForwardFilePath = "/proc/sys/net/ipv4/ip_forward" if not fileExists(ipForwardFilePath): return -1 printDebugMsg("set %s to %d" % (ipForwardFilePath, setValue)) f = open(ipForwardFilePath, "w") f.write("%d" % setValue) f.close() sysctlPath = "/etc/sysctl.conf" sysctlLines = [] if fileExists(sysctlPath): fp = file(sysctlPath, "r") sysctlLines = fp.readlines() fp.close() sysctlList = {} for line in sysctlLines: line = line.strip() try: (key, value) = line.split("=") key = key.strip() value = value.strip() except: continue sysctlList[key] = value sysctlList["net.ipv4.ip_forward"] = str(setValue) fp = file(sysctlPath, "w") for (key, value) in sysctlList.items(): fp.write("%s=%s\n" % (key, value)) fp.close() return 0 def getAdapterDescription(self, iface): classdir = "/sys/class/net/" + iface + "/device/" driverdir = "/sys/class/net/" + iface + "/device/driver/" if os_path.exists(classdir): files = listdir(classdir) if 'driver' in files: if os_path.realpath(driverdir).endswith('rtw_usb_drv'): return _("Realtek") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('ath_pci'): return _("Atheros") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('zd1211b'): return _("Zydas") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73'): return _("Ralink") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73usb'): return _("Ralink") + " " + _("WLAN adapter.") else: return str(os_path.basename( os_path.realpath(driverdir))) + " " + _("WLAN adapter") else: return _("Unknown network adapter") else: return _("Unknown network adapter") def __onClose(self): global apModeConfig for x in self["config"].list: x[1].cancel() apModeConfig.wpa.value = "0" apModeConfig.wep.value = False def keyCancel(self): self.close() def printConfigList(self, confList): printDebugMsg("== printConfigList ==") for (key, entry) in confList.items(): printDebugMsg("%s = %s" % (key, str(entry.value))) printDebugMsg("== printConfigList end ==") def loadHostapConfig(self): global apModeConfig fd = -1 if access("/etc/hostapd.conf", R_OK) is True: printDebugMsg("open /etc/hostapd.conf") fd = open("/etc/hostapd.conf", "r") elif access("/etc/hostapd.conf.linuxap.back", R_OK) is True: printDebugMsg("open /etc/hostapd.conf.linuxap.back") fd = open("/etc/hostapd.conf.linuxap.back", "r") if fd == -1: printDebugMsg("can not open hostapd.conf") return -1 for line in fd.readlines(): line = line.strip() if (len(line) == 0) or (line.find('=') == -1): continue data = line.split('=', 1) if len(data) != 2: continue key = data[0].strip() value = data[1].strip() if key == "#wep_key0": self.hostapdConf["wep_key0"].value = value apModeConfig.wep.value = False elif key == "wep_key0": self.hostapdConf["wep_key0"].value = value apModeConfig.wep.value = True elif key.startswith('#'): continue elif key == "channel": if int(value) not in range(14): self.hostapdConf[key].value = 1 else: self.hostapdConf[key].value = int(value) elif key in [ "beacon_int", "rts_threshold", "fragm_threshold", "wpa_group_rekey" ]: self.hostapdConf[key].value = int(value) elif key in self.hostapdConf.keys(): self.hostapdConf[key].value = value fd.close() self.printConfigList(self.hostapdConf) return 0 def writeHostapdConfig(self): global apModeConfig global ORIG_HOSTAPD_CONF self.printConfigList(self.hostapdConf) if access(ORIG_HOSTAPD_CONF, R_OK) is not True: self.msg = "can not access file. (%s)" % ORIG_HOSTAPD_CONF printDebugMsg(self.msg) return -1 orig_conf = open(ORIG_HOSTAPD_CONF, "r") if orig_conf == -1: print "can't open file. (%s)" % ORIG_HOSTAPD_CONF new_conf = open(HOSTAPD_CONF, "w") if new_conf == -1: print "can't open file. (%s)" % HOSTAPD_CONF isEncryptOn = apModeConfig.encrypt.value is True isEncryptWEP = apModeConfig.method.value == "0" isEncryptWPA = not isEncryptWEP for r_line in orig_conf.readlines(): line = r_line.strip() if len(line) < 2: new_conf.write(r_line) continue fix_line = None # for encrypt line if line.find("wep_default_key=") != -1: # is wepLine if isEncryptOn and isEncryptWEP: fix_line = "wep_default_key=%s\n" % self.hostapdConf[ "wep_default_key"].value elif line.find("wep_key0=") != -1: # is WepKeyLine if isEncryptOn: if isEncryptWEP: fix_line = "wep_key0=%s\n" % self.hostapdConf[ "wep_key0"].value else: fix_line = "#wep_key0=%s\n" % self.hostapdConf[ "wep_key0"].value else: fix_line = "#wep_key0=%s\n" % self.hostapdConf[ "wep_key0"].value elif line.find("wpa=") != -1: # is wpaLine if isEncryptOn and isEncryptWPA: fix_line = "wpa=%s\n" % apModeConfig.method.value ## elif line.startswith("#ssid"): pass else: for (key, entry) in self.hostapdConf.items(): value = str(entry.value) pos = line.find(key + '=') if ((pos != -1) and (pos < 2)) and len(value) != 0: fix_line = "%s=%s\n" % (key, value) break # if fix_line is not None: # print "r_line : ", r_line, # print "fix_li : ", fix_line if fix_line is not None: new_conf.write(fix_line) else: new_conf.write(r_line) orig_conf.close() new_conf.close() return 0
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
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 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 VISIONSwap(Screen): skin = """ <screen name="VISIONSwap" position="center,center" size="620,250"> <ePixmap pixmap="buttons/red.png" position="10,0" size="140,40" alphatest="on"/> <ePixmap pixmap="buttons/green.png" position="160,0" size="140,40" alphatest="on"/> <ePixmap pixmap="buttons/yellow.png" position="310,0" size="140,40" alphatest="on"/> <ePixmap pixmap="buttons/blue.png" position="460,0" size="140,40" alphatest="on"/> <widget name="key_red" position="10,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/> <widget name="key_green" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/> <widget name="key_yellow" position="310,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1"/> <widget name="key_blue" position="460,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1"/> <widget name="autostart_off" position="10,50" zPosition="1" pixmap="icons/lock_off.png" size="32,32" alphatest="on"/> <widget name="autostart_on" position="10,50" zPosition="2" pixmap="icons/lock_on.png" size="32,32" alphatest="on"/> <widget name="lab7" position="50,50" size="360,30" font="Regular;20" valign="center" transparent="1"/> <widget name="lab8" position="10,100" size="150,30" font="Regular;20" valign="center" transparent="1"/> <widget name="lab9" position="10,150" size="150,30" font="Regular;20" valign="center" transparent="1"/> <widget name="lab10" position="10,200" size="150,30" font="Regular;20" valign="center" transparent="1" /> <widget name="labplace" position="160,100" size="220,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/> <widget name="labsize" position="160,150" size="220,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/> <widget name="inactive" position="160,200" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/> <widget name="active" position="160,200" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="green"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) self.setTitle(_("Vision Swap Manager")) self["lab1"] = StaticText(_("OpenVision")) self["lab2"] = StaticText(_("Lets define enigma2 once more")) self["lab3"] = StaticText(_("Report problems to:")) self["lab4"] = StaticText(_("https://openvision.tech")) self["lab5"] = StaticText(_("Sources are available at:")) self["lab6"] = StaticText(_("https://github.com/OpenVisionE2")) self['lab7'] = Label() self['autostart_on'] = Pixmap() self['autostart_off'] = Pixmap() self['lab8'] = Label(_("Swap place:")) self['labplace'] = Label() self['lab9'] = Label(_("Swap size:")) self['labsize'] = Label() self['lab10'] = Label(_("Status:")) self['inactive'] = Label(_("Inactive")) self['active'] = Label(_("Active")) self['key_red'] = Label(_("Close")) self['key_green'] = Label(_("Activate")) self['key_blue'] = Label(_("Create")) self['key_yellow'] = Label(_("Autostart")) self['swapname_summary'] = StaticText() self['swapactive_summary'] = StaticText() self.Console = Console() self.swap_place = '' self.new_place = '' self.creatingswap = False self.swap_active = False self['actions'] = ActionMap( ['WizardActions', 'ColorActions', "MenuActions"], { 'back': self.close, 'red': self.close, 'green': self.actDeact, 'yellow': self.autoSsWap, 'blue': self.createDel, "menu": self.close }) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.getSwapDevice) self.updateSwap() def updateSwap(self, result=None, retval=None, extra_args=None): self["actions"].setEnabled(False) self.swap_active = False self.swap_place = None self['autostart_on'].hide() self['autostart_off'].show() self['active'].hide() self['inactive'].show() self['labplace'].hide() self['labsize'].hide() self['swapactive_summary'].setText(_("Current status:")) scanning = _("Wait please while scanning...") self['lab7'].setText(scanning) self.activityTimer.start(10) def getSwapDevice(self): self.activityTimer.stop() if path.exists('/etc/rcS.d/S98SwapManager'): remove('/etc/rcS.d/S98SwapManager') config.visionsettings.swapautostart.value = True config.visionsettings.swapautostart.save() if path.exists('/tmp/swapdevices.tmp'): remove('/tmp/swapdevices.tmp') self.Console.ePopen("parted -l /dev/sd? | grep swap", self.updateSwap2) def updateSwap2(self, result=None, retval=None, extra_args=None): self.swapsize = 0 self.swap_place = "" self.swap_active = False self.device = False if sys.version_info >= (3, 0): result = result.decode('utf-8') if result.find("sd") > 0: self["key_blue"].setText("") for line in result.split("\n"): if line.find("sd") > 0: parts = line.strip().split() self.swap_place = parts[0] if self.swap_place == "sfdisk:": self.swap_place = "" self.device = True f = open("/proc/swaps", "r") for line2 in f.readlines(): parts = line.strip().split() if line2.find("partition") != -1: self.swap_active = True self.swapsize = parts[2] continue f.close() else: self["key_blue"].setText(_("Create")) devicelist = [] for p in harddiskmanager.getMountedPartitions(): d = path.normpath(p.mountpoint) if path.exists("/media/"): devicelist.append((p.description, d)) if len(devicelist): for device in devicelist: for filename in glob(device[1] + "/swap*"): self.swap_place = filename self["key_blue"].setText(_("Delete")) info = mystat(self.swap_place) self.swapsize = info[stat.ST_SIZE] continue if not path.exists("/media/") and p.mountpoint == "/": devicelist.append((p.description, d)) if len(devicelist): for device in devicelist: for filename in glob(device[1] + "swapfile"): self.swap_place = filename self["key_blue"].setText(_("Delete")) info = mystat(self.swap_place) self.swapsize = info[stat.ST_SIZE] continue if config.visionsettings.swapautostart.value and self.swap_place: self["autostart_off"].hide() self["autostart_on"].show() else: config.visionsettings.swapautostart.setValue(False) config.visionsettings.swapautostart.save() configfile.save() self["autostart_on"].hide() self["autostart_off"].show() self["labplace"].setText(self.swap_place) self["labplace"].show() f = open("/proc/swaps", "r") for line in f.readlines(): parts = line.strip().split() if line.find("partition") != -1: self.swap_active = True continue elif line.find("file") != -1: self.swap_active = True continue f.close() if self.swapsize > 0: if self.swapsize >= 1024: self.swapsize = int(self.swapsize) // 1024 if self.swapsize >= 1024: self.swapsize = int(self.swapsize) // 1024 self.swapsize = str(self.swapsize) + " " + "MB" else: self.swapsize = str(self.swapsize) + " " + "KB" else: self.swapsize = "" self["labsize"].setText(self.swapsize) self["labsize"].show() if self.swap_active: self["inactive"].hide() self["active"].show() self["key_green"].setText(_("Deactivate")) self["swapactive_summary"].setText( _("Current status:") + " " + _("Active")) else: self["inactive"].show() self["active"].hide() self["key_green"].setText(_("Activate")) self["swapactive_summary"].setText( _("Current status:") + " " + _("Inactive")) scanning = _("Enable swap at startup") self["lab7"].setText(scanning) self["lab7"].show() self["actions"].setEnabled(True) name = self["labplace"].text self["swapname_summary"].setText(name) def actDeact(self): if self.swap_active: self.Console.ePopen('swapoff ' + self.swap_place, self.updateSwap) else: if not self.device: if self.swap_place != '': self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) else: mybox = self.session.open( MessageBox, _("Swap file not found. You have to create the file before you try to activate it." ), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) else: self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) def createDel(self): if not self.device: if self.swap_place != '': if self.swap_active: self.Console.ePopen('swapoff ' + self.swap_place, self.createDel2) else: self.createDel2(None, 0) else: self.doCreateSwap() def createDel2(self, result, retval, extra_args=None): if retval == 0: remove(self.swap_place) if config.visionsettings.swapautostart.value: config.visionsettings.swapautostart.setValue(False) config.visionsettings.swapautostart.save() configfile.save() self.updateSwap() def doCreateSwap(self): parts = [] supported_filesystems = frozenset(('ext4', 'ext3', 'ext2')) candidates = [] mounts = getProcMounts() for partition in harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if len(candidates): self.session.openWithCallback( self.doCSplace, ChoiceBox, title=_("Please select device to use as SWAP file location."), list=candidates) else: self.session.open( MessageBox, _("Sorry, no physical devices that supports SWAP attached. Can't create SWAP file on network or fat32 file-systems." ), MessageBox.TYPE_INFO, timeout=10) def doCSplace(self, name): if name: self.new_place = name[1] myoptions = [[_("8 Mb"), '8192'], [_("16 Mb"), '16384'], [_("32 Mb"), '32768'], [_("64 Mb"), '65536'], [_("96 Mb"), '98304'], [_("128 Mb"), '131072'], [_("256 Mb"), '262144']] self.session.openWithCallback( self.doCSsize, ChoiceBox, title=_("Select the swap file size:"), list=myoptions) def doCSsize(self, swapsize): if swapsize: self["actions"].setEnabled(False) scanning = _("Wait please while creating swap file...") self['lab7'].setText(scanning) self['lab7'].show() swapsize = swapsize[1] myfile = self.new_place + '/swapfile' self.commands = [] self.commands.append('dd if=/dev/zero of=' + myfile + ' bs=1024 count=' + swapsize + ' 2>/dev/null') self.commands.append('mkswap ' + myfile) self.Console.eBatch(self.commands, self.updateSwap, debug=True) def autoSsWap(self): if self.swap_place: if config.visionsettings.swapautostart.value: config.visionsettings.swapautostart.setValue(False) config.visionsettings.swapautostart.save() else: config.visionsettings.swapautostart.setValue(True) config.visionsettings.swapautostart.save() configfile.save() else: mybox = self.session.open( MessageBox, _("You have to create a swap file before trying to activate the autostart." ), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) self.updateSwap()
class NetworkSamba(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Samba Setup")) self.skinName = "NetworkSamba" self.onChangedEntry = [] self["lab1"] = Label(_("Autostart:")) self["labactive"] = Label(_(_("Disabled"))) self["lab2"] = Label(_("Current Status:")) self["labstop"] = Label(_("Stopped")) self["labrun"] = Label(_("Running")) self["key_green"] = Label(_("Start")) self["key_red"] = Label(_("Remove Service")) self["key_yellow"] = Label(_("Autostart")) self["key_blue"] = Label(_("Show Log")) self.Console = Console() self.my_Samba_active = False self.my_Samba_run = False self["actions"] = ActionMap( ["WizardActions", "ColorActions"], { "ok": self.close, "back": self.close, "red": self.UninstallCheck, "green": self.SambaStartStop, "yellow": self.activateSamba, "blue": self.Sambashowlog, }, ) self.service_name = basegroup + "-smbfs" self.onLayoutFinish.append(self.InstallCheck) def InstallCheck(self): self.Console.ePopen("/usr/bin/opkg list_installed " + self.service_name, self.checkNetworkState) def checkNetworkState(self, str, retval, extra_args): if "Collected errors" in str: self.session.openWithCallback( self.close, MessageBox, _("A background update check is in progress, please wait a few minutes and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True, ) elif not str: self.feedscheck = self.session.open( MessageBox, _("Please wait while feeds state is checked."), MessageBox.TYPE_INFO, enable_input=False ) self.feedscheck.setTitle(_("Checking Feeds")) cmd1 = "opkg update" self.CheckConsole = Console() self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished) else: self.updateService() def checkNetworkStateFinished(self, result, retval, extra_args=None): if "bad address" in result: self.session.openWithCallback( self.InstallPackageFailed, MessageBox, _("Your %s %s is not connected to the internet, please check your network settings and try again.") % (getMachineBrand(), getMachineName()), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True, ) elif ("wget returned 1" or "wget returned 255" or "404 Not Found") in result: self.session.openWithCallback( self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True, ) else: self.session.openWithCallback( self.QuestionCallback, MessageBox, _("Your %s %s will be restarted after the installation of service.\nReady to install %s ?") % (getMachineBrand(), getMachineName(), self.service_name), MessageBox.TYPE_YESNO, ) def QuestionCallback(self, val): if val: self.session.openWithCallback( self.InstallPackage, MessageBox, _( "Do you want to also install samba client?\nThis allows you to mount your windows shares on this device." ), MessageBox.TYPE_YESNO, ) else: self.feedscheck.close() self.close() def InstallPackage(self, val): if val: self.service_name = self.service_name + " " + basegroup + "-smbfs-client" self.doInstall(self.installComplete, self.service_name) def InstallPackageFailed(self, val): self.feedscheck.close() self.close() def doInstall(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_("Installing Service")) self.Console.ePopen("/usr/bin/opkg install " + pkgname, callback) def installComplete(self, result=None, retval=None, extra_args=None): self.session.open(TryQuitMainloop, 2) def UninstallCheck(self): self.service_name = self.service_name + " " + basegroup + "-smbfs-client" self.Console.ePopen("/usr/bin/opkg list_installed " + self.service_name, self.RemovedataAvail) def RemovedataAvail(self, str, retval, extra_args): if str: restartbox = self.session.openWithCallback( self.RemovePackage, MessageBox, _("Your %s %s will be restarted after the removal of service.\nDo you want to remove now ?") % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO, ) restartbox.setTitle(_("Ready to remove %s ?") % self.service_name) else: self.updateService() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) def doRemove(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_("Removing Service")) self.Console.ePopen("/usr/bin/opkg remove " + pkgname + " --force-remove --autoremove", callback) def removeComplete(self, result=None, retval=None, extra_args=None): self.session.open(TryQuitMainloop, 2) def createSummary(self): return NetworkServicesSummary def Sambashowlog(self): self.session.open(NetworkSambaLog) def SambaStartStop(self): commands = [] if not self.my_Samba_run: commands.append("/etc/init.d/samba start") commands.append("nmbd -D") commands.append("smbd -D") elif self.my_Samba_run: commands.append("/etc/init.d/samba stop") commands.append("killall nmbd") commands.append("killall smbd") self.Console.eBatch(commands, self.StartStopCallback, debug=True) def StartStopCallback(self, result=None, retval=None, extra_args=None): time.sleep(3) self.updateService() def activateSamba(self): if access("/etc/network/if-up.d/01samba-start", X_OK): chmod("/etc/network/if-up.d/01samba-start", 0644) elif not access("/etc/network/if-up.d/01samba-start", X_OK): chmod("/etc/network/if-up.d/01samba-start", 0755) if fileExists("/etc/rc2.d/S20samba"): self.Console.ePopen("update-rc.d -f samba remove", self.StartStopCallback) else: self.Console.ePopen("update-rc.d -f samba defaults", self.StartStopCallback) def updateService(self): import process p = process.ProcessList() samba_process = str(p.named("smbd")).strip("[]") self["labrun"].hide() self["labstop"].hide() self["labactive"].setText(_("Disabled")) self.my_Samba_active = False self.my_Samba_run = False if fileExists("/etc/rc2.d/S20samba"): self["labactive"].setText(_("Enabled")) self["labactive"].show() self.my_Samba_active = True if access("/etc/network/if-up.d/01samba-start", X_OK): self["labactive"].setText(_("Enabled")) self["labactive"].show() self.my_Samba_active = True if samba_process: self.my_Samba_run = True if self.my_Samba_run: self["labstop"].hide() self["labactive"].show() self["labrun"].show() self["key_green"].setText(_("Stop")) status_summary = self["lab2"].text + " " + self["labrun"].text else: self["labrun"].hide() self["labstop"].show() self["labactive"].show() self["key_green"].setText(_("Start")) status_summary = self["lab2"].text + " " + self["labstop"].text title = _("Samba Setup") autostartstatus_summary = self["lab1"].text + " " + self["labactive"].text for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary)
class WirelessAccessPoint(Screen, ConfigListScreen): skin = """ <screen position="center,center" size="590,450" title="Wireless Access Point" > <ePixmap pixmap="skin_default/buttons/red.png" position="20,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="160,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="300,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="440,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" /> <widget source="key_blue" render="Label" position="440,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" /> <widget name="config" zPosition="2" position="10,70" size="580,270" scrollbarMode="showOnDemand" transparent="1" /> <widget source="current_settings" render="Label" position="10,340" size="570,20" font="Regular;19" halign="center" valign="center" transparent="1" /> <widget source="IPAddress_text" render="Label" position="130,370" size="190,21" font="Regular;19" transparent="1" /> <widget source="Netmask_text" render="Label" position="130,395" size="190,21" font="Regular;19" transparent="1" /> <widget source="Gateway_text" render="Label" position="130,420" size="190,21" font="Regular;19" transparent="1" /> <widget source="IPAddress" render="Label" position="340,370" size="240,21" font="Regular;19" transparent="1" /> <widget source="Netmask" render="Label" position="340,395" size="240,21" font="Regular;19" transparent="1" /> <widget source="Gateway" render="Label" position="340,420" size="240,21" font="Regular;19" transparent="1" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) self.session = session self["shortcuts"] = ActionMap( ["ShortcutActions", "SetupActions"], { "ok": self.doConfigMsg, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.doConfigMsg, }, -2) self.list = [] ConfigListScreen.__init__(self, self.list, session=self.session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Ok")) self["key_yellow"] = StaticText(_(" ")) self["key_blue"] = StaticText(_(" ")) self["current_settings"] = StaticText( _("Current settings (interface : br0)")) self["IPAddress_text"] = StaticText(_("IP Address")) self["Netmask_text"] = StaticText(_("Netmask")) self["Gateway_text"] = StaticText(_("Gateway")) self["IPAddress"] = StaticText(_("N/A")) self["Netmask"] = StaticText(_("N/A")) self["Gateway"] = StaticText(_("N/A")) self.wirelessAP = wirelessap.wirelessAP() self.checkRunHostapd() self.checkWirelessDevices() self.makeConfigList() self.loadInterfacesConfig() self.loadHostapConfig() self.setupCurrentEncryption() self.createConfigEntry() self.createConfig() self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.checkwlanDeviceList) self.onLayoutFinish.append(self.currentNetworkSettings) self.checkwlanDeviceListTimer = eTimer() self.checkwlanDeviceListTimer.callback.append( self.WirelessDeviceNotDetectedMsg) def checkwlanDeviceList(self): if len(self.wlanDeviceList) == 0: self.checkwlanDeviceListTimer.start(100, True) def WirelessDeviceNotDetectedMsg(self): self.session.openWithCallback( self.close, MessageBox, _("Wireless Lan Device is not detected."), MessageBox.TYPE_ERROR) def currentNetworkSettings(self): self["IPAddress"].setText( self.formatAddr(iNetwork.getAdapterAttribute("br0", "ip"))) self["Netmask"].setText( self.formatAddr(iNetwork.getAdapterAttribute("br0", "netmask"))) self["Gateway"].setText( self.formatAddr(iNetwork.getAdapterAttribute("br0", "gateway"))) def formatAddr(self, address=[0, 0, 0, 0]): if address is None: return "N/A" return "%d:%d:%d:%d" % (address[0], address[1], address[2], address[3]) def checkRunHostapd(self): global apModeConfig if fileExists("/var/run/hostapd", 0): apModeConfig.useap.value = True def makeConfigList(self): global apModeConfig self.hostapdConfigList = {} self.hostapdConfigList["interface"] = apModeConfig.wirelessdevice self.hostapdConfigList["bridge"] = apModeConfig.branch # "br0" self.hostapdConfigList["driver"] = apModeConfig.driver # "nl80211" self.hostapdConfigList["hw_mode"] = apModeConfig.wirelessmode self.hostapdConfigList["channel"] = apModeConfig.channel self.hostapdConfigList["ssid"] = apModeConfig.ssid self.hostapdConfigList["beacon_int"] = apModeConfig.beacon self.hostapdConfigList["rts_threshold"] = apModeConfig.rts_threshold self.hostapdConfigList[ "fragm_threshold"] = apModeConfig.fragm_threshold self.hostapdConfigList["preamble"] = apModeConfig.preamble # self.hostapdConfigList["macaddr_acl"] = "" # fix to add Access Control List Editer # self.hostapdConfigList["accept_mac_file"] = "" # fix to add Access Control List Editer # self.hostapdConfigList["deny_mac_file"] = "" # fix to add Access Control List Editer self.hostapdConfigList[ "ignore_broadcast_ssid"] = apModeConfig.ignore_broadcast_ssid # self.hostapdConfigList["wmm_enabled"] = "" # self.hostapdConfigList["ieee80211n"] = "" # self.hostapdConfigList["ht_capab"] = "" self.hostapdConfigList[ "wep_default_key"] = apModeConfig.wep_default_key self.hostapdConfigList["wep_key0"] = apModeConfig.wep_key0 self.hostapdConfigList["wpa"] = apModeConfig.wpa self.hostapdConfigList["wpa_passphrase"] = apModeConfig.wpa_passphrase self.hostapdConfigList[ "wpa_key_mgmt"] = apModeConfig.wpa_key_mgmt # "WPA-PSK" self.hostapdConfigList[ "wpa_pairwise"] = apModeConfig.wpa_pairwise # "TKIP CCMP" self.hostapdConfigList[ "rsn_pairwise"] = apModeConfig.rsn_pairwise # "CCMP" self.hostapdConfigList["wpa_group_rekey"] = apModeConfig.wpagrouprekey def loadInterfacesConfig(self): global apModeConfig try: fp = file('/etc/network/interfaces', 'r') datas = fp.readlines() fp.close() except: printDebugMsg("interfaces - file open failed") # check br0 configuration current_iface = "" ifaceConf = {} try: for line in datas: split = line.strip().split(' ') if (split[0] == "iface"): current_iface = split[1] if (current_iface == "br0") and (len(split) == 4 and split[3] == "dhcp"): apModeConfig.usedhcp.value = True else: apModeConfig.usedhcp.value = False if (current_iface == "br0" or current_iface == "eth0"): if (split[0] == "address"): apModeConfig.address.value = map( int, split[1].split('.')) if (split[0] == "netmask"): apModeConfig.netmask.value = map( int, split[1].split('.')) if (split[0] == "gateway"): apModeConfig.gateway.value = map( int, split[1].split('.')) except: printDebugMsg( "configuration parsing error! - /etc/network/interfaces") def loadHostapConfig(self): hostapdConf = {} ret = self.wirelessAP.loadHostapConfig(hostapdConf) if ret != 0: printDebugMsg("configuration opening failed!!") return for (key, value) in hostapdConf.items(): if key == "config.wep": apModeConfig.wep.value = int(value) elif key in [ "channel", "beacon_int", "rts_threshold", "fragm_threshold", "wpa_group_rekey" ]: self.hostapdConfigList[key].value = int(value) elif key in self.hostapdConfigList.keys(): self.hostapdConfigList[key].value = value if key == "channel" and int(value) not in range(14): self.hostapdConfigList[key].value = 1 # for key in self.hostapdConfigList.keys(): # printDebugMsg("[cofigList] key : %s, value : %s"%(key, str(self.hostapdConfigList[key].value)) ) def setupCurrentEncryption(self): if apModeConfig.wpa.value is not "0" and apModeConfig.wpa_passphrase.value: # (1,WPA), (2,WPA2), (3,WPA/WPA2) apModeConfig.encrypt.value = True apModeConfig.method.value = apModeConfig.wpa.value elif apModeConfig.wep.value and apModeConfig.wep_key0.value: apModeConfig.encrypt.value = True apModeConfig.method.value = "0" if len(apModeConfig.wep_key0.value) > 10: apModeConfig.wepType.value = "128" else: apModeConfig.encrypt.value = False def createConfigEntry(self): global apModeConfig #hostap settings self.useApEntry = getConfigListEntry(_("Use AP Mode"), apModeConfig.useap) self.setupModeEntry = getConfigListEntry(_("Setup Mode"), apModeConfig.setupmode) self.wirelessDeviceEntry = getConfigListEntry( _("AP Device"), apModeConfig.wirelessdevice) self.wirelessModeEntry = getConfigListEntry(_("AP Mode"), apModeConfig.wirelessmode) self.channelEntry = getConfigListEntry(_("Channel (1~13)"), apModeConfig.channel) self.ssidEntry = getConfigListEntry(_("SSID (1~32 Characters)"), apModeConfig.ssid) self.beaconEntry = getConfigListEntry(_("Beacon (15~65535)"), apModeConfig.beacon) self.rtsThresholdEntry = getConfigListEntry( _("RTS Threshold (0~2347)"), apModeConfig.rts_threshold) self.fragmThresholdEntry = getConfigListEntry( _("FRAGM Threshold (256~2346)"), apModeConfig.fragm_threshold) self.prambleEntry = getConfigListEntry(_("Preamble"), apModeConfig.preamble) self.ignoreBroadcastSsid = getConfigListEntry( _("Ignore Broadcast SSID"), apModeConfig.ignore_broadcast_ssid) # hostap encryption self.encryptEntry = getConfigListEntry(_("Encrypt"), apModeConfig.encrypt) self.methodEntry = getConfigListEntry(_("Method"), apModeConfig.method) self.wepKeyTypeEntry = getConfigListEntry(_("KeyType"), apModeConfig.wepType) self.wepKey0Entry = getConfigListEntry(_("WEP Key (HEX)"), apModeConfig.wep_key0) self.wpaKeyEntry = getConfigListEntry(_("KEY (8~63 Characters)"), apModeConfig.wpa_passphrase) self.groupRekeyEntry = getConfigListEntry(_("Group Rekey Interval"), apModeConfig.wpagrouprekey) # interface settings self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), apModeConfig.usedhcp) self.ipEntry = getConfigListEntry(_("IP Address"), apModeConfig.address) self.netmaskEntry = getConfigListEntry(_("NetMask"), apModeConfig.netmask) self.gatewayEntry = getConfigListEntry(_("Gateway"), apModeConfig.gateway) def createConfig(self): global apModeConfig self.configList = [] self.configList.append(self.useApEntry) if apModeConfig.useap.value is True: self.configList.append(self.setupModeEntry) self.configList.append(self.wirelessDeviceEntry) self.configList.append(self.wirelessModeEntry) self.configList.append(self.channelEntry) self.configList.append(self.ssidEntry) if apModeConfig.setupmode.value is "advanced": self.configList.append(self.beaconEntry) self.configList.append(self.rtsThresholdEntry) self.configList.append(self.fragmThresholdEntry) self.configList.append(self.prambleEntry) self.configList.append(self.ignoreBroadcastSsid) self.configList.append(self.encryptEntry) if apModeConfig.encrypt.value is True: self.configList.append(self.methodEntry) if apModeConfig.method.value is "0": # wep self.configList.append(self.wepKeyTypeEntry) self.configList.append(self.wepKey0Entry) else: self.configList.append(self.wpaKeyEntry) if apModeConfig.setupmode.value is "advanced": self.configList.append(self.groupRekeyEntry) ## set network interfaces self.configList.append(self.usedhcpEntry) if apModeConfig.usedhcp.value is False: self.configList.append(self.ipEntry) self.configList.append(self.netmaskEntry) self.configList.append(self.gatewayEntry) self["config"].list = self.configList self["config"].l.setList(self.configList) def keyLeft(self): ConfigListScreen.keyLeft(self) self.newConfig() def keyRight(self): ConfigListScreen.keyRight(self) self.newConfig() def newConfig(self): if self["config"].getCurrent() in [ self.encryptEntry, self.methodEntry, self.useApEntry, self.usedhcpEntry, self.setupModeEntry ]: self.createConfig() def doConfigMsg(self): try: self.session.openWithCallback( self.doConfig, MessageBox, (_("Are you sure you want to setup your AP?\n\n"))) except: printDebugMsg("doConfig failed") def doConfig(self, ret=False): global apModeConfig if ret is not True: return if apModeConfig.useap.value is True and apModeConfig.encrypt.value is True: if not self.checkEncrypKey(): return if not self.checkConfig(): return self.configStartMsg = self.session.openWithCallback( self.ConfigFinishedMsg, MessageBox, _("Please wait for AP Configuration....\n"), type=MessageBox.TYPE_INFO, enable_input=False) if apModeConfig.useap.value is True: self.networkRestart(nextFunc=self.makeConf) else: self.networkRestart(nextFunc=self.removeConf) def checkEncrypKey(self): if apModeConfig.method.value == "0": if self.checkWep(apModeConfig.wep_key0.value) is False: self.session.open(MessageBox, _("Invalid WEP key\n\n"), type=MessageBox.TYPE_ERROR, timeout=10) else: return True else: if not len(apModeConfig.wpa_passphrase.value) in range(8, 65): self.session.open(MessageBox, _("Invalid WPA key\n\n"), type=MessageBox.TYPE_ERROR, timeout=10) else: return True return False def checkWep(self, key): length = len(key) if length == 0: return False elif apModeConfig.wepType.value == "64" and length == 10: return True elif apModeConfig.wepType.value == "128" and length == 26: return True else: return False def checkConfig(self): # ssid Check if len(apModeConfig.ssid.value) == 0 or len( apModeConfig.ssid.value) > 32: self.session.open(MessageBox, _("Invalid SSID\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.channel.value not in range(1, 14): self.session.open(MessageBox, _("Invalid channel\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.beacon.value < 15 or apModeConfig.beacon.value > 65535: self.session.open(MessageBox, _("Invalid beacon\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.rts_threshold.value < 0 or apModeConfig.rts_threshold.value > 2347: self.session.open(MessageBox, _("Invalid RTS Threshold\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.fragm_threshold.value < 256 or apModeConfig.fragm_threshold.value > 2346: self.session.open(MessageBox, _("Invalid Fragm Threshold\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False elif apModeConfig.wpagrouprekey.value < 0 or apModeConfig.wpagrouprekey.value > 3600: self.session.open(MessageBox, _("Invalid wpagrouprekey\n"), type=MessageBox.TYPE_ERROR, timeout=10) return False return True def networkRestart(self, nextFunc=None): self.networkRestart_stop(nextFunc=nextFunc) def networkRestart_stop(self, nextFunc=None): printDebugMsg("networkRestart_stop") self.msgPlugins(False) self.commands = [] # stop current network self.networkRestartConsole = Console() self.commands.append("/etc/init.d/avahi-daemon stop") for iface in iNetwork.getAdapterList(): if iface != 'eth0' or not iNetwork.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface) self.commands.append("/etc/init.d/hostapd stop") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.networkRestartConsole.eBatch(self.commands, nextFunc, debug=True) def makeConf(self, extra_args): printDebugMsg("makeConf") self.writeNetworkInterfaces() result = self.writeHostapdConfig() if result == -1: self.configStartMsg.close(False) return self.setIpForward(1) self.networkRestart_start() def removeConf(self, extra_args): printDebugMsg("removeConf") if fileExists("/etc/hostapd.conf", 0): os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back") fp = file("/etc/network/interfaces", 'w') fp.write( "# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") if apModeConfig.usedhcp.value is True: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value)) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value)) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value)) fp.close() self.setIpForward(0) self.networkRestart_start() def networkRestart_start(self): printDebugMsg("networkRestart_start") self.restartConsole = Console() self.commands = [] self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.commands.append("/etc/init.d/hostapd start") self.restartConsole.eBatch(self.commands, self.networkRestartFinished, debug=True) def networkRestartFinished(self, data): printDebugMsg("networkRestartFinished") iNetwork.removeAdapterAttribute('br0', "ip") iNetwork.removeAdapterAttribute('br0', "netmask") iNetwork.removeAdapterAttribute('br0', "gateway") iNetwork.getInterfaces(self.getInterfacesDataAvail) def getInterfacesDataAvail(self, data): if data is True and self.configStartMsg is not None: self.configStartMsg.close(True) def ConfigFinishedMsg(self, ret): if ret is True: self.session.openWithCallback( self.ConfigFinishedMsgCallback, MessageBox, _("Configuration your AP is finished"), type=MessageBox.TYPE_INFO, timeout=5, default=False) else: self.session.openWithCallback(self.close, MessageBox, _("Invalid model or Image."), MessageBox.TYPE_ERROR) def ConfigFinishedMsgCallback(self, data): self.close() def msgPlugins(self, reason=False): for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=reason) def writeNetworkInterfaces(self): global apModeConfig fp = file("/etc/network/interfaces", 'w') fp.write( "# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") fp.write("iface eth0 inet manual\n") fp.write(" up ip link set $IFACE up\n") fp.write(" down ip link set $IFACE down\n\n") # Wireless device setup fp.write("auto %s\n" % apModeConfig.wirelessdevice.value) fp.write("iface %s inet manual\n" % apModeConfig.wirelessdevice.value) fp.write(" up ip link set $IFACE up\n") fp.write(" down ip link set $IFACE down\n") # branch setup fp.write("auto br0\n") if apModeConfig.usedhcp.value is True: fp.write("iface br0 inet dhcp\n") else: fp.write("iface br0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value)) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value)) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value)) fp.write(" pre-up brctl addbr br0\n") fp.write(" pre-up brctl addif br0 eth0\n") # fp.write(" pre-up brctl addif br0 wlan0\n") // runned by hostpad fp.write(" post-down brctl delif br0 eth0\n") # fp.write(" post-down brctl delif br0 wlan0\n") // runned by hostpad fp.write(" post-down brctl delbr br0\n\n") fp.write("\n") fp.close() def writeHostapdConfig(self): #c++ global apModeConfig configDict = {} for key in self.hostapdConfigList.keys(): configDict[key] = str(self.hostapdConfigList[key].value) configDict["config.encrypt"] = str(int(apModeConfig.encrypt.value)) configDict["config.method"] = apModeConfig.method.value ret = self.wirelessAP.writeHostapdConfig(configDict) if (ret != 0): return -1 return 0 def setIpForward(self, setValue=0): ipForwardFilePath = "/proc/sys/net/ipv4/ip_forward" if not fileExists(ipForwardFilePath): return -1 printDebugMsg("set %s to %d" % (ipForwardFilePath, setValue)) f = open(ipForwardFilePath, "w") f.write("%d" % setValue) f.close() sysctlPath = "/etc/sysctl.conf" sysctlLines = [] if fileExists(sysctlPath): fp = file(sysctlPath, "r") sysctlLines = fp.readlines() fp.close() sysctlList = {} for line in sysctlLines: line = line.strip() (key, value) = line.split("=") key = key.strip() value = value.strip() sysctlList[key] = value sysctlList["net.ipv4.ip_forward"] = str(setValue) fp = file(sysctlPath, "w") for (key, value) in sysctlList.items(): fp.write("%s=%s\n" % (key, value)) fp.close() return 0 def checkWirelessDevices(self): global apModeConfig self.wlanDeviceList = [] wlanIfaces = [] for x in iNetwork.getInstalledAdapters(): if x.startswith('eth') or x.startswith('br') or x.startswith( 'mon'): continue wlanIfaces.append(x) description = self.getAdapterDescription(x) if description == "Unknown network adapter": self.wlanDeviceList.append((x, x)) else: self.wlanDeviceList.append((x, description + " (%s)" % x)) apModeConfig.wirelessdevice = ConfigSelection( choices=self.wlanDeviceList) def getAdapterDescription(self, iface): classdir = "/sys/class/net/" + iface + "/device/" driverdir = "/sys/class/net/" + iface + "/device/driver/" if os_path.exists(classdir): files = listdir(classdir) if 'driver' in files: if os_path.realpath(driverdir).endswith('rtw_usb_drv'): return _("Realtek") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('ath_pci'): return _("Atheros") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('zd1211b'): return _("Zydas") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73'): return _("Ralink") + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73usb'): return _("Ralink") + " " + _("WLAN adapter.") else: return str(os_path.basename( os_path.realpath(driverdir))) + " " + _("WLAN adapter") else: return _("Unknown network adapter") else: return _("Unknown network adapter") def __onClose(self): for x in self["config"].list: x[1].cancel() apModeConfig.wpa.value = "0" apModeConfig.wep.value = False def keyCancel(self): self.close()
class WirelessAccessPoint(Screen,ConfigListScreen): skin = """ <screen position="center,center" size="590,450" title="Wireless Access Point" > <ePixmap pixmap="skin_default/buttons/red.png" position="20,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="160,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="300,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="440,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" /> <widget source="key_blue" render="Label" position="440,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" /> <widget name="config" zPosition="2" position="10,70" size="580,270" scrollbarMode="showOnDemand" transparent="1" /> <widget source="current_settings" render="Label" position="10,340" size="570,20" font="Regular;19" halign="center" valign="center" transparent="1" /> <widget source="IPAddress_text" render="Label" position="130,370" size="190,21" font="Regular;19" transparent="1" /> <widget source="Netmask_text" render="Label" position="130,395" size="190,21" font="Regular;19" transparent="1" /> <widget source="Gateway_text" render="Label" position="130,420" size="190,21" font="Regular;19" transparent="1" /> <widget source="IPAddress" render="Label" position="340,370" size="240,21" font="Regular;19" transparent="1" /> <widget source="Netmask" render="Label" position="340,395" size="240,21" font="Regular;19" transparent="1" /> <widget source="Gateway" render="Label" position="340,420" size="240,21" font="Regular;19" transparent="1" /> </screen>""" def __init__(self,session): Screen.__init__(self,session) self.session = session self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ], { "ok": self.doConfigMsg, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.doConfigMsg, }, -2) self.list = [] ConfigListScreen.__init__(self, self.list,session = self.session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Ok")) self["key_yellow"] = StaticText(_(" ")) self["key_blue"] = StaticText(_(" ")) self["current_settings"] = StaticText(_("Current settings (interface : br0)")) self["IPAddress_text"] = StaticText(_("IP Address")) self["Netmask_text"] = StaticText(_("Netmask")) self["Gateway_text"] = StaticText(_("Gateway")) self["IPAddress"] = StaticText(_("N/A")) self["Netmask"] = StaticText(_("N/A")) self["Gateway"] = StaticText(_("N/A")) self.wirelessAP = wirelessap.wirelessAP() self.checkRunHostapd() self.checkWirelessDevices() self.makeConfigList() self.loadInterfacesConfig() self.loadHostapConfig() self.setupCurrentEncryption() self.createConfigEntry() self.createConfig() self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.checkwlanDeviceList) self.onLayoutFinish.append(self.currentNetworkSettings) self.checkwlanDeviceListTimer = eTimer() self.checkwlanDeviceListTimer.callback.append(self.WirelessDeviceNotDetectedMsg) def checkwlanDeviceList(self): if len(self.wlanDeviceList) == 0: self.checkwlanDeviceListTimer.start(100,True) def WirelessDeviceNotDetectedMsg(self): self.session.openWithCallback(self.close ,MessageBox, _("Wireless Lan Device is not detected."), MessageBox.TYPE_ERROR) def currentNetworkSettings(self): self["IPAddress"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "ip"))) self["Netmask"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "netmask"))) self["Gateway"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "gateway"))) def formatAddr(self, address = [0,0,0,0]): if address is None: return "N/A" return "%d:%d:%d:%d"%(address[0],address[1],address[2],address[3]) def checkRunHostapd(self): global apModeConfig if fileExists("/var/run/hostapd", 0): apModeConfig.useap.value = True def makeConfigList(self): global apModeConfig self.hostapdConfigList = {} self.hostapdConfigList["interface"] = apModeConfig.wirelessdevice self.hostapdConfigList["bridge"] = apModeConfig.branch # "br0" self.hostapdConfigList["driver"] = apModeConfig.driver # "nl80211" self.hostapdConfigList["hw_mode"] = apModeConfig.wirelessmode self.hostapdConfigList["channel"] = apModeConfig.channel self.hostapdConfigList["ssid"] = apModeConfig.ssid self.hostapdConfigList["beacon_int"] = apModeConfig.beacon self.hostapdConfigList["rts_threshold"] = apModeConfig.rts_threshold self.hostapdConfigList["fragm_threshold"] = apModeConfig.fragm_threshold self.hostapdConfigList["preamble"] = apModeConfig.preamble # self.hostapdConfigList["macaddr_acl"] = "" # fix to add Access Control List Editer # self.hostapdConfigList["accept_mac_file"] = "" # fix to add Access Control List Editer # self.hostapdConfigList["deny_mac_file"] = "" # fix to add Access Control List Editer self.hostapdConfigList["ignore_broadcast_ssid"] = apModeConfig.ignore_broadcast_ssid # self.hostapdConfigList["wmm_enabled"] = "" # self.hostapdConfigList["ieee80211n"] = "" # self.hostapdConfigList["ht_capab"] = "" self.hostapdConfigList["wep_default_key"] = apModeConfig.wep_default_key self.hostapdConfigList["wep_key0"] = apModeConfig.wep_key0 self.hostapdConfigList["wpa"] = apModeConfig.wpa self.hostapdConfigList["wpa_passphrase"] = apModeConfig.wpa_passphrase self.hostapdConfigList["wpa_key_mgmt"] = apModeConfig.wpa_key_mgmt # "WPA-PSK" self.hostapdConfigList["wpa_pairwise"] = apModeConfig.wpa_pairwise # "TKIP CCMP" self.hostapdConfigList["rsn_pairwise"] = apModeConfig.rsn_pairwise # "CCMP" self.hostapdConfigList["wpa_group_rekey"] = apModeConfig.wpagrouprekey def loadInterfacesConfig(self): global apModeConfig try: fp = file('/etc/network/interfaces', 'r') datas = fp.readlines() fp.close() except: printDebugMsg("interfaces - file open failed") # check br0 configuration current_iface = "" ifaceConf = {} try: for line in datas: split = line.strip().split(' ') if (split[0] == "iface"): current_iface = split[1] if (current_iface == "br0") and (len(split) == 4 and split[3] == "dhcp"): apModeConfig.usedhcp.value = True else: apModeConfig.usedhcp.value = False if (current_iface == "br0" or current_iface == "eth0"): if (split[0] == "address"): apModeConfig.address.value = map(int, split[1].split('.')) if (split[0] == "netmask"): apModeConfig.netmask.value = map(int, split[1].split('.')) if (split[0] == "gateway"): apModeConfig.gateway.value = map(int, split[1].split('.')) except: printDebugMsg("configuration parsing error! - /etc/network/interfaces") def loadHostapConfig(self): hostapdConf = { } ret = self.wirelessAP.loadHostapConfig(hostapdConf) if ret != 0: printDebugMsg("configuration opening failed!!") return for (key,value) in hostapdConf.items(): if key == "config.wep": apModeConfig.wep.value = int(value) elif key in ["channel", "beacon_int", "rts_threshold", "fragm_threshold", "wpa_group_rekey"]: self.hostapdConfigList[key].value = int(value) elif key in self.hostapdConfigList.keys(): self.hostapdConfigList[key].value = value if key == "channel" and int(value) not in range(14): self.hostapdConfigList[key].value = 1 # for key in self.hostapdConfigList.keys(): # printDebugMsg("[cofigList] key : %s, value : %s"%(key, str(self.hostapdConfigList[key].value)) ) def setupCurrentEncryption(self): if apModeConfig.wpa.value is not "0" and apModeConfig.wpa_passphrase.value: # (1,WPA), (2,WPA2), (3,WPA/WPA2) apModeConfig.encrypt.value = True apModeConfig.method.value = apModeConfig.wpa.value elif apModeConfig.wep.value and apModeConfig.wep_key0.value: apModeConfig.encrypt.value = True apModeConfig.method.value = "0" if len(apModeConfig.wep_key0.value) > 10: apModeConfig.wepType.value = "128" else: apModeConfig.encrypt.value = False def createConfigEntry(self): global apModeConfig #hostap settings self.useApEntry = getConfigListEntry(_("Use AP Mode"), apModeConfig.useap) self.setupModeEntry = getConfigListEntry(_("Setup Mode"), apModeConfig.setupmode) self.wirelessDeviceEntry = getConfigListEntry(_("AP Device"), apModeConfig.wirelessdevice) self.wirelessModeEntry = getConfigListEntry(_("AP Mode"), apModeConfig.wirelessmode) self.channelEntry = getConfigListEntry(_("Channel (1~13)"), apModeConfig.channel) self.ssidEntry = getConfigListEntry(_("SSID (1~32 Characters)"), apModeConfig.ssid) self.beaconEntry = getConfigListEntry(_("Beacon (15~65535)"), apModeConfig.beacon) self.rtsThresholdEntry = getConfigListEntry(_("RTS Threshold (0~2347)"), apModeConfig.rts_threshold) self.fragmThresholdEntry = getConfigListEntry(_("FRAGM Threshold (256~2346)"), apModeConfig.fragm_threshold) self.prambleEntry = getConfigListEntry(_("Preamble"), apModeConfig.preamble) self.ignoreBroadcastSsid = getConfigListEntry(_("Ignore Broadcast SSID"), apModeConfig.ignore_broadcast_ssid) # hostap encryption self.encryptEntry = getConfigListEntry(_("Encrypt"), apModeConfig.encrypt) self.methodEntry = getConfigListEntry(_("Method"), apModeConfig.method) self.wepKeyTypeEntry = getConfigListEntry(_("KeyType"), apModeConfig.wepType) self.wepKey0Entry = getConfigListEntry(_("WEP Key (HEX)"), apModeConfig.wep_key0) self.wpaKeyEntry = getConfigListEntry(_("KEY (8~63 Characters)"), apModeConfig.wpa_passphrase) self.groupRekeyEntry = getConfigListEntry(_("Group Rekey Interval"), apModeConfig.wpagrouprekey) # interface settings self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), apModeConfig.usedhcp) self.ipEntry = getConfigListEntry(_("IP Address"), apModeConfig.address) self.netmaskEntry = getConfigListEntry(_("NetMask"), apModeConfig.netmask) self.gatewayEntry = getConfigListEntry(_("Gateway"), apModeConfig.gateway) def createConfig(self): global apModeConfig self.configList = [] self.configList.append( self.useApEntry ) if apModeConfig.useap.value is True: self.configList.append( self.setupModeEntry ) self.configList.append( self.wirelessDeviceEntry ) self.configList.append( self.wirelessModeEntry ) self.configList.append( self.channelEntry ) self.configList.append( self.ssidEntry ) if apModeConfig.setupmode.value is "advanced": self.configList.append( self.beaconEntry ) self.configList.append( self.rtsThresholdEntry ) self.configList.append( self.fragmThresholdEntry ) self.configList.append( self.prambleEntry ) self.configList.append( self.ignoreBroadcastSsid ) self.configList.append( self.encryptEntry ) if apModeConfig.encrypt.value is True: self.configList.append( self.methodEntry ) if apModeConfig.method.value is "0": # wep self.configList.append( self.wepKeyTypeEntry ) self.configList.append( self.wepKey0Entry ) else: self.configList.append( self.wpaKeyEntry ) if apModeConfig.setupmode.value is "advanced": self.configList.append( self.groupRekeyEntry ) ## set network interfaces self.configList.append( self.usedhcpEntry ) if apModeConfig.usedhcp.value is False: self.configList.append( self.ipEntry ) self.configList.append( self.netmaskEntry ) self.configList.append( self.gatewayEntry ) self["config"].list = self.configList self["config"].l.setList(self.configList) def keyLeft(self): ConfigListScreen.keyLeft(self) self.newConfig() def keyRight(self): ConfigListScreen.keyRight(self) self.newConfig() def newConfig(self): if self["config"].getCurrent() in [ self.encryptEntry, self.methodEntry, self.useApEntry, self.usedhcpEntry, self.setupModeEntry]: self.createConfig() def doConfigMsg(self): try: self.session.openWithCallback(self.doConfig, MessageBox, (_("Are you sure you want to setup your AP?\n\n") ) ) except: printDebugMsg("doConfig failed") def doConfig(self, ret = False): global apModeConfig if ret is not True: return if apModeConfig.useap.value is True and apModeConfig.encrypt.value is True: if not self.checkEncrypKey(): return if not self.checkConfig(): return self.configStartMsg = self.session.openWithCallback(self.ConfigFinishedMsg, MessageBox, _("Please wait for AP Configuration....\n") , type = MessageBox.TYPE_INFO, enable_input = False) if apModeConfig.useap.value is True: self.networkRestart( nextFunc = self.makeConf ) else: self.networkRestart( nextFunc = self.removeConf ) def checkEncrypKey(self): if apModeConfig.method.value == "0": if self.checkWep(apModeConfig.wep_key0.value) is False: self.session.open(MessageBox, _("Invalid WEP key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10 ) else: return True else: if not len(apModeConfig.wpa_passphrase.value) in range(8,65): self.session.open(MessageBox, _("Invalid WPA key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10) else: return True return False def checkWep(self, key): length = len(key) if length == 0: return False elif apModeConfig.wepType.value == "64" and length == 10: return True elif apModeConfig.wepType.value == "128" and length == 26: return True else: return False def checkConfig(self): # ssid Check if len(apModeConfig.ssid.value) == 0 or len(apModeConfig.ssid.value) > 32: self.session.open(MessageBox, _("Invalid SSID\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.channel.value not in range(1,14): self.session.open(MessageBox, _("Invalid channel\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.beacon.value < 15 or apModeConfig.beacon.value > 65535: self.session.open(MessageBox, _("Invalid beacon\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.rts_threshold.value < 0 or apModeConfig.rts_threshold.value > 2347: self.session.open(MessageBox, _("Invalid RTS Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.fragm_threshold.value < 256 or apModeConfig.fragm_threshold.value > 2346: self.session.open(MessageBox, _("Invalid Fragm Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.wpagrouprekey.value < 0 or apModeConfig.wpagrouprekey.value > 3600: self.session.open(MessageBox, _("Invalid wpagrouprekey\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; return True; def networkRestart(self, nextFunc = None ): self.networkRestart_stop( nextFunc = nextFunc ) def networkRestart_stop(self, nextFunc = None ): printDebugMsg("networkRestart_stop") self.msgPlugins(False) self.commands = [] # stop current network self.networkRestartConsole = Console() self.commands.append("/etc/init.d/avahi-daemon stop") for iface in iNetwork.getAdapterList(): if iface != 'eth0' or not iNetwork.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface) self.commands.append("/etc/init.d/hostapd stop") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.networkRestartConsole.eBatch(self.commands, nextFunc, debug = True) def makeConf(self,extra_args): printDebugMsg("makeConf") self.writeNetworkInterfaces() result = self.writeHostapdConfig() if result == -1: self.configStartMsg.close(False) return self.setIpForward(1) self.networkRestart_start() def removeConf(self,extra_args): printDebugMsg("removeConf") if fileExists("/etc/hostapd.conf", 0): os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back") fp = file("/etc/network/interfaces", 'w') fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") if apModeConfig.usedhcp.value is True: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) ) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) ) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) ) fp.close() self.setIpForward(0) self.networkRestart_start() def networkRestart_start(self): printDebugMsg("networkRestart_start") self.restartConsole = Console() self.commands = [] self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.commands.append("/etc/init.d/hostapd start") self.restartConsole.eBatch(self.commands, self.networkRestartFinished, debug=True) def networkRestartFinished(self, data): printDebugMsg("networkRestartFinished") iNetwork.removeAdapterAttribute('br0',"ip") iNetwork.removeAdapterAttribute('br0',"netmask") iNetwork.removeAdapterAttribute('br0',"gateway") iNetwork.getInterfaces(self.getInterfacesDataAvail) def getInterfacesDataAvail(self, data): if data is True and self.configStartMsg is not None: self.configStartMsg.close(True) def ConfigFinishedMsg(self, ret): if ret is True: self.session.openWithCallback(self.ConfigFinishedMsgCallback ,MessageBox, _("Configuration your AP is finished"), type = MessageBox.TYPE_INFO, timeout = 5, default = False) else: self.session.openWithCallback(self.close ,MessageBox, _("Invalid model or Image."), MessageBox.TYPE_ERROR) def ConfigFinishedMsgCallback(self,data): self.close() def msgPlugins(self,reason = False): for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=reason) def writeNetworkInterfaces(self): global apModeConfig fp = file("/etc/network/interfaces", 'w') fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") fp.write("iface eth0 inet manual\n") fp.write(" up ip link set $IFACE up\n") fp.write(" down ip link set $IFACE down\n\n") # Wireless device setup fp.write("auto %s\n" % apModeConfig.wirelessdevice.value) fp.write("iface %s inet manual\n" % apModeConfig.wirelessdevice.value) fp.write(" up ip link set $IFACE up\n") fp.write(" down ip link set $IFACE down\n") # branch setup fp.write("auto br0\n") if apModeConfig.usedhcp.value is True: fp.write("iface br0 inet dhcp\n") else: fp.write("iface br0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) ) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) ) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) ) fp.write(" pre-up brctl addbr br0\n") fp.write(" pre-up brctl addif br0 eth0\n") # fp.write(" pre-up brctl addif br0 wlan0\n") // runned by hostpad fp.write(" post-down brctl delif br0 eth0\n") # fp.write(" post-down brctl delif br0 wlan0\n") // runned by hostpad fp.write(" post-down brctl delbr br0\n\n") fp.write("\n") fp.close() def writeHostapdConfig(self): #c++ global apModeConfig configDict = {} for key in self.hostapdConfigList.keys(): configDict[key] = str(self.hostapdConfigList[key].value) configDict["config.encrypt"] = str(int(apModeConfig.encrypt.value)) configDict["config.method"] = apModeConfig.method.value ret = self.wirelessAP.writeHostapdConfig(configDict) if(ret != 0): return -1 return 0 def setIpForward(self, setValue = 0): ipForwardFilePath = "/proc/sys/net/ipv4/ip_forward" if not fileExists(ipForwardFilePath): return -1 printDebugMsg("set %s to %d" % (ipForwardFilePath, setValue)) f = open(ipForwardFilePath, "w") f.write("%d" % setValue) f.close() sysctlPath = "/etc/sysctl.conf" sysctlLines = [] if fileExists(sysctlPath): fp = file(sysctlPath, "r") sysctlLines = fp.readlines() fp.close() sysctlList = {} for line in sysctlLines: line = line.strip() (key,value) = line.split("=") key=key.strip() value=value.strip() sysctlList[key] = value sysctlList["net.ipv4.ip_forward"] = str(setValue) fp = file(sysctlPath, "w") for (key,value) in sysctlList.items(): fp.write("%s=%s\n"%(key,value)) fp.close() return 0 def checkWirelessDevices(self): global apModeConfig self.wlanDeviceList = [] wlanIfaces =[] for x in iNetwork.getInstalledAdapters(): if x.startswith('eth') or x.startswith('br') or x.startswith('mon'): continue wlanIfaces.append(x) description=self.getAdapterDescription(x) if description == "Unknown network adapter": self.wlanDeviceList.append((x, x)) else: self.wlanDeviceList.append(( x, description + " (%s)"%x )) apModeConfig.wirelessdevice = ConfigSelection( choices = self.wlanDeviceList ) def getAdapterDescription(self, iface): classdir = "/sys/class/net/" + iface + "/device/" driverdir = "/sys/class/net/" + iface + "/device/driver/" if os_path.exists(classdir): files = listdir(classdir) if 'driver' in files: if os_path.realpath(driverdir).endswith('rtw_usb_drv'): return _("Realtek")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('ath_pci'): return _("Atheros")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('zd1211b'): return _("Zydas")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73'): return _("Ralink")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73usb'): return _("Ralink")+ " " + _("WLAN adapter.") else: return str(os_path.basename(os_path.realpath(driverdir))) + " " + _("WLAN adapter") else: return _("Unknown network adapter") else: return _("Unknown network adapter") def __onClose(self): for x in self["config"].list: x[1].cancel() apModeConfig.wpa.value = "0" apModeConfig.wep.value = False def keyCancel(self): self.close()
class AutoMount(): def __init__(self): self.automounts = {} self.restartConsole = Console() self.MountConsole = Console() self.removeConsole = Console() self.activeMountsCounter = 0 self.callback = None self.timer = eTimer() self.timer.callback.append(self.mountTimeout) self.getAutoMountPoints() return def getAutoMountPoints(self, callback=None, restart=False): automounts = [] self.automounts = {} self.activeMountsCounter = 0 if not os.path.exists(XML_FSTAB): return else: file = open(XML_FSTAB, 'r') tree = cet_parse(file).getroot() file.close() def getValue(definitions, default): ret = '' Len = len(definitions) return Len > 0 and definitions[Len - 1].text or default mountusing = 0 for autofs in tree.findall('autofs'): mountusing = 1 for nfs in autofs.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'autofs'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/media/hdd/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e for cifs in autofs.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'autofs'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/media/hdd/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue( mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue( mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e for fstab in tree.findall('fstab'): mountusing = 2 for nfs in fstab.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'fstab'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/media/hdd/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e for cifs in fstab.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'fstab'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/media/hdd/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue( mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue( mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e for enigma2 in tree.findall('enigma2'): mountusing = 3 for nfs in enigma2.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'enigma2'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e for cifs in enigma2.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'enigma2'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue( mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue( mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e if mountusing == 0: for nfs in tree.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'old_enigma2'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e for cifs in tree.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'old_enigma2'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data[ 'active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue( mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue( mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue( mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', e self.checkList = self.automounts.keys() if not self.checkList: if callback is not None: callback(True) else: self.CheckMountPoint(self.checkList.pop(), callback, restart) return def sanitizeOptions(self, origOptions, cifs=False, fstab=False, autofs=False): options = origOptions.strip() options = options.replace('utf8', 'iocharset=utf8') if fstab: if not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=8192,wsize=8192,proto=tcp' elif not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' options = options + ',timeo=14,soft' elif autofs: if not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=8192,wsize=8192' elif not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' options = options + ',timeo=14,soft' elif not options: options = 'rw,rsize=8192,wsize=8192' if not cifs: options += ',proto=tcp' elif not cifs: if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' return options def CheckMountPoint(self, item, callback, restart): data = self.automounts[item] if not self.MountConsole: self.MountConsole = Console() command = [] mountcommand = None unmountcommand = [] if data['mountusing'] == 'autofs': path = os.path.join('/media/autofs', data['sharename']) elif data['hdd_replacement'] == 'True' or data[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', data['sharename']) if data['mountusing'] == 'autofs' and restart: unmountcommand.append('/etc/init.d/autofs stop') if os.path.ismount(path) and 'autofs' not in path: unmountcommand.append('umount -fl ' + path) if self.activeMountsCounter != 0: if data['active'] == 'True' or data['active'] is True: if data['mountusing'] == 'autofs' and restart: mountcommand = '/etc/init.d/autofs start' elif data['mountusing'] == 'fstab': if data['mounttype'] == 'nfs': tmpcmd = 'mount ' + data['ip'] + ':/' + data['sharedir'] elif data['mounttype'] == 'cifs': tmpcmd = 'mount //' + data['ip'] + '/' + data[ 'sharedir'] mountcommand = tmpcmd.encode('UTF-8') elif data['mountusing'] == 'enigma2' or data[ 'mountusing'] == 'old_enigma2': tmpsharedir = data['sharedir'].replace(' ', '\\ ') if tmpsharedir[-1:] == '$': tmpdir = tmpsharedir.replace('$', '\\$') tmpsharedir = tmpdir if data['mounttype'] == 'nfs': if not os.path.ismount(path): tmpcmd = 'mount -t nfs -o ' + self.sanitizeOptions( data['options']) + ' ' + data[ 'ip'] + ':/' + tmpsharedir + ' ' + path mountcommand = tmpcmd.encode('UTF-8') elif data['mounttype'] == 'cifs': if not os.path.ismount(path): tmpusername = data['username'].replace(' ', '\\ ') tmpcmd = 'mount -t cifs -o ' + self.sanitizeOptions( data['options'], cifs=True ) + ',noatime,noserverino,username='******',password='******'password'] + ' //' + data[ 'ip'] + '/' + tmpsharedir + ' ' + path mountcommand = tmpcmd.encode('UTF-8') if len(unmountcommand) > 0 or mountcommand is not None: if len(unmountcommand) > 0: for x in unmountcommand: command.append(x) if not os.path.exists(path) and data['mountusing'] != 'autofs': command.append('mkdir -p ' + path) if command is not None: command.append('sleep 2') if mountcommand is not None: command.append(mountcommand) print 'command', command self.MountConsole.eBatch(command, self.CheckMountPointFinished, [data, callback, restart], debug=True) else: self.CheckMountPointFinished([data, callback, restart]) return def CheckMountPointFinished(self, extra_args): data, callback, restart = extra_args hdd_dir = '/media/hdd' sharepath = os.path.join('/media/net', data['sharename']) if data['mountusing'] == 'autofs': sharepath = os.path.join('/media/autofs', data['sharename']) path = os.path.join('/media/autofs', data['sharename']) elif data['hdd_replacement'] == 'True' or data[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', data['sharename']) if os.path.exists(path): if data['mountusing'] == 'autofs': if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(sharepath, desc) if data['hdd_replacement'] == 'True' or data[ 'hdd_replacement'] is True: if os.path.islink(hdd_dir): if os.readlink(hdd_dir) != path: os.unlink(hdd_dir) os.symlink(path, hdd_dir) elif not os.path.exists(hdd_dir): os.symlink(path, hdd_dir) elif os.path.ismount(path): if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(path, desc) else: if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = False if os.path.exists(path): if not os.path.ismount(path): try: rmtree(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print 'Failed to remove', path, 'Error:', ex if self.checkList: self.CheckMountPoint(self.checkList.pop(), callback, restart) if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1) return def mountTimeout(self): self.timer.stop() if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if self.callback is not None: self.callback(True) elif self.removeConsole: if len(self.removeConsole.appContainers) == 0: if self.callback is not None: self.callback(True) return def getMountsList(self): return self.automounts def getMountsAttribute(self, mountpoint, attribute): if self.automounts.has_key(mountpoint): if self.automounts[mountpoint].has_key(attribute): return self.automounts[mountpoint][attribute] return None def setMountsAttribute(self, mountpoint, attribute, value): if self.automounts.has_key(mountpoint): self.automounts[mountpoint][attribute] = value def removeEntryFromFile(self, entry, filename, separator=None): if os.path.exists(filename): f = open(filename) tmpfile = open(filename + '.tmp', 'w') tmpfile.writelines([ line for line in f.readlines() if entry not in line.split(separator) ]) tmpfile.close() f.close() os.rename(filename + '.tmp', filename) def escape(self, data): return data.replace('&', '&').replace('<', '<').replace( '>', '>').replace('"', '"').replace("'", ''') def generateMountXML(self, sharedata): res = [] mounttype = self.escape(sharedata['mounttype']) mountusing = self.escape(sharedata['mountusing']) if mountusing != 'old_enigma2': res.append('<' + mountusing + '>\n') res.append(' <' + mounttype + '>\n') res.append(' <mount>\n') res.append(' <active>' + self.escape(str(sharedata['active'])) + '</active>\n') res.append(' <hdd_replacement>' + self.escape(str(sharedata['hdd_replacement'])) + '</hdd_replacement>\n') res.append(' <ip>' + self.escape(sharedata['ip']) + '</ip>\n') res.append(' <sharename>' + self.escape(sharedata['sharename']) + '</sharename>\n') res.append(' <sharedir>' + self.escape(sharedata['sharedir']) + '</sharedir>\n') res.append(' <options>' + self.escape(sharedata['options']) + '</options>\n') if mounttype == 'cifs': res.append(' <username>' + self.escape(sharedata['username']) + '</username>\n') res.append(' <password>' + self.escape(sharedata['password']) + '</password>\n') res.append(' </mount>\n') res.append(' </' + mounttype + '>\n') if mountusing != 'old_enigma2': res.append('</' + mountusing + '>\n') return res def writeMountsConfig(self): list = ['<?xml version="1.0" ?>\n<mountmanager>\n'] for sharename, sharedata in self.automounts.items(): mounttype = sharedata['mounttype'] mountusing = sharedata['mountusing'] if sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', sharedata['sharename']) else: path = os.path.join('/media/net', sharedata['sharename']) sharepath = '' sharetemp = None if mounttype == 'nfs': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] self.removeEntryFromFile(sharetemp + '\n', '/etc/auto.network', ' ') self.removeEntryFromFile(sharetemp, '/etc/fstab') elif mounttype == 'cifs': sharetemp = '//' + sharedata['ip'] + '/' + sharedata['sharedir'] self.removeEntryFromFile(':' + sharetemp + '\n', '/etc/auto.network', ' ') self.removeEntryFromFile(sharetemp, '/etc/fstab') list += self.generateMountXML(sharedata) if mountusing == 'autofs': if sharedata['active'] == True or sharedata['active'] == 'True': out = open('/etc/auto.network', 'a') if mounttype == 'nfs': line = sharedata[ 'sharename'] + ' -fstype=' + mounttype + ',' + self.sanitizeOptions( sharedata['options'], autofs=True) + ' ' + sharedata[ 'ip'] + ':/' + sharedata['sharedir'] + '\n' elif sharedata['mounttype'] == 'cifs': tmpusername = sharedata['username'].replace(' ', '\\ ') tmppassword = sharedata['password'].replace(' ', '\\ ') tmpaddress = sharedata['ip'] line = sharedata[ 'sharename'] + ' -fstype=' + mounttype + ',user='******',pass='******',' + self.sanitizeOptions( sharedata['options'], cifs=True, autofs=True ) + ' ://' + tmpaddress + '/' + sharedata[ 'sharedir'] + '\n' out.write(line) out.close() elif mountusing == 'fstab': if sharedata['active'] == True or sharedata['active'] == 'True': out = open('/etc/fstab', 'a') if sharedata['mounttype'] == 'nfs': line = sharedata['ip'] + ':/' + sharedata[ 'sharedir'] + '\t' + path + '\tnfs\t_netdev,' + self.sanitizeOptions( sharedata['options'], fstab=True) + '\t0 0\n' elif sharedata['mounttype'] == 'cifs': line = '//' + sharedata['ip'] + '/' + sharedata[ 'sharedir'] + '\t' + path + '\tcifs\tuser='******'username'] + ',pass='******'password'] + ',_netdev,' + self.sanitizeOptions( sharedata['options'], cifs=True, fstab=True) + '\t0 0\n' out.write(line) out.close() list.append('</mountmanager>\n') try: f = open(XML_FSTAB, 'w') f.writelines(list) f.close() except Exception as e: print '[NetworkBrowser] Error Saving Mounts List:', e return def stopMountConsole(self): if self.MountConsole is not None: self.MountConsole = None return def removeMount(self, mountpoint, callback=None): self.newautomounts = {} for sharename, sharedata in self.automounts.items(): sharepath = os.path.join('/media/net', sharedata['sharename']) if sharedata['mountusing'] == 'autofs': sharepath = os.path.join('/media/autofs', sharedata['sharename']) path = os.path.join('/media/autofs', sharedata['sharename']) if sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: if os.path.islink('/media/hdd'): if os.readlink('/media/hdd') == path: os.unlink('/media/hdd') elif sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', sharedata['sharename']) if sharename is not mountpoint.strip(): self.newautomounts[sharename] = sharedata if sharedata['mounttype'] == 'nfs': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] elif sharedata['mounttype'] == 'cifs': sharetemp = '://' + sharedata['ip'] + '/' + sharedata[ 'sharedir'] if sharetemp: self.removeEntryFromFile(sharetemp + '\n', '/etc/auto.network', ' ') self.removeEntryFromFile(sharetemp, '/etc/fstab') self.automounts.clear() self.automounts = self.newautomounts if not self.removeConsole: self.removeConsole = Console() command = [] autofsstop = None if sharedata['mountusing'] == 'autofs': command.append('/etc/init.d/autofs stop') command.append('sleep 2') command.append('/etc/init.d/autofs start') else: command.append('umount -fl ' + path) self.removeConsole.eBatch(command, self.removeMountPointFinished, [path, callback], debug=True) return def removeMountPointFinished(self, extra_args): path, callback = extra_args if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print 'Failed to remove', path, 'Error:', ex if self.removeConsole: if len(self.removeConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1) return
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: 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', 'sys0', 'p2p0', 'tunl0') 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 = 'busybox ip -o addr show dev ' + iface + ' | grep -v inet6' 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.has_key('dns-nameservers') 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 self.onlyWoWifaces.has_key(ifacename): WoW = self.onlyWoWifaces[ifacename] if WoW == False and iface['up'] == True: fp.write('auto ' + ifacename + '\n') self.configuredInterfaces.append(ifacename) self.onlyWoWifaces[ifacename] = False elif WoW == True: self.onlyWoWifaces[ifacename] = True fp.write('#only WakeOnWiFi ' + ifacename + '\n') if iface['dhcp']: fp.write('iface ' + ifacename + ' inet dhcp\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] 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] 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: 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.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' elif name.startswith('brcm') or name.startswith('bcm'): 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 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 openspa.info' cmd2 = 'ping -c 1 duckduckgo.com' cmd3 = 'ping -c 1 www.linuxfoundation.org' 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 openspa.info' cmd2 = 'nslookup duckduckgo.com' cmd3 = 'nslookup www.linuxfoundation.org' 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 if os.path.isdir(self.sysfsPath(iface) + '/wireless'): return True 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 canWakeOnWiFi(self, iface): if self.sysfsPath(iface) == '/sys/class/net/wlan3' and os.path.exists( '/tmp/bcm/%s' % iface): return True def getWlanModuleDir(self, iface=None): if self.sysfsPath(iface) == '/sys/class/net/wlan3' and os.path.exists( '/tmp/bcm/%s' % iface): devicedir = self.sysfsPath('sys0') + '/device' else: devicedir = self.sysfsPath(iface) + '/device' moduledir = devicedir + '/driver/module' if os.path.isdir(moduledir): return moduledir try: 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 except: pass 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 ('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): 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 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 = re.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: result.extend(self.nameservers) return result
class AutoMount(): """Manages Mounts declared in a XML-Document.""" def __init__(self): self.automounts = {} self.restartConsole = Console() self.MountConsole = Console() self.removeConsole = Console() self.activeMountsCounter = 0 # Initialize Timer self.callback = None self.timer = eTimer() self.timer.callback.append(self.mountTimeout) self.autofsreload = None self.getAutoMountPoints() def makeAutoMountPoint(self, mountusing, mounttype, mount): def getValue(definitions, default): # Return last definition or default if none return definitions and definitions[-1].text or default try: default_options = default_mount_options[mounttype] default_sharedir = "/media/hdd/" if mounttype == 'cifs': username = getValue(mount.findall("username"), "guest").encode("UTF-8") password = getValue(mount.findall("password"), "").encode("UTF-8") else: username = False password = False data = { 'isMounted': False, 'mountusing': mountusing.encode("UTF-8"), 'mounttype': mounttype.encode("UTF-8"), 'active': getValue(mount.findall("active"), "False").encode("UTF-8"), 'hdd_replacement': getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8"), 'ip': getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8"), 'sharedir': getValue(mount.findall("sharedir"), default_sharedir).encode("UTF-8"), 'sharename': getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8"), 'options': getValue(mount.findall("options"), default_options).encode("UTF-8"), 'username': username, 'password': password, } except Exception as e: print("[MountManager] Error reading Mounts:", e) else: self.automounts[data['sharename']] = data if data["active"] is True or data["active"] == 'True': self.activeMountsCounter += 1 def getAutoMountPoints(self, callback=None, restart=False): # Initialize mounts to empty list self.automounts = {} self.activeMountsCounter = 0 if not os.path.exists(XML_FSTAB): return try: with open(XML_FSTAB, 'r') as f: tree = cet_parse(f).getroot() except: # Move a corrupt file out of the way os.rename(XML_FSTAB, XML_FSTAB + ".bad") return # Config is stored in "mountmanager" element for mountusing in ("autofs", "fstab", "enigma2"): for mountusingnode in tree.findall(mountusing): for mounttype in ("nfs", "cifs"): for fs in mountusingnode.findall(mounttype): for mount in fs.findall("mount"): self.makeAutoMountPoint(mountusing, mounttype, mount) # Process mounts using "old_enigma2" and convert them to "enigma2" old_enigma2_converted = False for mounttype in ("nfs", "cifs"): for fs in tree.findall(mounttype): for mount in fs.findall("mount"): old_enigma2_converted = True self.makeAutoMountPoint("enigma2", mounttype, mount) if old_enigma2_converted: self.writeAutoMountsXML() self.checkList = self.automounts.keys() if not self.checkList: # print("[NetworkBrowser] self.automounts without mounts", self.automounts) if callback is not None: callback(True) else: self.CheckMountPoint(self.checkList.pop(), callback, restart) def sanitizeOptions(self, origOptions, cifs=False, fstab=False, autofs=False): options = origOptions.strip().replace(" ", "") options = options.replace('utf8', 'iocharset=utf8') if fstab: if not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=8192,wsize=8192,proto=tcp' else: if not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' options = options + ',timeo=14,soft' elif autofs: if not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=8192,wsize=8192' else: if not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' options = options + ',timeo=14,soft' else: if not options: options = 'rw,rsize=8192,wsize=8192' if not cifs: options += ',proto=tcp' else: if not cifs: if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' if cifs: options += ",cache=loose" return options def CheckMountPoint(self, item, callback, restart): self.autofsreload = None self.doCheckMountPoint(item, callback, restart) def doCheckMountPoint(self, item, callback, restart): data = self.automounts[item] if not self.MountConsole: self.MountConsole = Console() command = [] mountcommand = None unmountcommand = [] if data['mountusing'] == 'autofs': path = os.path.join('/media/autofs', data['sharename']) elif data['hdd_replacement'] == 'True' or data[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', data['sharename']) if data['mountusing'] == 'autofs' and restart: self.autofsreload = "/etc/init.d/autofs reload" if os.path.ismount(path) and 'autofs' not in path: unmountcommand.append('umount -fl ' + path) if self.activeMountsCounter != 0: if data['active'] == 'True' or data['active'] is True: if data['mountusing'] == 'fstab': if data['mounttype'] == 'nfs': tmpcmd = 'mount ' + data['ip'] + ':/' + data['sharedir'] elif data['mounttype'] == 'cifs': tmpcmd = 'mount //' + data['ip'] + '/' + data[ 'sharedir'] mountcommand = tmpcmd.encode("UTF-8") elif data['mountusing'] == 'enigma2': tmpsharedir = data['sharedir'].replace(" ", "\\ ") if tmpsharedir[-1:] == "$": tmpdir = tmpsharedir.replace("$", "\\$") tmpsharedir = tmpdir if data['mounttype'] == 'nfs': tmpcmd = 'mount -t nfs -o ' + self.sanitizeOptions( data['options'] ) + ' ' + data['ip'] + ':/' + tmpsharedir + ' ' + path mountcommand = tmpcmd.encode("UTF-8") elif data['mounttype'] == 'cifs': tmpusername = data['username'].replace(" ", "\\ ") tmpcmd = 'mount -t cifs -o ' + \ self.sanitizeOptions(data['options'], cifs=True) + ',noatime,noserverino,' + \ 'username='******',password='******'password'] + \ ' //' + data['ip'] + '/' + tmpsharedir + ' ' + path mountcommand = tmpcmd.encode("UTF-8") for x in unmountcommand: command.append(x) if not os.path.exists(path) and data['mountusing'] != 'autofs': command.append('mkdir -p ' + path) if mountcommand: if command: command.append('sleep 2') command.append(mountcommand) if not self.checkList and self.autofsreload is not None: if command: command.append('sleep 2') command.append(self.autofsreload) self.autofsreload = None print('command', command) if command: self.MountConsole.eBatch(command, self.CheckMountPointFinished, [data, callback, restart], debug=True) else: self.CheckMountPointFinished([data, callback, restart]) def CheckMountPointFinished(self, extra_args): # print("[NetworkBrowser] CheckMountPointFinished") (data, callback, restart) = extra_args hdd_dir = '/media/hdd' sharepath = os.path.join('/media/net', data['sharename']) if data['mountusing'] == 'autofs': sharepath = os.path.join('/media/autofs', data['sharename']) path = os.path.join('/media/autofs', data['sharename']) elif data['hdd_replacement'] == 'True' or data[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', data['sharename']) if os.path.exists(path): if data['mountusing'] == 'autofs': if data['sharename'] in self.automounts: self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(sharepath, desc) if data['hdd_replacement'] == 'True' or data[ 'hdd_replacement'] is True: if os.path.islink(hdd_dir): if os.readlink(hdd_dir) != path: os.unlink(hdd_dir) os.symlink(path, hdd_dir) elif not os.path.exists(hdd_dir): os.symlink(path, hdd_dir) elif os.path.ismount(path): if data['sharename'] in self.automounts: self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(path, desc) else: if data['sharename'] in self.automounts: self.automounts[data['sharename']]['isMounted'] = False if os.path.exists(path): if not os.path.ismount(path): try: rmtree(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print("Failed to remove", path, "Error:", ex) if self.checkList: # Go to next item in list... self.doCheckMountPoint(self.checkList.pop(), callback, restart) if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1) def mountTimeout(self): self.timer.stop() if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if self.callback is not None: self.callback(True) elif self.removeConsole: if len(self.removeConsole.appContainers) == 0: if self.callback is not None: self.callback(True) def getMountsList(self): return self.automounts def getMountsAttribute(self, mountpoint, attribute): if mountpoint in self.automounts: if attribute in self.automounts[mountpoint]: return self.automounts[mountpoint][attribute] return None def setMountsAttribute(self, mountpoint, attribute, value): if mountpoint in self.automounts: self.automounts[mountpoint][attribute] = value def removeEntryFromFile(self, entry, filename, separator=None): if os.path.exists(filename): f = open(filename) tmpfile = open(filename + '.tmp', 'w') tmpfile.writelines([ line for line in f.readlines() if entry not in line.split(separator) ]) tmpfile.close() f.close() os.rename(filename + '.tmp', filename) def escape(self, data): return data.replace('&', '&').replace('<', '<').replace( '>', '>').replace('"', '"').replace("'", ''') def removeEntryFromAutofsMap(self, key, location, filename): if os.path.exists(filename): f = open(filename) tmpfile = open(filename + '.tmp', 'w') for line in f.readlines(): parts = line.split(" ", 2) if len(parts) > 1: if parts[1].startswith("-") and len(parts) > 2: parts = parts[:1] + parts[2:] if parts[0] != key and parts[1] != location: tmpfile.write(line) tmpfile.close() f.close() os.rename(filename + '.tmp', filename) def generateMountXML(self, sharedata): res = [] mounttype = self.escape(sharedata['mounttype']) mountusing = self.escape(sharedata['mountusing']) res.append('<' + mountusing + '>\n') res.append(' <' + mounttype + '>\n') res.append(' <mount>\n') res.append(' <active>' + self.escape(str(sharedata['active'])) + '</active>\n') res.append(' <hdd_replacement>' + self.escape(str(sharedata['hdd_replacement'])) + '</hdd_replacement>\n') res.append(' <ip>' + self.escape(sharedata['ip']) + '</ip>\n') res.append(' <sharename>' + self.escape(sharedata['sharename']) + '</sharename>\n') res.append(' <sharedir>' + self.escape(sharedata['sharedir']) + '</sharedir>\n') res.append(' <options>' + self.escape(sharedata['options']) + '</options>\n') if mounttype == 'cifs': res.append(" <username>" + self.escape(sharedata['username']) + "</username>\n") res.append(" <password>" + self.escape(sharedata['password']) + "</password>\n") res.append(' </mount>\n') res.append(' </' + mounttype + '>\n') res.append('</' + mountusing + '>\n') return res def writeAutoMountsXML(self): # XML header & open Mountmanager Tag # Generate List in RAM xmldata = ['<?xml version="1.0" ?>\n<mountmanager>\n'] for sharedata in self.automounts.itervalues(): xmldata += self.generateMountXML(sharedata) # Close Mountmanager Tag xmldata.append('</mountmanager>\n') # Try Saving to Flash try: f = open(XML_FSTAB, "w") f.writelines(xmldata) f.close() # print("[NetworkBrowser] Saving Mounts List:") except Exception as e: print("[NetworkBrowser] Error Saving Mounts List:", e) def writeMountsConfig(self): self.writeAutoMountsXML() for sharedata in self.automounts.itervalues(): mounttype = sharedata['mounttype'] mountusing = sharedata['mountusing'] if sharedata['hdd_replacement'] is True or sharedata[ 'hdd_replacement'] == 'True': # hdd replacement hack path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', sharedata['sharename']) sharetemp = None if mounttype == 'nfs': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] self.removeEntryFromAutofsMap(sharedata['sharename'], sharetemp + '\n', AUTOFS_NET) self.removeEntryFromFile(sharetemp, FSTAB) elif mounttype == 'cifs': sharetemp = '//' + sharedata['ip'] + '/' + sharedata['sharedir'] self.removeEntryFromAutofsMap(sharedata['sharename'], ":" + sharetemp + '\n', AUTOFS_NET) self.removeEntryFromFile(sharetemp, FSTAB) if mountusing == 'autofs': if sharedata['active'] is True or sharedata['active'] == 'True': out = open(AUTOFS_NET, 'a') if mounttype == 'nfs': line = sharedata['sharename'] + ' -fstype=' + mounttype + ',' + \ self.sanitizeOptions(sharedata['options'], autofs=True) + \ ' ' + sharedata['ip'] + ':/' + sharedata['sharedir'] + '\n' elif sharedata['mounttype'] == 'cifs': tmpusername = sharedata['username'].replace(" ", "\ ") tmppassword = sharedata['password'].replace(" ", "\ ") tmpaddress = sharedata['ip'] line = sharedata['sharename'] + ' -fstype=' + mounttype + \ ',user='******',pass='******',' + \ self.sanitizeOptions(sharedata['options'], cifs=True, autofs=True) + \ ' ://' + tmpaddress + '/' + sharedata['sharedir'] + '\n' out.write(line) out.close() elif mountusing == 'fstab': if sharedata['active'] is True or sharedata['active'] == 'True': out = open(FSTAB, 'a') if sharedata['mounttype'] == 'nfs': line = sharedata['ip'] + ':/' + sharedata['sharedir'] + '\t' + path + \ '\tnfs\t_netdev,' + self.sanitizeOptions(sharedata['options'], fstab=True) + '\t0 0\n' elif sharedata['mounttype'] == 'cifs': line = '//' + sharedata['ip'] + '/' + sharedata['sharedir'] + '\t' + path + \ '\tcifs\tuser='******'username'] + ',pass='******'password'] + \ ',_netdev,' + self.sanitizeOptions(sharedata['options'], cifs=True, fstab=True) + '\t0 0\n' out.write(line) out.close() def stopMountConsole(self): if self.MountConsole is not None: self.MountConsole = None def removeMount(self, mountpoint, callback=None): # print("[NetworkBrowser] removing mount: ", mountpoint) self.newautomounts = {} for sharename, sharedata in self.automounts.items(): if sharedata['mountusing'] == 'autofs': path = os.path.join('/media/autofs', sharedata['sharename']) if sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: if os.path.islink('/media/hdd'): if os.readlink('/media/hdd') == path: os.unlink('/media/hdd') elif sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', sharedata['sharename']) if sharename is not mountpoint.strip(): self.newautomounts[sharename] = sharedata if sharedata['mounttype'] == 'nfs': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] elif sharedata['mounttype'] == 'cifs': sharetemp = '://' + sharedata['ip'] + '/' + sharedata[ 'sharedir'] if sharetemp: self.removeEntryFromAutofsMap(sharedata['sharename'], sharetemp + '\n', AUTOFS_NET) self.removeEntryFromFile(sharetemp, FSTAB) self.automounts.clear() self.automounts = self.newautomounts if not self.removeConsole: self.removeConsole = Console() command = [] if sharedata['mountusing'] == 'autofs': # With a short sleep to allow time for the reload command.append("/etc/init.d/autofs reload; sleep 2") else: command.append('umount -fl ' + path) # print("[NetworkBrowser] UMOUNT-CMD--->", umountcmd) self.removeConsole.eBatch(command, self.removeMountPointFinished, [path, callback], debug=True) def removeMountPointFinished(self, extra_args): (path, callback) = extra_args if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print("Failed to remove", path, "Error:", ex) if self.removeConsole: if len(self.removeConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1)
class AutoMount(): def __init__(self): self.automounts = {} self.restartConsole = Console() self.MountConsole = Console() self.removeConsole = Console() self.activeMountsCounter = 0 self.callback = None self.timer = eTimer() self.timer.callback.append(self.mountTimeout) self.getAutoMountPoints() def getAutoMountPoints(self, callback=None): automounts = [] self.automounts = {} self.activeMountsCounter = 0 if not os.path.exists(XML_FSTAB): return file = open(XML_FSTAB, 'r') tree = cet_parse(file).getroot() file.close() def getValue(definitions, default): ret = '' Len = len(definitions) return Len > 0 and definitions[(Len - 1)].text or default mountusing = 0 for fstab in tree.findall('fstab'): mountusing = 1 for nfs in fstab.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'fstab'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for cifs in fstab.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'fstab'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue(mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue(mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for enigma2 in tree.findall('enigma2'): mountusing = 2 for nfs in enigma2.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'enigma2'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for cifs in enigma2.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'enigma2'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue(mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue(mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e if mountusing == 0: for nfs in tree.findall('nfs'): for mount in nfs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'old_enigma2'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue( mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for cifs in tree.findall('cifs'): for mount in cifs.findall('mount'): data = { 'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False } try: data['mountusing'] = 'old_enigma2'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue( mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue( mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue( mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue(mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue(mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e self.checkList = self.automounts.keys() if not self.checkList: print '[NetworkBrowser] self.automounts without mounts', print self.automounts if callback is not None: callback(True) else: self.CheckMountPoint(self.checkList.pop(), callback) def sanitizeOptions(self, origOptions, cifs=False, fstab=False): options = origOptions.strip() if not fstab: if not options: options = 'rw,rsize=32768,wsize=32768' if not cifs: options += ',proto=tcp' elif not cifs: if 'rsize' not in options: options += ',rsize=32768' if 'wsize' not in options: options += ',wsize=32768' if not cifs and 'tcp' not in options and 'udp' not in options: options += ',tcp' elif not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=32768,wsize=32768,proto=tcp' elif not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=32768' if 'wsize' not in options: options += ',wsize=32768' if 'tcp' not in options and 'udp' not in options: options += ',tcp' options = options + ',timeo=14,fg,soft,intr' options = options.replace('tcp', 'proto=tcp') options = options.replace('udp', 'proto=udp') options = options.replace('utf8', 'iocharset=utf8') return options def CheckMountPoint(self, item, callback): data = self.automounts[item] if not self.MountConsole: self.MountConsole = Console() self.command = [] self.mountcommand = None self.unmountcommand = None if data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', data['sharename']) else: path = os.path.join('/media/net', data['sharename']) sharepath = '' if os.path.ismount(path): self.unmountcommand = 'umount -fl ' + path if sharepath and os.path.ismount(sharepath): self.unmountcommand = self.unmountcommand + ' && umount -fl ' + sharepath if self.activeMountsCounter != 0: if data['active'] == 'True' or data['active'] is True: if data['mountusing'] == 'fstab': if data['mounttype'] == 'nfs': tmpcmd = 'mount ' + data['ip'] + ':/' + data['sharedir'] elif data['mounttype'] == 'cifs': tmpcmd = 'mount //' + data['ip'] + '/' + data[ 'sharedir'] self.mountcommand = tmpcmd.encode('UTF-8') elif data['mountusing'] == 'enigma2' or data[ 'mountusing'] == 'old_enigma2': tmpsharedir = data['sharedir'].replace(' ', '\\ ') if tmpsharedir[-1:] == '$': tmpdir = tmpsharedir.replace('$', '\\$') tmpsharedir = tmpdir if data['mounttype'] == 'nfs': if not os.path.ismount(path): tmpcmd = 'mount -t nfs -o ' + self.sanitizeOptions( data['options']) + ' ' + data[ 'ip'] + ':/' + tmpsharedir + ' ' + path print 'MOUNT CMD', print tmpcmd self.mountcommand = tmpcmd.encode('UTF-8') elif data['mounttype'] == 'cifs': if not os.path.ismount(path): tmpusername = data['username'].replace(' ', '\\ ') tmpcmd = 'mount -t cifs -o ' + self.sanitizeOptions( data['options'], cifs=True ) + ',noatime,noserverino,username='******',password='******'password'] + ' //' + data[ 'ip'] + '/' + tmpsharedir + ' ' + path self.mountcommand = tmpcmd.encode('UTF-8') if self.unmountcommand is not None or self.mountcommand is not None: if self.unmountcommand is not None: self.command.append(self.unmountcommand) if self.mountcommand is not None: if not os.path.exists(path): self.command.append('mkdir -p ' + path) self.command.append(self.mountcommand) self.MountConsole.eBatch(self.command, self.CheckMountPointFinished, [data, callback], debug=True) else: self.CheckMountPointFinished([data, callback]) def CheckMountPointFinished(self, extra_args): ( data, callback, ) = extra_args if data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', data['sharename']) else: path = os.path.join('/media/net', data['sharename']) sharepath = '' if os.path.exists(path): if os.path.ismount(path): if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(path, desc) else: if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = False if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print 'Failed to remove', print path, print 'Error:', print ex if self.checkList: self.CheckMountPoint(self.checkList.pop(), callback) if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1) def mountTimeout(self): self.timer.stop() if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if self.callback is not None: self.callback(True) elif self.removeConsole: if len(self.removeConsole.appContainers) == 0: if self.callback is not None: self.callback(True) def getMountsList(self): return self.automounts def getMountsAttribute(self, mountpoint, attribute): if self.automounts.has_key(mountpoint): if self.automounts[mountpoint].has_key(attribute): return self.automounts[mountpoint][attribute] def setMountsAttribute(self, mountpoint, attribute, value): if self.automounts.has_key(mountpoint): self.automounts[mountpoint][attribute] = value def writeMountsConfig(self): list = ['<?xml version="1.0" ?>\n<mountmanager>\n'] for ( sharename, sharedata, ) in self.automounts.items(): if sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', sharedata['sharename']) else: path = os.path.join('/media/net', sharedata['sharename']) sharepath = '' if sharedata['mountusing'] == 'fstab': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] + ' ' tmpfile = open('/etc/fstab.tmp', 'w') file = open('/etc/fstab') tmpfile.writelines( [l for l in file.readlines() if sharetemp not in l]) tmpfile.close() file.close() os.rename('/etc/fstab.tmp', '/etc/fstab') mtype = sharedata['mounttype'] list.append('<fstab>\n') list.append(' <' + mtype + '>\n') list.append(' <mount>\n') list.append(' <active>' + str(sharedata['active']) + '</active>\n') list.append(' <hdd_replacement>' + str(sharedata['hdd_replacement']) + '</hdd_replacement>\n') list.append(' <ip>' + sharedata['ip'] + '</ip>\n') list.append(' <sharename>' + sharedata['sharename'] + '</sharename>\n') list.append(' <sharedir>' + sharedata['sharedir'] + '</sharedir>\n') list.append(' <options>' + sharedata['options'] + '</options>\n') if sharedata['mounttype'] == 'cifs': list.append(' <username>' + sharedata['username'] + '</username>\n') list.append(' <password>' + sharedata['password'] + '</password>\n') list.append(' </mount>\n') list.append(' </' + mtype + '>\n') list.append('</fstab>\n') out = open('/etc/fstab', 'a') if sharedata['mounttype'] == 'nfs': line = sharedata['ip'] + ':/' + sharedata[ 'sharedir'] + ' ' + path + '\tnfs\t_netdev,' + self.sanitizeOptions( sharedata['options'], fstab=True) + '\t0 0\n' elif sharedata['mounttype'] == 'cifs': line = '//' + sharedata['ip'] + '/' + sharedata[ 'sharedir'] + ' ' + path + '\tcifs\tusername='******'username'] + ',password='******'password'] + ',_netdev,' + self.sanitizeOptions( sharedata['options'], cifs=True, fstab=True) + '\t0 0\n' out.write(line) out.close() elif sharedata['mountusing'] == 'enigma2': mtype = sharedata['mounttype'] list.append('<enigma2>\n') list.append(' <' + mtype + '>\n') list.append(' <mount>\n') list.append(' <active>' + str(sharedata['active']) + '</active>\n') list.append(' <hdd_replacement>' + str(sharedata['hdd_replacement']) + '</hdd_replacement>\n') list.append(' <ip>' + sharedata['ip'] + '</ip>\n') list.append(' <sharename>' + sharedata['sharename'] + '</sharename>\n') list.append(' <sharedir>' + sharedata['sharedir'] + '</sharedir>\n') list.append(' <options>' + sharedata['options'] + '</options>\n') if sharedata['mounttype'] == 'cifs': list.append(' <username>' + sharedata['username'] + '</username>\n') list.append(' <password>' + sharedata['password'] + '</password>\n') list.append(' </mount>\n') list.append(' </' + mtype + '>\n') list.append('</enigma2>\n') elif sharedata['mountusing'] == 'old_enigma2': mtype = sharedata['mounttype'] list.append(' <' + mtype + '>\n') list.append(' <mount>\n') list.append(' <active>' + str(sharedata['active']) + '</active>\n') list.append(' <hdd_replacement>' + str(sharedata['hdd_replacement']) + '</hdd_replacement>\n') list.append(' <ip>' + sharedata['ip'] + '</ip>\n') list.append(' <sharename>' + sharedata['sharename'] + '</sharename>\n') list.append(' <sharedir>' + sharedata['sharedir'] + '</sharedir>\n') list.append(' <options>' + sharedata['options'] + '</options>\n') if sharedata['mounttype'] == 'cifs': list.append(' <username>' + sharedata['username'] + '</username>\n') list.append(' <password>' + sharedata['password'] + '</password>\n') list.append(' </mount>\n') list.append(' </' + mtype + '>\n') list.append('</mountmanager>\n') try: f = open(XML_FSTAB, 'w') f.writelines(list) f.close() except Exception as e: print '[NetworkBrowser] Error Saving Mounts List:', print e def stopMountConsole(self): if self.MountConsole is not None: self.MountConsole = None def removeMount(self, mountpoint, callback=None): self.newautomounts = {} path = '' for ( sharename, sharedata, ) in self.automounts.items(): if sharedata['hdd_replacement'] == 'True' or sharedata[ 'hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', sharedata['sharename']) else: path = os.path.join('/media/net', sharedata['sharename']) sharepath = '' if sharename is not mountpoint.strip(): self.newautomounts[sharename] = sharedata if sharedata['mountusing'] == 'fstab': tmpfile = open('/etc/fstab.tmp', 'w') file = open('/etc/fstab') tmpfile.writelines([ l for l in file.readlines() if sharedata['sharedir'] not in l ]) tmpfile.close() file.close() os.rename('/etc/fstab.tmp', '/etc/fstab') self.automounts.clear() self.automounts = self.newautomounts if not self.removeConsole: self.removeConsole = Console() umountcmd = 'umount -fl ' + path self.removeConsole.ePopen(umountcmd, self.removeMountPointFinished, [path, callback]) def removeMountPointFinished(self, result, retval, extra_args): ( path, callback, ) = extra_args if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print 'Failed to remove', print path, print 'Error:', print ex if self.removeConsole: if len(self.removeConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1)
class NetworkSamba(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Samba Setup")) self.skinName = "NetworkSamba" self.onChangedEntry = [ ] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['key_green'] = Label(_("Start")) self['key_red'] = Label(_("Remove Service")) self['key_yellow'] = Label(_("Autostart")) self['key_blue'] = Label(_("Show Log")) self.Console = Console() self.my_Samba_active = False self.my_Samba_run = False self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.SambaStartStop, 'yellow': self.activateSamba, 'blue': self.Sambashowlog}) self.service_name = basegroup + '-smbfs-server' self.onLayoutFinish.append(self.InstallCheck) def InstallCheck(self): self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def checkNetworkState(self, str, retval, extra_args): if 'Collected errors' in str: self.session.openWithCallback(self.close, MessageBox, _("A background update check is in progress, please wait a few minutes and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif not str: self.feedscheck = self.session.open(MessageBox,_('Please wait while feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False) self.feedscheck.setTitle(_('Checking Feeds')) cmd1 = "opkg update" self.CheckConsole = Console() self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished) else: self.updateService() def checkNetworkStateFinished(self, result, retval,extra_args=None): if 'bad address' in result: self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your %s %s is not connected to the internet, please check your network settings and try again.") % (getMachineBrand(), getMachineName()), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif ('wget returned 1' or 'wget returned 255' or '404 Not Found') in result: self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) else: self.session.openWithCallback(self.QuestionCallback, MessageBox,_('Your %s %s will be restarted after the installation of service.\nReady to install %s ?') % (getMachineBrand(), getMachineName(), self.service_name), MessageBox.TYPE_YESNO) def QuestionCallback(self, val): if val: self.session.openWithCallback(self.InstallPackage, MessageBox, _('Do you want to also install samba client?\nThis allows you to mount your windows shares on this device.'), MessageBox.TYPE_YESNO) else: self.feedscheck.close() self.close() def InstallPackage(self, val): if val: self.service_name = self.service_name + ' ' + basegroup + '-smbfs-client' self.doInstall(self.installComplete, self.service_name) def InstallPackageFailed(self, val): self.feedscheck.close() self.close() def doInstall(self, callback, pkgname): self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False) self.message.setTitle(_('Installing Service')) self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback) def installComplete(self,result = None, retval = None, extra_args = None): self.session.open(TryQuitMainloop, 2) def UninstallCheck(self): self.service_name = self.service_name + ' ' + basegroup + '-smbfs-client' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail) def RemovedataAvail(self, str, retval, extra_args): if str: restartbox = self.session.openWithCallback(self.RemovePackage,MessageBox,_('Your %s %s will be restarted after the removal of service.\nDo you want to remove now ?') % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO) restartbox.setTitle(_('Ready to remove %s ?') % self.service_name) else: self.updateService() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) def doRemove(self, callback, pkgname): self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False) self.message.setTitle(_('Removing Service')) self.Console.ePopen('/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback) def removeComplete(self,result = None, retval = None, extra_args = None): self.session.open(TryQuitMainloop, 2) def createSummary(self): return NetworkServicesSummary def Sambashowlog(self): self.session.open(NetworkSambaLog) def SambaStartStop(self): commands = [] if not self.my_Samba_run: commands.append('/etc/init.d/samba start') elif self.my_Samba_run: commands.append('/etc/init.d/samba stop') commands.append('killall nmbd') commands.append('killall smbd') self.Console.eBatch(commands, self.StartStopCallback, debug=True) def StartStopCallback(self, result = None, retval = None, extra_args = None): time.sleep(3) self.updateService() def activateSamba(self): commands = [] if fileExists('/etc/rc2.d/S20samba'): commands.append('update-rc.d -f samba remove') else: commands.append('update-rc.d -f samba defaults') self.Console.eBatch(commands, self.StartStopCallback, debug=True) def updateService(self): import process p = process.ProcessList() samba_process = str(p.named('smbd')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].setText(_("Disabled")) self.my_Samba_active = False if fileExists('/etc/rc2.d/S20samba'): self['labactive'].setText(_("Enabled")) self['labactive'].show() self.my_Samba_active = True self.my_Samba_run = False if samba_process: self.my_Samba_run = True if self.my_Samba_run: self['labstop'].hide() self['labactive'].show() self['labrun'].show() self['key_green'].setText(_("Stop")) status_summary = self['lab2'].text + ' ' + self['labrun'].text else: self['labrun'].hide() self['labstop'].show() self['labactive'].show() self['key_green'].setText(_("Start")) status_summary = self['lab2'].text + ' ' + self['labstop'].text title = _("Samba Setup") autostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary)
class AutoMount(): def __init__(self): self.automounts = {} self.restartConsole = Console() self.MountConsole = Console() self.removeConsole = Console() self.activeMountsCounter = 0 self.callback = None self.timer = eTimer() self.timer.callback.append(self.mountTimeout) self.getAutoMountPoints() def getAutoMountPoints(self, callback = None): automounts = [] self.automounts = {} self.activeMountsCounter = 0 if not os.path.exists(XML_FSTAB): return file = open(XML_FSTAB, 'r') tree = cet_parse(file).getroot() file.close() def getValue(definitions, default): ret = '' Len = len(definitions) return Len > 0 and definitions[(Len - 1)].text or default mountusing = 0 for fstab in tree.findall('fstab'): mountusing = 1 for nfs in fstab.findall('nfs'): for mount in nfs.findall('mount'): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'fstab'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue(mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue(mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for cifs in fstab.findall('cifs'): for mount in cifs.findall('mount'): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'fstab'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue(mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue(mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue(mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue(mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for enigma2 in tree.findall('enigma2'): mountusing = 2 for nfs in enigma2.findall('nfs'): for mount in nfs.findall('mount'): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'enigma2'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue(mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue(mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for cifs in enigma2.findall('cifs'): for mount in cifs.findall('mount'): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'enigma2'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue(mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue(mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue(mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue(mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e if mountusing == 0: for nfs in tree.findall('nfs'): for mount in nfs.findall('mount'): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'old_enigma2'.encode('UTF-8') data['mounttype'] = 'nfs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue(mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue(mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,nolock,tcp,utf8').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e for cifs in tree.findall('cifs'): for mount in cifs.findall('mount'): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'old_enigma2'.encode('UTF-8') data['mounttype'] = 'cifs'.encode('UTF-8') data['active'] = getValue(mount.findall('active'), False).encode('UTF-8') if data['active'] == 'True' or data['active'] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall('hdd_replacement'), 'False').encode('UTF-8') data['ip'] = getValue(mount.findall('ip'), '192.168.0.0').encode('UTF-8') data['sharedir'] = getValue(mount.findall('sharedir'), '/exports/').encode('UTF-8') data['sharename'] = getValue(mount.findall('sharename'), 'MEDIA').encode('UTF-8') data['options'] = getValue(mount.findall('options'), 'rw,utf8').encode('UTF-8') data['username'] = getValue(mount.findall('username'), 'guest').encode('UTF-8') data['password'] = getValue(mount.findall('password'), '').encode('UTF-8') self.automounts[data['sharename']] = data except Exception as e: print '[MountManager] Error reading Mounts:', print e self.checkList = self.automounts.keys() if not self.checkList: print '[NetworkBrowser] self.automounts without mounts', print self.automounts if callback is not None: callback(True) else: self.CheckMountPoint(self.checkList.pop(), callback) def sanitizeOptions(self, origOptions, cifs = False, fstab = False): options = origOptions.strip() if not fstab: if not options: options = 'rw,rsize=32768,wsize=32768' if not cifs: options += ',proto=tcp' elif not cifs: if 'rsize' not in options: options += ',rsize=32768' if 'wsize' not in options: options += ',wsize=32768' if not cifs and 'tcp' not in options and 'udp' not in options: options += ',tcp' elif not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=32768,wsize=32768,proto=tcp' elif not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=32768' if 'wsize' not in options: options += ',wsize=32768' if 'tcp' not in options and 'udp' not in options: options += ',tcp' options = options + ',timeo=14,fg,soft,intr' options = options.replace('tcp', 'proto=tcp') options = options.replace('udp', 'proto=udp') options = options.replace('utf8', 'iocharset=utf8') return options def CheckMountPoint(self, item, callback): data = self.automounts[item] if not self.MountConsole: self.MountConsole = Console() self.command = [] self.mountcommand = None self.unmountcommand = None if data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', data['sharename']) else: path = os.path.join('/media/net', data['sharename']) sharepath = '' if os.path.ismount(path): self.unmountcommand = 'umount -fl ' + path if sharepath and os.path.ismount(sharepath): self.unmountcommand = self.unmountcommand + ' && umount -fl ' + sharepath if self.activeMountsCounter != 0: if data['active'] == 'True' or data['active'] is True: if data['mountusing'] == 'fstab': if data['mounttype'] == 'nfs': tmpcmd = 'mount ' + data['ip'] + ':/' + data['sharedir'] elif data['mounttype'] == 'cifs': tmpcmd = 'mount //' + data['ip'] + '/' + data['sharedir'] self.mountcommand = tmpcmd.encode('UTF-8') elif data['mountusing'] == 'enigma2' or data['mountusing'] == 'old_enigma2': tmpsharedir = data['sharedir'].replace(' ', '\\ ') if tmpsharedir[-1:] == '$': tmpdir = tmpsharedir.replace('$', '\\$') tmpsharedir = tmpdir if data['mounttype'] == 'nfs': if not os.path.ismount(path): tmpcmd = 'mount -t nfs -o ' + self.sanitizeOptions(data['options']) + ' ' + data['ip'] + ':/' + tmpsharedir + ' ' + path print 'MOUNT CMD', print tmpcmd self.mountcommand = tmpcmd.encode('UTF-8') elif data['mounttype'] == 'cifs': if not os.path.ismount(path): tmpusername = data['username'].replace(' ', '\\ ') tmpcmd = 'mount -t cifs -o ' + self.sanitizeOptions(data['options'], cifs=True) + ',noatime,noserverino,username='******',password='******'password'] + ' //' + data['ip'] + '/' + tmpsharedir + ' ' + path self.mountcommand = tmpcmd.encode('UTF-8') if self.unmountcommand is not None or self.mountcommand is not None: if self.unmountcommand is not None: self.command.append(self.unmountcommand) if self.mountcommand is not None: if not os.path.exists(path): self.command.append('mkdir -p ' + path) self.command.append(self.mountcommand) self.MountConsole.eBatch(self.command, self.CheckMountPointFinished, [data, callback], debug=True) else: self.CheckMountPointFinished([data, callback]) def CheckMountPointFinished(self, extra_args): (data, callback,) = extra_args if data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', data['sharename']) else: path = os.path.join('/media/net', data['sharename']) sharepath = '' if os.path.exists(path): if os.path.ismount(path): if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(path, desc) else: if self.automounts.has_key(data['sharename']): self.automounts[data['sharename']]['isMounted'] = False if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print 'Failed to remove', print path, print 'Error:', print ex if self.checkList: self.CheckMountPoint(self.checkList.pop(), callback) if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1) def mountTimeout(self): self.timer.stop() if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if self.callback is not None: self.callback(True) elif self.removeConsole: if len(self.removeConsole.appContainers) == 0: if self.callback is not None: self.callback(True) def getMountsList(self): return self.automounts def getMountsAttribute(self, mountpoint, attribute): if self.automounts.has_key(mountpoint): if self.automounts[mountpoint].has_key(attribute): return self.automounts[mountpoint][attribute] def setMountsAttribute(self, mountpoint, attribute, value): if self.automounts.has_key(mountpoint): self.automounts[mountpoint][attribute] = value def writeMountsConfig(self): list = ['<?xml version="1.0" ?>\n<mountmanager>\n'] for (sharename, sharedata,) in self.automounts.items(): if sharedata['hdd_replacement'] == 'True' or sharedata['hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', sharedata['sharename']) else: path = os.path.join('/media/net', sharedata['sharename']) sharepath = '' if sharedata['mountusing'] == 'fstab': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] + ' ' tmpfile = open('/etc/fstab.tmp', 'w') file = open('/etc/fstab') tmpfile.writelines([ l for l in file.readlines() if sharetemp not in l ]) tmpfile.close() file.close() os.rename('/etc/fstab.tmp', '/etc/fstab') mtype = sharedata['mounttype'] list.append('<fstab>\n') list.append(' <' + mtype + '>\n') list.append(' <mount>\n') list.append(' <active>' + str(sharedata['active']) + '</active>\n') list.append(' <hdd_replacement>' + str(sharedata['hdd_replacement']) + '</hdd_replacement>\n') list.append(' <ip>' + sharedata['ip'] + '</ip>\n') list.append(' <sharename>' + sharedata['sharename'] + '</sharename>\n') list.append(' <sharedir>' + sharedata['sharedir'] + '</sharedir>\n') list.append(' <options>' + sharedata['options'] + '</options>\n') if sharedata['mounttype'] == 'cifs': list.append(' <username>' + sharedata['username'] + '</username>\n') list.append(' <password>' + sharedata['password'] + '</password>\n') list.append(' </mount>\n') list.append(' </' + mtype + '>\n') list.append('</fstab>\n') out = open('/etc/fstab', 'a') if sharedata['mounttype'] == 'nfs': line = sharedata['ip'] + ':/' + sharedata['sharedir'] + ' ' + path + '\tnfs\t_netdev,' + self.sanitizeOptions(sharedata['options'], fstab=True) + '\t0 0\n' elif sharedata['mounttype'] == 'cifs': line = '//' + sharedata['ip'] + '/' + sharedata['sharedir'] + ' ' + path + '\tcifs\tusername='******'username'] + ',password='******'password'] + ',_netdev,' + self.sanitizeOptions(sharedata['options'], cifs=True, fstab=True) + '\t0 0\n' out.write(line) out.close() elif sharedata['mountusing'] == 'enigma2': mtype = sharedata['mounttype'] list.append('<enigma2>\n') list.append(' <' + mtype + '>\n') list.append(' <mount>\n') list.append(' <active>' + str(sharedata['active']) + '</active>\n') list.append(' <hdd_replacement>' + str(sharedata['hdd_replacement']) + '</hdd_replacement>\n') list.append(' <ip>' + sharedata['ip'] + '</ip>\n') list.append(' <sharename>' + sharedata['sharename'] + '</sharename>\n') list.append(' <sharedir>' + sharedata['sharedir'] + '</sharedir>\n') list.append(' <options>' + sharedata['options'] + '</options>\n') if sharedata['mounttype'] == 'cifs': list.append(' <username>' + sharedata['username'] + '</username>\n') list.append(' <password>' + sharedata['password'] + '</password>\n') list.append(' </mount>\n') list.append(' </' + mtype + '>\n') list.append('</enigma2>\n') elif sharedata['mountusing'] == 'old_enigma2': mtype = sharedata['mounttype'] list.append(' <' + mtype + '>\n') list.append(' <mount>\n') list.append(' <active>' + str(sharedata['active']) + '</active>\n') list.append(' <hdd_replacement>' + str(sharedata['hdd_replacement']) + '</hdd_replacement>\n') list.append(' <ip>' + sharedata['ip'] + '</ip>\n') list.append(' <sharename>' + sharedata['sharename'] + '</sharename>\n') list.append(' <sharedir>' + sharedata['sharedir'] + '</sharedir>\n') list.append(' <options>' + sharedata['options'] + '</options>\n') if sharedata['mounttype'] == 'cifs': list.append(' <username>' + sharedata['username'] + '</username>\n') list.append(' <password>' + sharedata['password'] + '</password>\n') list.append(' </mount>\n') list.append(' </' + mtype + '>\n') list.append('</mountmanager>\n') try: f = open(XML_FSTAB, 'w') f.writelines(list) f.close() except Exception as e: print '[NetworkBrowser] Error Saving Mounts List:', print e def stopMountConsole(self): if self.MountConsole is not None: self.MountConsole = None def removeMount(self, mountpoint, callback = None): self.newautomounts = {} path = '' for (sharename, sharedata,) in self.automounts.items(): if sharedata['hdd_replacement'] == 'True' or sharedata['hdd_replacement'] is True: path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', sharedata['sharename']) else: path = os.path.join('/media/net', sharedata['sharename']) sharepath = '' if sharename is not mountpoint.strip(): self.newautomounts[sharename] = sharedata if sharedata['mountusing'] == 'fstab': tmpfile = open('/etc/fstab.tmp', 'w') file = open('/etc/fstab') tmpfile.writelines([ l for l in file.readlines() if sharedata['sharedir'] not in l ]) tmpfile.close() file.close() os.rename('/etc/fstab.tmp', '/etc/fstab') self.automounts.clear() self.automounts = self.newautomounts if not self.removeConsole: self.removeConsole = Console() umountcmd = 'umount -fl ' + path self.removeConsole.ePopen(umountcmd, self.removeMountPointFinished, [path, callback]) def removeMountPointFinished(self, result, retval, extra_args): (path, callback,) = extra_args if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print 'Failed to remove', print path, print 'Error:', print ex if self.removeConsole: if len(self.removeConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1)
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 Network: def __init__(self): self.ifaces = {} self.configuredInterfaces = [] self.configuredNetworkAdapters = [] self.NetworkState = 0 self.DnsState = 0 self.nameservers = [] self.ethtool_bin = "ethtool" self.container = eConsoleAppContainer() self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateConsole = Console() self.deactivateInterfaceConsole = Console() self.activateConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.PingConsole = Console() self.config_ready = None self.friendlyNames = {} self.lan_interfaces = [] self.wlan_interfaces = [] self.getInterfaces() def onRemoteRootFS(self): fp = file('/proc/mounts', 'r') mounts = fp.readlines() fp.close() for line in mounts: parts = line.strip().split(' ') if parts[1] == '/' and (parts[2] == 'nfs' or parts[2] == 'smbfs'): return True return False def getInterfaces(self, callback=None): devicesPattern = re_compile('[a-z]+[0-9]+') self.configuredInterfaces = [] fp = file('/proc/net/dev', 'r') result = fp.readlines() fp.close() for line in result: try: device = devicesPattern.search(line).group() if device in ('wifi0', 'wmaster0'): continue self.getDataForInterface(device, callback) except AttributeError: pass #print "self.ifaces:", self.ifaces #self.writeNetworkConfig() #print ord(' ') #for line in result: # print ord(line[0]) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): strIP = ip.split('.') ip = [] for x in strIP: ip.append(int(x)) return ip def getDataForInterface(self, iface, callback): #get ip out of ip addr, as avahi sometimes overrides it in ifconfig. if not self.Console: self.Console = Console() cmd = "ip -o addr" 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, 'postdown': 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-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{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( '[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}' ) 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 is not None: 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 enigma 2\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("\n" + iface["configStrings"] + "\n") if iface["preup"] is not False and not iface.has_key( "configStrings"): fp.write(iface["preup"]) fp.write(iface["postdown"]) fp.write("\n") fp.close() 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] == "post-down"): if self.ifaces[currif].has_key("postdown"): self.ifaces[currif]["postdown"] = 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 is not None: self.nameservers.append(self.convertIP(ip)) print "nameservers:", self.nameservers def deactivateNetworkConfig(self, callback=None): if self.onRemoteRootFS(): if callback is not None: callback(True) return self.deactivateConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): cmd = "ip addr flush " + iface self.commands.append(cmd) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.deactivateConsole.eBatch(self.commands, self.deactivateNetworkFinished, callback, debug=True) def deactivateNetworkFinished(self, extra_args): callback = extra_args if len(self.deactivateConsole.appContainers) == 0: if callback is not None: callback(True) def activateNetworkConfig(self, callback=None): if self.onRemoteRootFS(): if callback is not None: callback(True) return self.activateConsole = Console() self.commands = [] self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.activateConsole.eBatch(self.commands, self.activateNetworkFinished, callback, debug=True) def activateNetworkFinished(self, extra_args): callback = extra_args if len(self.activateConsole.appContainers) == 0: if callback is not None: callback(True) 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) else: 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): if iface.startswith('eth'): if iface not in self.lan_interfaces and len( self.lan_interfaces) == 0: self.lan_interfaces.append(iface) return _("LAN connection") elif iface not in self.lan_interfaces and len( self.lan_interfaces) >= 1: self.lan_interfaces.append(iface) return _("LAN connection") + " " + str(len( self.lan_interfaces)) else: if iface not in self.lan_interfaces and len( self.lan_interfaces) == 0: self.lan_interfaces.append(iface) return _("WLAN connection") elif iface not in self.lan_interfaces and len( self.lan_interfaces) >= 1: self.lan_interfaces.append(iface) return _("WLAN connection") + " " + str( len(self.lan_interfaces)) def getFriendlyAdapterDescription(self, iface): if iface == 'eth0': return _("Internal LAN adapter.") else: classdir = "/sys/class/net/" driverdir = "/sys/class/net/" + iface if os_path.exists(classdir): files = listdir(classdir) if iface in files: if os_path.realpath(driverdir).endswith('ath_pci'): return _("Atheros") + " " + str( os_path.basename(os_path.realpath( driverdir))) + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('zd1211b'): return _("Zydas") + " " + str( os_path.basename(os_path.realpath( driverdir))) + " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('ra0'): return _("Ralink") + "-3070 " + " " + _( "WLAN adapter.") elif os_path.realpath(driverdir).endswith('wlan0'): return _("Ralink") + "-2870 " + " " + _( "WLAN adapter.") else: return str( os_path.basename(os_path.realpath( driverdir))) + " " + _("WLAN adapter.") else: return _("Unknown network adapter.") 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] return None 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): if self.onRemoteRootFS(): if callback is not None: callback(True) return self.resetNetworkConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): cmd = "ip addr flush " + iface self.commands.append(cmd) 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 enigma 2\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): # www.dream-multimedia-tv.de, www.heise.de, www.google.de self.NetworkState = 0 cmd1 = "ping -c 1 82.149.226.170" cmd2 = "ping -c 1 193.99.144.85" cmd3 = "ping -c 1 209.85.135.103" 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): if self.onRemoteRootFS(): if callback is not None: callback(True) return 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(): cmd = "ip addr flush " + iface self.commands.append(cmd) 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: if len(self.deactivateInterfaceConsole.appContainers): for name in self.deactivateInterfaceConsole.appContainers.keys( ): self.deactivateInterfaceConsole.kill(name) 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): 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, iface, callback=None): if self.onRemoteRootFS(): if callback is not None: callback(True) return self.deactivateInterfaceConsole = Console() self.commands = [] cmd1 = "ip addr flush " + iface cmd2 = "ifconfig " + iface + " down" self.commands.append(cmd1) self.commands.append(cmd2) self.deactivateInterfaceConsole.eBatch( self.commands, self.deactivateInterfaceFinished, callback, debug=True) def deactivateInterfaceFinished(self, extra_args): callback = extra_args if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def detectWlanModule(self, iface=None): self.wlanmodule = None classdir = "/sys/class/net/" + iface + "/device/" driverdir = "/sys/class/net/" + iface + "/device/driver/" if os_path.exists(classdir): classfiles = listdir(classdir) driver_found = False nl80211_found = False for x in classfiles: if x == 'driver': driver_found = True if x.startswith('ieee80211:'): nl80211_found = True if driver_found and nl80211_found: #print about.getKernelVersionString() self.wlanmodule = "nl80211" else: if driver_found and not nl80211_found: driverfiles = listdir(driverdir) if os_path.realpath(driverdir).endswith('ath_pci'): if len(driverfiles) >= 1: self.wlanmodule = 'madwifi' if os_path.realpath(driverdir).endswith('rt73'): if len(driverfiles) == 2 or len(driverfiles) == 5: self.wlanmodule = 'ralink' if os_path.realpath(driverdir).endswith('zd1211b'): if len(driverfiles) == 1 or len(driverfiles) == 5: self.wlanmodule = 'zydas' if self.wlanmodule is None: self.wlanmodule = "wext" print 'Using "%s" as wpa-supplicant driver' % (self.wlanmodule) return self.wlanmodule 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 NetworkSamba(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Samba Setup")) self.skinName = "NetworkSamba" self.onChangedEntry = [] self['lab1'] = Label(_("Autostart:")) self['labactive'] = Label(_(_("Disabled"))) self['lab2'] = Label(_("Current Status:")) self['labstop'] = Label(_("Stopped")) self['labrun'] = Label(_("Running")) self['key_green'] = Label(_("Start")) self['key_red'] = Label(_("Remove Service")) self['key_yellow'] = Label(_("Autostart")) self['key_blue'] = Label(_("Show Log")) self.Console = Console() self.my_Samba_active = False self.my_Samba_run = False self['actions'] = ActionMap( ['WizardActions', 'ColorActions'], { 'ok': self.close, 'back': self.close, 'red': self.UninstallCheck, 'green': self.SambaStartStop, 'yellow': self.activateSamba, 'blue': self.Sambashowlog }) self.service_name = basegroup + '-smbfs' self.onLayoutFinish.append(self.InstallCheck) def InstallCheck(self): self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def checkNetworkState(self, str, retval, extra_args): if 'Collected errors' in str: self.session.openWithCallback( self.close, MessageBox, _("A background update check is in progress, please wait a few minutes and try again." ), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif not str: self.feedscheck = self.session.open( MessageBox, _('Please wait while feeds state is checked.'), MessageBox.TYPE_INFO, enable_input=False) self.feedscheck.setTitle(_('Checking Feeds')) cmd1 = "opkg update" self.CheckConsole = Console() self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished) else: self.updateService() def checkNetworkStateFinished(self, result, retval, extra_args=None): if 'bad address' in result: self.session.openWithCallback( self.InstallPackageFailed, MessageBox, _("Your %s %s is not connected to the internet, please check your network settings and try again." ) % (getMachineBrand(), getMachineName()), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif ('wget returned 1' or 'wget returned 255' or '404 Not Found') in result: self.session.openWithCallback( self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later." ), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) else: self.session.openWithCallback( self.QuestionCallback, MessageBox, _('Your %s %s will be restarted after the installation of service.\nReady to install %s ?' ) % (getMachineBrand(), getMachineName(), self.service_name), MessageBox.TYPE_YESNO) def QuestionCallback(self, val): if val: self.session.openWithCallback( self.InstallPackage, MessageBox, _('Do you want to also install samba client?\nThis allows you to mount your windows shares on this device.' ), MessageBox.TYPE_YESNO) else: self.feedscheck.close() self.close() def InstallPackage(self, val): if val: self.service_name = self.service_name + ' ' + basegroup + '-smbfs-client' self.doInstall(self.installComplete, self.service_name) def InstallPackageFailed(self, val): self.feedscheck.close() self.close() def doInstall(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Installing Service')) self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback) def installComplete(self, result=None, retval=None, extra_args=None): self.session.open(TryQuitMainloop, 2) def UninstallCheck(self): self.service_name = self.service_name + ' ' + basegroup + '-smbfs-client' self.Console.ePopen( '/usr/bin/opkg list_installed ' + self.service_name, self.RemovedataAvail) def RemovedataAvail(self, str, retval, extra_args): if str: restartbox = self.session.openWithCallback( self.RemovePackage, MessageBox, _('Your %s %s will be restarted after the removal of service.\nDo you want to remove now ?' ) % (getMachineBrand(), getMachineName()), MessageBox.TYPE_YESNO) restartbox.setTitle(_('Ready to remove %s ?') % self.service_name) else: self.updateService() def RemovePackage(self, val): if val: self.doRemove(self.removeComplete, self.service_name) def doRemove(self, callback, pkgname): self.message = self.session.open(MessageBox, _("please wait..."), MessageBox.TYPE_INFO, enable_input=False) self.message.setTitle(_('Removing Service')) self.Console.ePopen( '/usr/bin/opkg remove ' + pkgname + ' --force-remove --autoremove', callback) def removeComplete(self, result=None, retval=None, extra_args=None): self.session.open(TryQuitMainloop, 2) def createSummary(self): return NetworkServicesSummary def Sambashowlog(self): self.session.open(NetworkSambaLog) def SambaStartStop(self): commands = [] if not self.my_Samba_run: commands.append('/etc/init.d/samba start') commands.append('nmbd -D') commands.append('smbd -D') elif self.my_Samba_run: commands.append('/etc/init.d/samba stop') commands.append('killall nmbd') commands.append('killall smbd') self.Console.eBatch(commands, self.StartStopCallback, debug=True) def StartStopCallback(self, result=None, retval=None, extra_args=None): time.sleep(3) self.updateService() def activateSamba(self): if access('/etc/network/if-up.d/01samba-start', X_OK): chmod('/etc/network/if-up.d/01samba-start', 0644) elif not access('/etc/network/if-up.d/01samba-start', X_OK): chmod('/etc/network/if-up.d/01samba-start', 0755) if fileExists('/etc/rc2.d/S20samba'): self.Console.ePopen('update-rc.d -f samba remove', self.StartStopCallback) else: self.Console.ePopen('update-rc.d -f samba defaults', self.StartStopCallback) def updateService(self): import process p = process.ProcessList() samba_process = str(p.named('smbd')).strip('[]') self['labrun'].hide() self['labstop'].hide() self['labactive'].setText(_("Disabled")) self.my_Samba_active = False self.my_Samba_run = False if fileExists('/etc/rc2.d/S20samba'): self['labactive'].setText(_("Enabled")) self['labactive'].show() self.my_Samba_active = True if access('/etc/network/if-up.d/01samba-start', X_OK): self['labactive'].setText(_("Enabled")) self['labactive'].show() self.my_Samba_active = True if samba_process: self.my_Samba_run = True if self.my_Samba_run: self['labstop'].hide() self['labactive'].show() self['labrun'].show() self['key_green'].setText(_("Stop")) status_summary = self['lab2'].text + ' ' + self['labrun'].text else: self['labrun'].hide() self['labstop'].show() self['labactive'].show() self['key_green'].setText(_("Start")) status_summary = self['lab2'].text + ' ' + self['labstop'].text title = _("Samba Setup") autostartstatus_summary = self['lab1'].text + ' ' + self[ 'labactive'].text for cb in self.onChangedEntry: cb(title, status_summary, autostartstatus_summary)
class WirelessAccessPoint(Screen,ConfigListScreen): skin = """ <screen position="center,center" size="590,450" title="Wireless Access Point" > <ePixmap pixmap="skin_default/buttons/red.png" position="20,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="160,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="300,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="440,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" /> <widget source="key_blue" render="Label" position="440,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" /> <widget name="config" zPosition="2" position="20,70" size="550,270" scrollbarMode="showOnDemand" transparent="1" /> <widget source="current_settings" render="Label" position="10,340" size="570,20" font="Regular;19" halign="center" valign="center" transparent="1" /> <widget source="IPAddress_text" render="Label" position="130,370" size="190,21" font="Regular;19" transparent="1" /> <widget source="Netmask_text" render="Label" position="130,395" size="190,21" font="Regular;19" transparent="1" /> <widget source="Gateway_text" render="Label" position="130,420" size="190,21" font="Regular;19" transparent="1" /> <widget source="IPAddress" render="Label" position="340,370" size="240,21" font="Regular;19" transparent="1" /> <widget source="Netmask" render="Label" position="340,395" size="240,21" font="Regular;19" transparent="1" /> <widget source="Gateway" render="Label" position="340,420" size="240,21" font="Regular;19" transparent="1" /> </screen>""" def __init__(self,session): Screen.__init__(self,session) self.session = session self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ], { "ok": self.doConfigMsg, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.doConfigMsg, }, -2) self.list = [] ConfigListScreen.__init__(self, self.list,session = self.session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Ok")) self["key_yellow"] = StaticText(_(" ")) self["key_blue"] = StaticText(_(" ")) self["current_settings"] = StaticText(_("Current settings (interface : br0)")) self["IPAddress_text"] = StaticText(_("IP Address")) self["Netmask_text"] = StaticText(_("Netmask")) self["Gateway_text"] = StaticText(_("Gateway")) self["IPAddress"] = StaticText(_("N/A")) self["Netmask"] = StaticText(_("N/A")) self["Gateway"] = StaticText(_("N/A")) self.makeConfig() self.apModeChanged = False self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.currentNetworkSettings) self.onLayoutFinish.append(self.checkConfigError) self.configErrorTimer = eTimer() self.configErrorTimer.callback.append(self.configErrorMsg) self.configStartMsg = None def makeConfig(self): self.msg = "" if self.checkWirelessDevices(): return self.checkRunHostapd() self.makeConfigList() self.loadInterfacesConfig() self.loadHostapConfig() self.setupCurrentEncryption() self.createConfigEntry() self.createConfig() def checkConfigError(self): if self.msg: self.configErrorTimer.start(100, True) def configErrorMsg(self): self.session.openWithCallback(self.close ,MessageBox, _(self.msg), MessageBox.TYPE_ERROR) def checkwlanDeviceList(self): if len(self.wlanDeviceList) == 0: self.checkwlanDeviceListTimer.start(100,True) def currentNetworkSettings(self): self["IPAddress"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "ip"))) self["Netmask"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "netmask"))) self["Gateway"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "gateway"))) def formatAddr(self, address = [0,0,0,0]): if address is None: return "N/A" return "%d:%d:%d:%d"%(address[0],address[1],address[2],address[3]) def checkRunHostapd(self): global apModeConfig if fileExists("/var/run/hostapd", 0): apModeConfig.useap.value = True def checkWirelessDevices(self): global apModeConfig self.wlanDeviceList = [] wlanIfaces =[] for x in iNetwork.getInstalledAdapters(): if x.startswith('eth') or x.startswith('br') or x.startswith('mon'): continue wlanIfaces.append(x) description=self.getAdapterDescription(x) if description == "Unknown network adapter": self.wlanDeviceList.append((x, x)) else: self.wlanDeviceList.append(( x, description + " (%s)"%x )) if len(self.wlanDeviceList) == 0: self.msg = "Wireless Lan Device is not detected." return -1 apModeConfig.wirelessdevice = ConfigSelection( choices = self.wlanDeviceList ) return 0 def makeConfigList(self): global apModeConfig self.hostapdConf = {} self.hostapdConf["interface"] = apModeConfig.wirelessdevice self.hostapdConf["bridge"] = apModeConfig.branch # "br0" self.hostapdConf["driver"] = apModeConfig.driver # "nl80211" self.hostapdConf["hw_mode"] = apModeConfig.wirelessmode self.hostapdConf["channel"] = apModeConfig.channel self.hostapdConf["ssid"] = apModeConfig.ssid self.hostapdConf["beacon_int"] = apModeConfig.beacon self.hostapdConf["rts_threshold"] = apModeConfig.rts_threshold self.hostapdConf["fragm_threshold"] = apModeConfig.fragm_threshold self.hostapdConf["preamble"] = apModeConfig.preamble # self.hostapdConf["macaddr_acl"] = "" # fix to add Access Control List Editer # self.hostapdConf["accept_mac_file"] = "" # fix to add Access Control List Editer # self.hostapdConf["deny_mac_file"] = "" # fix to add Access Control List Editer self.hostapdConf["ignore_broadcast_ssid"] = apModeConfig.ignore_broadcast_ssid # self.hostapdConf["wmm_enabled"] = "" # self.hostapdConf["ieee80211n"] = "" # self.hostapdConf["ht_capab"] = "" self.hostapdConf["wep_default_key"] = apModeConfig.wep_default_key self.hostapdConf["wep_key0"] = apModeConfig.wep_key0 self.hostapdConf["wpa"] = apModeConfig.wpa self.hostapdConf["wpa_passphrase"] = apModeConfig.wpa_passphrase self.hostapdConf["wpa_key_mgmt"] = apModeConfig.wpa_key_mgmt # "WPA-PSK" self.hostapdConf["wpa_pairwise"] = apModeConfig.wpa_pairwise # "TKIP CCMP" self.hostapdConf["rsn_pairwise"] = apModeConfig.rsn_pairwise # "CCMP" self.hostapdConf["wpa_group_rekey"] = apModeConfig.wpagrouprekey def loadInterfacesConfig(self): global apModeConfig try: fp = file('/etc/network/interfaces', 'r') datas = fp.readlines() fp.close() except: printDebugMsg("Read failed, /etc/network/interfaces.") return -1 current_iface = "" try: for line in datas: split = line.strip().split(' ') if (split[0] == "iface"): current_iface = split[1] if (current_iface == "br0" or current_iface == "eth0"): if (len(split) == 4 and split[3] == "dhcp"): apModeConfig.usedhcp.value = True if (split[0] == "address"): apModeConfig.address.value = map(int, split[1].split('.')) if (split[0] == "netmask"): apModeConfig.netmask.value = map(int, split[1].split('.')) if (split[0] == "gateway"): apModeConfig.gateway.value = map(int, split[1].split('.')) if (split[0] == "dns-nameservers"): apModeConfig.nameserver.value = map(int, split[1].split('.')) except: printDebugMsg("Parsing failed, /etc/network/interfaces.") return -1 return 0 def setupCurrentEncryption(self): global apModeConfig if len(apModeConfig.wep_key0.value) > 10: apModeConfig.wepType.value = "128" if apModeConfig.wpa.value is not "0" and apModeConfig.wpa_passphrase.value: # (1,WPA), (2,WPA2), (3,WPA/WPA2) apModeConfig.encrypt.value = True apModeConfig.method.value = apModeConfig.wpa.value elif apModeConfig.wep.value and apModeConfig.wep_key0.value: apModeConfig.encrypt.value = True apModeConfig.method.value = "0" # wep else: apModeConfig.encrypt.value = False def createConfigEntry(self): global apModeConfig #hostap settings self.useApEntry = getConfigListEntry(_("Use AP Mode"), apModeConfig.useap) self.setupModeEntry = getConfigListEntry(_("Setup Mode"), apModeConfig.setupmode) self.wirelessDeviceEntry = getConfigListEntry(_("AP Device"), apModeConfig.wirelessdevice) self.wirelessModeEntry = getConfigListEntry(_("AP Mode"), apModeConfig.wirelessmode) self.channelEntry = getConfigListEntry(_("Channel (1~13)"), apModeConfig.channel) self.ssidEntry = getConfigListEntry(_("SSID (1~32 Characters)"), apModeConfig.ssid) self.beaconEntry = getConfigListEntry(_("Beacon (15~65535)"), apModeConfig.beacon) self.rtsThresholdEntry = getConfigListEntry(_("RTS Threshold (0~2347)"), apModeConfig.rts_threshold) self.fragmThresholdEntry = getConfigListEntry(_("FRAGM Threshold (256~2346)"), apModeConfig.fragm_threshold) self.prambleEntry = getConfigListEntry(_("Preamble"), apModeConfig.preamble) self.ignoreBroadcastSsid = getConfigListEntry(_("Ignore Broadcast SSID"), apModeConfig.ignore_broadcast_ssid) # hostap encryption self.encryptEntry = getConfigListEntry(_("Encrypt"), apModeConfig.encrypt) self.methodEntry = getConfigListEntry(_("Method"), apModeConfig.method) self.wepKeyTypeEntry = getConfigListEntry(_("KeyType"), apModeConfig.wepType) self.wepKey0Entry = getConfigListEntry(_("WEP Key (HEX)"), apModeConfig.wep_key0) self.wpaKeyEntry = getConfigListEntry(_("KEY (8~63 Characters)"), apModeConfig.wpa_passphrase) self.groupRekeyEntry = getConfigListEntry(_("Group Rekey Interval"), apModeConfig.wpagrouprekey) # interface settings self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), apModeConfig.usedhcp) self.ipEntry = getConfigListEntry(_("IP Address"), apModeConfig.address) self.netmaskEntry = getConfigListEntry(_("NetMask"), apModeConfig.netmask) self.gatewayEntry = getConfigListEntry(_("Gateway"), apModeConfig.gateway) self.nameserverEntry = getConfigListEntry(_("Nameserver"), apModeConfig.nameserver) def createConfig(self): global apModeConfig apModeConfig.address.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "ip") or [0,0,0,0] apModeConfig.netmask.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "netmask") or [255,0,0,0] apModeConfig.gateway.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "gateway") or [0,0,0,0] self.configList = [] self.configList.append( self.useApEntry ) if apModeConfig.useap.value is True: self.configList.append( self.setupModeEntry ) self.configList.append( self.wirelessDeviceEntry ) self.configList.append( self.wirelessModeEntry ) self.configList.append( self.channelEntry ) self.configList.append( self.ssidEntry ) if apModeConfig.setupmode.value is "advanced": self.configList.append( self.beaconEntry ) self.configList.append( self.rtsThresholdEntry ) self.configList.append( self.fragmThresholdEntry ) self.configList.append( self.prambleEntry ) self.configList.append( self.ignoreBroadcastSsid ) self.configList.append( self.encryptEntry ) if apModeConfig.encrypt.value is True: self.configList.append( self.methodEntry ) if apModeConfig.method.value is "0": # wep self.configList.append( self.wepKeyTypeEntry ) self.configList.append( self.wepKey0Entry ) else: self.configList.append( self.wpaKeyEntry ) if apModeConfig.setupmode.value is "advanced": self.configList.append( self.groupRekeyEntry ) ## set network interfaces self.configList.append( self.usedhcpEntry ) if apModeConfig.usedhcp.value is False: self.configList.append( self.ipEntry ) self.configList.append( self.netmaskEntry ) self.configList.append( self.gatewayEntry ) self.configList.append( self.nameserverEntry ) self["config"].list = self.configList self["config"].l.setList(self.configList) def keyLeft(self): ConfigListScreen.keyLeft(self) self.newConfig() def keyRight(self): ConfigListScreen.keyRight(self) self.newConfig() def newConfig(self): if self["config"].getCurrent() in [ self.encryptEntry, self.methodEntry, self.useApEntry, self.usedhcpEntry, self.setupModeEntry]: self.createConfig() # 0 : legacy module activated, 1 : kernel module activated, -1 : None def checkProcModules(self): proc_path = "/proc/modules" legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta") kernel_modules = ("rt2800usb", "rt2800lib") fd = open(proc_path, "r") data = fd.readlines() fd.close() for line in data: module = line.split()[0].strip() if module in legacy_modules: return 0 elif module in kernel_modules: return 1 return -1 def isRalinkModule(self): global apModeConfig iface = apModeConfig.wirelessdevice.value # check vendor ID for lagacy driver vendorID = "148f" # ralink vendor ID idVendorPath = "/sys/class/net/%s/device/idVendor" % iface if access(idVendorPath, R_OK): fd = open(idVendorPath, "r") data = fd.read().strip() fd.close() printDebugMsg("Vendor ID : %s" % data) if data == vendorID: return True # check sys driver path for kernel driver ralinkKmod = "rt2800usb" # ralink kernel driver name driverPath = "/sys/class/net/%s/device/driver/" % iface if os_path.exists(driverPath): driverName = os_path.basename(os_path.realpath(driverPath)) printDebugMsg("driverName : %s" % driverName) if driverName == ralinkKmod: return True return False def doConfigMsg(self): global apModeConfig msg = "Are you sure you want to setup AP?\n" isRainkIface = self.isRalinkModule() isApMode = apModeConfig.useap.value is True isRalinkKmodUploaded = self.checkProcModules() == 1 if isRainkIface and isApMode and (not isRalinkKmodUploaded ): msg += "( STB should be reboot to enable AP mode. )\n" else: msg += ("\n") self.session.openWithCallback(self.doConfig, MessageBox, (_(msg) ) ) def doConfig(self, ret = False): global apModeConfig if ret is not True: return if apModeConfig.useap.value is True and apModeConfig.encrypt.value is True: if not self.checkEncrypKey(): return if not self.checkConfig(): return self.configStartMsg = self.session.openWithCallback(self.ConfigFinishedMsg, MessageBox, _("Please wait for AP Configuration....\n") , type = MessageBox.TYPE_INFO, enable_input = False) if apModeConfig.useap.value is True: self.networkRestart( nextFunc = self.makeConf ) else: self.networkRestart( nextFunc = self.removeConf ) def checkEncrypKey(self): global apModeConfig if apModeConfig.method.value == "0": if self.checkWep(apModeConfig.wep_key0.value) is False: self.session.open(MessageBox, _("Invalid WEP key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10 ) else: return True else: if not len(apModeConfig.wpa_passphrase.value) in range(8,65): self.session.open(MessageBox, _("Invalid WPA key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10) else: return True return False def checkWep(self, key): global apModeConfig length = len(key) if length == 0: return False elif apModeConfig.wepType.value == "64" and length == 10: return True elif apModeConfig.wepType.value == "128" and length == 26: return True else: return False def checkConfig(self): global apModeConfig # ssid Check if len(apModeConfig.ssid.value) == 0 or len(apModeConfig.ssid.value) > 32: self.session.open(MessageBox, _("Invalid SSID\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.channel.value not in range(1,14): self.session.open(MessageBox, _("Invalid channel\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.beacon.value < 15 or apModeConfig.beacon.value > 65535: self.session.open(MessageBox, _("Invalid beacon\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.rts_threshold.value < 0 or apModeConfig.rts_threshold.value > 2347: self.session.open(MessageBox, _("Invalid RTS Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.fragm_threshold.value < 256 or apModeConfig.fragm_threshold.value > 2346: self.session.open(MessageBox, _("Invalid Fragm Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; elif apModeConfig.wpagrouprekey.value < 0 or apModeConfig.wpagrouprekey.value > 3600: self.session.open(MessageBox, _("Invalid wpagrouprekey\n"), type = MessageBox.TYPE_ERROR, timeout = 10) return False; return True; def networkRestart(self, nextFunc = None ): self.networkRestart_stop( nextFunc = nextFunc ) def networkRestart_stop(self, nextFunc = None ): printDebugMsg("networkRestart_stop") self.msgPlugins(False) self.commands = [] # stop current network self.networkRestartConsole = Console() self.commands.append("/etc/init.d/avahi-daemon stop") for iface in iNetwork.getAdapterList(): if iface != 'eth0' or not iNetwork.onRemoteRootFS(): self.commands.append("ifdown " + iface) self.commands.append("ip addr flush dev " + iface) self.commands.append("/etc/init.d/hostapd stop") self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.networkRestartConsole.eBatch(self.commands, nextFunc, debug = True) def makeConf(self,extra_args): printDebugMsg("makeConf") self.writeNetworkInterfaces() result = self.writeHostapdConfig() if result == -1: self.configStartMsg.close(False) self.configErrorTimer.start(100, True) return self.setIpForward(1) self.networkRestart_start() def removeConf(self,extra_args): global apModeConfig printDebugMsg("removeConf") if fileExists("/etc/hostapd.conf", 'f'): os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back") fp = file("/etc/network/interfaces", 'w') fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") if apModeConfig.usedhcp.value is True: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) ) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) ) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) ) fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value) ) fp.close() self.setIpForward(0) self.networkRestart_start() def networkRestart_start(self): global apModeConfig printDebugMsg("networkRestart_start") self.restartConsole = Console() self.commands = [] self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") if apModeConfig.useap.value is True: self.commands.append("/etc/init.d/hostapd start") self.restartConsole.eBatch(self.commands, self.networkRestartFinished, debug=True) def networkRestartFinished(self, data): printDebugMsg("networkRestartFinished") iNetwork.ifaces = {} iNetwork.getInterfaces(self.getInterfacesDataAvail) def getInterfacesDataAvail(self, data): self.blacklist_legacy_drivers() if data is True and self.configStartMsg is not None: self.configStartMsg.close(True) def ConfigFinishedMsg(self, ret): if ret is True: self.session.openWithCallback(self.ConfigFinishedMsgCallback ,MessageBox, _("Configuration your AP is finished"), type = MessageBox.TYPE_INFO, timeout = 5, default = False) def needRalinkKmod(self): global apModeConfig isRainkIface = self.isRalinkModule() ApMode = apModeConfig.useap.value is True if isRainkIface and ApMode: return True else: return False def ConfigFinishedMsgCallback(self,data): isRalinkKmodUploaded = self.checkProcModules() == 1 needRalinkKmod_ = self.needRalinkKmod() if needRalinkKmod_ : # ralink device is activated in AP Mode. if not isRalinkKmodUploaded : # reboot to loading kernel module. msg = "You should now reboot your STB in order to ralink device operate in AP mode.\n\nReboot now ?\n\n" self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type = MessageBox.TYPE_YESNO, default = True ) else: self.close() elif isRalinkKmodUploaded : msg = "You should now reboot your STB to better performance of ralink device in STA mode.\n\nReboot now ?\n\n" self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type = MessageBox.TYPE_YESNO, default = True ) else: self.close() def blacklist_legacy_drivers(self): blacklist_conf_dir = "/etc/modprobe.d" blacklist_conf_file = blacklist_conf_dir + "/blacklist-wlan.conf" legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta") kernel_modules = ("rt2800usb", "rt2800lib") blacklist = "" need_ralink_kmod = self.needRalinkKmod() if access(blacklist_conf_file, R_OK) is True: fd = open(blacklist_conf_file, "r") data = fd.read() fd.close() if need_ralink_kmod: # check legacy modules in blacklist for mod in legacy_modules: if data.find(mod) != -1: return else: for mod in kernel_modules: # check kernel modules in blacklist if data.find(mod) != -1: return if not os_path.exists(blacklist_conf_dir): makedirs(blacklist_conf_dir) if need_ralink_kmod: blacklist_modules = legacy_modules else: blacklist_modules = kernel_modules for module in blacklist_modules: blacklist += "blacklist %s\n" % module f = open(blacklist_conf_file, "w+") f.write(blacklist) f.close() self.apModeChanged = True def doReboot(self, res): if res: self.session.open(TryQuitMainloop, 2) else: self.close() def msgPlugins(self,reason = False): for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ): p(reason=reason) def writeNetworkInterfaces(self): global apModeConfig fp = file("/etc/network/interfaces", 'w') fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") fp.write("iface eth0 inet manual\n") fp.write(" up ip link set $IFACE up\n") fp.write(" down ip link set $IFACE down\n\n") # branch setup fp.write("auto br0\n") if apModeConfig.usedhcp.value is True: fp.write("iface br0 inet dhcp\n") else: fp.write("iface br0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) ) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) ) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) ) fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value) ) fp.write(" pre-up brctl addbr br0\n") fp.write(" pre-up brctl addif br0 eth0\n") fp.write(" post-down brctl delif br0 eth0\n") fp.write(" post-down brctl delbr br0\n\n") fp.write("\n") fp.close() def setIpForward(self, setValue = 0): ipForwardFilePath = "/proc/sys/net/ipv4/ip_forward" if not fileExists(ipForwardFilePath): return -1 printDebugMsg("set %s to %d" % (ipForwardFilePath, setValue)) f = open(ipForwardFilePath, "w") f.write("%d" % setValue) f.close() sysctlPath = "/etc/sysctl.conf" sysctlLines = [] if fileExists(sysctlPath): fp = file(sysctlPath, "r") sysctlLines = fp.readlines() fp.close() sysctlList = {} for line in sysctlLines: line = line.strip() try: (key,value) = line.split("=") key=key.strip() value=value.strip() except: continue sysctlList[key] = value sysctlList["net.ipv4.ip_forward"] = str(setValue) fp = file(sysctlPath, "w") for (key,value) in sysctlList.items(): fp.write("%s=%s\n"%(key,value)) fp.close() return 0 def getAdapterDescription(self, iface): classdir = "/sys/class/net/" + iface + "/device/" driverdir = "/sys/class/net/" + iface + "/device/driver/" if os_path.exists(classdir): files = listdir(classdir) if 'driver' in files: if os_path.realpath(driverdir).endswith('rtw_usb_drv'): return _("Realtek")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('ath_pci'): return _("Atheros")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('zd1211b'): return _("Zydas")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73'): return _("Ralink")+ " " + _("WLAN adapter.") elif os_path.realpath(driverdir).endswith('rt73usb'): return _("Ralink")+ " " + _("WLAN adapter.") else: return str(os_path.basename(os_path.realpath(driverdir))) + " " + _("WLAN adapter") else: return _("Unknown network adapter") else: return _("Unknown network adapter") def __onClose(self): global apModeConfig for x in self["config"].list: x[1].cancel() apModeConfig.wpa.value = "0" apModeConfig.wep.value = False def keyCancel(self): self.close() def printConfigList(self, confList): printDebugMsg("== printConfigList =="); for (key, entry) in confList.items(): printDebugMsg("%s = %s"%(key , str(entry.value))); printDebugMsg("== printConfigList end =="); def loadHostapConfig(self): global apModeConfig fd = -1 if access("/etc/hostapd.conf", R_OK) is True: printDebugMsg("open /etc/hostapd.conf") fd = open("/etc/hostapd.conf", "r") elif access("/etc/hostapd.conf.linuxap.back", R_OK) is True: printDebugMsg("open /etc/hostapd.conf.linuxap.back") fd = open("/etc/hostapd.conf.linuxap.back", "r") if fd == -1: printDebugMsg("can not open hostapd.conf") return -1 for line in fd.readlines(): line = line.strip() if (len(line) == 0) or (line.find('=') == -1): continue data = line.split('=', 1) if len(data) != 2: continue key = data[0].strip() value = data[1].strip() if key == "#wep_key0": self.hostapdConf["wep_key0"].value = value apModeConfig.wep.value = False elif key == "wep_key0": self.hostapdConf["wep_key0"].value = value apModeConfig.wep.value = True elif key.startswith('#'): continue elif key == "channel" : if int(value) not in range(14): self.hostapdConf[key].value = 1 else: self.hostapdConf[key].value = int(value) elif key in ["beacon_int", "rts_threshold", "fragm_threshold", "wpa_group_rekey"]: self.hostapdConf[key].value = int(value) elif key in self.hostapdConf.keys(): self.hostapdConf[key].value = value fd.close() self.printConfigList(self.hostapdConf) return 0 def writeHostapdConfig(self): global apModeConfig global ORIG_HOSTAPD_CONF self.printConfigList(self.hostapdConf) if access(ORIG_HOSTAPD_CONF, R_OK) is not True: self.msg = "can not access file. (%s)" % ORIG_HOSTAPD_CONF printDebugMsg(self.msg) return -1 orig_conf = open(ORIG_HOSTAPD_CONF, "r") if orig_conf == -1: print "can't open file. (%s)" % ORIG_HOSTAPD_CONF new_conf = open(HOSTAPD_CONF, "w") if new_conf == -1: print "can't open file. (%s)" % HOSTAPD_CONF isEncryptOn = apModeConfig.encrypt.value is True isEncryptWEP = apModeConfig.method.value == "0" isEncryptWPA = not isEncryptWEP for r_line in orig_conf.readlines(): line = r_line.strip() if len(line) < 2: new_conf.write(r_line) continue fix_line = None # for encrypt line if line.find("wep_default_key=") != -1 : # is wepLine if isEncryptOn and isEncryptWEP : fix_line = "wep_default_key=%s\n" % self.hostapdConf["wep_default_key"].value elif line.find("wep_key0=") != -1 : # is WepKeyLine if isEncryptOn: if isEncryptWEP : fix_line = "wep_key0=%s\n" % self.hostapdConf["wep_key0"].value else: fix_line = "#wep_key0=%s\n" % self.hostapdConf["wep_key0"].value else: fix_line = "#wep_key0=%s\n" % self.hostapdConf["wep_key0"].value elif line.find("wpa=") != -1 : # is wpaLine if isEncryptOn and isEncryptWPA : fix_line = "wpa=%s\n" % apModeConfig.method.value ## elif line.startswith("#ssid"): pass else: for (key , entry) in self.hostapdConf.items(): value = str(entry.value) pos = line.find(key+'=') if ( (pos != -1) and (pos < 2) ) and len(value)!=0 : fix_line = "%s=%s\n" % (key, value) break # if fix_line is not None: # print "r_line : ", r_line, # print "fix_li : ", fix_line if fix_line is not None: new_conf.write(fix_line) else: new_conf.write(r_line) orig_conf.close() new_conf.close() return 0
class Swap(Screen): skin = """ <screen name="Swap" position="center,center" size="420,250" title="Swap File Manager" flags="wfBorder" > <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" /> <widget name="key_red" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="autostart_off" position="10,50" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" /> <widget name="autostart_on" position="10,50" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" /> <widget name="lab1" position="50,50" size="360,30" font="Regular;20" valign="center" transparent="1"/> <widget name="lab2" position="10,100" size="150,30" font="Regular;20" valign="center" transparent="1"/> <widget name="lab3" position="10,150" size="150,30" font="Regular;20" valign="center" transparent="1"/> <widget name="lab4" position="10,200" size="150,30" font="Regular;20" valign="center" transparent="1" /> <widget name="labplace" position="160,100" size="220,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/> <widget name="labsize" position="160,150" size="220,30" font="Regular;20" valign="center" backgroundColor="#4D5375"/> <widget name="inactive" position="160,200" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="red"/> <widget name="active" position="160,200" size="100,30" font="Regular;20" valign="center" halign="center" backgroundColor="green"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Swap Manager")) self['lab1'] = Label() self['autostart_on'] = Pixmap() self['autostart_off'] = Pixmap() self['lab2'] = Label(_("Swap Place:")) self['labplace'] = Label() self['lab3'] = Label(_("Swap Size:")) self['labsize'] = Label() self['lab4'] = Label(_("Status:")) self['inactive'] = Label(_("Inactive")) self['active'] = Label(_("Active")) self['key_red'] = Label(_("Activate")) self['key_green'] = Label(_("Create")) self['key_yellow'] = Label(_("Autostart")) self['swapname_summary'] = StaticText() self['swapactive_summary'] = StaticText() self.Console = Console() self.swap_place = '' self.new_place = '' self.creatingswap = False self['actions'] = ActionMap(['WizardActions', 'ColorActions', "MenuActions"], {'back': self.close, 'red': self.actDeact, 'green': self.createDel, 'yellow': self.autoSsWap, "menu": self.close}) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.getSwapDevice) self.updateSwap() def updateSwap(self, result = None, retval = None, extra_args = None): self["actions"].setEnabled(False) self.swap_active = False self['autostart_on'].hide() self['autostart_off'].show() self['active'].hide() self['inactive'].show() self['labplace'].hide() self['labsize'].hide() self['swapactive_summary'].setText(_("Current Status:")) scanning = _("Wait please while scanning...") self['lab1'].setText(scanning) self.activityTimer.start(10) def getSwapDevice(self): self.activityTimer.stop() if path.exists('/etc/rcS.d/S98SwapManager'): remove('/etc/rcS.d/S98SwapManager') config.plugins.infopanel.swapautostart.value = True config.plugins.infopanel.swapautostart.save() if path.exists('/tmp/swapdevices.tmp'): remove('/tmp/swapdevices.tmp') self.Console.ePopen("sfdisk -l /dev/sd? 2>/dev/null | grep swap", self.updateSwap2) def updateSwap2(self, result = None, retval = None, extra_args = None): self.swapsize = 0 self.swap_place = '' self.swap_active = False self.device = False if result.find('sd') > 0: self['key_green'].setText("") for line in result.split('\n'): if line.find('sd') > 0: parts = line.strip().split() self.swap_place = parts[0] if self.swap_place == 'sfdisk:': self.swap_place = '' self.device = True f = open('/proc/swaps', 'r') for line in f.readlines(): parts = line.strip().split() if line.find('partition') != -1: self.swap_active = True self.swapsize = parts[2] continue f.close() else: self['key_green'].setText(_("Create")) devicelist = [] for p in harddiskmanager.getMountedPartitions(): d = path.normpath(p.mountpoint) if path.exists(p.mountpoint) and p.mountpoint != "/" and not p.mountpoint.startswith('/media/net') and not p.mountpoint.startswith('/media/autofs'): devicelist.append((p.description, d)) if len(devicelist): for device in devicelist: for filename in glob(device[1] + '/swap*'): self.swap_place = filename self['key_green'].setText(_("Delete")) info = mystat(self.swap_place) self.swapsize = info[stat.ST_SIZE] continue if config.plugins.infopanel.swapautostart.value and self.swap_place: self['autostart_off'].hide() self['autostart_on'].show() else: config.plugins.infopanel.swapautostart.value = False config.plugins.infopanel.swapautostart.save() configfile.save() self['autostart_on'].hide() self['autostart_off'].show() self['labplace'].setText(self.swap_place) self['labplace'].show() f = open('/proc/swaps', 'r') for line in f.readlines(): parts = line.strip().split() if line.find('partition') != -1: self.swap_active = True continue elif line.find('file') != -1: self.swap_active = True continue f.close() if self.swapsize > 0: if self.swapsize >= 1024: self.swapsize = int(self.swapsize) / 1024 if self.swapsize >= 1024: self.swapsize = int(self.swapsize) / 1024 self.swapsize = str(self.swapsize) + ' ' + 'MB' else: self.swapsize = str(self.swapsize) + ' ' + 'KB' else: self.swapsize = '' self['labsize'].setText(self.swapsize) self['labsize'].show() if self.swap_active == True: self['inactive'].hide() self['active'].show() self['key_red'].setText(_("Deactivate")) self['swapactive_summary'].setText(_("Current Status:") + ' ' + _("Active")) else: self['inactive'].show() self['active'].hide() self['key_red'].setText(_("Activate")) self['swapactive_summary'].setText(_("Current Status:") + ' ' + _("Inactive")) scanning = _("Enable Swap at startup") self['lab1'].setText(scanning) self['lab1'].show() self["actions"].setEnabled(True) name = self['labplace'].text self['swapname_summary'].setText(name) def actDeact(self): if self.swap_active == True: self.Console.ePopen('swapoff ' + self.swap_place, self.updateSwap) else: if not self.device: if self.swap_place != '': self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) else: mybox = self.session.open(MessageBox, _("Swap File not found. You have to create the file before to activate."), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) else: self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) def createDel(self): if not self.device: if self.swap_place != '': if self.swap_active == True: self.Console.ePopen('swapoff ' + self.swap_place, self.createDel2) else: self.createDel2(None, 0) else: self.doCreateSwap() def createDel2(self, result, retval, extra_args = None): if retval == 0: remove(self.swap_place) if config.plugins.infopanel.swapautostart.value: config.plugins.infopanel.swapautostart.value = False config.plugins.infopanel.swapautostart.save() configfile.save() self.updateSwap() def doCreateSwap(self): parts = [] supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'vfat')) candidates = [] mounts = getProcMounts() for partition in harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if len(candidates): self.session.openWithCallback(self.doCSplace, ChoiceBox, title = _("Please select device to use as swapfile location"), list = candidates) else: self.session.open(MessageBox, _("Sorry, no physical devices that supports SWAP attached. Can't create Swapfile on network or fat32 filesystems"), MessageBox.TYPE_INFO, timeout = 10) def doCSplace(self, name): if name: self.new_place = name[1] myoptions = [[_("32 Mb"), '32768'], [_("64 Mb"), '65536'], [_("128 Mb"), '131072'], [_("256 Mb"), '262144'], [_("512 Mb"), '524288']] self.session.openWithCallback(self.doCSsize, ChoiceBox, title=_("Select the Swap File Size:"), list=myoptions) def doCSsize(self, swapsize): if swapsize: self["actions"].setEnabled(False) scanning = _("Wait please while creating swapfile...") self['lab1'].setText(scanning) self['lab1'].show() swapsize = swapsize[1] myfile = self.new_place + '/swapfile' self.commands = [] self.commands.append('dd if=/dev/zero of=' + myfile + ' bs=1024 count=' + swapsize + ' 2>/dev/null') self.commands.append('mkswap ' + myfile) self.Console.eBatch(self.commands, self.updateSwap, debug=True) def autoSsWap(self): if self.swap_place: if config.plugins.infopanel.swapautostart.value: config.plugins.infopanel.swapautostart.value = False config.plugins.infopanel.swapautostart.save() else: config.plugins.infopanel.swapautostart.value = True config.plugins.infopanel.swapautostart.save() configfile.save() else: mybox = self.session.open(MessageBox, _("You have to create a Swap File before to activate the autostart."), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) self.updateSwap()
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 = "/usr/sbin/ethtool" self.container = eConsoleAppContainer() self.Console = Console() self.LinkConsole = Console() self.restartConsole = Console() self.deactivateConsole = Console() self.deactivateInterfaceConsole = Console() self.activateConsole = Console() self.resetNetworkConsole = Console() self.DnsConsole = Console() self.config_ready = None self.getInterfaces() def getInterfaces(self, callback = None): devicesPattern = re_compile('[a-z]+[0-9]+') self.configuredInterfaces = [] fp = file('/proc/net/dev', 'r') result = fp.readlines() fp.close() for line in result: try: device = devicesPattern.search(line).group() if device == 'wifi0': continue self.getDataForInterface(device, callback) except AttributeError: pass #print "self.ifaces:", self.ifaces #self.writeNetworkConfig() #print ord(' ') #for line in result: # print ord(line[0]) # helper function def regExpMatch(self, pattern, string): if string is None: return None try: return pattern.search(string).group() except AttributeError: None # helper function to convert ips from a sring to a list of ints def convertIP(self, ip): strIP = ip.split('.') ip = [] for x in strIP: ip.append(int(x)) return ip def getDataForInterface(self, iface,callback): #get ip out of ip addr, as avahi sometimes overrides it in ifconfig. if not self.Console: self.Console = Console() cmd = "ip -o addr" 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, 'postdown' : 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-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{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('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}') 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 is not None: 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 enigma 2\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("\n" + iface["configStrings"] + "\n") if iface["preup"] is not False and not iface.has_key("configStrings"): fp.write(iface["preup"]) fp.write(iface["postdown"]) fp.write("\n") fp.close() 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] == "post-down"): if self.ifaces[currif].has_key("postdown"): self.ifaces[currif]["postdown"] = 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 interfac:", 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 is not None: self.nameservers.append(self.convertIP(ip)) print "nameservers:", self.nameservers def deactivateNetworkConfig(self, callback = None): self.deactivateConsole = Console() self.commands = [] self.commands.append("/etc/init.d/avahi-daemon stop") for iface in self.ifaces.keys(): cmd = "ip addr flush " + iface self.commands.append(cmd) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") self.deactivateConsole.eBatch(self.commands, self.deactivateNetworkFinished, callback, debug=True) def deactivateNetworkFinished(self,extra_args): callback = extra_args if len(self.deactivateConsole.appContainers) == 0: if callback is not None: callback(True) def activateNetworkConfig(self, callback = None): self.activateConsole = Console() self.commands = [] #+++> self.configuredInterfaces = [] for ifacename, iface in self.ifaces.items(): if iface['dhcp'] == True: self.commands.append("/etc/init.d/udhcpc start") #+++< self.commands.append("/etc/init.d/networking start") self.commands.append("/etc/init.d/avahi-daemon start") self.activateConsole.eBatch(self.commands, self.activateNetworkFinished, callback, debug=True) def activateNetworkFinished(self,extra_args): callback = extra_args if len(self.activateConsole.appContainers) == 0: if callback is not None: callback(True) def getConfiguredAdapters(self): return self.configuredNetworkAdapters def getNumberOfAdapters(self): return len(self.ifaces) def getFriendlyAdapterName(self, x): # maybe this needs to be replaced by an external list. friendlyNames = { "eth0": _("Integrated Ethernet"), "wlan0": _("Wireless"), "ath0": _("Integrated Wireless") } return friendlyNames.get(x, x) # when we have no friendly name, use adapter name 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] return None 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(): cmd = "ip addr flush " + iface self.commands.append(cmd) 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 enigma 2\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): # www.dream-multimedia-tv.de, www.heise.de, www.google.de cmd1 = "ping -c 1 82.149.226.170" cmd2 = "ping -c 1 193.99.144.85" cmd3 = "ping -c 1 209.85.135.103" 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(): cmd = "ip addr flush " + iface self.commands.append(cmd) self.commands.append("/etc/init.d/networking stop") self.commands.append("killall -9 udhcpc") self.commands.append("rm /var/run/udhcpc*") #+++> self.configuredInterfaces = [] for ifacename, iface in self.ifaces.items(): if iface['dhcp'] == True: self.commands.append("/etc/init.d/udhcpc start") #+++< 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 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: if len(self.deactivateInterfaceConsole.appContainers): for name in self.deactivateInterfaceConsole.appContainers.keys(): self.deactivateInterfaceConsole.kill(name) 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): 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,iface,callback = None): self.deactivateInterfaceConsole = Console() self.commands = [] cmd1 = "ip addr flush " + iface cmd2 = "ifconfig " + iface + " down" self.commands.append(cmd1) self.commands.append(cmd2) self.deactivateInterfaceConsole.eBatch(self.commands, self.deactivateInterfaceFinished, callback, debug=True) def deactivateInterfaceFinished(self,extra_args): callback = extra_args if self.deactivateInterfaceConsole: if len(self.deactivateInterfaceConsole.appContainers) == 0: if callback is not None: callback(True) def detectWlanModule(self): self.wlanmodule = None rt73_dir = "/sys/bus/usb/drivers/rt73/" zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/" madwifi_dir = "/sys/bus/pci/drivers/ath_pci/" if os_path.exists(madwifi_dir): files = listdir(madwifi_dir) if len(files) >= 1: self.wlanmodule = 'madwifi' if os_path.exists(rt73_dir): rtfiles = listdir(rt73_dir) if len(rtfiles) == 2: self.wlanmodule = 'ralink' if os_path.exists(zd1211b_dir): zdfiles = listdir(zd1211b_dir) if len(zdfiles) == 1: self.wlanmodule = 'zydas' return self.wlanmodule 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 VIXSwap(Screen): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Swap Manager")) self['lab1'] = Label() self['autostart_on'] = Pixmap() self['autostart_off'] = Pixmap() self['lab2'] = Label(_("Swap Place:")) self['labplace'] = Label() self['lab3'] = Label(_("Swap Size:")) self['labsize'] = Label() self['lab4'] = Label(_("Status:")) self['inactive'] = Label(_("Inactive")) self['active'] = Label(_("Active")) self['key_red'] = Label(_("Close")) self['key_green'] = Label(_("Activate")) self['key_blue'] = Label(_("Create")) self['key_yellow'] = Label(_("Autostart")) self['swapname_summary'] = StaticText() self['swapactive_summary'] = StaticText() self.Console = Console() self.swap_place = '' self.new_place = '' self.creatingswap = False self.swap_active = False self['actions'] = ActionMap(['WizardActions', 'ColorActions', "MenuActions"], {'back': self.close, 'red': self.close, 'green': self.actDeact, 'yellow': self.autoSsWap, 'blue': self.createDel, "menu": self.close}) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.getSwapDevice) self.updateSwap() def updateSwap(self, result=None, retval=None, extra_args=None): self["actions"].setEnabled(False) self.swap_active = False self.swap_place = None self['autostart_on'].hide() self['autostart_off'].show() self['active'].hide() self['inactive'].show() self['labplace'].hide() self['labsize'].hide() self['swapactive_summary'].setText(_("Current Status:")) scanning = _("Wait please while scanning...") self['lab1'].setText(scanning) self.activityTimer.start(10) def getSwapDevice(self): self.activityTimer.stop() if path.exists('/etc/rcS.d/S98SwapManager'): remove('/etc/rcS.d/S98SwapManager') config.vixsettings.swapautostart.value = True config.vixsettings.swapautostart.save() if path.exists('/tmp/swapdevices.tmp'): remove('/tmp/swapdevices.tmp') self.Console.ePopen("parted -l /dev/sd? | grep swap", self.updateSwap2) def updateSwap2(self, result=None, retval=None, extra_args=None): self.swapsize = 0 self.swap_place = '' self.swap_active = False self.device = False if result.find('sd') > 0: self['key_blue'].setText("") for line in result.split('\n'): if line.find('sd') > 0: parts = line.strip().split() self.swap_place = parts[0] if self.swap_place == 'sfdisk:': self.swap_place = '' self.device = True f = open('/proc/swaps', 'r') for line2 in f.readlines(): parts = line.strip().split() if line2.find('partition') != -1: self.swap_active = True self.swapsize = parts[2] continue f.close() else: self['key_blue'].setText(_("Create")) devicelist = [] for p in harddiskmanager.getMountedPartitions(): d = path.normpath(p.mountpoint) if path.exists(p.mountpoint) and p.mountpoint != "/" and not p.mountpoint.startswith('/media/net'): devicelist.append((p.description, d)) if len(devicelist): for device in devicelist: for filename in glob(device[1] + '/swap*'): self.swap_place = filename self['key_blue'].setText(_("Delete")) info = mystat(self.swap_place) self.swapsize = info[stat.ST_SIZE] continue if config.vixsettings.swapautostart.value and self.swap_place: self['autostart_off'].hide() self['autostart_on'].show() else: config.vixsettings.swapautostart.setValue(False) config.vixsettings.swapautostart.save() configfile.save() self['autostart_on'].hide() self['autostart_off'].show() self['labplace'].setText(self.swap_place) self['labplace'].show() f = open('/proc/swaps', 'r') for line in f.readlines(): parts = line.strip().split() if line.find('partition') != -1: self.swap_active = True continue elif line.find('file') != -1: self.swap_active = True continue f.close() if self.swapsize > 0: if self.swapsize >= 1024: self.swapsize = int(self.swapsize) / 1024 if self.swapsize >= 1024: self.swapsize = int(self.swapsize) / 1024 self.swapsize = str(self.swapsize) + ' ' + 'MB' else: self.swapsize = str(self.swapsize) + ' ' + 'KB' else: self.swapsize = '' self['labsize'].setText(self.swapsize) self['labsize'].show() if self.swap_active: self['inactive'].hide() self['active'].show() self['key_green'].setText(_("Deactivate")) self['swapactive_summary'].setText(_("Current Status:") + ' ' + _("Active")) else: self['inactive'].show() self['active'].hide() self['key_green'].setText(_("Activate")) self['swapactive_summary'].setText(_("Current Status:") + ' ' + _("Inactive")) scanning = _("Enable Swap at startup") self['lab1'].setText(scanning) self['lab1'].show() self["actions"].setEnabled(True) name = self['labplace'].text self['swapname_summary'].setText(name) def actDeact(self): if self.swap_active: self.Console.ePopen('swapoff ' + self.swap_place, self.updateSwap) else: if not self.device: if self.swap_place != '': self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) else: mybox = self.session.open(MessageBox, _("Swap File not found. You have to create the file before to activate."), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) else: self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) def createDel(self): if not self.device: if self.swap_place != '': if self.swap_active: self.Console.ePopen('swapoff ' + self.swap_place, self.createDel2) else: self.createDel2(None, 0) else: self.doCreateSwap() def createDel2(self, result, retval, extra_args=None): if retval == 0: remove(self.swap_place) if config.vixsettings.swapautostart.value: config.vixsettings.swapautostart.setValue(False) config.vixsettings.swapautostart.save() configfile.save() self.updateSwap() def doCreateSwap(self): parts = [] supported_filesystems = frozenset(('ext4', 'ext3', 'ext2')) candidates = [] mounts = getProcMounts() for partition in harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append((partition.description, partition.mountpoint)) if len(candidates): self.session.openWithCallback(self.doCSplace, ChoiceBox, title=_("Please select device to use as swapfile location"), list=candidates) else: self.session.open(MessageBox, _("Sorry, no physical devices that supports SWAP attached. Can't create Swapfile on network or fat32 filesystems"), MessageBox.TYPE_INFO, timeout=10) def doCSplace(self, name): if name: self.new_place = name[1] myoptions = [[_("8 Mb"), '8192'], [_("16 Mb"), '16384'], [_("32 Mb"), '32768'], [_("64 Mb"), '65536'], [_("96 Mb"), '98304'], [_("128 Mb"), '131072'], [_("256 Mb"), '262144']] self.session.openWithCallback(self.doCSsize, ChoiceBox, title=_("Select the Swap File Size:"), list=myoptions) def doCSsize(self, swapsize): if swapsize: self["actions"].setEnabled(False) scanning = _("Wait please while creating swapfile...") self['lab1'].setText(scanning) self['lab1'].show() swapsize = swapsize[1] myfile = self.new_place + 'swapfile' self.commands = [] self.commands.append('dd if=/dev/zero of=' + myfile + ' bs=1024 count=' + swapsize + ' 2>/dev/null') self.commands.append('mkswap ' + myfile) self.Console.eBatch(self.commands, self.updateSwap, debug=True) def autoSsWap(self): if self.swap_place: if config.vixsettings.swapautostart.value: config.vixsettings.swapautostart.setValue(False) config.vixsettings.swapautostart.save() else: config.vixsettings.swapautostart.setValue(True) config.vixsettings.swapautostart.save() configfile.save() else: mybox = self.session.open(MessageBox, _("You have to create a Swap File before to activate the autostart."), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) self.updateSwap()
class SwapManager(Screen): skin = """ <screen name="SwapManager" position="center,center" size="420,250" title="Swap File Manager" flags="wfBorder" > <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" /> <widget name="key_red" position="0,0" zPosition="1" size="150,40" font="Regular;18" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="140,0" zPosition="1" size="140,40" font="Regular;18" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="280,0" zPosition="1" size="140,40" font="Regular;18" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="autostart_off" position="10,50" zPosition="1" pixmap="skin_default/icons/lock_off.png" size="32,32" alphatest="on" /> <widget name="autostart_on" position="10,50" zPosition="2" pixmap="skin_default/icons/lock_on.png" size="32,32" alphatest="on" /> <widget name="lab1" position="50,50" size="360,30" font="Regular;18" valign="center" transparent="1"/> <widget name="lab2" position="10,100" size="150,30" font="Regular;18" valign="center" transparent="1"/> <widget name="lab3" position="10,150" size="150,30" font="Regular;18" valign="center" transparent="1"/> <widget name="lab4" position="10,200" size="150,30" font="Regular;18" valign="center" transparent="1" /> <widget name="labplace" position="160,100" size="220,30" font="Regular;18" valign="center" backgroundColor="#4D5375"/> <widget name="labsize" position="160,150" size="220,30" font="Regular;18" valign="center" backgroundColor="#4D5375"/> <widget name="inactive" position="160,200" size="110,30" font="Regular;17" valign="center" halign="center" backgroundColor="red"/> <widget name="active" position="160,200" size="110,30" font="Regular;17" valign="center" halign="center" backgroundColor="green"/> </screen>""" def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Swap Manager")) self['lab1'] = Label() self['autostart_on'] = Pixmap() self['autostart_off'] = Pixmap() self['lab2'] = Label(_("Swap Place:")) self['labplace'] = Label() self['lab3'] = Label(_("Swap Size:")) self['labsize'] = Label() self['lab4'] = Label(_("Status:")) self['inactive'] = Label(_("Inactive")) self['active'] = Label(_("Active")) self['key_red'] = Label(_("Activate")) self['key_green'] = Label(_("Create")) self['key_yellow'] = Label(_("Autostart")) self['swapname_summary'] = StaticText() self['swapactive_summary'] = StaticText() self.Console = Console() self.swap_place = '' self.new_place = '' self.creatingswap = False self['actions'] = ActionMap( ['WizardActions', 'ColorActions', "MenuActions"], { 'back': self.close, 'red': self.actDeact, 'green': self.createDel, 'yellow': self.autoSsWap, "menu": self.close }) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.getSwapDevice) self.updateSwap() def updateSwap(self, result=None, retval=None, extra_args=None): self["actions"].setEnabled(False) self.swap_active = False self['autostart_on'].hide() self['autostart_off'].show() self['active'].hide() self['inactive'].show() self['labplace'].hide() self['labsize'].hide() self['swapactive_summary'].setText(_("Current Status:")) scanning = _("Wait please while scanning...") self['lab1'].setText(scanning) self.activityTimer.start(10) def getSwapDevice(self): self.activityTimer.stop() if path.exists('/etc/rcS.d/S98SwapManager'): remove('/etc/rcS.d/S98SwapManager') config.plugins.swapmanager.swapautostart.value = True config.plugins.swapmanager.swapautostart.save() if path.exists('/tmp/swapdevices.tmp'): remove('/tmp/swapdevices.tmp') self.Console.ePopen("sfdisk -l /dev/sd? | grep swap", self.updateSwap2) def updateSwap2(self, result=None, retval=None, extra_args=None): self.swapsize = 0 self.swap_place = '' self.swap_active = False self.device = False if result.find('sd') > 0: self['key_green'].setText("") for line in result.split('\n'): if line.find('sd') > 0: parts = line.strip().split() self.swap_place = parts[0] if self.swap_place == 'sfdisk:': self.swap_place = '' self.device = True f = open('/proc/swaps', 'r') for line in f.readlines(): parts = line.strip().split() if line.find('partition') != -1: self.swap_active = True self.swapsize = parts[2] continue f.close() else: self['key_green'].setText(_("Create")) devicelist = [] for p in harddiskmanager.getMountedPartitions(): d = path.normpath(p.mountpoint) if path.exists( p.mountpoint ) and p.mountpoint != "/" and not p.mountpoint.startswith( '/media/net'): devicelist.append((p.description, d)) if len(devicelist): for device in devicelist: for filename in glob(device[1] + '/swap*'): self.swap_place = filename self['key_green'].setText(_("Delete")) info = mystat(self.swap_place) self.swapsize = info[stat.ST_SIZE] continue if config.plugins.swapmanager.swapautostart.value and self.swap_place: self['autostart_off'].hide() self['autostart_on'].show() else: config.plugins.swapmanager.swapautostart.setValue(False) config.plugins.swapmanager.swapautostart.save() configfile.save() self['autostart_on'].hide() self['autostart_off'].show() self['labplace'].setText(self.swap_place) self['labplace'].show() f = open('/proc/swaps', 'r') for line in f.readlines(): parts = line.strip().split() if line.find('partition') != -1: self.swap_active = True continue elif line.find('file') != -1: self.swap_active = True continue f.close() if self.swapsize > 0: if self.swapsize >= 1024: self.swapsize = int(self.swapsize) / 1024 if self.swapsize >= 1024: self.swapsize = int(self.swapsize) / 1024 self.swapsize = str(self.swapsize) + ' ' + 'MB' else: self.swapsize = str(self.swapsize) + ' ' + 'KB' else: self.swapsize = '' self['labsize'].setText(self.swapsize) self['labsize'].show() if self.swap_active == True: self['inactive'].hide() self['active'].show() self['key_red'].setText(_("Deactivate")) self['swapactive_summary'].setText( _("Current Status:") + ' ' + _("Active")) else: self['inactive'].show() self['active'].hide() self['key_red'].setText(_("Activate")) self['swapactive_summary'].setText( _("Current Status:") + ' ' + _("Inactive")) scanning = _("Enable Swap at startup") self['lab1'].setText(scanning) self['lab1'].show() self["actions"].setEnabled(True) name = self['labplace'].text self['swapname_summary'].setText(name) def actDeact(self): if self.swap_active == True: self.Console.ePopen('swapoff ' + self.swap_place, self.updateSwap) else: if not self.device: if self.swap_place != '': self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) else: mybox = self.session.open( MessageBox, _("Swap File not found. You have to create the file before to activate." ), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) else: self.Console.ePopen('swapon ' + self.swap_place, self.updateSwap) def createDel(self): if not self.device: if self.swap_place != '': if self.swap_active == True: self.Console.ePopen('swapoff ' + self.swap_place, self.createDel2) else: self.createDel2(None, 0) else: self.doCreateSwap() def createDel2(self, result, retval, extra_args=None): if retval == 0: remove(self.swap_place) if config.plugins.swapmanager.swapautostart.value: config.plugins.swapmanager.swapautostart.setValue(False) config.plugins.swapmanager.swapautostart.save() configfile.save() self.updateSwap() def doCreateSwap(self): parts = [] supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'vfat')) candidates = [] mounts = getProcMounts() for partition in harddiskmanager.getMountedPartitions(False, mounts): if partition.filesystem(mounts) in supported_filesystems: candidates.append( (partition.description, partition.mountpoint)) if len(candidates): self.session.openWithCallback( self.doCSplace, ChoiceBox, title=_("Please select device to use as swapfile location"), list=candidates) else: self.session.open( MessageBox, _("Sorry, no physical devices that supports SWAP attached. Can't create Swapfile on network or fat32 filesystems" ), MessageBox.TYPE_INFO, timeout=10) def doCSplace(self, name): if name: self.new_place = name[1] myoptions = [[_("8 MB"), '8192'], [_("16 MB"), '16384'], [_("32 MB"), '32768'], [_("64 MB"), '65536'], [_("96 MB"), '98304'], [_("128 MB"), '131072'], [_("256 MB"), '262144'], [_("512 MB"), '524288'], [_("1024 MB"), '1048576']] self.session.openWithCallback( self.doCSsize, ChoiceBox, title=_("Select the Swap File Size:"), list=myoptions) def doCSsize(self, swapsize): if swapsize: self["actions"].setEnabled(False) scanning = _("Wait please while creating swapfile...") self['lab1'].setText(scanning) self['lab1'].show() swapsize = swapsize[1] myfile = self.new_place + '/swapfile' self.commands = [] self.commands.append('dd if=/dev/zero of=' + myfile + ' bs=1024 count=' + swapsize + ' 2>/dev/null') self.commands.append('mkswap ' + myfile) self.Console.eBatch(self.commands, self.updateSwap, debug=True) def autoSsWap(self): if self.swap_place: if config.plugins.swapmanager.swapautostart.value: config.plugins.swapmanager.swapautostart.setValue(False) config.plugins.swapmanager.swapautostart.save() else: config.plugins.swapmanager.swapautostart.setValue(True) config.plugins.swapmanager.swapautostart.save() configfile.save() else: mybox = self.session.open( MessageBox, _("You have to create a Swap File before to activate the autostart." ), MessageBox.TYPE_INFO) mybox.setTitle(_("Info")) self.updateSwap()
class AutoMount(): """Manages Mounts declared in a XML-Document.""" def __init__(self): self.automounts = {} self.restartConsole = Console() self.MountConsole = Console() self.removeConsole = Console() self.activeMountsCounter = 0 # Initialize Timer self.callback = None self.timer = eTimer() self.timer.callback.append(self.mountTimeout) self.getAutoMountPoints() def getAutoMountPoints(self, callback=None, restart=False): # Initialize mounts to empty list automounts = [] self.automounts = {} self.activeMountsCounter = 0 if not os.path.exists(XML_FSTAB): return file = open(XML_FSTAB, 'r') tree = cet_parse(file).getroot() file.close() def getValue(definitions, default): # Initialize Output ret = "" # How many definitions are present Len = len(definitions) return Len > 0 and definitions[Len - 1].text or default mountusing = 0 # 0=old_enigma2, 1 =fstab, 2=enigma2 # Config is stored in "mountmanager" element # Read out NFS Mounts for autofs in tree.findall("autofs"): mountusing = 1 for nfs in autofs.findall("nfs"): for mount in nfs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'autofs'.encode("UTF-8") data['mounttype'] = 'nfs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/media/hdd/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,nolock,tcp,utf8").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) for cifs in autofs.findall("cifs"): for mount in cifs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'autofs'.encode("UTF-8") data['mounttype'] = 'cifs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/media/hdd/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,utf8").encode("UTF-8") data['username'] = getValue(mount.findall("username"), "guest").encode("UTF-8") data['password'] = getValue(mount.findall("password"), "").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) for fstab in tree.findall("fstab"): mountusing = 2 for nfs in fstab.findall("nfs"): for mount in nfs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'fstab'.encode("UTF-8") data['mounttype'] = 'nfs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/media/hdd/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,nolock,tcp,utf8").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) for cifs in fstab.findall("cifs"): for mount in cifs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'fstab'.encode("UTF-8") data['mounttype'] = 'cifs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/media/hdd/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,utf8").encode("UTF-8") data['username'] = getValue(mount.findall("username"), "guest").encode("UTF-8") data['password'] = getValue(mount.findall("password"), "").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) for enigma2 in tree.findall("enigma2"): mountusing = 3 for nfs in enigma2.findall("nfs"): for mount in nfs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'enigma2'.encode("UTF-8") data['mounttype'] = 'nfs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/exports/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,nolock,tcp,utf8").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) # Read out CIFS Mounts for cifs in enigma2.findall("cifs"): for mount in cifs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'enigma2'.encode("UTF-8") data['mounttype'] = 'cifs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/exports/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,utf8").encode("UTF-8") data['username'] = getValue(mount.findall("username"), "guest").encode("UTF-8") data['password'] = getValue(mount.findall("password"), "").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) if mountusing == 0: for nfs in tree.findall("nfs"): for mount in nfs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'old_enigma2'.encode("UTF-8") data['mounttype'] = 'nfs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/exports/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,nolock,tcp,utf8").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) for cifs in tree.findall("cifs"): for mount in cifs.findall("mount"): data = {'isMounted': False, 'mountusing': False, 'active': False, 'ip': False, 'sharename': False, 'sharedir': False, 'username': False, 'password': False, 'mounttype': False, 'options': False, 'hdd_replacement': False} try: data['mountusing'] = 'old_enigma2'.encode("UTF-8") data['mounttype'] = 'cifs'.encode("UTF-8") data['active'] = getValue(mount.findall("active"), False).encode("UTF-8") if data["active"] == 'True' or data["active"] == True: self.activeMountsCounter += 1 data['hdd_replacement'] = getValue(mount.findall("hdd_replacement"), "False").encode("UTF-8") data['ip'] = getValue(mount.findall("ip"), "192.168.0.0").encode("UTF-8") data['sharedir'] = getValue(mount.findall("sharedir"), "/exports/").encode("UTF-8") data['sharename'] = getValue(mount.findall("sharename"), "MEDIA").encode("UTF-8") data['options'] = getValue(mount.findall("options"), "rw,utf8").encode("UTF-8") data['username'] = getValue(mount.findall("username"), "guest").encode("UTF-8") data['password'] = getValue(mount.findall("password"), "").encode("UTF-8") self.automounts[data['sharename']] = data except Exception as e: print("[MountManager] Error reading Mounts:", e) self.checkList = self.automounts.keys() if not self.checkList: # print "[NetworkBrowser] self.automounts without mounts",self.automounts if callback is not None: callback(True) else: self.CheckMountPoint(self.checkList.pop(), callback, restart) def sanitizeOptions(self, origOptions, cifs=False, fstab=False, autofs=False): options = origOptions.strip() options = options.replace('utf8', 'iocharset=utf8') if fstab: if not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=8192,wsize=8192,proto=tcp' else: if not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' options = options + ',timeo=14,soft' elif autofs: if not options: options = 'rw' if not cifs: options += ',nfsvers=3,rsize=8192,wsize=8192' else: if not cifs: options += ',nfsvers=3' if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' options = options + ',timeo=14,soft' else: if not options: options = 'rw,rsize=8192,wsize=8192' if not cifs: options += ',proto=tcp' else: if not cifs: if 'rsize' not in options: options += ',rsize=8192' if 'wsize' not in options: options += ',wsize=8192' if 'tcp' not in options and 'udp' not in options: options += ',proto=tcp' return options def CheckMountPoint(self, item, callback, restart): data = self.automounts[item] if not self.MountConsole: self.MountConsole = Console() command = [] mountcommand = None unmountcommand = [] if data['mountusing'] == 'autofs': path = os.path.join('/media/autofs', data['sharename']) elif data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', data['sharename']) if data['mountusing'] == 'autofs' and restart: unmountcommand.append("/etc/init.d/autofs stop") if os.path.ismount(path) and 'autofs' not in path: unmountcommand.append('umount -fl ' + path) if self.activeMountsCounter != 0: if data['active'] == 'True' or data['active'] is True: if data['mountusing'] == 'autofs' and restart: mountcommand = "/etc/init.d/autofs start" elif data['mountusing'] == 'fstab': if data['mounttype'] == 'nfs': tmpcmd = 'mount ' + data['ip'] + ':/' + data['sharedir'] elif data['mounttype'] == 'cifs': tmpcmd = 'mount //' + data['ip'] + '/' + data['sharedir'] mountcommand = tmpcmd.encode("UTF-8") elif data['mountusing'] == 'enigma2' or data['mountusing'] == 'old_enigma2': tmpsharedir = data['sharedir'].replace(" ", "\\ ") if tmpsharedir[-1:] == "$": tmpdir = tmpsharedir.replace("$", "\\$") tmpsharedir = tmpdir if data['mounttype'] == 'nfs': if not os.path.ismount(path): tmpcmd = 'mount -t nfs -o ' + self.sanitizeOptions(data['options']) + ' ' + data['ip'] + ':/' + tmpsharedir + ' ' + path mountcommand = tmpcmd.encode("UTF-8") elif data['mounttype'] == 'cifs': if not os.path.ismount(path): tmpusername = data['username'].replace(" ", "\\ ") tmpcmd = 'mount -t cifs -o ' + self.sanitizeOptions(data['options'], cifs=True) + ',noatime,noserverino,username='******',password='******'password'] + ' //' + data['ip'] + '/' + tmpsharedir + ' ' + path mountcommand = tmpcmd.encode("UTF-8") if len(unmountcommand) > 0 or mountcommand is not None: if len(unmountcommand) > 0: for x in unmountcommand: command.append(x) if not os.path.exists(path) and data['mountusing'] != 'autofs': command.append('mkdir -p ' + path) if command is not None: command.append('sleep 2') if mountcommand is not None: command.append(mountcommand) print('command', command) self.MountConsole.eBatch(command, self.CheckMountPointFinished, [data, callback, restart], debug=True) else: self.CheckMountPointFinished([data, callback, restart]) def CheckMountPointFinished(self, extra_args): # print "[NetworkBrowser] CheckMountPointFinished" (data, callback, restart) = extra_args hdd_dir = '/media/hdd' sharepath = os.path.join('/media/net', data['sharename']) if data['mountusing'] == 'autofs': sharepath = os.path.join('/media/autofs', data['sharename']) path = os.path.join('/media/autofs', data['sharename']) elif data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', data['sharename']) if os.path.exists(path): if data['mountusing'] == 'autofs': if data['sharename'] in self.automounts: self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(sharepath, desc) if data['hdd_replacement'] == 'True' or data['hdd_replacement'] is True: if os.path.islink(hdd_dir): if os.readlink(hdd_dir) != path: os.unlink(hdd_dir) os.symlink(path, hdd_dir) elif not os.path.exists(hdd_dir): os.symlink(path, hdd_dir) elif os.path.ismount(path): if data['sharename'] in self.automounts: self.automounts[data['sharename']]['isMounted'] = True desc = data['sharename'] harddiskmanager.addMountedPartition(path, desc) else: if data['sharename'] in self.automounts: self.automounts[data['sharename']]['isMounted'] = False if os.path.exists(path): if not os.path.ismount(path): try: rmtree(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print("Failed to remove", path, "Error:", ex) if self.checkList: # Go to next item in list... self.CheckMountPoint(self.checkList.pop(), callback, restart) if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1) def mountTimeout(self): self.timer.stop() if self.MountConsole: if len(self.MountConsole.appContainers) == 0: if self.callback is not None: self.callback(True) elif self.removeConsole: if len(self.removeConsole.appContainers) == 0: if self.callback is not None: self.callback(True) def getMountsList(self): return self.automounts def getMountsAttribute(self, mountpoint, attribute): if mountpoint in self.automounts: if attribute in self.automounts[mountpoint]: return self.automounts[mountpoint][attribute] return None def setMountsAttribute(self, mountpoint, attribute, value): if mountpoint in self.automounts: self.automounts[mountpoint][attribute] = value def removeEntryFromFile(self, entry, filename, separator=None): if os.path.exists(filename): f = open(filename) tmpfile = open(filename + '.tmp', 'w') tmpfile.writelines([line for line in f.readlines() if entry not in line.split(separator)]) tmpfile.close() f.close() os.rename(filename + '.tmp', filename) def escape(self, data): return data.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') def generateMountXML(self, sharedata): res = [] mounttype = self.escape(sharedata['mounttype']) mountusing = self.escape(sharedata['mountusing']) if mountusing != 'old_enigma2': res.append('<' + mountusing + '>\n') res.append(' <' + mounttype + '>\n') res.append(' <mount>\n') res.append(' <active>' + self.escape(str(sharedata['active'])) + '</active>\n') res.append(' <hdd_replacement>' + self.escape(str(sharedata['hdd_replacement'])) + '</hdd_replacement>\n') res.append(' <ip>' + self.escape(sharedata['ip']) + '</ip>\n') res.append(' <sharename>' + self.escape(sharedata['sharename']) + '</sharename>\n') res.append(' <sharedir>' + self.escape(sharedata['sharedir']) + '</sharedir>\n') res.append(' <options>' + self.escape(sharedata['options']) + '</options>\n') if mounttype == 'cifs': res.append(" <username>" + self.escape(sharedata['username']) + "</username>\n") res.append(" <password>" + self.escape(sharedata['password']) + "</password>\n") res.append(' </mount>\n') res.append(' </' + mounttype + '>\n') if mountusing != 'old_enigma2': res.append('</' + mountusing + '>\n') return res def writeMountsConfig(self): # Generate List in RAM list = ['<?xml version="1.0" ?>\n<mountmanager>\n'] for sharename, sharedata in self.automounts.items(): mounttype = sharedata['mounttype'] mountusing = sharedata['mountusing'] if sharedata['hdd_replacement'] == 'True' or sharedata['hdd_replacement'] is True: #hdd replacement hack path = os.path.join('/media/hdd') sharepath = os.path.join('/media/net', sharedata['sharename']) else: path = os.path.join('/media/net', sharedata['sharename']) sharepath = "" sharetemp = None if mounttype == 'nfs': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] self.removeEntryFromFile(sharetemp + '\n', '/etc/auto.network', ' ') self.removeEntryFromFile(sharetemp, '/etc/fstab') elif mounttype == 'cifs': sharetemp = '//' + sharedata['ip'] + '/' + sharedata['sharedir'] self.removeEntryFromFile(":" + sharetemp + '\n', '/etc/auto.network', ' ') self.removeEntryFromFile(sharetemp, '/etc/fstab') list += self.generateMountXML(sharedata) if mountusing == 'autofs': if sharedata['active'] == True or sharedata['active'] == 'True': out = open('/etc/auto.network', 'a') if mounttype == 'nfs': line = sharedata['sharename'] + ' -fstype=' + mounttype + ',' + self.sanitizeOptions(sharedata['options'], autofs=True) + ' ' + sharedata['ip'] + ':/' + sharedata['sharedir'] + '\n' elif sharedata['mounttype'] == 'cifs': tmpusername = sharedata['username'].replace(" ", "\ ") tmppassword = sharedata['password'].replace(" ", "\ ") tmpaddress = sharedata['ip'] line = sharedata['sharename'] + ' -fstype=' + mounttype + ',user='******',pass='******',' + self.sanitizeOptions(sharedata['options'], cifs=True, autofs=True) + ' ://' + tmpaddress + '/' + sharedata['sharedir'] + '\n' out.write(line) out.close() elif mountusing == 'fstab': if sharedata['active'] == True or sharedata['active'] == 'True': out = open('/etc/fstab', 'a') if sharedata['mounttype'] == 'nfs': line = sharedata['ip'] + ':/' + sharedata['sharedir'] + '\t' + path + '\tnfs\t_netdev,' + self.sanitizeOptions(sharedata['options'], fstab=True) + '\t0 0\n' elif sharedata['mounttype'] == 'cifs': line = '//' + sharedata['ip'] + '/' + sharedata['sharedir'] + '\t' + path + '\tcifs\tuser='******'username'] + ',pass='******'password'] + ',_netdev,' + self.sanitizeOptions(sharedata['options'], cifs=True, fstab=True) + '\t0 0\n' out.write(line) out.close() # Close Mountmanager Tag list.append('</mountmanager>\n') # Try Saving to Flash try: f = open(XML_FSTAB, "w") f.writelines(list) f.close() # print "[NetworkBrowser] Saving Mounts List:" except Exception as e: print("[NetworkBrowser] Error Saving Mounts List:", e) def stopMountConsole(self): if self.MountConsole is not None: self.MountConsole = None def removeMount(self, mountpoint, callback=None): # print "[NetworkBrowser] removing mount: ",mountpoint self.newautomounts = {} for sharename, sharedata in self.automounts.items(): sharepath = os.path.join('/media/net', sharedata['sharename']) if sharedata['mountusing'] == 'autofs': sharepath = os.path.join('/media/autofs', sharedata['sharename']) path = os.path.join('/media/autofs', sharedata['sharename']) if sharedata['hdd_replacement'] == 'True' or sharedata['hdd_replacement'] is True: if os.path.islink('/media/hdd'): if os.readlink('/media/hdd') == path: os.unlink('/media/hdd') elif sharedata['hdd_replacement'] == 'True' or sharedata['hdd_replacement'] is True: path = os.path.join('/media/hdd') else: path = os.path.join('/media/net', sharedata['sharename']) if sharename is not mountpoint.strip(): self.newautomounts[sharename] = sharedata if sharedata['mounttype'] == 'nfs': sharetemp = sharedata['ip'] + ':/' + sharedata['sharedir'] elif sharedata['mounttype'] == 'cifs': sharetemp = '://' + sharedata['ip'] + '/' + sharedata['sharedir'] if sharetemp: self.removeEntryFromFile(sharetemp + '\n', '/etc/auto.network', ' ') self.removeEntryFromFile(sharetemp, '/etc/fstab') self.automounts.clear() self.automounts = self.newautomounts if not self.removeConsole: self.removeConsole = Console() command = [] autofsstop = None if sharedata['mountusing'] == 'autofs': command.append("/etc/init.d/autofs stop") command.append("sleep 2") command.append("/etc/init.d/autofs start") else: command.append('umount -fl ' + path) # print "[NetworkBrowser] UMOUNT-CMD--->",umountcmd self.removeConsole.eBatch(command, self.removeMountPointFinished, [path, callback], debug=True) def removeMountPointFinished(self, extra_args): (path, callback) = extra_args if os.path.exists(path): if not os.path.ismount(path): try: os.rmdir(path) harddiskmanager.removeMountedPartition(path) except Exception as ex: print("Failed to remove", path, "Error:", ex) if self.removeConsole: if len(self.removeConsole.appContainers) == 0: if callback is not None: self.callback = callback self.timer.startLongTimer(1)
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', '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, } if 'ip' not in data: 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 = file('/etc/network/interfaces', 'w') fp.write('''# automatically generated by enigma2 # do NOT change manually! ''') fp.write('auto lo\n') fp.write('''iface lo inet loopback ''') 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') 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 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' elif name.startswith('brcm') or name.startswith('bcm'): name = 'Broadcom' elif os.path.isdir('/tmp/bcm/' + iface): name = 'Broadcom' 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 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 writeDefaultNetworkConfig(self, mode='lan', callback=None): fp = file('/etc/network/interfaces', 'w') fp.write('''# automatically generated by enigma2 # do NOT change manually! ''') fp.write('auto lo\n') fp.write('''iface lo inet loopback ''') 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.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.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 = [] 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): 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 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 if os.path.exists('/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 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' if module == 'brcm-systemport': return 'brcm-wl' return 'wext' 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