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