root / pykota / trunk / pykota / config.py @ 2583

Revision 2583, 25.2 kB (checked in by jerome, 19 years ago)

Preliminary work on the "onbackenderror" directive.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[695]1# PyKota
[1144]2# -*- coding: ISO-8859-15 -*-
[695]3#
[952]4# PyKota : Print Quotas for CUPS and LPRng
[695]5#
[1257]6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
[873]7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
[695]11#
[873]12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
[2302]19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
[695]20#
21# $Id$
22#
[2074]23#
[695]24
25import os
[2405]26import tempfile
[695]27import ConfigParser
28
29class PyKotaConfigError(Exception):
30    """An exception for PyKota config related stuff."""
31    def __init__(self, message = ""):
32        self.message = message
33        Exception.__init__(self, message)
34    def __repr__(self):
35        return self.message
36    __str__ = __repr__
37   
38class PyKotaConfig :
39    """A class to deal with PyKota's configuration."""
40    def __init__(self, directory) :
41        """Reads and checks the configuration file."""
[1785]42        self.isAdmin = 0
43        self.directory = directory
[695]44        self.filename = os.path.join(directory, "pykota.conf")
[2418]45        self.adminfilename = os.path.join(directory, "pykotadmin.conf")
[2421]46        if not os.access(self.filename, os.R_OK) :
47            raise PyKotaConfigError, _("Configuration file %s can't be read. Please check that the file exists and that your permissions are sufficient.") % self.filename
[2418]48        if not os.path.isfile(self.adminfilename) :
49            raise PyKotaConfigError, _("Configuration file %s not found.") % self.adminfilename
50        if os.access(self.adminfilename, os.R_OK) :   
51            self.isAdmin = 1
[695]52        self.config = ConfigParser.ConfigParser()
53        self.config.read([self.filename])
[1227]54           
55    def isTrue(self, option) :       
56        """Returns 1 if option is set to true, else 0."""
[2308]57        if (option is not None) and (option.strip().upper() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
[1227]58            return 1
59        else :   
60            return 0
[695]61                       
[2308]62    def isFalse(self, option) :       
63        """Returns 1 if option is set to false, else 0."""
64        if (option is not None) and (option.strip().upper() in ['N', 'NO', '0', 'OFF', 'F', 'FALSE']) :
65            return 1
66        else :   
67            return 0
68                       
[695]69    def getPrinterNames(self) :   
70        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
71        return [pname for pname in self.config.sections() if pname != "global"]
72       
[802]73    def getGlobalOption(self, option, ignore=0) :   
74        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
75        try :
76            return self.config.get("global", option, raw=1)
77        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
78            if ignore :
79                return
80            else :
81                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
82               
[1192]83    def getPrinterOption(self, printername, option) :   
[802]84        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
85        globaloption = self.getGlobalOption(option, ignore=1)
86        try :
[1192]87            return self.config.get(printername, option, raw=1)
[802]88        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
89            if globaloption is not None :
90                return globaloption
91            else :
[1192]92                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
[802]93       
[695]94    def getStorageBackend(self) :   
[800]95        """Returns the storage backend information as a Python mapping."""       
96        backendinfo = {}
[695]97        for option in [ "storagebackend", "storageserver", \
[1087]98                        "storagename", "storageuser", \
[695]99                      ] :
[804]100            backendinfo[option] = self.getGlobalOption(option)
[1087]101        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
102        backendinfo["storageadmin"] = None
103        backendinfo["storageadminpw"] = None
[2418]104        if self.isAdmin :
105            adminconf = ConfigParser.ConfigParser()
106            adminconf.read([self.adminfilename])
107            if adminconf.sections() : # were we able to read the file ?
108                try :
109                    backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
110                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
111                    raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", self.adminfilename)
112                try :
113                    backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
114                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
115                    pass # Password is optional
116                # Now try to overwrite the storagebackend, storageserver
117                # and storagename. This allows admins to use the master LDAP
118                # server directly and users to use the replicas transparently.
119                try :
120                    backendinfo["storagebackend"] = adminconf.get("global", "storagebackend", raw=1)
121                except ConfigParser.NoOptionError :
122                    pass
123                try :
124                    backendinfo["storageserver"] = adminconf.get("global", "storageserver", raw=1)
125                except ConfigParser.NoOptionError :
126                    pass
127                try :
128                    backendinfo["storagename"] = adminconf.get("global", "storagename", raw=1)
129                except ConfigParser.NoOptionError :
130                    pass
[800]131        return backendinfo
[695]132       
[1029]133    def getLDAPInfo(self) :   
134        """Returns some hints for the LDAP backend."""       
135        ldapinfo = {}
136        for option in [ "userbase", "userrdn", \
[1041]137                        "balancebase", "balancerdn", \
[1029]138                        "groupbase", "grouprdn", "groupmembers", \
139                        "printerbase", "printerrdn", \
140                        "userquotabase", "groupquotabase", \
[2370]141                        "jobbase", "lastjobbase", "billingcodebase", \
[1105]142                        "newuser", "newgroup", \
[1111]143                        "usermail", \
[1029]144                      ] :
[1105]145            ldapinfo[option] = self.getGlobalOption(option).strip()
146        for field in ["newuser", "newgroup"] :
147            if ldapinfo[field].lower().startswith('attach(') :
148                ldapinfo[field] = ldapinfo[field][7:-1]
[1968]149               
150        # should we use TLS, by default (if unset) value is NO       
151        ldapinfo["ldaptls"] = self.isTrue(self.getGlobalOption("ldaptls", ignore=1))
152        ldapinfo["cacert"] = self.getGlobalOption("cacert", ignore=1)
153        if ldapinfo["cacert"] :
154            ldapinfo["cacert"] = ldapinfo["cacert"].strip()
155        if ldapinfo["ldaptls"] :   
156            if not os.access(ldapinfo["cacert"] or "", os.R_OK) :
157                raise PyKotaConfigError, _("Option ldaptls is set, but certificate %s is not readable.") % str(ldapinfo["cacert"])
[1029]158        return ldapinfo
159       
[695]160    def getLoggingBackend(self) :   
161        """Returns the logging backend information."""
[802]162        validloggers = [ "stderr", "system" ] 
[853]163        try :
164            logger = self.getGlobalOption("logger").lower()
165        except PyKotaConfigError :   
166            logger = "system"
[802]167        if logger not in validloggers :             
168            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
169        return logger   
[695]170       
[2262]171    def getLogoURL(self) :
172        """Returns the URL to use for the logo in the CGI scripts."""
173        url = self.getGlobalOption("logourl", ignore=1) or \
174                   "http://www.librelogiciel.com/software/PyKota/pykota.png"
175        return url.strip()           
[2265]176       
177    def getLogoLink(self) :
178        """Returns the URL to go to when the user clicks on the logo in the CGI scripts."""
179        url = self.getGlobalOption("logolink", ignore=1) or \
180                   "http://www.librelogiciel.com/software/"
181        return url.strip()           
[2262]182   
[1192]183    def getAccounterBackend(self, printername) :   
[973]184        """Returns the accounter backend to use for a given printer.
185       
[1475]186           if it is not set, it defaults to 'hardware' which means ask printer
[973]187           for its internal lifetime page counter.
188        """   
[1475]189        validaccounters = [ "hardware", "software" ]     
[1371]190        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
[1483]191        flower = fullaccounter.lower()
192        if flower.startswith("software") or flower.startswith("hardware") :   
[980]193            try :
194                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
195            except ValueError :   
[1483]196                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[980]197            if args.endswith(')') :
[2074]198                args = args[:-1].strip()
199            if (accounter == "hardware") and not args :
[1483]200                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[2422]201            return (accounter.lower(), args)
[1483]202        else :
[1192]203            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
[973]204       
[1371]205    def getPreHook(self, printername) :   
206        """Returns the prehook command line to launch, or None if unset."""
207        try :
208            return self.getPrinterOption(printername, "prehook").strip()
209        except PyKotaConfigError :   
210            return      # No command to launch in the pre-hook
211           
212    def getPostHook(self, printername) :   
213        """Returns the posthook command line to launch, or None if unset."""
214        try :
215            return self.getPrinterOption(printername, "posthook").strip()
216        except PyKotaConfigError :   
217            return      # No command to launch in the post-hook
218           
[2307]219    def getStripTitle(self, printername) :   
220        """Returns the striptitle directive's content, or None if unset."""
221        try :
222            return self.getPrinterOption(printername, "striptitle").strip()
223        except PyKotaConfigError :   
224            return      # No prefix to strip off
225           
[2385]226    def getOverwriteJobTicket(self, printername) :       
227        """Returns the overwrite_jobticket directive's content, or None if unset."""
228        try :
229            return self.getPrinterOption(printername, "overwrite_jobticket").strip()
230        except PyKotaConfigError :   
231            return      # No overwriting will be done
232       
233    def getUnknownBillingCode(self, printername) :       
234        """Returns the unknown_billingcode directive's content, or the default value if unset."""
235        validvalues = [ "CREATE", "DENY" ]
236        try :
237            fullvalue = self.getPrinterOption(printername, "unknown_billingcode")
238        except PyKotaConfigError :   
239            return ("CREATE", None)
240        else :   
241            try :
242                value = [x.strip() for x in fullvalue.split('(', 1)]
243            except ValueError :   
244                raise PyKotaConfigError, _("Invalid unknown_billingcode directive %s for printer %s") % (fullvalue, printername)
245            if len(value) == 1 :   
246                value.append("")
247            (value, args) = value   
248            if args.endswith(')') :
249                args = args[:-1]
250            value = value.upper()   
251            if (value == "DENY") and not args :
252                return ("DENY", None)
253            if value not in validvalues :
254                raise PyKotaConfigError, _("Directive unknown_billingcode in section %s only supports values in %s") % (printername, str(validvalues))
255            return (value, args)
256       
[1495]257    def getPrinterEnforcement(self, printername) :   
258        """Returns if quota enforcement should be strict or laxist for the current printer."""
259        validenforcements = [ "STRICT", "LAXIST" ]     
260        try :
261            enforcement = self.getPrinterOption(printername, "enforcement")
262        except PyKotaConfigError :   
263            return "LAXIST"
264        else :   
265            enforcement = enforcement.upper()
266            if enforcement not in validenforcements :
267                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
268            return enforcement   
269           
[2583]270    def getPrinterOnBackendError(self, printername) :   
271        """Returns what must be done whenever the real CUPS backend fails."""
272        validactions = [ "CHARGE", "NOCHARGE" ]     
273        try :
274            action = self.getPrinterOption(printername, "onbackenderror")
275        except PyKotaConfigError :   
276            return "NOCHARGE"
277        else :   
278            action = action.upper()
279            if action not in validactions :
280                raise PyKotaConfigError, _("Option onbackenderror in section %s only supports values in %s") % (printername, str(validactions))
281            return action 
282           
[1687]283    def getPrinterOnAccounterError(self, printername) :   
284        """Returns what must be done whenever the accounter fails."""
285        validactions = [ "CONTINUE", "STOP" ]     
286        try :
287            action = self.getPrinterOption(printername, "onaccountererror")
288        except PyKotaConfigError :   
289            return "STOP"
290        else :   
291            action = action.upper()
292            if action not in validactions :
293                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
294            return action 
295           
[1192]296    def getPrinterPolicy(self, printername) :   
[695]297        """Returns the default policy for the current printer."""
[1152]298        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
[853]299        try :
[1192]300            fullpolicy = self.getPrinterOption(printername, "policy")
[853]301        except PyKotaConfigError :   
[1152]302            return ("DENY", None)
303        else :   
304            try :
305                policy = [x.strip() for x in fullpolicy.split('(', 1)]
306            except ValueError :   
[1192]307                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]308            if len(policy) == 1 :   
309                policy.append("")
310            (policy, args) = policy   
311            if args.endswith(')') :
312                args = args[:-1]
313            policy = policy.upper()   
314            if (policy == "EXTERNAL") and not args :
[1192]315                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]316            if policy not in validpolicies :
[1192]317                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
[1152]318            return (policy, args)
[695]319       
[1518]320    def getCrashRecipient(self) :   
321        """Returns the email address of the software crash messages recipient."""
322        try :
323            return self.getGlobalOption("crashrecipient")
324        except :   
325            return
326           
[695]327    def getSMTPServer(self) :   
328        """Returns the SMTP server to use to send messages to users."""
[853]329        try :
330            return self.getGlobalOption("smtpserver")
331        except PyKotaConfigError :   
332            return "localhost"
[695]333       
[1353]334    def getMailDomain(self) :   
335        """Returns the mail domain to use to send messages to users."""
336        try :
337            return self.getGlobalOption("maildomain")
338        except PyKotaConfigError :   
339            return 
340       
[1192]341    def getAdminMail(self, printername) :   
[695]342        """Returns the Email address of the Print Quota Administrator."""
[853]343        try :
[1192]344            return self.getPrinterOption(printername, "adminmail")
[853]345        except PyKotaConfigError :   
346            return "root@localhost"
[695]347       
[1192]348    def getAdmin(self, printername) :   
[695]349        """Returns the full name of the Print Quota Administrator."""
[853]350        try :
[1192]351            return self.getPrinterOption(printername, "admin")
[853]352        except PyKotaConfigError :   
353            return "root"
[708]354       
[1192]355    def getMailTo(self, printername) :   
[852]356        """Returns the recipient of email messages."""
[1192]357        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
[853]358        try :
[1192]359            fullmailto = self.getPrinterOption(printername, "mailto")
[853]360        except PyKotaConfigError :   
[1192]361            return ("BOTH", None)
362        else :   
363            try :
364                mailto = [x.strip() for x in fullmailto.split('(', 1)]
365            except ValueError :   
366                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
367            if len(mailto) == 1 :   
368                mailto.append("")
369            (mailto, args) = mailto   
370            if args.endswith(')') :
371                args = args[:-1]
372            mailto = mailto.upper()   
373            if (mailto == "EXTERNAL") and not args :
374                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
375            if mailto not in validmailtos :
376                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
377            return (mailto, args)
[852]378       
[2054]379    def getMaxDenyBanners(self, printername) :   
380        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
381        try :
382            maxdb = self.getPrinterOption(printername, "maxdenybanners")
383        except PyKotaConfigError :   
384            return 0 # default value is to forbid printing a deny banner.
385        try :
386            value = int(maxdb.strip())
387            if value < 0 :
388                raise ValueError
389        except (TypeError, ValueError) :   
390            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
391        else :   
392            return value
393           
[1192]394    def getGraceDelay(self, printername) :   
[708]395        """Returns the grace delay in days."""
[731]396        try :
[1192]397            gd = self.getPrinterOption(printername, "gracedelay")
[853]398        except PyKotaConfigError :   
[1914]399            gd = 7      # default value of 7 days
[853]400        try :
[731]401            return int(gd)
[1077]402        except (TypeError, ValueError) :   
[773]403            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
[1021]404           
[1077]405    def getPoorMan(self) :   
[1646]406        """Returns the poor man's threshold."""
[1077]407        try :
408            pm = self.getGlobalOption("poorman")
409        except PyKotaConfigError :   
[1914]410            pm = 1.0    # default value of 1 unit
[1077]411        try :
412            return float(pm)
413        except (TypeError, ValueError) :   
[1646]414            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
[1077]415           
416    def getPoorWarn(self) :   
417        """Returns the poor man's warning message."""
418        try :
419            return self.getGlobalOption("poorwarn")
420        except PyKotaConfigError :   
421            return _("Your Print Quota account balance is Low.\nSoon you'll not be allowed to print anymore.\nPlease contact the Print Quota Administrator to solve the problem.")
422           
[1192]423    def getHardWarn(self, printername) :   
[1077]424        """Returns the hard limit error message."""
425        try :
[1192]426            return self.getPrinterOption(printername, "hardwarn")
[1077]427        except PyKotaConfigError :   
[1192]428            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
[1077]429           
[1192]430    def getSoftWarn(self, printername) :   
[1077]431        """Returns the soft limit error message."""
432        try :
[1192]433            return self.getPrinterOption(printername, "softwarn")
[1077]434        except PyKotaConfigError :   
[1192]435            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
[1077]436           
[1875]437    def getPrivacy(self) :       
438        """Returns 1 if privacy is activated, else 0."""
439        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
440       
[1021]441    def getDebug(self) :         
442        """Returns 1 if debugging is activated, else 0."""
[1227]443        return self.isTrue(self.getGlobalOption("debug", ignore=1))
[1130]444           
445    def getCaching(self) :         
446        """Returns 1 if database caching is enabled, else 0."""
[1227]447        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
[1148]448           
[1356]449    def getLDAPCache(self) :         
450        """Returns 1 if low-level LDAP caching is enabled, else 0."""
451        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
452           
[1148]453    def getDisableHistory(self) :         
454        """Returns 1 if we want to disable history, else 0."""
[1227]455        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
456           
457    def getUserNameToLower(self) :         
458        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
459        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
[1757]460       
[1956]461    def getRejectUnknown(self) :         
462        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
463        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
464       
[2405]465    def getPrinterKeepFiles(self, printername) :         
466        """Returns 1 if files must be kept on disk, else 0."""
467        try : 
468            return self.isTrue(self.getPrinterOption(printername, "keepfiles"))
469        except PyKotaConfigError :   
470            return 0
471           
472    def getPrinterDirectory(self, printername) :         
473        """Returns the path to our working directory, else a directory suitable for temporary files."""
474        try : 
475            return self.getPrinterOption(printername, "directory").strip()
476        except PyKotaConfigError :   
477            return tempfile.gettempdir()
478           
[2066]479    def getDenyDuplicates(self, printername) :         
[2308]480        """Returns 1 or a command if we want to deny duplicate jobs, else 0."""
[2066]481        try : 
[2308]482            denyduplicates = self.getPrinterOption(printername, "denyduplicates")
[2066]483        except PyKotaConfigError :   
484            return 0
[2308]485        else :   
486            if self.isTrue(denyduplicates) :
487                return 1
488            elif self.isFalse(denyduplicates) :
489                return 0
490            else :   
491                # it's a command to run.
492                return denyduplicates
[2066]493       
[1757]494    def getWinbindSeparator(self) :         
495        """Returns the winbind separator's value if it is set, else None."""
496        return self.getGlobalOption("winbind_separator", ignore=1)
[1914]497
498    def getAccountBanner(self, printername) :
499        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
500        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
501        try :
502            value = self.getPrinterOption(printername, "accountbanner")
503        except PyKotaConfigError :   
504            return "BOTH"       # Default value of BOTH
505        else :   
[1916]506            value = value.strip().upper()
[1914]507            if value not in validvalues :
[1916]508                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
[1914]509            return value 
510
511    def getStartingBanner(self, printername) :
512        """Returns the startingbanner value if set, else None."""
513        try :
[1916]514            return self.getPrinterOption(printername, "startingbanner").strip()
[1914]515        except PyKotaConfigError :
516            return None
517
518    def getEndingBanner(self, printername) :
519        """Returns the endingbanner value if set, else None."""
520        try :
[1916]521            return self.getPrinterOption(printername, "endingbanner").strip()
[1914]522        except PyKotaConfigError :
523            return None
[2062]524           
525    def getTrustJobSize(self, printername) :
526        """Returns the normalized value of the trustjobsize's directive."""
527        try :
528            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
529        except PyKotaConfigError :
530            return (None, "YES")
531        else :   
532            if value == "YES" :
533                return (None, "YES")
534            try :   
535                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
536                limit = int(limit)
537                try :
538                    replacement = int(replacement) 
539                except ValueError :   
540                    if replacement != "PRECOMPUTED" :
541                        raise
542                if limit < 0 :
543                    raise ValueError
544                if (replacement != "PRECOMPUTED") and (replacement < 0) :
545                    raise ValueError
546            except (IndexError, ValueError, TypeError) :
547                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
548            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.