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

Revision 1916, 24.1 kB (checked in by jalet, 19 years ago)

Strips spaces just in case

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