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

Revision 2405, 23.5 kB (checked in by jerome, 19 years ago)

Added support for the new 'directory' and 'keepfiles' directives.
Both will be used in the new cupspykota backend.

  • 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        if not os.path.isfile(self.filename) :
46            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
47        self.config = ConfigParser.ConfigParser()
48        self.config.read([self.filename])
49           
50    def isTrue(self, option) :       
51        """Returns 1 if option is set to true, else 0."""
52        if (option is not None) and (option.strip().upper() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
53            return 1
54        else :   
55            return 0
56                       
57    def isFalse(self, option) :       
58        """Returns 1 if option is set to false, else 0."""
59        if (option is not None) and (option.strip().upper() in ['N', 'NO', '0', 'OFF', 'F', 'FALSE']) :
60            return 1
61        else :   
62            return 0
63                       
64    def getPrinterNames(self) :   
65        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
66        return [pname for pname in self.config.sections() if pname != "global"]
67       
68    def getGlobalOption(self, option, ignore=0) :   
69        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
70        try :
71            return self.config.get("global", option, raw=1)
72        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
73            if ignore :
74                return
75            else :
76                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
77               
78    def getPrinterOption(self, printername, option) :   
79        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
80        globaloption = self.getGlobalOption(option, ignore=1)
81        try :
82            return self.config.get(printername, option, raw=1)
83        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
84            if globaloption is not None :
85                return globaloption
86            else :
87                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
88       
89    def getStorageBackend(self) :   
90        """Returns the storage backend information as a Python mapping."""       
91        backendinfo = {}
92        for option in [ "storagebackend", "storageserver", \
93                        "storagename", "storageuser", \
94                      ] :
95            backendinfo[option] = self.getGlobalOption(option)
96        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
97        backendinfo["storageadmin"] = None
98        backendinfo["storageadminpw"] = None
99        adminconf = ConfigParser.ConfigParser()
100        filename = os.path.join(self.directory, "pykotadmin.conf")
101        adminconf.read([filename])
102        if adminconf.sections() : # were we able to read the file ?
103            try :
104                backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
105            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
106                raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", filename)
107            else :   
108                self.isAdmin = 1 # We are a PyKota administrator
109            try :
110                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
111            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
112                pass # Password is optional
113        return backendinfo
114       
115    def getLDAPInfo(self) :   
116        """Returns some hints for the LDAP backend."""       
117        ldapinfo = {}
118        for option in [ "userbase", "userrdn", \
119                        "balancebase", "balancerdn", \
120                        "groupbase", "grouprdn", "groupmembers", \
121                        "printerbase", "printerrdn", \
122                        "userquotabase", "groupquotabase", \
123                        "jobbase", "lastjobbase", "billingcodebase", \
124                        "newuser", "newgroup", \
125                        "usermail", \
126                      ] :
127            ldapinfo[option] = self.getGlobalOption(option).strip()
128        for field in ["newuser", "newgroup"] :
129            if ldapinfo[field].lower().startswith('attach(') :
130                ldapinfo[field] = ldapinfo[field][7:-1]
131               
132        # should we use TLS, by default (if unset) value is NO       
133        ldapinfo["ldaptls"] = self.isTrue(self.getGlobalOption("ldaptls", ignore=1))
134        ldapinfo["cacert"] = self.getGlobalOption("cacert", ignore=1)
135        if ldapinfo["cacert"] :
136            ldapinfo["cacert"] = ldapinfo["cacert"].strip()
137        if ldapinfo["ldaptls"] :   
138            if not os.access(ldapinfo["cacert"] or "", os.R_OK) :
139                raise PyKotaConfigError, _("Option ldaptls is set, but certificate %s is not readable.") % str(ldapinfo["cacert"])
140        return ldapinfo
141       
142    def getLoggingBackend(self) :   
143        """Returns the logging backend information."""
144        validloggers = [ "stderr", "system" ] 
145        try :
146            logger = self.getGlobalOption("logger").lower()
147        except PyKotaConfigError :   
148            logger = "system"
149        if logger not in validloggers :             
150            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
151        return logger   
152       
153    def getLogoURL(self) :
154        """Returns the URL to use for the logo in the CGI scripts."""
155        url = self.getGlobalOption("logourl", ignore=1) or \
156                   "http://www.librelogiciel.com/software/PyKota/pykota.png"
157        return url.strip()           
158       
159    def getLogoLink(self) :
160        """Returns the URL to go to when the user clicks on the logo in the CGI scripts."""
161        url = self.getGlobalOption("logolink", ignore=1) or \
162                   "http://www.librelogiciel.com/software/"
163        return url.strip()           
164   
165    def getAccounterBackend(self, printername) :   
166        """Returns the accounter backend to use for a given printer.
167       
168           if it is not set, it defaults to 'hardware' which means ask printer
169           for its internal lifetime page counter.
170        """   
171        validaccounters = [ "hardware", "software" ]     
172        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
173        flower = fullaccounter.lower()
174        if flower.startswith("software") or flower.startswith("hardware") :   
175            try :
176                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
177            except ValueError :   
178                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
179            if args.endswith(')') :
180                args = args[:-1].strip()
181            if (accounter == "hardware") and not args :
182                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
183            return (accounter.lower(), args)   
184        else :
185            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
186       
187    def getPreHook(self, printername) :   
188        """Returns the prehook command line to launch, or None if unset."""
189        try :
190            return self.getPrinterOption(printername, "prehook").strip()
191        except PyKotaConfigError :   
192            return      # No command to launch in the pre-hook
193           
194    def getPostHook(self, printername) :   
195        """Returns the posthook command line to launch, or None if unset."""
196        try :
197            return self.getPrinterOption(printername, "posthook").strip()
198        except PyKotaConfigError :   
199            return      # No command to launch in the post-hook
200           
201    def getStripTitle(self, printername) :   
202        """Returns the striptitle directive's content, or None if unset."""
203        try :
204            return self.getPrinterOption(printername, "striptitle").strip()
205        except PyKotaConfigError :   
206            return      # No prefix to strip off
207           
208    def getOverwriteJobTicket(self, printername) :       
209        """Returns the overwrite_jobticket directive's content, or None if unset."""
210        try :
211            return self.getPrinterOption(printername, "overwrite_jobticket").strip()
212        except PyKotaConfigError :   
213            return      # No overwriting will be done
214       
215    def getUnknownBillingCode(self, printername) :       
216        """Returns the unknown_billingcode directive's content, or the default value if unset."""
217        validvalues = [ "CREATE", "DENY" ]
218        try :
219            fullvalue = self.getPrinterOption(printername, "unknown_billingcode")
220        except PyKotaConfigError :   
221            return ("CREATE", None)
222        else :   
223            try :
224                value = [x.strip() for x in fullvalue.split('(', 1)]
225            except ValueError :   
226                raise PyKotaConfigError, _("Invalid unknown_billingcode directive %s for printer %s") % (fullvalue, printername)
227            if len(value) == 1 :   
228                value.append("")
229            (value, args) = value   
230            if args.endswith(')') :
231                args = args[:-1]
232            value = value.upper()   
233            if (value == "DENY") and not args :
234                return ("DENY", None)
235            if value not in validvalues :
236                raise PyKotaConfigError, _("Directive unknown_billingcode in section %s only supports values in %s") % (printername, str(validvalues))
237            return (value, args)
238       
239    def getPrinterEnforcement(self, printername) :   
240        """Returns if quota enforcement should be strict or laxist for the current printer."""
241        validenforcements = [ "STRICT", "LAXIST" ]     
242        try :
243            enforcement = self.getPrinterOption(printername, "enforcement")
244        except PyKotaConfigError :   
245            return "LAXIST"
246        else :   
247            enforcement = enforcement.upper()
248            if enforcement not in validenforcements :
249                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
250            return enforcement   
251           
252    def getPrinterOnAccounterError(self, printername) :   
253        """Returns what must be done whenever the accounter fails."""
254        validactions = [ "CONTINUE", "STOP" ]     
255        try :
256            action = self.getPrinterOption(printername, "onaccountererror")
257        except PyKotaConfigError :   
258            return "STOP"
259        else :   
260            action = action.upper()
261            if action not in validactions :
262                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
263            return action 
264           
265    def getPrinterPolicy(self, printername) :   
266        """Returns the default policy for the current printer."""
267        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
268        try :
269            fullpolicy = self.getPrinterOption(printername, "policy")
270        except PyKotaConfigError :   
271            return ("DENY", None)
272        else :   
273            try :
274                policy = [x.strip() for x in fullpolicy.split('(', 1)]
275            except ValueError :   
276                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
277            if len(policy) == 1 :   
278                policy.append("")
279            (policy, args) = policy   
280            if args.endswith(')') :
281                args = args[:-1]
282            policy = policy.upper()   
283            if (policy == "EXTERNAL") and not args :
284                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
285            if policy not in validpolicies :
286                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
287            return (policy, args)
288       
289    def getCrashRecipient(self) :   
290        """Returns the email address of the software crash messages recipient."""
291        try :
292            return self.getGlobalOption("crashrecipient")
293        except :   
294            return
295           
296    def getSMTPServer(self) :   
297        """Returns the SMTP server to use to send messages to users."""
298        try :
299            return self.getGlobalOption("smtpserver")
300        except PyKotaConfigError :   
301            return "localhost"
302       
303    def getMailDomain(self) :   
304        """Returns the mail domain to use to send messages to users."""
305        try :
306            return self.getGlobalOption("maildomain")
307        except PyKotaConfigError :   
308            return 
309       
310    def getAdminMail(self, printername) :   
311        """Returns the Email address of the Print Quota Administrator."""
312        try :
313            return self.getPrinterOption(printername, "adminmail")
314        except PyKotaConfigError :   
315            return "root@localhost"
316       
317    def getAdmin(self, printername) :   
318        """Returns the full name of the Print Quota Administrator."""
319        try :
320            return self.getPrinterOption(printername, "admin")
321        except PyKotaConfigError :   
322            return "root"
323       
324    def getMailTo(self, printername) :   
325        """Returns the recipient of email messages."""
326        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
327        try :
328            fullmailto = self.getPrinterOption(printername, "mailto")
329        except PyKotaConfigError :   
330            return ("BOTH", None)
331        else :   
332            try :
333                mailto = [x.strip() for x in fullmailto.split('(', 1)]
334            except ValueError :   
335                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
336            if len(mailto) == 1 :   
337                mailto.append("")
338            (mailto, args) = mailto   
339            if args.endswith(')') :
340                args = args[:-1]
341            mailto = mailto.upper()   
342            if (mailto == "EXTERNAL") and not args :
343                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
344            if mailto not in validmailtos :
345                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
346            return (mailto, args)
347       
348    def getMaxDenyBanners(self, printername) :   
349        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
350        try :
351            maxdb = self.getPrinterOption(printername, "maxdenybanners")
352        except PyKotaConfigError :   
353            return 0 # default value is to forbid printing a deny banner.
354        try :
355            value = int(maxdb.strip())
356            if value < 0 :
357                raise ValueError
358        except (TypeError, ValueError) :   
359            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
360        else :   
361            return value
362           
363    def getGraceDelay(self, printername) :   
364        """Returns the grace delay in days."""
365        try :
366            gd = self.getPrinterOption(printername, "gracedelay")
367        except PyKotaConfigError :   
368            gd = 7      # default value of 7 days
369        try :
370            return int(gd)
371        except (TypeError, ValueError) :   
372            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
373           
374    def getPoorMan(self) :   
375        """Returns the poor man's threshold."""
376        try :
377            pm = self.getGlobalOption("poorman")
378        except PyKotaConfigError :   
379            pm = 1.0    # default value of 1 unit
380        try :
381            return float(pm)
382        except (TypeError, ValueError) :   
383            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
384           
385    def getPoorWarn(self) :   
386        """Returns the poor man's warning message."""
387        try :
388            return self.getGlobalOption("poorwarn")
389        except PyKotaConfigError :   
390            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.")
391           
392    def getHardWarn(self, printername) :   
393        """Returns the hard limit error message."""
394        try :
395            return self.getPrinterOption(printername, "hardwarn")
396        except PyKotaConfigError :   
397            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
398           
399    def getSoftWarn(self, printername) :   
400        """Returns the soft limit error message."""
401        try :
402            return self.getPrinterOption(printername, "softwarn")
403        except PyKotaConfigError :   
404            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
405           
406    def getPrivacy(self) :       
407        """Returns 1 if privacy is activated, else 0."""
408        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
409       
410    def getDebug(self) :         
411        """Returns 1 if debugging is activated, else 0."""
412        return self.isTrue(self.getGlobalOption("debug", ignore=1))
413           
414    def getCaching(self) :         
415        """Returns 1 if database caching is enabled, else 0."""
416        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
417           
418    def getLDAPCache(self) :         
419        """Returns 1 if low-level LDAP caching is enabled, else 0."""
420        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
421           
422    def getDisableHistory(self) :         
423        """Returns 1 if we want to disable history, else 0."""
424        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
425           
426    def getUserNameToLower(self) :         
427        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
428        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
429       
430    def getRejectUnknown(self) :         
431        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
432        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
433       
434    def getPrinterKeepFiles(self, printername) :         
435        """Returns 1 if files must be kept on disk, else 0."""
436        try : 
437            return self.isTrue(self.getPrinterOption(printername, "keepfiles"))
438        except PyKotaConfigError :   
439            return 0
440           
441    def getPrinterDirectory(self, printername) :         
442        """Returns the path to our working directory, else a directory suitable for temporary files."""
443        try : 
444            return self.getPrinterOption(printername, "directory").strip()
445        except PyKotaConfigError :   
446            return tempfile.gettempdir()
447           
448    def getDenyDuplicates(self, printername) :         
449        """Returns 1 or a command if we want to deny duplicate jobs, else 0."""
450        try : 
451            denyduplicates = self.getPrinterOption(printername, "denyduplicates")
452        except PyKotaConfigError :   
453            return 0
454        else :   
455            if self.isTrue(denyduplicates) :
456                return 1
457            elif self.isFalse(denyduplicates) :
458                return 0
459            else :   
460                # it's a command to run.
461                return denyduplicates
462       
463    def getWinbindSeparator(self) :         
464        """Returns the winbind separator's value if it is set, else None."""
465        return self.getGlobalOption("winbind_separator", ignore=1)
466
467    def getAccountBanner(self, printername) :
468        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
469        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
470        try :
471            value = self.getPrinterOption(printername, "accountbanner")
472        except PyKotaConfigError :   
473            return "BOTH"       # Default value of BOTH
474        else :   
475            value = value.strip().upper()
476            if value not in validvalues :
477                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
478            return value 
479
480    def getStartingBanner(self, printername) :
481        """Returns the startingbanner value if set, else None."""
482        try :
483            return self.getPrinterOption(printername, "startingbanner").strip()
484        except PyKotaConfigError :
485            return None
486
487    def getEndingBanner(self, printername) :
488        """Returns the endingbanner value if set, else None."""
489        try :
490            return self.getPrinterOption(printername, "endingbanner").strip()
491        except PyKotaConfigError :
492            return None
493           
494    def getTrustJobSize(self, printername) :
495        """Returns the normalized value of the trustjobsize's directive."""
496        try :
497            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
498        except PyKotaConfigError :
499            return (None, "YES")
500        else :   
501            if value == "YES" :
502                return (None, "YES")
503            try :   
504                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
505                limit = int(limit)
506                try :
507                    replacement = int(replacement) 
508                except ValueError :   
509                    if replacement != "PRECOMPUTED" :
510                        raise
511                if limit < 0 :
512                    raise ValueError
513                if (replacement != "PRECOMPUTED") and (replacement < 0) :
514                    raise ValueError
515            except (IndexError, ValueError, TypeError) :
516                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
517            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.