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