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

Revision 1757, 22.1 kB (checked in by jalet, 20 years ago)

Added the winbind_separator directive to pykota.conf to allow the admin to
strip out the Samba/Winbind domain name when users print.

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