1 from os import system, popen, path as os_path, listdir
2 from re import compile as re_compile, search as re_search
4 from enigma import eConsoleAppContainer
5 from Components.Console import Console
6 from Components.PluginComponent import plugins
7 from Plugins.Plugin import PluginDescriptor
12 self.configuredInterfaces = []
13 self.configuredNetworkAdapters = []
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
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()
38 device = devicesPattern.search(line).group()
41 self.getDataForInterface(device, callback)
42 except AttributeError:
44 #print "self.ifaces:", self.ifaces
45 #self.writeNetworkConfig()
51 def regExpMatch(self, pattern, string):
55 return pattern.search(string).group()
56 except AttributeError:
59 # helper function to convert ips from a sring to a list of ints
60 def convertIP(self, ip):
67 def getDataForInterface(self, iface,callback):
68 #get ip out of ip addr, as avahi sometimes overrides it in ifconfig.
70 self.Console = Console()
72 self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
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)
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]))
98 self.configuredInterfaces.append(iface)
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]))
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)
113 if not data.has_key('ip'):
115 data['ip'] = [0, 0, 0, 0]
116 data['netmask'] = [0, 0, 0, 0]
117 data['gateway'] = [0, 0, 0, 0]
119 cmd = "route -n | grep " + iface
120 self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback])
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)
128 for line in result.splitlines():
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)
135 self.ifaces[iface] = data
136 self.loadNetworkConfig(iface,callback)
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"])
165 self.writeNameserverConfig()
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))
173 def loadNetworkConfig(self,iface,callback = None):
175 # parse the interfaces-file
177 fp = file('/etc/network/interfaces', 'r')
178 interfaces = fp.readlines()
181 print "[Network.py] interfaces - opening failed"
186 split = i.strip().split(' ')
187 if (split[0] == "iface"):
190 if (len(split) == 4 and split[3] == "dhcp"):
191 ifaces[currif]["dhcp"] = True
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
217 for ifacename, iface in ifaces.items():
218 if self.ifaces.has_key(ifacename):
219 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
221 if len(self.Console.appContainers) == 0:
222 # save configured interfacelist
223 self.configuredNetworkAdapters = self.configuredInterfaces
225 self.loadNameserverConfig()
226 print "read configured interfac:", ifaces
227 print "self.ifaces after loading:", self.ifaces
228 self.config_ready = True
230 if callback is not None:
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)
240 fp = file('/etc/resolv.conf', 'r')
241 resolv = fp.readlines()
243 self.nameservers = []
245 print "[Network.py] resolv.conf - opening failed"
248 if self.regExpMatch(nameserverPattern, line) is not None:
249 ip = self.regExpMatch(ipPattern, line)
251 self.nameservers.append(self.convertIP(ip))
253 print "nameservers:", self.nameservers
255 def deactivateNetworkConfig(self, callback = None):
256 self.deactivateConsole = Console()
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)
267 def deactivateNetworkFinished(self,extra_args):
268 callback = extra_args
269 if len(self.deactivateConsole.appContainers) == 0:
270 if callback is not None:
273 def activateNetworkConfig(self, callback = None):
274 self.activateConsole = Console()
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)
280 def activateNetworkFinished(self,extra_args):
281 callback = extra_args
282 if len(self.activateConsole.appContainers) == 0:
283 if callback is not None:
286 def getConfiguredAdapters(self):
287 return self.configuredNetworkAdapters
289 def getNumberOfAdapters(self):
290 return len(self.ifaces)
292 def getFriendlyAdapterName(self, x):
293 # maybe this needs to be replaced by an external list.
295 "eth0": _("Integrated Ethernet"),
296 "wlan0": _("Wireless"),
297 "ath0": _("Integrated Wireless")
299 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
301 def getAdapterName(self, iface):
304 def getAdapterList(self):
305 return self.ifaces.keys()
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]
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
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]
323 def getNameserverList(self):
324 if len(self.nameservers) == 0:
325 return [[0, 0, 0, 0], [0, 0, 0, 0]]
327 return self.nameservers
329 def clearNameservers(self):
330 self.nameservers = []
332 def addNameserver(self, nameserver):
333 if nameserver not in self.nameservers:
334 self.nameservers.append(nameserver)
336 def removeNameserver(self, nameserver):
337 if nameserver in self.nameservers:
338 self.nameservers.remove(nameserver)
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
346 def resetNetworkConfig(self, mode='lan', callback = None):
347 self.resetNetworkConsole = Console()
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)
358 def resetNetworkFinishedCB(self, extra_args):
359 (mode, callback) = extra_args
360 if len(self.resetNetworkConsole.appContainers) == 0:
361 self.writeDefaultNetworkConfig(mode, callback)
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")
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")
375 fp.write("auto eth0\n")
376 fp.write("iface eth0 inet dhcp\n")
380 self.resetNetworkConsole = Console()
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")
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)
397 def resetNetworkFinished(self,extra_args):
398 (mode, callback) = extra_args
399 if len(self.resetNetworkConsole.appContainers) == 0:
400 if callback is not None:
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)
413 def checkNetworkStateFinished(self, result, retval,extra_args):
414 (statecallback) = extra_args
415 if self.PingConsole is not None:
417 self.PingConsole = None
418 statecallback(self.NetworkState)
420 self.NetworkState += 1
421 if len(self.PingConsole.appContainers) == 0:
422 statecallback(self.NetworkState)
424 def restartNetwork(self,callback = None):
425 self.restartConsole = Console()
426 self.config_ready = False
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)
440 def restartNetworkFinished(self,extra_args):
441 ( callback ) = extra_args
442 if callback is not None:
445 def getLinkState(self,iface,callback):
446 cmd = self.ethtool_bin + " " + iface
447 self.LinkConsole = Console()
448 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
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:
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)
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)
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)
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)
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)
486 def checkforInterface(self,iface):
487 if self.getAdapterAttribute(iface, 'up') is True:
490 ret=system("ifconfig " + iface + " up")
491 system("ifconfig " + iface + " down")
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)
506 def checkDNSLookupFinished(self, result, retval,extra_args):
507 (statecallback) = extra_args
508 if self.DnsConsole is not None:
510 self.DnsConsole = None
511 statecallback(self.DnsState)
514 if len(self.DnsConsole.appContainers) == 0:
515 statecallback(self.DnsState)
517 def deactivateInterface(self,iface,callback = None):
518 self.deactivateInterfaceConsole = Console()
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)
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:
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)
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
552 def calc_netmask(self,nmask):
553 from struct import pack, unpack
554 from socket import inet_ntoa, inet_aton
557 cidr_range = range(0, 32)
559 if cidr not in cidr_range:
560 print 'cidr invalid: %d' % cidr
563 nm = ((1L<<cidr)-1)<<(32-cidr)
564 netmask = str(inet_ntoa(pack('>L', nm)))
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)