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