switch network to use new epopen implementation instead of system call
[enigma2.git] / lib / python / Components / Network.py
1 from os import system, popen, path as os_path, listdir
2 from re import compile as re_compile
3 from socket import *
4 from enigma import eConsoleAppContainer
5 from Components.Console import Console
6
7 class Network:
8         def __init__(self):
9                 self.ifaces = {}
10                 self.configuredInterfaces = []          
11                 self.nameservers = []
12                 self.ethtool_bin = "/usr/sbin/ethtool"
13                 self.container = eConsoleAppContainer()
14                 self.Console = Console()
15                 self.getInterfaces()
16
17         def getInterfaces(self):
18                 devicesPattern = re_compile('[a-z]+[0-9]+')
19                 self.configuredInterfaces = []
20                 fp = file('/proc/net/dev', 'r')
21                 result = fp.readlines()
22                 fp.close()
23                 for line in result:
24                         try:
25                                 device = devicesPattern.search(line).group()
26                                 if device == 'wifi0':
27                                         continue
28                                 self.getDataForInterface(device)
29                                 # Show only UP Interfaces in E2
30                                 #if self.getAdapterAttribute(device, 'up') is False:
31                                 #       del self.ifaces[device]
32                         except AttributeError:
33                                 pass
34
35                 #print "self.ifaces:", self.ifaces
36                 #self.writeNetworkConfig()
37                 #print ord(' ')
38                 #for line in result:
39                 #       print ord(line[0])
40
41         # helper function
42         def regExpMatch(self, pattern, string):
43                 if string is None:
44                         return None
45                 try:
46                         return pattern.search(string).group()
47                 except AttributeError:
48                         None
49
50         # helper function to convert ips from a sring to a list of ints
51         def convertIP(self, ip):
52                 strIP = ip.split('.')
53                 ip = []
54                 for x in strIP:
55                         ip.append(int(x))
56                 return ip
57
58         def getDataForInterface(self, iface):
59                 cmd = "ifconfig " + iface
60                 self.Console.ePopen(cmd, self.ifconfigFinished, iface)
61                 
62         def ifconfigFinished(self, result, retval, iface):
63                 data = { 'up': False, 'dhcp': False, 'preup' : False, 'postdown' : False }
64                 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
65                 ipLinePattern = re_compile('inet addr:' + ipRegexp)
66                 netmaskLinePattern = re_compile('Mask:' + ipRegexp)
67                 bcastLinePattern = re_compile('Bcast:' + ipRegexp)
68                 ipPattern = re_compile(ipRegexp)
69                 upPattern = re_compile('UP ')
70                 macPattern = re_compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}')
71                 
72                 for line in result.splitlines():
73                         ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, line))
74                         netmask = self.regExpMatch(ipPattern, self.regExpMatch(netmaskLinePattern, line))
75                         bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, line))
76                         up = self.regExpMatch(upPattern, line)
77                         mac = self.regExpMatch(macPattern, line)
78                         if ip is not None:
79                                 data['ip'] = self.convertIP(ip)
80                         if netmask is not None:
81                                 data['netmask'] = self.convertIP(netmask)
82                         if bcast is not None:
83                                 data['bcast'] = self.convertIP(bcast)
84                         if up is not None:
85                                 data['up'] = True
86                                 if iface is not 'lo':
87                                         self.configuredInterfaces.append(iface)
88                         if mac is not None:
89                                 data['mac'] = mac
90                 if not data.has_key('ip'):
91                         data['dhcp'] = True
92                         data['ip'] = [0, 0, 0, 0]
93                         data['netmask'] = [0, 0, 0, 0]
94                         data['gateway'] = [0, 0, 0, 0]
95                         
96                 cmd = "route -n | grep  " + iface
97                 self.Console.ePopen(cmd,self.routeFinished,[iface,data,ipPattern])
98
99         def routeFinished(self, result, retval, extra_args):
100                 (iface, data, ipPattern) = extra_args
101                 
102                 for line in result.splitlines():
103                         print line[0:7]
104                         if line[0:7] == "0.0.0.0":
105                                 gateway = self.regExpMatch(ipPattern, line[16:31])
106                                 if gateway is not None:
107                                         data['gateway'] = self.convertIP(gateway)
108                 self.ifaces[iface] = data
109                 if len(self.Console.appContainers) == 0:
110                         self.loadNetworkConfig()
111
112         def writeNetworkConfig(self):
113                 self.configuredInterfaces = []
114                 fp = file('/etc/network/interfaces', 'w')
115                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
116                 fp.write("auto lo\n")
117                 fp.write("iface lo inet loopback\n\n")
118                 for ifacename, iface in self.ifaces.items():
119                         if iface['up'] == True:
120                                 fp.write("auto " + ifacename + "\n")
121                                 self.configuredInterfaces.append(ifacename)
122                         if iface['dhcp'] == True:
123                                 fp.write("iface "+ ifacename +" inet dhcp\n")
124                         if iface['dhcp'] == False:
125                                 fp.write("iface "+ ifacename +" inet static\n")
126                                 if iface.has_key('ip'):
127                                         print tuple(iface['ip'])
128                                         fp.write("      address %d.%d.%d.%d\n" % tuple(iface['ip']))
129                                         fp.write("      netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
130                                         if iface.has_key('gateway'):
131                                                 fp.write("      gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
132                         if iface.has_key("configStrings"):
133                                 fp.write("\n" + iface["configStrings"] + "\n")
134                         if iface["preup"] is not False and not iface.has_key("configStrings"):
135                                 fp.write(iface["preup"])
136                                 fp.write(iface["postdown"])
137                         fp.write("\n")                          
138                 fp.close()
139                 self.writeNameserverConfig()
140
141         def writeNameserverConfig(self):
142                 fp = file('/etc/resolv.conf', 'w')
143                 for nameserver in self.nameservers:
144                         fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
145                 fp.close()
146
147         def loadNetworkConfig(self):
148                 self.loadNameserverConfig()
149                 interfaces = []
150                 # parse the interfaces-file
151                 try:
152                         fp = file('/etc/network/interfaces', 'r')
153                         interfaces = fp.readlines()
154                         fp.close()
155                 except:
156                         print "[Network.py] interfaces - opening failed"
157
158                 ifaces = {}
159                 currif = ""
160                 for i in interfaces:
161                         split = i.strip().split(' ')
162                         if (split[0] == "iface"):
163                                 currif = split[1]
164                                 ifaces[currif] = {}
165                                 if (len(split) == 4 and split[3] == "dhcp"):
166                                         ifaces[currif]["dhcp"] = True
167                                 else:
168                                         ifaces[currif]["dhcp"] = False
169                         if (currif != ""):
170                                 if (split[0] == "address"):
171                                         ifaces[currif]["address"] = map(int, split[1].split('.'))
172                                         if self.ifaces[currif].has_key("ip"):
173                                                 if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
174                                                         self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
175                                 if (split[0] == "netmask"):
176                                         ifaces[currif]["netmask"] = map(int, split[1].split('.'))
177                                         if self.ifaces[currif].has_key("netmask"):
178                                                 if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
179                                                         self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
180                                 if (split[0] == "gateway"):
181                                         ifaces[currif]["gateway"] = map(int, split[1].split('.'))
182                                         if self.ifaces[currif].has_key("gateway"):
183                                                 if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
184                                                         self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))                                  
185                                 if (split[0] == "pre-up"):
186                                         if self.ifaces[currif].has_key("preup"):
187                                                 self.ifaces[currif]["preup"] = i
188                                 if (split[0] == "post-down"):
189                                         if self.ifaces[currif].has_key("postdown"):
190                                                 self.ifaces[currif]["postdown"] = i
191
192                 print "read interfaces:", ifaces
193                 for ifacename, iface in ifaces.items():
194                         if self.ifaces.has_key(ifacename):
195                                 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
196                 print "self.ifaces after loading:", self.ifaces
197
198         def loadNameserverConfig(self):
199                 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
200                 nameserverPattern = re_compile("nameserver +" + ipRegexp)
201                 ipPattern = re_compile(ipRegexp)
202
203                 resolv = []
204                 try:
205                         fp = file('/etc/resolv.conf', 'r')
206                         resolv = fp.readlines()
207                         fp.close()
208                         self.nameservers = []
209                 except:
210                         print "[Network.py] resolv.conf - opening failed"
211
212                 for line in resolv:
213                         if self.regExpMatch(nameserverPattern, line) is not None:
214                                 ip = self.regExpMatch(ipPattern, line)
215                                 if ip is not None:
216                                         self.nameservers.append(self.convertIP(ip))
217
218                 print "nameservers:", self.nameservers
219
220         def deactivateNetworkConfig(self):
221                 for iface in self.ifaces.keys():
222                         system("ip addr flush " + iface)
223                 system("/etc/init.d/networking stop")
224                 system("killall -9 udhcpc")
225                 system("rm /var/run/udhcpc*")
226
227         def activateNetworkConfig(self):
228                 system("/etc/init.d/networking start")
229                 self.getInterfaces()
230
231         def getNumberOfAdapters(self):
232                 return len(self.ifaces)
233
234         def getFriendlyAdapterName(self, x):
235                 # maybe this needs to be replaced by an external list.
236                 friendlyNames = {
237                         "eth0": _("Integrated Ethernet"),
238                         "wlan0": _("Wireless"),
239                         "ath0": _("Integrated Wireless")
240                 }
241                 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
242
243         def getAdapterName(self, iface):
244                 return iface
245
246         def getAdapterList(self):
247                 return self.ifaces.keys()
248
249         def getAdapterAttribute(self, iface, attribute):
250                 if self.ifaces.has_key(iface):
251                         if self.ifaces[iface].has_key(attribute):
252                                 return self.ifaces[iface][attribute]
253                 return None
254
255         def setAdapterAttribute(self, iface, attribute, value):
256                 print "setting for adapter", iface, "attribute", attribute, " to value", value
257                 if self.ifaces.has_key(iface):
258                         self.ifaces[iface][attribute] = value
259
260         def removeAdapterAttribute(self, iface, attribute):
261                 if self.ifaces.has_key(iface):
262                         if self.ifaces[iface].has_key(attribute):
263                                 del self.ifaces[iface][attribute]
264
265         def getNameserverList(self):
266                 if len(self.nameservers) == 0:
267                         return [[0, 0, 0, 0], [0, 0, 0, 0]]
268                 else: 
269                         return self.nameservers
270
271         def clearNameservers(self):
272                 self.nameservers = []
273
274         def addNameserver(self, nameserver):
275                 if nameserver not in self.nameservers:
276                         self.nameservers.append(nameserver)
277
278         def removeNameserver(self, nameserver):
279                 if nameserver in self.nameservers:
280                         self.nameservers.remove(nameserver)
281
282         def changeNameserver(self, oldnameserver, newnameserver):
283                 if oldnameserver in self.nameservers:
284                         for i in range(len(self.nameservers)):
285                                 if self.nameservers[i] == oldnameserver:
286                                         self.nameservers[i] = newnameserver
287
288         def writeDefaultNetworkConfig(self,mode='lan'):
289                 fp = file('/etc/network/interfaces', 'w')
290                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
291                 fp.write("auto lo\n")
292                 fp.write("iface lo inet loopback\n\n")
293                 if mode == 'wlan':
294                         fp.write("auto wlan0\n")
295                         fp.write("iface wlan0 inet dhcp\n")
296                 if mode == 'wlan-mpci':
297                         fp.write("auto ath0\n")
298                         fp.write("iface ath0 inet dhcp\n")
299                 if mode == 'lan':
300                         fp.write("auto eth0\n")
301                         fp.write("iface eth0 inet dhcp\n")
302                 fp.write("\n")
303                 fp.close()
304
305         def resetNetworkConfig(self,mode='lan'):
306                 self.deactivateNetworkConfig()
307                 self.writeDefaultNetworkConfig(mode)
308                 if mode == 'wlan':
309                         system("ifconfig eth0 down")
310                         system("ifconfig ath0 down")
311                         system("ifconfig wlan0 up")
312                 if mode == 'wlan-mpci':
313                         system("ifconfig eth0 down")
314                         system("ifconfig wlan0 down")
315                         system("ifconfig ath0 up")              
316                 if mode == 'lan':                       
317                         system("ifconfig eth0 up")
318                         system("ifconfig wlan0 down")
319                         system("ifconfig ath0 down")
320                 self.getInterfaces()    
321
322         def checkNetworkState(self):
323                  # www.dream-multimedia-tv.de, www.heise.de, www.google.de
324                 return system("ping -c 1 82.149.226.170") == 0 or \
325                         system("ping -c 1 193.99.144.85") == 0 or \
326                         system("ping -c 1 209.85.135.103") == 0
327
328         def restartNetwork(self):
329                 iNetwork.deactivateNetworkConfig()
330                 iNetwork.activateNetworkConfig()
331
332         def getLinkState(self,iface,callback):
333                 self.dataAvail = callback
334                 cmd = self.ethtool_bin + " " + iface
335                 self.container.appClosed.get().append(self.cmdFinished)
336                 self.container.dataAvail.get().append(callback)
337                 self.container.execute(cmd)
338
339         def cmdFinished(self,retval):
340                 self.container.appClosed.get().remove(self.cmdFinished)
341                 self.container.dataAvail.get().remove(self.dataAvail)
342
343         def stopContainer(self):
344                 self.container.kill()
345                 
346         def ContainerRunning(self):
347                 return self.container.running()
348
349         def checkforInterface(self,iface):
350                 if self.getAdapterAttribute(iface, 'up') is True:
351                         return True
352                 else:
353                         ret=system("ifconfig " + iface + " up")
354                         system("ifconfig " + iface + " down")
355                         if ret == 0:
356                                 return True
357                         else:
358                                 return False
359
360         def checkDNSLookup(self):
361                 return system("nslookup www.dream-multimedia-tv.de") == 0 or \
362                         system("nslookup www.heise.de") == 0 or \
363                         system("nslookup www.google.de")
364
365         def deactivateInterface(self,iface):
366                 system("ifconfig " + iface + " down")
367
368         def detectWlanModule(self):
369                 self.wlanmodule = None
370                 rt73_dir = "/sys/bus/usb/drivers/rt73/"
371                 zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
372                 madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
373                 if os_path.exists(madwifi_dir):
374                         files = listdir(madwifi_dir)
375                         if len(files) >= 1:
376                                 self.wlanmodule = 'madwifi'
377                 if os_path.exists(rt73_dir):
378                         rtfiles = listdir(rt73_dir)
379                         if len(rtfiles) == 2:
380                                 self.wlanmodule = 'ralink'
381                 if os_path.exists(zd1211b_dir):
382                         zdfiles = listdir(zd1211b_dir)
383                         if len(zdfiles) == 1:
384                                 self.wlanmodule = 'zydas'
385                 return self.wlanmodule
386         
387         
388 iNetwork = Network()
389
390 def InitNetwork():
391         pass