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