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