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