[1144] | 1 | # PyKota |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
[695] | 3 | |
---|
[952] | 4 | # PyKota - Print Quotas for CUPS and LPRng |
---|
[695] | 5 | # |
---|
[2622] | 6 | # (c) 2003, 2004, 2005, 2006 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 |
---|
[2302] | 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[695] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
[2093] | 23 | # |
---|
[695] | 24 | |
---|
| 25 | import sys |
---|
[1193] | 26 | import os |
---|
[1960] | 27 | import pwd |
---|
[817] | 28 | import fnmatch |
---|
[715] | 29 | import getopt |
---|
[695] | 30 | import smtplib |
---|
[772] | 31 | import gettext |
---|
[782] | 32 | import locale |
---|
[1434] | 33 | import signal |
---|
[1469] | 34 | import socket |
---|
[1492] | 35 | import tempfile |
---|
[1756] | 36 | import md5 |
---|
[1537] | 37 | import ConfigParser |
---|
[1917] | 38 | import popen2 |
---|
[2643] | 39 | from email.MIMEText import MIMEText |
---|
| 40 | from email.Header import Header |
---|
[695] | 41 | |
---|
[708] | 42 | from mx import DateTime |
---|
| 43 | |
---|
[2345] | 44 | from pykota import config, storage, logger, accounter |
---|
[2344] | 45 | from pykota.version import __version__, __author__, __years__, __gplblurb__ |
---|
[695] | 46 | |
---|
[2345] | 47 | try : |
---|
| 48 | from pkpgpdls import analyzer, pdlparser |
---|
[2347] | 49 | except ImportError : # TODO : Remove the try/except after release 1.24. |
---|
[2345] | 50 | sys.stderr.write("ERROR: pkpgcounter is now distributed separately, please grab it from http://www.librelogiciel.com/software/pkpgcounter/action_Download\n") |
---|
| 51 | |
---|
[1795] | 52 | def N_(message) : |
---|
| 53 | """Fake translation marker for translatable strings extraction.""" |
---|
| 54 | return message |
---|
| 55 | |
---|
[695] | 56 | class PyKotaToolError(Exception): |
---|
[2512] | 57 | """An exception for PyKota related stuff.""" |
---|
[695] | 58 | def __init__(self, message = ""): |
---|
| 59 | self.message = message |
---|
| 60 | Exception.__init__(self, message) |
---|
| 61 | def __repr__(self): |
---|
| 62 | return self.message |
---|
| 63 | __str__ = __repr__ |
---|
| 64 | |
---|
[2512] | 65 | class PyKotaCommandLineError(PyKotaToolError) : |
---|
| 66 | """An exception for Pykota command line tools.""" |
---|
| 67 | pass |
---|
| 68 | |
---|
[2229] | 69 | def crashed(message="Bug in PyKota") : |
---|
[1546] | 70 | """Minimal crash method.""" |
---|
| 71 | import traceback |
---|
| 72 | lines = [] |
---|
| 73 | for line in traceback.format_exception(*sys.exc_info()) : |
---|
| 74 | lines.extend([l for l in line.split("\n") if l]) |
---|
[2344] | 75 | msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % __version__, message] + lines)]) |
---|
[1546] | 76 | sys.stderr.write(msg) |
---|
| 77 | sys.stderr.flush() |
---|
| 78 | return msg |
---|
| 79 | |
---|
[1911] | 80 | class Tool : |
---|
| 81 | """Base class for tools with no database access.""" |
---|
[2344] | 82 | def __init__(self, lang="", charset=None, doc="PyKota v%(__version__)s (c) %(__years__)s %(__author__)s") : |
---|
[695] | 83 | """Initializes the command line tool.""" |
---|
[2006] | 84 | # did we drop priviledges ? |
---|
| 85 | self.privdropped = 0 |
---|
| 86 | |
---|
[772] | 87 | # locale stuff |
---|
[2210] | 88 | self.defaultToCLocale = 0 |
---|
[788] | 89 | try : |
---|
[1171] | 90 | locale.setlocale(locale.LC_ALL, lang) |
---|
[788] | 91 | except (locale.Error, IOError) : |
---|
[2510] | 92 | # locale.setlocale(locale.LC_ALL, "C") |
---|
[2210] | 93 | self.defaultToCLocale = 1 |
---|
[1898] | 94 | try : |
---|
| 95 | gettext.install("pykota") |
---|
| 96 | except : |
---|
[788] | 97 | gettext.NullTranslations().install() |
---|
[1761] | 98 | |
---|
| 99 | # We can force the charset. |
---|
| 100 | # The CHARSET environment variable is set by CUPS when printing. |
---|
| 101 | # Else we use the current locale's one. |
---|
| 102 | # If nothing is set, we use ISO-8859-15 widely used in western Europe. |
---|
[1856] | 103 | localecharset = None |
---|
[1776] | 104 | try : |
---|
[1851] | 105 | try : |
---|
[2195] | 106 | localecharset = locale.nl_langinfo(locale.CODESET) |
---|
[1856] | 107 | except AttributeError : |
---|
| 108 | try : |
---|
[2195] | 109 | localecharset = locale.getpreferredencoding() |
---|
| 110 | except AttributeError : |
---|
| 111 | try : |
---|
[2214] | 112 | localecharset = locale.getlocale()[1] |
---|
[2195] | 113 | localecharset = localecharset or locale.getdefaultlocale()[1] |
---|
| 114 | except ValueError : |
---|
| 115 | pass # Unknown locale, strange... |
---|
[1856] | 116 | except locale.Error : |
---|
| 117 | pass |
---|
[1776] | 118 | self.charset = charset or os.environ.get("CHARSET") or localecharset or "ISO-8859-15" |
---|
[772] | 119 | |
---|
| 120 | # pykota specific stuff |
---|
[715] | 121 | self.documentation = doc |
---|
[1960] | 122 | |
---|
[2210] | 123 | def deferredInit(self) : |
---|
| 124 | """Deferred initialization.""" |
---|
[1960] | 125 | # try to find the configuration files in user's 'pykota' home directory. |
---|
[1537] | 126 | try : |
---|
[2006] | 127 | self.pykotauser = pwd.getpwnam("pykota") |
---|
[1960] | 128 | except KeyError : |
---|
[2006] | 129 | self.pykotauser = None |
---|
[1960] | 130 | confdir = "/etc/pykota" |
---|
| 131 | missingUser = 1 |
---|
| 132 | else : |
---|
[2006] | 133 | confdir = self.pykotauser[5] |
---|
[1960] | 134 | missingUser = 0 |
---|
| 135 | |
---|
[2210] | 136 | self.config = config.PyKotaConfig(confdir) |
---|
| 137 | self.debug = self.config.getDebug() |
---|
| 138 | self.smtpserver = self.config.getSMTPServer() |
---|
| 139 | self.maildomain = self.config.getMailDomain() |
---|
| 140 | self.logger = logger.openLogger(self.config.getLoggingBackend()) |
---|
[1542] | 141 | |
---|
[2006] | 142 | # now drop priviledge if possible |
---|
| 143 | self.dropPriv() |
---|
| 144 | |
---|
[1960] | 145 | # We NEED this here, even when not in an accounting filter/backend |
---|
[1497] | 146 | self.softwareJobSize = 0 |
---|
[1495] | 147 | self.softwareJobPrice = 0.0 |
---|
[1960] | 148 | |
---|
[2210] | 149 | if self.defaultToCLocale : |
---|
[2511] | 150 | self.printInfo("Incorrect locale settings. PyKota falls back to the default locale.", "warn") |
---|
[1960] | 151 | if missingUser : |
---|
| 152 | self.printInfo("The 'pykota' system account is missing. Configuration files were searched in /etc/pykota instead.", "warn") |
---|
| 153 | |
---|
[1761] | 154 | self.logdebug("Charset in use : %s" % self.charset) |
---|
[1872] | 155 | arguments = " ".join(['"%s"' % arg for arg in sys.argv]) |
---|
| 156 | self.logdebug("Command line arguments : %s" % arguments) |
---|
[695] | 157 | |
---|
[2006] | 158 | def dropPriv(self) : |
---|
| 159 | """Drops priviledges.""" |
---|
| 160 | uid = os.geteuid() |
---|
| 161 | if uid : |
---|
| 162 | try : |
---|
| 163 | username = pwd.getpwuid(uid)[0] |
---|
| 164 | except (KeyError, IndexError), msg : |
---|
| 165 | self.printInfo(_("Strange problem with uid(%s) : %s") % (uid, msg), "warn") |
---|
| 166 | else : |
---|
| 167 | self.logdebug(_("Running as user '%s'.") % username) |
---|
| 168 | else : |
---|
| 169 | if self.pykotauser is None : |
---|
| 170 | self.logdebug(_("No user named 'pykota'. Not dropping priviledges.")) |
---|
| 171 | else : |
---|
| 172 | try : |
---|
| 173 | os.setegid(self.pykotauser[3]) |
---|
| 174 | os.seteuid(self.pykotauser[2]) |
---|
| 175 | except OSError, msg : |
---|
| 176 | self.printInfo(_("Impossible to drop priviledges : %s") % msg, "warn") |
---|
| 177 | else : |
---|
| 178 | self.logdebug(_("Priviledges dropped. Now running as user 'pykota'.")) |
---|
| 179 | self.privdropped = 1 |
---|
| 180 | |
---|
| 181 | def regainPriv(self) : |
---|
| 182 | """Drops priviledges.""" |
---|
| 183 | if self.privdropped : |
---|
| 184 | try : |
---|
| 185 | os.seteuid(0) |
---|
| 186 | os.setegid(0) |
---|
| 187 | except OSError, msg : |
---|
| 188 | self.printInfo(_("Impossible to regain priviledges : %s") % msg, "warn") |
---|
| 189 | else : |
---|
[2008] | 190 | self.logdebug(_("Regained priviledges. Now running as root.")) |
---|
[2006] | 191 | self.privdropped = 0 |
---|
| 192 | |
---|
[1761] | 193 | def getCharset(self) : |
---|
| 194 | """Returns the charset in use.""" |
---|
| 195 | return self.charset |
---|
| 196 | |
---|
[1130] | 197 | def logdebug(self, message) : |
---|
| 198 | """Logs something to debug output if debug is enabled.""" |
---|
| 199 | if self.debug : |
---|
| 200 | self.logger.log_message(message, "debug") |
---|
[1582] | 201 | |
---|
[1584] | 202 | def printInfo(self, message, level="info") : |
---|
[1582] | 203 | """Sends a message to standard error.""" |
---|
[1584] | 204 | sys.stderr.write("%s: %s\n" % (level.upper(), message)) |
---|
[1582] | 205 | sys.stderr.flush() |
---|
[1130] | 206 | |
---|
[2210] | 207 | def matchString(self, s, patterns) : |
---|
| 208 | """Returns 1 if the string s matches one of the patterns, else 0.""" |
---|
| 209 | for pattern in patterns : |
---|
| 210 | if fnmatch.fnmatchcase(s, pattern) : |
---|
| 211 | return 1 |
---|
| 212 | return 0 |
---|
| 213 | |
---|
[715] | 214 | def display_version_and_quit(self) : |
---|
| 215 | """Displays version number, then exists successfully.""" |
---|
[1923] | 216 | try : |
---|
| 217 | self.clean() |
---|
| 218 | except AttributeError : |
---|
| 219 | pass |
---|
[2344] | 220 | print __version__ |
---|
[715] | 221 | sys.exit(0) |
---|
| 222 | |
---|
| 223 | def display_usage_and_quit(self) : |
---|
| 224 | """Displays command line usage, then exists successfully.""" |
---|
[1923] | 225 | try : |
---|
| 226 | self.clean() |
---|
| 227 | except AttributeError : |
---|
| 228 | pass |
---|
[2344] | 229 | print _(self.documentation) % globals() |
---|
| 230 | print __gplblurb__ |
---|
| 231 | print |
---|
| 232 | print _("Please report bugs to :"), __author__ |
---|
[715] | 233 | sys.exit(0) |
---|
| 234 | |
---|
[2229] | 235 | def crashed(self, message="Bug in PyKota") : |
---|
[1517] | 236 | """Outputs a crash message, and optionally sends it to software author.""" |
---|
[1546] | 237 | msg = crashed(message) |
---|
[2229] | 238 | fullmessage = "========== Traceback :\n\n%s\n\n========== sys.argv :\n\n%s\n\n========== Environment :\n\n%s\n" % \ |
---|
| 239 | (msg, \ |
---|
| 240 | "\n".join([" %s" % repr(a) for a in sys.argv]), \ |
---|
| 241 | "\n".join([" %s=%s" % (k, v) for (k, v) in os.environ.items()])) |
---|
[1541] | 242 | try : |
---|
| 243 | crashrecipient = self.config.getCrashRecipient() |
---|
| 244 | if crashrecipient : |
---|
[1517] | 245 | admin = self.config.getAdminMail("global") # Nice trick, isn't it ? |
---|
| 246 | server = smtplib.SMTP(self.smtpserver) |
---|
[1546] | 247 | server.sendmail(admin, [admin, crashrecipient], \ |
---|
[1560] | 248 | "From: %s\nTo: %s\nCc: %s\nSubject: PyKota v%s crash traceback !\n\n%s" % \ |
---|
[2344] | 249 | (admin, crashrecipient, admin, __version__, fullmessage)) |
---|
[1517] | 250 | server.quit() |
---|
[1541] | 251 | except : |
---|
| 252 | pass |
---|
[2229] | 253 | return fullmessage |
---|
[1517] | 254 | |
---|
[729] | 255 | def parseCommandline(self, argv, short, long, allownothing=0) : |
---|
[715] | 256 | """Parses the command line, controlling options.""" |
---|
| 257 | # split options in two lists: those which need an argument, those which don't need any |
---|
[2605] | 258 | short = "%sA:" % short |
---|
| 259 | long.append("arguments=") |
---|
[715] | 260 | withoutarg = [] |
---|
| 261 | witharg = [] |
---|
| 262 | lgs = len(short) |
---|
| 263 | i = 0 |
---|
| 264 | while i < lgs : |
---|
| 265 | ii = i + 1 |
---|
| 266 | if (ii < lgs) and (short[ii] == ':') : |
---|
| 267 | # needs an argument |
---|
| 268 | witharg.append(short[i]) |
---|
| 269 | ii = ii + 1 # skip the ':' |
---|
| 270 | else : |
---|
| 271 | # doesn't need an argument |
---|
| 272 | withoutarg.append(short[i]) |
---|
| 273 | i = ii |
---|
| 274 | |
---|
| 275 | for option in long : |
---|
| 276 | if option[-1] == '=' : |
---|
| 277 | # needs an argument |
---|
| 278 | witharg.append(option[:-1]) |
---|
| 279 | else : |
---|
| 280 | # doesn't need an argument |
---|
| 281 | withoutarg.append(option) |
---|
| 282 | |
---|
| 283 | # then we parse the command line |
---|
[2605] | 284 | done = 0 |
---|
| 285 | while not done : |
---|
| 286 | # we begin with all possible options unset |
---|
| 287 | parsed = {} |
---|
| 288 | for option in withoutarg + witharg : |
---|
| 289 | parsed[option] = None |
---|
| 290 | args = [] # to not break if something unexpected happened |
---|
| 291 | try : |
---|
| 292 | options, args = getopt.getopt(argv, short, long) |
---|
| 293 | if options : |
---|
| 294 | for (o, v) in options : |
---|
| 295 | # we skip the '-' chars |
---|
| 296 | lgo = len(o) |
---|
| 297 | i = 0 |
---|
| 298 | while (i < lgo) and (o[i] == '-') : |
---|
| 299 | i = i + 1 |
---|
| 300 | o = o[i:] |
---|
| 301 | if o in witharg : |
---|
| 302 | # needs an argument : set it |
---|
| 303 | parsed[o] = v |
---|
| 304 | elif o in withoutarg : |
---|
| 305 | # doesn't need an argument : boolean |
---|
| 306 | parsed[o] = 1 |
---|
| 307 | else : |
---|
| 308 | # should never occur |
---|
[2610] | 309 | raise PyKotaCommandLineError, "Unexpected problem when parsing command line" |
---|
[2605] | 310 | elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty |
---|
| 311 | self.display_usage_and_quit() |
---|
| 312 | except getopt.error, msg : |
---|
[2610] | 313 | raise PyKotaCommandLineError, str(msg) |
---|
[2605] | 314 | else : |
---|
| 315 | if parsed["arguments"] or parsed["A"] : |
---|
| 316 | # arguments are in a file, we ignore all other arguments |
---|
| 317 | # and reset the list of arguments to the lines read from |
---|
| 318 | # the file. |
---|
| 319 | argsfile = open(parsed["arguments"] or parsed["A"], "r") |
---|
| 320 | argv = [ l.strip() for l in argsfile.readlines() ] |
---|
| 321 | argsfile.close() |
---|
| 322 | for i in range(len(argv)) : |
---|
| 323 | argi = argv[i] |
---|
| 324 | if argi.startswith('"') and argi.endswith('"') : |
---|
| 325 | argv[i] = argi[1:-1] |
---|
| 326 | else : |
---|
| 327 | done = 1 |
---|
[715] | 328 | return (parsed, args) |
---|
| 329 | |
---|
[1911] | 330 | class PyKotaTool(Tool) : |
---|
| 331 | """Base class for all PyKota command line tools.""" |
---|
[2344] | 332 | def __init__(self, lang="", charset=None, doc="PyKota v%(__version__)s (c) %(__years__)s %(__author__)s") : |
---|
[1911] | 333 | """Initializes the command line tool and opens the database.""" |
---|
| 334 | Tool.__init__(self, lang, charset, doc) |
---|
[2210] | 335 | |
---|
| 336 | def deferredInit(self) : |
---|
| 337 | """Deferred initialization.""" |
---|
| 338 | Tool.deferredInit(self) |
---|
| 339 | self.storage = storage.openConnection(self) |
---|
| 340 | if self.config.isAdmin : # TODO : We don't know this before, fix this ! |
---|
| 341 | self.logdebug("Beware : running as a PyKota administrator !") |
---|
[2093] | 342 | else : |
---|
[2210] | 343 | self.logdebug("Don't Panic : running as a mere mortal !") |
---|
[1911] | 344 | |
---|
| 345 | def clean(self) : |
---|
| 346 | """Ensures that the database is closed.""" |
---|
| 347 | try : |
---|
| 348 | self.storage.close() |
---|
| 349 | except (TypeError, NameError, AttributeError) : |
---|
| 350 | pass |
---|
| 351 | |
---|
[764] | 352 | def isValidName(self, name) : |
---|
| 353 | """Checks if a user or printer name is valid.""" |
---|
[1725] | 354 | invalidchars = "/@?*,;&|" |
---|
[1637] | 355 | for c in list(invalidchars) : |
---|
[1593] | 356 | if c in name : |
---|
[1394] | 357 | return 0 |
---|
| 358 | return 1 |
---|
[764] | 359 | |
---|
[802] | 360 | def sendMessage(self, adminmail, touser, fullmessage) : |
---|
[695] | 361 | """Sends an email message containing headers to some user.""" |
---|
| 362 | if "@" not in touser : |
---|
[1353] | 363 | touser = "%s@%s" % (touser, self.maildomain or self.smtpserver) |
---|
[1469] | 364 | try : |
---|
| 365 | server = smtplib.SMTP(self.smtpserver) |
---|
| 366 | except socket.error, msg : |
---|
[1584] | 367 | self.printInfo(_("Impossible to connect to SMTP server : %s") % msg, "error") |
---|
[1469] | 368 | else : |
---|
| 369 | try : |
---|
| 370 | server.sendmail(adminmail, [touser], "From: %s\nTo: %s\n%s" % (adminmail, touser, fullmessage)) |
---|
| 371 | except smtplib.SMTPException, answer : |
---|
| 372 | for (k, v) in answer.recipients.items() : |
---|
[1584] | 373 | self.printInfo(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error") |
---|
[1469] | 374 | server.quit() |
---|
[695] | 375 | |
---|
[1079] | 376 | def sendMessageToUser(self, admin, adminmail, user, subject, message) : |
---|
[695] | 377 | """Sends an email message to a user.""" |
---|
[802] | 378 | message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail) |
---|
[1079] | 379 | self.sendMessage(adminmail, user.Email or user.Name, "Subject: %s\n\n%s" % (subject, message)) |
---|
[695] | 380 | |
---|
[802] | 381 | def sendMessageToAdmin(self, adminmail, subject, message) : |
---|
[695] | 382 | """Sends an email message to the Print Quota administrator.""" |
---|
[802] | 383 | self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message)) |
---|
[695] | 384 | |
---|
[1365] | 385 | def _checkUserPQuota(self, userpquota) : |
---|
| 386 | """Checks the user quota on a printer and deny or accept the job.""" |
---|
| 387 | # then we check the user's own quota |
---|
| 388 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 389 | user = userpquota.User |
---|
| 390 | printer = userpquota.Printer |
---|
[1495] | 391 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 392 | self.logdebug("Checking user %s's quota on printer %s" % (user.Name, printer.Name)) |
---|
| 393 | (policy, dummy) = self.config.getPrinterPolicy(userpquota.Printer.Name) |
---|
| 394 | if not userpquota.Exists : |
---|
| 395 | # Unknown userquota |
---|
| 396 | if policy == "ALLOW" : |
---|
| 397 | action = "POLICY_ALLOW" |
---|
| 398 | else : |
---|
| 399 | action = "POLICY_DENY" |
---|
[1584] | 400 | self.printInfo(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action)) |
---|
[1365] | 401 | else : |
---|
| 402 | pagecounter = int(userpquota.PageCounter or 0) |
---|
[1495] | 403 | if enforcement == "STRICT" : |
---|
| 404 | pagecounter += self.softwareJobSize |
---|
[1365] | 405 | if userpquota.SoftLimit is not None : |
---|
| 406 | softlimit = int(userpquota.SoftLimit) |
---|
| 407 | if pagecounter < softlimit : |
---|
| 408 | action = "ALLOW" |
---|
| 409 | else : |
---|
| 410 | if userpquota.HardLimit is None : |
---|
| 411 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 412 | action = "DENY" |
---|
| 413 | else : |
---|
| 414 | hardlimit = int(userpquota.HardLimit) |
---|
| 415 | if softlimit <= pagecounter < hardlimit : |
---|
| 416 | now = DateTime.now() |
---|
| 417 | if userpquota.DateLimit is not None : |
---|
| 418 | datelimit = DateTime.ISO.ParseDateTime(userpquota.DateLimit) |
---|
| 419 | else : |
---|
| 420 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 421 | userpquota.setDateLimit(datelimit) |
---|
| 422 | if now < datelimit : |
---|
| 423 | action = "WARN" |
---|
| 424 | else : |
---|
| 425 | action = "DENY" |
---|
| 426 | else : |
---|
| 427 | action = "DENY" |
---|
| 428 | else : |
---|
| 429 | if userpquota.HardLimit is not None : |
---|
| 430 | # no soft limit, only a hard one. |
---|
| 431 | hardlimit = int(userpquota.HardLimit) |
---|
| 432 | if pagecounter < hardlimit : |
---|
| 433 | action = "ALLOW" |
---|
| 434 | else : |
---|
| 435 | action = "DENY" |
---|
| 436 | else : |
---|
| 437 | # Both are unset, no quota, i.e. accounting only |
---|
| 438 | action = "ALLOW" |
---|
| 439 | return action |
---|
| 440 | |
---|
[1041] | 441 | def checkGroupPQuota(self, grouppquota) : |
---|
[927] | 442 | """Checks the group quota on a printer and deny or accept the job.""" |
---|
[1041] | 443 | group = grouppquota.Group |
---|
| 444 | printer = grouppquota.Printer |
---|
[1495] | 445 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 446 | self.logdebug("Checking group %s's quota on printer %s" % (group.Name, printer.Name)) |
---|
[1061] | 447 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
[1666] | 448 | val = group.AccountBalance or 0.0 |
---|
[1495] | 449 | if enforcement == "STRICT" : |
---|
| 450 | val -= self.softwareJobPrice # use precomputed size. |
---|
| 451 | if val <= 0.0 : |
---|
[1041] | 452 | action = "DENY" |
---|
[1495] | 453 | elif val <= self.config.getPoorMan() : |
---|
[1077] | 454 | action = "WARN" |
---|
[927] | 455 | else : |
---|
[1041] | 456 | action = "ALLOW" |
---|
[1529] | 457 | if (enforcement == "STRICT") and (val == 0.0) : |
---|
| 458 | action = "WARN" # we can still print until account is 0 |
---|
[927] | 459 | else : |
---|
[1665] | 460 | val = grouppquota.PageCounter or 0 |
---|
[1495] | 461 | if enforcement == "STRICT" : |
---|
| 462 | val += self.softwareJobSize |
---|
[1041] | 463 | if grouppquota.SoftLimit is not None : |
---|
| 464 | softlimit = int(grouppquota.SoftLimit) |
---|
[1495] | 465 | if val < softlimit : |
---|
[1041] | 466 | action = "ALLOW" |
---|
[927] | 467 | else : |
---|
[1041] | 468 | if grouppquota.HardLimit is None : |
---|
| 469 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 470 | action = "DENY" |
---|
[927] | 471 | else : |
---|
[1041] | 472 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 473 | if softlimit <= val < hardlimit : |
---|
[1041] | 474 | now = DateTime.now() |
---|
| 475 | if grouppquota.DateLimit is not None : |
---|
| 476 | datelimit = DateTime.ISO.ParseDateTime(grouppquota.DateLimit) |
---|
| 477 | else : |
---|
| 478 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 479 | grouppquota.setDateLimit(datelimit) |
---|
| 480 | if now < datelimit : |
---|
| 481 | action = "WARN" |
---|
| 482 | else : |
---|
[927] | 483 | action = "DENY" |
---|
[1041] | 484 | else : |
---|
[927] | 485 | action = "DENY" |
---|
[1041] | 486 | else : |
---|
| 487 | if grouppquota.HardLimit is not None : |
---|
| 488 | # no soft limit, only a hard one. |
---|
| 489 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 490 | if val < hardlimit : |
---|
[927] | 491 | action = "ALLOW" |
---|
[1041] | 492 | else : |
---|
| 493 | action = "DENY" |
---|
| 494 | else : |
---|
| 495 | # Both are unset, no quota, i.e. accounting only |
---|
| 496 | action = "ALLOW" |
---|
[927] | 497 | return action |
---|
| 498 | |
---|
[1041] | 499 | def checkUserPQuota(self, userpquota) : |
---|
[1365] | 500 | """Checks the user quota on a printer and all its parents and deny or accept the job.""" |
---|
[1041] | 501 | user = userpquota.User |
---|
| 502 | printer = userpquota.Printer |
---|
| 503 | |
---|
[1365] | 504 | # indicates that a warning needs to be sent |
---|
| 505 | warned = 0 |
---|
| 506 | |
---|
[927] | 507 | # first we check any group the user is a member of |
---|
[1041] | 508 | for group in self.storage.getUserGroups(user) : |
---|
[2452] | 509 | # No need to check anything if the group is in noquota mode |
---|
| 510 | if group.LimitBy != "noquota" : |
---|
| 511 | grouppquota = self.storage.getGroupPQuota(group, printer) |
---|
| 512 | # for the printer and all its parents |
---|
| 513 | for gpquota in [ grouppquota ] + grouppquota.ParentPrintersGroupPQuota : |
---|
| 514 | if gpquota.Exists : |
---|
| 515 | action = self.checkGroupPQuota(gpquota) |
---|
| 516 | if action == "DENY" : |
---|
| 517 | return action |
---|
| 518 | elif action == "WARN" : |
---|
| 519 | warned = 1 |
---|
[1365] | 520 | |
---|
| 521 | # Then we check the user's account balance |
---|
[1152] | 522 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 523 | (policy, dummy) = self.config.getPrinterPolicy(printer.Name) |
---|
[1061] | 524 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
[1365] | 525 | self.logdebug("Checking account balance for user %s" % user.Name) |
---|
[1041] | 526 | if user.AccountBalance is None : |
---|
[956] | 527 | if policy == "ALLOW" : |
---|
[925] | 528 | action = "POLICY_ALLOW" |
---|
| 529 | else : |
---|
| 530 | action = "POLICY_DENY" |
---|
[1584] | 531 | self.printInfo(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name)) |
---|
[1365] | 532 | return action |
---|
[713] | 533 | else : |
---|
[2054] | 534 | if user.OverCharge == 0.0 : |
---|
| 535 | self.printInfo(_("User %s will not be charged for printing.") % user.Name) |
---|
| 536 | action = "ALLOW" |
---|
[1529] | 537 | else : |
---|
[2054] | 538 | val = float(user.AccountBalance or 0.0) |
---|
| 539 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
| 540 | if enforcement == "STRICT" : |
---|
| 541 | val -= self.softwareJobPrice # use precomputed size. |
---|
| 542 | if val <= 0.0 : |
---|
| 543 | action = "DENY" |
---|
| 544 | elif val <= self.config.getPoorMan() : |
---|
| 545 | action = "WARN" |
---|
| 546 | else : |
---|
| 547 | action = "ALLOW" |
---|
| 548 | if (enforcement == "STRICT") and (val == 0.0) : |
---|
| 549 | action = "WARN" # we can still print until account is 0 |
---|
[1529] | 550 | return action |
---|
[925] | 551 | else : |
---|
[1365] | 552 | # Then check the user quota on current printer and all its parents. |
---|
| 553 | policyallowed = 0 |
---|
| 554 | for upquota in [ userpquota ] + userpquota.ParentPrintersUserPQuota : |
---|
| 555 | action = self._checkUserPQuota(upquota) |
---|
| 556 | if action in ("DENY", "POLICY_DENY") : |
---|
| 557 | return action |
---|
| 558 | elif action == "WARN" : |
---|
| 559 | warned = 1 |
---|
| 560 | elif action == "POLICY_ALLOW" : |
---|
| 561 | policyallowed = 1 |
---|
| 562 | if warned : |
---|
| 563 | return "WARN" |
---|
| 564 | elif policyallowed : |
---|
| 565 | return "POLICY_ALLOW" |
---|
[925] | 566 | else : |
---|
[1365] | 567 | return "ALLOW" |
---|
| 568 | |
---|
[1196] | 569 | def externalMailTo(self, cmd, action, user, printer, message) : |
---|
[1192] | 570 | """Warns the user with an external command.""" |
---|
| 571 | username = user.Name |
---|
[1196] | 572 | printername = printer.Name |
---|
[1192] | 573 | email = user.Email or user.Name |
---|
| 574 | if "@" not in email : |
---|
[1353] | 575 | email = "%s@%s" % (email, self.maildomain or self.smtpserver) |
---|
[1192] | 576 | os.system(cmd % locals()) |
---|
| 577 | |
---|
[1196] | 578 | def formatCommandLine(self, cmd, user, printer) : |
---|
| 579 | """Executes an external command.""" |
---|
| 580 | username = user.Name |
---|
| 581 | printername = printer.Name |
---|
| 582 | return cmd % locals() |
---|
| 583 | |
---|
[1041] | 584 | def warnGroupPQuota(self, grouppquota) : |
---|
[927] | 585 | """Checks a group quota and send messages if quota is exceeded on current printer.""" |
---|
[1041] | 586 | group = grouppquota.Group |
---|
| 587 | printer = grouppquota.Printer |
---|
| 588 | admin = self.config.getAdmin(printer.Name) |
---|
| 589 | adminmail = self.config.getAdminMail(printer.Name) |
---|
[1192] | 590 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[2547] | 591 | if group.LimitBy in ("noquota", "nochange") : |
---|
| 592 | action = "ALLOW" |
---|
| 593 | else : |
---|
| 594 | action = self.checkGroupPQuota(grouppquota) |
---|
| 595 | if action.startswith("POLICY_") : |
---|
| 596 | action = action[7:] |
---|
| 597 | if action == "DENY" : |
---|
| 598 | adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name) |
---|
| 599 | self.printInfo(adminmessage) |
---|
| 600 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 601 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 602 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 603 | for user in self.storage.getGroupMembers(group) : |
---|
| 604 | if mailto != "EXTERNAL" : |
---|
| 605 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name)) |
---|
| 606 | else : |
---|
| 607 | self.externalMailTo(arguments, action, user, printer, self.config.getHardWarn(printer.Name)) |
---|
| 608 | elif action == "WARN" : |
---|
| 609 | adminmessage = _("Print Quota low for group %s on printer %s") % (group.Name, printer.Name) |
---|
| 610 | self.printInfo(adminmessage) |
---|
| 611 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 612 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 613 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
| 614 | message = self.config.getPoorWarn() |
---|
| 615 | else : |
---|
| 616 | message = self.config.getSoftWarn(printer.Name) |
---|
| 617 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 618 | for user in self.storage.getGroupMembers(group) : |
---|
| 619 | if mailto != "EXTERNAL" : |
---|
| 620 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 621 | else : |
---|
| 622 | self.externalMailTo(arguments, action, user, printer, message) |
---|
[927] | 623 | return action |
---|
[728] | 624 | |
---|
[1041] | 625 | def warnUserPQuota(self, userpquota) : |
---|
[728] | 626 | """Checks a user quota and send him a message if quota is exceeded on current printer.""" |
---|
[1041] | 627 | user = userpquota.User |
---|
[1245] | 628 | printer = userpquota.Printer |
---|
| 629 | admin = self.config.getAdmin(printer.Name) |
---|
| 630 | adminmail = self.config.getAdminMail(printer.Name) |
---|
| 631 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[2547] | 632 | |
---|
| 633 | if user.LimitBy in ("noquota", "nochange") : |
---|
| 634 | action = "ALLOW" |
---|
| 635 | elif user.LimitBy == "noprint" : |
---|
| 636 | action = "DENY" |
---|
[2558] | 637 | message = _("User %s is not allowed to print at this time.") % user.Name |
---|
| 638 | self.printInfo(message) |
---|
[1245] | 639 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 640 | if mailto != "EXTERNAL" : |
---|
[2547] | 641 | self.sendMessageToUser(admin, adminmail, user, _("Printing denied."), message) |
---|
[1245] | 642 | else : |
---|
| 643 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 644 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
[2547] | 645 | self.sendMessageToAdmin(adminmail, _("Print Quota"), message) |
---|
| 646 | else : |
---|
| 647 | action = self.checkUserPQuota(userpquota) |
---|
| 648 | if action.startswith("POLICY_") : |
---|
| 649 | action = action[7:] |
---|
| 650 | |
---|
| 651 | if action == "DENY" : |
---|
| 652 | adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 653 | self.printInfo(adminmessage) |
---|
| 654 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 655 | message = self.config.getHardWarn(printer.Name) |
---|
| 656 | if mailto != "EXTERNAL" : |
---|
| 657 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 658 | else : |
---|
| 659 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 660 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 661 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 662 | elif action == "WARN" : |
---|
| 663 | adminmessage = _("Print Quota low for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 664 | self.printInfo(adminmessage) |
---|
| 665 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 666 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
| 667 | message = self.config.getPoorWarn() |
---|
| 668 | else : |
---|
| 669 | message = self.config.getSoftWarn(printer.Name) |
---|
| 670 | if mailto != "EXTERNAL" : |
---|
| 671 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message) |
---|
| 672 | else : |
---|
| 673 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 674 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 675 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1245] | 676 | return action |
---|
[1196] | 677 | |
---|