remove debug output
[enigma2.git] / lib / python / Components / Network.py
index d94fa30cd68851e29407e0962c7ebe751c95ecf0..cf21c6d053e5067c63efbddb0ffaa5fe8dee3d28 100644 (file)
@@ -2,19 +2,21 @@ from os import system, popen, path as os_path, listdir
 from re import compile as re_compile
 from socket import *
 from enigma import eConsoleAppContainer
+from Components.Console import Console
 
 class Network:
        def __init__(self):
                self.ifaces = {}
-               self.configuredInterfaces = {}
+               self.configuredInterfaces = []          
                self.nameservers = []
-               self.getInterfaces()
                self.ethtool_bin = "/usr/sbin/ethtool"
                self.container = eConsoleAppContainer()
+               self.Console = Console()
+               self.getInterfaces()
 
-       def getInterfaces(self):
+       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()
@@ -23,20 +25,10 @@ class Network:
                                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]
+                               self.getDataForInterface(device, callback)
                        except AttributeError:
                                pass
 
-               print "self.ifaces:", self.ifaces
-               self.loadNetworkConfig()
-               #self.writeNetworkConfig()
-               #print ord(' ')
-               #for line in result:
-               #       print ord(line[0])
-
        # helper function
        def regExpMatch(self, pattern, string):
                if string is None:
@@ -54,8 +46,37 @@ class Network:
                        ip.append(int(x))
                return ip
 
-       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}'
+       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}'
+               ipLinePattern = re_compile('inet ' + ipRegexp +'/')
+               ipPattern = re_compile(ipRegexp)
+
+               for line in result.splitlines():
+                       split = line.strip().split(' ',2)
+                       if (split[1] == iface):
+                               if re_search(globalIPpattern, split[2]):
+                                       ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
+                                       if ip is not None:
+                                               data['ip'] = self.convertIP(ip)
+               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 = "ifconfig " + iface
+               self.Console.ePopen(cmd, self.ifconfigFinished, [iface, data, callback])
+
+       def getDataForInterface(self, iface,callback):
+               #get ip out of ip addr, as avahi sometimes overrides it in ifconfig.
+               cmd = "ip -o addr"
+               self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
+
+       def ifconfigFinished(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}'
                ipLinePattern = re_compile('inet addr:' + ipRegexp)
                netmaskLinePattern = re_compile('Mask:' + ipRegexp)
@@ -63,45 +84,56 @@ class Network:
                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 = popen("ifconfig " + iface)
-               result = fp.readlines()
-               fp.close()
-               data = { 'up': False, 'dhcp': False }
-               for line in result:
-                       ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, line))
+
+               for line in result.splitlines():
+                       #ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, line))
                        netmask = self.regExpMatch(ipPattern, self.regExpMatch(netmaskLinePattern, line))
                        bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, line))
                        up = self.regExpMatch(upPattern, line)
                        mac = self.regExpMatch(macPattern, line)
-                       if ip is not None:
-                               data['ip'] = self.convertIP(ip)
+                       #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 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 not data.has_key('ip'):
-                       data['dhcp'] = True
-                       data['ip'] = [192, 168, 1, 2]
-                       data['netmask'] = [255, 255, 255, 0]
-                       data['gateway'] = [192, 168, 1, 1]
-                       
-               fp = popen("route -n | grep  " + iface)
-               result = fp.readlines()
-               fp.close()
-               for line in result:
+
+               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)
-               return data
+
+               for line in result.splitlines(): #get real netmask in case avahi has overridden ifconfig netmask
+                       split = line.strip().split('   ')
+                       if re_search(ipPattern, split[0]):
+                               foundip = self.convertIP(split[0])
+                               if (foundip[0] == data['ip'][0] and foundip[1] == data['ip'][1]):
+                                       if re_search(ipPattern, split[4]):
+                                               mask = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[4]))
+                                               if mask is not None:
+                                                       data['netmask'] = self.convertIP(mask)
+               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")
@@ -109,19 +141,23 @@ class Network:
                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")
-                               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")                          
+                               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()
 
@@ -131,8 +167,7 @@ class Network:
                        fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
                fp.close()
 
-       def loadNetworkConfig(self):
-               self.loadNameserverConfig()
+       def loadNetworkConfig(self,iface,callback = None):
                interfaces = []
                # parse the interfaces-file
                try:
@@ -153,21 +188,39 @@ class Network:
                                        ifaces[currif]["dhcp"] = True
                                else:
                                        ifaces[currif]["dhcp"] = False
-                       if (currif != ""):
+                       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('.'))
-               
-               self.configuredInterfaces = ifaces
-               print "read interfaces:", ifaces
+                                       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"]
-
-               print "self.ifaces after loading:", self.ifaces
+               if len(self.Console.appContainers) == 0:
+                       # load ns only once
+                       self.loadNameserverConfig()
+                       print "read configured interfac:", ifaces
+                       print "self.ifaces after loading:", self.ifaces
+                       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}"
@@ -306,13 +359,19 @@ class Network:
        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.appClosed.append(self.cmdFinished)
+               self.container.dataAvail.append(callback)
                self.container.execute(cmd)
 
        def cmdFinished(self,retval):
-               self.container.appClosed.get().remove(self.cmdFinished)
-               self.container.dataAvail.get().remove(self.dataAvail)
+               self.container.appClosed.remove(self.cmdFinished)
+               self.container.dataAvail.remove(self.dataAvail)
+
+       def stopContainer(self):
+               self.container.kill()
+               
+       def ContainerRunning(self):
+               return self.container.running()
 
        def checkforInterface(self,iface):
                if self.getAdapterAttribute(iface, 'up') is True:
@@ -342,13 +401,13 @@ class Network:
                        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:
+               if os_path.exists(rt73_dir):
+                       rtfiles = listdir(rt73_dir)
+                       if len(rtfiles) == 2:
                                self.wlanmodule = 'ralink'
-               elif os_path.exists(zd1211b_dir):
-                       files = listdir(zd1211b_dir)
-                       if len(files) != 0:
+               if os_path.exists(zd1211b_dir):
+                       zdfiles = listdir(zd1211b_dir)
+                       if len(zdfiles) == 1:
                                self.wlanmodule = 'zydas'
                return self.wlanmodule