1 from enigma import eTimer
3 from Components.config import config, ConfigSubsection, NoSave, ConfigText, ConfigYesNo, ConfigSelection, ConfigPassword
4 from Components.Console import Console
5 from Components.Network import iNetwork
7 from pythonwifi.iwlibs import Wireless
8 from pythonwifi import flags as wifi_flags
14 encryptionlist.append(("Unencrypted", _("Unencrypted")))
15 encryptionlist.append(("WEP", _("WEP")))
16 encryptionlist.append(("WPA", _("WPA")))
17 encryptionlist.append(("WPA/WPA2", _("WPA or WPA2")))
18 encryptionlist.append(("WPA2", _("WPA2")))
20 config.plugins.wlan = ConfigSubsection()
21 config.plugins.wlan.essid = NoSave(ConfigText(default = "", fixed_size = False))
22 config.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default = False))
23 config.plugins.wlan.encryption = NoSave(ConfigSelection(encryptionlist, default = "WPA2"))
24 config.plugins.wlan.wepkeytype = NoSave(ConfigSelection(["ASCII", "HEX"], default = "ASCII"))
25 config.plugins.wlan.psk = NoSave(ConfigPassword(default = "", fixed_size = False))
27 def search_pattern(data, p, s):
28 if not isinstance(s, list):
46 def getWlConfName(self, iface):
47 return "/etc/wl.conf.%s" % iface
49 def getDefaultWlConf(self):
52 "hiddenessid" : False,
53 "encryption" : "WPA2",
54 "wepkeytype" : "ASCII",
58 def readWlConf(self, iface):
59 wsconf = self.getDefaultWlConf()
60 wlConfName = self.getWlConfName(iface)
61 if os.path.exists(wlConfName):
62 data = open(wlConfName, "r").readlines()
65 (key, value) = x.strip().split('=',1)
70 wsconf["ssid"] = value.strip()
72 wsconf["encryption"] = value.strip()
74 wsconf["key"] = value.strip()
78 #for (k,v) in wsconf.items():
79 # print "[wsconf][%s] %s" % (k , v)
83 def writeWlConf(self, iface):
84 essid = config.plugins.wlan.essid.value
85 encryption = config.plugins.wlan.encryption.value
86 psk = config.plugins.wlan.psk.value
89 contents += "ssid="+essid+"\n"
90 contents += "method="+encryption+"\n"
91 contents += "key="+psk+"\n"
92 #print "[writeWlConf] content = \n"+contents
94 wlConfName = self.getWlConfName(iface)
96 fd = open(wlConfName, "w")
98 self.session.open(MessageBox, _("%s open error." % wlConfName ), type = MessageBox.TYPE_ERROR, timeout = 10)
105 def getWpaSupplicantName(self, iface):
106 return "/etc/wpa_supplicant.conf.%s" % iface
108 def readWpaSupplicantConf(self, iface):
109 wsconf = self.getDefaultWlConf()
110 wpaSupplicantName = self.getWpaSupplicantName(iface)
112 if os.path.exists(wpaSupplicantName):
113 wpa_conf_data = open(wpaSupplicantName, "r").readlines()
115 for line in wpa_conf_data:
117 (key, value) = line.strip().split('=',1)
121 if key not in ('ssid', 'scan_ssid', 'key_mgmt', 'proto', 'wep_key0', 'psk', '#psk'):
124 data[key] = value.strip('"')
126 data[key] = value.strip()
128 wsconf["ssid"] = data.get("ssid", "INPUTSSID")
129 wsconf["hiddenessid"] = data.get("scan_ssid") == '1' and True or False
131 key_mgmt = data.get("key_mgmt")
132 if key_mgmt == "NONE":
133 wep_key = data.get("wep_key0")
136 wsconf["encryption"] = "Unencrypted"
138 wsconf["encryption"] = "WEP"
140 if wep_key.startswith('"') and wep_key.endswith('"'):
141 wsconf["wepkeytype"] = "ASCII"
142 wsconf["key"] = wep_key.strip('"')
144 wsconf["wepkeytype"] = "HEX"
145 wsconf["key"] = wep_key
147 elif key_mgmt == "WPA-PSK":
148 proto = data.get("proto")
151 wsconf["encryption"] = "WPA"
153 wsconf["encryption"] = "WPA2"
154 elif proto in ( "WPA RSN", "WPA WPA2"):
155 wsconf["encryption"] = "WPA/WPA2"
157 wsconf["encryption"] = "WPA2"
159 psk = data.get("#psk")
161 wsconf["key"] = psk.strip('"')
163 wsconf["key"] = data.get("psk")
165 wsconf["encryption"] = "WPA2"
170 # for (k,v) in wsconf.items():
171 # print "[wsconf][%s] %s" % (k , v)
175 def getWpaPhrase(self):
176 essid = config.plugins.wlan.essid.value
177 psk = config.plugins.wlan.psk.value
178 cmd = "wpa_passphrase '%s' '%s'" % (essid, psk)
180 data = os.popen(cmd).readlines()
186 (key, value) = line.strip().split('=',1)
195 return (psk, plainpwd)
197 def writeWpasupplicantConf(self, iface):
198 wpaSupplicantName = self.getWpaSupplicantName(iface)
200 wpafd = open(wpaSupplicantName, "w")
202 self.session.open(MessageBox, _("%s open error." % wpaSupplicantName ), type = MessageBox.TYPE_ERROR, timeout = 10)
205 essid = config.plugins.wlan.essid.value
206 hiddenessid = config.plugins.wlan.hiddenessid.value
207 encryption = config.plugins.wlan.encryption.value
208 wepkeytype = config.plugins.wlan.wepkeytype.value
209 psk = config.plugins.wlan.psk.value
211 contents = "#WPA Supplicant Configuration by STB\n"
212 contents += "ctrl_interface=/var/run/wpa_supplicant\n"
213 contents += "eapol_version=1\n"
214 contents += "fast_reauth=1\n"
215 contents += "ap_scan=1\n"
216 contents += "network={\n"
218 contents += "\tssid=\""+essid+"\"\n"
220 if hiddenessid is True:
221 contents += "\tscan_ssid=1\n"
223 contents += "\tscan_ssid=0\n"
225 if encryption == "None":
226 contents += "\tkey_mgmt=NONE\n"
228 elif encryption == "WEP":
229 contents += "\tkey_mgmt=NONE\n"
230 contents += "\twep_key0="
231 if wepkeytype == "ASCII":
232 contents += "\""+psk+"\"\n"
237 if encryption == "WPA":
238 contents += "\tkey_mgmt=WPA-PSK\n"
239 contents += "\tproto=WPA\n"
240 contents += "\tpairwise=CCMP TKIP\n"
241 contents += "\tgroup=CCMP TKIP\n"
242 elif encryption == "WPA2":
243 contents += "\tkey_mgmt=WPA-PSK\n"
244 contents += "\tproto=RSN\n"
245 contents += "\tpairwise=CCMP TKIP\n"
246 contents += "\tgroup=CCMP TKIP\n"
248 contents += "\tkey_mgmt=WPA-PSK\n"
249 contents += "\tproto=WPA RSN\n"
250 contents += "\tpairwise=CCMP TKIP\n"
251 contents += "\tgroup=CCMP TKIP\n"
254 (passphrasekey, plainpwd) = self.getWpaPhrase()
256 # print "plainpwd : ",plainpwd
257 # print "passphrasekey : ",passphrasekey
258 if passphrasekey is not None and plainpwd is not None:
260 contents += passphrasekey
262 contents += "\tpsk=%s\n" % psk
265 # print "content = \n"+contents
266 wpafd.write(contents)
271 def loadConfig(self, iface):
272 if iNetwork.useWlCommand(iface):
273 wsconf = self.readWlConf(iface)
275 wsconf = self.readWpaSupplicantConf(iface)
278 def writeConfig(self, iface):
279 if iNetwork.useWlCommand(iface):
280 res = self.writeWlConf(iface)
282 res = self.writeWpasupplicantConf(iface)
285 def __init__(self, iface = None):
287 self.oldInterfaceState = None
289 def setInterface(self, iface = None):
292 def getInterface(self):
295 def activateIface(self):
296 if self.oldInterfaceState is None:
297 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
299 if self.oldInterfaceState is not True:
300 os.system("ifconfig "+self.iface+" up")
301 iNetwork.setAdapterAttribute(self.iface, "up", True)
303 if iNetwork.useWlCommand(self.iface):
306 def deActivateIface(self):
307 if self.oldInterfaceState is not True:
308 os.system("ifconfig "+self.iface+" down")
309 iNetwork.setAdapterAttribute(self.iface, "up", False)
311 if iNetwork.useWlCommand(self.iface):
314 self.oldInterfaceState = None
316 def getScanResult(self, wirelessObj):
319 Iwscanresult = wirelessObj.scan()
321 print "%s Interface doesn't support scanning.."%self.iface
324 def getNetworkList(self):
327 wirelessObj = Wireless(self.iface)
328 Iwscanresult=self.getScanResult(wirelessObj)
330 if Iwscanresult is None or len(Iwscanresult.aplist) == 0:
334 (num_channels, frequencies) = wirelessObj.getChannelInfo()
338 for ap in Iwscanresult:
341 apList[bssid]['active'] = True
342 apList[bssid]['bssid'] = bssid
343 apList[bssid]['essid'] = ap.essid or None
345 apList[bssid]['Address'] = apList[bssid]['bssid']
346 apList[bssid]['ESSID'] = apList[bssid]['essid']
347 apList[bssid]['Protocol'] = ap.protocol
348 apList[bssid]['Frequency'] = wirelessObj._formatFrequency(ap.frequency.getFrequency())
352 channel = frequencies.index(self.apList[index]["Frequency"]) + 1
355 apList[bssid]['Channel'] = channel
357 apList[bssid]['Quality'] = "%s/%s" % ( ap.quality.quality, wirelessObj.getQualityMax().quality )
358 apList[bssid]['Signal Level'] = "%s/%s" % ( ap.quality.getSignallevel(), "100" )
359 apList[bssid]['Noise Level'] = "%s/%s" % ( ap.quality.getNoiselevel(), "100" )
361 # get encryption key on/off
362 key_status = "Unknown"
363 if (ap.encode.flags & wifi_flags.IW_ENCODE_DISABLED):
365 elif (ap.encode.flags & wifi_flags.IW_ENCODE_NOKEY):
366 if (ap.encode.length <= 0):
368 apList[bssid]['Encryption key'] = key_status
371 if ap.rate and ap.rate[0]:
372 apList[bssid]['BitRate'] = wirelessObj._formatBitrate(ap.rate[0][-1])
374 apList[bssid]['BitRate'] = ""
380 def stopGetNetworkList(self):
381 self.deActivateIface()
387 self.getStatusConsole = Console()
388 self.essid_pattern = re.compile('ESSID:".+" ')
389 self.frequency_pattern = re.compile('Frequency:[.0-9]+ [a-zA-Z]{2,3} ')
390 self.channel_pattern = re.compile('Channel:\d+ ')
391 self.accesspoint_pattren = re.compile('Access Point: .+')
392 self.bitrate_pattern = re.compile("Bit Rate[=:][\d.]{1,5} [GMgmb/s]{1,5}")
393 self.link_quality_pattern = re.compile('Link Quality=\d+/\d+')
394 self.signal_level_pattern = re.compile('Signal level=\d+/\d+')
395 self.noise_level_pattern = re.compile('Noise level=\d+/\d+')
396 self.signal_level_dbm_pattern = re.compile('Signal level=.+ dBm ')
397 self.noise_level_dbm_pattern = re.compile('Noise level=.+ dBm')
398 self.inet_addr_pattern = re.compile('inet addr:[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}')
400 def stopWlanConsole(self):
401 if self.getStatusConsole is not None:
402 if len(self.getStatusConsole.appContainers):
403 for x in self.getStatusConsole.appContainers.keys():
404 self.getStatusConsole.kill(x)
406 def getDataForInterface(self, iface, callback = None):
407 cmd = "iwconfig "+iface
408 self.getStatusConsole.ePopen(cmd, self.getStatusFinished, (callback, iface))
410 def getStatusFinished(self, result, retval, extra_args):
411 (callback, iface) = extra_args
412 if self.getStatusConsole is not None:
413 self.handleStatusData(result, retval, callback, iface)
415 def handleStatusData(self, result, retval, callback, iface):
427 if retval and result:
428 for x in result.split('\n'):
429 essid = search_pattern(x, self.essid_pattern, 'ESSID:').strip('"') or essid
430 frequency = search_pattern(x, self.frequency_pattern, 'Frequency:') or frequency
431 channel = search_pattern(x, self.channel_pattern, 'Channel:') or channel
432 accesspoint = search_pattern(x, self.accesspoint_pattren, 'Access Point: ') or accesspoint
433 bitrate = search_pattern(x, self.bitrate_pattern, ['Bit Rate:', 'Bit Rate=']) or bitrate
434 link_quality = search_pattern(x, self.link_quality_pattern, 'Link Quality=') or link_quality
435 signal_level = search_pattern(x, self.signal_level_pattern, 'Signal level=') or signal_level
436 noise_level = search_pattern(x, self.noise_level_pattern, 'Noise level=') or noise_level
437 signal_level = search_pattern(x, self.signal_level_dbm_pattern, 'Signal level=') or signal_level
438 noise_level = search_pattern(x, self.noise_level_dbm_pattern, 'Noise level=') or noise_level
442 data[iface]["essid"] = essid
443 data[iface]["frequency"] = frequency
444 data[iface]["channel"] = channel
445 data[iface]["accesspoint"] = accesspoint
446 data[iface]["bitrate"] = bitrate
447 data[iface]["link_quality"] = link_quality
448 data[iface]["signal_level"] = signal_level
449 data[iface]["noise_level"] = noise_level
451 self.getIfconfigData(iface, data, callback)
454 # callback(retval, data)
456 def getIfconfigData(self, iface, data, callback):
457 cmd = "ifconfig "+iface
458 self.getStatusConsole.ePopen(cmd, self.getIfconfigDataFinished, (iface, data, callback))
460 def getIfconfigDataFinished(self, result, retval, extra_args):
461 if self.getStatusConsole is not None:
462 self.handleIfconfigData(result, retval, extra_args)
464 def handleIfconfigData(self, result, retval, extra_args):
465 (iface, data, callback) = extra_args
469 if retval and result:
470 for x in result.split('\n'):
471 ipaddr = search_pattern(x, self.inet_addr_pattern, 'inet addr:') or ipaddr
473 data[iface]["ip_addr"] = ipaddr
476 callback(retval, data)
478 iStatus = wlanStatus()