46c7571d89707ad97d72207b9dafb0bff7ea4acd
[enigma2.git] / lib / python / Components / Network.py
1 from os import system, popen, path as os_path, listdir
2 from re import compile as re_compile, search as re_search
3 from socket import *
4 from enigma import eConsoleAppContainer
5 from Components.Console import Console
6 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-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{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('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}')
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 getConfiguredAdapters(self):
257                 return self.configuredNetworkAdapters
258
259         def getNumberOfAdapters(self):
260                 return len(self.ifaces)
261
262         def getFriendlyAdapterName(self, x):
263                 if x in self.friendlyNames.keys():
264                         return self.friendlyNames.get(x, x)
265                 else:
266                         self.friendlyNames[x] = self.getFriendlyAdapterNaming(x)
267                         return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name
268
269         def getFriendlyAdapterNaming(self, iface):
270                 if iface.startswith('eth'):
271                         if iface not in self.lan_interfaces and len(self.lan_interfaces) == 0:
272                                 self.lan_interfaces.append(iface)
273                                 return _("LAN connection")
274                         elif iface not in self.lan_interfaces and len(self.lan_interfaces) >= 1:
275                                 self.lan_interfaces.append(iface)
276                                 return _("LAN connection") + " " + str(len(self.lan_interfaces))
277                 else:
278                         if iface not in self.wlan_interfaces and len(self.wlan_interfaces) == 0:
279                                 self.wlan_interfaces.append(iface)
280                                 return _("WLAN connection")
281                         elif iface not in self.wlan_interfaces and len(self.wlan_interfaces) >= 1:
282                                 self.wlan_interfaces.append(iface)
283                                 return _("WLAN connection") + " " + str(len(self.wlan_interfaces))
284
285         def getFriendlyAdapterDescription(self, iface):
286                 if not self.isWirelessInterface(iface):
287                         return _('Ethernet network interface')
288
289                 moduledir = self.sysfsPath(iface) + '/device/driver/module'
290                 if not os_path.isdir(moduledir):
291                         tmpfiles = listdir(self.sysfsPath(iface) + '/device')
292                         for x in tmpfiles:
293                                 if x.startswith("1-"):
294                                         moduledir = self.sysfsPath(iface) + '/device/' + x + '/driver/module'
295
296                 if os_path.isdir(moduledir):
297                         name = os_path.basename(os_path.realpath(moduledir))
298                         if name in ('ath_pci','ath5k'):
299                                 name = 'Atheros'
300                         elif name in ('rt73','rt73usb','rt3070sta'):
301                                 name = 'Ralink'
302                         elif name == 'zd1211b':
303                                 name = 'Zydas'
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                 if not self.deactivateInterfaceConsole:
543                         self.deactivateInterfaceConsole = Console()
544                 if isinstance(ifaces, (list, tuple)):
545                         for iface in ifaces:
546                                 if iface != 'eth0' or not self.onRemoteRootFS():
547                                         commands.append("ifdown " + iface)
548                                         commands.append("ip addr flush dev " + iface)
549                                         # HACK: wpa_supplicant sometimes doesn't quit properly on SIGTERM
550                                         if os_path.exists('/var/run/wpa_supplicant/'+ iface):
551                                                 commands.append("killall -9 wpa_supplicant")
552                                                 commands.append("rm -rf /var/run/wpa_supplicant/" + iface)
553                         self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, callback, debug=True)
554                 else:
555                         iface = ifaces
556                         if iface == 'eth0' and self.onRemoteRootFS():
557                                 if callback is not None:
558                                         callback(True)
559                                 return
560                         commands.append("ifdown " + iface)
561                         commands.append("ip addr flush dev " + iface)
562                         # HACK: wpa_supplicant sometimes doesn't quit properly on SIGTERM
563                         if os_path.exists('/var/run/wpa_supplicant/'+ iface):
564                                 commands.append("killall -9 wpa_supplicant")
565                                 commands.append("rm -rf /var/run/wpa_supplicant/" + iface)
566                         self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, callback, debug=True)
567
568         def deactivateInterfaceFinished(self,extra_args):
569                 callback = extra_args
570                 if self.deactivateInterfaceConsole:
571                         if len(self.deactivateInterfaceConsole.appContainers) == 0:
572                                 if callback is not None:
573                                         callback(True)
574
575         def activateInterface(self,iface,callback = None):
576                 if iface == 'eth0' and self.onRemoteRootFS():
577                         if callback is not None:
578                                 callback(True)
579                         return
580                 if not self.activateInterfaceConsole:
581                         self.activateInterfaceConsole = Console()
582                 commands = []
583                 commands.append("ifup " + iface)
584                 self.deactivateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True)
585
586         def activateInterfaceFinished(self,extra_args):
587                 callback = extra_args
588                 if self.activateInterfaceConsole:
589                         if len(self.activateInterfaceConsole.appContainers) == 0:
590                                 if callback is not None:
591                                         callback(True)
592
593         def sysfsPath(self, iface):
594                 return '/sys/class/net/' + iface
595
596         def isWirelessInterface(self, iface):
597                 return os_path.isdir(self.sysfsPath(iface) + '/wireless')
598
599         def detectWlanModule(self, iface = None):
600                 if not self.isWirelessInterface(iface):
601                         return None
602
603                 devicedir = self.sysfsPath(iface) + '/device'
604                 if os_path.isdir(devicedir + '/ieee80211'):
605                         return 'nl80211'
606
607                 moduledir = devicedir + "/driver/module"
608                 if not os_path.isdir(moduledir):
609                         tmpfiles = listdir(devicedir)
610                         for x in tmpfiles:
611                                 if x.startswith("1-"):
612                                         moduledir = devicedir + "/" + x + "/driver/module"
613                                         
614                 if os_path.isdir(moduledir):
615                         module = os_path.basename(os_path.realpath(moduledir))
616                         if module in ('ath_pci','ath5k'):
617                                 return 'madwifi'
618                         if module in ('rt73','rt73'):
619                                 return 'ralink'
620                         if module == 'zd1211b':
621                                 return 'zydas'
622                         if module in ('rt3070sta'):
623                                 return 'wext'           
624                 return 'wext'
625         
626         def calc_netmask(self,nmask):
627                 from struct import pack, unpack
628                 from socket import inet_ntoa, inet_aton
629                 mask = 1L<<31
630                 xnet = (1L<<32)-1
631                 cidr_range = range(0, 32)
632                 cidr = long(nmask)
633                 if cidr not in cidr_range:
634                         print 'cidr invalid: %d' % cidr
635                         return None
636                 else:
637                         nm = ((1L<<cidr)-1)<<(32-cidr)
638                         netmask = str(inet_ntoa(pack('>L', nm)))
639                         return netmask
640         
641         def msgPlugins(self):
642                 if self.config_ready is not None:
643                         for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
644                                 p(reason=self.config_ready)
645         
646 iNetwork = Network()
647
648 def InitNetwork():
649         pass