32b8bdbe76dcb89f68d9c1eb152e2aadbbb7a64c
[vuplus_dvbapp] / 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 from Components.PluginComponent import plugins
7 from Components.About import about
8 from Plugins.Plugin import PluginDescriptor
9
10 class Network:
11         def __init__(self):
12                 self.ifaces = {}
13                 self.configuredInterfaces = []
14                 self.configuredNetworkAdapters = []
15                 self.NetworkState = 0
16                 self.DnsState = 0
17                 self.nameservers = []
18                 self.ethtool_bin = "ethtool"
19                 self.container = eConsoleAppContainer()
20                 self.Console = Console()
21                 self.LinkConsole = Console()
22                 self.restartConsole = Console()
23                 self.deactivateInterfaceConsole = Console()
24                 self.activateInterfaceConsole = Console()
25                 self.resetNetworkConsole = Console()
26                 self.DnsConsole = Console()
27                 self.PingConsole = Console()
28                 self.config_ready = None
29                 self.friendlyNames = {}
30                 self.lan_interfaces = []
31                 self.wlan_interfaces = []
32                 self.remoteRootFS = None
33                 self.getInterfaces()
34
35         def onRemoteRootFS(self):
36                 if self.remoteRootFS == None:
37                         fp = file('/proc/mounts', 'r')
38                         mounts = fp.readlines()
39                         fp.close()
40                         self.remoteRootFS = False
41                         for line in mounts:
42                                 parts = line.strip().split()
43                                 if parts[1] == '/' and parts[2] == 'nfs':
44                                         self.remoteRootFS = True
45                                         break
46                 return self.remoteRootFS
47
48         def isBlacklisted(self, iface):
49                 return iface in ('lo', 'wifi0', 'wmaster0')
50
51         def getInterfaces(self, callback = None):
52                 self.configuredInterfaces = []
53                 for device in self.getInstalledAdapters():
54                         self.getAddrInet(device, callback)
55
56         # helper function
57         def regExpMatch(self, pattern, string):
58                 if string is None:
59                         return None
60                 try:
61                         return pattern.search(string).group()
62                 except AttributeError:
63                         return None
64
65         # helper function to convert ips from a sring to a list of ints
66         def convertIP(self, ip):
67                 return [ int(n) for n in ip.split('.') ]
68
69         def getAddrInet(self, iface, callback):
70                 if not self.Console:
71                         self.Console = Console()
72                 cmd = "ip -o addr show dev " + iface
73                 self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
74
75         def IPaddrFinished(self, result, retval, extra_args):
76                 (iface, callback ) = extra_args
77                 data = { 'up': False, 'dhcp': False, 'preup' : False, 'predown' : False }
78                 globalIPpattern = re_compile("scope global")
79                 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
80                 netRegexp = '[0-9]{1,2}'
81                 macRegexp = '[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}'
82                 ipLinePattern = re_compile('inet ' + ipRegexp + '/')
83                 ipPattern = re_compile(ipRegexp)
84                 netmaskLinePattern = re_compile('/' + netRegexp)
85                 netmaskPattern = re_compile(netRegexp)
86                 bcastLinePattern = re_compile(' brd ' + ipRegexp)
87                 upPattern = re_compile('UP')
88                 macPattern = re_compile(macRegexp)
89                 macLinePattern = re_compile('link/ether ' + macRegexp)
90                 
91                 for line in result.splitlines():
92                         split = line.strip().split(' ',2)
93                         if (split[1][:-1] == iface):
94                                 up = self.regExpMatch(upPattern, split[2])
95                                 mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2]))
96                                 if up is not None:
97                                         data['up'] = True
98                                         if iface is not 'lo':
99                                                 self.configuredInterfaces.append(iface)
100                                 if mac is not None:
101                                         data['mac'] = mac
102                         if (split[1] == iface):
103                                 if re_search(globalIPpattern, split[2]):
104                                         ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
105                                         netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2])))
106                                         bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2]))
107                                         if ip is not None:
108                                                 data['ip'] = self.convertIP(ip)
109                                         if netmask is not None:
110                                                 data['netmask'] = self.convertIP(netmask)
111                                         if bcast is not None:
112                                                 data['bcast'] = self.convertIP(bcast)
113                                                 
114                 if not data.has_key('ip'):
115                         data['dhcp'] = True
116                         data['ip'] = [0, 0, 0, 0]
117                         data['netmask'] = [0, 0, 0, 0]
118                         data['gateway'] = [0, 0, 0, 0]
119
120                 cmd = "route -n | grep  " + iface
121                 self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback])
122
123         def routeFinished(self, result, retval, extra_args):
124                 (iface, data, callback) = extra_args
125                 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
126                 ipPattern = re_compile(ipRegexp)
127                 ipLinePattern = re_compile(ipRegexp)
128
129                 for line in result.splitlines():
130                         print line[0:7]
131                         if line[0:7] == "0.0.0.0":
132                                 gateway = self.regExpMatch(ipPattern, line[16:31])
133                                 if gateway:
134                                         data['gateway'] = self.convertIP(gateway)
135                                         
136                 self.ifaces[iface] = data
137                 self.loadNetworkConfig(iface,callback)
138
139         def writeNetworkConfig(self):
140                 self.configuredInterfaces = []
141                 fp = file('/etc/network/interfaces', 'w')
142                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
143                 fp.write("auto lo\n")
144                 fp.write("iface lo inet loopback\n\n")
145                 for ifacename, iface in self.ifaces.items():
146                         if iface['up'] == True:
147                                 fp.write("auto " + ifacename + "\n")
148                                 self.configuredInterfaces.append(ifacename)
149                         if iface['dhcp'] == True:
150                                 fp.write("iface "+ ifacename +" inet dhcp\n")
151                         if iface['dhcp'] == False:
152                                 fp.write("iface "+ ifacename +" inet static\n")
153                                 if iface.has_key('ip'):
154                                         print tuple(iface['ip'])
155                                         fp.write("      address %d.%d.%d.%d\n" % tuple(iface['ip']))
156                                         fp.write("      netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
157                                         if iface.has_key('gateway'):
158                                                 fp.write("      gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
159                         if iface.has_key("configStrings"):
160                                 fp.write(iface["configStrings"])
161                         if iface["preup"] is not False and not iface.has_key("configStrings"):
162                                 fp.write(iface["preup"])
163                         if iface["predown"] is not False and not iface.has_key("configStrings"):
164                                 fp.write(iface["predown"])
165                         fp.write("\n")                          
166                 fp.close()
167                 self.configuredNetworkAdapters = self.configuredInterfaces
168                 self.writeNameserverConfig()
169
170         def writeNameserverConfig(self):
171                 fp = file('/etc/resolv.conf', 'w')
172                 for nameserver in self.nameservers:
173                         fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
174                 fp.close()
175
176         def loadNetworkConfig(self,iface,callback = None):
177                 interfaces = []
178                 # parse the interfaces-file
179                 try:
180                         fp = file('/etc/network/interfaces', 'r')
181                         interfaces = fp.readlines()
182                         fp.close()
183                 except:
184                         print "[Network.py] interfaces - opening failed"
185
186                 ifaces = {}
187                 currif = ""
188                 for i in interfaces:
189                         split = i.strip().split(' ')
190                         if (split[0] == "iface"):
191                                 currif = split[1]
192                                 ifaces[currif] = {}
193                                 if (len(split) == 4 and split[3] == "dhcp"):
194                                         ifaces[currif]["dhcp"] = True
195                                 else:
196                                         ifaces[currif]["dhcp"] = False
197                         if (currif == iface): #read information only for available interfaces
198                                 if (split[0] == "address"):
199                                         ifaces[currif]["address"] = map(int, split[1].split('.'))
200                                         if self.ifaces[currif].has_key("ip"):
201                                                 if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
202                                                         self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
203                                 if (split[0] == "netmask"):
204                                         ifaces[currif]["netmask"] = map(int, split[1].split('.'))
205                                         if self.ifaces[currif].has_key("netmask"):
206                                                 if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
207                                                         self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
208                                 if (split[0] == "gateway"):
209                                         ifaces[currif]["gateway"] = map(int, split[1].split('.'))
210                                         if self.ifaces[currif].has_key("gateway"):
211                                                 if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
212                                                         self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))
213                                 if (split[0] == "pre-up"):
214                                         if self.ifaces[currif].has_key("preup"):
215                                                 self.ifaces[currif]["preup"] = i
216                                 if (split[0] in ("pre-down","post-down")):
217                                         if self.ifaces[currif].has_key("predown"):
218                                                 self.ifaces[currif]["predown"] = i
219
220                 for ifacename, iface in ifaces.items():
221                         if self.ifaces.has_key(ifacename):
222                                 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
223                 if self.Console:
224                         if len(self.Console.appContainers) == 0:
225                                 # save configured interfacelist
226                                 self.configuredNetworkAdapters = self.configuredInterfaces
227                                 # load ns only once     
228                                 self.loadNameserverConfig()
229                                 print "read configured interface:", ifaces
230                                 print "self.ifaces after loading:", self.ifaces
231                                 self.config_ready = True
232                                 self.msgPlugins()
233                                 if callback is not None:
234                                         callback(True)
235
236         def loadNameserverConfig(self):
237                 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
238                 nameserverPattern = re_compile("nameserver +" + ipRegexp)
239                 ipPattern = re_compile(ipRegexp)
240
241                 resolv = []
242                 try:
243                         fp = file('/etc/resolv.conf', 'r')
244                         resolv = fp.readlines()
245                         fp.close()
246                         self.nameservers = []
247                 except:
248                         print "[Network.py] resolv.conf - opening failed"
249
250                 for line in resolv:
251                         if self.regExpMatch(nameserverPattern, line) is not None:
252                                 ip = self.regExpMatch(ipPattern, line)
253                                 if ip:
254                                         self.nameservers.append(self.convertIP(ip))
255
256                 print "nameservers:", self.nameservers
257
258         def getInstalledAdapters(self):
259                 return [x for x in listdir('/sys/class/net') if not self.isBlacklisted(x)]
260
261         def getConfiguredAdapters(self):
262                 return self.configuredNetworkAdapters
263
264         def getNumberOfAdapters(self):
265                 return len(self.ifaces)
266
267         def getFriendlyAdapterName(self, x):
268                 if x in self.friendlyNames.keys():
269                         return self.friendlyNames.get(x, x)
270                 self.friendlyNames[x] = self.getFriendlyAdapterNaming(x)
271                 return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name
272
273         def getFriendlyAdapterNaming(self, iface):
274                 name = None
275                 if self.isWirelessInterface(iface):
276                         if iface not in self.wlan_interfaces:
277                                 name = _("WLAN connection")
278                                 if len(self.wlan_interfaces):
279                                         name += " " + str(len(self.wlan_interfaces)+1)
280                                 self.wlan_interfaces.append(iface)                                                              
281                 else:
282                         if iface not in self.lan_interfaces:
283                                 name = _("LAN connection")
284                                 if len(self.lan_interfaces):
285                                         name += " " + str(len(self.lan_interfaces)+1)
286                                 self.lan_interfaces.append(iface)
287                 return name
288         
289         def getFriendlyAdapterDescription(self, iface):
290                 if not self.isWirelessInterface(iface):
291                         return _('Ethernet network interface')
292
293                 moduledir = self.getWlanModuleDir(iface)
294                 if moduledir:
295                         name = os_path.basename(os_path.realpath(moduledir))
296                         if name in ('ath_pci','ath5k'):
297                                 name = 'Atheros'
298                         elif name in ('rt73','rt73usb','rt3070sta'):
299                                 name = 'Ralink'
300                         elif name == 'zd1211b':
301                                 name = 'Zydas'
302                         elif name == 'r871x_usb_drv':
303                                 name = 'Realtek'
304                 else:
305                         name = _('Unknown')
306
307                 return name + ' ' + _('wireless network interface')
308
309         def getAdapterName(self, iface):
310                 return iface
311
312         def getAdapterList(self):
313                 return self.ifaces.keys()
314
315         def getAdapterAttribute(self, iface, attribute):
316                 if self.ifaces.has_key(iface):
317                         if self.ifaces[iface].has_key(attribute):
318                                 return self.ifaces[iface][attribute]
319                 return None
320
321         def setAdapterAttribute(self, iface, attribute, value):
322                 print "setting for adapter", iface, "attribute", attribute, " to value", value
323                 if self.ifaces.has_key(iface):
324                         self.ifaces[iface][attribute] = value
325
326         def removeAdapterAttribute(self, iface, attribute):
327                 if self.ifaces.has_key(iface):
328                         if self.ifaces[iface].has_key(attribute):
329                                 del self.ifaces[iface][attribute]
330
331         def getNameserverList(self):
332                 if len(self.nameservers) == 0:
333                         return [[0, 0, 0, 0], [0, 0, 0, 0]]
334                 else: 
335                         return self.nameservers
336
337         def clearNameservers(self):
338                 self.nameservers = []
339
340         def addNameserver(self, nameserver):
341                 if nameserver not in self.nameservers:
342                         self.nameservers.append(nameserver)
343
344         def removeNameserver(self, nameserver):
345                 if nameserver in self.nameservers:
346                         self.nameservers.remove(nameserver)
347
348         def changeNameserver(self, oldnameserver, newnameserver):
349                 if oldnameserver in self.nameservers:
350                         for i in range(len(self.nameservers)):
351                                 if self.nameservers[i] == oldnameserver:
352                                         self.nameservers[i] = newnameserver
353
354         def resetNetworkConfig(self, mode='lan', callback = None):
355                 self.resetNetworkConsole = Console()
356                 self.commands = []
357                 self.commands.append("/etc/init.d/avahi-daemon stop")
358                 for iface in self.ifaces.keys():
359                         if iface != 'eth0' or not self.onRemoteRootFS():
360                                 self.commands.append("ip addr flush dev " + iface)      
361                 self.commands.append("/etc/init.d/networking stop")
362                 self.commands.append("killall -9 udhcpc")
363                 self.commands.append("rm /var/run/udhcpc*")
364                 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True)
365
366         def resetNetworkFinishedCB(self, extra_args):
367                 (mode, callback) = extra_args
368                 if len(self.resetNetworkConsole.appContainers) == 0:
369                         self.writeDefaultNetworkConfig(mode, callback)
370
371         def writeDefaultNetworkConfig(self,mode='lan', callback = None):
372                 fp = file('/etc/network/interfaces', 'w')
373                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
374                 fp.write("auto lo\n")
375                 fp.write("iface lo inet loopback\n\n")
376                 if mode == 'wlan':
377                         fp.write("auto wlan0\n")
378                         fp.write("iface wlan0 inet dhcp\n")
379                 if mode == 'wlan-mpci':
380                         fp.write("auto ath0\n")
381                         fp.write("iface ath0 inet dhcp\n")
382                 if mode == 'lan':
383                         fp.write("auto eth0\n")
384                         fp.write("iface eth0 inet dhcp\n")
385                 fp.write("\n")
386                 fp.close()
387
388                 self.resetNetworkConsole = Console()
389                 self.commands = []
390                 if mode == 'wlan':
391                         self.commands.append("ifconfig eth0 down")
392                         self.commands.append("ifconfig ath0 down")
393                         self.commands.append("ifconfig wlan0 up")
394                 if mode == 'wlan-mpci':
395                         self.commands.append("ifconfig eth0 down")
396                         self.commands.append("ifconfig wlan0 down")
397                         self.commands.append("ifconfig ath0 up")                
398                 if mode == 'lan':                       
399                         self.commands.append("ifconfig eth0 up")
400                         self.commands.append("ifconfig wlan0 down")
401                         self.commands.append("ifconfig ath0 down")
402                 self.commands.append("/etc/init.d/avahi-daemon start")  
403                 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)  
404
405         def resetNetworkFinished(self,extra_args):
406                 (mode, callback) = extra_args
407                 if len(self.resetNetworkConsole.appContainers) == 0:
408                         if callback is not None:
409                                 callback(True,mode)
410
411         def checkNetworkState(self,statecallback):
412                 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
413                 self.NetworkState = 0
414                 cmd1 = "ping -c 1 82.149.226.170"
415                 cmd2 = "ping -c 1 193.99.144.85"
416                 cmd3 = "ping -c 1 209.85.135.103"
417                 self.PingConsole = Console()
418                 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
419                 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
420                 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
421                 
422         def checkNetworkStateFinished(self, result, retval,extra_args):
423                 (statecallback) = extra_args
424                 if self.PingConsole is not None:
425                         if retval == 0:
426                                 self.PingConsole = None
427                                 statecallback(self.NetworkState)
428                         else:
429                                 self.NetworkState += 1
430                                 if len(self.PingConsole.appContainers) == 0:
431                                         statecallback(self.NetworkState)
432                 
433         def restartNetwork(self,callback = None):
434                 self.restartConsole = Console()
435                 self.config_ready = False
436                 self.msgPlugins()
437                 self.commands = []
438                 self.commands.append("/etc/init.d/avahi-daemon stop")
439                 for iface in self.ifaces.keys():
440                         if iface != 'eth0' or not self.onRemoteRootFS():
441                                 self.commands.append("ifdown " + iface)
442                                 self.commands.append("ip addr flush dev " + iface)
443                 self.commands.append("/etc/init.d/networking stop")
444                 self.commands.append("killall -9 udhcpc")
445                 self.commands.append("rm /var/run/udhcpc*")
446                 self.commands.append("/etc/init.d/networking start")
447                 self.commands.append("/etc/init.d/avahi-daemon start")
448                 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
449         
450         def restartNetworkFinished(self,extra_args):
451                 ( callback ) = extra_args
452                 if callback is not None:
453                         callback(True)
454
455         def getLinkState(self,iface,callback):
456                 cmd = self.ethtool_bin + " " + iface
457                 self.LinkConsole = Console()
458                 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
459
460         def getLinkStateFinished(self, result, retval,extra_args):
461                 (callback) = extra_args
462
463                 if self.LinkConsole is not None:
464                         if len(self.LinkConsole.appContainers) == 0:
465                                 callback(result)
466                         
467         def stopPingConsole(self):
468                 if self.PingConsole is not None:
469                         if len(self.PingConsole.appContainers):
470                                 for name in self.PingConsole.appContainers.keys():
471                                         self.PingConsole.kill(name)
472
473         def stopLinkStateConsole(self):
474                 if self.LinkConsole is not None:
475                         if len(self.LinkConsole.appContainers):
476                                 for name in self.LinkConsole.appContainers.keys():
477                                         self.LinkConsole.kill(name)
478                                         
479         def stopDNSConsole(self):
480                 if self.DnsConsole is not None:
481                         if len(self.DnsConsole.appContainers):
482                                 for name in self.DnsConsole.appContainers.keys():
483                                         self.DnsConsole.kill(name)
484                                         
485         def stopRestartConsole(self):
486                 if self.restartConsole is not None:
487                         if len(self.restartConsole.appContainers):
488                                 for name in self.restartConsole.appContainers.keys():
489                                         self.restartConsole.kill(name)
490                                         
491         def stopGetInterfacesConsole(self):
492                 if self.Console is not None:
493                         if len(self.Console.appContainers):
494                                 for name in self.Console.appContainers.keys():
495                                         self.Console.kill(name)
496                                         
497         def stopDeactivateInterfaceConsole(self):
498                 if self.deactivateInterfaceConsole is not None:
499                         self.deactivateInterfaceConsole.killAll()
500                         self.deactivateInterfaceConsole = None
501
502         def stopActivateInterfaceConsole(self):
503                 if self.activateInterfaceConsole is not None:
504                         self.activateInterfaceConsole.killAll()
505                         self.activateInterfaceConsole = None
506                                         
507         def checkforInterface(self,iface):
508                 if self.getAdapterAttribute(iface, 'up') is True:
509                         return True
510                 else:
511                         ret=system("ifconfig " + iface + " up")
512                         system("ifconfig " + iface + " down")
513                         if ret == 0:
514                                 return True
515                         else:
516                                 return False
517
518         def checkDNSLookup(self,statecallback):
519                 cmd1 = "nslookup www.dream-multimedia-tv.de"
520                 cmd2 = "nslookup www.heise.de"
521                 cmd3 = "nslookup www.google.de"
522                 self.DnsConsole = Console()
523                 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
524                 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
525                 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
526                 
527         def checkDNSLookupFinished(self, result, retval,extra_args):
528                 (statecallback) = extra_args
529                 if self.DnsConsole is not None:
530                         if retval == 0:
531                                 self.DnsConsole = None
532                                 statecallback(self.DnsState)
533                         else:
534                                 self.DnsState += 1
535                                 if len(self.DnsConsole.appContainers) == 0:
536                                         statecallback(self.DnsState)
537
538         def deactivateInterface(self,ifaces,callback = None):
539                 self.config_ready = False
540                 self.msgPlugins()
541                 commands = []
542                 def buildCommands(iface):
543                         commands.append("ifdown " + iface)
544                         commands.append("ip addr flush dev " + iface)
545                         #wpa_supplicant sometimes doesn't quit properly on SIGTERM
546                         if os_path.exists('/var/run/wpa_supplicant/'+ iface):
547                                 commands.append("wpa_cli -i" + iface + " terminate")
548                         
549                 if not self.deactivateInterfaceConsole:
550                         self.deactivateInterfaceConsole = Console()
551
552                 if isinstance(ifaces, (list, tuple)):
553                         for iface in ifaces:
554                                 if iface != 'eth0' or not self.onRemoteRootFS():
555                                         buildCommands(iface)
556                 else:
557                         if ifaces == 'eth0' and self.onRemoteRootFS():
558                                 if callback is not None:
559                                         callback(True)
560                                 return
561                         buildCommands(ifaces)
562                 self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces,callback], debug=True)
563
564         def deactivateInterfaceFinished(self,extra_args):
565                 (ifaces, callback) = extra_args
566                 def checkCommandResult(iface):
567                         if self.deactivateInterfaceConsole and self.deactivateInterfaceConsole.appResults.has_key("ifdown " + iface):
568                                 result = str(self.deactivateInterfaceConsole.appResults.get("ifdown " + iface)).strip("\n")
569                                 if result == "ifdown: interface " + iface + " not configured":
570                                         return False
571                                 else:
572                                         return True
573                 #ifdown sometimes can't get the interface down.
574                 if isinstance(ifaces, (list, tuple)):
575                         for iface in ifaces:
576                                 if checkCommandResult(iface) is False:
577                                         Console().ePopen(("ifconfig " + iface + " down" ))
578                 else:
579                         if checkCommandResult(ifaces) is False:
580                                 Console().ePopen(("ifconfig " + ifaces + " down" ))
581
582                 if self.deactivateInterfaceConsole:
583                         if len(self.deactivateInterfaceConsole.appContainers) == 0:
584                                 if callback is not None:
585                                         callback(True)
586
587         def activateInterface(self,iface,callback = None):
588                 if self.config_ready:
589                         self.config_ready = False
590                         self.msgPlugins()
591                 if iface == 'eth0' and self.onRemoteRootFS():
592                         if callback is not None:
593                                 callback(True)
594                         return
595                 if not self.activateInterfaceConsole:
596                         self.activateInterfaceConsole = Console()
597                 commands = []
598                 commands.append("ifup " + iface)
599                 self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True)
600
601         def activateInterfaceFinished(self,extra_args):
602                 callback = extra_args
603                 if self.activateInterfaceConsole:
604                         if len(self.activateInterfaceConsole.appContainers) == 0:
605                                 if callback is not None:
606                                         callback(True)
607
608         def sysfsPath(self, iface):
609                 return '/sys/class/net/' + iface
610
611         def isWirelessInterface(self, iface):
612                 if iface in self.wlan_interfaces:
613                         return True
614
615                 if os_path.isdir(self.sysfsPath(iface) + '/wireless'):
616                         return True
617
618                 # r871x_usb_drv on kernel 2.6.12 is not identifiable over /sys/class/net/'ifacename'/wireless so look also inside /proc/net/wireless
619                 device = re_compile('[a-z]{2,}[0-9]*:')
620                 ifnames = []
621                 fp = open('/proc/net/wireless', 'r')
622                 for line in fp:
623                         try:
624                                 ifnames.append(device.search(line).group()[:-1])
625                         except AttributeError:
626                                 pass
627                 if iface in ifnames:
628                         return True
629
630                 return False
631
632         def getWlanModuleDir(self, iface = None):
633                 devicedir = self.sysfsPath(iface) + '/device'
634                 moduledir = devicedir + '/driver/module'
635                 if os_path.isdir(moduledir):
636                         return moduledir
637
638                 # identification is not possible over default moduledir
639                 for x in listdir(devicedir):
640                         # rt3070 on kernel 2.6.18 registers wireless devices as usb_device (e.g. 1-1.3:1.0) and identification is only possible over /sys/class/net/'ifacename'/device/1-xxx
641                         if x.startswith("1-"):
642                                 moduledir = devicedir + '/' + x + '/driver/module'
643                                 if os_path.isdir(moduledir):
644                                         return moduledir
645                 # rt73, zd1211b, r871x_usb_drv on kernel 2.6.12 can be identified over /sys/class/net/'ifacename'/device/driver, so look also here
646                 moduledir = devicedir + '/driver'
647                 if os_path.isdir(moduledir):
648                         return moduledir
649
650                 return None
651
652         def detectWlanModule(self, iface = None):
653                 if not self.isWirelessInterface(iface):
654                         return None
655
656                 devicedir = self.sysfsPath(iface) + '/device'
657                 if os_path.isdir(devicedir + '/ieee80211'):
658                         return 'nl80211'
659
660                 moduledir = self.getWlanModuleDir(iface)
661                 if moduledir:
662                         module = os_path.basename(os_path.realpath(moduledir))
663                         if module in ('ath_pci','ath5k'):
664                                 return 'madwifi'
665                         if module in ('rt73','rt73'):
666                                 return 'ralink'
667                         if module == 'zd1211b':
668                                 return 'zydas'
669                 return 'wext'
670         
671         def calc_netmask(self,nmask):
672                 from struct import pack, unpack
673                 from socket import inet_ntoa, inet_aton
674                 mask = 1L<<31
675                 xnet = (1L<<32)-1
676                 cidr_range = range(0, 32)
677                 cidr = long(nmask)
678                 if cidr not in cidr_range:
679                         print 'cidr invalid: %d' % cidr
680                         return None
681                 else:
682                         nm = ((1L<<cidr)-1)<<(32-cidr)
683                         netmask = str(inet_ntoa(pack('>L', nm)))
684                         return netmask
685         
686         def msgPlugins(self):
687                 if self.config_ready is not None:
688                         for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
689                                 p(reason=self.config_ready)
690         
691 iNetwork = Network()
692
693 def InitNetwork():
694         pass