1 from Screens.Screen import Screen
2 from Components.ConfigList import ConfigListScreen, ConfigList
3 from Components.config import config, ConfigSubsection, getConfigListEntry, ConfigSelection, ConfigIP, ConfigInteger
4 from Components.config import ConfigText, ConfigYesNo, NoSave, ConfigPassword, ConfigNothing, ConfigSequence
5 from Components.ActionMap import ActionMap
6 from Screens.MessageBox import MessageBox
7 from Screens.Standby import TryQuitMainloop
8 from Components.Sources.StaticText import StaticText
9 from Plugins.Plugin import PluginDescriptor
10 from Tools.Directories import fileExists
11 from math import pow as math_pow
12 from Components.Network import iNetwork
13 from Components.PluginComponent import plugins
14 from Components.Console import Console
15 from os import path as os_path, system as os_system, listdir, makedirs, access, R_OK
16 from Tools.Directories import resolveFilename, SCOPE_PLUGINS
17 from enigma import eTimer
20 def printDebugMsg(msg):
23 print "[Wireless Access Point] ", msg
26 def __init__(self, value = ""):
29 ORIG_HOSTAPD_CONF = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/WirelessAccessPoint/hostapd.conf.orig")
30 HOSTAPD_CONF = "/etc/hostapd.conf"
31 HOSTAPD_CONF_BACK = "/etc/hostapd.conf.linuxap.back"
33 apModeConfig = ConfigSubsection()
34 apModeConfig.useap = ConfigYesNo(default = False)
35 apModeConfig.setupmode = ConfigSelection(default = "simple", choices = [ ("simple", "Simple"), ("advanced", "Advanced") ] )
36 #apModeConfig.wirelessdevice = fixedValue(value = "")
37 apModeConfig.branch = fixedValue(value = "br0")
38 apModeConfig.driver = fixedValue(value = "nl80211")
39 apModeConfig.wirelessmode = ConfigSelection(default = "g", choices = [ ("b", "802.11b"), ("a", "802.11a"), ("g", "802.11g") ] )
40 apModeConfig.channel = ConfigInteger(default = 1, limits = (1,13) )
41 apModeConfig.ssid = ConfigText(default = "Vuplus AP", visible_width = 50, fixed_size = False)
42 apModeConfig.beacon = ConfigInteger(default = 100, limits = (15,65535))
43 apModeConfig.rts_threshold = ConfigInteger(default = 2347, limits = (0,2347) )
44 apModeConfig.fragm_threshold = ConfigInteger(default = 2346, limits = (256,2346) )
45 apModeConfig.preamble = ConfigSelection(default = "0", choices = [ ("0", "Long"), ("1", "Short") ] )
46 apModeConfig.ignore_broadcast_ssid = ConfigSelection(default = "0", choices = [ ("0", _("disabled")), ("1", _("enabled")) ])
48 apModeConfig.encrypt = ConfigYesNo(default = False)
49 apModeConfig.method = ConfigSelection(default = "0", choices = [
50 ("0", _("WEP")), ("1", _("WPA")), ("2", _("WPA2")),("3", _("WPA/WPA2"))])
51 apModeConfig.wep = ConfigYesNo(default = False)
52 #apModeConfig.wep_default_key = ConfigSelection(default = "0", choices = [ ("0", "0"), ("1", "1"), ("2", "2"), ("3", "3") ] )
53 apModeConfig.wep_default_key = fixedValue(value = "0")
54 apModeConfig.wepType = ConfigSelection(default = "64", choices = [
55 ("64", _("Enable 64 bit (Input 10 hex keys)")), ("128", _("Enable 128 bit (Input 26 hex keys)"))])
56 apModeConfig.wep_key0 = ConfigPassword(default = "", visible_width = 50, fixed_size = False)
57 apModeConfig.wpa = ConfigSelection(default = "0", choices = [
58 ("0", _("not set")), ("1", _("WPA")), ("2", _("WPA2")),("3", _("WPA/WPA2"))])
59 apModeConfig.wpa_passphrase = ConfigPassword(default = "", visible_width = 50, fixed_size = False)
60 apModeConfig.wpagrouprekey = ConfigInteger(default = 600, limits = (0,3600))
61 apModeConfig.wpa_key_mgmt = fixedValue(value = "WPA-PSK")
62 apModeConfig.wpa_pairwise = fixedValue(value = "TKIP CCMP")
63 apModeConfig.rsn_pairwise = fixedValue(value = "CCMP")
65 apModeConfig.usedhcp = ConfigYesNo(default=False)
66 apModeConfig.address = ConfigIP(default = [0,0,0,0])
67 apModeConfig.netmask = ConfigIP(default = [255,0,0,0])
68 apModeConfig.gateway = ConfigIP(default = [0,0,0,0])
69 apModeConfig.nameserver = ConfigIP(default = [0,0,0,0])
71 class WirelessAccessPoint(Screen,ConfigListScreen):
73 <screen position="center,center" size="590,450" title="Wireless Access Point" >
74 <ePixmap pixmap="skin_default/buttons/red.png" position="20,0" size="140,40" alphatest="on" />
75 <ePixmap pixmap="skin_default/buttons/green.png" position="160,0" size="140,40" alphatest="on" />
76 <ePixmap pixmap="skin_default/buttons/yellow.png" position="300,0" size="140,40" alphatest="on" />
77 <ePixmap pixmap="skin_default/buttons/blue.png" position="440,0" size="140,40" alphatest="on" />
79 <widget source="key_red" render="Label" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" />
80 <widget source="key_green" render="Label" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" />
81 <widget source="key_yellow" render="Label" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" />
82 <widget source="key_blue" render="Label" position="440,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" />
84 <widget name="config" zPosition="2" position="20,70" size="550,270" scrollbarMode="showOnDemand" transparent="1" />
85 <widget source="current_settings" render="Label" position="10,340" size="570,20" font="Regular;19" halign="center" valign="center" transparent="1" />
86 <widget source="IPAddress_text" render="Label" position="130,370" size="190,21" font="Regular;19" transparent="1" />
87 <widget source="Netmask_text" render="Label" position="130,395" size="190,21" font="Regular;19" transparent="1" />
88 <widget source="Gateway_text" render="Label" position="130,420" size="190,21" font="Regular;19" transparent="1" />
89 <widget source="IPAddress" render="Label" position="340,370" size="240,21" font="Regular;19" transparent="1" />
90 <widget source="Netmask" render="Label" position="340,395" size="240,21" font="Regular;19" transparent="1" />
91 <widget source="Gateway" render="Label" position="340,420" size="240,21" font="Regular;19" transparent="1" />
94 def __init__(self,session):
95 Screen.__init__(self,session)
96 self.session = session
97 self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ],
99 "ok": self.doConfigMsg,
100 "cancel": self.keyCancel,
101 "red": self.keyCancel,
102 "green": self.doConfigMsg,
105 ConfigListScreen.__init__(self, self.list,session = self.session)
106 self["key_red"] = StaticText(_("Cancel"))
107 self["key_green"] = StaticText(_("Ok"))
108 self["key_yellow"] = StaticText(_(" "))
109 self["key_blue"] = StaticText(_(" "))
110 self["current_settings"] = StaticText(_("Current settings (interface : br0)"))
111 self["IPAddress_text"] = StaticText(_("IP Address"))
112 self["Netmask_text"] = StaticText(_("Netmask"))
113 self["Gateway_text"] = StaticText(_("Gateway"))
114 self["IPAddress"] = StaticText(_("N/A"))
115 self["Netmask"] = StaticText(_("N/A"))
116 self["Gateway"] = StaticText(_("N/A"))
119 self.apModeChanged = False
121 self.onClose.append(self.__onClose)
122 self.onLayoutFinish.append(self.currentNetworkSettings)
123 self.onLayoutFinish.append(self.checkConfigError)
125 self.configErrorTimer = eTimer()
126 self.configErrorTimer.callback.append(self.configErrorMsg)
128 self.configStartMsg = None
130 def makeConfig(self):
132 if self.checkWirelessDevices():
135 self.checkRunHostapd()
136 self.makeConfigList()
137 self.loadInterfacesConfig()
138 self.loadHostapConfig()
139 self.setupCurrentEncryption()
140 self.createConfigEntry()
143 def checkConfigError(self):
145 self.configErrorTimer.start(100, True)
147 def configErrorMsg(self):
148 self.session.openWithCallback(self.close ,MessageBox, _(self.msg), MessageBox.TYPE_ERROR)
150 def checkwlanDeviceList(self):
151 if len(self.wlanDeviceList) == 0:
152 self.checkwlanDeviceListTimer.start(100,True)
154 def currentNetworkSettings(self):
155 self["IPAddress"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "ip")))
156 self["Netmask"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "netmask")))
157 self["Gateway"].setText(self.formatAddr(iNetwork.getAdapterAttribute("br0", "gateway")))
159 def formatAddr(self, address = [0,0,0,0]):
162 return "%d:%d:%d:%d"%(address[0],address[1],address[2],address[3])
164 def checkRunHostapd(self):
166 if fileExists("/var/run/hostapd", 0):
167 apModeConfig.useap.value = True
169 def checkWirelessDevices(self):
171 self.wlanDeviceList = []
173 for x in iNetwork.getInstalledAdapters():
174 if x.startswith('eth') or x.startswith('br') or x.startswith('mon'):
176 elif os_path.exists("/tmp/bcm/%s"%x):
179 description=self.getAdapterDescription(x)
180 if description == "Unknown network adapter":
181 self.wlanDeviceList.append((x, x))
183 self.wlanDeviceList.append(( x, description + " (%s)"%x ))
185 if len(self.wlanDeviceList) == 0:
186 self.msg = "Can not find wireless lan devices that support AP mode."
189 apModeConfig.wirelessdevice = ConfigSelection( choices = self.wlanDeviceList )
192 def makeConfigList(self):
194 self.hostapdConf = {}
195 self.hostapdConf["interface"] = apModeConfig.wirelessdevice
196 self.hostapdConf["bridge"] = apModeConfig.branch # "br0"
197 self.hostapdConf["driver"] = apModeConfig.driver # "nl80211"
198 self.hostapdConf["hw_mode"] = apModeConfig.wirelessmode
199 self.hostapdConf["channel"] = apModeConfig.channel
200 self.hostapdConf["ssid"] = apModeConfig.ssid
201 self.hostapdConf["beacon_int"] = apModeConfig.beacon
202 self.hostapdConf["rts_threshold"] = apModeConfig.rts_threshold
203 self.hostapdConf["fragm_threshold"] = apModeConfig.fragm_threshold
204 self.hostapdConf["preamble"] = apModeConfig.preamble
205 # self.hostapdConf["macaddr_acl"] = "" # fix to add Access Control List Editer
206 # self.hostapdConf["accept_mac_file"] = "" # fix to add Access Control List Editer
207 # self.hostapdConf["deny_mac_file"] = "" # fix to add Access Control List Editer
208 self.hostapdConf["ignore_broadcast_ssid"] = apModeConfig.ignore_broadcast_ssid
209 # self.hostapdConf["wmm_enabled"] = ""
210 # self.hostapdConf["ieee80211n"] = ""
211 # self.hostapdConf["ht_capab"] = ""
212 self.hostapdConf["wep_default_key"] = apModeConfig.wep_default_key
213 self.hostapdConf["wep_key0"] = apModeConfig.wep_key0
214 self.hostapdConf["wpa"] = apModeConfig.wpa
215 self.hostapdConf["wpa_passphrase"] = apModeConfig.wpa_passphrase
216 self.hostapdConf["wpa_key_mgmt"] = apModeConfig.wpa_key_mgmt # "WPA-PSK"
217 self.hostapdConf["wpa_pairwise"] = apModeConfig.wpa_pairwise # "TKIP CCMP"
218 self.hostapdConf["rsn_pairwise"] = apModeConfig.rsn_pairwise # "CCMP"
219 self.hostapdConf["wpa_group_rekey"] = apModeConfig.wpagrouprekey
221 def loadInterfacesConfig(self):
224 fp = file('/etc/network/interfaces', 'r')
225 datas = fp.readlines()
228 printDebugMsg("Read failed, /etc/network/interfaces.")
234 split = line.strip().split(' ')
235 if (split[0] == "iface"):
236 current_iface = split[1]
238 if (current_iface == "br0" or current_iface == "eth0"):
239 if (len(split) == 4 and split[3] == "dhcp"):
240 apModeConfig.usedhcp.value = True
241 if (split[0] == "address"):
242 apModeConfig.address.value = map(int, split[1].split('.'))
243 if (split[0] == "netmask"):
244 apModeConfig.netmask.value = map(int, split[1].split('.'))
245 if (split[0] == "gateway"):
246 apModeConfig.gateway.value = map(int, split[1].split('.'))
247 if (split[0] == "dns-nameservers"):
248 apModeConfig.nameserver.value = map(int, split[1].split('.'))
250 printDebugMsg("Parsing failed, /etc/network/interfaces.")
255 def setupCurrentEncryption(self):
257 if len(apModeConfig.wep_key0.value) > 10:
258 apModeConfig.wepType.value = "128"
260 if apModeConfig.wpa.value is not "0" and apModeConfig.wpa_passphrase.value: # (1,WPA), (2,WPA2), (3,WPA/WPA2)
261 apModeConfig.encrypt.value = True
262 apModeConfig.method.value = apModeConfig.wpa.value
263 elif apModeConfig.wep.value and apModeConfig.wep_key0.value:
264 apModeConfig.encrypt.value = True
265 apModeConfig.method.value = "0" # wep
267 apModeConfig.encrypt.value = False
269 def createConfigEntry(self):
272 self.useApEntry = getConfigListEntry(_("Use AP Mode"), apModeConfig.useap)
273 self.setupModeEntry = getConfigListEntry(_("Setup Mode"), apModeConfig.setupmode)
274 self.wirelessDeviceEntry = getConfigListEntry(_("AP Device"), apModeConfig.wirelessdevice)
275 self.wirelessModeEntry = getConfigListEntry(_("AP Mode"), apModeConfig.wirelessmode)
276 self.channelEntry = getConfigListEntry(_("Channel (1~13)"), apModeConfig.channel)
277 self.ssidEntry = getConfigListEntry(_("SSID (1~32 Characters)"), apModeConfig.ssid)
278 self.beaconEntry = getConfigListEntry(_("Beacon (15~65535)"), apModeConfig.beacon)
279 self.rtsThresholdEntry = getConfigListEntry(_("RTS Threshold (0~2347)"), apModeConfig.rts_threshold)
280 self.fragmThresholdEntry = getConfigListEntry(_("FRAGM Threshold (256~2346)"), apModeConfig.fragm_threshold)
281 self.prambleEntry = getConfigListEntry(_("Preamble"), apModeConfig.preamble)
282 self.ignoreBroadcastSsid = getConfigListEntry(_("Ignore Broadcast SSID"), apModeConfig.ignore_broadcast_ssid)
284 self.encryptEntry = getConfigListEntry(_("Encrypt"), apModeConfig.encrypt)
285 self.methodEntry = getConfigListEntry(_("Method"), apModeConfig.method)
286 self.wepKeyTypeEntry = getConfigListEntry(_("KeyType"), apModeConfig.wepType)
287 self.wepKey0Entry = getConfigListEntry(_("WEP Key (HEX)"), apModeConfig.wep_key0)
288 self.wpaKeyEntry = getConfigListEntry(_("KEY (8~63 Characters)"), apModeConfig.wpa_passphrase)
289 self.groupRekeyEntry = getConfigListEntry(_("Group Rekey Interval"), apModeConfig.wpagrouprekey)
291 self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), apModeConfig.usedhcp)
292 self.ipEntry = getConfigListEntry(_("IP Address"), apModeConfig.address)
293 self.netmaskEntry = getConfigListEntry(_("NetMask"), apModeConfig.netmask)
294 self.gatewayEntry = getConfigListEntry(_("Gateway"), apModeConfig.gateway)
295 self.nameserverEntry = getConfigListEntry(_("Nameserver"), apModeConfig.nameserver)
297 def createConfig(self):
299 apModeConfig.address.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "ip") or [0,0,0,0]
300 apModeConfig.netmask.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "netmask") or [255,0,0,0]
301 apModeConfig.gateway.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "gateway") or [0,0,0,0]
304 self.configList.append( self.useApEntry )
305 if apModeConfig.useap.value is True:
306 self.configList.append( self.setupModeEntry )
307 self.configList.append( self.wirelessDeviceEntry )
308 self.configList.append( self.wirelessModeEntry )
309 self.configList.append( self.channelEntry )
310 self.configList.append( self.ssidEntry )
311 if apModeConfig.setupmode.value is "advanced":
312 self.configList.append( self.beaconEntry )
313 self.configList.append( self.rtsThresholdEntry )
314 self.configList.append( self.fragmThresholdEntry )
315 self.configList.append( self.prambleEntry )
316 self.configList.append( self.ignoreBroadcastSsid )
317 self.configList.append( self.encryptEntry )
318 if apModeConfig.encrypt.value is True:
319 self.configList.append( self.methodEntry )
320 if apModeConfig.method.value is "0": # wep
321 self.configList.append( self.wepKeyTypeEntry )
322 self.configList.append( self.wepKey0Entry )
324 self.configList.append( self.wpaKeyEntry )
325 if apModeConfig.setupmode.value is "advanced":
326 self.configList.append( self.groupRekeyEntry )
327 ## set network interfaces
328 self.configList.append( self.usedhcpEntry )
329 if apModeConfig.usedhcp.value is False:
330 self.configList.append( self.ipEntry )
331 self.configList.append( self.netmaskEntry )
332 self.configList.append( self.gatewayEntry )
333 self.configList.append( self.nameserverEntry )
334 self["config"].list = self.configList
335 self["config"].l.setList(self.configList)
338 ConfigListScreen.keyLeft(self)
342 ConfigListScreen.keyRight(self)
346 if self["config"].getCurrent() in [ self.encryptEntry, self.methodEntry, self.useApEntry, self.usedhcpEntry, self.setupModeEntry]:
349 # 0 : legacy module activated, 1 : kernel module activated, -1 : None
350 def checkProcModules(self):
351 proc_path = "/proc/modules"
352 legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta")
353 kernel_modules = ("rt2800usb", "rt2800lib")
355 fd = open(proc_path, "r")
356 data = fd.readlines()
360 module = line.split()[0].strip()
361 if module in legacy_modules:
363 elif module in kernel_modules:
368 def isRalinkModule(self):
370 iface = apModeConfig.wirelessdevice.value
372 # check vendor ID for lagacy driver
373 vendorID = "148f" # ralink vendor ID
374 idVendorPath = "/sys/class/net/%s/device/idVendor" % iface
375 if access(idVendorPath, R_OK):
376 fd = open(idVendorPath, "r")
377 data = fd.read().strip()
380 printDebugMsg("Vendor ID : %s" % data)
385 # check sys driver path for kernel driver
386 ralinkKmod = "rt2800usb" # ralink kernel driver name
387 driverPath = "/sys/class/net/%s/device/driver/" % iface
388 if os_path.exists(driverPath):
389 driverName = os_path.basename(os_path.realpath(driverPath))
391 printDebugMsg("driverName : %s" % driverName)
393 if driverName == ralinkKmod:
398 def doConfigMsg(self):
400 msg = "Are you sure you want to setup AP?\n"
402 isRainkIface = self.isRalinkModule()
403 isApMode = apModeConfig.useap.value is True
404 isRalinkKmodUploaded = self.checkProcModules() == 1
406 if isRainkIface and isApMode and (not isRalinkKmodUploaded ):
407 msg += "( STB should be reboot to enable AP mode. )\n"
410 self.session.openWithCallback(self.doConfig, MessageBox, (_(msg) ) )
412 def doConfig(self, ret = False):
416 if apModeConfig.useap.value is True and apModeConfig.encrypt.value is True:
417 if not self.checkEncrypKey():
419 if not self.checkConfig():
422 self.configStartMsg = self.session.openWithCallback(self.ConfigFinishedMsg, MessageBox, _("Please wait for AP Configuration....\n") , type = MessageBox.TYPE_INFO, enable_input = False)
424 if apModeConfig.useap.value is True:
425 self.networkRestart( nextFunc = self.makeConf )
427 self.networkRestart( nextFunc = self.removeConf )
429 def checkEncrypKey(self):
431 if apModeConfig.method.value == "0":
432 if self.checkWep(apModeConfig.wep_key0.value) is False:
433 self.session.open(MessageBox, _("Invalid WEP key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10 )
437 if not len(apModeConfig.wpa_passphrase.value) in range(8,65):
438 self.session.open(MessageBox, _("Invalid WPA key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
443 def checkWep(self, key):
448 elif apModeConfig.wepType.value == "64" and length == 10:
450 elif apModeConfig.wepType.value == "128" and length == 26:
455 def checkConfig(self):
458 if len(apModeConfig.ssid.value) == 0 or len(apModeConfig.ssid.value) > 32:
459 self.session.open(MessageBox, _("Invalid SSID\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
461 elif apModeConfig.channel.value not in range(1,14):
462 self.session.open(MessageBox, _("Invalid channel\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
464 elif apModeConfig.beacon.value < 15 or apModeConfig.beacon.value > 65535:
465 self.session.open(MessageBox, _("Invalid beacon\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
467 elif apModeConfig.rts_threshold.value < 0 or apModeConfig.rts_threshold.value > 2347:
468 self.session.open(MessageBox, _("Invalid RTS Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
470 elif apModeConfig.fragm_threshold.value < 256 or apModeConfig.fragm_threshold.value > 2346:
471 self.session.open(MessageBox, _("Invalid Fragm Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
473 elif apModeConfig.wpagrouprekey.value < 0 or apModeConfig.wpagrouprekey.value > 3600:
474 self.session.open(MessageBox, _("Invalid wpagrouprekey\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
478 def networkRestart(self, nextFunc = None ):
479 self.networkRestart_stop( nextFunc = nextFunc )
481 def networkRestart_stop(self, nextFunc = None ):
482 printDebugMsg("networkRestart_stop")
483 self.msgPlugins(False)
484 self.commands = [] # stop current network
485 self.networkRestartConsole = Console()
486 self.commands.append("/etc/init.d/avahi-daemon stop")
487 for iface in iNetwork.getAdapterList():
488 if iface != 'eth0' or not iNetwork.onRemoteRootFS():
489 self.commands.append("ifdown " + iface)
490 self.commands.append("ip addr flush dev " + iface)
491 self.commands.append("/etc/init.d/hostapd stop")
492 self.commands.append("/etc/init.d/networking stop")
493 self.commands.append("killall -9 udhcpc")
494 self.commands.append("rm /var/run/udhcpc*")
495 self.networkRestartConsole.eBatch(self.commands, nextFunc, debug = True)
497 def makeConf(self,extra_args):
498 printDebugMsg("makeConf")
499 self.writeNetworkInterfaces()
500 result = self.writeHostapdConfig()
502 self.configStartMsg.close(False)
503 self.configErrorTimer.start(100, True)
506 self.networkRestart_start()
508 def removeConf(self,extra_args):
510 printDebugMsg("removeConf")
511 if fileExists("/etc/hostapd.conf", 'f'):
512 os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back")
513 fp = file("/etc/network/interfaces", 'w')
514 fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n")
515 fp.write("auto lo\n")
516 fp.write("iface lo inet loopback\n\n")
518 fp.write("auto eth0\n")
519 if apModeConfig.usedhcp.value is True:
520 fp.write("iface eth0 inet dhcp\n")
522 fp.write("iface eth0 inet static\n")
523 fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) )
524 fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) )
525 fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) )
526 fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value) )
529 self.networkRestart_start()
531 def networkRestart_start(self):
533 printDebugMsg("networkRestart_start")
534 self.restartConsole = Console()
536 self.commands.append("/etc/init.d/networking start")
537 self.commands.append("/etc/init.d/avahi-daemon start")
538 if apModeConfig.useap.value is True:
539 self.commands.append("/etc/init.d/hostapd start")
540 self.restartConsole.eBatch(self.commands, self.networkRestartFinished, debug=True)
542 def networkRestartFinished(self, data):
543 printDebugMsg("networkRestartFinished")
545 iNetwork.getInterfaces(self.getInterfacesDataAvail)
547 def getInterfacesDataAvail(self, data):
548 self.blacklist_legacy_drivers()
549 if data is True and self.configStartMsg is not None:
550 self.configStartMsg.close(True)
552 def ConfigFinishedMsg(self, ret):
554 self.session.openWithCallback(self.ConfigFinishedMsgCallback ,MessageBox, _("Configuration your AP is finished"), type = MessageBox.TYPE_INFO, timeout = 5, default = False)
556 def needRalinkKmod(self):
558 isRainkIface = self.isRalinkModule()
559 ApMode = apModeConfig.useap.value is True
561 if isRainkIface and ApMode:
566 def ConfigFinishedMsgCallback(self,data):
567 isRalinkKmodUploaded = self.checkProcModules() == 1
568 needRalinkKmod_ = self.needRalinkKmod()
570 if needRalinkKmod_ : # ralink device is activated in AP Mode.
571 if not isRalinkKmodUploaded : # reboot to loading kernel module.
572 msg = "You should now reboot your STB in order to ralink device operate in AP mode.\n\nReboot now ?\n\n"
573 self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type = MessageBox.TYPE_YESNO, default = True )
576 elif isRalinkKmodUploaded :
577 msg = "You should now reboot your STB to better performance of ralink device in STA mode.\n\nReboot now ?\n\n"
578 self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type = MessageBox.TYPE_YESNO, default = True )
582 def blacklist_legacy_drivers(self):
583 blacklist_conf_dir = "/etc/modprobe.d"
584 blacklist_conf_file = blacklist_conf_dir + "/blacklist-wlan.conf"
585 legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta")
586 kernel_modules = ("rt2800usb", "rt2800lib")
589 need_ralink_kmod = self.needRalinkKmod()
591 if access(blacklist_conf_file, R_OK) is True:
592 fd = open(blacklist_conf_file, "r")
596 if need_ralink_kmod: # check legacy modules in blacklist
597 for mod in legacy_modules:
598 if data.find(mod) != -1: return
600 for mod in kernel_modules: # check kernel modules in blacklist
601 if data.find(mod) != -1: return
603 if not os_path.exists(blacklist_conf_dir):
604 makedirs(blacklist_conf_dir)
607 blacklist_modules = legacy_modules
609 blacklist_modules = kernel_modules
611 for module in blacklist_modules:
612 blacklist += "blacklist %s\n" % module
613 f = open(blacklist_conf_file, "w+")
616 self.apModeChanged = True
618 def doReboot(self, res):
620 self.session.open(TryQuitMainloop, 2)
624 def msgPlugins(self,reason = False):
625 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
628 def writeNetworkInterfaces(self):
630 fp = file("/etc/network/interfaces", 'w')
631 fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n")
632 fp.write("auto lo\n")
633 fp.write("iface lo inet loopback\n\n")
635 fp.write("auto eth0\n")
636 fp.write("iface eth0 inet manual\n")
637 fp.write(" up ip link set $IFACE up\n")
638 fp.write(" down ip link set $IFACE down\n\n")
640 fp.write("auto br0\n")
641 if apModeConfig.usedhcp.value is True:
642 fp.write("iface br0 inet dhcp\n")
644 fp.write("iface br0 inet static\n")
645 fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) )
646 fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) )
647 fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) )
648 fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value) )
649 fp.write(" pre-up brctl addbr br0\n")
650 fp.write(" pre-up brctl addif br0 eth0\n")
651 fp.write(" post-down brctl delif br0 eth0\n")
652 fp.write(" post-down brctl delbr br0\n\n")
656 def setIpForward(self, setValue = 0):
657 ipForwardFilePath = "/proc/sys/net/ipv4/ip_forward"
658 if not fileExists(ipForwardFilePath):
660 printDebugMsg("set %s to %d" % (ipForwardFilePath, setValue))
661 f = open(ipForwardFilePath, "w")
662 f.write("%d" % setValue)
664 sysctlPath = "/etc/sysctl.conf"
666 if fileExists(sysctlPath):
667 fp = file(sysctlPath, "r")
668 sysctlLines = fp.readlines()
671 for line in sysctlLines:
674 (key,value) = line.split("=")
679 sysctlList[key] = value
680 sysctlList["net.ipv4.ip_forward"] = str(setValue)
681 fp = file(sysctlPath, "w")
682 for (key,value) in sysctlList.items():
683 fp.write("%s=%s\n"%(key,value))
687 def getAdapterDescription(self, iface):
688 classdir = "/sys/class/net/" + iface + "/device/"
689 driverdir = "/sys/class/net/" + iface + "/device/driver/"
690 if os_path.exists(classdir):
691 files = listdir(classdir)
692 if 'driver' in files:
693 if os_path.realpath(driverdir).endswith('rtw_usb_drv'):
694 return _("Realtek")+ " " + _("WLAN adapter.")
695 elif os_path.realpath(driverdir).endswith('ath_pci'):
696 return _("Atheros")+ " " + _("WLAN adapter.")
697 elif os_path.realpath(driverdir).endswith('zd1211b'):
698 return _("Zydas")+ " " + _("WLAN adapter.")
699 elif os_path.realpath(driverdir).endswith('rt73'):
700 return _("Ralink")+ " " + _("WLAN adapter.")
701 elif os_path.realpath(driverdir).endswith('rt73usb'):
702 return _("Ralink")+ " " + _("WLAN adapter.")
704 return str(os_path.basename(os_path.realpath(driverdir))) + " " + _("WLAN adapter")
706 return _("Unknown network adapter")
708 return _("Unknown network adapter")
712 for x in self["config"].list:
714 apModeConfig.wpa.value = "0"
715 apModeConfig.wep.value = False
720 def printConfigList(self, confList):
721 printDebugMsg("== printConfigList ==");
722 for (key, entry) in confList.items():
723 printDebugMsg("%s = %s"%(key , str(entry.value)));
725 printDebugMsg("== printConfigList end ==");
727 def loadHostapConfig(self):
730 if access("/etc/hostapd.conf", R_OK) is True:
731 printDebugMsg("open /etc/hostapd.conf")
732 fd = open("/etc/hostapd.conf", "r")
733 elif access("/etc/hostapd.conf.linuxap.back", R_OK) is True:
734 printDebugMsg("open /etc/hostapd.conf.linuxap.back")
735 fd = open("/etc/hostapd.conf.linuxap.back", "r")
737 printDebugMsg("can not open hostapd.conf")
740 for line in fd.readlines():
743 if (len(line) == 0) or (line.find('=') == -1):
746 data = line.split('=', 1)
750 key = data[0].strip()
751 value = data[1].strip()
753 if key == "#wep_key0":
754 self.hostapdConf["wep_key0"].value = value
755 apModeConfig.wep.value = False
757 elif key == "wep_key0":
758 self.hostapdConf["wep_key0"].value = value
759 apModeConfig.wep.value = True
761 elif key.startswith('#'):
764 elif key == "channel" :
765 if int(value) not in range(14):
766 self.hostapdConf[key].value = 1
768 self.hostapdConf[key].value = int(value)
770 elif key in ["beacon_int", "rts_threshold", "fragm_threshold", "wpa_group_rekey"]:
771 self.hostapdConf[key].value = int(value)
773 elif key in self.hostapdConf.keys():
774 self.hostapdConf[key].value = value
777 self.printConfigList(self.hostapdConf)
781 def writeHostapdConfig(self):
783 global ORIG_HOSTAPD_CONF
784 self.printConfigList(self.hostapdConf)
785 if access(ORIG_HOSTAPD_CONF, R_OK) is not True:
786 self.msg = "can not access file. (%s)" % ORIG_HOSTAPD_CONF
787 printDebugMsg(self.msg)
790 orig_conf = open(ORIG_HOSTAPD_CONF, "r")
792 print "can't open file. (%s)" % ORIG_HOSTAPD_CONF
794 new_conf = open(HOSTAPD_CONF, "w")
796 print "can't open file. (%s)" % HOSTAPD_CONF
798 isEncryptOn = apModeConfig.encrypt.value is True
799 isEncryptWEP = apModeConfig.method.value == "0"
800 isEncryptWPA = not isEncryptWEP
802 for r_line in orig_conf.readlines():
803 line = r_line.strip()
805 new_conf.write(r_line)
810 if line.find("wep_default_key=") != -1 : # is wepLine
811 if isEncryptOn and isEncryptWEP :
812 fix_line = "wep_default_key=%s\n" % self.hostapdConf["wep_default_key"].value
814 elif line.find("wep_key0=") != -1 : # is WepKeyLine
817 fix_line = "wep_key0=%s\n" % self.hostapdConf["wep_key0"].value
819 fix_line = "#wep_key0=%s\n" % self.hostapdConf["wep_key0"].value
822 fix_line = "#wep_key0=%s\n" % self.hostapdConf["wep_key0"].value
824 elif line.find("wpa=") != -1 : # is wpaLine
825 if isEncryptOn and isEncryptWPA :
826 fix_line = "wpa=%s\n" % apModeConfig.method.value
828 elif line.startswith("#ssid"):
832 for (key , entry) in self.hostapdConf.items():
833 value = str(entry.value)
834 pos = line.find(key+'=')
835 if ( (pos != -1) and (pos < 2) ) and len(value)!=0 :
836 fix_line = "%s=%s\n" % (key, value)
839 # if fix_line is not None:
840 # print "r_line : ", r_line,
841 # print "fix_li : ", fix_line
843 if fix_line is not None:
844 new_conf.write(fix_line)
846 new_conf.write(r_line)
852 def main(session, **kwargs):
853 session.open(WirelessAccessPoint)
855 def Plugins(**kwargs):
856 return [PluginDescriptor(name=_("Wireless Access Point"), description=_("Using a Wireless module as access point."), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = True, fnc=main)]