+merged some config changes

@[l] please also check the webserver if you change the config
+moved language checkers
+changed input sanitizing
This commit is contained in:
age 2006-08-30 19:56:37 +00:00
parent f450e116a7
commit f4bf1c7a34
5 changed files with 80 additions and 68 deletions

View file

@ -287,6 +287,41 @@ class CryptoBoxProps(CryptoBox):
"the uuid was not found" "the uuid was not found"
return None return None
def getAvailableLanguages(self):
'''reads all files in path LangDir and returns a list of
basenames from existing hdf files, that should are all available
languages'''
languages = []
for file in os.listdir(self.cbxPrefs["Locations"]["LangDir"]):
if file.endswith(".hdf"): languages.append(file.rstrip(".hdf"))
if len(languages) < 1:
self.log.warn("No .hdf files found! The website won't render properly.")
return languages
def getAvailableDocLanguages(self):
'''reads all dirs in path DocDir and returns a list of
available documentation languages, this list might be empty.'''
doclangs = []
regpat = re.compile(r"^\w+$")
try:
doc_dir = self.cbxPrefs["Locations"]["DocDir"]
except KeyError:
self.log.error("Could not find a configuration setting: [Locations]->DocDir - please check the config file")
return []
if not os.path.exists(doc_dir):
self.log.error("The configured documentation directory (%s) does not exist" % (doc_dir, ))
return []
try:
for e in os.listdir(doc_dir):
if regpat.search(e) and os.path.isdir(os.path.join(doc_dir, e)):
doclangs.append(e)
if len(doclangs) < 1:
self.log.warn("Didn't find any documentation files.")
return doclangs
except OSError:
self.log.error("Could not access the documentations directory (%s)" % (doc_dir,))
return []
""" ************ internal stuff starts here *********** """ """ ************ internal stuff starts here *********** """

View file

@ -1,8 +1,8 @@
import os import os
try: try:
import neo_cgi, neo_util, neo_cs import neo_cgi, neo_util, neo_cs
except: except ImportError:
print "could not import clearsilver modules! Try apt-get install python-clearsilver." raise ImportError("could not import clearsilver modules! Try apt-get install python-clearsilver.")
class CryptoBoxWebserverRender: class CryptoBoxWebserverRender:
'''renders the site with clearsilver template and languagefile '''renders the site with clearsilver template and languagefile
@ -24,13 +24,14 @@ class CryptoBoxWebserverRender:
website.log.error("Couldn't read cs file: %s" % cs_path) website.log.error("Couldn't read cs file: %s" % cs_path)
return "Couldn't read cs file: %s" % cs_path return "Couldn't read cs file: %s" % cs_path
hdf_path = website.cbxPrefs["Locations"]["LangDir"]+"/"+website.cbxPrefs["Settings"]["Language"]+".hdf" hdf_path = website.cbxPrefs["Locations"]["LangDir"]+"/"+website.cbxPrefs["WebSettings"]["Language"]+".hdf"
if not os.access(hdf_path, os.R_OK): if not os.access(hdf_path, os.R_OK):
website.log.error("Couldn't read hdf file: %s" % hdf_path) website.log.error("Couldn't read hdf file: %s" % hdf_path)
return "Couldn't read hdf file: %s" % hdf_path return "Couldn't read hdf file: %s" % hdf_path
hdf = neo_util.HDF() hdf = neo_util.HDF()
hdf.readFile(hdf_path) hdf.readFile(hdf_path)
#website.log.info(website.settings)
for key in website.settings.keys(): for key in website.settings.keys():
hdf.setValue(key,str(website.settings[key])) hdf.setValue(key,str(website.settings[key]))
cs = neo_cs.CS(hdf) cs = neo_cs.CS(hdf)

View file

@ -8,13 +8,23 @@ class CryptoBoxWebserverSettings:
There may also be set some useful standards here.''' There may also be set some useful standards here.'''
website.settings={} website.settings={}
## put all found Settings values in the dictionary #TODO: this is nessessary since the last config split in different sections
for key in self.cbxPrefs["Settings"].keys(): ## put all found WebSettings values in the dictionary
website.settings["Settings."+key] = self.cbxPrefs["Settings"][key] for key in self.cbxPrefs["WebSettings"].keys():
website.settings["Settings."+key] = self.cbxPrefs["WebSettings"][key]
## also all Log values ## also all Log values
for key in self.cbxPrefs["Log"].keys(): for key in self.cbxPrefs["Log"].keys():
website.settings["Log."+key] = self.cbxPrefs["Log"][key] website.settings["Log."+key] = self.cbxPrefs["Log"][key]
## also Main
for key in self.cbxPrefs["Main"].keys():
website.settings["Settings."+key] = self.cbxPrefs["Main"][key]
## Locations dito
for key in self.cbxPrefs["Locations"].keys():
website.settings["Settings."+key] = self.cbxPrefs["Locations"][key]
## put available languages also in the dictionary
website.settings["Settings.AvailableLanguages"] = self.getAvailableLanguages()
website.settings["Settings.AvailableDocLanguages"] = self.getAvailableDocLanguages()
#self.log.info(self.settings) #self.log.info(self.settings)

View file

@ -34,25 +34,26 @@ class CryptoBoxWebserverSites(CryptoBox.CryptoBoxProps, CryptoBoxWebserverSettin
at url-given parameters. at url-given parameters.
This has to be called manually, since I don't see any other way of This has to be called manually, since I don't see any other way of
sanitizing input automatically for all sites. sanitizing input automatically for all sites.
To take full effect it is good style not to use any given
parameter for any website. Instead use "settings.["..." if it
isn't already defined. Then define it in here, after carefully
checking.
# RFC: why shouldn't it be called in __init__? [l] # RFC: why shouldn't it be called in __init__? [l]
there is no such thing like __init__ in cherrypy sites [a]
''' '''
niceparams = { 'weblang': tuple(self.__getAvailableLanguages()), niceparams = { 'weblang': self.settings["Settings.AvailableLanguages"],
'loglevel': ('','info', 'warn', 'debug', 'error'), 'loglevel': ('','info', 'warn', 'debug', 'error'),
'type': ('reboot', 'poweroff') 'type': ('reboot', 'poweroff')
} }
for evilkey in evilparams.keys(): for evilkey in evilparams.keys():
## if the param isn't in the niceparams list, ignore it if evilkey == "weblang":
if not niceparams.get(evilkey): if evilparams["weblang"] and evilparams["weblang"] in niceparams["weblang"]:
self.log.warn('ignoring "%s"' % evilkey) self.settings["Settings.Language"] = evilparams["weblang"]
# RFC: why "return False"? - just ignoring is sufficient if evilkey == "loglevel":
return False if evilparams["loglevel"] and evilparams["loglevel"] in niceparams["loglevel"]:
#TODO: until now only a warning message is printed self.settings["Log.Level"] = evilparams["loglevel"]
## if the param has no such value, set it to a default (the first in the list) return
if evilparams.get(evilkey) not in niceparams.get(evilkey):
self.log.warn('"%s" not in weblang %s' % (evilkey, niceparams.get(evilkey)))
# RFC: why "weblang"?
#TODO: set it to: niceparams.get(evilkey)[0]))
return
def __check_config(self): def __check_config(self):
@ -64,44 +65,6 @@ class CryptoBoxWebserverSites(CryptoBox.CryptoBoxProps, CryptoBoxWebserverSettin
#TODO #TODO
pass pass
def __getAvailableLanguages(self):
import re, os
regpat = re.compile(r"^\w+\.hdf$")
try:
lang_dir = self.cbxPrefs["Locations"]["LangDir"]
except KeyError:
self.log.error("Could not find a configuration setting: [Locations]->LangDir - please check the config file")
return []
if not os.path.exists(lang_dir):
self.log.error("The configured language directory (%s) does not exist" % (lang_dir, ))
return []
try:
return [ e[:-4] for e in os.listdir(lang_dir) if regpat.search(e)]
except OSError:
self.log.error("Could not access the language directory (%s)" % (lang_dir,))
return []
def __getAvailableDocLanguages(self):
import re, os
regpat = re.compile(r"^\w+$")
try:
doc_dir = self.cbxPrefs["Locations"]["DocDir"]
except KeyError:
self.log.error("Could not find a configuration setting: [Locations]->DocDir - please check the config file")
return []
if not os.path.exists(doc_dir):
self.log.error("The configured documentation directory (%s) does not exist" % (doc_dir, ))
return []
try:
return [ e for e in os.listdir(doc_dir)
if regpat.search(e) and os.path.isdir(os.path.join(doc_dir, e))]
except OSError:
self.log.error("Could not access the documentations directory (%s)" % (doc_dir,))
return []
###################################################################### ######################################################################
## put real sites down here and don't forget to expose them at the end ## put real sites down here and don't forget to expose them at the end
@ -115,16 +78,16 @@ class CryptoBoxWebserverSites(CryptoBox.CryptoBoxProps, CryptoBoxWebserverSettin
reserved word. reserved word.
# RFC: maybe it conflicts with CryptoBoxProps.log - which we inherited? # RFC: maybe it conflicts with CryptoBoxProps.log - which we inherited?
''' '''
self.__sanitize_input({"loglevel":loglevel})
self.__prepare("show_log") self.__prepare("show_log")
self.__sanitize_input({"loglevel":loglevel})
self.settings["Data.Log"] = "<br/>".join(self.getLogData(lines=30, maxSize=2000)) self.settings["Data.Log"] = "<br/>".join(self.getLogData(lines=30, maxSize=2000))
return website.render(self) return website.render(self)
def status(self, weblang=""): def status(self, weblang=""):
'''shows the current status of the box '''shows the current status of the box
''' '''
self.__sanitize_input({"weblang":weblang})
self.__prepare("show_status") self.__prepare("show_status")
self.__sanitize_input({"weblang":weblang})
if not self.__check_config(): if not self.__check_config():
self.settings["Data.Warning"] = "NotInitialized" self.settings["Data.Warning"] = "NotInitialized"
self.settings["Data.Action"] = "form_init" self.settings["Data.Action"] = "form_init"
@ -146,7 +109,7 @@ class CryptoBoxWebserverSites(CryptoBox.CryptoBoxProps, CryptoBoxWebserverSettin
def doc(self,action="",page="",weblang=""): def doc(self,action="",page="",weblang=""):
'''prints the offline wikipage '''prints the offline wikipage
TODO: action is unnessessary, remove here and from all html TODO: "action" is unnessessary, remove it here and from all html
files in doc/html/[de|en]/* files in doc/html/[de|en]/*
''' '''
# RFC: sanitize? # RFC: sanitize?
@ -154,12 +117,13 @@ class CryptoBoxWebserverSites(CryptoBox.CryptoBoxProps, CryptoBoxWebserverSettin
if page: if page:
self.settings["Data.Doc.Page"] = page self.settings["Data.Doc.Page"] = page
else: else:
## display this site as default helpsite
self.settings["Data.Doc.Page"] ="CryptoBoxUser" self.settings["Data.Doc.Page"] ="CryptoBoxUser"
if weblang: if len(self.settings["Settings.AvailableDocLanguages"]) < 1:
if weblang in self.__getAvailableDocLanguages(): self.settings["Data.Error"] = "NoDocumentation"
self.settings["Settings.DocLang"] = weblang ## set doclang to weblang, otherwise the default lang from the config will be used
else: elif weblang in ("en","de"):
self.log.warn("invalid documentation language selected: %s", % (weblang, )) self.settings["Settings.DocLang"] = weblang
return website.render(self) return website.render(self)

View file

@ -86,9 +86,11 @@ CryptoBoxRootActions = CryptoBoxRootActions
self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps,"/invalid/path/to/config/file") self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps,"/invalid/path/to/config/file")
self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps,"/etc/shadow") self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps,"/etc/shadow")
for a in self.CryptoBox.CONF_LOCATIONS: for a in self.CryptoBox.CONF_LOCATIONS:
if os.path.exists(a): self.CryptoBox.CryptoBoxProps() if os.path.exists(a):
else: self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps) self.CryptoBox.CryptoBoxProps()
self.CryptoBox.CryptoBoxProps(self.filenames["configFileOK"]) self.CryptoBox.CryptoBoxProps(self.filenames["configFileOK"])
else:
self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps)
self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps,[]) self.assertRaises(CBConfigUnavailableError, self.CryptoBox.CryptoBoxProps,[])
def testBrokenConfigs(self): def testBrokenConfigs(self):