update network setup
[enigma2.git] / lib / python / Components / Network.py
index 6990f356eb929453e74ea1cc124f764f6413e568..3abfc34c6c68d2dd7104c5dc44d7d4b3c79e0605 100644 (file)
-from config import *
-
-import os
+from os import system, popen
+from re import compile as re_compile
 from socket import *
+from enigma import eConsoleAppContainer
 
 class Network:
        def __init__(self):
-               pass
+               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]+')
+
+               fp = file('/proc/net/dev', 'r')
+               result = fp.readlines()
+               fp.close()
+               for line in result:
+                       try:
+                               device = devicesPattern.search(line).group()
+                               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])
+
+       # 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):
+               #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}')
                
+               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))
+                       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 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 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:
+                       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
+
        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
                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")
+                               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:
-                       # 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
+                       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 != ""):
+                               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('.'))
                
+               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)
+
+               resolv = []
                try:
-                       # set this config
-                       if (ifaces.has_key("eth0")):
-                               if (ifaces["eth0"]["dhcp"] == "yes"):
-                                       config.network.dhcp.value = 1
-                               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"]
+                       fp = file('/etc/resolv.conf', 'r')
+                       resolv = fp.readlines()
+                       fp.close()
+                       self.nameservers = []
                except:
-                       pass
+                       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):
+               for iface in self.ifaces.keys():
+                       system("ip addr flush " + iface)
+               system("/etc/init.d/networking stop")
+               system("killall -9 udhcpc")
+               system("rm /var/run/udhcpc*")
 
        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
-               
-       def setIPAddress(self, ip):
-               pass
-               #os.system("echo ifconfig eth0 %d.%d.%d.%d" % tuple(ip))
-               #self.writeNetworkConfig()
+               system("/etc/init.d/networking start")
+               self.getInterfaces()
 
-       def setGateway(self, ip):
-               pass
-               #os.system("echo route add default gw %d.%d.%d.%d" % tuple(ip))
-               #self.writeNetworkConfig()
-               
-       def setNetmask(self, ip):
-               pass
-               #os.system("echo ifconfig eth0 netmask %d.%d.%d.%d" % tuple(ip))                
-               #self.writeNetworkConfig()              
-
-       def getCurrentIP(self):
-               ip = [0,0,0,0]
-               for x in os.popen("ifconfig eth0 | grep 'inet addr:'", "r").readline().split(' '):
-                       if x.split(':')[0] == "addr":
-                               ip = x.split(':')[1].split('.')
-               print "[Network.py] got ip " + str(ip)
-               return ip
+       def getNumberOfAdapters(self):
+               return len(self.ifaces)
 
-iNetwork = Network()
+       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 InitNetwork():
-       ip = iNetwork.getCurrentIP()
+       def getAdapterName(self, iface):
+               return iface
 
-               
-       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()
-       
-       #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 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 writeNetworkConfig(configElement):
-               iNetwork.writeNetworkConfig()
-               
-       def setIPAddress(configElement):
-               iNetwork.setIPAddress(configElement.value)
+       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 setGateway(configElement):
-               iNetwork.setGateway(configElement.value)
+       def addNameserver(self, nameserver):
+               if nameserver not in self.nameservers:
+                       self.nameservers.append(nameserver)
 
-       def setNetmask(configElement):
-               iNetwork.setNetmask(configElement.value)                
+       def removeNameserver(self, nameserver):
+               if nameserver in self.nameservers:
+                       self.nameservers.remove(nameserver)
 
-       def setDHCP(configElement):
-               iNetwork.setDHCP(configElement.value)
+       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 setIPNameserver(configElement):
-               iNetwork.setIPNameserver(configElement.value)
+       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 eth0 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):
+               ok_counter = 0
+               ret1=system("ping -c 1 www.dream-multimedia-tv.de")
+               if ret1 != 0:
+                       ok_counter = ok_counter + 1
+               ret2=system("ping -c 1 www.heise.de")
+               if ret2 != 0:
+                       ok_counter = ok_counter + 1
+               ret3=system("ping -c 1 www.google.de")
+               if ret2 != 0:
+                       ok_counter = ok_counter + 1             
+               if ok_counter <= 2:
+                       return True
+               else:
+                       return False
+
+       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 setMACAddress(configElement):
-               iNetwork.setMACAddress(configElement.value)
+       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):
+               ok_counter = 0
+               ret1=system("nslookup www.dream-multimedia-tv.de")
+               if ret1 != 0:
+                       ok_counter = ok_counter + 1
+               ret2=system("nslookup www.heise.de")
+               if ret2 != 0:
+                       ok_counter = ok_counter + 1
+               ret3=system("nslookup www.google.de")
+               if ret2 != 0:
+                       ok_counter = ok_counter + 1             
+               if ok_counter <= 2:
+                       return True
+               else:
+                       return False
+               
+       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/"
+               if os_path.exists(rt73_dir):
+                       files = []
+                       files = listdir(rt73_dir)
+                       if len(files) >= 1:
+                               self.wlanmodule = 'ralink'
+               if os_path.exists(zd1211b_dir):
+                       files = []
+                       files = listdir(zd1211b_dir)
+                       if len(files) != 0:
+                               self.wlanmodule = 'zydas'
+               return self.wlanmodule
+       
+       
+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