Networksetup update
[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'] = [192, 168, 1, 2]
92                         data['netmask'] = [255, 255, 255, 0]
93                         data['gateway'] = [192, 168, 1, 1]
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                                         self.ifaces[currif]["preup"] = i
181                                 if (split[0] == "post-down"):
182                                         self.ifaces[currif]["postdown"] = i
183
184                 print "read interfaces:", ifaces
185                 for ifacename, iface in ifaces.items():
186                         if self.ifaces.has_key(ifacename):
187                                 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
188                 print "self.ifaces after loading:", self.ifaces
189
190         def loadNameserverConfig(self):
191                 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
192                 nameserverPattern = re_compile("nameserver +" + ipRegexp)
193                 ipPattern = re_compile(ipRegexp)
194
195                 resolv = []
196                 try:
197                         fp = file('/etc/resolv.conf', 'r')
198                         resolv = fp.readlines()
199                         fp.close()
200                         self.nameservers = []
201                 except:
202                         print "[Network.py] resolv.conf - opening failed"
203
204                 for line in resolv:
205                         if self.regExpMatch(nameserverPattern, line) is not None:
206                                 ip = self.regExpMatch(ipPattern, line)
207                                 if ip is not None:
208                                         self.nameservers.append(self.convertIP(ip))
209
210                 print "nameservers:", self.nameservers
211
212         def deactivateNetworkConfig(self):
213                 for iface in self.ifaces.keys():
214                         system("ip addr flush " + iface)
215                 system("/etc/init.d/networking stop")
216                 system("killall -9 udhcpc")
217                 system("rm /var/run/udhcpc*")
218
219         def activateNetworkConfig(self):
220                 system("/etc/init.d/networking start")
221                 self.getInterfaces()
222
223         def getNumberOfAdapters(self):
224                 return len(self.ifaces)
225
226         def getFriendlyAdapterName(self, x):
227                 # maybe this needs to be replaced by an external list.
228                 friendlyNames = {
229                         "eth0": _("Integrated Ethernet"),
230                         "wlan0": _("Wireless"),
231                         "ath0": _("Integrated Wireless")
232                 }
233                 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
234
235         def getAdapterName(self, iface):
236                 return iface
237
238         def getAdapterList(self):
239                 return self.ifaces.keys()
240
241         def getAdapterAttribute(self, iface, attribute):
242                 if self.ifaces.has_key(iface):
243                         if self.ifaces[iface].has_key(attribute):
244                                 return self.ifaces[iface][attribute]
245                 return None
246
247         def setAdapterAttribute(self, iface, attribute, value):
248                 print "setting for adapter", iface, "attribute", attribute, " to value", value
249                 if self.ifaces.has_key(iface):
250                         self.ifaces[iface][attribute] = value
251
252         def removeAdapterAttribute(self, iface, attribute):
253                 if self.ifaces.has_key(iface):
254                         if self.ifaces[iface].has_key(attribute):
255                                 del self.ifaces[iface][attribute]
256
257         def getNameserverList(self):
258                 if len(self.nameservers) == 0:
259                         return [[0, 0, 0, 0], [0, 0, 0, 0]]
260                 else: 
261                         return self.nameservers
262
263         def clearNameservers(self):
264                 self.nameservers = []
265
266         def addNameserver(self, nameserver):
267                 if nameserver not in self.nameservers:
268                         self.nameservers.append(nameserver)
269
270         def removeNameserver(self, nameserver):
271                 if nameserver in self.nameservers:
272                         self.nameservers.remove(nameserver)
273
274         def changeNameserver(self, oldnameserver, newnameserver):
275                 if oldnameserver in self.nameservers:
276                         for i in range(len(self.nameservers)):
277                                 if self.nameservers[i] == oldnameserver:
278                                         self.nameservers[i] = newnameserver
279
280         def writeDefaultNetworkConfig(self,mode='lan'):
281                 fp = file('/etc/network/interfaces', 'w')
282                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
283                 fp.write("auto lo\n")
284                 fp.write("iface lo inet loopback\n\n")
285                 if mode == 'wlan':
286                         fp.write("auto wlan0\n")
287                         fp.write("iface wlan0 inet dhcp\n")
288                 if mode == 'wlan-mpci':
289                         fp.write("auto ath0\n")
290                         fp.write("iface ath0 inet dhcp\n")
291                 if mode == 'lan':
292                         fp.write("auto eth0\n")
293                         fp.write("iface eth0 inet dhcp\n")
294                 fp.write("\n")
295                 fp.close()
296
297         def resetNetworkConfig(self,mode='lan'):
298                 self.deactivateNetworkConfig()
299                 self.writeDefaultNetworkConfig(mode)
300                 if mode == 'wlan':
301                         system("ifconfig eth0 down")
302                         system("ifconfig ath0 down")
303                         system("ifconfig wlan0 up")
304                 if mode == 'wlan-mpci':
305                         system("ifconfig eth0 down")
306                         system("ifconfig wlan0 down")
307                         system("ifconfig ath0 up")              
308                 if mode == 'lan':                       
309                         system("ifconfig eth0 up")
310                         system("ifconfig wlan0 down")
311                         system("ifconfig ath0 down")
312                 self.getInterfaces()    
313
314         def checkNetworkState(self):
315                  # www.dream-multimedia-tv.de, www.heise.de, www.google.de
316                 return system("ping -c 1 82.149.226.170") == 0 or \
317                         system("ping -c 1 193.99.144.85") == 0 or \
318                         system("ping -c 1 209.85.135.103") == 0
319
320         def restartNetwork(self):
321                 iNetwork.deactivateNetworkConfig()
322                 iNetwork.activateNetworkConfig()
323
324         def getLinkState(self,iface,callback):
325                 self.dataAvail = callback
326                 cmd = self.ethtool_bin + " " + iface
327                 self.container.appClosed.get().append(self.cmdFinished)
328                 self.container.dataAvail.get().append(callback)
329                 self.container.execute(cmd)
330
331         def cmdFinished(self,retval):
332                 self.container.appClosed.get().remove(self.cmdFinished)
333                 self.container.dataAvail.get().remove(self.dataAvail)
334
335         def checkforInterface(self,iface):
336                 if self.getAdapterAttribute(iface, 'up') is True:
337                         return True
338                 else:
339                         ret=system("ifconfig " + iface + " up")
340                         system("ifconfig " + iface + " down")
341                         if ret == 0:
342                                 return True
343                         else:
344                                 return False
345
346         def checkDNSLookup(self):
347                 return system("nslookup www.dream-multimedia-tv.de") == 0 or \
348                         system("nslookup www.heise.de") == 0 or \
349                         system("nslookup www.google.de")
350
351         def deactivateInterface(self,iface):
352                 system("ifconfig " + iface + " down")
353
354         def detectWlanModule(self):
355                 self.wlanmodule = None
356                 rt73_dir = "/sys/bus/usb/drivers/rt73/"
357                 zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
358                 madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
359                 if os_path.exists(madwifi_dir):
360                         files = listdir(madwifi_dir)
361                         if len(files) >= 1:
362                                 self.wlanmodule = 'madwifi'
363                 if os_path.exists(rt73_dir):
364                         rtfiles = listdir(rt73_dir)
365                         if len(rtfiles) == 2:
366                                 self.wlanmodule = 'ralink'
367                 if os_path.exists(zd1211b_dir):
368                         zdfiles = listdir(zd1211b_dir)
369                         if len(zdfiles) == 1:
370                                 self.wlanmodule = 'zydas'
371                 return self.wlanmodule
372         
373         
374 iNetwork = Network()
375
376 def InitNetwork():
377         pass