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