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
10 self.configuredInterfaces = []
11 self.configuredNetworkAdapters = []
15 self.ethtool_bin = "/usr/sbin/ethtool"
16 self.container = eConsoleAppContainer()
17 self.Console = Console()
18 self.LinkConsole = Console()
19 self.restartConsole = Console()
20 self.deactivateConsole = Console()
21 self.deactivateInterfaceConsole = Console()
22 self.activateConsole = Console()
23 self.resetNetworkConsole = Console()
24 self.DnsConsole = Console()
27 def getInterfaces(self, callback = None):
28 devicesPattern = re_compile('[a-z]+[0-9]+')
29 self.configuredInterfaces = []
30 fp = file('/proc/net/dev', 'r')
31 result = fp.readlines()
35 device = devicesPattern.search(line).group()
38 self.getDataForInterface(device, callback)
39 except AttributeError:
41 #print "self.ifaces:", self.ifaces
42 #self.writeNetworkConfig()
48 def regExpMatch(self, pattern, string):
52 return pattern.search(string).group()
53 except AttributeError:
56 # helper function to convert ips from a sring to a list of ints
57 def convertIP(self, ip):
64 def getDataForInterface(self, iface,callback):
65 #get ip out of ip addr, as avahi sometimes overrides it in ifconfig.
67 self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])
69 def IPaddrFinished(self, result, retval, extra_args):
70 (iface, callback ) = extra_args
71 data = { 'up': False, 'dhcp': False, 'preup' : False, 'postdown' : False }
72 globalIPpattern = re_compile("scope global")
73 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
74 netRegexp = '[0-9]{1,2}'
75 macRegexp = '[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}'
76 ipLinePattern = re_compile('inet ' + ipRegexp + '/')
77 ipPattern = re_compile(ipRegexp)
78 netmaskLinePattern = re_compile('/' + netRegexp)
79 netmaskPattern = re_compile(netRegexp)
80 bcastLinePattern = re_compile(' brd ' + ipRegexp)
81 upPattern = re_compile('UP')
82 macPattern = re_compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}\:[a-z0-9]{2}')
83 macLinePattern = re_compile('link/ether ' + macRegexp)
85 for line in result.splitlines():
86 split = line.strip().split(' ',2)
87 if (split[1][:-1] == iface):
88 up = self.regExpMatch(upPattern, split[2])
89 mac = self.regExpMatch(macPattern, self.regExpMatch(macLinePattern, split[2]))
93 self.configuredInterfaces.append(iface)
96 if (split[1] == iface):
97 if re_search(globalIPpattern, split[2]):
98 ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
99 netmask = self.calc_netmask(self.regExpMatch(netmaskPattern, self.regExpMatch(netmaskLinePattern, split[2])))
100 bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, split[2]))
102 data['ip'] = self.convertIP(ip)
103 if netmask is not None:
104 data['netmask'] = self.convertIP(netmask)
105 if bcast is not None:
106 data['bcast'] = self.convertIP(bcast)
108 if not data.has_key('ip'):
110 data['ip'] = [0, 0, 0, 0]
111 data['netmask'] = [0, 0, 0, 0]
112 data['gateway'] = [0, 0, 0, 0]
114 cmd = "route -n | grep " + iface
115 self.Console.ePopen(cmd,self.routeFinished, [iface, data, callback])
117 def routeFinished(self, result, retval, extra_args):
118 (iface, data, callback) = extra_args
119 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
120 ipPattern = re_compile(ipRegexp)
121 ipLinePattern = re_compile(ipRegexp)
123 for line in result.splitlines():
125 if line[0:7] == "0.0.0.0":
126 gateway = self.regExpMatch(ipPattern, line[16:31])
127 if gateway is not None:
128 data['gateway'] = self.convertIP(gateway)
130 self.ifaces[iface] = data
131 self.loadNetworkConfig(iface,callback)
133 def writeNetworkConfig(self):
134 self.configuredInterfaces = []
135 fp = file('/etc/network/interfaces', 'w')
136 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
137 fp.write("auto lo\n")
138 fp.write("iface lo inet loopback\n\n")
139 for ifacename, iface in self.ifaces.items():
140 if iface['up'] == True:
141 fp.write("auto " + ifacename + "\n")
142 self.configuredInterfaces.append(ifacename)
143 if iface['dhcp'] == True:
144 fp.write("iface "+ ifacename +" inet dhcp\n")
145 if iface['dhcp'] == False:
146 fp.write("iface "+ ifacename +" inet static\n")
147 if iface.has_key('ip'):
148 print tuple(iface['ip'])
149 fp.write(" address %d.%d.%d.%d\n" % tuple(iface['ip']))
150 fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
151 if iface.has_key('gateway'):
152 fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
153 if iface.has_key("configStrings"):
154 fp.write("\n" + iface["configStrings"] + "\n")
155 if iface["preup"] is not False and not iface.has_key("configStrings"):
156 fp.write(iface["preup"])
157 fp.write(iface["postdown"])
160 self.writeNameserverConfig()
162 def writeNameserverConfig(self):
163 fp = file('/etc/resolv.conf', 'w')
164 for nameserver in self.nameservers:
165 fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
168 def loadNetworkConfig(self,iface,callback = None):
170 # parse the interfaces-file
172 fp = file('/etc/network/interfaces', 'r')
173 interfaces = fp.readlines()
176 print "[Network.py] interfaces - opening failed"
181 split = i.strip().split(' ')
182 if (split[0] == "iface"):
185 if (len(split) == 4 and split[3] == "dhcp"):
186 ifaces[currif]["dhcp"] = True
188 ifaces[currif]["dhcp"] = False
189 if (currif == iface): #read information only for available interfaces
190 if (split[0] == "address"):
191 ifaces[currif]["address"] = map(int, split[1].split('.'))
192 if self.ifaces[currif].has_key("ip"):
193 if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
194 self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
195 if (split[0] == "netmask"):
196 ifaces[currif]["netmask"] = map(int, split[1].split('.'))
197 if self.ifaces[currif].has_key("netmask"):
198 if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
199 self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
200 if (split[0] == "gateway"):
201 ifaces[currif]["gateway"] = map(int, split[1].split('.'))
202 if self.ifaces[currif].has_key("gateway"):
203 if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
204 self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))
205 if (split[0] == "pre-up"):
206 if self.ifaces[currif].has_key("preup"):
207 self.ifaces[currif]["preup"] = i
208 if (split[0] == "post-down"):
209 if self.ifaces[currif].has_key("postdown"):
210 self.ifaces[currif]["postdown"] = i
212 for ifacename, iface in ifaces.items():
213 if self.ifaces.has_key(ifacename):
214 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
215 if len(self.Console.appContainers) == 0:
216 # save configured interfacelist
217 self.configuredNetworkAdapters = self.configuredInterfaces
219 self.loadNameserverConfig()
220 print "read configured interfac:", ifaces
221 print "self.ifaces after loading:", self.ifaces
222 if callback is not None:
225 def loadNameserverConfig(self):
226 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
227 nameserverPattern = re_compile("nameserver +" + ipRegexp)
228 ipPattern = re_compile(ipRegexp)
232 fp = file('/etc/resolv.conf', 'r')
233 resolv = fp.readlines()
235 self.nameservers = []
237 print "[Network.py] resolv.conf - opening failed"
240 if self.regExpMatch(nameserverPattern, line) is not None:
241 ip = self.regExpMatch(ipPattern, line)
243 self.nameservers.append(self.convertIP(ip))
245 print "nameservers:", self.nameservers
247 def deactivateNetworkConfig(self, callback = None):
248 self.deactivateConsole = Console()
250 self.commands.append("/etc/init.d/avahi-daemon stop")
251 for iface in self.ifaces.keys():
252 cmd = "ip addr flush " + iface
253 self.commands.append(cmd)
254 self.commands.append("/etc/init.d/networking stop")
255 self.commands.append("killall -9 udhcpc")
256 self.commands.append("rm /var/run/udhcpc*")
257 self.deactivateConsole.eBatch(self.commands, self.deactivateNetworkFinished, callback, debug=True)
259 def deactivateNetworkFinished(self,extra_args):
260 callback = extra_args
261 if len(self.deactivateConsole.appContainers) == 0:
262 if callback is not None:
265 def activateNetworkConfig(self, callback = None):
266 self.activateConsole = Console()
268 self.commands.append("/etc/init.d/networking start")
269 self.commands.append("/etc/init.d/avahi-daemon start")
270 self.activateConsole.eBatch(self.commands, self.activateNetworkFinished, callback, debug=True)
272 def activateNetworkFinished(self,extra_args):
273 callback = extra_args
274 if len(self.activateConsole.appContainers) == 0:
275 if callback is not None:
278 def getConfiguredAdapters(self):
279 return self.configuredNetworkAdapters
281 def getNumberOfAdapters(self):
282 return len(self.ifaces)
284 def getFriendlyAdapterName(self, x):
285 # maybe this needs to be replaced by an external list.
287 "eth0": _("Integrated Ethernet"),
288 "wlan0": _("Wireless"),
289 "ath0": _("Integrated Wireless")
291 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
293 def getAdapterName(self, iface):
296 def getAdapterList(self):
297 return self.ifaces.keys()
299 def getAdapterAttribute(self, iface, attribute):
300 if self.ifaces.has_key(iface):
301 if self.ifaces[iface].has_key(attribute):
302 return self.ifaces[iface][attribute]
305 def setAdapterAttribute(self, iface, attribute, value):
306 print "setting for adapter", iface, "attribute", attribute, " to value", value
307 if self.ifaces.has_key(iface):
308 self.ifaces[iface][attribute] = value
310 def removeAdapterAttribute(self, iface, attribute):
311 if self.ifaces.has_key(iface):
312 if self.ifaces[iface].has_key(attribute):
313 del self.ifaces[iface][attribute]
315 def getNameserverList(self):
316 if len(self.nameservers) == 0:
317 return [[0, 0, 0, 0], [0, 0, 0, 0]]
319 return self.nameservers
321 def clearNameservers(self):
322 self.nameservers = []
324 def addNameserver(self, nameserver):
325 if nameserver not in self.nameservers:
326 self.nameservers.append(nameserver)
328 def removeNameserver(self, nameserver):
329 if nameserver in self.nameservers:
330 self.nameservers.remove(nameserver)
332 def changeNameserver(self, oldnameserver, newnameserver):
333 if oldnameserver in self.nameservers:
334 for i in range(len(self.nameservers)):
335 if self.nameservers[i] == oldnameserver:
336 self.nameservers[i] = newnameserver
338 def resetNetworkConfig(self, mode='lan', callback = None):
339 self.resetNetworkConsole = Console()
341 self.commands.append("/etc/init.d/avahi-daemon stop")
342 for iface in self.ifaces.keys():
343 cmd = "ip addr flush " + iface
344 self.commands.append(cmd)
345 self.commands.append("/etc/init.d/networking stop")
346 self.commands.append("killall -9 udhcpc")
347 self.commands.append("rm /var/run/udhcpc*")
348 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinishedCB, [mode, callback], debug=True)
350 def resetNetworkFinishedCB(self, extra_args):
351 (mode, callback) = extra_args
352 if len(self.resetNetworkConsole.appContainers) == 0:
353 self.writeDefaultNetworkConfig(mode, callback)
355 def writeDefaultNetworkConfig(self,mode='lan', callback = None):
356 fp = file('/etc/network/interfaces', 'w')
357 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
358 fp.write("auto lo\n")
359 fp.write("iface lo inet loopback\n\n")
361 fp.write("auto wlan0\n")
362 fp.write("iface wlan0 inet dhcp\n")
363 if mode == 'wlan-mpci':
364 fp.write("auto ath0\n")
365 fp.write("iface ath0 inet dhcp\n")
367 fp.write("auto eth0\n")
368 fp.write("iface eth0 inet dhcp\n")
372 self.resetNetworkConsole = Console()
375 self.commands.append("ifconfig eth0 down")
376 self.commands.append("ifconfig ath0 down")
377 self.commands.append("ifconfig wlan0 up")
378 if mode == 'wlan-mpci':
379 self.commands.append("ifconfig eth0 down")
380 self.commands.append("ifconfig wlan0 down")
381 self.commands.append("ifconfig ath0 up")
383 self.commands.append("ifconfig eth0 up")
384 self.commands.append("ifconfig wlan0 down")
385 self.commands.append("ifconfig ath0 down")
386 self.commands.append("/etc/init.d/avahi-daemon start")
387 self.resetNetworkConsole.eBatch(self.commands, self.resetNetworkFinished, [mode,callback], debug=True)
389 def resetNetworkFinished(self,extra_args):
390 (mode, callback) = extra_args
391 if len(self.resetNetworkConsole.appContainers) == 0:
392 if callback is not None:
395 def checkNetworkState(self,statecallback):
396 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
397 cmd1 = "ping -c 1 82.149.226.170"
398 cmd2 = "ping -c 1 193.99.144.85"
399 cmd3 = "ping -c 1 209.85.135.103"
400 self.PingConsole = Console()
401 self.PingConsole.ePopen(cmd1, self.checkNetworkStateFinished,statecallback)
402 self.PingConsole.ePopen(cmd2, self.checkNetworkStateFinished,statecallback)
403 self.PingConsole.ePopen(cmd3, self.checkNetworkStateFinished,statecallback)
405 def checkNetworkStateFinished(self, result, retval,extra_args):
406 (statecallback) = extra_args
407 if self.PingConsole is not None:
409 self.PingConsole = None
410 statecallback(self.NetworkState)
412 self.NetworkState += 1
413 if len(self.PingConsole.appContainers) == 0:
414 statecallback(self.NetworkState)
416 def restartNetwork(self,callback = None):
417 self.restartConsole = Console()
419 self.commands.append("/etc/init.d/avahi-daemon stop")
420 for iface in self.ifaces.keys():
421 cmd = "ip addr flush " + iface
422 self.commands.append(cmd)
423 self.commands.append("/etc/init.d/networking stop")
424 self.commands.append("killall -9 udhcpc")
425 self.commands.append("rm /var/run/udhcpc*")
426 self.commands.append("/etc/init.d/networking start")
427 self.commands.append("/etc/init.d/avahi-daemon start")
428 self.restartConsole.eBatch(self.commands, self.restartNetworkFinished, callback, debug=True)
430 def restartNetworkFinished(self,extra_args):
431 ( callback ) = extra_args
432 if callback is not None:
435 def getLinkState(self,iface,callback):
436 cmd = self.ethtool_bin + " " + iface
437 self.LinkConsole = Console()
438 self.LinkConsole.ePopen(cmd, self.getLinkStateFinished,callback)
440 def getLinkStateFinished(self, result, retval,extra_args):
441 (callback) = extra_args
442 if self.LinkConsole is not None:
443 if len(self.LinkConsole.appContainers) == 0:
446 def stopLinkStateConsole(self):
447 if self.LinkConsole is not None:
448 self.LinkConsole = None
450 def stopDNSConsole(self):
451 if self.DnsConsole is not None:
452 self.DnsConsole = None
454 def stopRestartConsole(self):
455 if self.restartConsole is not None:
456 self.restartConsole = None
458 def stopGetInterfacesConsole(self):
459 if self.Console is not None:
462 def stopDeactivateInterfaceConsole(self):
463 if self.deactivateInterfaceConsole:
464 self.deactivateInterfaceConsole = None
466 def checkforInterface(self,iface):
467 if self.getAdapterAttribute(iface, 'up') is True:
470 ret=system("ifconfig " + iface + " up")
471 system("ifconfig " + iface + " down")
477 def checkDNSLookup(self,statecallback):
478 cmd1 = "nslookup www.dream-multimedia-tv.de"
479 cmd2 = "nslookup www.heise.de"
480 cmd3 = "nslookup www.google.de"
481 self.DnsConsole = Console()
482 self.DnsConsole.ePopen(cmd1, self.checkDNSLookupFinished,statecallback)
483 self.DnsConsole.ePopen(cmd2, self.checkDNSLookupFinished,statecallback)
484 self.DnsConsole.ePopen(cmd3, self.checkDNSLookupFinished,statecallback)
486 def checkDNSLookupFinished(self, result, retval,extra_args):
487 (statecallback) = extra_args
488 if self.DnsConsole is not None:
490 self.DnsConsole = None
491 statecallback(self.DnsState)
494 if len(self.DnsConsole.appContainers) == 0:
495 statecallback(self.DnsState)
497 def deactivateInterface(self,iface,callback = None):
498 self.deactivateInterfaceConsole = Console()
500 cmd1 = "ip addr flush " + iface
501 cmd2 = "ifconfig " + iface + " down"
502 self.commands.append(cmd1)
503 self.commands.append(cmd2)
504 self.deactivateInterfaceConsole.eBatch(self.commands, self.deactivateInterfaceFinished, callback, debug=True)
506 def deactivateInterfaceFinished(self,extra_args):
507 callback = extra_args
508 if self.deactivateInterfaceConsole:
509 if len(self.deactivateInterfaceConsole.appContainers) == 0:
510 if callback is not None:
513 def detectWlanModule(self):
514 self.wlanmodule = None
515 rt73_dir = "/sys/bus/usb/drivers/rt73/"
516 zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
517 madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
518 if os_path.exists(madwifi_dir):
519 files = listdir(madwifi_dir)
521 self.wlanmodule = 'madwifi'
522 if os_path.exists(rt73_dir):
523 rtfiles = listdir(rt73_dir)
524 if len(rtfiles) == 2:
525 self.wlanmodule = 'ralink'
526 if os_path.exists(zd1211b_dir):
527 zdfiles = listdir(zd1211b_dir)
528 if len(zdfiles) == 1:
529 self.wlanmodule = 'zydas'
530 return self.wlanmodule
532 def calc_netmask(self,nmask):
533 from struct import pack, unpack
534 from socket import inet_ntoa, inet_aton
537 cidr_range = range(0, 32)
539 if cidr not in cidr_range:
540 print 'cidr invalid: %d' % cidr
543 nm = ((1L<<cidr)-1)<<(32-cidr)
544 netmask = str(inet_ntoa(pack('>L', nm)))