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 interfac:", 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 cmd1 = "ping -c 1 82.149.226.170"
429 cmd2 = "ping -c 1 193.99.144.85"
430 cmd3 = "ping -c 1 209.85.135.103"
431 self.PingConsole = Console()
432 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
433 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
434 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
436 def checkNetworkStateFinished(self, result, retval,extra_args):
437 (statecallback) = extra_args
438 if self.PingConsole is not None:
440 self.PingConsole = None
441 statecallback(self.NetworkState)
443 self.NetworkState += 1
444 if len(self.PingConsole.appContainers) == 0:
445 statecallback(self.NetworkState)
447 def restartNetwork(self,callback = None):
448 if self.onRemoteRootFS():
449 if callback is not None:
452 self.restartConsole = Console()
453 self.config_ready = False
456 self.commands.append("/etc/init.d/avahi-daemon stop")
457 for iface in self.ifaces.keys():
458 cmd = "ip addr flush " + iface
459 self.commands.append(cmd)
460 self.commands.append("/etc/init.d/networking stop")
461 self.commands.append("killall -9 udhcpc")
462 self.commands.append("rm /var/run/udhcpc*")
463 self.commands.append("/etc/init.d/networking start")
464 self.commands.append("/etc/init.d/avahi-daemon start")
465 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
467 def restartNetworkFinished(self,extra_args):
468 ( callback ) = extra_args
469 if callback is not None:
472 def getLinkState(self,iface,callback):
473 cmd = self.ethtool_bin + " " + iface
474 self.LinkConsole = Console()
475 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
477 def getLinkStateFinished(self, result, retval,extra_args):
478 (callback) = extra_args
480 if self.LinkConsole is not None:
481 if len(self.LinkConsole.appContainers) == 0:
484 def stopPingConsole(self):
485 if self.PingConsole is not None:
486 if len(self.PingConsole.appContainers):
487 for name in self.PingConsole.appContainers.keys():
488 self.PingConsole.kill(name)
490 def stopLinkStateConsole(self):
491 if self.LinkConsole is not None:
492 if len(self.LinkConsole.appContainers):
493 for name in self.LinkConsole.appContainers.keys():
494 self.LinkConsole.kill(name)
496 def stopDNSConsole(self):
497 if self.DnsConsole is not None:
498 if len(self.DnsConsole.appContainers):
499 for name in self.DnsConsole.appContainers.keys():
500 self.DnsConsole.kill(name)
502 def stopRestartConsole(self):
503 if self.restartConsole is not None:
504 if len(self.restartConsole.appContainers):
505 for name in self.restartConsole.appContainers.keys():
506 self.restartConsole.kill(name)
508 def stopGetInterfacesConsole(self):
509 if self.Console is not None:
510 if len(self.Console.appContainers):
511 for name in self.Console.appContainers.keys():
512 self.Console.kill(name)
514 def stopDeactivateInterfaceConsole(self):
515 if self.deactivateInterfaceConsole is not None:
516 if len(self.deactivateInterfaceConsole.appContainers):
517 for name in self.deactivateInterfaceConsole.appContainers.keys():
518 self.deactivateInterfaceConsole.kill(name)
520 def checkforInterface(self,iface):
521 if self.getAdapterAttribute(iface, 'up') is True:
524 ret=system("ifconfig " + iface + " up")
525 system("ifconfig " + iface + " down")
531 def checkDNSLookup(self,statecallback):
532 cmd1 = "nslookup www.dream-multimedia-tv.de"
533 cmd2 = "nslookup www.heise.de"
534 cmd3 = "nslookup www.google.de"
535 self.DnsConsole = Console()
536 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
537 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
538 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
540 def checkDNSLookupFinished(self, result, retval,extra_args):
541 (statecallback) = extra_args
542 if self.DnsConsole is not None:
544 self.DnsConsole = None
545 statecallback(self.DnsState)
548 if len(self.DnsConsole.appContainers) == 0:
549 statecallback(self.DnsState)
551 def deactivateInterface(self,iface,callback = None):
552 if self.onRemoteRootFS():
553 if callback is not None:
556 self.deactivateInterfaceConsole = Console()
558 cmd1 = "ip addr flush " + iface
559 cmd2 = "ifconfig " + iface + " down"
560 self.commands.append(cmd1)
561 self.commands.append(cmd2)
562 self.deactivateInterfaceConsole.eBatch(self.commands, self.deactivateInterfaceFinished, callback, debug=True)
564 def deactivateInterfaceFinished(self,extra_args):
565 callback = extra_args
566 if self.deactivateInterfaceConsole:
567 if len(self.deactivateInterfaceConsole.appContainers) == 0:
568 if callback is not None:
571 def detectWlanModule(self):
572 self.wlanmodule = None
573 rt73_dir = "/sys/bus/usb/drivers/rt73/"
574 zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
575 madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
576 if os_path.exists(madwifi_dir):
577 files = listdir(madwifi_dir)
579 self.wlanmodule = 'madwifi'
580 if os_path.exists(rt73_dir):
581 rtfiles = listdir(rt73_dir)
582 if len(rtfiles) == 2:
583 self.wlanmodule = 'ralink'
584 if os_path.exists(zd1211b_dir):
585 zdfiles = listdir(zd1211b_dir)
586 if len(zdfiles) == 1:
587 self.wlanmodule = 'zydas'
588 return self.wlanmodule
590 def calc_netmask(self,nmask):
591 from struct import pack, unpack
592 from socket import inet_ntoa, inet_aton
595 cidr_range = range(0, 32)
597 if cidr not in cidr_range:
598 print 'cidr invalid: %d' % cidr
601 nm = ((1L<<cidr)-1)<<(32-cidr)
602 netmask = str(inet_ntoa(pack('>L', nm)))
605 def msgPlugins(self):
606 if self.config_ready is not None:
607 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
608 p(reason=self.config_ready)