some fixes and cleanups
[enigma2-plugins.git] / wirelesslan / src / Wlan.py
1 from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER
2 from Components.MultiContent import MultiContentEntryText
3 from Components.GUIComponent import GUIComponent
4 from Components.HTMLComponent import HTMLComponent
5 from Components.config import config, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, ConfigSelection
6
7 from os import system
8 from string import maketrans, strip
9 from iwlibs import getNICnames, Wireless, Iwfreq
10
11 list = []
12 list.append(_("WEP"))
13 list.append(_("WPA"))
14 list.append(_("WPA2"))
15
16 config.plugins.wlan = ConfigSubsection()
17 config.plugins.wlan.essid = NoSave(ConfigText(default = "home", fixed_size = False))
18
19 config.plugins.wlan.encryption = ConfigSubsection()
20 config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = False))
21 config.plugins.wlan.encryption.type = NoSave(ConfigSelection(list, default = _("WPA")))
22 config.plugins.wlan.encryption.psk = NoSave(ConfigText(default = "mysecurewlan", fixed_size = False))
23
24 class Wlan:
25         def __init__(self, iface):
26                 a = ''; b = ''
27                 
28                 for i in range(0, 255):
29                     a = a + chr(i)
30                     if i < 32 or i > 127:
31                         b = b + ' '
32                     else:
33                         b = b + chr(i)
34                 
35                 self.iface = iface
36                 self.asciitrans = maketrans(a, b)
37
38         
39         def asciify(self, str):
40                 return str.translate(self.asciitrans)
41
42         
43         def getWirelessInterfaces(self):
44                 iwifaces = None
45                 try:
46                         iwifaces = getNICnames()
47                 except:
48                         print "[Wlan.py] No Wireless Networkcards could be found"
49                 
50                 return iwifaces
51
52         
53         def getNetworkList(self):
54                 ifobj = Wireless(self.iface) # a Wireless NIC Object
55                 print "ifobj.getStatistics(): ", ifobj.getStatistics()
56                 
57                 #Association mappings
58                 stats, quality, discard, missed_beacon = ifobj.getStatistics()
59                 snr = quality.signallevel - quality.noiselevel
60                 system("ifconfig "+self.iface+" up")
61                 
62                 try:
63                         scanresults = ifobj.scan()
64                 except:
65                         scanresults = None
66                         print "[Wlan.py] No Wireless Networks could be found"
67                 
68                 if scanresults is not None:
69                         aps = {}
70                         for result in scanresults:
71                                 
72                                 bssid = result.bssid
73                 
74                                 encryption = map(lambda x: hex(ord(x)), result.encode)
75                 
76                                 if encryption[-1] == "0x8":
77                                         encryption = True
78                                 else:
79                                         encryption = False
80                 
81                                 extra = []
82                                 for element in result.custom:
83                                         element = element.encode()
84                                         extra.append( strip(self.asciify(element)) )
85                                 
86                                 print result.quality.getSignallevel()
87                                 
88                                 if result.quality.sl is 0 and len(extra) > 0:
89                                         begin = extra[0].find('SignalStrength=')+15
90                                                                         
91                                         done = False
92                                         end = begin+1
93                                         
94                                         while not done:
95                                                 if extra[0][begin:end].isdigit():
96                                                         end += 1
97                                                 else:
98                                                         done = True
99                                                         end -= 1
100                                         
101                                         signal = extra[0][begin:end]
102                                         print "[Wlan.py] signal is:" + str(signal)
103
104                                 else:
105                                         signal = str(result.quality.sl)
106                                 
107                                 aps[bssid] = {
108                                         'active' : True,
109                                         'bssid': result.bssid,
110                                         'channel': result.frequency.getChannel(result.frequency.getFrequency()),
111                                         'encrypted': encryption,
112                                         'essid': strip(self.asciify(result.essid)),
113                                         'iface': self.iface,
114                                         'maxrate' : result.rate[-1],
115                                         'noise' : result.quality.getNoiselevel(),
116                                         'quality' : str(result.quality.quality),
117                                         'signal' : signal,
118                                         'custom' : extra,
119                                 }
120                                 print aps[bssid]
121                         return aps
122
123                 
124         def getStatus(self):
125                 ifobj = Wireless(self.iface)
126                 fq = Iwfreq()
127                 
128                 status = {
129                                   'BSSID': str(ifobj.getAPaddr()),
130                                   'ESSID': str(ifobj.getEssid()),
131                                   'quality': str(ifobj.getStatistics()[1].quality),
132                                   'signal': str(ifobj.getStatistics()[1].sl),
133                                   'bitrate': str(ifobj.getBitrate()),
134                                   'channel': str(fq.getChannel(str(ifobj.getFrequency()[0:-3]))),
135                 }
136                 
137                 for (key, item) in status.items():
138                         if item is "None" or item is "":
139                                         status[key] = _("N/A")
140                                 
141                 return status
142
143
144
145 class WlanList(HTMLComponent, GUIComponent):
146         def __init__(self, session, iface):
147                 
148                 GUIComponent.__init__(self)
149                 self.w = Wlan(iface)
150                 self.iface = iface
151                 
152                 self.length = 0
153                 self.aplist = None
154                 self.l = None
155                 self.l = eListboxPythonMultiContent()
156                 
157                 self.l.setFont(0, gFont("Regular", 32))
158                 self.l.setFont(1, gFont("Regular", 18))
159                 self.l.setFont(2, gFont("Regular", 16))
160                 self.l.setBuildFunc(self.buildWlanListEntry)            
161                                 
162                 self.reload()
163         
164         
165         def buildWlanListEntry(self, essid, bssid, encrypted, iface, maxrate, signal):                                                                                                 
166                 
167                 res = [ (essid, encrypted, iface) ]
168                 
169                 if essid == "":
170                         essid = bssid
171                 
172                 e = encrypted and _("Yes") or _("No")
173                 res.append( MultiContentEntryText(pos=(0, 0), size=(470, 35), font=0, flags=RT_HALIGN_LEFT, text=essid) )
174                 res.append( MultiContentEntryText(pos=(425, 0), size=(60, 20), font=1, flags=RT_HALIGN_LEFT, text=_("Signal: ")))
175                 res.append( MultiContentEntryText(pos=(480, 0), size=(70, 35), font=0, flags=RT_HALIGN_RIGHT, text="%s" %signal))
176                 res.append( MultiContentEntryText(pos=(0, 40), size=(180, 20), font=1, flags=RT_HALIGN_LEFT, text=_("Max. Bitrate: %s") %maxrate ))
177                 res.append( MultiContentEntryText(pos=(190, 40), size=(180, 20), font=1, flags=RT_HALIGN_CENTER, text=_("Encrypted: %s") %e ))
178                 res.append( MultiContentEntryText(pos=(360, 40), size=(190, 20), font=1, flags=RT_HALIGN_RIGHT, text=_("Interface: %s") %iface ))
179                 return res
180                 
181                         
182         def reload(self):
183                 aps = self.w.getNetworkList()
184                 list = []
185                 self.aplist = []
186                 if aps is not None:
187                         print "[Wlan.py] got Accespoints!"
188                         for ap in aps:
189                                 a = aps[ap]
190                                 if a['active']:
191                                         if a['essid'] == "":
192                                                 a['essid'] = a['bssid']
193                                         list.append( (a['essid'], a['bssid'], a['encrypted'], a['iface'], a['maxrate'], a['signal']) )
194                                         self.aplist.append( a['essid'])
195                 
196                 self.length = len(list)
197                 self.l.setList([])
198                 self.l.setList(list)
199                         
200         GUI_WIDGET = eListbox
201
202
203         def getCurrent(self):
204                 return self.l.getCurrentSelection()
205         
206         
207         def postWidgetCreate(self, instance):
208                 instance.setContent(self.l)
209                 instance.setItemHeight(60)
210         
211         
212         def getLength(self):
213                 return self.length
214         
215         def getList(self):
216                 return self.aplist
217
218
219 class wpaSupplicant:
220         def __init__(self):
221                 pass
222         
223                 
224         def writeConfig(self):  
225                         
226                         essid = config.plugins.wlan.essid.value
227                         encrypted = config.plugins.wlan.encryption.enabled.value
228                         encryption = config.plugins.wlan.encryption.type.value
229                         psk = config.plugins.wlan.encryption.psk.value
230
231
232                         fp = file('/etc/wpa_supplicant.conf', 'w')
233                         fp.write('#WPA Supplicant Configuration by enigma2\n\n')
234                         fp.write('ctrl_interface=/var/run/wpa_supplicant\n')
235                         fp.write('ctrl_interface_group=0\n')
236                         fp.write('eapol_version=1\n')
237                         fp.write('ap_scan=1\n')
238                         fp.write('fast_reauth=1\n')                     
239                         fp.write('network={\n')
240                         fp.write('\tssid="'+essid+'"\n')
241                         fp.write('\tscan_ssid=0\n')
242                         
243                         if encrypted:
244                                                         
245                                 if encryption == 'WPA' or encryption == 'WPA2':
246                                         fp.write('\tkey_mgmt=WPA-PSK\n')
247                                         
248                                         if encryption == 'WPA':
249                                                 fp.write('\tproto=WPA\n')
250                                                 fp.write('\tpairwise=TKIP\n')
251                                                 fp.write('\tgroup=TKIP\n')
252                                         else:
253                                                 fp.write('\tproto=WPA RSN\n')
254                                                 fp.write('\tpairwise=CCMP TKIP\n')
255                                                 fp.write('\tgroup=CCMP TKIP\n')
256                                         
257                                         fp.write('\tpsk="'+psk+'"\n')
258                                 
259                                 elif encryption == 'WEP':
260                                         fp.write('\tkey_mgmt=NONE\n')
261                                         fp.write('\twep_key0="'+psk+'"\n')
262                         else:
263                                 fp.write('\tkey_mgmt=NONE\n')                   
264                         fp.write('}')   
265                         fp.close()
266                                 
267                         
268         def loadConfig(self):
269                 try:
270                         #parse the wpasupplicant configfile
271                         fp = file('/etc/wpa_supplicant.conf', 'r')
272                         supplicant = fp.readlines()
273                         fp.close()
274
275                         for s in supplicant:
276                                 split = s.strip().split('=',1)
277                                 if split[0] == 'ssid':
278                                         print "[Wlan.py] Got SSID "+split[1][1:-1]
279                                         config.plugins.wlan.essid.value = split[1][1:-1]
280                                         
281                                 elif split[0] == 'proto':
282                                         config.plugins.wlan.encryption.enabled.value = True
283                                         if split[1] == "WPA RSN" : split[1] = 'WPA2'
284                                         config.plugins.wlan.encryption.type.value = split[1]
285                                         print "[Wlan.py] Got Encryption: "+split[1]
286                                         
287                                 elif split[0] == 'wep_key0':
288                                         config.plugins.wlan.encryption.enabled.value = True
289                                         config.plugins.wlan.encryption.type.value = 'WEP'
290                                         config.plugins.wlan.encryption.psk.value = split[1][1:-1]
291                                         print "[Wlan.py] Got Encryption: WEP - key0 is: "+split[1][1:-1]
292                                         
293                                 elif split[0] == 'psk':
294                                         config.plugins.wlan.encryption.psk.value = split[1][1:-1]
295                                         print "[Wlan.py] Got PSK: "+split[1][1:-1]
296                                 else:
297                                         pass
298                                 
299                         wsconfig = {
300                                         'ssid': config.plugins.wlan.essid.value,
301                                         'encryption': config.plugins.wlan.encryption.enabled.value,
302                                         'encryption_type': config.plugins.wlan.encryption.type.value,
303                                         'key': config.plugins.wlan.encryption.psk.value,
304                                 }
305                 
306                         for (key, item) in wsconfig.items():
307                                 if item is "None" or item is "":
308                                         if key == 'ssid':
309                                                 wsconfig['ssid'] = "home"
310                                         if key == 'encryption':
311                                                 wsconfig['encryption'] = False                          
312                                         if key == 'encryption':
313                                                 wsconfig['encryption_type'] = "WPA"
314                                         if key == 'encryption':
315                                                 wsconfig['key'] = "mysecurewlan"
316
317                 except:
318                         print "[Wlan.py] Error parsing /etc/wpa_supplicant.conf"
319                         wsconfig = {
320                                         'ssid': "home",
321                                         'encryption': False,
322                                         'encryption_type': "WPA",
323                                         'key': "mysecurewlan",
324                                 }
325                 print "WS-CONFIG-->",wsconfig
326                 return wsconfig
327
328         
329         def restart(self, iface):
330                 system("start-stop-daemon -K -x /usr/sbin/wpa_supplicant")
331                 system("start-stop-daemon -S -x /usr/sbin/wpa_supplicant -- -B -i"+iface+" -c/etc/wpa_supplicant.conf")