aboutsummaryrefslogtreecommitdiff
path: root/lib/python/Components/Network.py
blob: cf21c6d053e5067c63efbddb0ffaa5fe8dee3d28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
from os import system, popen, path as os_path, listdir
from re import compile as re_compile
from socket import *
from enigma import eConsoleAppContainer
from Components.Console import Console

class Network:
	def __init__(self):
		self.ifaces = {}
		self.configuredInterfaces = []		
		self.nameservers = []
		self.ethtool_bin = "/usr/sbin/ethtool"
		self.container = eConsoleAppContainer()
		self.Console = Console()
		self.getInterfaces()

	def getInterfaces(self, callback = None):
		devicesPattern = re_compile('[a-z]+[0-9]+')
		self.configuredInterfaces = []
		fp = file('/proc/net/dev', 'r')
		result = fp.readlines()
		fp.close()
		for line in result:
			try:
				device = devicesPattern.search(line).group()
				if device == 'wifi0':
					continue
				self.getDataForInterface(device, callback)
			except AttributeError:
				pass

	# helper function
	def regExpMatch(self, pattern, string):
		if string is None:
			return None
		try:
			return pattern.search(string).group()
		except AttributeError:
			None

	# helper function to convert ips from a sring to a list of ints
	def convertIP(self, ip):
		strIP = ip.split('.')
		ip = []
		for x in strIP:
			ip.append(int(x))
		return ip

	def IPaddrFinished(self, result, retval, extra_args):
		(iface, callback ) = extra_args
		data = { 'up': False, 'dhcp': False, 'preup' : False, 'postdown' : False }
		globalIPpattern = re_compile("scope global")
		ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
		ipLinePattern = re_compile('inet ' + ipRegexp +'/')
		ipPattern = re_compile(ipRegexp)

		for line in result.splitlines():
			split = line.strip().split(' ',2)
			if (split[1] == iface):
				if re_search(globalIPpattern, split[2]):
					ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[2]))
					if ip is not None:
						data['ip'] = self.convertIP(ip)
		if not data.has_key('ip'):
			data['dhcp'] = True
			data['ip'] = [0, 0, 0, 0]
			data['netmask'] = [0, 0, 0, 0]
			data['gateway'] = [0, 0, 0, 0]

		cmd = "ifconfig " + iface
		self.Console.ePopen(cmd, self.ifconfigFinished, [iface, data, callback])

	def getDataForInterface(self, iface,callback):
		#get ip out of ip addr, as avahi sometimes overrides it in ifconfig.
		cmd = "ip -o addr"
		self.Console.ePopen(cmd, self.IPaddrFinished, [iface,callback])

	def ifconfigFinished(self, result, retval, extra_args ):
		(iface, data, callback ) = extra_args
		ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
		ipLinePattern = re_compile('inet addr:' + ipRegexp)
		netmaskLinePattern = re_compile('Mask:' + ipRegexp)
		bcastLinePattern = re_compile('Bcast:' + ipRegexp)
		ipPattern = re_compile(ipRegexp)
		upPattern = re_compile('UP ')
		macPattern = re_compile('[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}\:[0-9]{2}')

		for line in result.splitlines():
			#ip = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, line))
			netmask = self.regExpMatch(ipPattern, self.regExpMatch(netmaskLinePattern, line))
			bcast = self.regExpMatch(ipPattern, self.regExpMatch(bcastLinePattern, line))
			up = self.regExpMatch(upPattern, line)
			mac = self.regExpMatch(macPattern, line)
			#if ip is not None:
			#       data['ip'] = self.convertIP(ip)
			if netmask is not None:
				data['netmask'] = self.convertIP(netmask)
			if bcast is not None:
				data['bcast'] = self.convertIP(bcast)
			if up is not None:
				data['up'] = True
				if iface is not 'lo':
					self.configuredInterfaces.append(iface)
			if mac is not None:
				data['mac'] = mac

		cmd = "route -n | grep  " + iface
		self.Console.ePopen(cmd,self.routeFinished,[iface,data,callback])

	def routeFinished(self, result, retval, extra_args):
		(iface, data, callback) = extra_args
		ipRegexp = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
		ipPattern = re_compile(ipRegexp)
		ipLinePattern = re_compile(ipRegexp)

		for line in result.splitlines():
			print line[0:7]
			if line[0:7] == "0.0.0.0":
				gateway = self.regExpMatch(ipPattern, line[16:31])
				if gateway is not None:
					data['gateway'] = self.convertIP(gateway)

		for line in result.splitlines(): #get real netmask in case avahi has overridden ifconfig netmask
			split = line.strip().split('   ')
			if re_search(ipPattern, split[0]):
				foundip = self.convertIP(split[0])
				if (foundip[0] == data['ip'][0] and foundip[1] == data['ip'][1]):
					if re_search(ipPattern, split[4]):
						mask = self.regExpMatch(ipPattern, self.regExpMatch(ipLinePattern, split[4]))
						if mask is not None:
							data['netmask'] = self.convertIP(mask)
		self.ifaces[iface] = data
		self.loadNetworkConfig(iface,callback)

	def writeNetworkConfig(self):
		self.configuredInterfaces = []
		fp = file('/etc/network/interfaces', 'w')
		fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
		fp.write("auto lo\n")
		fp.write("iface lo inet loopback\n\n")
		for ifacename, iface in self.ifaces.items():
			if iface['up'] == True:
				fp.write("auto " + ifacename + "\n")
				self.configuredInterfaces.append(ifacename)
			if iface['dhcp'] == True:
				fp.write("iface "+ ifacename +" inet dhcp\n")
			if iface['dhcp'] == False:
				fp.write("iface "+ ifacename +" inet static\n")
				if iface.has_key('ip'):
					print tuple(iface['ip'])
					fp.write("	address %d.%d.%d.%d\n" % tuple(iface['ip']))
					fp.write("	netmask %d.%d.%d.%d\n" % tuple(iface['netmask']))
					if iface.has_key('gateway'):
						fp.write("	gateway %d.%d.%d.%d\n" % tuple(iface['gateway']))
			if iface.has_key("configStrings"):
				fp.write("\n" + iface["configStrings"] + "\n")
			if iface["preup"] is not False and not iface.has_key("configStrings"):
				fp.write(iface["preup"])
				fp.write(iface["postdown"])
			fp.write("\n")				
		fp.close()
		self.writeNameserverConfig()

	def writeNameserverConfig(self):
		fp = file('/etc/resolv.conf', 'w')
		for nameserver in self.nameservers:
			fp.write("nameserver %d.%d.%d.%d\n" % tuple(nameserver))
		fp.close()

	def loadNetworkConfig(self,iface,callback = None):
		interfaces = []
		# parse the interfaces-file
		try:
			fp = file('/etc/network/interfaces', 'r')
			interfaces = fp.readlines()
			fp.close()
		except:
			print "[Network.py] interfaces - opening failed"

		ifaces = {}
		currif = ""
		for i in interfaces:
			split = i.strip().split(' ')
			if (split[0] == "iface"):
				currif = split[1]
				ifaces[currif] = {}
				if (len(split) == 4 and split[3] == "dhcp"):
					ifaces[currif]["dhcp"] = True
				else:
					ifaces[currif]["dhcp"] = False
			if (currif == iface): #read information only for available interfaces
				if (split[0] == "address"):
					ifaces[currif]["address"] = map(int, split[1].split('.'))
					if self.ifaces[currif].has_key("ip"):
						if self.ifaces[currif]["ip"] != ifaces[currif]["address"] and ifaces[currif]["dhcp"] == False:
							self.ifaces[currif]["ip"] = map(int, split[1].split('.'))
				if (split[0] == "netmask"):
					ifaces[currif]["netmask"] = map(int, split[1].split('.'))
					if self.ifaces[currif].has_key("netmask"):
						if self.ifaces[currif]["netmask"] != ifaces[currif]["netmask"] and ifaces[currif]["dhcp"] == False:
							self.ifaces[currif]["netmask"] = map(int, split[1].split('.'))
				if (split[0] == "gateway"):
					ifaces[currif]["gateway"] = map(int, split[1].split('.'))
					if self.ifaces[currif].has_key("gateway"):
						if self.ifaces[currif]["gateway"] != ifaces[currif]["gateway"] and ifaces[currif]["dhcp"] == False:
							self.ifaces[currif]["gateway"] = map(int, split[1].split('.'))
				if (split[0] == "pre-up"):
					if self.ifaces[currif].has_key("preup"):
						self.ifaces[currif]["preup"] = i
				if (split[0] == "post-down"):
					if self.ifaces[currif].has_key("postdown"):
						self.ifaces[currif]["postdown"] = i

		for ifacename, iface in ifaces.items():
			if self.ifaces.has_key(ifacename):
				self.ifaces[ifacename]["dhcp"] = iface["dhcp"]
		if len(self.Console.appContainers) == 0:
			# load ns only once
			self.loadNameserverConfig()
			print "read configured interfac:", ifaces
			print "self.ifaces after loading:", self.ifaces
			if callback is not None:
				callback(True)

	def loadNameserverConfig(self):
		ipRegexp = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
		nameserverPattern = re_compile("nameserver +" + ipRegexp)
		ipPattern = re_compile(ipRegexp)

		resolv = []
		try:
			fp = file('/etc/resolv.conf', 'r')
			resolv = fp.readlines()
			fp.close()
			self.nameservers = []
		except:
			print "[Network.py] resolv.conf - opening failed"

		for line in resolv:
			if self.regExpMatch(nameserverPattern, line) is not None:
				ip = self.regExpMatch(ipPattern, line)
				if ip is not None:
					self.nameservers.append(self.convertIP(ip))

		print "nameservers:", self.nameservers

	def deactivateNetworkConfig(self):
		for iface in self.ifaces.keys():
			system("ip addr flush " + iface)
		system("/etc/init.d/networking stop")
		system("killall -9 udhcpc")
		system("rm /var/run/udhcpc*")

	def activateNetworkConfig(self):
		system("/etc/init.d/networking start")
		self.getInterfaces()

	def getNumberOfAdapters(self):
		return len(self.ifaces)

	def getFriendlyAdapterName(self, x):
		# maybe this needs to be replaced by an external list.
		friendlyNames = {
			"eth0": _("Integrated Ethernet"),
			"wlan0": _("Wireless"),
			"ath0": _("Integrated Wireless")
		}
		return friendlyNames.get(x, x) # when we have no friendly name, use adapter name

	def getAdapterName(self, iface):
		return iface

	def getAdapterList(self):
		return self.ifaces.keys()

	def getAdapterAttribute(self, iface, attribute):
		if self.ifaces.has_key(iface):
			if self.ifaces[iface].has_key(attribute):
				return self.ifaces[iface][attribute]
		return None

	def setAdapterAttribute(self, iface, attribute, value):
		print "setting for adapter", iface, "attribute", attribute, " to value", value
		if self.ifaces.has_key(iface):
			self.ifaces[iface][attribute] = value

	def removeAdapterAttribute(self, iface, attribute):
		if self.ifaces.has_key(iface):
			if self.ifaces[iface].has_key(attribute):
				del self.ifaces[iface][attribute]

	def getNameserverList(self):
		if len(self.nameservers) == 0:
			return [[0, 0, 0, 0], [0, 0, 0, 0]]
		else: 
			return self.nameservers

	def clearNameservers(self):
		self.nameservers = []

	def addNameserver(self, nameserver):
		if nameserver not in self.nameservers:
			self.nameservers.append(nameserver)

	def removeNameserver(self, nameserver):
		if nameserver in self.nameservers:
			self.nameservers.remove(nameserver)

	def changeNameserver(self, oldnameserver, newnameserver):
		if oldnameserver in self.nameservers:
			for i in range(len(self.nameservers)):
				if self.nameservers[i] == oldnameserver:
					self.nameservers[i] = newnameserver

	def writeDefaultNetworkConfig(self,mode='lan'):
		fp = file('/etc/network/interfaces', 'w')
		fp.write("# automatically generated by enigma 2\n# do NOT change manually!\n\n")
		fp.write("auto lo\n")
		fp.write("iface lo inet loopback\n\n")
		if mode == 'wlan':
			fp.write("auto wlan0\n")
			fp.write("iface wlan0 inet dhcp\n")
		if mode == 'wlan-mpci':
			fp.write("auto ath0\n")
			fp.write("iface ath0 inet dhcp\n")
		if mode == 'lan':
			fp.write("auto eth0\n")
			fp.write("iface eth0 inet dhcp\n")
		fp.write("\n")
		fp.close()

	def resetNetworkConfig(self,mode='lan'):
		self.deactivateNetworkConfig()
		self.writeDefaultNetworkConfig(mode)
		if mode == 'wlan':
			system("ifconfig eth0 down")
			system("ifconfig ath0 down")
			system("ifconfig wlan0 up")
		if mode == 'wlan-mpci':
			system("ifconfig eth0 down")
			system("ifconfig wlan0 down")
			system("ifconfig ath0 up")		
		if mode == 'lan':			
			system("ifconfig eth0 up")
			system("ifconfig wlan0 down")
			system("ifconfig ath0 down")
		self.getInterfaces()	

	def checkNetworkState(self):
		 # www.dream-multimedia-tv.de, www.heise.de, www.google.de
		return system("ping -c 1 82.149.226.170") == 0 or \
			system("ping -c 1 193.99.144.85") == 0 or \
			system("ping -c 1 209.85.135.103") == 0

	def restartNetwork(self):
		iNetwork.deactivateNetworkConfig()
		iNetwork.activateNetworkConfig()

	def getLinkState(self,iface,callback):
		self.dataAvail = callback
		cmd = self.ethtool_bin + " " + iface
		self.container.appClosed.append(self.cmdFinished)
		self.container.dataAvail.append(callback)
		self.container.execute(cmd)

	def cmdFinished(self,retval):
		self.container.appClosed.remove(self.cmdFinished)
		self.container.dataAvail.remove(self.dataAvail)

	def stopContainer(self):
		self.container.kill()
		
	def ContainerRunning(self):
		return self.container.running()

	def checkforInterface(self,iface):
		if self.getAdapterAttribute(iface, 'up') is True:
			return True
		else:
			ret=system("ifconfig " + iface + " up")
			system("ifconfig " + iface + " down")
			if ret == 0:
				return True
			else:
				return False

	def checkDNSLookup(self):
		return system("nslookup www.dream-multimedia-tv.de") == 0 or \
			system("nslookup www.heise.de") == 0 or \
			system("nslookup www.google.de")

	def deactivateInterface(self,iface):
		system("ifconfig " + iface + " down")

	def detectWlanModule(self):
		self.wlanmodule = None
		rt73_dir = "/sys/bus/usb/drivers/rt73/"
		zd1211b_dir = "/sys/bus/usb/drivers/zd1211b/"
		madwifi_dir = "/sys/bus/pci/drivers/ath_pci/"
		if os_path.exists(madwifi_dir):
			files = listdir(madwifi_dir)
			if len(files) >= 1:
				self.wlanmodule = 'madwifi'
		if os_path.exists(rt73_dir):
			rtfiles = listdir(rt73_dir)
			if len(rtfiles) == 2:
				self.wlanmodule = 'ralink'
		if os_path.exists(zd1211b_dir):
			zdfiles = listdir(zd1211b_dir)
			if len(zdfiles) == 1:
				self.wlanmodule = 'zydas'
		return self.wlanmodule
	
	
iNetwork = Network()

def InitNetwork():
	pass