Components/Network.py: small improvements and cleanups/fixes
[vuplus_dvbapp] / lib / python / Components / Network.py
index 46c7571..eee5a70 100755 (executable)
@@ -45,11 +45,13 @@ class Network:
                                        break
                return self.remoteRootFS
 
+       def isBlacklisted(self, iface):
+               return iface in ('lo', 'wifi0', 'wmaster0')
+
        def getInterfaces(self, callback = None):
                self.configuredInterfaces = []
-               for device in listdir('/sys/class/net'):
-                       if not device in ('lo','wifi0', 'wmaster0'):
-                               self.getAddrInet(device, callback)
+               for device in self.getInstalledAdapters():
+                       self.getAddrInet(device, callback)
 
        # helper function
        def regExpMatch(self, pattern, string):
@@ -58,7 +60,7 @@ class Network:
                try:
                        return pattern.search(string).group()
                except AttributeError:
-                       None
+                       return None
 
        # helper function to convert ips from a sring to a list of ints
        def convertIP(self, ip):
@@ -76,14 +78,14 @@ class Network:
                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}'
+               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('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}')
+               macPattern = re_compile(macRegexp)
                macLinePattern = re_compile('link/ether ' + macRegexp)
                
                for line in result.splitlines():
@@ -128,7 +130,7 @@ class Network:
                        print line[0:7]
                        if line[0:7] == "0.0.0.0":
                                gateway = self.regExpMatch(ipPattern, line[16:31])
-                               if gateway is not None:
+                               if gateway:
                                        data['gateway'] = self.convertIP(gateway)
                                        
                self.ifaces[iface] = data
@@ -160,7 +162,7 @@ class Network:
                                fp.write(iface["preup"])
                        if iface["predown"] is not False and not iface.has_key("configStrings"):
                                fp.write(iface["predown"])
-                       fp.write("\n")
+                       fp.write("\n")                          
                fp.close()
                self.configuredNetworkAdapters = self.configuredInterfaces
                self.writeNameserverConfig()
@@ -248,11 +250,14 @@ class Network:
                for line in resolv:
                        if self.regExpMatch(nameserverPattern, line) is not None:
                                ip = self.regExpMatch(ipPattern, line)
-                               if ip is not None:
+                               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
 
@@ -262,38 +267,31 @@ class Network:
        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
+               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.wlan_interfaces and len(self.wlan_interfaces) == 0:
-                               self.wlan_interfaces.append(iface)
-                               return _("WLAN connection")
-                       elif iface not in self.wlan_interfaces and len(self.wlan_interfaces) >= 1:
+               name = None
+               if self.isWirelessInterface(iface):
+                       if iface not in self.wlan_interfaces:
                                self.wlan_interfaces.append(iface)
-                               return _("WLAN connection") + " " + str(len(self.wlan_interfaces))
-
+                               name = _("WLAN connection")
+                               if len(self.wlan_interfaces):
+                                       name += " " + str(len(self.wlan_interfaces))
+               else:
+                       if iface not in self.lan_interfaces:
+                               self.lan_interfaces.append(iface)
+                               name = _("LAN connection")
+                               if len(self.lan_interfaces):
+                                       name += " " + str(len(self.lan_interfaces))
+               return name
+       
        def getFriendlyAdapterDescription(self, iface):
                if not self.isWirelessInterface(iface):
                        return _('Ethernet network interface')
 
-               moduledir = self.sysfsPath(iface) + '/device/driver/module'
-               if not os_path.isdir(moduledir):
-                       tmpfiles = listdir(self.sysfsPath(iface) + '/device')
-                       for x in tmpfiles:
-                               if x.startswith("1-"):
-                                       moduledir = self.sysfsPath(iface) + '/device/' + x + '/driver/module'
-
-               if os_path.isdir(moduledir):
+               moduledir = self.getWlanModuleDir(iface)
+               if moduledir:
                        name = os_path.basename(os_path.realpath(moduledir))
                        if name in ('ath_pci','ath5k'):
                                name = 'Atheros'
@@ -301,6 +299,8 @@ class Network:
                                name = 'Ralink'
                        elif name == 'zd1211b':
                                name = 'Zydas'
+                       elif name == 'r871x_usb_drv':
+                               name = 'Realtek'
                else:
                        name = _('Unknown')
 
@@ -539,40 +539,55 @@ class Network:
                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():
-                                       commands.append("ifdown " + iface)
-                                       commands.append("ip addr flush dev " + iface)
-                                       # HACK: wpa_supplicant sometimes doesn't quit properly on SIGTERM
-                                       if os_path.exists('/var/run/wpa_supplicant/'+ iface):
-                                               commands.append("killall -9 wpa_supplicant")
-                                               commands.append("rm -rf /var/run/wpa_supplicant/" + iface)
-                       self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, callback, debug=True)
+                                       buildCommands(iface)
                else:
-                       iface = ifaces
-                       if iface == 'eth0' and self.onRemoteRootFS():
+                       if ifaces == 'eth0' and self.onRemoteRootFS():
                                if callback is not None:
                                        callback(True)
                                return
-                       commands.append("ifdown " + iface)
-                       commands.append("ip addr flush dev " + iface)
-                       # HACK: wpa_supplicant sometimes doesn't quit properly on SIGTERM
-                       if os_path.exists('/var/run/wpa_supplicant/'+ iface):
-                               commands.append("killall -9 wpa_supplicant")
-                               commands.append("rm -rf /var/run/wpa_supplicant/" + iface)
-                       self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, callback, debug=True)
+                       buildCommands(ifaces)
+               self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces,callback], debug=True)
 
        def deactivateInterfaceFinished(self,extra_args):
-               callback = 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)
@@ -581,7 +596,7 @@ class Network:
                        self.activateInterfaceConsole = Console()
                commands = []
                commands.append("ifup " + iface)
-               self.deactivateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True)
+               self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True)
 
        def activateInterfaceFinished(self,extra_args):
                callback = extra_args
@@ -594,7 +609,45 @@ class Network:
                return '/sys/class/net/' + iface
 
        def isWirelessInterface(self, iface):
-               return os_path.isdir(self.sysfsPath(iface) + '/wireless')
+               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'
+               moduledir = devicedir + '/driver/module'
+               if os_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 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):
@@ -604,14 +657,8 @@ class Network:
                if os_path.isdir(devicedir + '/ieee80211'):
                        return 'nl80211'
 
-               moduledir = devicedir + "/driver/module"
-               if not os_path.isdir(moduledir):
-                       tmpfiles = listdir(devicedir)
-                       for x in tmpfiles:
-                               if x.startswith("1-"):
-                                       moduledir = devicedir + "/" + x + "/driver/module"
-                                       
-               if os_path.isdir(moduledir):
+               moduledir = self.getWlanModuleDir(iface)
+               if moduledir:
                        module = os_path.basename(os_path.realpath(moduledir))
                        if module in ('ath_pci','ath5k'):
                                return 'madwifi'
@@ -619,8 +666,6 @@ class Network:
                                return 'ralink'
                        if module == 'zd1211b':
                                return 'zydas'
-                       if module in ('rt3070sta'):
-                               return 'wext'           
                return 'wext'
        
        def calc_netmask(self,nmask):