some fixes
[enigma2.git] / lib / python / Components / Network.py
1 from os import system, popen, path as os_path, listdir
2 from re import compile as re_compile, search as re_search
3 from socket import *
4 from enigma import eConsoleAppContainer
5 from Components.Console import Console
6
7 class Network:
8         def __init__(self):
9                 self.ifaces = {}
10                 self.configuredInterfaces = []
11                 self.configuredNetworkAdapters = []
12                 self.NetworkState = 0
13                 self.DnsState = 0
14                 self.nameservers = []
15                 self.ethtool_bin = "/usr/sbin/ethtool"
16                 self.container = eConsoleAppContainer()
17                 self.Console = Console()
18                 self.LinkConsole = Console()
19                 self.restartConsole = Console()
20                 self.deactivateConsole = Console()
21                 self.activateConsole = Console()
22                 self.resetNetworkConsole = Console()
23                 self.DnsConsole = Console()
24                 self.getInterfaces()
25
26         def getInterfaces(self, callback = None):
27                 devicesPattern = re_compile('[a-z]+[0-9]+')
28                 self.configuredInterfaces = []
29                 fp = file('/proc/net/dev', 'r')
30                 result = fp.readlines()
31                 fp.close()
32                 for line in result:
33                         try:
34                                 device = devicesPattern.search(line).group()
35                                 if device == 'wifi0':
36                                         continue
37                                 self.getDataForInterface(device, callback)
38                         except AttributeError:
39                                 pass
40                 #print "self.ifaces:", self.ifaces
41                 #self.writeNetworkConfig()
42                 #print ord(' ')
43                 #for line in result:
44                 #       print ord(line[0])
45
46         # helper function
47         def regExpMatch(self, pattern, string):
48                 if string is None:
49                         return None
50                 try:
51                         return pattern.search(string).group()
52                 except AttributeError:
53                         None
54
55         # helper function to convert ips from a sring to a list of ints
56         def convertIP(self, ip):
57                 strIP = ip.split('.')
58                 ip = []
59                 for x in strIP:
60                         ip.append(int(x))
61                 return ip
62
63         def getDataForInterface(self, iface,callback):
64                 #get ip out of ip addr, as avahi sometimes overrides it in ifconfig.
65                 cmd = "ip -o addr"
66                 self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
67
68         def IPaddrFinished(self, result, retval, extra_args):
69                 (iface, callback ) = extra_args
70                 data = { 'up': False, 'dhcp': False, 'preup' : False, 'postdown' : False }
71                 globalIPpattern = re_compile("scope global")
72                 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
73                 netRegexp = '[0-9]{1,2}'
74                 macRegexp = '[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}'
75                 ipLinePattern = re_compile('inet ' + ipRegexp + '/')
76                 ipPattern = re_compile(ipRegexp)
77                 netmaskLinePattern = re_compile('/' + netRegexp + ' brd ')
78                 netmaskPattern = re_compile(netRegexp)
79                 bcastLinePattern = re_compile(' brd ' + ipRegexp)
80                 upPattern = re_compile('UP')
81                 macPattern = re_compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}')
82                 macLinePattern = re_compile('link/ether ' + macRegexp)
83                 
84                 for line in result.splitlines():
85                         split = line.strip().split(' ',2)
86                         if (split[1][:-1] == iface):
87                                 up = self.regExpMatch(upPattern, split[2])
88                                 mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2]))
89                                 if up is not None:
90                                         data['up'] = True
91                                         if iface is not 'lo':
92                                                 self.configuredInterfaces.append(iface)
93                                 if mac is not None:
94                                         data['mac'] = mac
95                         if (split[1] == iface):
96                                 if re_search(globalIPpattern, split[2]):
97                                         ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
98                                         netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2])))
99                                         bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2]))
100                                         if ip is not None:
101                                                 data['ip'] = self.convertIP(ip)
102                                         if netmask is not None:
103                                                 data['netmask'] = self.convertIP(netmask)
104                                         if bcast is not None:
105                                                 data['bcast'] = self.convertIP(bcast)
106                                                 
107                 if not data.has_key('ip'):
108                         data['dhcp'] = True
109                         data['ip'] = [0, 0, 0, 0]
110                         data['netmask'] = [0, 0, 0, 0]
111                         data['gateway'] = [0, 0, 0, 0]
112
113                 cmd = "route -n | grep  " + iface
114                 self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback])
115
116         def routeFinished(self, result, retval, extra_args):
117                 (iface, data, callback) = extra_args
118                 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
119                 ipPattern = re_compile(ipRegexp)
120                 ipLinePattern = re_compile(ipRegexp)
121
122                 for line in result.splitlines():
123                         print line[0:7]
124                         if line[0:7] == "0.0.0.0":
125                                 gateway = self.regExpMatch(ipPattern, line[16:31])
126                                 if gateway is not None:
127                                         data['gateway'] = self.convertIP(gateway)
128                                         
129                 self.ifaces[iface] = data
130                 self.loadNetworkConfig(iface,callback)
131
132         def writeNetworkConfig(self):
133                 self.configuredInterfaces = []
134                 fp = file('/etc/network/interfaces', 'w')
135                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
136                 fp.write("auto lo\n")
137                 fp.write("iface lo inet loopback\n\n")
138                 for ifacename, iface in self.ifaces.items():
139                         if iface['up'] == True:
140                                 fp.write("auto " + ifacename + "\n")
141                                 self.configuredInterfaces.append(ifacename)
142                         if iface['dhcp'] == True:
143                                 fp.write("iface "+ ifacename +" inet dhcp\n")
144                         if iface['dhcp'] == False:
145                                 fp.write("iface "+ ifacename +" inet static\n")
146                                 if iface.has_key('ip'):
147                                         print tuple(iface['ip'])
148                                         fp.write("      address %d.%d.%d.%d\n" % tuple(iface['ip']))
149                                         fp.write("      netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
150                                         if iface.has_key('gateway'):
151                                                 fp.write("      gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
152                         if iface.has_key("configStrings"):
153                                 fp.write("\n" + iface["configStrings"] + "\n")
154                         if iface["preup"] is not False and not iface.has_key("configStrings"):
155                                 fp.write(iface["preup"])
156                                 fp.write(iface["postdown"])
157                         fp.write("\n")                          
158                 fp.close()
159                 self.writeNameserverConfig()
160
161         def writeNameserverConfig(self):
162                 fp = file('/etc/resolv.conf', 'w')
163                 for nameserver in self.nameservers:
164                         fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
165                 fp.close()
166
167         def loadNetworkConfig(self,iface,callback = None):
168                 interfaces = []
169                 # parse the interfaces-file
170                 try:
171                         fp = file('/etc/network/interfaces', 'r')
172                         interfaces = fp.readlines()
173                         fp.close()
174                 except:
175                         print "[Network.py] interfaces - opening failed"
176
177                 ifaces = {}
178                 currif = ""
179                 for i in interfaces:
180                         split = i.strip().split(' ')
181                         if (split[0] == "iface"):
182                                 currif = split[1]
183                                 ifaces[currif] = {}
184                                 if (len(split) == 4 and split[3] == "dhcp"):
185                                         ifaces[currif]["dhcp"] = True
186                                 else:
187                                         ifaces[currif]["dhcp"] = False
188                         if (currif == iface): #read information only for available interfaces
189                                 if (split[0] == "address"):
190                                         ifaces[currif]["address"] = map(int, split[1].split('.'))
191                                         if self.ifaces[currif].has_key("ip"):
192                                                 if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
193                                                         self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
194                                 if (split[0] == "netmask"):
195                                         ifaces[currif]["netmask"] = map(int, split[1].split('.'))
196                                         if self.ifaces[currif].has_key("netmask"):
197                                                 if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
198                                                         self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
199                                 if (split[0] == "gateway"):
200                                         ifaces[currif]["gateway"] = map(int, split[1].split('.'))
201                                         if self.ifaces[currif].has_key("gateway"):
202                                                 if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
203                                                         self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))                                  
204                                 if (split[0] == "pre-up"):
205                                         if self.ifaces[currif].has_key("preup"):
206                                                 self.ifaces[currif]["preup"] = i
207                                 if (split[0] == "post-down"):
208                                         if self.ifaces[currif].has_key("postdown"):
209                                                 self.ifaces[currif]["postdown"] = i
210
211                 for ifacename, iface in ifaces.items():
212                         if self.ifaces.has_key(ifacename):
213                                 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
214                 if len(self.Console.appContainers) == 0:
215                         # save configured interfacelist
216                         self.configuredNetworkAdapters = self.configuredInterfaces
217                         # load ns only once     
218                         self.loadNameserverConfig()
219                         print "read configured interfac:", ifaces
220                         print "self.ifaces after loading:", self.ifaces
221                         if callback is not None:
222                                 callback(True)
223
224         def loadNameserverConfig(self):
225                 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
226                 nameserverPattern = re_compile("nameserver +" + ipRegexp)
227                 ipPattern = re_compile(ipRegexp)
228
229                 resolv = []
230                 try:
231                         fp = file('/etc/resolv.conf', 'r')
232                         resolv = fp.readlines()
233                         fp.close()
234                         self.nameservers = []
235                 except:
236                         print "[Network.py] resolv.conf - opening failed"
237
238                 for line in resolv:
239                         if self.regExpMatch(nameserverPattern, line) is not None:
240                                 ip = self.regExpMatch(ipPattern, line)
241                                 if ip is not None:
242                                         self.nameservers.append(self.convertIP(ip))
243
244                 print "nameservers:", self.nameservers
245
246         def deactivateNetworkConfig(self, callback = None):
247                 self.deactivateConsole = Console()
248                 self.commands = []
249                 self.commands.append("/etc/init.d/avahi-daemon stop")
250                 for iface in self.ifaces.keys():
251                         cmd = "ip addr flush " + iface
252                         self.commands.append(cmd)               
253                 self.commands.append("/etc/init.d/networking stop")
254                 self.commands.append("killall -9 udhcpc")
255                 self.commands.append("rm /var/run/udhcpc*")
256                 self.deactivateConsole.eBatch(self.commands, self.deactivateNetworkFinished, callback, debug=True)
257                 
258         def deactivateNetworkFinished(self,extra_args):
259                 callback = extra_args
260                 if len(self.deactivateConsole.appContainers) == 0:
261                         if callback is not None:
262                                 callback(True)
263
264         def activateNetworkConfig(self, callback = None):
265                 self.activateConsole = Console()
266                 self.commands = []
267                 self.commands.append("/etc/init.d/networking start")
268                 self.commands.append("/etc/init.d/avahi-daemon start")
269                 self.activateConsole.eBatch(self.commands, self.activateNetworkFinished, callback, debug=True)
270                 
271         def activateNetworkFinished(self,extra_args):
272                 callback = extra_args
273                 if len(self.activateConsole.appContainers) == 0:
274                         if callback is not None:
275                                 callback(True)
276
277         def getConfiguredAdapters(self):
278                 return self.configuredNetworkAdapters
279
280         def getNumberOfAdapters(self):
281                 return len(self.ifaces)
282
283         def getFriendlyAdapterName(self, x):
284                 # maybe this needs to be replaced by an external list.
285                 friendlyNames = {
286                         "eth0": _("Integrated Ethernet"),
287                         "wlan0": _("Wireless"),
288                         "ath0": _("Integrated Wireless")
289                 }
290                 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
291
292         def getAdapterName(self, iface):
293                 return iface
294
295         def getAdapterList(self):
296                 return self.ifaces.keys()
297
298         def getAdapterAttribute(self, iface, attribute):
299                 if self.ifaces.has_key(iface):
300                         if self.ifaces[iface].has_key(attribute):
301                                 return self.ifaces[iface][attribute]
302                 return None
303
304         def setAdapterAttribute(self, iface, attribute, value):
305                 print "setting for adapter", iface, "attribute", attribute, " to value", value
306                 if self.ifaces.has_key(iface):
307                         self.ifaces[iface][attribute] = value
308
309         def removeAdapterAttribute(self, iface, attribute):
310                 if self.ifaces.has_key(iface):
311                         if self.ifaces[iface].has_key(attribute):
312                                 del self.ifaces[iface][attribute]
313
314         def getNameserverList(self):
315                 if len(self.nameservers) == 0:
316                         return [[0, 0, 0, 0], [0, 0, 0, 0]]
317                 else: 
318                         return self.nameservers
319
320         def clearNameservers(self):
321                 self.nameservers = []
322
323         def addNameserver(self, nameserver):
324                 if nameserver not in self.nameservers:
325                         self.nameservers.append(nameserver)
326
327         def removeNameserver(self, nameserver):
328                 if nameserver in self.nameservers:
329                         self.nameservers.remove(nameserver)
330
331         def changeNameserver(self, oldnameserver, newnameserver):
332                 if oldnameserver in self.nameservers:
333                         for i in range(len(self.nameservers)):
334                                 if self.nameservers[i] == oldnameserver:
335                                         self.nameservers[i] = newnameserver
336
337         def resetNetworkConfig(self, mode='lan', callback = None):
338                 self.resetNetworkConsole = Console()
339                 self.commands = []
340                 self.commands.append("/etc/init.d/avahi-daemon stop")
341                 for iface in self.ifaces.keys():
342                         cmd = "ip addr flush " + iface
343                         self.commands.append(cmd)               
344                 self.commands.append("/etc/init.d/networking stop")
345                 self.commands.append("killall -9 udhcpc")
346                 self.commands.append("rm /var/run/udhcpc*")
347                 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True)
348
349         def resetNetworkFinishedCB(self, extra_args):
350                 (mode, callback) = extra_args
351                 if len(self.resetNetworkConsole.appContainers) == 0:
352                         self.writeDefaultNetworkConfig(mode, callback)
353
354         def writeDefaultNetworkConfig(self,mode='lan', callback = None):
355                 fp = file('/etc/network/interfaces', 'w')
356                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
357                 fp.write("auto lo\n")
358                 fp.write("iface lo inet loopback\n\n")
359                 if mode == 'wlan':
360                         fp.write("auto wlan0\n")
361                         fp.write("iface wlan0 inet dhcp\n")
362                 if mode == 'wlan-mpci':
363                         fp.write("auto ath0\n")
364                         fp.write("iface ath0 inet dhcp\n")
365                 if mode == 'lan':
366                         fp.write("auto eth0\n")
367                         fp.write("iface eth0 inet dhcp\n")
368                 fp.write("\n")
369                 fp.close()
370
371                 self.resetNetworkConsole = Console()
372                 self.commands = []
373                 if mode == 'wlan':
374                         self.commands.append("ifconfig eth0 down")
375                         self.commands.append("ifconfig ath0 down")
376                         self.commands.append("ifconfig wlan0 up")
377                 if mode == 'wlan-mpci':
378                         self.commands.append("ifconfig eth0 down")
379                         self.commands.append("ifconfig wlan0 down")
380                         self.commands.append("ifconfig ath0 up")                
381                 if mode == 'lan':                       
382                         self.commands.append("ifconfig eth0 up")
383                         self.commands.append("ifconfig wlan0 down")
384                         self.commands.append("ifconfig ath0 down")
385                 self.commands.append("/etc/init.d/avahi-daemon start")  
386                 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)  
387
388         def resetNetworkFinished(self,extra_args):
389                 (mode, callback) = extra_args
390                 if len(self.resetNetworkConsole.appContainers) == 0:
391                         if callback is not None:
392                                 callback(True,mode)
393
394         def checkNetworkState(self,statecallback):
395                 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
396                 cmd1 = "ping -c 1 82.149.226.170"
397                 cmd2 = "ping -c 1 193.99.144.85"
398                 cmd3 = "ping -c 1 209.85.135.103"
399                 self.PingConsole = Console()
400                 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
401                 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
402                 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
403                 
404         def checkNetworkStateFinished(self, result, retval,extra_args):
405                 (statecallback) = extra_args
406                 if self.PingConsole is not None:
407                         if retval == 0:
408                                 self.PingConsole = None
409                                 statecallback(self.NetworkState)
410                         else:
411                                 self.NetworkState += 1
412                                 if len(self.PingConsole.appContainers) == 0:
413                                         statecallback(self.NetworkState)
414                 
415         def restartNetwork(self,callback):
416                 self.restartConsole = Console()
417                 self.commands = []
418                 self.commands.append("/etc/init.d/avahi-daemon stop")
419                 for iface in self.ifaces.keys():
420                         cmd = "ip addr flush " + iface
421                         self.commands.append(cmd)               
422                 self.commands.append("/etc/init.d/networking stop")
423                 self.commands.append("killall -9 udhcpc")
424                 self.commands.append("rm /var/run/udhcpc*")
425                 self.commands.append("/etc/init.d/networking start")
426                 self.commands.append("/etc/init.d/avahi-daemon start")
427                 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
428         
429         def restartNetworkFinished(self,extra_args):
430                 callback = extra_args
431                 if len(self.restartConsole.appContainers) == 0:
432                         callback(True)
433
434         def getLinkState(self,iface,callback):
435                 cmd = self.ethtool_bin + " " + iface
436                 self.LinkConsole = Console()
437                 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
438
439         def getLinkStateFinished(self, result, retval,extra_args):
440                 (callback) = extra_args
441                 if self.LinkConsole is not None:
442                         if len(self.LinkConsole.appContainers) == 0:
443                                 callback(result)
444                         
445         def stopLinkStateConsole(self):
446                 if self.LinkConsole is not None:
447                         self.LinkConsole = None
448
449         def stopDNSConsole(self):
450                 if self.DnsConsole is not None:
451                         self.DnsConsole = None
452
453         def stopRestartConsole(self):
454                 if self.restartConsole is not None:
455                         self.restartConsole = None
456                         
457         def RestartConsoleRunning(self):
458                 if self.restartConsole is not None:
459                         if len(self.restartConsole.appContainers) == 0:
460                                 return False
461                         else:
462                                 return True
463                         
464         def checkforInterface(self,iface):
465                 if self.getAdapterAttribute(iface, 'up') is True:
466                         return True
467                 else:
468                         ret=system("ifconfig " + iface + " up")
469                         system("ifconfig " + iface + " down")
470                         if ret == 0:
471                                 return True
472                         else:
473                                 return False
474
475         def checkDNSLookup(self,statecallback):
476                 cmd1 = "nslookup www.dream-multimedia-tv.de"
477                 cmd2 = "nslookup www.heise.de"
478                 cmd3 = "nslookup www.google.de"
479                 self.DnsConsole = Console()
480                 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
481                 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
482                 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
483                 
484         def checkDNSLookupFinished(self, result, retval,extra_args):
485                 (statecallback) = extra_args
486                 if self.DnsConsole is not None:
487                         if retval == 0:
488                                 self.DnsConsole = None
489                                 statecallback(self.DnsState)
490                         else:
491                                 self.DnsState += 1
492                                 if len(self.DnsConsole.appContainers) == 0:
493                                         statecallback(self.DnsState)
494
495         def deactivateInterface(self,iface):
496                 self.deactivateInterfaceConsole = Console()
497                 self.commands = []
498                 cmd1 = "ip addr flush " + iface
499                 cmd2 = "ifconfig " + iface + " down"
500                 self.commands.append(cmd1)
501                 self.commands.append(cmd2)
502                 self.deactivateInterfaceConsole.eBatch(self.commands, self.deactivateInterfaceFinished, extra_args = None, debug=True)
503
504         def deactivateInterfaceFinished(self,extra_args):
505                 pass
506
507         def detectWlanModule(self):
508                 self.wlanmodule = None
509                 rt73_dir = "/sys/bus/usb/drivers/rt73/"
510                 zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
511                 madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
512                 if os_path.exists(madwifi_dir):
513                         files = listdir(madwifi_dir)
514                         if len(files) >= 1:
515                                 self.wlanmodule = 'madwifi'
516                 if os_path.exists(rt73_dir):
517                         rtfiles = listdir(rt73_dir)
518                         if len(rtfiles) == 2:
519                                 self.wlanmodule = 'ralink'
520                 if os_path.exists(zd1211b_dir):
521                         zdfiles = listdir(zd1211b_dir)
522                         if len(zdfiles) == 1:
523                                 self.wlanmodule = 'zydas'
524                 return self.wlanmodule
525         
526         def calc_netmask(self,nmask):
527                 from struct import pack, unpack
528                 from socket import inet_ntoa, inet_aton
529                 mask = 1L<<31
530                 xnet = (1L<<32)-1
531                 cidr_range = range(0, 32)
532                 cidr = long(nmask)
533                 if cidr not in cidr_range:
534                         print 'cidr invalid: %d' % cidr
535                         return None
536                 else:
537                         nm = ((1L<<cidr)-1)<<(32-cidr)
538                         netmask = str(inet_ntoa(pack('>L', nm)))
539                         return netmask
540         
541 iNetwork = Network()
542
543 def InitNetwork():
544         pass