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.PingConsole = Console()
28 self.config_ready = None
31 def onRemoteRootFS(self):
32 fp = file('/proc/mounts', 'r')
33 mounts = fp.readlines()
36 parts = line.strip().split(' ')
37 if parts[1] == '/' and (parts[2] == 'nfs' or parts[2] == 'smbfs'):
41 def getInterfaces(self, callback = None):
42 devicesPattern = re_compile('[a-z]+[0-9]+')
43 self.configuredInterfaces = []
44 fp = file('/proc/net/dev', 'r')
45 result = fp.readlines()
49 device = devicesPattern.search(line).group()
50 if device in ('wifi0', 'wmaster0'):
52 self.getDataForInterface(device, callback)
53 except AttributeError:
55 #print "self.ifaces:", self.ifaces
56 #self.writeNetworkConfig()
62 def regExpMatch(self, pattern, string):
66 return pattern.search(string).group()
67 except AttributeError:
70 # helper function to convert ips from a sring to a list of ints
71 def convertIP(self, ip):
78 def getDataForInterface(self, iface,callback):
79 #get ip out of ip addr, as avahi sometimes overrides it in ifconfig.
81 self.Console = Console()
83 self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
85 def IPaddrFinished(self, result, retval, extra_args):
86 (iface, callback ) = extra_args
87 data = { 'up': False, 'dhcp': False, 'preup' : False, 'postdown' : False }
88 globalIPpattern = re_compile("scope global")
89 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
90 netRegexp = '[0-9]{1,2}'
91 macRegexp = '[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}'
92 ipLinePattern = re_compile('inet ' + ipRegexp + '/')
93 ipPattern = re_compile(ipRegexp)
94 netmaskLinePattern = re_compile('/' + netRegexp)
95 netmaskPattern = re_compile(netRegexp)
96 bcastLinePattern = re_compile(' brd ' + ipRegexp)
97 upPattern = re_compile('UP')
98 macPattern = re_compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}')
99 macLinePattern = re_compile('link/ether ' + macRegexp)
101 for line in result.splitlines():
102 split = line.strip().split(' ',2)
103 if (split[1][:-1] == iface):
104 up = self.regExpMatch(upPattern, split[2])
105 mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2]))
108 if iface is not 'lo':
109 self.configuredInterfaces.append(iface)
112 if (split[1] == iface):
113 if re_search(globalIPpattern, split[2]):
114 ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
115 netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2])))
116 bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2]))
118 data['ip'] = self.convertIP(ip)
119 if netmask is not None:
120 data['netmask'] = self.convertIP(netmask)
121 if bcast is not None:
122 data['bcast'] = self.convertIP(bcast)
124 if not data.has_key('ip'):
126 data['ip'] = [0, 0, 0, 0]
127 data['netmask'] = [0, 0, 0, 0]
128 data['gateway'] = [0, 0, 0, 0]
130 cmd = "route -n | grep " + iface
131 self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback])
133 def routeFinished(self, result, retval, extra_args):
134 (iface, data, callback) = extra_args
135 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
136 ipPattern = re_compile(ipRegexp)
137 ipLinePattern = re_compile(ipRegexp)
139 for line in result.splitlines():
141 if line[0:7] == "0.0.0.0":
142 gateway = self.regExpMatch(ipPattern, line[16:31])
143 if gateway is not None:
144 data['gateway'] = self.convertIP(gateway)
146 self.ifaces[iface] = data
147 self.loadNetworkConfig(iface,callback)
149 def writeNetworkConfig(self):
150 self.configuredInterfaces = []
151 fp = file('/etc/network/interfaces', 'w')
152 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
153 fp.write("auto lo\n")
154 fp.write("iface lo inet loopback\n\n")
155 for ifacename, iface in self.ifaces.items():
156 if iface['up'] == True:
157 fp.write("auto " + ifacename + "\n")
158 self.configuredInterfaces.append(ifacename)
159 if iface['dhcp'] == True:
160 fp.write("iface "+ ifacename +" inet dhcp\n")
161 if iface['dhcp'] == False:
162 fp.write("iface "+ ifacename +" inet static\n")
163 if iface.has_key('ip'):
164 print tuple(iface['ip'])
165 fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip']))
166 fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
167 if iface.has_key('gateway'):
168 fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
169 if iface.has_key("configStrings"):
170 fp.write("\n" + iface["configStrings"] + "\n")
171 if iface["preup"] is not False and not iface.has_key("configStrings"):
172 fp.write(iface["preup"])
173 fp.write(iface["postdown"])
176 self.writeNameserverConfig()
178 def writeNameserverConfig(self):
179 fp = file('/etc/resolv.conf', 'w')
180 for nameserver in self.nameservers:
181 fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
184 def loadNetworkConfig(self,iface,callback = None):
186 # parse the interfaces-file
188 fp = file('/etc/network/interfaces', 'r')
189 interfaces = fp.readlines()
192 print "[Network.py] interfaces - opening failed"
197 split = i.strip().split(' ')
198 if (split[0] == "iface"):
201 if (len(split) == 4 and split[3] == "dhcp"):
202 ifaces[currif]["dhcp"] = True
204 ifaces[currif]["dhcp"] = False
205 if (currif == iface): #read information only for available interfaces
206 if (split[0] == "address"):
207 ifaces[currif]["address"] = map(int, split[1].split('.'))
208 if self.ifaces[currif].has_key("ip"):
209 if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
210 self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
211 if (split[0] == "netmask"):
212 ifaces[currif]["netmask"] = map(int, split[1].split('.'))
213 if self.ifaces[currif].has_key("netmask"):
214 if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
215 self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
216 if (split[0] == "gateway"):
217 ifaces[currif]["gateway"] = map(int, split[1].split('.'))
218 if self.ifaces[currif].has_key("gateway"):
219 if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
220 self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))
221 if (split[0] == "pre-up"):
222 if self.ifaces[currif].has_key("preup"):
223 self.ifaces[currif]["preup"] = i
224 if (split[0] == "post-down"):
225 if self.ifaces[currif].has_key("postdown"):
226 self.ifaces[currif]["postdown"] = i
228 for ifacename, iface in ifaces.items():
229 if self.ifaces.has_key(ifacename):
230 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
232 if len(self.Console.appContainers) == 0:
233 # save configured interfacelist
234 self.configuredNetworkAdapters = self.configuredInterfaces
236 self.loadNameserverConfig()
237 print "read configured interface:", ifaces
238 print "self.ifaces after loading:", self.ifaces
239 self.config_ready = True
241 if callback is not None:
244 def loadNameserverConfig(self):
245 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
246 nameserverPattern = re_compile("nameserver +" + ipRegexp)
247 ipPattern = re_compile(ipRegexp)
251 fp = file('/etc/resolv.conf', 'r')
252 resolv = fp.readlines()
254 self.nameservers = []
256 print "[Network.py] resolv.conf - opening failed"
259 if self.regExpMatch(nameserverPattern, line) is not None:
260 ip = self.regExpMatch(ipPattern, line)
262 self.nameservers.append(self.convertIP(ip))
264 print "nameservers:", self.nameservers
266 def deactivateNetworkConfig(self, callback = None):
267 if self.onRemoteRootFS():
268 if callback is not None:
271 self.deactivateConsole = Console()
273 self.commands.append("/etc/init.d/avahi-daemon stop")
274 for iface in self.ifaces.keys():
275 cmd = "ip addr flush " + iface
276 self.commands.append(cmd)
277 self.commands.append("/etc/init.d/networking stop")
278 self.commands.append("killall -9 udhcpc")
279 self.commands.append("rm /var/run/udhcpc*")
280 self.deactivateConsole.eBatch(self.commands, self.deactivateNetworkFinished, callback, debug=True)
282 def deactivateNetworkFinished(self,extra_args):
283 callback = extra_args
284 if len(self.deactivateConsole.appContainers) == 0:
285 if callback is not None:
288 def activateNetworkConfig(self, callback = None):
289 if self.onRemoteRootFS():
290 if callback is not None:
293 self.activateConsole = Console()
295 self.commands.append("/etc/init.d/networking start")
296 self.commands.append("/etc/init.d/avahi-daemon start")
297 self.activateConsole.eBatch(self.commands, self.activateNetworkFinished, callback, debug=True)
299 def activateNetworkFinished(self,extra_args):
300 callback = extra_args
301 if len(self.activateConsole.appContainers) == 0:
302 if callback is not None:
305 def getConfiguredAdapters(self):
306 return self.configuredNetworkAdapters
308 def getNumberOfAdapters(self):
309 return len(self.ifaces)
311 def getFriendlyAdapterName(self, x):
312 # maybe this needs to be replaced by an external list.
314 "eth0": _("Integrated Ethernet"),
315 "wlan0": _("Wireless"),
316 "ath0": _("Integrated Wireless")
318 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
320 def getAdapterName(self, iface):
323 def getAdapterList(self):
324 return self.ifaces.keys()
326 def getAdapterAttribute(self, iface, attribute):
327 if self.ifaces.has_key(iface):
328 if self.ifaces[iface].has_key(attribute):
329 return self.ifaces[iface][attribute]
332 def setAdapterAttribute(self, iface, attribute, value):
333 print "setting for adapter", iface, "attribute", attribute, " to value", value
334 if self.ifaces.has_key(iface):
335 self.ifaces[iface][attribute] = value
337 def removeAdapterAttribute(self, iface, attribute):
338 if self.ifaces.has_key(iface):
339 if self.ifaces[iface].has_key(attribute):
340 del self.ifaces[iface][attribute]
342 def getNameserverList(self):
343 if len(self.nameservers) == 0:
344 return [[0, 0, 0, 0], [0, 0, 0, 0]]
346 return self.nameservers
348 def clearNameservers(self):
349 self.nameservers = []
351 def addNameserver(self, nameserver):
352 if nameserver not in self.nameservers:
353 self.nameservers.append(nameserver)
355 def removeNameserver(self, nameserver):
356 if nameserver in self.nameservers:
357 self.nameservers.remove(nameserver)
359 def changeNameserver(self, oldnameserver, newnameserver):
360 if oldnameserver in self.nameservers:
361 for i in range(len(self.nameservers)):
362 if self.nameservers[i] == oldnameserver:
363 self.nameservers[i] = newnameserver
365 def resetNetworkConfig(self, mode='lan', callback = None):
366 if self.onRemoteRootFS():
367 if callback is not None:
370 self.resetNetworkConsole = Console()
372 self.commands.append("/etc/init.d/avahi-daemon stop")
373 for iface in self.ifaces.keys():
374 cmd = "ip addr flush " + iface
375 self.commands.append(cmd)
376 self.commands.append("/etc/init.d/networking stop")
377 self.commands.append("killall -9 udhcpc")
378 self.commands.append("rm /var/run/udhcpc*")
379 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True)
381 def resetNetworkFinishedCB(self, extra_args):
382 (mode, callback) = extra_args
383 if len(self.resetNetworkConsole.appContainers) == 0:
384 self.writeDefaultNetworkConfig(mode, callback)
386 def writeDefaultNetworkConfig(self,mode='lan', callback = None):
387 fp = file('/etc/network/interfaces', 'w')
388 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
389 fp.write("auto lo\n")
390 fp.write("iface lo inet loopback\n\n")
392 fp.write("auto wlan0\n")
393 fp.write("iface wlan0 inet dhcp\n")
394 if mode == 'wlan-mpci':
395 fp.write("auto ath0\n")
396 fp.write("iface ath0 inet dhcp\n")
398 fp.write("auto eth0\n")
399 fp.write("iface eth0 inet dhcp\n")
403 self.resetNetworkConsole = Console()
406 self.commands.append("ifconfig eth0 down")
407 self.commands.append("ifconfig ath0 down")
408 self.commands.append("ifconfig wlan0 up")
409 if mode == 'wlan-mpci':
410 self.commands.append("ifconfig eth0 down")
411 self.commands.append("ifconfig wlan0 down")
412 self.commands.append("ifconfig ath0 up")
414 self.commands.append("ifconfig eth0 up")
415 self.commands.append("ifconfig wlan0 down")
416 self.commands.append("ifconfig ath0 down")
417 self.commands.append("/etc/init.d/avahi-daemon start")
418 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)
420 def resetNetworkFinished(self,extra_args):
421 (mode, callback) = extra_args
422 if len(self.resetNetworkConsole.appContainers) == 0:
423 if callback is not None:
426 def checkNetworkState(self,statecallback):
427 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
428 self.NetworkState = 0
429 cmd1 = "ping -c 1 82.149.226.170"
430 cmd2 = "ping -c 1 193.99.144.85"
431 cmd3 = "ping -c 1 209.85.135.103"
432 self.PingConsole = Console()
433 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
434 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
435 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
437 def checkNetworkStateFinished(self, result, retval,extra_args):
438 (statecallback) = extra_args
439 if self.PingConsole is not None:
441 self.PingConsole = None
442 statecallback(self.NetworkState)
444 self.NetworkState += 1
445 if len(self.PingConsole.appContainers) == 0:
446 statecallback(self.NetworkState)
448 def restartNetwork(self,callback = None):
449 if self.onRemoteRootFS():
450 if callback is not None:
453 self.restartConsole = Console()
454 self.config_ready = False
457 self.commands.append("/etc/init.d/avahi-daemon stop")
458 for iface in self.ifaces.keys():
459 cmd = "ip addr flush " + iface
460 self.commands.append(cmd)
461 self.commands.append("/etc/init.d/networking stop")
462 self.commands.append("killall -9 udhcpc")
463 self.commands.append("rm /var/run/udhcpc*")
464 self.commands.append("/etc/init.d/networking start")
465 self.commands.append("/etc/init.d/avahi-daemon start")
466 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
468 def restartNetworkFinished(self,extra_args):
469 ( callback ) = extra_args
470 if callback is not None:
473 def getLinkState(self,iface,callback):
474 cmd = self.ethtool_bin + " " + iface
475 self.LinkConsole = Console()
476 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
478 def getLinkStateFinished(self, result, retval,extra_args):
479 (callback) = extra_args
481 if self.LinkConsole is not None:
482 if len(self.LinkConsole.appContainers) == 0:
485 def stopPingConsole(self):
486 if self.PingConsole is not None:
487 if len(self.PingConsole.appContainers):
488 for name in self.PingConsole.appContainers.keys():
489 self.PingConsole.kill(name)
491 def stopLinkStateConsole(self):
492 if self.LinkConsole is not None:
493 if len(self.LinkConsole.appContainers):
494 for name in self.LinkConsole.appContainers.keys():
495 self.LinkConsole.kill(name)
497 def stopDNSConsole(self):
498 if self.DnsConsole is not None:
499 if len(self.DnsConsole.appContainers):
500 for name in self.DnsConsole.appContainers.keys():
501 self.DnsConsole.kill(name)
503 def stopRestartConsole(self):
504 if self.restartConsole is not None:
505 if len(self.restartConsole.appContainers):
506 for name in self.restartConsole.appContainers.keys():
507 self.restartConsole.kill(name)
509 def stopGetInterfacesConsole(self):
510 if self.Console is not None:
511 if len(self.Console.appContainers):
512 for name in self.Console.appContainers.keys():
513 self.Console.kill(name)
515 def stopDeactivateInterfaceConsole(self):
516 if self.deactivateInterfaceConsole is not None:
517 if len(self.deactivateInterfaceConsole.appContainers):
518 for name in self.deactivateInterfaceConsole.appContainers.keys():
519 self.deactivateInterfaceConsole.kill(name)
521 def checkforInterface(self,iface):
522 if self.getAdapterAttribute(iface, 'up') is True:
525 ret=system("ifconfig " + iface + " up")
526 system("ifconfig " + iface + " down")
532 def checkDNSLookup(self,statecallback):
533 cmd1 = "nslookup www.dream-multimedia-tv.de"
534 cmd2 = "nslookup www.heise.de"
535 cmd3 = "nslookup www.google.de"
536 self.DnsConsole = Console()
537 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
538 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
539 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
541 def checkDNSLookupFinished(self, result, retval,extra_args):
542 (statecallback) = extra_args
543 if self.DnsConsole is not None:
545 self.DnsConsole = None
546 statecallback(self.DnsState)
549 if len(self.DnsConsole.appContainers) == 0:
550 statecallback(self.DnsState)
552 def deactivateInterface(self,iface,callback = None):
553 if self.onRemoteRootFS():
554 if callback is not None:
557 self.deactivateInterfaceConsole = Console()
559 cmd1 = "ip addr flush " + iface
560 cmd2 = "ifconfig " + iface + " down"
561 self.commands.append(cmd1)
562 self.commands.append(cmd2)
563 self.deactivateInterfaceConsole.eBatch(self.commands, self.deactivateInterfaceFinished, callback, debug=True)
565 def deactivateInterfaceFinished(self,extra_args):
566 callback = extra_args
567 if self.deactivateInterfaceConsole:
568 if len(self.deactivateInterfaceConsole.appContainers) == 0:
569 if callback is not None:
572 def detectWlanModule(self):
573 self.wlanmodule = None
574 rt73_dir = "/sys/bus/usb/drivers/rt73/"
575 zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
576 madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
577 if os_path.exists(madwifi_dir):
578 files = listdir(madwifi_dir)
580 self.wlanmodule = 'madwifi'
581 if os_path.exists(rt73_dir):
582 rtfiles = listdir(rt73_dir)
583 if len(rtfiles) == 2 or len(rtfiles) == 5:
584 self.wlanmodule = 'ralink'
585 if os_path.exists(zd1211b_dir):
586 zdfiles = listdir(zd1211b_dir)
587 if len(zdfiles) == 1 or len(zdfiles) == 5:
588 self.wlanmodule = 'zydas'
589 return self.wlanmodule
591 def calc_netmask(self,nmask):
592 from struct import pack, unpack
593 from socket import inet_ntoa, inet_aton
596 cidr_range = range(0, 32)
598 if cidr not in cidr_range:
599 print 'cidr invalid: %d' % cidr
602 nm = ((1L<<cidr)-1)<<(32-cidr)
603 netmask = str(inet_ntoa(pack('>L', nm)))
606 def msgPlugins(self):
607 if self.config_ready is not None:
608 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
609 p(reason=self.config_ready)