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 Components.About import about
8 from Plugins.Plugin import PluginDescriptor
13 self.configuredInterfaces = []
14 self.configuredNetworkAdapters = []
18 self.ethtool_bin = "ethtool"
19 self.container = eConsoleAppContainer()
20 self.Console = Console()
21 self.LinkConsole = Console()
22 self.restartConsole = Console()
23 self.deactivateInterfaceConsole = Console()
24 self.activateInterfaceConsole = Console()
25 self.resetNetworkConsole = Console()
26 self.DnsConsole = Console()
27 self.PingConsole = Console()
28 self.config_ready = None
29 self.friendlyNames = {}
30 self.lan_interfaces = []
31 self.wlan_interfaces = []
32 self.remoteRootFS = None
35 def onRemoteRootFS(self):
36 if self.remoteRootFS == None:
37 fp = file('/proc/mounts', 'r')
38 mounts = fp.readlines()
40 self.remoteRootFS = False
42 parts = line.strip().split()
43 if parts[1] == '/' and parts[2] == 'nfs':
44 self.remoteRootFS = True
46 return self.remoteRootFS
48 def getInterfaces(self, callback = None):
49 self.configuredInterfaces = []
50 for device in listdir('/sys/class/net'):
51 if not device in ('lo','wifi0', 'wmaster0'):
52 self.getAddrInet(device, callback)
55 def regExpMatch(self, pattern, string):
59 return pattern.search(string).group()
60 except AttributeError:
63 # helper function to convert ips from a sring to a list of ints
64 def convertIP(self, ip):
65 return [ int(n) for n in ip.split('.') ]
67 def getAddrInet(self, iface, callback):
69 self.Console = Console()
70 cmd = "ip -o addr show dev " + iface
71 self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
73 def IPaddrFinished(self, result, retval, extra_args):
74 (iface, callback ) = extra_args
75 data = { 'up': False, 'dhcp': False, 'preup' : False, 'predown' : False }
76 globalIPpattern = re_compile("scope global")
77 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
78 netRegexp = '[0-9]{1,2}'
79 macRegexp = '[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}'
80 ipLinePattern = re_compile('inet ' + ipRegexp + '/')
81 ipPattern = re_compile(ipRegexp)
82 netmaskLinePattern = re_compile('/' + netRegexp)
83 netmaskPattern = re_compile(netRegexp)
84 bcastLinePattern = re_compile(' brd ' + ipRegexp)
85 upPattern = re_compile('UP')
86 macPattern = re_compile(macRegexp)
87 macLinePattern = re_compile('link/ether ' + macRegexp)
89 for line in result.splitlines():
90 split = line.strip().split(' ',2)
91 if (split[1][:-1] == iface):
92 up = self.regExpMatch(upPattern, split[2])
93 mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2]))
97 self.configuredInterfaces.append(iface)
100 if (split[1] == iface):
101 if re_search(globalIPpattern, split[2]):
102 ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
103 netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2])))
104 bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2]))
106 data['ip'] = self.convertIP(ip)
107 if netmask is not None:
108 data['netmask'] = self.convertIP(netmask)
109 if bcast is not None:
110 data['bcast'] = self.convertIP(bcast)
112 if not data.has_key('ip'):
114 data['ip'] = [0, 0, 0, 0]
115 data['netmask'] = [0, 0, 0, 0]
116 data['gateway'] = [0, 0, 0, 0]
118 cmd = "route -n | grep " + iface
119 self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback])
121 def routeFinished(self, result, retval, extra_args):
122 (iface, data, callback) = extra_args
123 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
124 ipPattern = re_compile(ipRegexp)
125 ipLinePattern = re_compile(ipRegexp)
127 for line in result.splitlines():
129 if line[0:7] == "0.0.0.0":
130 gateway = self.regExpMatch(ipPattern, line[16:31])
131 if gateway is not None:
132 data['gateway'] = self.convertIP(gateway)
134 self.ifaces[iface] = data
135 self.loadNetworkConfig(iface,callback)
137 def writeNetworkConfig(self):
138 self.configuredInterfaces = []
139 fp = file('/etc/network/interfaces', 'w')
140 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
141 fp.write("auto lo\n")
142 fp.write("iface lo inet loopback\n\n")
143 for ifacename, iface in self.ifaces.items():
144 if iface['up'] == True:
145 fp.write("auto " + ifacename + "\n")
146 self.configuredInterfaces.append(ifacename)
147 if iface['dhcp'] == True:
148 fp.write("iface "+ ifacename +" inet dhcp\n")
149 if iface['dhcp'] == False:
150 fp.write("iface "+ ifacename +" inet static\n")
151 if iface.has_key('ip'):
152 print tuple(iface['ip'])
153 fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip']))
154 fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
155 if iface.has_key('gateway'):
156 fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
157 if iface.has_key("configStrings"):
158 fp.write(iface["configStrings"])
159 if iface["preup"] is not False and not iface.has_key("configStrings"):
160 fp.write(iface["preup"])
161 if iface["predown"] is not False and not iface.has_key("configStrings"):
162 fp.write(iface["predown"])
165 self.configuredNetworkAdapters = self.configuredInterfaces
166 self.writeNameserverConfig()
168 def writeNameserverConfig(self):
169 fp = file('/etc/resolv.conf', 'w')
170 for nameserver in self.nameservers:
171 fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
174 def loadNetworkConfig(self,iface,callback = None):
176 # parse the interfaces-file
178 fp = file('/etc/network/interfaces', 'r')
179 interfaces = fp.readlines()
182 print "[Network.py] interfaces - opening failed"
187 split = i.strip().split(' ')
188 if (split[0] == "iface"):
191 if (len(split) == 4 and split[3] == "dhcp"):
192 ifaces[currif]["dhcp"] = True
194 ifaces[currif]["dhcp"] = False
195 if (currif == iface): #read information only for available interfaces
196 if (split[0] == "address"):
197 ifaces[currif]["address"] = map(int, split[1].split('.'))
198 if self.ifaces[currif].has_key("ip"):
199 if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
200 self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
201 if (split[0] == "netmask"):
202 ifaces[currif]["netmask"] = map(int, split[1].split('.'))
203 if self.ifaces[currif].has_key("netmask"):
204 if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
205 self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
206 if (split[0] == "gateway"):
207 ifaces[currif]["gateway"] = map(int, split[1].split('.'))
208 if self.ifaces[currif].has_key("gateway"):
209 if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
210 self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))
211 if (split[0] == "pre-up"):
212 if self.ifaces[currif].has_key("preup"):
213 self.ifaces[currif]["preup"] = i
214 if (split[0] in ("pre-down","post-down")):
215 if self.ifaces[currif].has_key("predown"):
216 self.ifaces[currif]["predown"] = i
218 for ifacename, iface in ifaces.items():
219 if self.ifaces.has_key(ifacename):
220 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
222 if len(self.Console.appContainers) == 0:
223 # save configured interfacelist
224 self.configuredNetworkAdapters = self.configuredInterfaces
226 self.loadNameserverConfig()
227 print "read configured interface:", ifaces
228 print "self.ifaces after loading:", self.ifaces
229 self.config_ready = True
231 if callback is not None:
234 def loadNameserverConfig(self):
235 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
236 nameserverPattern = re_compile("nameserver +" + ipRegexp)
237 ipPattern = re_compile(ipRegexp)
241 fp = file('/etc/resolv.conf', 'r')
242 resolv = fp.readlines()
244 self.nameservers = []
246 print "[Network.py] resolv.conf - opening failed"
249 if self.regExpMatch(nameserverPattern, line) is not None:
250 ip = self.regExpMatch(ipPattern, line)
252 self.nameservers.append(self.convertIP(ip))
254 print "nameservers:", self.nameservers
256 def getInstalledAdapters(self):
257 return [x for x in listdir('/sys/class/net') if not x in ('lo','wifi0', 'wmaster0')]
259 def getConfiguredAdapters(self):
260 return self.configuredNetworkAdapters
262 def getNumberOfAdapters(self):
263 return len(self.ifaces)
265 def getFriendlyAdapterName(self, x):
266 if x in self.friendlyNames.keys():
267 return self.friendlyNames.get(x, x)
269 self.friendlyNames[x] = self.getFriendlyAdapterNaming(x)
270 return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name
272 def getFriendlyAdapterNaming(self, iface):
273 if iface.startswith('eth'):
274 if iface not in self.lan_interfaces and len(self.lan_interfaces) == 0:
275 self.lan_interfaces.append(iface)
276 return _("LAN connection")
277 elif iface not in self.lan_interfaces and len(self.lan_interfaces) >= 1:
278 self.lan_interfaces.append(iface)
279 return _("LAN connection") + " " + str(len(self.lan_interfaces))
281 if iface not in self.wlan_interfaces and len(self.wlan_interfaces) == 0:
282 self.wlan_interfaces.append(iface)
283 return _("WLAN connection")
284 elif iface not in self.wlan_interfaces and len(self.wlan_interfaces) >= 1:
285 self.wlan_interfaces.append(iface)
286 return _("WLAN connection") + " " + str(len(self.wlan_interfaces))
288 def getFriendlyAdapterDescription(self, iface):
289 if not self.isWirelessInterface(iface):
290 return _('Ethernet network interface')
292 moduledir = self.getWlanModuleDir(iface)
293 if os_path.isdir(moduledir):
294 name = os_path.basename(os_path.realpath(moduledir))
295 if name in ('ath_pci','ath5k'):
297 elif name in ('rt73','rt73usb','rt3070sta'):
299 elif name == 'zd1211b':
301 elif name == 'r871x_usb_drv':
306 return name + ' ' + _('wireless network interface')
308 def getAdapterName(self, iface):
311 def getAdapterList(self):
312 return self.ifaces.keys()
314 def getAdapterAttribute(self, iface, attribute):
315 if self.ifaces.has_key(iface):
316 if self.ifaces[iface].has_key(attribute):
317 return self.ifaces[iface][attribute]
320 def setAdapterAttribute(self, iface, attribute, value):
321 print "setting for adapter", iface, "attribute", attribute, " to value", value
322 if self.ifaces.has_key(iface):
323 self.ifaces[iface][attribute] = value
325 def removeAdapterAttribute(self, iface, attribute):
326 if self.ifaces.has_key(iface):
327 if self.ifaces[iface].has_key(attribute):
328 del self.ifaces[iface][attribute]
330 def getNameserverList(self):
331 if len(self.nameservers) == 0:
332 return [[0, 0, 0, 0], [0, 0, 0, 0]]
334 return self.nameservers
336 def clearNameservers(self):
337 self.nameservers = []
339 def addNameserver(self, nameserver):
340 if nameserver not in self.nameservers:
341 self.nameservers.append(nameserver)
343 def removeNameserver(self, nameserver):
344 if nameserver in self.nameservers:
345 self.nameservers.remove(nameserver)
347 def changeNameserver(self, oldnameserver, newnameserver):
348 if oldnameserver in self.nameservers:
349 for i in range(len(self.nameservers)):
350 if self.nameservers[i] == oldnameserver:
351 self.nameservers[i] = newnameserver
353 def resetNetworkConfig(self, mode='lan', callback = None):
354 self.resetNetworkConsole = Console()
356 self.commands.append("/etc/init.d/avahi-daemon stop")
357 for iface in self.ifaces.keys():
358 if iface != 'eth0' or not self.onRemoteRootFS():
359 self.commands.append("ip addr flush dev " + iface)
360 self.commands.append("/etc/init.d/networking stop")
361 self.commands.append("killall -9 udhcpc")
362 self.commands.append("rm /var/run/udhcpc*")
363 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True)
365 def resetNetworkFinishedCB(self, extra_args):
366 (mode, callback) = extra_args
367 if len(self.resetNetworkConsole.appContainers) == 0:
368 self.writeDefaultNetworkConfig(mode, callback)
370 def writeDefaultNetworkConfig(self,mode='lan', callback = None):
371 fp = file('/etc/network/interfaces', 'w')
372 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
373 fp.write("auto lo\n")
374 fp.write("iface lo inet loopback\n\n")
376 fp.write("auto wlan0\n")
377 fp.write("iface wlan0 inet dhcp\n")
378 if mode == 'wlan-mpci':
379 fp.write("auto ath0\n")
380 fp.write("iface ath0 inet dhcp\n")
382 fp.write("auto eth0\n")
383 fp.write("iface eth0 inet dhcp\n")
387 self.resetNetworkConsole = Console()
390 self.commands.append("ifconfig eth0 down")
391 self.commands.append("ifconfig ath0 down")
392 self.commands.append("ifconfig wlan0 up")
393 if mode == 'wlan-mpci':
394 self.commands.append("ifconfig eth0 down")
395 self.commands.append("ifconfig wlan0 down")
396 self.commands.append("ifconfig ath0 up")
398 self.commands.append("ifconfig eth0 up")
399 self.commands.append("ifconfig wlan0 down")
400 self.commands.append("ifconfig ath0 down")
401 self.commands.append("/etc/init.d/avahi-daemon start")
402 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)
404 def resetNetworkFinished(self,extra_args):
405 (mode, callback) = extra_args
406 if len(self.resetNetworkConsole.appContainers) == 0:
407 if callback is not None:
410 def checkNetworkState(self,statecallback):
411 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
412 self.NetworkState = 0
413 cmd1 = "ping -c 1 82.149.226.170"
414 cmd2 = "ping -c 1 193.99.144.85"
415 cmd3 = "ping -c 1 209.85.135.103"
416 self.PingConsole = Console()
417 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
418 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
419 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
421 def checkNetworkStateFinished(self, result, retval,extra_args):
422 (statecallback) = extra_args
423 if self.PingConsole is not None:
425 self.PingConsole = None
426 statecallback(self.NetworkState)
428 self.NetworkState += 1
429 if len(self.PingConsole.appContainers) == 0:
430 statecallback(self.NetworkState)
432 def restartNetwork(self,callback = None):
433 self.restartConsole = Console()
434 self.config_ready = False
437 self.commands.append("/etc/init.d/avahi-daemon stop")
438 for iface in self.ifaces.keys():
439 if iface != 'eth0' or not self.onRemoteRootFS():
440 self.commands.append("ifdown " + iface)
441 self.commands.append("ip addr flush dev " + iface)
442 self.commands.append("/etc/init.d/networking stop")
443 self.commands.append("killall -9 udhcpc")
444 self.commands.append("rm /var/run/udhcpc*")
445 self.commands.append("/etc/init.d/networking start")
446 self.commands.append("/etc/init.d/avahi-daemon start")
447 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
449 def restartNetworkFinished(self,extra_args):
450 ( callback ) = extra_args
451 if callback is not None:
454 def getLinkState(self,iface,callback):
455 cmd = self.ethtool_bin + " " + iface
456 self.LinkConsole = Console()
457 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
459 def getLinkStateFinished(self, result, retval,extra_args):
460 (callback) = extra_args
462 if self.LinkConsole is not None:
463 if len(self.LinkConsole.appContainers) == 0:
466 def stopPingConsole(self):
467 if self.PingConsole is not None:
468 if len(self.PingConsole.appContainers):
469 for name in self.PingConsole.appContainers.keys():
470 self.PingConsole.kill(name)
472 def stopLinkStateConsole(self):
473 if self.LinkConsole is not None:
474 if len(self.LinkConsole.appContainers):
475 for name in self.LinkConsole.appContainers.keys():
476 self.LinkConsole.kill(name)
478 def stopDNSConsole(self):
479 if self.DnsConsole is not None:
480 if len(self.DnsConsole.appContainers):
481 for name in self.DnsConsole.appContainers.keys():
482 self.DnsConsole.kill(name)
484 def stopRestartConsole(self):
485 if self.restartConsole is not None:
486 if len(self.restartConsole.appContainers):
487 for name in self.restartConsole.appContainers.keys():
488 self.restartConsole.kill(name)
490 def stopGetInterfacesConsole(self):
491 if self.Console is not None:
492 if len(self.Console.appContainers):
493 for name in self.Console.appContainers.keys():
494 self.Console.kill(name)
496 def stopDeactivateInterfaceConsole(self):
497 if self.deactivateInterfaceConsole is not None:
498 self.deactivateInterfaceConsole.killAll()
499 self.deactivateInterfaceConsole = None
501 def stopActivateInterfaceConsole(self):
502 if self.activateInterfaceConsole is not None:
503 self.activateInterfaceConsole.killAll()
504 self.activateInterfaceConsole = None
506 def checkforInterface(self,iface):
507 if self.getAdapterAttribute(iface, 'up') is True:
510 ret=system("ifconfig " + iface + " up")
511 system("ifconfig " + iface + " down")
517 def checkDNSLookup(self,statecallback):
518 cmd1 = "nslookup www.dream-multimedia-tv.de"
519 cmd2 = "nslookup www.heise.de"
520 cmd3 = "nslookup www.google.de"
521 self.DnsConsole = Console()
522 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
523 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
524 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
526 def checkDNSLookupFinished(self, result, retval,extra_args):
527 (statecallback) = extra_args
528 if self.DnsConsole is not None:
530 self.DnsConsole = None
531 statecallback(self.DnsState)
534 if len(self.DnsConsole.appContainers) == 0:
535 statecallback(self.DnsState)
537 def deactivateInterface(self,ifaces,callback = None):
538 self.config_ready = False
541 def buildCommands(iface):
542 commands.append("ifdown " + iface)
543 commands.append("ip addr flush dev " + iface)
544 #wpa_supplicant sometimes doesn't quit properly on SIGTERM
545 if os_path.exists('/var/run/wpa_supplicant/'+ iface):
546 commands.append("wpa_cli -i" + iface + " terminate")
548 if not self.deactivateInterfaceConsole:
549 self.deactivateInterfaceConsole = Console()
551 if isinstance(ifaces, (list, tuple)):
553 if iface != 'eth0' or not self.onRemoteRootFS():
556 if ifaces == 'eth0' and self.onRemoteRootFS():
557 if callback is not None:
560 buildCommands(ifaces)
561 self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, [ifaces,callback], debug=True)
563 def deactivateInterfaceFinished(self,extra_args):
564 (ifaces, callback) = extra_args
565 def checkCommandResult(iface):
566 if self.deactivateInterfaceConsole and self.deactivateInterfaceConsole.appResults.has_key("ifdown " + iface):
567 result = str(self.deactivateInterfaceConsole.appResults.get("ifdown " + iface)).strip("\n")
568 if result == "ifdown: interface " + iface + " not configured":
572 #ifdown sometimes can't get the interface down.
573 if isinstance(ifaces, (list, tuple)):
575 if checkCommandResult(iface) is False:
576 Console().ePopen(("ifconfig " + iface + " down" ))
578 if checkCommandResult(ifaces) is False:
579 Console().ePopen(("ifconfig " + ifaces + " down" ))
581 if self.deactivateInterfaceConsole:
582 if len(self.deactivateInterfaceConsole.appContainers) == 0:
583 if callback is not None:
586 def activateInterface(self,iface,callback = None):
587 if self.config_ready:
588 self.config_ready = False
590 if iface == 'eth0' and self.onRemoteRootFS():
591 if callback is not None:
594 if not self.activateInterfaceConsole:
595 self.activateInterfaceConsole = Console()
597 commands.append("ifup " + iface)
598 self.activateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True)
600 def activateInterfaceFinished(self,extra_args):
601 callback = extra_args
602 if self.activateInterfaceConsole:
603 if len(self.activateInterfaceConsole.appContainers) == 0:
604 if callback is not None:
607 def sysfsPath(self, iface):
608 return '/sys/class/net/' + iface
610 def isWirelessInterface(self, iface):
611 if os_path.isdir(self.sysfsPath(iface) + '/wireless'):
614 ifaces = file('/proc/net/wireless').read().strip()
620 def getWlanModuleDir(self, iface = None):
621 devicedir = self.sysfsPath(iface) + '/device'
622 moduledir = devicedir + '/driver/module'
623 if not os_path.isdir(moduledir):
624 tmpfiles = listdir(devicedir)
625 moduledir_found = False
627 if x.startswith("1-"):
628 moduledir_found = True
629 moduledir = devicedir + '/' + x + '/driver/module'
630 if not moduledir_found:
631 moduledir_found = True
632 if os_path.isdir(devicedir + '/driver'):
633 moduledir = devicedir + '/driver'
637 def detectWlanModule(self, iface = None):
638 if not self.isWirelessInterface(iface):
641 devicedir = self.sysfsPath(iface) + '/device'
642 if os_path.isdir(devicedir + '/ieee80211'):
645 moduledir = self.getWlanModuleDir(iface)
646 if os_path.isdir(moduledir):
647 module = os_path.basename(os_path.realpath(moduledir))
648 if module in ('ath_pci','ath5k'):
650 if module in ('rt73','rt73'):
652 if module == 'zd1211b':
656 def calc_netmask(self,nmask):
657 from struct import pack, unpack
658 from socket import inet_ntoa, inet_aton
661 cidr_range = range(0, 32)
663 if cidr not in cidr_range:
664 print 'cidr invalid: %d' % cidr
667 nm = ((1L<<cidr)-1)<<(32-cidr)
668 netmask = str(inet_ntoa(pack('>L', nm)))
671 def msgPlugins(self):
672 if self.config_ready is not None:
673 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
674 p(reason=self.config_ready)