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

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

Preliminary work on the "onbackenderror" directive.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
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.
11#
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
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import os
26import tempfile
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."""
42        self.isAdmin = 0
43        self.directory = directory
44        self.filename = os.path.join(directory, "pykota.conf")
45        self.adminfilename = os.path.join(directory, "pykotadmin.conf")
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
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
52        self.config = ConfigParser.ConfigParser()
53        self.config.read([self.filename])
54           
55    def isTrue(self, option) :       
56        """Returns 1 if option is set to true, else 0."""
57        if (option is not None) and (option.strip().upper() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
58            return 1
59        else :   
60            return 0
61                       
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                       
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       
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               
83    def getPrinterOption(self, printername, option) :   
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 :
87            return self.config.get(printername, option, raw=1)
88        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
89            if globaloption is not None :
90                return globaloption
91            else :
92                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
93       
94    def getStorageBackend(self) :   
95        """Returns the storage backend information as a Python mapping."""       
96        backendinfo = {}
97        for option in [ "storagebackend", "storageserver", \
98                        "storagename", "storageuser", \
99                      ] :
100            backendinfo[option] = self.getGlobalOption(option)
101        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
102        backendinfo["storageadmin"] = None
103        backendinfo["storageadminpw"] = None
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
131        return backendinfo
132       
133    def getLDAPInfo(self) :   
134        """Returns some hints for the LDAP backend."""       
135        ldapinfo = {}
136        for option in [ "userbase", "userrdn", \
137                        "balancebase", "balancerdn", \
138                        "groupbase", "grouprdn", "groupmembers", \
139                        "printerbase", "printerrdn", \
140                        "userquotabase", "groupquotabase", \
141                        "jobbase", "lastjobbase", "billingcodebase", \
142                        "newuser", "newgroup", \
143                        "usermail", \
144                      ] :
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]
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"])
158        return ldapinfo
159       
160    def getLoggingBackend(self) :   
161        """Returns the logging backend information."""
162        validloggers = [ "stderr", "system" ] 
163        try :
164            logger = self.getGlobalOption("logger").lower()
165        except PyKotaConfigError :   
166            logger = "system"
167        if logger not in validloggers :             
168            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
169        return logger   
170       
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()           
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()           
182   
183    def getAccounterBackend(self, printername) :   
184        """Returns the accounter backend to use for a given printer.
185       
186           if it is not set, it defaults to 'hardware' which means ask printer
187           for its internal lifetime page counter.
188        """   
189        validaccounters = [ "hardware", "software" ]     
190        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
191        flower = fullaccounter.lower()
192        if flower.startswith("software") or flower.startswith("hardware") :   
193            try :
194                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
195            except ValueError :   
196                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
197            if args.endswith(')') :
198                args = args[:-1].strip()
199            if (accounter == "hardware") and not args :
200                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
201            return (accounter.lower(), args)
202        else :
203            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
204       
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           
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           
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       
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           
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           
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           
296    def getPrinterPolicy(self, printername) :   
297        """Returns the default policy for the current printer."""
298        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
299        try :
300            fullpolicy = self.getPrinterOption(printername, "policy")
301        except PyKotaConfigError :   
302            return ("DENY", None)
303        else :   
304            try :
305                policy = [x.strip() for x in fullpolicy.split('(', 1)]
306            except ValueError :   
307                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
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 :
315                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
316            if policy not in validpolicies :
317                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
318            return (policy, args)
319       
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           
327    def getSMTPServer(self) :   
328        """Returns the SMTP server to use to send messages to users."""
329        try :
330            return self.getGlobalOption("smtpserver")
331        except PyKotaConfigError :   
332            return "localhost"
333       
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       
341    def getAdminMail(self, printername) :   
342        """Returns the Email address of the Print Quota Administrator."""
343        try :
344            return self.getPrinterOption(printername, "adminmail")
345        except PyKotaConfigError :   
346            return "root@localhost"
347       
348    def getAdmin(self, printername) :   
349        """Returns the full name of the Print Quota Administrator."""
350        try :
351            return self.getPrinterOption(printername, "admin")
352        except PyKotaConfigError :   
353            return "root"
354       
355    def getMailTo(self, printername) :   
356        """Returns the recipient of email messages."""
357        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
358        try :
359            fullmailto = self.getPrinterOption(printername, "mailto")
360        except PyKotaConfigError :   
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)
378       
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           
394    def getGraceDelay(self, printername) :   
395        """Returns the grace delay in days."""
396        try :
397            gd = self.getPrinterOption(printername, "gracedelay")
398        except PyKotaConfigError :   
399            gd = 7      # default value of 7 days
400        try :
401            return int(gd)
402        except (TypeError, ValueError) :   
403            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
404           
405    def getPoorMan(self) :   
406        """Returns the poor man's threshold."""
407        try :
408            pm = self.getGlobalOption("poorman")
409        except PyKotaConfigError :   
410            pm = 1.0    # default value of 1 unit
411        try :
412            return float(pm)
413        except (TypeError, ValueError) :   
414            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
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           
423    def getHardWarn(self, printername) :   
424        """Returns the hard limit error message."""
425        try :
426            return self.getPrinterOption(printername, "hardwarn")
427        except PyKotaConfigError :   
428            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
429           
430    def getSoftWarn(self, printername) :   
431        """Returns the soft limit error message."""
432        try :
433            return self.getPrinterOption(printername, "softwarn")
434        except PyKotaConfigError :   
435            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
436           
437    def getPrivacy(self) :       
438        """Returns 1 if privacy is activated, else 0."""
439        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
440       
441    def getDebug(self) :         
442        """Returns 1 if debugging is activated, else 0."""
443        return self.isTrue(self.getGlobalOption("debug", ignore=1))
444           
445    def getCaching(self) :         
446        """Returns 1 if database caching is enabled, else 0."""
447        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
448           
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           
453    def getDisableHistory(self) :         
454        """Returns 1 if we want to disable history, else 0."""
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))
460       
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       
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           
479    def getDenyDuplicates(self, printername) :         
480        """Returns 1 or a command if we want to deny duplicate jobs, else 0."""
481        try : 
482            denyduplicates = self.getPrinterOption(printername, "denyduplicates")
483        except PyKotaConfigError :   
484            return 0
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
493       
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)
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 :   
506            value = value.strip().upper()
507            if value not in validvalues :
508                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
509            return value 
510
511    def getStartingBanner(self, printername) :
512        """Returns the startingbanner value if set, else None."""
513        try :
514            return self.getPrinterOption(printername, "startingbanner").strip()
515        except PyKotaConfigError :
516            return None
517
518    def getEndingBanner(self, printername) :
519        """Returns the endingbanner value if set, else None."""
520        try :
521            return self.getPrinterOption(printername, "endingbanner").strip()
522        except PyKotaConfigError :
523            return None
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.