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