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

Revision 1914, 24.0 kB (checked in by jalet, 19 years ago)

Preliminary integration of Matt's patch for banners.

  • 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.55  2004/11/15 15:14:06  jalet
25# Preliminary integration of Matt's patch for banners.
26#
27# Revision 1.54  2004/10/25 14:12:25  jalet
28# For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
29# to hide print jobs' title, filename, and options.
30#
31# Revision 1.53  2004/10/06 10:05:47  jalet
32# Minor changes to allow any PyKota administrator to launch enhanced versions
33# of the commands, and not only the root user.
34#
35# Revision 1.52  2004/09/29 20:20:52  jalet
36# Added the winbind_separator directive to pykota.conf to allow the admin to
37# strip out the Samba/Winbind domain name when users print.
38#
39# Revision 1.51  2004/08/31 23:29:53  jalet
40# Introduction of the new 'onaccountererror' configuration directive.
41# Small fix for software accounter's return code which can't be None anymore.
42# Make software and hardware accounting code look similar : will be factorized
43# later.
44#
45# Revision 1.50  2004/07/27 07:07:27  jalet
46# Typo : treshold ==> threshold
47#
48# Revision 1.49  2004/06/03 21:53:24  jalet
49# crashrecipient directive
50#
51# Revision 1.48  2004/05/24 22:45:49  jalet
52# New 'enforcement' directive added
53# Polling loop improvements
54#
55# Revision 1.47  2004/05/18 14:49:20  jalet
56# Big code changes to completely remove the need for "requester" directives,
57# jsut use "hardware(... your previous requester directive's content ...)"
58#
59# Revision 1.46  2004/05/13 13:59:28  jalet
60# Code simplifications
61#
62# Revision 1.45  2004/03/01 10:22:30  jalet
63# Can now extract per printer pre and post hooks from the configuration file
64#
65# Revision 1.44  2004/02/20 14:42:21  jalet
66# Experimental ldapcache directive added
67#
68# Revision 1.43  2004/02/19 14:20:21  jalet
69# maildomain pykota.conf directive added.
70# Small improvements on mail headers quality.
71#
72# Revision 1.42  2004/01/08 14:10:32  jalet
73# Copyright year changed.
74#
75# Revision 1.41  2003/11/29 20:06:20  jalet
76# Added 'utolower' configuration option to convert all usernames to
77# lowercase when printing. All database accesses are still and will
78# remain case sensitive though.
79#
80# Revision 1.40  2003/11/18 23:43:12  jalet
81# Mailto can be any external command now, as usual.
82#
83# Revision 1.39  2003/10/08 21:41:38  jalet
84# External policies for printers works !
85# We can now auto-add users on first print, and do other useful things if needed.
86#
87# Revision 1.38  2003/10/07 22:06:05  jalet
88# Preliminary code to disable job history
89#
90# Revision 1.37  2003/10/07 09:07:28  jalet
91# Character encoding added to please latest version of Python
92#
93# Revision 1.36  2003/10/02 20:23:18  jalet
94# Storage caching mechanism added.
95#
96# Revision 1.35  2003/07/29 09:54:03  jalet
97# Added configurable LDAP mail attribute support
98#
99# Revision 1.34  2003/07/28 09:11:12  jalet
100# PyKota now tries to add its attributes intelligently in existing LDAP
101# directories.
102#
103# Revision 1.33  2003/07/16 21:53:07  jalet
104# Really big modifications wrt new configuration file's location and content.
105#
106# Revision 1.32  2003/07/08 19:43:51  jalet
107# Configurable warning messages.
108# Poor man's treshold value added.
109#
110# Revision 1.31  2003/07/07 11:49:24  jalet
111# Lots of small fixes with the help of PyChecker
112#
113# Revision 1.30  2003/06/25 14:10:01  jalet
114# Hey, it may work (edpykota --reset excepted) !
115#
116# Revision 1.29  2003/06/14 22:44:21  jalet
117# More work on LDAP storage backend.
118#
119# Revision 1.28  2003/06/10 16:37:54  jalet
120# Deletion of the second user which is not needed anymore.
121# Added a debug configuration field in /etc/pykota.conf
122# All queries can now be sent to the logger in debug mode, this will
123# greatly help improve performance when time for this will come.
124#
125# Revision 1.27  2003/05/27 23:00:21  jalet
126# Big rewrite of external accounting methods.
127# Should work well now.
128#
129# Revision 1.26  2003/04/30 19:53:58  jalet
130# 1.05
131#
132# Revision 1.25  2003/04/30 13:36:40  jalet
133# Stupid accounting method was added.
134#
135# Revision 1.24  2003/04/29 18:37:54  jalet
136# Pluggable accounting methods (actually doesn't support external scripts)
137#
138# Revision 1.23  2003/04/24 11:53:48  jalet
139# Default policy for unknown users/groups is to DENY printing instead
140# of the previous default to ALLOW printing. This is to solve an accuracy
141# problem. If you set the policy to ALLOW, jobs printed by in nexistant user
142# (from PyKota's POV) will be charged to the next user who prints on the
143# same printer.
144#
145# Revision 1.22  2003/04/23 22:13:57  jalet
146# Preliminary support for LPRng added BUT STILL UNTESTED.
147#
148# Revision 1.21  2003/03/29 13:45:27  jalet
149# GPL paragraphs were incorrectly (from memory) copied into the sources.
150# Two README files were added.
151# Upgrade script for PostgreSQL pre 1.01 schema was added.
152#
153# Revision 1.20  2003/03/29 13:08:28  jalet
154# Configuration is now expected to be found in /etc/pykota.conf instead of
155# in /etc/cups/pykota.conf
156# Installation script can move old config files to the new location if needed.
157# Better error handling if configuration file is absent.
158#
159# Revision 1.19  2003/03/16 09:56:52  jalet
160# Mailto option now accepts some additional values which all mean that
161# nobody will receive any email message.
162# Mailto option now works. Version 1.01 is now officially out.
163#
164# Revision 1.18  2003/03/16 08:00:50  jalet
165# Default hard coded options are now used if they are not set in the
166# configuration file.
167#
168# Revision 1.17  2003/03/15 23:01:28  jalet
169# New mailto option in configuration file added.
170# No time to test this tonight (although it should work).
171#
172# Revision 1.16  2003/02/17 23:01:56  jalet
173# Typos
174#
175# Revision 1.15  2003/02/17 22:55:01  jalet
176# More options can now be set per printer or globally :
177#
178#       admin
179#       adminmail
180#       gracedelay
181#       requester
182#
183# the printer option has priority when both are defined.
184#
185# Revision 1.14  2003/02/17 22:05:50  jalet
186# Storage backend now supports admin and user passwords (untested)
187#
188# Revision 1.13  2003/02/10 11:47:39  jalet
189# Moved some code down into the requesters
190#
191# Revision 1.12  2003/02/10 10:36:33  jalet
192# Small problem wrt external requester
193#
194# Revision 1.11  2003/02/10 08:50:45  jalet
195# External requester seems to be finally ok now
196#
197# Revision 1.10  2003/02/10 08:19:57  jalet
198# tell ConfigParser to return raw data, this allows our own strings
199# interpolations in the requester
200#
201# Revision 1.9  2003/02/10 00:44:38  jalet
202# Typos
203#
204# Revision 1.8  2003/02/10 00:42:17  jalet
205# External requester should be ok (untested)
206# New syntax for configuration file wrt requesters
207#
208# Revision 1.7  2003/02/09 13:05:43  jalet
209# Internationalization continues...
210#
211# Revision 1.6  2003/02/07 22:00:09  jalet
212# Bad cut&paste
213#
214# Revision 1.5  2003/02/06 23:58:05  jalet
215# repykota should be ok
216#
217# Revision 1.4  2003/02/06 09:19:02  jalet
218# More robust behavior (hopefully) when the user or printer is not managed
219# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
220# printer and/or user not 'yet?' in storage.
221#
222# Revision 1.3  2003/02/05 23:26:22  jalet
223# Incorrect handling of grace delay
224#
225# Revision 1.2  2003/02/05 23:09:20  jalet
226# Name conflict
227#
228# Revision 1.1  2003/02/05 21:28:17  jalet
229# Initial import into CVS
230#
231#
232#
233
234import os
235import ConfigParser
236
237class PyKotaConfigError(Exception):
238    """An exception for PyKota config related stuff."""
239    def __init__(self, message = ""):
240        self.message = message
241        Exception.__init__(self, message)
242    def __repr__(self):
243        return self.message
244    __str__ = __repr__
245   
246class PyKotaConfig :
247    """A class to deal with PyKota's configuration."""
248    def __init__(self, directory) :
249        """Reads and checks the configuration file."""
250        self.isAdmin = 0
251        self.directory = directory
252        self.filename = os.path.join(directory, "pykota.conf")
253        if not os.path.isfile(self.filename) :
254            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
255        self.config = ConfigParser.ConfigParser()
256        self.config.read([self.filename])
257           
258    def isTrue(self, option) :       
259        """Returns 1 if option is set to true, else 0."""
260        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
261            return 1
262        else :   
263            return 0
264                       
265    def getPrinterNames(self) :   
266        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
267        return [pname for pname in self.config.sections() if pname != "global"]
268       
269    def getGlobalOption(self, option, ignore=0) :   
270        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
271        try :
272            return self.config.get("global", option, raw=1)
273        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
274            if ignore :
275                return
276            else :
277                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
278               
279    def getPrinterOption(self, printername, option) :   
280        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
281        globaloption = self.getGlobalOption(option, ignore=1)
282        try :
283            return self.config.get(printername, option, raw=1)
284        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
285            if globaloption is not None :
286                return globaloption
287            else :
288                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
289       
290    def getStorageBackend(self) :   
291        """Returns the storage backend information as a Python mapping."""       
292        backendinfo = {}
293        for option in [ "storagebackend", "storageserver", \
294                        "storagename", "storageuser", \
295                      ] :
296            backendinfo[option] = self.getGlobalOption(option)
297        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
298        backendinfo["storageadmin"] = None
299        backendinfo["storageadminpw"] = None
300        adminconf = ConfigParser.ConfigParser()
301        filename = os.path.join(self.directory, "pykotadmin.conf")
302        adminconf.read([filename])
303        if adminconf.sections() : # were we able to read the file ?
304            try :
305                backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
306            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
307                raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", filename)
308            else :   
309                self.isAdmin = 1 # We are a PyKota administrator
310            try :
311                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
312            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
313                pass # Password is optional
314        return backendinfo
315       
316    def getLDAPInfo(self) :   
317        """Returns some hints for the LDAP backend."""       
318        ldapinfo = {}
319        for option in [ "userbase", "userrdn", \
320                        "balancebase", "balancerdn", \
321                        "groupbase", "grouprdn", "groupmembers", \
322                        "printerbase", "printerrdn", \
323                        "userquotabase", "groupquotabase", \
324                        "jobbase", "lastjobbase", \
325                        "newuser", "newgroup", \
326                        "usermail", \
327                      ] :
328            ldapinfo[option] = self.getGlobalOption(option).strip()
329        for field in ["newuser", "newgroup"] :
330            if ldapinfo[field].lower().startswith('attach(') :
331                ldapinfo[field] = ldapinfo[field][7:-1]
332        return ldapinfo
333       
334    def getLoggingBackend(self) :   
335        """Returns the logging backend information."""
336        validloggers = [ "stderr", "system" ] 
337        try :
338            logger = self.getGlobalOption("logger").lower()
339        except PyKotaConfigError :   
340            logger = "system"
341        if logger not in validloggers :             
342            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
343        return logger   
344       
345    def getAccounterBackend(self, printername) :   
346        """Returns the accounter backend to use for a given printer.
347       
348           if it is not set, it defaults to 'hardware' which means ask printer
349           for its internal lifetime page counter.
350        """   
351        validaccounters = [ "hardware", "software" ]     
352        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
353        flower = fullaccounter.lower()
354        if flower.startswith("software") or flower.startswith("hardware") :   
355            try :
356                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
357            except ValueError :   
358                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
359            if args.endswith(')') :
360                args = args[:-1]
361            if not args :
362                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
363            return (accounter.lower(), args)   
364        else :
365            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
366       
367    def getPreHook(self, printername) :   
368        """Returns the prehook command line to launch, or None if unset."""
369        try :
370            return self.getPrinterOption(printername, "prehook").strip()
371        except PyKotaConfigError :   
372            return      # No command to launch in the pre-hook
373           
374    def getPostHook(self, printername) :   
375        """Returns the posthook command line to launch, or None if unset."""
376        try :
377            return self.getPrinterOption(printername, "posthook").strip()
378        except PyKotaConfigError :   
379            return      # No command to launch in the post-hook
380           
381    def getPrinterEnforcement(self, printername) :   
382        """Returns if quota enforcement should be strict or laxist for the current printer."""
383        validenforcements = [ "STRICT", "LAXIST" ]     
384        try :
385            enforcement = self.getPrinterOption(printername, "enforcement")
386        except PyKotaConfigError :   
387            return "LAXIST"
388        else :   
389            enforcement = enforcement.upper()
390            if enforcement not in validenforcements :
391                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
392            return enforcement   
393           
394    def getPrinterOnAccounterError(self, printername) :   
395        """Returns what must be done whenever the accounter fails."""
396        validactions = [ "CONTINUE", "STOP" ]     
397        try :
398            action = self.getPrinterOption(printername, "onaccountererror")
399        except PyKotaConfigError :   
400            return "STOP"
401        else :   
402            action = action.upper()
403            if action not in validactions :
404                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
405            return action 
406           
407    def getPrinterPolicy(self, printername) :   
408        """Returns the default policy for the current printer."""
409        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
410        try :
411            fullpolicy = self.getPrinterOption(printername, "policy")
412        except PyKotaConfigError :   
413            return ("DENY", None)
414        else :   
415            try :
416                policy = [x.strip() for x in fullpolicy.split('(', 1)]
417            except ValueError :   
418                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
419            if len(policy) == 1 :   
420                policy.append("")
421            (policy, args) = policy   
422            if args.endswith(')') :
423                args = args[:-1]
424            policy = policy.upper()   
425            if (policy == "EXTERNAL") and not args :
426                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
427            if policy not in validpolicies :
428                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
429            return (policy, args)
430       
431    def getCrashRecipient(self) :   
432        """Returns the email address of the software crash messages recipient."""
433        try :
434            return self.getGlobalOption("crashrecipient")
435        except :   
436            return
437           
438    def getSMTPServer(self) :   
439        """Returns the SMTP server to use to send messages to users."""
440        try :
441            return self.getGlobalOption("smtpserver")
442        except PyKotaConfigError :   
443            return "localhost"
444       
445    def getMailDomain(self) :   
446        """Returns the mail domain to use to send messages to users."""
447        try :
448            return self.getGlobalOption("maildomain")
449        except PyKotaConfigError :   
450            return 
451       
452    def getAdminMail(self, printername) :   
453        """Returns the Email address of the Print Quota Administrator."""
454        try :
455            return self.getPrinterOption(printername, "adminmail")
456        except PyKotaConfigError :   
457            return "root@localhost"
458       
459    def getAdmin(self, printername) :   
460        """Returns the full name of the Print Quota Administrator."""
461        try :
462            return self.getPrinterOption(printername, "admin")
463        except PyKotaConfigError :   
464            return "root"
465       
466    def getMailTo(self, printername) :   
467        """Returns the recipient of email messages."""
468        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
469        try :
470            fullmailto = self.getPrinterOption(printername, "mailto")
471        except PyKotaConfigError :   
472            return ("BOTH", None)
473        else :   
474            try :
475                mailto = [x.strip() for x in fullmailto.split('(', 1)]
476            except ValueError :   
477                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
478            if len(mailto) == 1 :   
479                mailto.append("")
480            (mailto, args) = mailto   
481            if args.endswith(')') :
482                args = args[:-1]
483            mailto = mailto.upper()   
484            if (mailto == "EXTERNAL") and not args :
485                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
486            if mailto not in validmailtos :
487                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
488            return (mailto, args)
489       
490    def getGraceDelay(self, printername) :   
491        """Returns the grace delay in days."""
492        try :
493            gd = self.getPrinterOption(printername, "gracedelay")
494        except PyKotaConfigError :   
495            gd = 7      # default value of 7 days
496        try :
497            return int(gd)
498        except (TypeError, ValueError) :   
499            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
500           
501    def getPoorMan(self) :   
502        """Returns the poor man's threshold."""
503        try :
504            pm = self.getGlobalOption("poorman")
505        except PyKotaConfigError :   
506            pm = 1.0    # default value of 1 unit
507        try :
508            return float(pm)
509        except (TypeError, ValueError) :   
510            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
511           
512    def getPoorWarn(self) :   
513        """Returns the poor man's warning message."""
514        try :
515            return self.getGlobalOption("poorwarn")
516        except PyKotaConfigError :   
517            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.")
518           
519    def getHardWarn(self, printername) :   
520        """Returns the hard limit error message."""
521        try :
522            return self.getPrinterOption(printername, "hardwarn")
523        except PyKotaConfigError :   
524            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
525           
526    def getSoftWarn(self, printername) :   
527        """Returns the soft limit error message."""
528        try :
529            return self.getPrinterOption(printername, "softwarn")
530        except PyKotaConfigError :   
531            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
532           
533    def getPrivacy(self) :       
534        """Returns 1 if privacy is activated, else 0."""
535        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
536       
537    def getDebug(self) :         
538        """Returns 1 if debugging is activated, else 0."""
539        return self.isTrue(self.getGlobalOption("debug", ignore=1))
540           
541    def getCaching(self) :         
542        """Returns 1 if database caching is enabled, else 0."""
543        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
544           
545    def getLDAPCache(self) :         
546        """Returns 1 if low-level LDAP caching is enabled, else 0."""
547        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
548           
549    def getDisableHistory(self) :         
550        """Returns 1 if we want to disable history, else 0."""
551        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
552           
553    def getUserNameToLower(self) :         
554        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
555        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
556       
557    def getWinbindSeparator(self) :         
558        """Returns the winbind separator's value if it is set, else None."""
559        return self.getGlobalOption("winbind_separator", ignore=1)
560
561    def getAccountBanner(self, printername) :
562        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
563        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
564        try :
565            value = self.getPrinterOption(printername, "accountbanner")
566        except PyKotaConfigError :   
567            return "BOTH"       # Default value of BOTH
568        else :   
569            value = value.upper()
570            if value not in validvalues :
571                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validvalues))
572            return value 
573
574    def getStartingBanner(self, printername) :
575        """Returns the startingbanner value if set, else None."""
576        try :
577            return self.getPrinterOption(printername, "startingbanner")
578        except PyKotaConfigError :
579            return None
580
581    def getEndingBanner(self, printername) :
582        """Returns the endingbanner value if set, else None."""
583        try :
584            return self.getPrinterOption(printername, "endingbanner")
585        except PyKotaConfigError :
586            return None
Note: See TracBrowser for help on using the browser.