handle case of empty text
[enigma2.git] / lib / python / Components / Network.py
1 import os
2 import re
3 from socket import *
4
5 class Network:
6         def __init__(self):
7                 self.ifaces = {}
8                 self.nameservers = []
9                 self.getInterfaces()
10                 
11         def getInterfaces(self):
12                 devicesPattern = re.compile('[a-z]+[0-9]+')
13                 
14                 fp = file('/proc/net/dev', 'r')
15                 result = fp.readlines()
16                 fp.close()
17                 for line in result:
18                         try:
19                                 device = devicesPattern.search(line).group()
20                                 self.ifaces[device] = self.getDataForInterface(device)
21                         except AttributeError:
22                                 pass
23                 
24                 print "self.ifaces:", self.ifaces
25                 self.loadNetworkConfig()
26                 #self.writeNetworkConfig()
27                 #print ord(' ')
28                 #for line in result:
29 #                       print ord(line[0])
30
31         # helper function
32         def regExpMatch(self, pattern, string):
33                 if string is None:
34                         return None
35                 try:
36                         return pattern.search(string).group()
37                 except AttributeError:
38                         None
39         
40         # helper function to convert ips from a sring to a list of ints
41         def convertIP(self, ip):
42                 strIP = ip.split('.')
43                 ip = []
44                 for x in strIP:
45                         ip.append(int(x))
46                 return ip
47
48         def getDataForInterface(self, iface):
49                 #ipRegexp = '[0-9]{1,2,3}\.[0-9]{1,2,3}\.[0-9]{1,2,3}\.[0-9]{1,2,3}'
50                 ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
51                 ipLinePattern = re.compile('inet addr:' + ipRegexp)
52                 netmaskLinePattern = re.compile('Mask:' + ipRegexp)
53                 bcastLinePattern = re.compile('Bcast:' + ipRegexp)
54                 ipPattern = re.compile(ipRegexp)
55                 upPattern = re.compile('UP ')
56                 macPattern = re.compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}')
57                 
58                 fp = os.popen("ifconfig " + iface)
59                 result = fp.readlines()
60                 fp.close()
61                 data = { 'up': False, 'dhcp': False }
62                 for line in result:
63                         ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, line))
64                         netmask = self.regExpMatch(ipPattern, self.regExpMatch(netmaskLinePattern, line))
65                         bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, line))
66                         up = self.regExpMatch(upPattern, line)
67                         mac = self.regExpMatch(macPattern, line)
68                         if ip is not None:
69                                 data['ip'] = self.convertIP(ip)
70                         if netmask is not None:
71                                 data['netmask'] = self.convertIP(netmask)
72                         if bcast is not None:
73                                 data['bcast'] = self.convertIP(bcast)
74                         if up is not None:
75                                 data['up'] = True
76                         if mac is not None:
77                                 data['mac'] = mac
78                 if not data.has_key('ip'):
79                         data['dhcp'] = True
80                         data['ip'] = [192, 168, 1, 2]
81                         data['netmask'] = [255, 255, 255, 0]
82                         data['gateway'] = [192, 168, 1, 1]
83                 
84                 fp = os.popen("route -n | grep  " + iface)
85                 result = fp.readlines()
86                 fp.close()                              
87                 for line in result:
88                         print line[0:7]
89                         if line[0:7] == "0.0.0.0":
90                                 gateway = self.regExpMatch(ipPattern, line[16:31])
91                                 if gateway is not None:
92                                         data['gateway'] = self.convertIP(gateway)
93                 return data
94
95         def writeNetworkConfig(self):
96                 fp = file('/etc/network/interfaces', 'w')
97                 fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
98                 fp.write("auto lo\n")
99                 fp.write("iface lo inet loopback\n\n")
100                 
101                 for ifacename, iface in self.ifaces.items():
102                         if iface['up'] == True:
103                                 fp.write("auto " + ifacename + "\n")
104                         if iface['dhcp'] == True:
105                                 fp.write("iface "+ ifacename +" inet dhcp\n")
106                         else:
107                                 fp.write("iface "+ ifacename +" inet static\n")
108                                 if iface.has_key('ip'):
109                                         print tuple(iface['ip'])
110                                         fp.write("      address %d.%d.%d.%d\n" % tuple(iface['ip']))
111                                         fp.write("      netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
112                                         if iface.has_key('gateway'):
113                                                 fp.write("      gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
114                                                 
115                         if iface.has_key("configStrings"):
116                                 fp.write("\n" + iface["configStrings"] + "\n")
117                         fp.write("\n")
118                 fp.close()
119                 self.writeNameserverConfig()
120
121                 
122         def writeNameserverConfig(self):
123                 fp = file('/etc/resolv.conf', 'w')
124                 for nameserver in self.nameservers:
125                         fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
126                 fp.close()
127                 
128
129         def loadNetworkConfig(self):
130                 self.loadNameserverConfig()
131                 
132                 interfaces = []
133                 # parse the interfaces-file
134                 try:
135                         fp = file('/etc/network/interfaces', 'r')
136                         interfaces = fp.readlines()
137                         fp.close()
138                 except:
139                         print "[Network.py] interfaces - opening failed"
140                         
141                 ifaces = {}
142                 currif = ""
143                 for i in interfaces:
144                         split = i.strip().split(' ')
145                         if (split[0] == "iface"):
146                                 currif = split[1]
147                                 ifaces[currif] = {}
148                                 if (len(split) == 4 and split[3] == "dhcp"):
149                                         ifaces[currif]["dhcp"] = True
150                                 else:
151                                         ifaces[currif]["dhcp"] = False
152                         if (currif != ""):
153                                 if (split[0] == "address"):
154                                         ifaces[currif]["address"] = map(int, split[1].split('.'))
155                                 if (split[0] == "netmask"):
156                                         ifaces[currif]["netmask"] = map(int, split[1].split('.'))
157                                 if (split[0] == "gateway"):
158                                         ifaces[currif]["gateway"] = map(int, split[1].split('.'))                                                                       
159                 
160                 print "read interfaces:", ifaces
161                 for ifacename, iface in ifaces.items():
162                         if self.ifaces.has_key(ifacename):
163                                 self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
164                 
165                 print "self.ifaces after loading:", self.ifaces
166
167         def loadNameserverConfig(self):
168                 ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
169                 nameserverPattern = re.compile("nameserver +" + ipRegexp)
170                 ipPattern = re.compile(ipRegexp)
171                 
172                 resolv = []
173                 try:
174                         fp = file('/etc/resolv.conf', 'r')
175                         resolv = fp.readlines()
176                         fp.close()
177                         self.nameservers = []
178                 except:
179                         print "[Network.py] resolv.conf - opening failed"
180                 
181                 for line in resolv:
182                         if self.regExpMatch(nameserverPattern, line) is not None:
183                                 ip = self.regExpMatch(ipPattern, line)
184                                 if ip is not None:
185                                         self.nameservers.append(self.convertIP(ip))
186                                         
187                 print "nameservers:", self.nameservers          
188
189         def deactivateNetworkConfig(self):
190                 for iface in self.ifaces.keys():
191                         os.system("ip addr flush " + iface)
192                 os.system("/etc/init.d/networking stop")
193                 os.system("killall -9 udhcpc")
194                 os.system("rm /var/run/udhcpc*")
195
196         def activateNetworkConfig(self):
197                 os.system("/etc/init.d/networking start")
198                 
199         def getNumberOfAdapters(self):
200                 return len(self.ifaces)
201
202         def getFriendlyAdapterName(self, x):
203                 # maybe this needs to be replaced by an external list.
204                 friendlyNames = {
205                         "eth0": _("Integrated Ethernet"),
206                         "wlan0": _("Wireless")
207                 }
208                 return friendlyNames.get(x, x) # when we have no friendly name, use adapter name
209
210         def getAdapterName(self, iface):
211                 return iface
212         
213         def getAdapterList(self):
214                 return self.ifaces.keys()
215         
216         def getAdapterAttribute(self, iface, attribute):
217                 if self.ifaces.has_key(iface):
218                         if self.ifaces[iface].has_key(attribute):
219                                 return self.ifaces[iface][attribute]
220                 return None
221         
222         def setAdapterAttribute(self, iface, attribute, value):
223                 print "setting for adapter", iface, "attribute", attribute, " to value", value
224                 if self.ifaces.has_key(iface):
225                         self.ifaces[iface][attribute] = value
226
227         def removeAdapterAttribute(self, iface, attribute):
228                 if self.ifaces.has_key(iface):
229                         if self.ifaces[iface].has_key(attribute):
230                                 del self.ifaces[iface][attribute]
231                                 
232         def getNameserverList(self):
233                 return self.nameservers
234         
235         def clearNameservers(self):
236                 self.nameservers = []
237         
238         def addNameserver(self, nameserver):
239                 if nameserver not in self.nameservers:
240                         self.nameservers.append(nameserver)
241                 
242         def removeNameserver(self, nameserver):
243                 if nameserver in self.nameservers:
244                         self.nameservers.remove(nameserver)
245                         
246         def changeNameserver(self, oldnameserver, newnameserver):
247                 if oldnameserver in self.nameservers:
248                         for i in range(len(self.nameservers)):
249                                 if self.nameservers[i] == oldnameserver:
250                                         self.nameservers[i] = newnameserver
251
252 iNetwork = Network()
253
254 def InitNetwork():
255         pass