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