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

Revision 1875, 22.7 kB (checked in by jalet, 20 years ago)

For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
to hide print jobs' title, filename, and options.

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