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