now link dvb-s frontends to dvb-s2 frontends is possible
[enigma2.git] / lib / python / Components / Network.py
index a8c75907ddfff25639306f3478c744fb23ed25d2..d94fa30cd68851e29407e0962c7ebe751c95ecf0 100644 (file)
@@ -1,34 +1,41 @@
-from Components.config import config, ConfigYesNo, ConfigIP, NoSave, ConfigSubsection, ConfigMAC
-
-import os
-import re
+from os import system, popen, path as os_path, listdir
+from re import compile as re_compile
 from socket import *
+from enigma import eConsoleAppContainer
 
 class Network:
        def __init__(self):
                self.ifaces = {}
+               self.configuredInterfaces = {}
                self.nameservers = []
                self.getInterfaces()
-               
+               self.ethtool_bin = "/usr/sbin/ethtool"
+               self.container = eConsoleAppContainer()
+
        def getInterfaces(self):
-               devicesPattern = re.compile('[a-z]+[0-9]+')
-               
+               devicesPattern = re_compile('[a-z]+[0-9]+')
+
                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.ifaces[device] = self.getDataForInterface(device)
+                               # Show only UP Interfaces in E2
+                               #if self.getAdapterAttribute(device, 'up') is False:
+                               #       del self.ifaces[device]
                        except AttributeError:
                                pass
-               
+
                print "self.ifaces:", self.ifaces
                self.loadNetworkConfig()
                #self.writeNetworkConfig()
                #print ord(' ')
                #for line in result:
-#                      print ord(line[0])
+               #       print ord(line[0])
 
        # helper function
        def regExpMatch(self, pattern, string):
@@ -38,7 +45,7 @@ class Network:
                        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('.')
@@ -50,14 +57,14 @@ class Network:
        def getDataForInterface(self, iface):
                #ipRegexp = '[0-9]{1,2,3}\.[0-9]{1,2,3}\.[0-9]{1,2,3}\.[0-9]{1,2,3}'
                ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
-               ipLinePattern = re.compile('inet addr:' + ipRegexp)
-               netmaskLinePattern = re.compile('Mask:' + ipRegexp)
-               bcastLinePattern = re.compile('Bcast:' + ipRegexp)
-               ipPattern = re.compile(ipRegexp)
-               upPattern = re.compile('UP ')
-               macPattern = re.compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}')
+               ipLinePattern = re_compile('inet addr:' + ipRegexp)
+               netmaskLinePattern = re_compile('Mask:' + ipRegexp)
+               bcastLinePattern = re_compile('Bcast:' + ipRegexp)
+               ipPattern = re_compile(ipRegexp)
+               upPattern = re_compile('UP ')
+               macPattern = re_compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}')
                
-               fp = os.popen("ifconfig " + iface)
+               fp = popen("ifconfig " + iface)
                result = fp.readlines()
                fp.close()
                data = { 'up': False, 'dhcp': False }
@@ -82,10 +89,10 @@ class Network:
                        data['ip'] = [192, 168, 1, 2]
                        data['netmask'] = [255, 255, 255, 0]
                        data['gateway'] = [192, 168, 1, 1]
-               
-               fp = os.popen("route -n | grep  " + iface)
+                       
+               fp = popen("route -n | grep  " + iface)
                result = fp.readlines()
-               fp.close()                              
+               fp.close()
                for line in result:
                        print line[0:7]
                        if line[0:7] == "0.0.0.0":
@@ -99,38 +106,33 @@ class Network:
                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")
-                       if iface['dhcp'] == True:
-                               fp.write("iface "+ ifacename +" inet dhcp\n")
-                       else:
-                               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")
-                       fp.write("\n")
+                               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")
+                               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):
                self.loadNameserverConfig()
-               
                interfaces = []
                # parse the interfaces-file
                try:
@@ -139,7 +141,7 @@ class Network:
                        fp.close()
                except:
                        print "[Network.py] interfaces - opening failed"
-                       
+
                ifaces = {}
                currif = ""
                for i in interfaces:
@@ -157,20 +159,21 @@ class Network:
                                if (split[0] == "netmask"):
                                        ifaces[currif]["netmask"] = map(int, split[1].split('.'))
                                if (split[0] == "gateway"):
-                                       ifaces[currif]["gateway"] = map(int, split[1].split('.'))                                                                       
+                                       ifaces[currif]["gateway"] = map(int, split[1].split('.'))
                
+               self.configuredInterfaces = ifaces
                print "read interfaces:", ifaces
                for ifacename, iface in ifaces.items():
                        if self.ifaces.has_key(ifacename):
                                self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
-               
+
                print "self.ifaces after loading:", self.ifaces
 
        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)
-               
+               nameserverPattern = re_compile("nameserver +" + ipRegexp)
+               ipPattern = re_compile(ipRegexp)
+
                resolv = []
                try:
                        fp = file('/etc/resolv.conf', 'r')
@@ -179,40 +182,50 @@ class Network:
                        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          
+
+               print "nameservers:", self.nameservers
 
        def deactivateNetworkConfig(self):
                for iface in self.ifaces.keys():
-                       os.system("ip addr flush " + iface)
-               os.system("/etc/init.d/networking stop")
-               os.system("killall -9 udhcpc")
-               os.system("rm /var/run/udhcpc*")
+                       system("ip addr flush " + iface)
+               system("/etc/init.d/networking stop")
+               system("killall -9 udhcpc")
+               system("rm /var/run/udhcpc*")
 
        def activateNetworkConfig(self):
-               os.system("/etc/init.d/networking start")
-               
+               system("/etc/init.d/networking start")
+               self.getInterfaces()
+
        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):
@@ -222,27 +235,124 @@ class Network:
                if self.ifaces.has_key(iface):
                        if self.ifaces[iface].has_key(attribute):
                                del self.ifaces[iface][attribute]
-                               
+
        def getNameserverList(self):
-               return self.nameservers
-       
+               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 writeDefaultNetworkConfig(self,mode='lan'):
+               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()
+
+       def resetNetworkConfig(self,mode='lan'):
+               self.deactivateNetworkConfig()
+               self.writeDefaultNetworkConfig(mode)
+               if mode == 'wlan':
+                       system("ifconfig eth0 down")
+                       system("ifconfig ath0 down")
+                       system("ifconfig wlan0 up")
+               if mode == 'wlan-mpci':
+                       system("ifconfig eth0 down")
+                       system("ifconfig wlan0 down")
+                       system("ifconfig ath0 up")              
+               if mode == 'lan':                       
+                       system("ifconfig eth0 up")
+                       system("ifconfig wlan0 down")
+                       system("ifconfig ath0 down")
+               self.getInterfaces()    
+
+       def checkNetworkState(self):
+                # www.dream-multimedia-tv.de, www.heise.de, www.google.de
+               return system("ping -c 1 82.149.226.170") == 0 or \
+                       system("ping -c 1 193.99.144.85") == 0 or \
+                       system("ping -c 1 209.85.135.103") == 0
+
+       def restartNetwork(self):
+               iNetwork.deactivateNetworkConfig()
+               iNetwork.activateNetworkConfig()
+
+       def getLinkState(self,iface,callback):
+               self.dataAvail = callback
+               cmd = self.ethtool_bin + " " + iface
+               self.container.appClosed.get().append(self.cmdFinished)
+               self.container.dataAvail.get().append(callback)
+               self.container.execute(cmd)
+
+       def cmdFinished(self,retval):
+               self.container.appClosed.get().remove(self.cmdFinished)
+               self.container.dataAvail.get().remove(self.dataAvail)
+
+       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):
+               return system("nslookup www.dream-multimedia-tv.de") == 0 or \
+                       system("nslookup www.heise.de") == 0 or \
+                       system("nslookup www.google.de")
+
+       def deactivateInterface(self,iface):
+               system("ifconfig " + iface + " down")
+
+       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'
+               elif os_path.exists(rt73_dir):
+                       files = listdir(rt73_dir)
+                       if len(files) >= 1:
+                               self.wlanmodule = 'ralink'
+               elif os_path.exists(zd1211b_dir):
+                       files = listdir(zd1211b_dir)
+                       if len(files) != 0:
+                               self.wlanmodule = 'zydas'
+               return self.wlanmodule
+       
+       
 iNetwork = Network()
 
 def InitNetwork():