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

Revision 1956, 24.5 kB (checked in by jalet, 19 years ago)

Added the reject_unknown directive to pykota.conf to reject user/group
creation if user or group is unknown to the system

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