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-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{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('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}')
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 getConfiguredAdapters(self):
257 return self.configuredNetworkAdapters
259 def getNumberOfAdapters(self):
260 return len(self.ifaces)
262 def getFriendlyAdapterName(self, x):
263 if x in self.friendlyNames.keys():
264 return self.friendlyNames.get(x, x)
266 self.friendlyNames[x] = self.getFriendlyAdapterNaming(x)
267 return self.friendlyNames.get(x, x) # when we have no friendly name, use adapter name
269 def getFriendlyAdapterNaming(self, iface):
270 if iface.startswith('eth'):
271 if iface not in self.lan_interfaces and len(self.lan_interfaces) == 0:
272 self.lan_interfaces.append(iface)
273 return _("LAN connection")
274 elif iface not in self.lan_interfaces and len(self.lan_interfaces) >= 1:
275 self.lan_interfaces.append(iface)
276 return _("LAN connection") + " " + str(len(self.lan_interfaces))
278 if iface not in self.wlan_interfaces and len(self.wlan_interfaces) == 0:
279 self.wlan_interfaces.append(iface)
280 return _("WLAN connection")
281 elif iface not in self.wlan_interfaces and len(self.wlan_interfaces) >= 1:
282 self.wlan_interfaces.append(iface)
283 return _("WLAN connection") + " " + str(len(self.wlan_interfaces))
285 def getFriendlyAdapterDescription(self, iface):
286 if not self.isWirelessInterface(iface):
287 return _('Ethernet network interface')
289 moduledir = self.sysfsPath(iface) + '/device/driver/module'
290 if not os_path.isdir(moduledir):
291 tmpfiles = listdir(self.sysfsPath(iface) + '/device')
293 if x.startswith("1-"):
294 moduledir = self.sysfsPath(iface) + '/device/' + x + '/driver/module'
296 if os_path.isdir(moduledir):
297 name = os_path.basename(os_path.realpath(moduledir))
298 if name in ('ath_pci','ath5k'):
300 elif name in ('rt73','rt73usb','rt3070sta'):
302 elif name == 'zd1211b':
307 return name + ' ' + _('wireless network interface')
309 def getAdapterName(self, iface):
312 def getAdapterList(self):
313 return self.ifaces.keys()
315 def getAdapterAttribute(self, iface, attribute):
316 if self.ifaces.has_key(iface):
317 if self.ifaces[iface].has_key(attribute):
318 return self.ifaces[iface][attribute]
321 def setAdapterAttribute(self, iface, attribute, value):
322 print "setting for adapter", iface, "attribute", attribute, " to value", value
323 if self.ifaces.has_key(iface):
324 self.ifaces[iface][attribute] = value
326 def removeAdapterAttribute(self, iface, attribute):
327 if self.ifaces.has_key(iface):
328 if self.ifaces[iface].has_key(attribute):
329 del self.ifaces[iface][attribute]
331 def getNameserverList(self):
332 if len(self.nameservers) == 0:
333 return [[0, 0, 0, 0], [0, 0, 0, 0]]
335 return self.nameservers
337 def clearNameservers(self):
338 self.nameservers = []
340 def addNameserver(self, nameserver):
341 if nameserver not in self.nameservers:
342 self.nameservers.append(nameserver)
344 def removeNameserver(self, nameserver):
345 if nameserver in self.nameservers:
346 self.nameservers.remove(nameserver)
348 def changeNameserver(self, oldnameserver, newnameserver):
349 if oldnameserver in self.nameservers:
350 for i in range(len(self.nameservers)):
351 if self.nameservers[i] == oldnameserver:
352 self.nameservers[i] = newnameserver
354 def resetNetworkConfig(self, mode='lan', callback = None):
355 self.resetNetworkConsole = Console()
357 self.commands.append("/etc/init.d/avahi-daemon stop")
358 for iface in self.ifaces.keys():
359 if iface != 'eth0' or not self.onRemoteRootFS():
360 self.commands.append("ip addr flush dev " + iface)
361 self.commands.append("/etc/init.d/networking stop")
362 self.commands.append("killall -9 udhcpc")
363 self.commands.append("rm /var/run/udhcpc*")
364 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True)
366 def resetNetworkFinishedCB(self, extra_args):
367 (mode, callback) = extra_args
368 if len(self.resetNetworkConsole.appContainers) == 0:
369 self.writeDefaultNetworkConfig(mode, callback)
371 def writeDefaultNetworkConfig(self,mode='lan', callback = None):
372 fp = file('/etc/network/interfaces', 'w')
373 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
374 fp.write("auto lo\n")
375 fp.write("iface lo inet loopback\n\n")
377 fp.write("auto wlan0\n")
378 fp.write("iface wlan0 inet dhcp\n")
379 if mode == 'wlan-mpci':
380 fp.write("auto ath0\n")
381 fp.write("iface ath0 inet dhcp\n")
383 fp.write("auto eth0\n")
384 fp.write("iface eth0 inet dhcp\n")
388 self.resetNetworkConsole = Console()
391 self.commands.append("ifconfig eth0 down")
392 self.commands.append("ifconfig ath0 down")
393 self.commands.append("ifconfig wlan0 up")
394 if mode == 'wlan-mpci':
395 self.commands.append("ifconfig eth0 down")
396 self.commands.append("ifconfig wlan0 down")
397 self.commands.append("ifconfig ath0 up")
399 self.commands.append("ifconfig eth0 up")
400 self.commands.append("ifconfig wlan0 down")
401 self.commands.append("ifconfig ath0 down")
402 self.commands.append("/etc/init.d/avahi-daemon start")
403 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)
405 def resetNetworkFinished(self,extra_args):
406 (mode, callback) = extra_args
407 if len(self.resetNetworkConsole.appContainers) == 0:
408 if callback is not None:
411 def checkNetworkState(self,statecallback):
412 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
413 self.NetworkState = 0
414 cmd1 = "ping -c 1 82.149.226.170"
415 cmd2 = "ping -c 1 193.99.144.85"
416 cmd3 = "ping -c 1 209.85.135.103"
417 self.PingConsole = Console()
418 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
419 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
420 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
422 def checkNetworkStateFinished(self, result, retval,extra_args):
423 (statecallback) = extra_args
424 if self.PingConsole is not None:
426 self.PingConsole = None
427 statecallback(self.NetworkState)
429 self.NetworkState += 1
430 if len(self.PingConsole.appContainers) == 0:
431 statecallback(self.NetworkState)
433 def restartNetwork(self,callback = None):
434 self.restartConsole = Console()
435 self.config_ready = False
438 self.commands.append("/etc/init.d/avahi-daemon stop")
439 for iface in self.ifaces.keys():
440 if iface != 'eth0' or not self.onRemoteRootFS():
441 self.commands.append("ifdown " + iface)
442 self.commands.append("ip addr flush dev " + iface)
443 self.commands.append("/etc/init.d/networking stop")
444 self.commands.append("killall -9 udhcpc")
445 self.commands.append("rm /var/run/udhcpc*")
446 self.commands.append("/etc/init.d/networking start")
447 self.commands.append("/etc/init.d/avahi-daemon start")
448 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
450 def restartNetworkFinished(self,extra_args):
451 ( callback ) = extra_args
452 if callback is not None:
455 def getLinkState(self,iface,callback):
456 cmd = self.ethtool_bin + " " + iface
457 self.LinkConsole = Console()
458 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
460 def getLinkStateFinished(self, result, retval,extra_args):
461 (callback) = extra_args
463 if self.LinkConsole is not None:
464 if len(self.LinkConsole.appContainers) == 0:
467 def stopPingConsole(self):
468 if self.PingConsole is not None:
469 if len(self.PingConsole.appContainers):
470 for name in self.PingConsole.appContainers.keys():
471 self.PingConsole.kill(name)
473 def stopLinkStateConsole(self):
474 if self.LinkConsole is not None:
475 if len(self.LinkConsole.appContainers):
476 for name in self.LinkConsole.appContainers.keys():
477 self.LinkConsole.kill(name)
479 def stopDNSConsole(self):
480 if self.DnsConsole is not None:
481 if len(self.DnsConsole.appContainers):
482 for name in self.DnsConsole.appContainers.keys():
483 self.DnsConsole.kill(name)
485 def stopRestartConsole(self):
486 if self.restartConsole is not None:
487 if len(self.restartConsole.appContainers):
488 for name in self.restartConsole.appContainers.keys():
489 self.restartConsole.kill(name)
491 def stopGetInterfacesConsole(self):
492 if self.Console is not None:
493 if len(self.Console.appContainers):
494 for name in self.Console.appContainers.keys():
495 self.Console.kill(name)
497 def stopDeactivateInterfaceConsole(self):
498 if self.deactivateInterfaceConsole is not None:
499 self.deactivateInterfaceConsole.killAll()
500 self.deactivateInterfaceConsole = None
502 def stopActivateInterfaceConsole(self):
503 if self.activateInterfaceConsole is not None:
504 self.activateInterfaceConsole.killAll()
505 self.activateInterfaceConsole = None
507 def checkforInterface(self,iface):
508 if self.getAdapterAttribute(iface, 'up') is True:
511 ret=system("ifconfig " + iface + " up")
512 system("ifconfig " + iface + " down")
518 def checkDNSLookup(self,statecallback):
519 cmd1 = "nslookup www.dream-multimedia-tv.de"
520 cmd2 = "nslookup www.heise.de"
521 cmd3 = "nslookup www.google.de"
522 self.DnsConsole = Console()
523 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
524 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
525 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
527 def checkDNSLookupFinished(self, result, retval,extra_args):
528 (statecallback) = extra_args
529 if self.DnsConsole is not None:
531 self.DnsConsole = None
532 statecallback(self.DnsState)
535 if len(self.DnsConsole.appContainers) == 0:
536 statecallback(self.DnsState)
538 def deactivateInterface(self,ifaces,callback = None):
539 self.config_ready = False
542 if not self.deactivateInterfaceConsole:
543 self.deactivateInterfaceConsole = Console()
544 if isinstance(ifaces, (list, tuple)):
546 if iface != 'eth0' or not self.onRemoteRootFS():
547 commands.append("ifdown " + iface)
548 commands.append("ip addr flush dev " + iface)
549 # HACK: wpa_supplicant sometimes doesn't quit properly on SIGTERM
550 if os_path.exists('/var/run/wpa_supplicant/'+ iface):
551 commands.append("killall -9 wpa_supplicant")
552 commands.append("rm -rf /var/run/wpa_supplicant/" + iface)
553 self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, callback, debug=True)
556 if iface == 'eth0' and self.onRemoteRootFS():
557 if callback is not None:
560 commands.append("ifdown " + iface)
561 commands.append("ip addr flush dev " + iface)
562 # HACK: wpa_supplicant sometimes doesn't quit properly on SIGTERM
563 if os_path.exists('/var/run/wpa_supplicant/'+ iface):
564 commands.append("killall -9 wpa_supplicant")
565 commands.append("rm -rf /var/run/wpa_supplicant/" + iface)
566 self.deactivateInterfaceConsole.eBatch(commands, self.deactivateInterfaceFinished, callback, debug=True)
568 def deactivateInterfaceFinished(self,extra_args):
569 callback = extra_args
570 if self.deactivateInterfaceConsole:
571 if len(self.deactivateInterfaceConsole.appContainers) == 0:
572 if callback is not None:
575 def activateInterface(self,iface,callback = None):
576 if iface == 'eth0' and self.onRemoteRootFS():
577 if callback is not None:
580 if not self.activateInterfaceConsole:
581 self.activateInterfaceConsole = Console()
583 commands.append("ifup " + iface)
584 self.deactivateInterfaceConsole.eBatch(commands, self.activateInterfaceFinished, callback, debug=True)
586 def activateInterfaceFinished(self,extra_args):
587 callback = extra_args
588 if self.activateInterfaceConsole:
589 if len(self.activateInterfaceConsole.appContainers) == 0:
590 if callback is not None:
593 def sysfsPath(self, iface):
594 return '/sys/class/net/' + iface
596 def isWirelessInterface(self, iface):
597 return os_path.isdir(self.sysfsPath(iface) + '/wireless')
599 def detectWlanModule(self, iface = None):
600 if not self.isWirelessInterface(iface):
603 devicedir = self.sysfsPath(iface) + '/device'
604 if os_path.isdir(devicedir + '/ieee80211'):
607 moduledir = devicedir + "/driver/module"
608 if not os_path.isdir(moduledir):
609 tmpfiles = listdir(devicedir)
611 if x.startswith("1-"):
612 moduledir = devicedir + "/" + x + "/driver/module"
614 if os_path.isdir(moduledir):
615 module = os_path.basename(os_path.realpath(moduledir))
616 if module in ('ath_pci','ath5k'):
618 if module in ('rt73','rt73'):
620 if module == 'zd1211b':
622 if module in ('rt3070sta'):
626 def calc_netmask(self,nmask):
627 from struct import pack, unpack
628 from socket import inet_ntoa, inet_aton
631 cidr_range = range(0, 32)
633 if cidr not in cidr_range:
634 print 'cidr invalid: %d' % cidr
637 nm = ((1L<<cidr)-1)<<(32-cidr)
638 netmask = str(inet_ntoa(pack('>L', nm)))
641 def msgPlugins(self):
642 if self.config_ready is not None:
643 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
644 p(reason=self.config_ready)