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