[1144] | 1 | # PyKota |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
[695] | 3 | |
---|
[952] | 4 | # PyKota - Print Quotas for CUPS and LPRng |
---|
[695] | 5 | # |
---|
| 6 | # (c) 2003 Jerome Alet <alet@librelogiciel.com> |
---|
[873] | 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. |
---|
[695] | 11 | # |
---|
[873] | 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. |
---|
[695] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
| 23 | # $Log$ |
---|
[1245] | 24 | # Revision 1.66 2004/01/02 17:31:26 jalet |
---|
| 25 | # Forgot to remove some code |
---|
[1240] | 26 | # |
---|
| 27 | # Revision 1.65 2003/12/06 08:14:38 jalet |
---|
| 28 | # Added support for CUPS device uris which contain authentication information. |
---|
| 29 | # |
---|
[1229] | 30 | # Revision 1.64 2003/11/29 22:03:17 jalet |
---|
| 31 | # Some code refactoring work. New code is not used at this time. |
---|
| 32 | # |
---|
[1227] | 33 | # Revision 1.63 2003/11/29 20:06:20 jalet |
---|
| 34 | # Added 'utolower' configuration option to convert all usernames to |
---|
| 35 | # lowercase when printing. All database accesses are still and will |
---|
| 36 | # remain case sensitive though. |
---|
| 37 | # |
---|
[1218] | 38 | # Revision 1.62 2003/11/25 22:37:22 jalet |
---|
| 39 | # Small code move |
---|
| 40 | # |
---|
[1217] | 41 | # Revision 1.61 2003/11/25 22:03:28 jalet |
---|
| 42 | # No more message on stderr when the translation is not available. |
---|
| 43 | # |
---|
[1216] | 44 | # Revision 1.60 2003/11/25 21:54:05 jalet |
---|
| 45 | # updated FAQ |
---|
| 46 | # |
---|
[1211] | 47 | # Revision 1.59 2003/11/25 13:33:43 jalet |
---|
| 48 | # Puts 'root' instead of '' when printing from CUPS web interface (which |
---|
| 49 | # gives an empty username) |
---|
| 50 | # |
---|
[1200] | 51 | # Revision 1.58 2003/11/21 14:28:45 jalet |
---|
| 52 | # More complete job history. |
---|
| 53 | # |
---|
[1196] | 54 | # Revision 1.57 2003/11/19 23:19:38 jalet |
---|
| 55 | # Code refactoring work. |
---|
| 56 | # Explicit redirection to /dev/null has to be set in external policy now, just |
---|
| 57 | # like in external mailto. |
---|
| 58 | # |
---|
[1193] | 59 | # Revision 1.56 2003/11/19 07:40:20 jalet |
---|
| 60 | # Missing import statement. |
---|
| 61 | # Better documentation for mailto: external(...) |
---|
| 62 | # |
---|
[1192] | 63 | # Revision 1.55 2003/11/18 23:43:12 jalet |
---|
| 64 | # Mailto can be any external command now, as usual. |
---|
| 65 | # |
---|
[1171] | 66 | # Revision 1.54 2003/10/24 21:52:46 jalet |
---|
| 67 | # Now can force language when coming from CGI script. |
---|
| 68 | # |
---|
[1152] | 69 | # Revision 1.53 2003/10/08 21:41:38 jalet |
---|
| 70 | # External policies for printers works ! |
---|
| 71 | # We can now auto-add users on first print, and do other useful things if needed. |
---|
| 72 | # |
---|
[1144] | 73 | # Revision 1.52 2003/10/07 09:07:28 jalet |
---|
| 74 | # Character encoding added to please latest version of Python |
---|
| 75 | # |
---|
[1140] | 76 | # Revision 1.51 2003/10/06 14:21:41 jalet |
---|
| 77 | # Test reversed to not retrieve group members when no messages for them. |
---|
| 78 | # |
---|
[1130] | 79 | # Revision 1.50 2003/10/02 20:23:18 jalet |
---|
| 80 | # Storage caching mechanism added. |
---|
| 81 | # |
---|
[1113] | 82 | # Revision 1.49 2003/07/29 20:55:17 jalet |
---|
| 83 | # 1.14 is out ! |
---|
| 84 | # |
---|
[1091] | 85 | # Revision 1.48 2003/07/21 23:01:56 jalet |
---|
| 86 | # Modified some messages aout soft limit |
---|
| 87 | # |
---|
[1087] | 88 | # Revision 1.47 2003/07/16 21:53:08 jalet |
---|
| 89 | # Really big modifications wrt new configuration file's location and content. |
---|
| 90 | # |
---|
[1079] | 91 | # Revision 1.46 2003/07/09 20:17:07 jalet |
---|
| 92 | # Email field added to PostgreSQL schema |
---|
| 93 | # |
---|
[1077] | 94 | # Revision 1.45 2003/07/08 19:43:51 jalet |
---|
| 95 | # Configurable warning messages. |
---|
| 96 | # Poor man's treshold value added. |
---|
| 97 | # |
---|
[1068] | 98 | # Revision 1.44 2003/07/07 11:49:24 jalet |
---|
| 99 | # Lots of small fixes with the help of PyChecker |
---|
| 100 | # |
---|
[1061] | 101 | # Revision 1.43 2003/07/04 09:06:32 jalet |
---|
| 102 | # Small bug fix wrt undefined "LimitBy" field. |
---|
| 103 | # |
---|
[1048] | 104 | # Revision 1.42 2003/06/30 12:46:15 jalet |
---|
| 105 | # Extracted reporting code. |
---|
| 106 | # |
---|
[1041] | 107 | # Revision 1.41 2003/06/25 14:10:01 jalet |
---|
| 108 | # Hey, it may work (edpykota --reset excepted) ! |
---|
| 109 | # |
---|
[1021] | 110 | # Revision 1.40 2003/06/10 16:37:54 jalet |
---|
| 111 | # Deletion of the second user which is not needed anymore. |
---|
| 112 | # Added a debug configuration field in /etc/pykota.conf |
---|
| 113 | # All queries can now be sent to the logger in debug mode, this will |
---|
| 114 | # greatly help improve performance when time for this will come. |
---|
| 115 | # |
---|
[973] | 116 | # Revision 1.39 2003/04/29 18:37:54 jalet |
---|
| 117 | # Pluggable accounting methods (actually doesn't support external scripts) |
---|
| 118 | # |
---|
[956] | 119 | # Revision 1.38 2003/04/24 11:53:48 jalet |
---|
| 120 | # Default policy for unknown users/groups is to DENY printing instead |
---|
| 121 | # of the previous default to ALLOW printing. This is to solve an accuracy |
---|
| 122 | # problem. If you set the policy to ALLOW, jobs printed by in nexistant user |
---|
| 123 | # (from PyKota's POV) will be charged to the next user who prints on the |
---|
| 124 | # same printer. |
---|
| 125 | # |
---|
[955] | 126 | # Revision 1.37 2003/04/24 08:08:27 jalet |
---|
| 127 | # Debug message forgotten |
---|
| 128 | # |
---|
[954] | 129 | # Revision 1.36 2003/04/24 07:59:40 jalet |
---|
| 130 | # LPRng support now works ! |
---|
| 131 | # |
---|
[952] | 132 | # Revision 1.35 2003/04/23 22:13:57 jalet |
---|
| 133 | # Preliminary support for LPRng added BUT STILL UNTESTED. |
---|
| 134 | # |
---|
[929] | 135 | # Revision 1.34 2003/04/17 09:26:21 jalet |
---|
| 136 | # repykota now reports account balances too. |
---|
| 137 | # |
---|
[927] | 138 | # Revision 1.33 2003/04/16 12:35:49 jalet |
---|
| 139 | # Groups quota work now ! |
---|
| 140 | # |
---|
[925] | 141 | # Revision 1.32 2003/04/16 08:53:14 jalet |
---|
| 142 | # Printing can now be limited either by user's account balance or by |
---|
| 143 | # page quota (the default). Quota report doesn't include account balance |
---|
| 144 | # yet, though. |
---|
| 145 | # |
---|
[915] | 146 | # Revision 1.31 2003/04/15 11:30:57 jalet |
---|
| 147 | # More work done on money print charging. |
---|
| 148 | # Minor bugs corrected. |
---|
| 149 | # All tools now access to the storage as priviledged users, repykota excepted. |
---|
| 150 | # |
---|
[900] | 151 | # Revision 1.30 2003/04/10 21:47:20 jalet |
---|
| 152 | # Job history added. Upgrade script neutralized for now ! |
---|
| 153 | # |
---|
[873] | 154 | # Revision 1.29 2003/03/29 13:45:27 jalet |
---|
| 155 | # GPL paragraphs were incorrectly (from memory) copied into the sources. |
---|
| 156 | # Two README files were added. |
---|
| 157 | # Upgrade script for PostgreSQL pre 1.01 schema was added. |
---|
| 158 | # |
---|
[872] | 159 | # Revision 1.28 2003/03/29 13:08:28 jalet |
---|
| 160 | # Configuration is now expected to be found in /etc/pykota.conf instead of |
---|
| 161 | # in /etc/cups/pykota.conf |
---|
| 162 | # Installation script can move old config files to the new location if needed. |
---|
| 163 | # Better error handling if configuration file is absent. |
---|
| 164 | # |
---|
[852] | 165 | # Revision 1.27 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 | # |
---|
[844] | 169 | # Revision 1.26 2003/03/09 23:58:16 jalet |
---|
| 170 | # Comment |
---|
| 171 | # |
---|
[834] | 172 | # Revision 1.25 2003/03/07 22:56:14 jalet |
---|
| 173 | # 0.99 is out with some bug fixes. |
---|
| 174 | # |
---|
[825] | 175 | # Revision 1.24 2003/02/27 23:48:41 jalet |
---|
| 176 | # Correctly maps PyKota's log levels to syslog log levels |
---|
| 177 | # |
---|
[824] | 178 | # Revision 1.23 2003/02/27 22:55:20 jalet |
---|
| 179 | # WARN log priority doesn't exist. |
---|
| 180 | # |
---|
[817] | 181 | # Revision 1.22 2003/02/27 09:09:20 jalet |
---|
| 182 | # Added a method to match strings against wildcard patterns |
---|
| 183 | # |
---|
[804] | 184 | # Revision 1.21 2003/02/17 23:01:56 jalet |
---|
| 185 | # Typos |
---|
| 186 | # |
---|
[802] | 187 | # Revision 1.20 2003/02/17 22:55:01 jalet |
---|
| 188 | # More options can now be set per printer or globally : |
---|
| 189 | # |
---|
[804] | 190 | # admin |
---|
| 191 | # adminmail |
---|
| 192 | # gracedelay |
---|
| 193 | # requester |
---|
[802] | 194 | # |
---|
| 195 | # the printer option has priority when both are defined. |
---|
| 196 | # |
---|
[788] | 197 | # Revision 1.19 2003/02/10 11:28:45 jalet |
---|
| 198 | # Localization |
---|
| 199 | # |
---|
[782] | 200 | # Revision 1.18 2003/02/10 01:02:17 jalet |
---|
| 201 | # External requester is about to work, but I must sleep |
---|
| 202 | # |
---|
[773] | 203 | # Revision 1.17 2003/02/09 13:05:43 jalet |
---|
| 204 | # Internationalization continues... |
---|
| 205 | # |
---|
[772] | 206 | # Revision 1.16 2003/02/09 12:56:53 jalet |
---|
| 207 | # Internationalization begins... |
---|
| 208 | # |
---|
[764] | 209 | # Revision 1.15 2003/02/08 22:09:52 jalet |
---|
| 210 | # Name check method moved here |
---|
| 211 | # |
---|
[742] | 212 | # Revision 1.14 2003/02/07 10:42:45 jalet |
---|
| 213 | # Indentation problem |
---|
| 214 | # |
---|
[733] | 215 | # Revision 1.13 2003/02/07 08:34:16 jalet |
---|
| 216 | # Test wrt date limit was wrong |
---|
| 217 | # |
---|
[729] | 218 | # Revision 1.12 2003/02/06 23:20:02 jalet |
---|
| 219 | # warnpykota doesn't need any user/group name argument, mimicing the |
---|
| 220 | # warnquota disk quota tool. |
---|
| 221 | # |
---|
[728] | 222 | # Revision 1.11 2003/02/06 22:54:33 jalet |
---|
| 223 | # warnpykota should be ok |
---|
| 224 | # |
---|
[722] | 225 | # Revision 1.10 2003/02/06 15:03:11 jalet |
---|
| 226 | # added a method to set the limit date |
---|
| 227 | # |
---|
[715] | 228 | # Revision 1.9 2003/02/06 10:39:23 jalet |
---|
| 229 | # Preliminary edpykota work. |
---|
| 230 | # |
---|
[713] | 231 | # Revision 1.8 2003/02/06 09:19:02 jalet |
---|
| 232 | # More robust behavior (hopefully) when the user or printer is not managed |
---|
| 233 | # correctly by the Quota System : e.g. cupsFilter added in ppd file, but |
---|
| 234 | # printer and/or user not 'yet?' in storage. |
---|
| 235 | # |
---|
[712] | 236 | # Revision 1.7 2003/02/06 00:00:45 jalet |
---|
| 237 | # Now includes the printer name in email messages |
---|
| 238 | # |
---|
[711] | 239 | # Revision 1.6 2003/02/05 23:55:02 jalet |
---|
| 240 | # Cleaner email messages |
---|
| 241 | # |
---|
[709] | 242 | # Revision 1.5 2003/02/05 23:45:09 jalet |
---|
| 243 | # Better DateTime manipulation wrt grace delay |
---|
| 244 | # |
---|
[708] | 245 | # Revision 1.4 2003/02/05 23:26:22 jalet |
---|
| 246 | # Incorrect handling of grace delay |
---|
| 247 | # |
---|
[699] | 248 | # Revision 1.3 2003/02/05 22:16:20 jalet |
---|
| 249 | # DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools |
---|
| 250 | # |
---|
[698] | 251 | # Revision 1.2 2003/02/05 22:10:29 jalet |
---|
| 252 | # Typos |
---|
| 253 | # |
---|
[695] | 254 | # Revision 1.1 2003/02/05 21:28:17 jalet |
---|
| 255 | # Initial import into CVS |
---|
| 256 | # |
---|
| 257 | # |
---|
| 258 | # |
---|
| 259 | |
---|
| 260 | import sys |
---|
[1193] | 261 | import os |
---|
[817] | 262 | import fnmatch |
---|
[715] | 263 | import getopt |
---|
[695] | 264 | import smtplib |
---|
[772] | 265 | import gettext |
---|
[782] | 266 | import locale |
---|
[695] | 267 | |
---|
[708] | 268 | from mx import DateTime |
---|
| 269 | |
---|
[1218] | 270 | from pykota import version, config, storage, logger, accounter |
---|
[695] | 271 | |
---|
| 272 | class PyKotaToolError(Exception): |
---|
| 273 | """An exception for PyKota config related stuff.""" |
---|
| 274 | def __init__(self, message = ""): |
---|
| 275 | self.message = message |
---|
| 276 | Exception.__init__(self, message) |
---|
| 277 | def __repr__(self): |
---|
| 278 | return self.message |
---|
| 279 | __str__ = __repr__ |
---|
| 280 | |
---|
| 281 | class PyKotaTool : |
---|
| 282 | """Base class for all PyKota command line tools.""" |
---|
[1171] | 283 | def __init__(self, lang=None, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) : |
---|
[695] | 284 | """Initializes the command line tool.""" |
---|
[772] | 285 | # locale stuff |
---|
[788] | 286 | try : |
---|
[1171] | 287 | locale.setlocale(locale.LC_ALL, lang) |
---|
[788] | 288 | gettext.install("pykota") |
---|
| 289 | except (locale.Error, IOError) : |
---|
| 290 | gettext.NullTranslations().install() |
---|
[1217] | 291 | # sys.stderr.write("PyKota : Error while loading translations\n") |
---|
[772] | 292 | |
---|
| 293 | # pykota specific stuff |
---|
[715] | 294 | self.documentation = doc |
---|
[1087] | 295 | self.config = config.PyKotaConfig("/etc/pykota") |
---|
[1245] | 296 | self.logger = logger.openLogger(self) |
---|
[1130] | 297 | self.debug = self.config.getDebug() |
---|
[1021] | 298 | self.storage = storage.openConnection(self) |
---|
[695] | 299 | self.smtpserver = self.config.getSMTPServer() |
---|
| 300 | |
---|
[1130] | 301 | def logdebug(self, message) : |
---|
| 302 | """Logs something to debug output if debug is enabled.""" |
---|
| 303 | if self.debug : |
---|
| 304 | self.logger.log_message(message, "debug") |
---|
| 305 | |
---|
[1113] | 306 | def clean(self) : |
---|
| 307 | """Ensures that the database is closed.""" |
---|
| 308 | try : |
---|
| 309 | self.storage.close() |
---|
| 310 | except (TypeError, NameError, AttributeError) : |
---|
| 311 | pass |
---|
| 312 | |
---|
[715] | 313 | def display_version_and_quit(self) : |
---|
| 314 | """Displays version number, then exists successfully.""" |
---|
[1113] | 315 | self.clean() |
---|
[715] | 316 | print version.__version__ |
---|
| 317 | sys.exit(0) |
---|
| 318 | |
---|
| 319 | def display_usage_and_quit(self) : |
---|
| 320 | """Displays command line usage, then exists successfully.""" |
---|
[1113] | 321 | self.clean() |
---|
[715] | 322 | print self.documentation |
---|
| 323 | sys.exit(0) |
---|
| 324 | |
---|
[729] | 325 | def parseCommandline(self, argv, short, long, allownothing=0) : |
---|
[715] | 326 | """Parses the command line, controlling options.""" |
---|
| 327 | # split options in two lists: those which need an argument, those which don't need any |
---|
| 328 | withoutarg = [] |
---|
| 329 | witharg = [] |
---|
| 330 | lgs = len(short) |
---|
| 331 | i = 0 |
---|
| 332 | while i < lgs : |
---|
| 333 | ii = i + 1 |
---|
| 334 | if (ii < lgs) and (short[ii] == ':') : |
---|
| 335 | # needs an argument |
---|
| 336 | witharg.append(short[i]) |
---|
| 337 | ii = ii + 1 # skip the ':' |
---|
| 338 | else : |
---|
| 339 | # doesn't need an argument |
---|
| 340 | withoutarg.append(short[i]) |
---|
| 341 | i = ii |
---|
| 342 | |
---|
| 343 | for option in long : |
---|
| 344 | if option[-1] == '=' : |
---|
| 345 | # needs an argument |
---|
| 346 | witharg.append(option[:-1]) |
---|
| 347 | else : |
---|
| 348 | # doesn't need an argument |
---|
| 349 | withoutarg.append(option) |
---|
| 350 | |
---|
| 351 | # we begin with all possible options unset |
---|
| 352 | parsed = {} |
---|
| 353 | for option in withoutarg + witharg : |
---|
| 354 | parsed[option] = None |
---|
| 355 | |
---|
| 356 | # then we parse the command line |
---|
| 357 | args = [] # to not break if something unexpected happened |
---|
| 358 | try : |
---|
| 359 | options, args = getopt.getopt(argv, short, long) |
---|
| 360 | if options : |
---|
| 361 | for (o, v) in options : |
---|
| 362 | # we skip the '-' chars |
---|
| 363 | lgo = len(o) |
---|
| 364 | i = 0 |
---|
| 365 | while (i < lgo) and (o[i] == '-') : |
---|
| 366 | i = i + 1 |
---|
| 367 | o = o[i:] |
---|
| 368 | if o in witharg : |
---|
| 369 | # needs an argument : set it |
---|
| 370 | parsed[o] = v |
---|
| 371 | elif o in withoutarg : |
---|
| 372 | # doesn't need an argument : boolean |
---|
| 373 | parsed[o] = 1 |
---|
| 374 | else : |
---|
| 375 | # should never occur |
---|
| 376 | raise PyKotaToolError, "Unexpected problem when parsing command line" |
---|
[729] | 377 | elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty |
---|
[715] | 378 | self.display_usage_and_quit() |
---|
| 379 | except getopt.error, msg : |
---|
| 380 | sys.stderr.write("%s\n" % msg) |
---|
| 381 | sys.stderr.flush() |
---|
| 382 | self.display_usage_and_quit() |
---|
| 383 | return (parsed, args) |
---|
| 384 | |
---|
[764] | 385 | def isValidName(self, name) : |
---|
| 386 | """Checks if a user or printer name is valid.""" |
---|
| 387 | # unfortunately Python 2.1 string modules doesn't define ascii_letters... |
---|
| 388 | asciiletters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' |
---|
| 389 | digits = '0123456789' |
---|
| 390 | if name[0] in asciiletters : |
---|
| 391 | validchars = asciiletters + digits + "-_" |
---|
| 392 | for c in name[1:] : |
---|
| 393 | if c not in validchars : |
---|
| 394 | return 0 |
---|
| 395 | return 1 |
---|
| 396 | return 0 |
---|
| 397 | |
---|
[817] | 398 | def matchString(self, s, patterns) : |
---|
| 399 | """Returns 1 if the string s matches one of the patterns, else 0.""" |
---|
| 400 | for pattern in patterns : |
---|
| 401 | if fnmatch.fnmatchcase(s, pattern) : |
---|
| 402 | return 1 |
---|
| 403 | return 0 |
---|
| 404 | |
---|
[802] | 405 | def sendMessage(self, adminmail, touser, fullmessage) : |
---|
[695] | 406 | """Sends an email message containing headers to some user.""" |
---|
| 407 | if "@" not in touser : |
---|
| 408 | touser = "%s@%s" % (touser, self.smtpserver) |
---|
| 409 | server = smtplib.SMTP(self.smtpserver) |
---|
[1041] | 410 | try : |
---|
| 411 | server.sendmail(adminmail, [touser], fullmessage) |
---|
| 412 | except smtplib.SMTPRecipientsRefused, answer : |
---|
| 413 | for (k, v) in answer.recipients.items() : |
---|
| 414 | self.logger.log_message(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error") |
---|
[695] | 415 | server.quit() |
---|
| 416 | |
---|
[1079] | 417 | def sendMessageToUser(self, admin, adminmail, user, subject, message) : |
---|
[695] | 418 | """Sends an email message to a user.""" |
---|
[802] | 419 | message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail) |
---|
[1079] | 420 | self.sendMessage(adminmail, user.Email or user.Name, "Subject: %s\n\n%s" % (subject, message)) |
---|
[695] | 421 | |
---|
[802] | 422 | def sendMessageToAdmin(self, adminmail, subject, message) : |
---|
[695] | 423 | """Sends an email message to the Print Quota administrator.""" |
---|
[802] | 424 | self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message)) |
---|
[695] | 425 | |
---|
[1041] | 426 | def checkGroupPQuota(self, grouppquota) : |
---|
[927] | 427 | """Checks the group quota on a printer and deny or accept the job.""" |
---|
[1041] | 428 | group = grouppquota.Group |
---|
| 429 | printer = grouppquota.Printer |
---|
[1061] | 430 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
[1077] | 431 | if group.AccountBalance <= 0.0 : |
---|
[1041] | 432 | action = "DENY" |
---|
[1077] | 433 | elif group.AccountBalance <= self.config.getPoorMan() : |
---|
| 434 | action = "WARN" |
---|
[927] | 435 | else : |
---|
[1041] | 436 | action = "ALLOW" |
---|
[927] | 437 | else : |
---|
[1041] | 438 | if grouppquota.SoftLimit is not None : |
---|
| 439 | softlimit = int(grouppquota.SoftLimit) |
---|
| 440 | if grouppquota.PageCounter < softlimit : |
---|
| 441 | action = "ALLOW" |
---|
[927] | 442 | else : |
---|
[1041] | 443 | if grouppquota.HardLimit is None : |
---|
| 444 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 445 | action = "DENY" |
---|
[927] | 446 | else : |
---|
[1041] | 447 | hardlimit = int(grouppquota.HardLimit) |
---|
| 448 | if softlimit <= grouppquota.PageCounter < hardlimit : |
---|
| 449 | now = DateTime.now() |
---|
| 450 | if grouppquota.DateLimit is not None : |
---|
| 451 | datelimit = DateTime.ISO.ParseDateTime(grouppquota.DateLimit) |
---|
| 452 | else : |
---|
| 453 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 454 | grouppquota.setDateLimit(datelimit) |
---|
| 455 | if now < datelimit : |
---|
| 456 | action = "WARN" |
---|
| 457 | else : |
---|
[927] | 458 | action = "DENY" |
---|
[1041] | 459 | else : |
---|
[927] | 460 | action = "DENY" |
---|
[1041] | 461 | else : |
---|
| 462 | if grouppquota.HardLimit is not None : |
---|
| 463 | # no soft limit, only a hard one. |
---|
| 464 | hardlimit = int(grouppquota.HardLimit) |
---|
| 465 | if grouppquota.PageCounter < hardlimit : |
---|
[927] | 466 | action = "ALLOW" |
---|
[1041] | 467 | else : |
---|
| 468 | action = "DENY" |
---|
| 469 | else : |
---|
| 470 | # Both are unset, no quota, i.e. accounting only |
---|
| 471 | action = "ALLOW" |
---|
[927] | 472 | return action |
---|
| 473 | |
---|
[1041] | 474 | def checkUserPQuota(self, userpquota) : |
---|
[708] | 475 | """Checks the user quota on a printer and deny or accept the job.""" |
---|
[1041] | 476 | user = userpquota.User |
---|
| 477 | printer = userpquota.Printer |
---|
| 478 | |
---|
[927] | 479 | # first we check any group the user is a member of |
---|
[1041] | 480 | for group in self.storage.getUserGroups(user) : |
---|
| 481 | grouppquota = self.storage.getGroupPQuota(group, printer) |
---|
| 482 | if grouppquota.Exists : |
---|
| 483 | action = self.checkGroupPQuota(grouppquota) |
---|
| 484 | if action == "DENY" : |
---|
| 485 | return action |
---|
[927] | 486 | |
---|
| 487 | # then we check the user's own quota |
---|
[1152] | 488 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 489 | (policy, dummy) = self.config.getPrinterPolicy(printer.Name) |
---|
[1061] | 490 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
[1041] | 491 | if user.AccountBalance is None : |
---|
[956] | 492 | if policy == "ALLOW" : |
---|
[925] | 493 | action = "POLICY_ALLOW" |
---|
| 494 | else : |
---|
| 495 | action = "POLICY_DENY" |
---|
[1041] | 496 | self.logger.log_message(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name)) |
---|
[713] | 497 | else : |
---|
[1077] | 498 | val = float(user.AccountBalance or 0.0) |
---|
| 499 | if val <= 0.0 : |
---|
[925] | 500 | action = "DENY" |
---|
[1077] | 501 | elif val <= self.config.getPoorMan() : |
---|
| 502 | action = "WARN" |
---|
[925] | 503 | else : |
---|
[713] | 504 | action = "ALLOW" |
---|
[925] | 505 | else : |
---|
[1041] | 506 | if not userpquota.Exists : |
---|
| 507 | # Unknown userquota |
---|
[956] | 508 | if policy == "ALLOW" : |
---|
[925] | 509 | action = "POLICY_ALLOW" |
---|
[834] | 510 | else : |
---|
[925] | 511 | action = "POLICY_DENY" |
---|
[1041] | 512 | self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action)) |
---|
[925] | 513 | else : |
---|
[1041] | 514 | pagecounter = int(userpquota.PageCounter or 0) |
---|
| 515 | if userpquota.SoftLimit is not None : |
---|
| 516 | softlimit = int(userpquota.SoftLimit) |
---|
[925] | 517 | if pagecounter < softlimit : |
---|
| 518 | action = "ALLOW" |
---|
[834] | 519 | else : |
---|
[1041] | 520 | if userpquota.HardLimit is None : |
---|
[925] | 521 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 522 | action = "DENY" |
---|
| 523 | else : |
---|
[1041] | 524 | hardlimit = int(userpquota.HardLimit) |
---|
[925] | 525 | if softlimit <= pagecounter < hardlimit : |
---|
| 526 | now = DateTime.now() |
---|
[1041] | 527 | if userpquota.DateLimit is not None : |
---|
| 528 | datelimit = DateTime.ISO.ParseDateTime(userpquota.DateLimit) |
---|
[925] | 529 | else : |
---|
[1041] | 530 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 531 | userpquota.setDateLimit(datelimit) |
---|
[925] | 532 | if now < datelimit : |
---|
| 533 | action = "WARN" |
---|
| 534 | else : |
---|
| 535 | action = "DENY" |
---|
| 536 | else : |
---|
[834] | 537 | action = "DENY" |
---|
[925] | 538 | else : |
---|
[1041] | 539 | if userpquota.HardLimit is not None : |
---|
[925] | 540 | # no soft limit, only a hard one. |
---|
[1041] | 541 | hardlimit = int(userpquota.HardLimit) |
---|
[925] | 542 | if pagecounter < hardlimit : |
---|
| 543 | action = "ALLOW" |
---|
| 544 | else : |
---|
[742] | 545 | action = "DENY" |
---|
[925] | 546 | else : |
---|
| 547 | # Both are unset, no quota, i.e. accounting only |
---|
[834] | 548 | action = "ALLOW" |
---|
| 549 | return action |
---|
[708] | 550 | |
---|
[1196] | 551 | def externalMailTo(self, cmd, action, user, printer, message) : |
---|
[1192] | 552 | """Warns the user with an external command.""" |
---|
| 553 | username = user.Name |
---|
[1196] | 554 | printername = printer.Name |
---|
[1192] | 555 | email = user.Email or user.Name |
---|
| 556 | if "@" not in email : |
---|
| 557 | email = "%s@%s" % (email, self.smtpserver) |
---|
| 558 | os.system(cmd % locals()) |
---|
| 559 | |
---|
[1196] | 560 | def formatCommandLine(self, cmd, user, printer) : |
---|
| 561 | """Executes an external command.""" |
---|
| 562 | username = user.Name |
---|
| 563 | printername = printer.Name |
---|
| 564 | return cmd % locals() |
---|
| 565 | |
---|
[1041] | 566 | def warnGroupPQuota(self, grouppquota) : |
---|
[927] | 567 | """Checks a group quota and send messages if quota is exceeded on current printer.""" |
---|
[1041] | 568 | group = grouppquota.Group |
---|
| 569 | printer = grouppquota.Printer |
---|
| 570 | admin = self.config.getAdmin(printer.Name) |
---|
| 571 | adminmail = self.config.getAdminMail(printer.Name) |
---|
[1192] | 572 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[1068] | 573 | action = self.checkGroupPQuota(grouppquota) |
---|
[927] | 574 | if action.startswith("POLICY_") : |
---|
| 575 | action = action[7:] |
---|
| 576 | if action == "DENY" : |
---|
[1041] | 577 | adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name) |
---|
[927] | 578 | self.logger.log_message(adminmessage) |
---|
| 579 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 580 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1192] | 581 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
[1140] | 582 | for user in self.storage.getGroupMembers(group) : |
---|
[1192] | 583 | if mailto != "EXTERNAL" : |
---|
[1245] | 584 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name)) |
---|
[1192] | 585 | else : |
---|
[1196] | 586 | self.externalMailTo(arguments, action, user, printer, message) |
---|
[927] | 587 | elif action == "WARN" : |
---|
[1091] | 588 | adminmessage = _("Print Quota low for group %s on printer %s") % (group.Name, printer.Name) |
---|
[927] | 589 | self.logger.log_message(adminmessage) |
---|
| 590 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 591 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1077] | 592 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
| 593 | message = self.config.getPoorWarn() |
---|
| 594 | else : |
---|
| 595 | message = self.config.getSoftWarn(printer.Name) |
---|
[1192] | 596 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
[1140] | 597 | for user in self.storage.getGroupMembers(group) : |
---|
[1192] | 598 | if mailto != "EXTERNAL" : |
---|
| 599 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 600 | else : |
---|
[1196] | 601 | self.externalMailTo(arguments, action, user, printer, message) |
---|
[927] | 602 | return action |
---|
[728] | 603 | |
---|
[1041] | 604 | def warnUserPQuota(self, userpquota) : |
---|
[728] | 605 | """Checks a user quota and send him a message if quota is exceeded on current printer.""" |
---|
[1041] | 606 | user = userpquota.User |
---|
[1245] | 607 | printer = userpquota.Printer |
---|
| 608 | admin = self.config.getAdmin(printer.Name) |
---|
| 609 | adminmail = self.config.getAdminMail(printer.Name) |
---|
| 610 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
| 611 | action = self.checkUserPQuota(userpquota) |
---|
| 612 | if action.startswith("POLICY_") : |
---|
| 613 | action = action[7:] |
---|
| 614 | if action == "DENY" : |
---|
| 615 | adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 616 | self.logger.log_message(adminmessage) |
---|
| 617 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 618 | message = self.config.getHardWarn(printer.Name) |
---|
| 619 | if mailto != "EXTERNAL" : |
---|
| 620 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 621 | else : |
---|
| 622 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 623 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 624 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 625 | elif action == "WARN" : |
---|
| 626 | adminmessage = _("Print Quota low for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 627 | self.logger.log_message(adminmessage) |
---|
| 628 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 629 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
| 630 | message = self.config.getPoorWarn() |
---|
| 631 | else : |
---|
| 632 | message = self.config.getSoftWarn(printer.Name) |
---|
| 633 | if mailto != "EXTERNAL" : |
---|
| 634 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message) |
---|
| 635 | else : |
---|
| 636 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 637 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 638 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 639 | return action |
---|
[1196] | 640 | |
---|
| 641 | class PyKotaFilterOrBackend(PyKotaTool) : |
---|
| 642 | """Class for the PyKota filter or backend.""" |
---|
| 643 | def __init__(self) : |
---|
| 644 | PyKotaTool.__init__(self) |
---|
| 645 | (self.printingsystem, \ |
---|
| 646 | self.printerhostname, \ |
---|
| 647 | self.printername, \ |
---|
| 648 | self.username, \ |
---|
| 649 | self.jobid, \ |
---|
| 650 | self.inputfile, \ |
---|
| 651 | self.copies, \ |
---|
| 652 | self.title, \ |
---|
| 653 | self.options, \ |
---|
| 654 | self.originalbackend) = self.extractInfoFromCupsOrLprng() |
---|
[1216] | 655 | self.username = self.username or 'root' |
---|
[1227] | 656 | if self.config.getUserNameToLower() : |
---|
| 657 | self.username = self.username.lower() |
---|
[1200] | 658 | self.preserveinputfile = self.inputfile |
---|
[1218] | 659 | self.accounter = accounter.openAccounter(self) |
---|
[1196] | 660 | |
---|
| 661 | def extractInfoFromCupsOrLprng(self) : |
---|
| 662 | """Returns a tuple (printingsystem, printerhostname, printername, username, jobid, filename, title, options, backend). |
---|
| 663 | |
---|
| 664 | Returns (None, None, None, None, None, None, None, None, None, None) if no printing system is recognized. |
---|
| 665 | """ |
---|
| 666 | # Try to detect CUPS |
---|
| 667 | if os.environ.has_key("CUPS_SERVERROOT") and os.path.isdir(os.environ.get("CUPS_SERVERROOT", "")) : |
---|
| 668 | if len(sys.argv) == 7 : |
---|
| 669 | inputfile = sys.argv[6] |
---|
| 670 | else : |
---|
| 671 | inputfile = None |
---|
| 672 | |
---|
| 673 | # check that the DEVICE_URI environment variable's value is |
---|
| 674 | # prefixed with "cupspykota:" otherwise don't touch it. |
---|
| 675 | # If this is the case, we have to remove the prefix from |
---|
| 676 | # the environment before launching the real backend in cupspykota |
---|
| 677 | device_uri = os.environ.get("DEVICE_URI", "") |
---|
| 678 | if device_uri.startswith("cupspykota:") : |
---|
| 679 | fulldevice_uri = device_uri[:] |
---|
| 680 | device_uri = fulldevice_uri[len("cupspykota:"):] |
---|
| 681 | if device_uri.startswith("//") : # lpd (at least) |
---|
| 682 | device_uri = device_uri[2:] |
---|
| 683 | os.environ["DEVICE_URI"] = device_uri # TODO : side effect ! |
---|
| 684 | # TODO : check this for more complex urls than ipp://myprinter.dot.com:631/printers/lp |
---|
| 685 | try : |
---|
| 686 | (backend, destination) = device_uri.split(":", 1) |
---|
| 687 | except ValueError : |
---|
| 688 | raise PyKotaToolError, "Invalid DEVICE_URI : %s\n" % device_uri |
---|
| 689 | while destination.startswith("/") : |
---|
| 690 | destination = destination[1:] |
---|
[1240] | 691 | checkauth = destination.split("@", 1) |
---|
| 692 | if len(checkauth) == 2 : |
---|
| 693 | destination = checkauth[1] |
---|
[1196] | 694 | printerhostname = destination.split("/")[0].split(":")[0] |
---|
| 695 | return ("CUPS", \ |
---|
| 696 | printerhostname, \ |
---|
| 697 | os.environ.get("PRINTER"), \ |
---|
[1216] | 698 | sys.argv[2].strip(), \ |
---|
[1196] | 699 | sys.argv[1].strip(), \ |
---|
| 700 | inputfile, \ |
---|
| 701 | int(sys.argv[4].strip()), \ |
---|
| 702 | sys.argv[3], \ |
---|
| 703 | sys.argv[5], \ |
---|
| 704 | backend) |
---|
| 705 | else : |
---|
| 706 | # Try to detect LPRng |
---|
[1200] | 707 | # TODO : try to extract filename, job's title, and options if available |
---|
[1196] | 708 | jseen = Pseen = nseen = rseen = Kseen = None |
---|
| 709 | for arg in sys.argv : |
---|
| 710 | if arg.startswith("-j") : |
---|
| 711 | jseen = arg[2:].strip() |
---|
| 712 | elif arg.startswith("-n") : |
---|
| 713 | nseen = arg[2:].strip() |
---|
| 714 | elif arg.startswith("-P") : |
---|
| 715 | Pseen = arg[2:].strip() |
---|
| 716 | elif arg.startswith("-r") : |
---|
| 717 | rseen = arg[2:].strip() |
---|
| 718 | elif arg.startswith("-K") or arg.startswith("-#") : |
---|
| 719 | Kseen = int(arg[2:].strip()) |
---|
| 720 | if Kseen is None : |
---|
| 721 | Kseen = 1 # we assume the user wants at least one copy... |
---|
| 722 | if (rseen is None) and jseen and Pseen and nseen : |
---|
| 723 | self.logger.log_message(_("Printer hostname undefined, set to 'localhost'"), "warn") |
---|
| 724 | rseen = "localhost" |
---|
| 725 | if jseen and Pseen and nseen and rseen : |
---|
| 726 | # job is always in stdin (None) |
---|
| 727 | return ("LPRNG", rseen, Pseen, nseen, jseen, None, Kseen, None, None, None) |
---|
| 728 | self.logger.log_message(_("Printing system unknown, args=%s") % " ".join(sys.argv), "warn") |
---|
| 729 | return (None, None, None, None, None, None, None, None, None, None) # Unknown printing system |
---|
[1229] | 730 | |
---|
| 731 | def getPrinterUserAndUserPQuota(self) : |
---|
| 732 | """Returns a tuple (policy, printer, user, and user print quota) on this printer. |
---|
| 733 | |
---|
| 734 | "OK" is returned in the policy if both printer, user and user print quota |
---|
| 735 | exist in the Quota Storage. |
---|
| 736 | Otherwise, the policy as defined for this printer in pykota.conf is returned. |
---|
| 737 | |
---|
| 738 | If policy was set to "EXTERNAL" and one of printer, user, or user print quota |
---|
| 739 | doesn't exist in the Quota Storage, then an external command is launched, as |
---|
| 740 | defined in the external policy for this printer in pykota.conf |
---|
| 741 | This external command can do anything, like automatically adding printers |
---|
| 742 | or users, for example, and finally extracting printer, user and user print |
---|
| 743 | quota from the Quota Storage is tried a second time. |
---|
| 744 | |
---|
| 745 | "EXTERNALERROR" is returned in case policy was "EXTERNAL" and an error status |
---|
| 746 | was returned by the external command. |
---|
| 747 | """ |
---|
[1245] | 748 | for passnumber in range(1, 3) : |
---|
[1229] | 749 | printer = self.storage.getPrinter(self.printername) |
---|
| 750 | user = self.storage.getUser(self.username) |
---|
| 751 | userpquota = self.storage.getUserPQuota(user, printer) |
---|
| 752 | if printer.Exists and user.Exists and userpquota.Exists : |
---|
| 753 | policy = "OK" |
---|
| 754 | break |
---|
| 755 | (policy, args) = self.config.getPrinterPolicy(self.printername) |
---|
| 756 | if policy == "EXTERNAL" : |
---|
| 757 | commandline = self.formatCommandLine(args, user, printer) |
---|
| 758 | if not printer.Exists : |
---|
| 759 | self.logger.log_message(_("Printer %s not registered in the PyKota system, applying external policy (%s) for printer %s") % (self.printername, commandline, self.printername), "info") |
---|
| 760 | if not user.Exists : |
---|
| 761 | self.logger.log_message(_("User %s not registered in the PyKota system, applying external policy (%s) for printer %s") % (self.username, commandline, self.printername), "info") |
---|
| 762 | if not userpquota.Exists : |
---|
| 763 | self.logger.log_message(_("User %s doesn't have quota on printer %s in the PyKota system, applying external policy (%s) for printer %s") % (self.username, self.printername, commandline, self.printername), "info") |
---|
| 764 | if os.system(commandline) : |
---|
| 765 | # if an error occured, we die without error, |
---|
| 766 | # so that the job doesn't stop the print queue. |
---|
| 767 | self.logger.log_message(_("External policy %s for printer %s produced an error. Job rejected. Please check PyKota's configuration files.") % (commandline, self.printername), "error") |
---|
| 768 | policy = "EXTERNALERROR" |
---|
| 769 | break |
---|
| 770 | else : |
---|
| 771 | break |
---|
| 772 | return (policy, printer, user, userpquota) |
---|
| 773 | |
---|
| 774 | def main(self) : |
---|
| 775 | """Main work is done here.""" |
---|
| 776 | (policy, printer, user, userpquota) = self.getPrinterUserAndUserPQuota() |
---|
| 777 | if policy == "EXTERNALERROR" : |
---|
| 778 | # Policy was 'EXTERNAL' and the external command returned an error code |
---|
| 779 | pass # TODO : reject job |
---|
| 780 | elif policy == "EXTERNAL" : |
---|
| 781 | # Policy was 'EXTERNAL' and the external command wasn't able |
---|
| 782 | # to add either the printer, user or user print quota |
---|
| 783 | pass # TODO : reject job |
---|
| 784 | elif policy == "ALLOW": |
---|
| 785 | # Either printer, user or user print quota doesn't exist, |
---|
| 786 | # but the job should be allowed anyway. |
---|
| 787 | pass # TODO : accept job |
---|
| 788 | elif policy == "OK" : |
---|
| 789 | # Both printer, user and user print quota exist, job should |
---|
| 790 | # be allowed if current user is allowed to print on this |
---|
| 791 | # printer |
---|
| 792 | pass # TODO : decide what to do based on user quota. |
---|
| 793 | else : # DENY |
---|
| 794 | # Either printer, user or user print quota doesn't exist, |
---|
| 795 | # and the job should be rejected. |
---|
| 796 | pass # TODO : reject job |
---|