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'):
177 description=self.getAdapterDescription(x)
178 if description == "Unknown network adapter":
179 self.wlanDeviceList.append((x, x))
181 self.wlanDeviceList.append(( x, description + " (%s)"%x ))
183 if len(self.wlanDeviceList) == 0:
184 self.msg = "Wireless Lan Device is not detected."
187 apModeConfig.wirelessdevice = ConfigSelection( choices = self.wlanDeviceList )
190 def makeConfigList(self):
192 self.hostapdConf = {}
193 self.hostapdConf["interface"] = apModeConfig.wirelessdevice
194 self.hostapdConf["bridge"] = apModeConfig.branch # "br0"
195 self.hostapdConf["driver"] = apModeConfig.driver # "nl80211"
196 self.hostapdConf["hw_mode"] = apModeConfig.wirelessmode
197 self.hostapdConf["channel"] = apModeConfig.channel
198 self.hostapdConf["ssid"] = apModeConfig.ssid
199 self.hostapdConf["beacon_int"] = apModeConfig.beacon
200 self.hostapdConf["rts_threshold"] = apModeConfig.rts_threshold
201 self.hostapdConf["fragm_threshold"] = apModeConfig.fragm_threshold
202 self.hostapdConf["preamble"] = apModeConfig.preamble
203 # self.hostapdConf["macaddr_acl"] = "" # fix to add Access Control List Editer
204 # self.hostapdConf["accept_mac_file"] = "" # fix to add Access Control List Editer
205 # self.hostapdConf["deny_mac_file"] = "" # fix to add Access Control List Editer
206 self.hostapdConf["ignore_broadcast_ssid"] = apModeConfig.ignore_broadcast_ssid
207 # self.hostapdConf["wmm_enabled"] = ""
208 # self.hostapdConf["ieee80211n"] = ""
209 # self.hostapdConf["ht_capab"] = ""
210 self.hostapdConf["wep_default_key"] = apModeConfig.wep_default_key
211 self.hostapdConf["wep_key0"] = apModeConfig.wep_key0
212 self.hostapdConf["wpa"] = apModeConfig.wpa
213 self.hostapdConf["wpa_passphrase"] = apModeConfig.wpa_passphrase
214 self.hostapdConf["wpa_key_mgmt"] = apModeConfig.wpa_key_mgmt # "WPA-PSK"
215 self.hostapdConf["wpa_pairwise"] = apModeConfig.wpa_pairwise # "TKIP CCMP"
216 self.hostapdConf["rsn_pairwise"] = apModeConfig.rsn_pairwise # "CCMP"
217 self.hostapdConf["wpa_group_rekey"] = apModeConfig.wpagrouprekey
219 def loadInterfacesConfig(self):
222 fp = file('/etc/network/interfaces', 'r')
223 datas = fp.readlines()
226 printDebugMsg("Read failed, /etc/network/interfaces.")
232 split = line.strip().split(' ')
233 if (split[0] == "iface"):
234 current_iface = split[1]
236 if (current_iface == "br0" or current_iface == "eth0"):
237 if (len(split) == 4 and split[3] == "dhcp"):
238 apModeConfig.usedhcp.value = True
239 if (split[0] == "address"):
240 apModeConfig.address.value = map(int, split[1].split('.'))
241 if (split[0] == "netmask"):
242 apModeConfig.netmask.value = map(int, split[1].split('.'))
243 if (split[0] == "gateway"):
244 apModeConfig.gateway.value = map(int, split[1].split('.'))
245 if (split[0] == "dns-nameservers"):
246 apModeConfig.nameserver.value = map(int, split[1].split('.'))
248 printDebugMsg("Parsing failed, /etc/network/interfaces.")
253 def setupCurrentEncryption(self):
255 if len(apModeConfig.wep_key0.value) > 10:
256 apModeConfig.wepType.value = "128"
258 if apModeConfig.wpa.value is not "0" and apModeConfig.wpa_passphrase.value: # (1,WPA), (2,WPA2), (3,WPA/WPA2)
259 apModeConfig.encrypt.value = True
260 apModeConfig.method.value = apModeConfig.wpa.value
261 elif apModeConfig.wep.value and apModeConfig.wep_key0.value:
262 apModeConfig.encrypt.value = True
263 apModeConfig.method.value = "0" # wep
265 apModeConfig.encrypt.value = False
267 def createConfigEntry(self):
270 self.useApEntry = getConfigListEntry(_("Use AP Mode"), apModeConfig.useap)
271 self.setupModeEntry = getConfigListEntry(_("Setup Mode"), apModeConfig.setupmode)
272 self.wirelessDeviceEntry = getConfigListEntry(_("AP Device"), apModeConfig.wirelessdevice)
273 self.wirelessModeEntry = getConfigListEntry(_("AP Mode"), apModeConfig.wirelessmode)
274 self.channelEntry = getConfigListEntry(_("Channel (1~13)"), apModeConfig.channel)
275 self.ssidEntry = getConfigListEntry(_("SSID (1~32 Characters)"), apModeConfig.ssid)
276 self.beaconEntry = getConfigListEntry(_("Beacon (15~65535)"), apModeConfig.beacon)
277 self.rtsThresholdEntry = getConfigListEntry(_("RTS Threshold (0~2347)"), apModeConfig.rts_threshold)
278 self.fragmThresholdEntry = getConfigListEntry(_("FRAGM Threshold (256~2346)"), apModeConfig.fragm_threshold)
279 self.prambleEntry = getConfigListEntry(_("Preamble"), apModeConfig.preamble)
280 self.ignoreBroadcastSsid = getConfigListEntry(_("Ignore Broadcast SSID"), apModeConfig.ignore_broadcast_ssid)
282 self.encryptEntry = getConfigListEntry(_("Encrypt"), apModeConfig.encrypt)
283 self.methodEntry = getConfigListEntry(_("Method"), apModeConfig.method)
284 self.wepKeyTypeEntry = getConfigListEntry(_("KeyType"), apModeConfig.wepType)
285 self.wepKey0Entry = getConfigListEntry(_("WEP Key (HEX)"), apModeConfig.wep_key0)
286 self.wpaKeyEntry = getConfigListEntry(_("KEY (8~63 Characters)"), apModeConfig.wpa_passphrase)
287 self.groupRekeyEntry = getConfigListEntry(_("Group Rekey Interval"), apModeConfig.wpagrouprekey)
289 self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), apModeConfig.usedhcp)
290 self.ipEntry = getConfigListEntry(_("IP Address"), apModeConfig.address)
291 self.netmaskEntry = getConfigListEntry(_("NetMask"), apModeConfig.netmask)
292 self.gatewayEntry = getConfigListEntry(_("Gateway"), apModeConfig.gateway)
293 self.nameserverEntry = getConfigListEntry(_("Nameserver"), apModeConfig.nameserver)
295 def createConfig(self):
297 apModeConfig.address.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "ip") or [0,0,0,0]
298 apModeConfig.netmask.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "netmask") or [255,0,0,0]
299 apModeConfig.gateway.value = iNetwork.getAdapterAttribute(apModeConfig.branch.value, "gateway") or [0,0,0,0]
302 self.configList.append( self.useApEntry )
303 if apModeConfig.useap.value is True:
304 self.configList.append( self.setupModeEntry )
305 self.configList.append( self.wirelessDeviceEntry )
306 self.configList.append( self.wirelessModeEntry )
307 self.configList.append( self.channelEntry )
308 self.configList.append( self.ssidEntry )
309 if apModeConfig.setupmode.value is "advanced":
310 self.configList.append( self.beaconEntry )
311 self.configList.append( self.rtsThresholdEntry )
312 self.configList.append( self.fragmThresholdEntry )
313 self.configList.append( self.prambleEntry )
314 self.configList.append( self.ignoreBroadcastSsid )
315 self.configList.append( self.encryptEntry )
316 if apModeConfig.encrypt.value is True:
317 self.configList.append( self.methodEntry )
318 if apModeConfig.method.value is "0": # wep
319 self.configList.append( self.wepKeyTypeEntry )
320 self.configList.append( self.wepKey0Entry )
322 self.configList.append( self.wpaKeyEntry )
323 if apModeConfig.setupmode.value is "advanced":
324 self.configList.append( self.groupRekeyEntry )
325 ## set network interfaces
326 self.configList.append( self.usedhcpEntry )
327 if apModeConfig.usedhcp.value is False:
328 self.configList.append( self.ipEntry )
329 self.configList.append( self.netmaskEntry )
330 self.configList.append( self.gatewayEntry )
331 self.configList.append( self.nameserverEntry )
332 self["config"].list = self.configList
333 self["config"].l.setList(self.configList)
336 ConfigListScreen.keyLeft(self)
340 ConfigListScreen.keyRight(self)
344 if self["config"].getCurrent() in [ self.encryptEntry, self.methodEntry, self.useApEntry, self.usedhcpEntry, self.setupModeEntry]:
347 # 0 : legacy module activated, 1 : kernel module activated, -1 : None
348 def checkProcModules(self):
349 proc_path = "/proc/modules"
350 legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta")
351 kernel_modules = ("rt2800usb", "rt2800lib")
353 fd = open(proc_path, "r")
354 data = fd.readlines()
358 module = line.split()[0].strip()
359 if module in legacy_modules:
361 elif module in kernel_modules:
366 def isRalinkModule(self):
368 iface = apModeConfig.wirelessdevice.value
370 # check vendor ID for lagacy driver
371 vendorID = "148f" # ralink vendor ID
372 idVendorPath = "/sys/class/net/%s/device/idVendor" % iface
373 if access(idVendorPath, R_OK):
374 fd = open(idVendorPath, "r")
375 data = fd.read().strip()
378 printDebugMsg("Vendor ID : %s" % data)
383 # check sys driver path for kernel driver
384 ralinkKmod = "rt2800usb" # ralink kernel driver name
385 driverPath = "/sys/class/net/%s/device/driver/" % iface
386 if os_path.exists(driverPath):
387 driverName = os_path.basename(os_path.realpath(driverPath))
389 printDebugMsg("driverName : %s" % driverName)
391 if driverName == ralinkKmod:
396 def doConfigMsg(self):
398 msg = "Are you sure you want to setup AP?\n"
400 isRainkIface = self.isRalinkModule()
401 isApMode = apModeConfig.useap.value is True
402 isRalinkKmodUploaded = self.checkProcModules() == 1
404 if isRainkIface and isApMode and (not isRalinkKmodUploaded ):
405 msg += "( STB should be reboot to enable AP mode. )\n"
408 self.session.openWithCallback(self.doConfig, MessageBox, (_(msg) ) )
410 def doConfig(self, ret = False):
414 if apModeConfig.useap.value is True and apModeConfig.encrypt.value is True:
415 if not self.checkEncrypKey():
417 if not self.checkConfig():
420 self.configStartMsg = self.session.openWithCallback(self.ConfigFinishedMsg, MessageBox, _("Please wait for AP Configuration....\n") , type = MessageBox.TYPE_INFO, enable_input = False)
422 if apModeConfig.useap.value is True:
423 self.networkRestart( nextFunc = self.makeConf )
425 self.networkRestart( nextFunc = self.removeConf )
427 def checkEncrypKey(self):
429 if apModeConfig.method.value == "0":
430 if self.checkWep(apModeConfig.wep_key0.value) is False:
431 self.session.open(MessageBox, _("Invalid WEP key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10 )
435 if not len(apModeConfig.wpa_passphrase.value) in range(8,65):
436 self.session.open(MessageBox, _("Invalid WPA key\n\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
441 def checkWep(self, key):
446 elif apModeConfig.wepType.value == "64" and length == 10:
448 elif apModeConfig.wepType.value == "128" and length == 26:
453 def checkConfig(self):
456 if len(apModeConfig.ssid.value) == 0 or len(apModeConfig.ssid.value) > 32:
457 self.session.open(MessageBox, _("Invalid SSID\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
459 elif apModeConfig.channel.value not in range(1,14):
460 self.session.open(MessageBox, _("Invalid channel\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
462 elif apModeConfig.beacon.value < 15 or apModeConfig.beacon.value > 65535:
463 self.session.open(MessageBox, _("Invalid beacon\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
465 elif apModeConfig.rts_threshold.value < 0 or apModeConfig.rts_threshold.value > 2347:
466 self.session.open(MessageBox, _("Invalid RTS Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
468 elif apModeConfig.fragm_threshold.value < 256 or apModeConfig.fragm_threshold.value > 2346:
469 self.session.open(MessageBox, _("Invalid Fragm Threshold\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
471 elif apModeConfig.wpagrouprekey.value < 0 or apModeConfig.wpagrouprekey.value > 3600:
472 self.session.open(MessageBox, _("Invalid wpagrouprekey\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
476 def networkRestart(self, nextFunc = None ):
477 self.networkRestart_stop( nextFunc = nextFunc )
479 def networkRestart_stop(self, nextFunc = None ):
480 printDebugMsg("networkRestart_stop")
481 self.msgPlugins(False)
482 self.commands = [] # stop current network
483 self.networkRestartConsole = Console()
484 self.commands.append("/etc/init.d/avahi-daemon stop")
485 for iface in iNetwork.getAdapterList():
486 if iface != 'eth0' or not iNetwork.onRemoteRootFS():
487 self.commands.append("ifdown " + iface)
488 self.commands.append("ip addr flush dev " + iface)
489 self.commands.append("/etc/init.d/hostapd stop")
490 self.commands.append("/etc/init.d/networking stop")
491 self.commands.append("killall -9 udhcpc")
492 self.commands.append("rm /var/run/udhcpc*")
493 self.networkRestartConsole.eBatch(self.commands, nextFunc, debug = True)
495 def makeConf(self,extra_args):
496 printDebugMsg("makeConf")
497 self.writeNetworkInterfaces()
498 result = self.writeHostapdConfig()
500 self.configStartMsg.close(False)
501 self.configErrorTimer.start(100, True)
504 self.networkRestart_start()
506 def removeConf(self,extra_args):
508 printDebugMsg("removeConf")
509 if fileExists("/etc/hostapd.conf", 'f'):
510 os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back")
511 fp = file("/etc/network/interfaces", 'w')
512 fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n")
513 fp.write("auto lo\n")
514 fp.write("iface lo inet loopback\n\n")
516 fp.write("auto eth0\n")
517 if apModeConfig.usedhcp.value is True:
518 fp.write("iface eth0 inet dhcp\n")
520 fp.write("iface eth0 inet static\n")
521 fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) )
522 fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) )
523 fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) )
524 fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value) )
527 self.networkRestart_start()
529 def networkRestart_start(self):
531 printDebugMsg("networkRestart_start")
532 self.restartConsole = Console()
534 self.commands.append("/etc/init.d/networking start")
535 self.commands.append("/etc/init.d/avahi-daemon start")
536 if apModeConfig.useap.value is True:
537 self.commands.append("/etc/init.d/hostapd start")
538 self.restartConsole.eBatch(self.commands, self.networkRestartFinished, debug=True)
540 def networkRestartFinished(self, data):
541 printDebugMsg("networkRestartFinished")
543 iNetwork.getInterfaces(self.getInterfacesDataAvail)
545 def getInterfacesDataAvail(self, data):
546 self.blacklist_legacy_drivers()
547 if data is True and self.configStartMsg is not None:
548 self.configStartMsg.close(True)
550 def ConfigFinishedMsg(self, ret):
552 self.session.openWithCallback(self.ConfigFinishedMsgCallback ,MessageBox, _("Configuration your AP is finished"), type = MessageBox.TYPE_INFO, timeout = 5, default = False)
554 def needRalinkKmod(self):
556 isRainkIface = self.isRalinkModule()
557 ApMode = apModeConfig.useap.value is True
559 if isRainkIface and ApMode:
564 def ConfigFinishedMsgCallback(self,data):
565 isRalinkKmodUploaded = self.checkProcModules() == 1
566 needRalinkKmod_ = self.needRalinkKmod()
568 if needRalinkKmod_ : # ralink device is activated in AP Mode.
569 if not isRalinkKmodUploaded : # reboot to loading kernel module.
570 msg = "You should now reboot your STB in order to ralink device operate in AP mode.\n\nReboot now ?\n\n"
571 self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type = MessageBox.TYPE_YESNO, default = True )
574 elif isRalinkKmodUploaded :
575 msg = "You should now reboot your STB to better performance of ralink device in STA mode.\n\nReboot now ?\n\n"
576 self.session.openWithCallback(self.doReboot, MessageBox, _(msg), type = MessageBox.TYPE_YESNO, default = True )
580 def blacklist_legacy_drivers(self):
581 blacklist_conf_dir = "/etc/modprobe.d"
582 blacklist_conf_file = blacklist_conf_dir + "/blacklist-wlan.conf"
583 legacy_modules = ("rt3070", "rt3070sta", "rt5372", "rt5372sta", "rt5370", "rt5370sta")
584 kernel_modules = ("rt2800usb", "rt2800lib")
587 need_ralink_kmod = self.needRalinkKmod()
589 if access(blacklist_conf_file, R_OK) is True:
590 fd = open(blacklist_conf_file, "r")
594 if need_ralink_kmod: # check legacy modules in blacklist
595 for mod in legacy_modules:
596 if data.find(mod) != -1: return
598 for mod in kernel_modules: # check kernel modules in blacklist
599 if data.find(mod) != -1: return
601 if not os_path.exists(blacklist_conf_dir):
602 makedirs(blacklist_conf_dir)
605 blacklist_modules = legacy_modules
607 blacklist_modules = kernel_modules
609 for module in blacklist_modules:
610 blacklist += "blacklist %s\n" % module
611 f = open(blacklist_conf_file, "w+")
614 self.apModeChanged = True
616 def doReboot(self, res):
618 self.session.open(TryQuitMainloop, 2)
622 def msgPlugins(self,reason = False):
623 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKCONFIG_READ):
626 def writeNetworkInterfaces(self):
628 fp = file("/etc/network/interfaces", 'w')
629 fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n")
630 fp.write("auto lo\n")
631 fp.write("iface lo inet loopback\n\n")
633 fp.write("auto eth0\n")
634 fp.write("iface eth0 inet manual\n")
635 fp.write(" up ip link set $IFACE up\n")
636 fp.write(" down ip link set $IFACE down\n\n")
638 fp.write("auto br0\n")
639 if apModeConfig.usedhcp.value is True:
640 fp.write("iface br0 inet dhcp\n")
642 fp.write("iface br0 inet static\n")
643 fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) )
644 fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) )
645 fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) )
646 fp.write(" dns-nameservers %d.%d.%d.%d\n" % tuple(apModeConfig.nameserver.value) )
647 fp.write(" pre-up brctl addbr br0\n")
648 fp.write(" pre-up brctl addif br0 eth0\n")
649 fp.write(" post-down brctl delif br0 eth0\n")
650 fp.write(" post-down brctl delbr br0\n\n")
654 def setIpForward(self, setValue = 0):
655 ipForwardFilePath = "/proc/sys/net/ipv4/ip_forward"
656 if not fileExists(ipForwardFilePath):
658 printDebugMsg("set %s to %d" % (ipForwardFilePath, setValue))
659 f = open(ipForwardFilePath, "w")
660 f.write("%d" % setValue)
662 sysctlPath = "/etc/sysctl.conf"
664 if fileExists(sysctlPath):
665 fp = file(sysctlPath, "r")
666 sysctlLines = fp.readlines()
669 for line in sysctlLines:
672 (key,value) = line.split("=")
677 sysctlList[key] = value
678 sysctlList["net.ipv4.ip_forward"] = str(setValue)
679 fp = file(sysctlPath, "w")
680 for (key,value) in sysctlList.items():
681 fp.write("%s=%s\n"%(key,value))
685 def getAdapterDescription(self, iface):
686 classdir = "/sys/class/net/" + iface + "/device/"
687 driverdir = "/sys/class/net/" + iface + "/device/driver/"
688 if os_path.exists(classdir):
689 files = listdir(classdir)
690 if 'driver' in files:
691 if os_path.realpath(driverdir).endswith('rtw_usb_drv'):
692 return _("Realtek")+ " " + _("WLAN adapter.")
693 elif os_path.realpath(driverdir).endswith('ath_pci'):
694 return _("Atheros")+ " " + _("WLAN adapter.")
695 elif os_path.realpath(driverdir).endswith('zd1211b'):
696 return _("Zydas")+ " " + _("WLAN adapter.")
697 elif os_path.realpath(driverdir).endswith('rt73'):
698 return _("Ralink")+ " " + _("WLAN adapter.")
699 elif os_path.realpath(driverdir).endswith('rt73usb'):
700 return _("Ralink")+ " " + _("WLAN adapter.")
702 return str(os_path.basename(os_path.realpath(driverdir))) + " " + _("WLAN adapter")
704 return _("Unknown network adapter")
706 return _("Unknown network adapter")
710 for x in self["config"].list:
712 apModeConfig.wpa.value = "0"
713 apModeConfig.wep.value = False
718 def printConfigList(self, confList):
719 printDebugMsg("== printConfigList ==");
720 for (key, entry) in confList.items():
721 printDebugMsg("%s = %s"%(key , str(entry.value)));
723 printDebugMsg("== printConfigList end ==");
725 def loadHostapConfig(self):
728 if access("/etc/hostapd.conf", R_OK) is True:
729 printDebugMsg("open /etc/hostapd.conf")
730 fd = open("/etc/hostapd.conf", "r")
731 elif access("/etc/hostapd.conf.linuxap.back", R_OK) is True:
732 printDebugMsg("open /etc/hostapd.conf.linuxap.back")
733 fd = open("/etc/hostapd.conf.linuxap.back", "r")
735 printDebugMsg("can not open hostapd.conf")
738 for line in fd.readlines():
741 if (len(line) == 0) or (line.find('=') == -1):
744 data = line.split('=', 1)
748 key = data[0].strip()
749 value = data[1].strip()
751 if key == "#wep_key0":
752 self.hostapdConf["wep_key0"].value = value
753 apModeConfig.wep.value = False
755 elif key == "wep_key0":
756 self.hostapdConf["wep_key0"].value = value
757 apModeConfig.wep.value = True
759 elif key.startswith('#'):
762 elif key == "channel" :
763 if int(value) not in range(14):
764 self.hostapdConf[key].value = 1
766 self.hostapdConf[key].value = int(value)
768 elif key in ["beacon_int", "rts_threshold", "fragm_threshold", "wpa_group_rekey"]:
769 self.hostapdConf[key].value = int(value)
771 elif key in self.hostapdConf.keys():
772 self.hostapdConf[key].value = value
775 self.printConfigList(self.hostapdConf)
779 def writeHostapdConfig(self):
781 global ORIG_HOSTAPD_CONF
782 self.printConfigList(self.hostapdConf)
783 if access(ORIG_HOSTAPD_CONF, R_OK) is not True:
784 self.msg = "can not access file. (%s)" % ORIG_HOSTAPD_CONF
785 printDebugMsg(self.msg)
788 orig_conf = open(ORIG_HOSTAPD_CONF, "r")
790 print "can't open file. (%s)" % ORIG_HOSTAPD_CONF
792 new_conf = open(HOSTAPD_CONF, "w")
794 print "can't open file. (%s)" % HOSTAPD_CONF
796 isEncryptOn = apModeConfig.encrypt.value is True
797 isEncryptWEP = apModeConfig.method.value == "0"
798 isEncryptWPA = not isEncryptWEP
800 for r_line in orig_conf.readlines():
801 line = r_line.strip()
803 new_conf.write(r_line)
808 if line.find("wep_default_key=") != -1 : # is wepLine
809 if isEncryptOn and isEncryptWEP :
810 fix_line = "wep_default_key=%s\n" % self.hostapdConf["wep_default_key"].value
812 elif line.find("wep_key0=") != -1 : # is WepKeyLine
815 fix_line = "wep_key0=%s\n" % self.hostapdConf["wep_key0"].value
817 fix_line = "#wep_key0=%s\n" % self.hostapdConf["wep_key0"].value
820 fix_line = "#wep_key0=%s\n" % self.hostapdConf["wep_key0"].value
822 elif line.find("wpa=") != -1 : # is wpaLine
823 if isEncryptOn and isEncryptWPA :
824 fix_line = "wpa=%s\n" % apModeConfig.method.value
826 elif line.startswith("#ssid"):
830 for (key , entry) in self.hostapdConf.items():
831 value = str(entry.value)
832 pos = line.find(key+'=')
833 if ( (pos != -1) and (pos < 2) ) and len(value)!=0 :
834 fix_line = "%s=%s\n" % (key, value)
837 # if fix_line is not None:
838 # print "r_line : ", r_line,
839 # print "fix_li : ", fix_line
841 if fix_line is not None:
842 new_conf.write(fix_line)
844 new_conf.write(r_line)
850 def main(session, **kwargs):
851 session.open(WirelessAccessPoint)
853 def Plugins(**kwargs):
854 return [PluginDescriptor(name=_("Wireless Access Point"), description=_("Using a Wireless module as access point."), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = True, fnc=main)]