1 | # PyKota |
---|
2 | # -*- coding: ISO-8859-15 -*- |
---|
3 | # |
---|
4 | # PyKota : Print Quotas for CUPS and LPRng |
---|
5 | # |
---|
6 | # (c) 2003 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.38 2003/10/07 22:06:05 jalet |
---|
25 | # Preliminary code to disable job history |
---|
26 | # |
---|
27 | # Revision 1.37 2003/10/07 09:07:28 jalet |
---|
28 | # Character encoding added to please latest version of Python |
---|
29 | # |
---|
30 | # Revision 1.36 2003/10/02 20:23:18 jalet |
---|
31 | # Storage caching mechanism added. |
---|
32 | # |
---|
33 | # Revision 1.35 2003/07/29 09:54:03 jalet |
---|
34 | # Added configurable LDAP mail attribute support |
---|
35 | # |
---|
36 | # Revision 1.34 2003/07/28 09:11:12 jalet |
---|
37 | # PyKota now tries to add its attributes intelligently in existing LDAP |
---|
38 | # directories. |
---|
39 | # |
---|
40 | # Revision 1.33 2003/07/16 21:53:07 jalet |
---|
41 | # Really big modifications wrt new configuration file's location and content. |
---|
42 | # |
---|
43 | # Revision 1.32 2003/07/08 19:43:51 jalet |
---|
44 | # Configurable warning messages. |
---|
45 | # Poor man's treshold value added. |
---|
46 | # |
---|
47 | # Revision 1.31 2003/07/07 11:49:24 jalet |
---|
48 | # Lots of small fixes with the help of PyChecker |
---|
49 | # |
---|
50 | # Revision 1.30 2003/06/25 14:10:01 jalet |
---|
51 | # Hey, it may work (edpykota --reset excepted) ! |
---|
52 | # |
---|
53 | # Revision 1.29 2003/06/14 22:44:21 jalet |
---|
54 | # More work on LDAP storage backend. |
---|
55 | # |
---|
56 | # Revision 1.28 2003/06/10 16:37:54 jalet |
---|
57 | # Deletion of the second user which is not needed anymore. |
---|
58 | # Added a debug configuration field in /etc/pykota.conf |
---|
59 | # All queries can now be sent to the logger in debug mode, this will |
---|
60 | # greatly help improve performance when time for this will come. |
---|
61 | # |
---|
62 | # Revision 1.27 2003/05/27 23:00:21 jalet |
---|
63 | # Big rewrite of external accounting methods. |
---|
64 | # Should work well now. |
---|
65 | # |
---|
66 | # Revision 1.26 2003/04/30 19:53:58 jalet |
---|
67 | # 1.05 |
---|
68 | # |
---|
69 | # Revision 1.25 2003/04/30 13:36:40 jalet |
---|
70 | # Stupid accounting method was added. |
---|
71 | # |
---|
72 | # Revision 1.24 2003/04/29 18:37:54 jalet |
---|
73 | # Pluggable accounting methods (actually doesn't support external scripts) |
---|
74 | # |
---|
75 | # Revision 1.23 2003/04/24 11:53:48 jalet |
---|
76 | # Default policy for unknown users/groups is to DENY printing instead |
---|
77 | # of the previous default to ALLOW printing. This is to solve an accuracy |
---|
78 | # problem. If you set the policy to ALLOW, jobs printed by in nexistant user |
---|
79 | # (from PyKota's POV) will be charged to the next user who prints on the |
---|
80 | # same printer. |
---|
81 | # |
---|
82 | # Revision 1.22 2003/04/23 22:13:57 jalet |
---|
83 | # Preliminary support for LPRng added BUT STILL UNTESTED. |
---|
84 | # |
---|
85 | # Revision 1.21 2003/03/29 13:45:27 jalet |
---|
86 | # GPL paragraphs were incorrectly (from memory) copied into the sources. |
---|
87 | # Two README files were added. |
---|
88 | # Upgrade script for PostgreSQL pre 1.01 schema was added. |
---|
89 | # |
---|
90 | # Revision 1.20 2003/03/29 13:08:28 jalet |
---|
91 | # Configuration is now expected to be found in /etc/pykota.conf instead of |
---|
92 | # in /etc/cups/pykota.conf |
---|
93 | # Installation script can move old config files to the new location if needed. |
---|
94 | # Better error handling if configuration file is absent. |
---|
95 | # |
---|
96 | # Revision 1.19 2003/03/16 09:56:52 jalet |
---|
97 | # Mailto option now accepts some additional values which all mean that |
---|
98 | # nobody will receive any email message. |
---|
99 | # Mailto option now works. Version 1.01 is now officially out. |
---|
100 | # |
---|
101 | # Revision 1.18 2003/03/16 08:00:50 jalet |
---|
102 | # Default hard coded options are now used if they are not set in the |
---|
103 | # configuration file. |
---|
104 | # |
---|
105 | # Revision 1.17 2003/03/15 23:01:28 jalet |
---|
106 | # New mailto option in configuration file added. |
---|
107 | # No time to test this tonight (although it should work). |
---|
108 | # |
---|
109 | # Revision 1.16 2003/02/17 23:01:56 jalet |
---|
110 | # Typos |
---|
111 | # |
---|
112 | # Revision 1.15 2003/02/17 22:55:01 jalet |
---|
113 | # More options can now be set per printer or globally : |
---|
114 | # |
---|
115 | # admin |
---|
116 | # adminmail |
---|
117 | # gracedelay |
---|
118 | # requester |
---|
119 | # |
---|
120 | # the printer option has priority when both are defined. |
---|
121 | # |
---|
122 | # Revision 1.14 2003/02/17 22:05:50 jalet |
---|
123 | # Storage backend now supports admin and user passwords (untested) |
---|
124 | # |
---|
125 | # Revision 1.13 2003/02/10 11:47:39 jalet |
---|
126 | # Moved some code down into the requesters |
---|
127 | # |
---|
128 | # Revision 1.12 2003/02/10 10:36:33 jalet |
---|
129 | # Small problem wrt external requester |
---|
130 | # |
---|
131 | # Revision 1.11 2003/02/10 08:50:45 jalet |
---|
132 | # External requester seems to be finally ok now |
---|
133 | # |
---|
134 | # Revision 1.10 2003/02/10 08:19:57 jalet |
---|
135 | # tell ConfigParser to return raw data, this allows our own strings |
---|
136 | # interpolations in the requester |
---|
137 | # |
---|
138 | # Revision 1.9 2003/02/10 00:44:38 jalet |
---|
139 | # Typos |
---|
140 | # |
---|
141 | # Revision 1.8 2003/02/10 00:42:17 jalet |
---|
142 | # External requester should be ok (untested) |
---|
143 | # New syntax for configuration file wrt requesters |
---|
144 | # |
---|
145 | # Revision 1.7 2003/02/09 13:05:43 jalet |
---|
146 | # Internationalization continues... |
---|
147 | # |
---|
148 | # Revision 1.6 2003/02/07 22:00:09 jalet |
---|
149 | # Bad cut&paste |
---|
150 | # |
---|
151 | # Revision 1.5 2003/02/06 23:58:05 jalet |
---|
152 | # repykota should be ok |
---|
153 | # |
---|
154 | # Revision 1.4 2003/02/06 09:19:02 jalet |
---|
155 | # More robust behavior (hopefully) when the user or printer is not managed |
---|
156 | # correctly by the Quota System : e.g. cupsFilter added in ppd file, but |
---|
157 | # printer and/or user not 'yet?' in storage. |
---|
158 | # |
---|
159 | # Revision 1.3 2003/02/05 23:26:22 jalet |
---|
160 | # Incorrect handling of grace delay |
---|
161 | # |
---|
162 | # Revision 1.2 2003/02/05 23:09:20 jalet |
---|
163 | # Name conflict |
---|
164 | # |
---|
165 | # Revision 1.1 2003/02/05 21:28:17 jalet |
---|
166 | # Initial import into CVS |
---|
167 | # |
---|
168 | # |
---|
169 | # |
---|
170 | |
---|
171 | import os |
---|
172 | import ConfigParser |
---|
173 | |
---|
174 | class PyKotaConfigError(Exception): |
---|
175 | """An exception for PyKota config related stuff.""" |
---|
176 | def __init__(self, message = ""): |
---|
177 | self.message = message |
---|
178 | Exception.__init__(self, message) |
---|
179 | def __repr__(self): |
---|
180 | return self.message |
---|
181 | __str__ = __repr__ |
---|
182 | |
---|
183 | class PyKotaConfig : |
---|
184 | """A class to deal with PyKota's configuration.""" |
---|
185 | def __init__(self, directory) : |
---|
186 | """Reads and checks the configuration file.""" |
---|
187 | self.filename = os.path.join(directory, "pykota.conf") |
---|
188 | if not os.path.isfile(self.filename) : |
---|
189 | raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename |
---|
190 | self.config = ConfigParser.ConfigParser() |
---|
191 | self.config.read([self.filename]) |
---|
192 | |
---|
193 | def getPrinterNames(self) : |
---|
194 | """Returns the list of configured printers, i.e. all sections names minus 'global'.""" |
---|
195 | return [pname for pname in self.config.sections() if pname != "global"] |
---|
196 | |
---|
197 | def getGlobalOption(self, option, ignore=0) : |
---|
198 | """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None.""" |
---|
199 | try : |
---|
200 | return self.config.get("global", option, raw=1) |
---|
201 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
202 | if ignore : |
---|
203 | return |
---|
204 | else : |
---|
205 | raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename) |
---|
206 | |
---|
207 | def getPrinterOption(self, printer, option) : |
---|
208 | """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError.""" |
---|
209 | globaloption = self.getGlobalOption(option, ignore=1) |
---|
210 | try : |
---|
211 | return self.config.get(printer, option, raw=1) |
---|
212 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
213 | if globaloption is not None : |
---|
214 | return globaloption |
---|
215 | else : |
---|
216 | raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printer, self.filename) |
---|
217 | |
---|
218 | def getStorageBackend(self) : |
---|
219 | """Returns the storage backend information as a Python mapping.""" |
---|
220 | backendinfo = {} |
---|
221 | for option in [ "storagebackend", "storageserver", \ |
---|
222 | "storagename", "storageuser", \ |
---|
223 | ] : |
---|
224 | backendinfo[option] = self.getGlobalOption(option) |
---|
225 | backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1) # password is optional |
---|
226 | backendinfo["storageadmin"] = None |
---|
227 | backendinfo["storageadminpw"] = None |
---|
228 | adminconf = ConfigParser.ConfigParser() |
---|
229 | adminconf.read(["/etc/pykota/pykotadmin.conf"]) |
---|
230 | if adminconf.sections() : # were we able to read the file ? |
---|
231 | try : |
---|
232 | backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1) |
---|
233 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
234 | raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", "/etc/pykota/pykotadmin.conf") |
---|
235 | try : |
---|
236 | backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1) |
---|
237 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
238 | pass # Password is optional |
---|
239 | return backendinfo |
---|
240 | |
---|
241 | def getLDAPInfo(self) : |
---|
242 | """Returns some hints for the LDAP backend.""" |
---|
243 | ldapinfo = {} |
---|
244 | for option in [ "userbase", "userrdn", \ |
---|
245 | "balancebase", "balancerdn", \ |
---|
246 | "groupbase", "grouprdn", "groupmembers", \ |
---|
247 | "printerbase", "printerrdn", \ |
---|
248 | "userquotabase", "groupquotabase", \ |
---|
249 | "jobbase", "lastjobbase", \ |
---|
250 | "newuser", "newgroup", \ |
---|
251 | "usermail", \ |
---|
252 | ] : |
---|
253 | ldapinfo[option] = self.getGlobalOption(option).strip() |
---|
254 | for field in ["newuser", "newgroup"] : |
---|
255 | if ldapinfo[field].lower().startswith('attach(') : |
---|
256 | ldapinfo[field] = ldapinfo[field][7:-1] |
---|
257 | return ldapinfo |
---|
258 | |
---|
259 | def getLoggingBackend(self) : |
---|
260 | """Returns the logging backend information.""" |
---|
261 | validloggers = [ "stderr", "system" ] |
---|
262 | try : |
---|
263 | logger = self.getGlobalOption("logger").lower() |
---|
264 | except PyKotaConfigError : |
---|
265 | logger = "system" |
---|
266 | if logger not in validloggers : |
---|
267 | raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers) |
---|
268 | return logger |
---|
269 | |
---|
270 | def getAccounterBackend(self, printer) : |
---|
271 | """Returns the accounter backend to use for a given printer. |
---|
272 | |
---|
273 | if it is not set, it defaults to 'querying' which means ask printer |
---|
274 | for its internal lifetime page counter. |
---|
275 | """ |
---|
276 | validaccounters = [ "querying", "stupid", "external" ] |
---|
277 | try : |
---|
278 | fullaccounter = self.getPrinterOption(printer, "accounter").strip() |
---|
279 | except PyKotaConfigError : |
---|
280 | fullaccounter = "querying" |
---|
281 | if fullaccounter.lower().startswith("external") : |
---|
282 | try : |
---|
283 | (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)] |
---|
284 | except ValueError : |
---|
285 | raise PyKotaConfigError, _("Invalid external accounter %s for printer %s") % (fullaccounter, printer) |
---|
286 | if args.endswith(')') : |
---|
287 | args = args[:-1] |
---|
288 | if not args : |
---|
289 | raise PyKotaConfigError, _("Invalid external accounter %s for printer %s") % (fullaccounter, printer) |
---|
290 | return (accounter.lower(), args) |
---|
291 | elif fullaccounter.lower() not in validaccounters : |
---|
292 | raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printer, str(validaccounters)) |
---|
293 | else : |
---|
294 | return (fullaccounter.lower(), None) |
---|
295 | |
---|
296 | def getRequesterBackend(self, printer) : |
---|
297 | """Returns the requester backend to use for a given printer, with its arguments.""" |
---|
298 | try : |
---|
299 | fullrequester = self.getPrinterOption(printer, "requester") |
---|
300 | except PyKotaConfigError : |
---|
301 | # No requester defined, maybe it is not needed if accounting method |
---|
302 | # is not set to 'querying', but if we are called, then the accounting |
---|
303 | # method really IS 'querying', and so there's a big problem. |
---|
304 | raise PyKotaConfigError, _("Option requester for printer %s was not set") % printer |
---|
305 | else : |
---|
306 | try : |
---|
307 | (requester, args) = [x.strip() for x in fullrequester.split('(', 1)] |
---|
308 | except ValueError : |
---|
309 | raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer) |
---|
310 | if args.endswith(')') : |
---|
311 | args = args[:-1] |
---|
312 | if not args : |
---|
313 | raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer) |
---|
314 | validrequesters = [ "snmp", "external" ] # TODO : add more requesters |
---|
315 | requester = requester.lower() |
---|
316 | if requester not in validrequesters : |
---|
317 | raise PyKotaConfigError, _("Option requester for printer %s only supports values in %s") % (printer, str(validrequesters)) |
---|
318 | return (requester, args) |
---|
319 | |
---|
320 | def getPrinterPolicy(self, printer) : |
---|
321 | """Returns the default policy for the current printer.""" |
---|
322 | validpolicies = [ "ALLOW", "DENY" ] |
---|
323 | try : |
---|
324 | policy = self.getPrinterOption(printer, "policy").upper() |
---|
325 | except PyKotaConfigError : |
---|
326 | policy = "DENY" |
---|
327 | if policy not in validpolicies : |
---|
328 | raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printer, str(validpolicies)) |
---|
329 | return policy |
---|
330 | |
---|
331 | def getSMTPServer(self) : |
---|
332 | """Returns the SMTP server to use to send messages to users.""" |
---|
333 | try : |
---|
334 | return self.getGlobalOption("smtpserver") |
---|
335 | except PyKotaConfigError : |
---|
336 | return "localhost" |
---|
337 | |
---|
338 | def getAdminMail(self, printer) : |
---|
339 | """Returns the Email address of the Print Quota Administrator.""" |
---|
340 | try : |
---|
341 | return self.getPrinterOption(printer, "adminmail") |
---|
342 | except PyKotaConfigError : |
---|
343 | return "root@localhost" |
---|
344 | |
---|
345 | def getAdmin(self, printer) : |
---|
346 | """Returns the full name of the Print Quota Administrator.""" |
---|
347 | try : |
---|
348 | return self.getPrinterOption(printer, "admin") |
---|
349 | except PyKotaConfigError : |
---|
350 | return "root" |
---|
351 | |
---|
352 | def getMailTo(self, printer) : |
---|
353 | """Returns the recipient of email messages.""" |
---|
354 | validmailtos = [ "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ] |
---|
355 | try : |
---|
356 | mailto = self.getPrinterOption(printer, "mailto").upper() |
---|
357 | except PyKotaConfigError : |
---|
358 | mailto = "BOTH" |
---|
359 | if mailto not in validmailtos : |
---|
360 | raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printer, str(validmailtos)) |
---|
361 | return mailto |
---|
362 | |
---|
363 | def getGraceDelay(self, printer) : |
---|
364 | """Returns the grace delay in days.""" |
---|
365 | try : |
---|
366 | gd = self.getPrinterOption(printer, "gracedelay") |
---|
367 | except PyKotaConfigError : |
---|
368 | gd = 7 |
---|
369 | try : |
---|
370 | return int(gd) |
---|
371 | except (TypeError, ValueError) : |
---|
372 | raise PyKotaConfigError, _("Invalid grace delay %s") % gd |
---|
373 | |
---|
374 | def getPoorMan(self) : |
---|
375 | """Returns the poor man's treshold.""" |
---|
376 | try : |
---|
377 | pm = self.getGlobalOption("poorman") |
---|
378 | except PyKotaConfigError : |
---|
379 | pm = 1.0 |
---|
380 | try : |
---|
381 | return float(pm) |
---|
382 | except (TypeError, ValueError) : |
---|
383 | raise PyKotaConfigError, _("Invalid poor man's treshold %s") % pm |
---|
384 | |
---|
385 | def getPoorWarn(self) : |
---|
386 | """Returns the poor man's warning message.""" |
---|
387 | try : |
---|
388 | return self.getGlobalOption("poorwarn") |
---|
389 | except PyKotaConfigError : |
---|
390 | 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.") |
---|
391 | |
---|
392 | def getHardWarn(self, printer) : |
---|
393 | """Returns the hard limit error message.""" |
---|
394 | try : |
---|
395 | return self.getPrinterOption(printer, "hardwarn") |
---|
396 | except PyKotaConfigError : |
---|
397 | return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printer |
---|
398 | |
---|
399 | def getSoftWarn(self, printer) : |
---|
400 | """Returns the soft limit error message.""" |
---|
401 | try : |
---|
402 | return self.getPrinterOption(printer, "softwarn") |
---|
403 | except PyKotaConfigError : |
---|
404 | return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printer |
---|
405 | |
---|
406 | def getDebug(self) : |
---|
407 | """Returns 1 if debugging is activated, else 0.""" |
---|
408 | debug = self.getGlobalOption("debug", ignore=1) |
---|
409 | if (debug is not None) and (debug.upper().strip() in ['Y', 'YES', '1', 'ON', 'O']) : |
---|
410 | return 1 |
---|
411 | else : |
---|
412 | return 0 |
---|
413 | |
---|
414 | def getCaching(self) : |
---|
415 | """Returns 1 if database caching is enabled, else 0.""" |
---|
416 | caching = self.getGlobalOption("storagecaching", ignore=1) |
---|
417 | if (caching is not None) and (caching.upper().strip() in ['Y', 'YES', '1', 'ON', 'O']) : |
---|
418 | return 1 |
---|
419 | else : |
---|
420 | return 0 |
---|
421 | |
---|
422 | def getDisableHistory(self) : |
---|
423 | """Returns 1 if we want to disable history, else 0.""" |
---|
424 | disablehistory = self.getGlobalOption("disablehistory", ignore=1) |
---|
425 | if (disablehistory is not None) and (disablehistory.upper().strip() in ['Y', 'YES', '1', 'ON', 'O']) : |
---|
426 | return 1 |
---|
427 | else : |
---|
428 | return 0 |
---|