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