"finished" message also when skipping configuration backup
[enigma2.git] / lib / python / Components / Network.py
old mode 100644 (file)
new mode 100755 (executable)
index c38c44c..f32a648
-from config import *
-
-import os
+from os import system, popen, path as os_path, listdir
+from re import compile as re_compile, search as re_search
 from socket import *
+from enigma import eConsoleAppContainer
+from Components.Console import Console
 
 class Network:
        def __init__(self):
-               pass
+               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.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):
-               # fixme restarting and updating the network too often. possible fix: check current config and execute only if changed :/
-               # fixme using interfaces.tmp instead of interfaces for now
+               self.configuredInterfaces = []
                fp = file('/etc/network/interfaces', 'w')
-               fp.write("auto eth0\n")
-               if (config.network.dhcp.value == _("yes")):
-                       fp.write("iface eth0 inet dhcp\n")
-               else:
-                       fp.write("iface eth0 inet static\n")
-                       fp.write("      address %d.%d.%d.%d\n" % tuple(config.network.ip.value))
-                       fp.write("      netmask %d.%d.%d.%d\n" % tuple(config.network.netmask.value))
-                       fp.write("      gateway %d.%d.%d.%d\n" % tuple(config.network.gateway.value))
+               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 loadNetworkConfig(self):
+       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:
-                       # parse the interfaces-file
                        fp = file('/etc/network/interfaces', 'r')
                        interfaces = fp.readlines()
                        fp.close()
-                       
-                       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"] = "yes"
-                                       else:
-                                               ifaces[currif]["dhcp"] = "no"
-                               if (currif != ""):
-                                       if (split[0] == "address"):
-                                               ifaces[currif]["address"] = map(int, split[1].split('.'))
-                                       if (split[0] == "netmask"):
-                                               ifaces[currif]["netmask"] = map(int, split[1].split('.'))
-                                       if (split[0] == "gateway"):
-                                               ifaces[currif]["gateway"] = map(int, split[1].split('.'))                                                                       
-                       
-                       # parse the resolv.conf-file
-                       fp = file('/etc/network/interfaces', 'r')
-                       resolv = fp.readlines()
-                       fp.close()
-               except:
-                       pass
-                       
-               try:
-                       for i in resolv:
-                               split = i.strip().split(' ')
-                               if (split[0] == "nameserver"):
-                                       config.network.nameserver.value = map(int, split[1].split('.'))
                except:
-                       pass
-               
-               try:
-                       # set this config
-                       if (ifaces.has_key("eth0")):
-                               if (ifaces["eth0"]["dhcp"] == "yes"):
-                                       config.network.dhcp.value = 1
+                       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:
-                                       config.network.dhcp.value = 0
-                               if (ifaces["eth0"].has_key("address")): config.network.ip.value = ifaces["eth0"]["address"]
-                               if (ifaces["eth0"].has_key("netmask")): config.network.netmask.value = ifaces["eth0"]["netmask"]
-                               if (ifaces["eth0"].has_key("gateway")): config.network.gateway.value = ifaces["eth0"]["gateway"]
+                                       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
+                               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:
-                       pass
+                       print "[Network.py] resolv.conf - opening failed"
 
-       def activateNetworkConfig(self):
-               import os
-               os.system("/etc/init.d/networking restart")
-               config.network.ip.value = self.getCurrentIP()
-               
-       def setDHCP(self, useDHCP):
-               if (useDHCP):
-                       print "Using DHCP"
-                       config.network.ip.enabled = False
-                       config.network.netmask.enabled = False
-                       config.network.gateway.enabled = False
-                       config.network.dns.enabled = False
-               else:
-                       print "NOT using DHCP"
-                       config.network.ip.enabled = True
-                       config.network.netmask.enabled = True
-                       config.network.gateway.enabled = True
-                       config.network.dns.enabled = True
-                                       
-       def setIPNameserver(self, ip):
-               return
-               resolvconf = file('/etc/resolv.conf', 'w')
-               resolvconf.write("nameserver %d.%d.%d.%d" % tuple(ip))
-               resolvconf.close()
-               
-       def setMACAddress(self, mac):
-               #os.system("echo ifconfig eth0 ether %02x:%02x:%02x:%02x:%02x:%02x" % tuple(mac))
-               pass
+               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 setIPAddress(self, ip):
-               pass
-               #os.system("echo ifconfig eth0 %d.%d.%d.%d" % tuple(ip))
-               #self.writeNetworkConfig()
+       def deactivateNetworkFinished(self,extra_args):
+               callback = extra_args
+               if len(self.deactivateConsole.appContainers) == 0:
+                       if callback is not None:
+                               callback(True)
 
-       def setGateway(self, ip):
-               pass
-               #os.system("echo route add default gw %d.%d.%d.%d" % tuple(ip))
-               #self.writeNetworkConfig()
+       def activateNetworkConfig(self, callback = None):
+               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 setNetmask(self, ip):
-               pass
-               #os.system("echo ifconfig eth0 netmask %d.%d.%d.%d" % tuple(ip))                
-               #self.writeNetworkConfig()              
+       def activateNetworkFinished(self,extra_args):
+               callback = extra_args
+               if len(self.activateConsole.appContainers) == 0:
+                       if callback is not None:
+                               callback(True)
 
-       def getCurrentIP(self):
-               ip = [0, 0, 0, 0]
-               try:
-                       print gethostbyname(gethostname())
-                       ip = gethostbyname(gethostname()).split('.')
-               except:
-                       print "[Network.py] Could not get current ip (not necessarily an error)"
-               return ip
+       def getConfiguredAdapters(self):
+               return self.configuredNetworkAdapters
 
-iNetwork = Network()
+       def getNumberOfAdapters(self):
+               return len(self.ifaces)
 
-def InitNetwork():
-       ip = iNetwork.getCurrentIP()
+       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)
                
-       config.network = ConfigSubsection()
-       config.network.dhcp = configElement_nonSave("config.network.dhcp", configSelection, 1, (_("no"), _("yes")))
-       config.network.ip = configElement_nonSave("config.network.ip", configSequence, ip, configsequencearg.get("IP"))
-       config.network.netmask = configElement_nonSave("config.network.netmask", configSequence, [255,255,255,0], configsequencearg.get("IP"))
-       config.network.gateway = configElement_nonSave("config.network.gateway", configSequence, [192,168,1,3], configsequencearg.get("IP"))
-       config.network.dns = configElement_nonSave("config.network.dns", configSequence, [192,168,1,3], configsequencearg.get("IP"))
-       config.network.mac = configElement_nonSave("config.network.mac", configSequence, [00,11,22,33,44,55], configsequencearg.get("MAC"))
-
-       iNetwork.loadNetworkConfig()
+       def restartNetwork(self,callback = None):
+               self.restartConsole = 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.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)
        
-       #FIXME using this till other concept for this is implemented
-       #config.network.activate = configElement("config.network.activate", configSelection, 0, ("yes, sir", "you are my hero"))
-       #config.network.activate = configElement("config.network.activate", configSelection, 0, ("yes", "you are my hero"))
+       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 writeNetworkConfig(configElement):
-               iNetwork.writeNetworkConfig()
-               
-       def setIPAddress(configElement):
-               iNetwork.setIPAddress(configElement.value)
+       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:
+                       self.LinkConsole = None
 
-       def setGateway(configElement):
-               iNetwork.setGateway(configElement.value)
+       def stopDNSConsole(self):
+               if self.DnsConsole is not None:
+                       self.DnsConsole = None
 
-       def setNetmask(configElement):
-               iNetwork.setNetmask(configElement.value)                
+       def stopRestartConsole(self):
+               if self.restartConsole is not None:
+                       self.restartConsole = None
+                       
+       def stopGetInterfacesConsole(self):
+               if self.Console is not None:
+                       self.Console = None
 
-       def setDHCP(configElement):
-               iNetwork.setDHCP(configElement.value)
+       def stopDeactivateInterfaceConsole(self):
+               if self.deactivateInterfaceConsole:
+                       self.deactivateInterfaceConsole = None
+                       
+       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 setIPNameserver(configElement):
-               iNetwork.setIPNameserver(configElement.value)
+       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 setMACAddress(configElement):
-               iNetwork.setMACAddress(configElement.value)
+       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
+       
+iNetwork = Network()
 
-       # this will call the "setup-val" initial
-       config.network.dhcp.addNotifier(setDHCP)
-       config.network.ip.addNotifier(setIPAddress)
-       config.network.netmask.addNotifier(setNetmask)  
-       config.network.gateway.addNotifier(setGateway)
-       config.network.dns.addNotifier(setIPNameserver)
-       config.network.mac.addNotifier(setMACAddress)
+def InitNetwork():
+       pass