[1144] | 1 | # PyKota |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
[695] | 3 | |
---|
[952] | 4 | # PyKota - Print Quotas for CUPS and LPRng |
---|
[695] | 5 | # |
---|
[1257] | 6 | # (c) 2003-2004 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 | # |
---|
[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 |
---|
[695] | 39 | |
---|
[708] | 40 | from mx import DateTime |
---|
| 41 | |
---|
[1492] | 42 | from pykota import version, config, storage, logger, accounter, pdlanalyzer |
---|
[695] | 43 | |
---|
[1795] | 44 | def N_(message) : |
---|
| 45 | """Fake translation marker for translatable strings extraction.""" |
---|
| 46 | return message |
---|
| 47 | |
---|
[695] | 48 | class PyKotaToolError(Exception): |
---|
| 49 | """An exception for PyKota config related stuff.""" |
---|
| 50 | def __init__(self, message = ""): |
---|
| 51 | self.message = message |
---|
| 52 | Exception.__init__(self, message) |
---|
| 53 | def __repr__(self): |
---|
| 54 | return self.message |
---|
| 55 | __str__ = __repr__ |
---|
| 56 | |
---|
[1546] | 57 | def crashed(message) : |
---|
| 58 | """Minimal crash method.""" |
---|
| 59 | import traceback |
---|
| 60 | lines = [] |
---|
| 61 | for line in traceback.format_exception(*sys.exc_info()) : |
---|
| 62 | lines.extend([l for l in line.split("\n") if l]) |
---|
| 63 | msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % version.__version__, message] + lines)]) |
---|
| 64 | sys.stderr.write(msg) |
---|
| 65 | sys.stderr.flush() |
---|
| 66 | return msg |
---|
| 67 | |
---|
[1911] | 68 | class Tool : |
---|
| 69 | """Base class for tools with no database access.""" |
---|
[1846] | 70 | def __init__(self, lang="", charset=None, doc="PyKota %s (c) 2003-2004 %s" % (version.__version__, version.__author__)) : |
---|
[695] | 71 | """Initializes the command line tool.""" |
---|
[2006] | 72 | # did we drop priviledges ? |
---|
| 73 | self.privdropped = 0 |
---|
| 74 | |
---|
[772] | 75 | # locale stuff |
---|
[1856] | 76 | defaultToCLocale = 0 |
---|
[788] | 77 | try : |
---|
[1171] | 78 | locale.setlocale(locale.LC_ALL, lang) |
---|
[788] | 79 | except (locale.Error, IOError) : |
---|
[1856] | 80 | locale.setlocale(locale.LC_ALL, "C") |
---|
| 81 | defaultToCLocale = 1 |
---|
[1898] | 82 | try : |
---|
| 83 | gettext.install("pykota") |
---|
| 84 | except : |
---|
[788] | 85 | gettext.NullTranslations().install() |
---|
[1761] | 86 | |
---|
| 87 | # We can force the charset. |
---|
| 88 | # The CHARSET environment variable is set by CUPS when printing. |
---|
| 89 | # Else we use the current locale's one. |
---|
| 90 | # If nothing is set, we use ISO-8859-15 widely used in western Europe. |
---|
[1856] | 91 | localecharset = None |
---|
[1776] | 92 | try : |
---|
[1851] | 93 | try : |
---|
[2195] | 94 | localecharset = locale.nl_langinfo(locale.CODESET) |
---|
[1856] | 95 | except AttributeError : |
---|
| 96 | try : |
---|
[2195] | 97 | localecharset = locale.getpreferredencoding() |
---|
| 98 | except AttributeError : |
---|
| 99 | localecharset = locale.getlocale()[1] |
---|
| 100 | try : |
---|
| 101 | localecharset = localecharset or locale.getdefaultlocale()[1] |
---|
| 102 | except ValueError : |
---|
| 103 | pass # Unknown locale, strange... |
---|
[1856] | 104 | except locale.Error : |
---|
| 105 | pass |
---|
[1776] | 106 | self.charset = charset or os.environ.get("CHARSET") or localecharset or "ISO-8859-15" |
---|
[772] | 107 | |
---|
| 108 | # pykota specific stuff |
---|
[715] | 109 | self.documentation = doc |
---|
[1960] | 110 | |
---|
| 111 | # try to find the configuration files in user's 'pykota' home directory. |
---|
[1537] | 112 | try : |
---|
[2006] | 113 | self.pykotauser = pwd.getpwnam("pykota") |
---|
[1960] | 114 | except KeyError : |
---|
[2006] | 115 | self.pykotauser = None |
---|
[1960] | 116 | confdir = "/etc/pykota" |
---|
| 117 | missingUser = 1 |
---|
| 118 | else : |
---|
[2006] | 119 | confdir = self.pykotauser[5] |
---|
[1960] | 120 | missingUser = 0 |
---|
| 121 | |
---|
| 122 | try : |
---|
| 123 | self.config = config.PyKotaConfig(confdir) |
---|
[1537] | 124 | except ConfigParser.ParsingError, msg : |
---|
| 125 | sys.stderr.write("ERROR: Problem encountered while parsing configuration file : %s\n" % msg) |
---|
| 126 | sys.stderr.flush() |
---|
| 127 | sys.exit(-1) |
---|
[1542] | 128 | |
---|
[1523] | 129 | try : |
---|
[1541] | 130 | self.debug = self.config.getDebug() |
---|
| 131 | self.smtpserver = self.config.getSMTPServer() |
---|
| 132 | self.maildomain = self.config.getMailDomain() |
---|
[1523] | 133 | self.logger = logger.openLogger(self.config.getLoggingBackend()) |
---|
[1537] | 134 | except (config.PyKotaConfigError, logger.PyKotaLoggingError, storage.PyKotaStorageError), msg : |
---|
[1523] | 135 | self.crashed(msg) |
---|
| 136 | raise |
---|
[1960] | 137 | |
---|
[2006] | 138 | # now drop priviledge if possible |
---|
| 139 | self.dropPriv() |
---|
| 140 | |
---|
[1960] | 141 | # We NEED this here, even when not in an accounting filter/backend |
---|
[1497] | 142 | self.softwareJobSize = 0 |
---|
[1495] | 143 | self.softwareJobPrice = 0.0 |
---|
[1960] | 144 | |
---|
[1856] | 145 | if defaultToCLocale : |
---|
| 146 | self.printInfo("Incorrect locale settings. PyKota falls back to the 'C' locale.", "warn") |
---|
[1960] | 147 | if missingUser : |
---|
| 148 | self.printInfo("The 'pykota' system account is missing. Configuration files were searched in /etc/pykota instead.", "warn") |
---|
| 149 | |
---|
[1761] | 150 | self.logdebug("Charset in use : %s" % self.charset) |
---|
[1872] | 151 | arguments = " ".join(['"%s"' % arg for arg in sys.argv]) |
---|
| 152 | self.logdebug("Command line arguments : %s" % arguments) |
---|
[695] | 153 | |
---|
[2006] | 154 | def dropPriv(self) : |
---|
| 155 | """Drops priviledges.""" |
---|
| 156 | uid = os.geteuid() |
---|
| 157 | if uid : |
---|
| 158 | try : |
---|
| 159 | username = pwd.getpwuid(uid)[0] |
---|
| 160 | except (KeyError, IndexError), msg : |
---|
| 161 | self.printInfo(_("Strange problem with uid(%s) : %s") % (uid, msg), "warn") |
---|
| 162 | else : |
---|
| 163 | self.logdebug(_("Running as user '%s'.") % username) |
---|
| 164 | else : |
---|
| 165 | if self.pykotauser is None : |
---|
| 166 | self.logdebug(_("No user named 'pykota'. Not dropping priviledges.")) |
---|
| 167 | else : |
---|
| 168 | try : |
---|
| 169 | os.setegid(self.pykotauser[3]) |
---|
| 170 | os.seteuid(self.pykotauser[2]) |
---|
| 171 | except OSError, msg : |
---|
| 172 | self.printInfo(_("Impossible to drop priviledges : %s") % msg, "warn") |
---|
| 173 | else : |
---|
| 174 | self.logdebug(_("Priviledges dropped. Now running as user 'pykota'.")) |
---|
| 175 | self.privdropped = 1 |
---|
| 176 | |
---|
| 177 | def regainPriv(self) : |
---|
| 178 | """Drops priviledges.""" |
---|
| 179 | if self.privdropped : |
---|
| 180 | try : |
---|
| 181 | os.seteuid(0) |
---|
| 182 | os.setegid(0) |
---|
| 183 | except OSError, msg : |
---|
| 184 | self.printInfo(_("Impossible to regain priviledges : %s") % msg, "warn") |
---|
| 185 | else : |
---|
[2008] | 186 | self.logdebug(_("Regained priviledges. Now running as root.")) |
---|
[2006] | 187 | self.privdropped = 0 |
---|
| 188 | |
---|
[1761] | 189 | def getCharset(self) : |
---|
| 190 | """Returns the charset in use.""" |
---|
| 191 | return self.charset |
---|
| 192 | |
---|
[1130] | 193 | def logdebug(self, message) : |
---|
| 194 | """Logs something to debug output if debug is enabled.""" |
---|
| 195 | if self.debug : |
---|
| 196 | self.logger.log_message(message, "debug") |
---|
[1582] | 197 | |
---|
[1584] | 198 | def printInfo(self, message, level="info") : |
---|
[1582] | 199 | """Sends a message to standard error.""" |
---|
[1584] | 200 | sys.stderr.write("%s: %s\n" % (level.upper(), message)) |
---|
[1582] | 201 | sys.stderr.flush() |
---|
[1130] | 202 | |
---|
[715] | 203 | def display_version_and_quit(self) : |
---|
| 204 | """Displays version number, then exists successfully.""" |
---|
[1923] | 205 | try : |
---|
| 206 | self.clean() |
---|
| 207 | except AttributeError : |
---|
| 208 | pass |
---|
[715] | 209 | print version.__version__ |
---|
| 210 | sys.exit(0) |
---|
| 211 | |
---|
| 212 | def display_usage_and_quit(self) : |
---|
| 213 | """Displays command line usage, then exists successfully.""" |
---|
[1923] | 214 | try : |
---|
| 215 | self.clean() |
---|
| 216 | except AttributeError : |
---|
| 217 | pass |
---|
[1803] | 218 | print _(self.documentation) % (version.__version__, version.__author__) |
---|
[715] | 219 | sys.exit(0) |
---|
| 220 | |
---|
[1517] | 221 | def crashed(self, message) : |
---|
| 222 | """Outputs a crash message, and optionally sends it to software author.""" |
---|
[1546] | 223 | msg = crashed(message) |
---|
[1541] | 224 | try : |
---|
| 225 | crashrecipient = self.config.getCrashRecipient() |
---|
| 226 | if crashrecipient : |
---|
[1517] | 227 | admin = self.config.getAdminMail("global") # Nice trick, isn't it ? |
---|
[1546] | 228 | fullmessage = "========== Traceback :\n\n%s\n\n========== sys.argv :\n\n%s\n\n========== Environment :\n\n%s\n" % \ |
---|
| 229 | (msg, \ |
---|
[1517] | 230 | "\n".join([" %s" % repr(a) for a in sys.argv]), \ |
---|
| 231 | "\n".join([" %s=%s" % (k, v) for (k, v) in os.environ.items()])) |
---|
| 232 | server = smtplib.SMTP(self.smtpserver) |
---|
[1546] | 233 | server.sendmail(admin, [admin, crashrecipient], \ |
---|
[1560] | 234 | "From: %s\nTo: %s\nCc: %s\nSubject: PyKota v%s crash traceback !\n\n%s" % \ |
---|
| 235 | (admin, crashrecipient, admin, version.__version__, fullmessage)) |
---|
[1517] | 236 | server.quit() |
---|
[1541] | 237 | except : |
---|
| 238 | pass |
---|
[1517] | 239 | |
---|
[729] | 240 | def parseCommandline(self, argv, short, long, allownothing=0) : |
---|
[715] | 241 | """Parses the command line, controlling options.""" |
---|
| 242 | # split options in two lists: those which need an argument, those which don't need any |
---|
| 243 | withoutarg = [] |
---|
| 244 | witharg = [] |
---|
| 245 | lgs = len(short) |
---|
| 246 | i = 0 |
---|
| 247 | while i < lgs : |
---|
| 248 | ii = i + 1 |
---|
| 249 | if (ii < lgs) and (short[ii] == ':') : |
---|
| 250 | # needs an argument |
---|
| 251 | witharg.append(short[i]) |
---|
| 252 | ii = ii + 1 # skip the ':' |
---|
| 253 | else : |
---|
| 254 | # doesn't need an argument |
---|
| 255 | withoutarg.append(short[i]) |
---|
| 256 | i = ii |
---|
| 257 | |
---|
| 258 | for option in long : |
---|
| 259 | if option[-1] == '=' : |
---|
| 260 | # needs an argument |
---|
| 261 | witharg.append(option[:-1]) |
---|
| 262 | else : |
---|
| 263 | # doesn't need an argument |
---|
| 264 | withoutarg.append(option) |
---|
| 265 | |
---|
| 266 | # we begin with all possible options unset |
---|
| 267 | parsed = {} |
---|
| 268 | for option in withoutarg + witharg : |
---|
| 269 | parsed[option] = None |
---|
| 270 | |
---|
| 271 | # then we parse the command line |
---|
| 272 | args = [] # to not break if something unexpected happened |
---|
| 273 | try : |
---|
| 274 | options, args = getopt.getopt(argv, short, long) |
---|
| 275 | if options : |
---|
| 276 | for (o, v) in options : |
---|
| 277 | # we skip the '-' chars |
---|
| 278 | lgo = len(o) |
---|
| 279 | i = 0 |
---|
| 280 | while (i < lgo) and (o[i] == '-') : |
---|
| 281 | i = i + 1 |
---|
| 282 | o = o[i:] |
---|
| 283 | if o in witharg : |
---|
| 284 | # needs an argument : set it |
---|
| 285 | parsed[o] = v |
---|
| 286 | elif o in withoutarg : |
---|
| 287 | # doesn't need an argument : boolean |
---|
| 288 | parsed[o] = 1 |
---|
| 289 | else : |
---|
| 290 | # should never occur |
---|
| 291 | raise PyKotaToolError, "Unexpected problem when parsing command line" |
---|
[729] | 292 | elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty |
---|
[715] | 293 | self.display_usage_and_quit() |
---|
| 294 | except getopt.error, msg : |
---|
[1584] | 295 | self.printInfo(msg) |
---|
[715] | 296 | self.display_usage_and_quit() |
---|
| 297 | return (parsed, args) |
---|
| 298 | |
---|
[1911] | 299 | class PyKotaTool(Tool) : |
---|
| 300 | """Base class for all PyKota command line tools.""" |
---|
| 301 | def __init__(self, lang="", charset=None, doc="PyKota %s (c) 2003-2004 %s" % (version.__version__, version.__author__)) : |
---|
| 302 | """Initializes the command line tool and opens the database.""" |
---|
| 303 | Tool.__init__(self, lang, charset, doc) |
---|
| 304 | try : |
---|
| 305 | self.storage = storage.openConnection(self) |
---|
| 306 | except storage.PyKotaStorageError, msg : |
---|
| 307 | self.crashed(msg) |
---|
| 308 | raise |
---|
[2093] | 309 | else : |
---|
| 310 | if self.config.isAdmin : # TODO : We don't know this before, fix this ! |
---|
| 311 | self.logdebug("Beware : running as a PyKota administrator !") |
---|
| 312 | else : |
---|
| 313 | self.logdebug("Don't Panic : running as a mere mortal !") |
---|
[1911] | 314 | |
---|
| 315 | def clean(self) : |
---|
| 316 | """Ensures that the database is closed.""" |
---|
| 317 | try : |
---|
| 318 | self.storage.close() |
---|
| 319 | except (TypeError, NameError, AttributeError) : |
---|
| 320 | pass |
---|
| 321 | |
---|
[764] | 322 | def isValidName(self, name) : |
---|
| 323 | """Checks if a user or printer name is valid.""" |
---|
[1725] | 324 | invalidchars = "/@?*,;&|" |
---|
[1637] | 325 | for c in list(invalidchars) : |
---|
[1593] | 326 | if c in name : |
---|
[1394] | 327 | return 0 |
---|
| 328 | return 1 |
---|
[764] | 329 | |
---|
[817] | 330 | def matchString(self, s, patterns) : |
---|
| 331 | """Returns 1 if the string s matches one of the patterns, else 0.""" |
---|
| 332 | for pattern in patterns : |
---|
| 333 | if fnmatch.fnmatchcase(s, pattern) : |
---|
| 334 | return 1 |
---|
| 335 | return 0 |
---|
| 336 | |
---|
[802] | 337 | def sendMessage(self, adminmail, touser, fullmessage) : |
---|
[695] | 338 | """Sends an email message containing headers to some user.""" |
---|
| 339 | if "@" not in touser : |
---|
[1353] | 340 | touser = "%s@%s" % (touser, self.maildomain or self.smtpserver) |
---|
[1469] | 341 | try : |
---|
| 342 | server = smtplib.SMTP(self.smtpserver) |
---|
| 343 | except socket.error, msg : |
---|
[1584] | 344 | self.printInfo(_("Impossible to connect to SMTP server : %s") % msg, "error") |
---|
[1469] | 345 | else : |
---|
| 346 | try : |
---|
| 347 | server.sendmail(adminmail, [touser], "From: %s\nTo: %s\n%s" % (adminmail, touser, fullmessage)) |
---|
| 348 | except smtplib.SMTPException, answer : |
---|
| 349 | for (k, v) in answer.recipients.items() : |
---|
[1584] | 350 | self.printInfo(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error") |
---|
[1469] | 351 | server.quit() |
---|
[695] | 352 | |
---|
[1079] | 353 | def sendMessageToUser(self, admin, adminmail, user, subject, message) : |
---|
[695] | 354 | """Sends an email message to a user.""" |
---|
[802] | 355 | message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail) |
---|
[1079] | 356 | self.sendMessage(adminmail, user.Email or user.Name, "Subject: %s\n\n%s" % (subject, message)) |
---|
[695] | 357 | |
---|
[802] | 358 | def sendMessageToAdmin(self, adminmail, subject, message) : |
---|
[695] | 359 | """Sends an email message to the Print Quota administrator.""" |
---|
[802] | 360 | self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message)) |
---|
[695] | 361 | |
---|
[1365] | 362 | def _checkUserPQuota(self, userpquota) : |
---|
| 363 | """Checks the user quota on a printer and deny or accept the job.""" |
---|
| 364 | # then we check the user's own quota |
---|
| 365 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 366 | user = userpquota.User |
---|
| 367 | printer = userpquota.Printer |
---|
[1495] | 368 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 369 | self.logdebug("Checking user %s's quota on printer %s" % (user.Name, printer.Name)) |
---|
| 370 | (policy, dummy) = self.config.getPrinterPolicy(userpquota.Printer.Name) |
---|
| 371 | if not userpquota.Exists : |
---|
| 372 | # Unknown userquota |
---|
| 373 | if policy == "ALLOW" : |
---|
| 374 | action = "POLICY_ALLOW" |
---|
| 375 | else : |
---|
| 376 | action = "POLICY_DENY" |
---|
[1584] | 377 | self.printInfo(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action)) |
---|
[1365] | 378 | else : |
---|
| 379 | pagecounter = int(userpquota.PageCounter or 0) |
---|
[1495] | 380 | if enforcement == "STRICT" : |
---|
| 381 | pagecounter += self.softwareJobSize |
---|
[1365] | 382 | if userpquota.SoftLimit is not None : |
---|
| 383 | softlimit = int(userpquota.SoftLimit) |
---|
| 384 | if pagecounter < softlimit : |
---|
| 385 | action = "ALLOW" |
---|
| 386 | else : |
---|
| 387 | if userpquota.HardLimit is None : |
---|
| 388 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 389 | action = "DENY" |
---|
| 390 | else : |
---|
| 391 | hardlimit = int(userpquota.HardLimit) |
---|
| 392 | if softlimit <= pagecounter < hardlimit : |
---|
| 393 | now = DateTime.now() |
---|
| 394 | if userpquota.DateLimit is not None : |
---|
| 395 | datelimit = DateTime.ISO.ParseDateTime(userpquota.DateLimit) |
---|
| 396 | else : |
---|
| 397 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 398 | userpquota.setDateLimit(datelimit) |
---|
| 399 | if now < datelimit : |
---|
| 400 | action = "WARN" |
---|
| 401 | else : |
---|
| 402 | action = "DENY" |
---|
| 403 | else : |
---|
| 404 | action = "DENY" |
---|
| 405 | else : |
---|
| 406 | if userpquota.HardLimit is not None : |
---|
| 407 | # no soft limit, only a hard one. |
---|
| 408 | hardlimit = int(userpquota.HardLimit) |
---|
| 409 | if pagecounter < hardlimit : |
---|
| 410 | action = "ALLOW" |
---|
| 411 | else : |
---|
| 412 | action = "DENY" |
---|
| 413 | else : |
---|
| 414 | # Both are unset, no quota, i.e. accounting only |
---|
| 415 | action = "ALLOW" |
---|
| 416 | return action |
---|
| 417 | |
---|
[1041] | 418 | def checkGroupPQuota(self, grouppquota) : |
---|
[927] | 419 | """Checks the group quota on a printer and deny or accept the job.""" |
---|
[1041] | 420 | group = grouppquota.Group |
---|
| 421 | printer = grouppquota.Printer |
---|
[1495] | 422 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 423 | self.logdebug("Checking group %s's quota on printer %s" % (group.Name, printer.Name)) |
---|
[1061] | 424 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
[1666] | 425 | val = group.AccountBalance or 0.0 |
---|
[1495] | 426 | if enforcement == "STRICT" : |
---|
| 427 | val -= self.softwareJobPrice # use precomputed size. |
---|
| 428 | if val <= 0.0 : |
---|
[1041] | 429 | action = "DENY" |
---|
[1495] | 430 | elif val <= self.config.getPoorMan() : |
---|
[1077] | 431 | action = "WARN" |
---|
[927] | 432 | else : |
---|
[1041] | 433 | action = "ALLOW" |
---|
[1529] | 434 | if (enforcement == "STRICT") and (val == 0.0) : |
---|
| 435 | action = "WARN" # we can still print until account is 0 |
---|
[927] | 436 | else : |
---|
[1665] | 437 | val = grouppquota.PageCounter or 0 |
---|
[1495] | 438 | if enforcement == "STRICT" : |
---|
| 439 | val += self.softwareJobSize |
---|
[1041] | 440 | if grouppquota.SoftLimit is not None : |
---|
| 441 | softlimit = int(grouppquota.SoftLimit) |
---|
[1495] | 442 | if val < softlimit : |
---|
[1041] | 443 | action = "ALLOW" |
---|
[927] | 444 | else : |
---|
[1041] | 445 | if grouppquota.HardLimit is None : |
---|
| 446 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 447 | action = "DENY" |
---|
[927] | 448 | else : |
---|
[1041] | 449 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 450 | if softlimit <= val < hardlimit : |
---|
[1041] | 451 | now = DateTime.now() |
---|
| 452 | if grouppquota.DateLimit is not None : |
---|
| 453 | datelimit = DateTime.ISO.ParseDateTime(grouppquota.DateLimit) |
---|
| 454 | else : |
---|
| 455 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 456 | grouppquota.setDateLimit(datelimit) |
---|
| 457 | if now < datelimit : |
---|
| 458 | action = "WARN" |
---|
| 459 | else : |
---|
[927] | 460 | action = "DENY" |
---|
[1041] | 461 | else : |
---|
[927] | 462 | action = "DENY" |
---|
[1041] | 463 | else : |
---|
| 464 | if grouppquota.HardLimit is not None : |
---|
| 465 | # no soft limit, only a hard one. |
---|
| 466 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 467 | if val < hardlimit : |
---|
[927] | 468 | action = "ALLOW" |
---|
[1041] | 469 | else : |
---|
| 470 | action = "DENY" |
---|
| 471 | else : |
---|
| 472 | # Both are unset, no quota, i.e. accounting only |
---|
| 473 | action = "ALLOW" |
---|
[927] | 474 | return action |
---|
| 475 | |
---|
[1041] | 476 | def checkUserPQuota(self, userpquota) : |
---|
[1365] | 477 | """Checks the user quota on a printer and all its parents and deny or accept the job.""" |
---|
[1041] | 478 | user = userpquota.User |
---|
| 479 | printer = userpquota.Printer |
---|
| 480 | |
---|
[1365] | 481 | # indicates that a warning needs to be sent |
---|
| 482 | warned = 0 |
---|
| 483 | |
---|
[927] | 484 | # first we check any group the user is a member of |
---|
[1041] | 485 | for group in self.storage.getUserGroups(user) : |
---|
| 486 | grouppquota = self.storage.getGroupPQuota(group, printer) |
---|
[1365] | 487 | # for the printer and all its parents |
---|
| 488 | for gpquota in [ grouppquota ] + grouppquota.ParentPrintersGroupPQuota : |
---|
| 489 | if gpquota.Exists : |
---|
| 490 | action = self.checkGroupPQuota(gpquota) |
---|
| 491 | if action == "DENY" : |
---|
| 492 | return action |
---|
| 493 | elif action == "WARN" : |
---|
| 494 | warned = 1 |
---|
| 495 | |
---|
| 496 | # Then we check the user's account balance |
---|
[1152] | 497 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 498 | (policy, dummy) = self.config.getPrinterPolicy(printer.Name) |
---|
[1061] | 499 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
[1365] | 500 | self.logdebug("Checking account balance for user %s" % user.Name) |
---|
[1041] | 501 | if user.AccountBalance is None : |
---|
[956] | 502 | if policy == "ALLOW" : |
---|
[925] | 503 | action = "POLICY_ALLOW" |
---|
| 504 | else : |
---|
| 505 | action = "POLICY_DENY" |
---|
[1584] | 506 | self.printInfo(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name)) |
---|
[1365] | 507 | return action |
---|
[713] | 508 | else : |
---|
[2054] | 509 | if user.OverCharge == 0.0 : |
---|
| 510 | self.printInfo(_("User %s will not be charged for printing.") % user.Name) |
---|
| 511 | action = "ALLOW" |
---|
[1529] | 512 | else : |
---|
[2054] | 513 | val = float(user.AccountBalance or 0.0) |
---|
| 514 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
| 515 | if enforcement == "STRICT" : |
---|
| 516 | val -= self.softwareJobPrice # use precomputed size. |
---|
| 517 | if val <= 0.0 : |
---|
| 518 | action = "DENY" |
---|
| 519 | elif val <= self.config.getPoorMan() : |
---|
| 520 | action = "WARN" |
---|
| 521 | else : |
---|
| 522 | action = "ALLOW" |
---|
| 523 | if (enforcement == "STRICT") and (val == 0.0) : |
---|
| 524 | action = "WARN" # we can still print until account is 0 |
---|
[1529] | 525 | return action |
---|
[925] | 526 | else : |
---|
[1365] | 527 | # Then check the user quota on current printer and all its parents. |
---|
| 528 | policyallowed = 0 |
---|
| 529 | for upquota in [ userpquota ] + userpquota.ParentPrintersUserPQuota : |
---|
| 530 | action = self._checkUserPQuota(upquota) |
---|
| 531 | if action in ("DENY", "POLICY_DENY") : |
---|
| 532 | return action |
---|
| 533 | elif action == "WARN" : |
---|
| 534 | warned = 1 |
---|
| 535 | elif action == "POLICY_ALLOW" : |
---|
| 536 | policyallowed = 1 |
---|
| 537 | if warned : |
---|
| 538 | return "WARN" |
---|
| 539 | elif policyallowed : |
---|
| 540 | return "POLICY_ALLOW" |
---|
[925] | 541 | else : |
---|
[1365] | 542 | return "ALLOW" |
---|
| 543 | |
---|
[1196] | 544 | def externalMailTo(self, cmd, action, user, printer, message) : |
---|
[1192] | 545 | """Warns the user with an external command.""" |
---|
| 546 | username = user.Name |
---|
[1196] | 547 | printername = printer.Name |
---|
[1192] | 548 | email = user.Email or user.Name |
---|
| 549 | if "@" not in email : |
---|
[1353] | 550 | email = "%s@%s" % (email, self.maildomain or self.smtpserver) |
---|
[1192] | 551 | os.system(cmd % locals()) |
---|
| 552 | |
---|
[1196] | 553 | def formatCommandLine(self, cmd, user, printer) : |
---|
| 554 | """Executes an external command.""" |
---|
| 555 | username = user.Name |
---|
| 556 | printername = printer.Name |
---|
| 557 | return cmd % locals() |
---|
| 558 | |
---|
[1041] | 559 | def warnGroupPQuota(self, grouppquota) : |
---|
[927] | 560 | """Checks a group quota and send messages if quota is exceeded on current printer.""" |
---|
[1041] | 561 | group = grouppquota.Group |
---|
| 562 | printer = grouppquota.Printer |
---|
| 563 | admin = self.config.getAdmin(printer.Name) |
---|
| 564 | adminmail = self.config.getAdminMail(printer.Name) |
---|
[1192] | 565 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[1068] | 566 | action = self.checkGroupPQuota(grouppquota) |
---|
[927] | 567 | if action.startswith("POLICY_") : |
---|
| 568 | action = action[7:] |
---|
| 569 | if action == "DENY" : |
---|
[1041] | 570 | adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name) |
---|
[1584] | 571 | self.printInfo(adminmessage) |
---|
[927] | 572 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 573 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1192] | 574 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
[1140] | 575 | for user in self.storage.getGroupMembers(group) : |
---|
[1192] | 576 | if mailto != "EXTERNAL" : |
---|
[1245] | 577 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name)) |
---|
[1192] | 578 | else : |
---|
[1637] | 579 | self.externalMailTo(arguments, action, user, printer, self.config.getHardWarn(printer.Name)) |
---|
[927] | 580 | elif action == "WARN" : |
---|
[1091] | 581 | adminmessage = _("Print Quota low for group %s on printer %s") % (group.Name, printer.Name) |
---|
[1584] | 582 | self.printInfo(adminmessage) |
---|
[927] | 583 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 584 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1077] | 585 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
| 586 | message = self.config.getPoorWarn() |
---|
| 587 | else : |
---|
| 588 | message = self.config.getSoftWarn(printer.Name) |
---|
[1192] | 589 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
[1140] | 590 | for user in self.storage.getGroupMembers(group) : |
---|
[1192] | 591 | if mailto != "EXTERNAL" : |
---|
| 592 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 593 | else : |
---|
[1196] | 594 | self.externalMailTo(arguments, action, user, printer, message) |
---|
[927] | 595 | return action |
---|
[728] | 596 | |
---|
[1041] | 597 | def warnUserPQuota(self, userpquota) : |
---|
[728] | 598 | """Checks a user quota and send him a message if quota is exceeded on current printer.""" |
---|
[1041] | 599 | user = userpquota.User |
---|
[1245] | 600 | printer = userpquota.Printer |
---|
| 601 | admin = self.config.getAdmin(printer.Name) |
---|
| 602 | adminmail = self.config.getAdminMail(printer.Name) |
---|
| 603 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
| 604 | action = self.checkUserPQuota(userpquota) |
---|
| 605 | if action.startswith("POLICY_") : |
---|
| 606 | action = action[7:] |
---|
[2054] | 607 | |
---|
[1245] | 608 | if action == "DENY" : |
---|
| 609 | adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name) |
---|
[1584] | 610 | self.printInfo(adminmessage) |
---|
[1245] | 611 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 612 | message = self.config.getHardWarn(printer.Name) |
---|
| 613 | if mailto != "EXTERNAL" : |
---|
| 614 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 615 | else : |
---|
| 616 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 617 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 618 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 619 | elif action == "WARN" : |
---|
| 620 | adminmessage = _("Print Quota low for user %s on printer %s") % (user.Name, printer.Name) |
---|
[1584] | 621 | self.printInfo(adminmessage) |
---|
[1245] | 622 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 623 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
| 624 | message = self.config.getPoorWarn() |
---|
| 625 | else : |
---|
| 626 | message = self.config.getSoftWarn(printer.Name) |
---|
| 627 | if mailto != "EXTERNAL" : |
---|
| 628 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message) |
---|
| 629 | else : |
---|
| 630 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 631 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 632 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 633 | return action |
---|
[1196] | 634 | |
---|
| 635 | class PyKotaFilterOrBackend(PyKotaTool) : |
---|
| 636 | """Class for the PyKota filter or backend.""" |
---|
| 637 | def __init__(self) : |
---|
[1290] | 638 | """Initialize local datas from current environment.""" |
---|
[1492] | 639 | # We begin with ignoring signals, we may de-ignore them later on. |
---|
| 640 | self.gotSigTerm = 0 |
---|
| 641 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
---|
[1532] | 642 | # signal.signal(signal.SIGCHLD, signal.SIG_IGN) |
---|
[1492] | 643 | signal.signal(signal.SIGPIPE, signal.SIG_IGN) |
---|
| 644 | |
---|
[1196] | 645 | PyKotaTool.__init__(self) |
---|
| 646 | (self.printingsystem, \ |
---|
| 647 | self.printerhostname, \ |
---|
| 648 | self.printername, \ |
---|
| 649 | self.username, \ |
---|
| 650 | self.jobid, \ |
---|
| 651 | self.inputfile, \ |
---|
| 652 | self.copies, \ |
---|
| 653 | self.title, \ |
---|
| 654 | self.options, \ |
---|
| 655 | self.originalbackend) = self.extractInfoFromCupsOrLprng() |
---|
[1601] | 656 | |
---|
[1849] | 657 | arguments = " ".join(['"%s"' % arg for arg in sys.argv]) |
---|
| 658 | self.logdebug(_("Printing system %s, args=%s") % (str(self.printingsystem), arguments)) |
---|
[1601] | 659 | |
---|
[1483] | 660 | self.username = self.username or 'root' # when printing test page from CUPS web interface, username is empty |
---|
[1757] | 661 | |
---|
| 662 | # do we want to strip out the Samba/Winbind domain name ? |
---|
| 663 | separator = self.config.getWinbindSeparator() |
---|
| 664 | if separator is not None : |
---|
| 665 | self.username = self.username.split(separator)[-1] |
---|
| 666 | |
---|
| 667 | # do we want to lowercase usernames ? |
---|
[1227] | 668 | if self.config.getUserNameToLower() : |
---|
| 669 | self.username = self.username.lower() |
---|
[1757] | 670 | |
---|
[1200] | 671 | self.preserveinputfile = self.inputfile |
---|
[1538] | 672 | try : |
---|
| 673 | self.accounter = accounter.openAccounter(self) |
---|
[1563] | 674 | except (config.PyKotaConfigError, accounter.PyKotaAccounterError), msg : |
---|
[1538] | 675 | self.crashed(msg) |
---|
| 676 | raise |
---|
[1372] | 677 | self.exportJobInfo() |
---|
[1492] | 678 | self.jobdatastream = self.openJobDataStream() |
---|
[1756] | 679 | self.checksum = self.computeChecksum() |
---|
[2060] | 680 | self.softwareJobSize = self.precomputeJobSize() |
---|
| 681 | os.environ["PYKOTAPRECOMPUTEDJOBSIZE"] = str(self.softwareJobSize) |
---|
[1517] | 682 | os.environ["PYKOTAJOBSIZEBYTES"] = str(self.jobSizeBytes) |
---|
[2060] | 683 | self.logdebug("Job size is %s bytes on %s pages." % (self.jobSizeBytes, self.softwareJobSize)) |
---|
[1514] | 684 | self.logdebug("Capturing SIGTERM events.") |
---|
| 685 | signal.signal(signal.SIGTERM, self.sigterm_handler) |
---|
[1372] | 686 | |
---|
[1606] | 687 | def sendBackChannelData(self, message, level="info") : |
---|
[1600] | 688 | """Sends an informational message to CUPS via back channel stream (stderr).""" |
---|
[1606] | 689 | sys.stderr.write("%s: PyKota (PID %s) : %s\n" % (level.upper(), os.getpid(), message.strip())) |
---|
| 690 | sys.stderr.flush() |
---|
[1600] | 691 | |
---|
[1756] | 692 | def computeChecksum(self) : |
---|
| 693 | """Computes the MD5 checksum of the job's datas, to be able to detect and forbid duplicate jobs.""" |
---|
| 694 | self.logdebug("Computing MD5 checksum for job %s" % self.jobid) |
---|
| 695 | MEGABYTE = 1024*1024 |
---|
| 696 | checksum = md5.new() |
---|
| 697 | while 1 : |
---|
| 698 | data = self.jobdatastream.read(MEGABYTE) |
---|
| 699 | if not data : |
---|
| 700 | break |
---|
| 701 | checksum.update(data) |
---|
| 702 | self.jobdatastream.seek(0) |
---|
| 703 | digest = checksum.hexdigest() |
---|
| 704 | self.logdebug("MD5 checksum for job %s is %s" % (self.jobid, digest)) |
---|
[1766] | 705 | os.environ["PYKOTAMD5SUM"] = digest |
---|
[1756] | 706 | return digest |
---|
| 707 | |
---|
[1492] | 708 | def openJobDataStream(self) : |
---|
| 709 | """Opens the file which contains the job's datas.""" |
---|
| 710 | if self.preserveinputfile is None : |
---|
| 711 | # Job comes from sys.stdin, but this is not |
---|
| 712 | # seekable and complexifies our task, so create |
---|
| 713 | # a temporary file and use it instead |
---|
[1606] | 714 | self.logdebug("Duplicating data stream from stdin to temporary file") |
---|
[1562] | 715 | dummy = 0 |
---|
[1492] | 716 | MEGABYTE = 1024*1024 |
---|
[1517] | 717 | self.jobSizeBytes = 0 |
---|
[1492] | 718 | infile = tempfile.TemporaryFile() |
---|
| 719 | while 1 : |
---|
| 720 | data = sys.stdin.read(MEGABYTE) |
---|
| 721 | if not data : |
---|
| 722 | break |
---|
[1517] | 723 | self.jobSizeBytes += len(data) |
---|
[1562] | 724 | if not (dummy % 10) : |
---|
[1606] | 725 | self.logdebug("%s bytes read..." % self.jobSizeBytes) |
---|
[1562] | 726 | dummy += 1 |
---|
[1492] | 727 | infile.write(data) |
---|
[1606] | 728 | self.logdebug("%s bytes read total." % self.jobSizeBytes) |
---|
[1492] | 729 | infile.flush() |
---|
| 730 | infile.seek(0) |
---|
| 731 | return infile |
---|
| 732 | else : |
---|
| 733 | # real file, just open it |
---|
[2008] | 734 | self.regainPriv() |
---|
[1606] | 735 | self.logdebug("Opening data stream %s" % self.preserveinputfile) |
---|
[1517] | 736 | self.jobSizeBytes = os.stat(self.preserveinputfile)[6] |
---|
[2008] | 737 | infile = open(self.preserveinputfile, "rb") |
---|
| 738 | self.dropPriv() |
---|
| 739 | return infile |
---|
[1433] | 740 | |
---|
[1492] | 741 | def closeJobDataStream(self) : |
---|
| 742 | """Closes the file which contains the job's datas.""" |
---|
[1606] | 743 | self.logdebug("Closing data stream.") |
---|
[1492] | 744 | try : |
---|
| 745 | self.jobdatastream.close() |
---|
| 746 | except : |
---|
| 747 | pass |
---|
| 748 | |
---|
| 749 | def precomputeJobSize(self) : |
---|
| 750 | """Computes the job size with a software method.""" |
---|
[1495] | 751 | self.logdebug("Precomputing job's size with generic PDL analyzer...") |
---|
[1497] | 752 | self.jobdatastream.seek(0) |
---|
[1492] | 753 | try : |
---|
| 754 | parser = pdlanalyzer.PDLAnalyzer(self.jobdatastream) |
---|
[1495] | 755 | jobsize = parser.getJobSize() |
---|
[1492] | 756 | except pdlanalyzer.PDLAnalyzerError, msg : |
---|
| 757 | # Here we just log the failure, but |
---|
| 758 | # we finally ignore it and return 0 since this |
---|
| 759 | # computation is just an indication of what the |
---|
| 760 | # job's size MAY be. |
---|
[1584] | 761 | self.printInfo(_("Unable to precompute the job's size with the generic PDL analyzer : %s") % msg, "warn") |
---|
[1492] | 762 | return 0 |
---|
[1495] | 763 | else : |
---|
| 764 | if ((self.printingsystem == "CUPS") \ |
---|
| 765 | and (self.preserveinputfile is not None)) \ |
---|
| 766 | or (self.printingsystem != "CUPS") : |
---|
| 767 | return jobsize * self.copies |
---|
| 768 | else : |
---|
| 769 | return jobsize |
---|
[1492] | 770 | |
---|
[1433] | 771 | def sigterm_handler(self, signum, frame) : |
---|
[1481] | 772 | """Sets an attribute whenever SIGTERM is received.""" |
---|
[1433] | 773 | self.gotSigTerm = 1 |
---|
[1517] | 774 | os.environ["PYKOTASTATUS"] = "CANCELLED" |
---|
[1584] | 775 | self.printInfo(_("SIGTERM received, job %s cancelled.") % self.jobid) |
---|
[1433] | 776 | |
---|
[1372] | 777 | def exportJobInfo(self) : |
---|
| 778 | """Exports job information to the environment.""" |
---|
[1517] | 779 | os.environ["PYKOTAUSERNAME"] = str(self.username) |
---|
| 780 | os.environ["PYKOTAPRINTERNAME"] = str(self.printername) |
---|
| 781 | os.environ["PYKOTAJOBID"] = str(self.jobid) |
---|
| 782 | os.environ["PYKOTATITLE"] = self.title or "" |
---|
| 783 | os.environ["PYKOTAFILENAME"] = self.preserveinputfile or "" |
---|
| 784 | os.environ["PYKOTACOPIES"] = str(self.copies) |
---|
| 785 | os.environ["PYKOTAOPTIONS"] = self.options or "" |
---|
[1694] | 786 | os.environ["PYKOTAPRINTERHOSTNAME"] = self.printerhostname or "localhost" |
---|
[1196] | 787 | |
---|
[1372] | 788 | def exportUserInfo(self, userpquota) : |
---|
| 789 | """Exports user information to the environment.""" |
---|
[2054] | 790 | os.environ["PYKOTAOVERCHARGE"] = str(userpquota.User.OverCharge) |
---|
[1517] | 791 | os.environ["PYKOTALIMITBY"] = str(userpquota.User.LimitBy) |
---|
| 792 | os.environ["PYKOTABALANCE"] = str(userpquota.User.AccountBalance or 0.0) |
---|
| 793 | os.environ["PYKOTALIFETIMEPAID"] = str(userpquota.User.LifeTimePaid or 0.0) |
---|
| 794 | os.environ["PYKOTAPAGECOUNTER"] = str(userpquota.PageCounter or 0) |
---|
| 795 | os.environ["PYKOTALIFEPAGECOUNTER"] = str(userpquota.LifePageCounter or 0) |
---|
| 796 | os.environ["PYKOTASOFTLIMIT"] = str(userpquota.SoftLimit) |
---|
| 797 | os.environ["PYKOTAHARDLIMIT"] = str(userpquota.HardLimit) |
---|
| 798 | os.environ["PYKOTADATELIMIT"] = str(userpquota.DateLimit) |
---|
[2054] | 799 | os.environ["PYKOTAWARNCOUNT"] = str(userpquota.WarnCount) |
---|
[1439] | 800 | |
---|
| 801 | # not really an user information, but anyway |
---|
| 802 | # exports the list of printers groups the current |
---|
| 803 | # printer is a member of |
---|
[1517] | 804 | os.environ["PYKOTAPGROUPS"] = ",".join([p.Name for p in self.storage.getParentPrinters(userpquota.Printer)]) |
---|
| 805 | |
---|
[1372] | 806 | def prehook(self, userpquota) : |
---|
[1475] | 807 | """Allows plugging of an external hook before the job gets printed.""" |
---|
[1372] | 808 | prehook = self.config.getPreHook(userpquota.Printer.Name) |
---|
| 809 | if prehook : |
---|
| 810 | self.logdebug("Executing pre-hook [%s]" % prehook) |
---|
| 811 | os.system(prehook) |
---|
| 812 | |
---|
| 813 | def posthook(self, userpquota) : |
---|
[1475] | 814 | """Allows plugging of an external hook after the job gets printed and/or denied.""" |
---|
[1372] | 815 | posthook = self.config.getPostHook(userpquota.Printer.Name) |
---|
| 816 | if posthook : |
---|
| 817 | self.logdebug("Executing post-hook [%s]" % posthook) |
---|
| 818 | os.system(posthook) |
---|
[2060] | 819 | |
---|
[1584] | 820 | def printInfo(self, message, level="info") : |
---|
| 821 | """Sends a message to standard error.""" |
---|
| 822 | self.logger.log_message("%s" % message, level) |
---|
| 823 | |
---|
[1820] | 824 | def printMoreInfo(self, user, printer, message, level="info") : |
---|
| 825 | """Prefixes the information printed with 'user@printer(jobid) =>'.""" |
---|
[1848] | 826 | self.printInfo("%s@%s(%s) => %s" % (getattr(user, "Name", None), getattr(printer, "Name", None), self.jobid, message), level) |
---|
[1820] | 827 | |
---|
[1196] | 828 | def extractInfoFromCupsOrLprng(self) : |
---|
| 829 | """Returns a tuple (printingsystem, printerhostname, printername, username, jobid, filename, title, options, backend). |
---|
| 830 | |
---|
| 831 | Returns (None, None, None, None, None, None, None, None, None, None) if no printing system is recognized. |
---|
| 832 | """ |
---|
| 833 | # Try to detect CUPS |
---|
| 834 | if os.environ.has_key("CUPS_SERVERROOT") and os.path.isdir(os.environ.get("CUPS_SERVERROOT", "")) : |
---|
| 835 | if len(sys.argv) == 7 : |
---|
| 836 | inputfile = sys.argv[6] |
---|
| 837 | else : |
---|
| 838 | inputfile = None |
---|
| 839 | |
---|
| 840 | # check that the DEVICE_URI environment variable's value is |
---|
| 841 | # prefixed with "cupspykota:" otherwise don't touch it. |
---|
| 842 | # If this is the case, we have to remove the prefix from |
---|
| 843 | # the environment before launching the real backend in cupspykota |
---|
| 844 | device_uri = os.environ.get("DEVICE_URI", "") |
---|
| 845 | if device_uri.startswith("cupspykota:") : |
---|
| 846 | fulldevice_uri = device_uri[:] |
---|
| 847 | device_uri = fulldevice_uri[len("cupspykota:"):] |
---|
| 848 | if device_uri.startswith("//") : # lpd (at least) |
---|
| 849 | device_uri = device_uri[2:] |
---|
| 850 | os.environ["DEVICE_URI"] = device_uri # TODO : side effect ! |
---|
| 851 | # TODO : check this for more complex urls than ipp://myprinter.dot.com:631/printers/lp |
---|
| 852 | try : |
---|
| 853 | (backend, destination) = device_uri.split(":", 1) |
---|
| 854 | except ValueError : |
---|
| 855 | raise PyKotaToolError, "Invalid DEVICE_URI : %s\n" % device_uri |
---|
| 856 | while destination.startswith("/") : |
---|
| 857 | destination = destination[1:] |
---|
[1240] | 858 | checkauth = destination.split("@", 1) |
---|
| 859 | if len(checkauth) == 2 : |
---|
| 860 | destination = checkauth[1] |
---|
[1196] | 861 | printerhostname = destination.split("/")[0].split(":")[0] |
---|
| 862 | return ("CUPS", \ |
---|
| 863 | printerhostname, \ |
---|
| 864 | os.environ.get("PRINTER"), \ |
---|
[1216] | 865 | sys.argv[2].strip(), \ |
---|
[1196] | 866 | sys.argv[1].strip(), \ |
---|
| 867 | inputfile, \ |
---|
| 868 | int(sys.argv[4].strip()), \ |
---|
| 869 | sys.argv[3], \ |
---|
| 870 | sys.argv[5], \ |
---|
| 871 | backend) |
---|
| 872 | else : |
---|
| 873 | # Try to detect LPRng |
---|
[1606] | 874 | # TODO : try to extract filename, options if available |
---|
| 875 | jseen = Jseen = Pseen = nseen = rseen = Kseen = None |
---|
[1196] | 876 | for arg in sys.argv : |
---|
| 877 | if arg.startswith("-j") : |
---|
| 878 | jseen = arg[2:].strip() |
---|
| 879 | elif arg.startswith("-n") : |
---|
| 880 | nseen = arg[2:].strip() |
---|
| 881 | elif arg.startswith("-P") : |
---|
| 882 | Pseen = arg[2:].strip() |
---|
| 883 | elif arg.startswith("-r") : |
---|
| 884 | rseen = arg[2:].strip() |
---|
[1606] | 885 | elif arg.startswith("-J") : |
---|
| 886 | Jseen = arg[2:].strip() |
---|
[1196] | 887 | elif arg.startswith("-K") or arg.startswith("-#") : |
---|
| 888 | Kseen = int(arg[2:].strip()) |
---|
| 889 | if Kseen is None : |
---|
| 890 | Kseen = 1 # we assume the user wants at least one copy... |
---|
| 891 | if (rseen is None) and jseen and Pseen and nseen : |
---|
[1850] | 892 | lparg = [arg for arg in "".join(os.environ.get("PRINTCAP_ENTRY", "").split()).split(":") if arg.startswith("rm=") or arg.startswith("lp=")] |
---|
| 893 | try : |
---|
| 894 | rseen = lparg[0].split("=")[-1].split("@")[-1].split("%")[0] |
---|
| 895 | except : |
---|
| 896 | # Not found |
---|
| 897 | self.printInfo(_("Printer hostname undefined, set to 'localhost'"), "warn") |
---|
| 898 | rseen = "localhost" |
---|
[1695] | 899 | |
---|
| 900 | spooldir = os.environ.get("SPOOL_DIR", ".") |
---|
[1932] | 901 | df_name = os.environ.get("DATAFILES") |
---|
| 902 | if not df_name : |
---|
| 903 | try : |
---|
| 904 | df_name = [line[10:] for line in os.environ.get("HF", "").split() if line.startswith("datafiles=")][0] |
---|
[1611] | 905 | except IndexError : |
---|
[1932] | 906 | try : |
---|
| 907 | df_name = [line[8:] for line in os.environ.get("HF", "").split() if line.startswith("df_name=")][0] |
---|
| 908 | except IndexError : |
---|
| 909 | try : |
---|
| 910 | cftransfername = [line[15:] for line in os.environ.get("HF", "").split() if line.startswith("cftransfername=")][0] |
---|
| 911 | except IndexError : |
---|
| 912 | try : |
---|
| 913 | df_name = [line[1:] for line in os.environ.get("CONTROL", "").split() if line.startswith("fdf") or line.startswith("Udf")][0] |
---|
| 914 | except IndexError : |
---|
| 915 | raise PyKotaToolError, "Unable to find the file which holds the job's datas. Please file a bug report for PyKota." |
---|
| 916 | else : |
---|
[1944] | 917 | inputfile = os.path.join(spooldir, df_name) # no need to strip() |
---|
[1932] | 918 | else : |
---|
[1944] | 919 | inputfile = os.path.join(spooldir, "d" + cftransfername[1:]) # no need to strip() |
---|
[1695] | 920 | else : |
---|
[1944] | 921 | inputfile = os.path.join(spooldir, df_name) # no need to strip() |
---|
[1611] | 922 | else : |
---|
[1944] | 923 | inputfile = os.path.join(spooldir, df_name) # no need to strip() |
---|
[1600] | 924 | else : |
---|
[1944] | 925 | inputfile = os.path.join(spooldir, df_name.strip()) |
---|
[1695] | 926 | |
---|
[1196] | 927 | if jseen and Pseen and nseen and rseen : |
---|
[1695] | 928 | options = os.environ.get("HF", "") or os.environ.get("CONTROL", "") |
---|
[1606] | 929 | return ("LPRNG", rseen, Pseen, nseen, jseen, inputfile, Kseen, Jseen, options, None) |
---|
[1584] | 930 | self.printInfo(_("Printing system unknown, args=%s") % " ".join(sys.argv), "warn") |
---|
[1196] | 931 | return (None, None, None, None, None, None, None, None, None, None) # Unknown printing system |
---|
[1229] | 932 | |
---|
| 933 | def getPrinterUserAndUserPQuota(self) : |
---|
| 934 | """Returns a tuple (policy, printer, user, and user print quota) on this printer. |
---|
| 935 | |
---|
| 936 | "OK" is returned in the policy if both printer, user and user print quota |
---|
| 937 | exist in the Quota Storage. |
---|
| 938 | Otherwise, the policy as defined for this printer in pykota.conf is returned. |
---|
| 939 | |
---|
| 940 | If policy was set to "EXTERNAL" and one of printer, user, or user print quota |
---|
| 941 | doesn't exist in the Quota Storage, then an external command is launched, as |
---|
| 942 | defined in the external policy for this printer in pykota.conf |
---|
| 943 | This external command can do anything, like automatically adding printers |
---|
| 944 | or users, for example, and finally extracting printer, user and user print |
---|
| 945 | quota from the Quota Storage is tried a second time. |
---|
| 946 | |
---|
| 947 | "EXTERNALERROR" is returned in case policy was "EXTERNAL" and an error status |
---|
| 948 | was returned by the external command. |
---|
| 949 | """ |
---|
[1245] | 950 | for passnumber in range(1, 3) : |
---|
[1229] | 951 | printer = self.storage.getPrinter(self.printername) |
---|
| 952 | user = self.storage.getUser(self.username) |
---|
| 953 | userpquota = self.storage.getUserPQuota(user, printer) |
---|
| 954 | if printer.Exists and user.Exists and userpquota.Exists : |
---|
| 955 | policy = "OK" |
---|
| 956 | break |
---|
| 957 | (policy, args) = self.config.getPrinterPolicy(self.printername) |
---|
| 958 | if policy == "EXTERNAL" : |
---|
| 959 | commandline = self.formatCommandLine(args, user, printer) |
---|
| 960 | if not printer.Exists : |
---|
[1584] | 961 | self.printInfo(_("Printer %s not registered in the PyKota system, applying external policy (%s) for printer %s") % (self.printername, commandline, self.printername)) |
---|
[1229] | 962 | if not user.Exists : |
---|
[1584] | 963 | self.printInfo(_("User %s not registered in the PyKota system, applying external policy (%s) for printer %s") % (self.username, commandline, self.printername)) |
---|
[1229] | 964 | if not userpquota.Exists : |
---|
[1584] | 965 | self.printInfo(_("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)) |
---|
[1229] | 966 | if os.system(commandline) : |
---|
[1584] | 967 | self.printInfo(_("External policy %s for printer %s produced an error. Job rejected. Please check PyKota's configuration files.") % (commandline, self.printername), "error") |
---|
[1229] | 968 | policy = "EXTERNALERROR" |
---|
| 969 | break |
---|
| 970 | else : |
---|
[1271] | 971 | if not printer.Exists : |
---|
[1584] | 972 | self.printInfo(_("Printer %s not registered in the PyKota system, applying default policy (%s)") % (self.printername, policy)) |
---|
[1271] | 973 | if not user.Exists : |
---|
[1584] | 974 | self.printInfo(_("User %s not registered in the PyKota system, applying default policy (%s) for printer %s") % (self.username, policy, self.printername)) |
---|
[1271] | 975 | if not userpquota.Exists : |
---|
[1584] | 976 | self.printInfo(_("User %s doesn't have quota on printer %s in the PyKota system, applying default policy (%s)") % (self.username, self.printername, policy)) |
---|
[1229] | 977 | break |
---|
[1271] | 978 | if policy == "EXTERNAL" : |
---|
| 979 | if not printer.Exists : |
---|
[1584] | 980 | self.printInfo(_("Printer %s still not registered in the PyKota system, job will be rejected") % self.printername) |
---|
[1271] | 981 | if not user.Exists : |
---|
[1584] | 982 | self.printInfo(_("User %s still not registered in the PyKota system, job will be rejected on printer %s") % (self.username, self.printername)) |
---|
[1271] | 983 | if not userpquota.Exists : |
---|
[1584] | 984 | self.printInfo(_("User %s still doesn't have quota on printer %s in the PyKota system, job will be rejected") % (self.username, self.printername)) |
---|
[1229] | 985 | return (policy, printer, user, userpquota) |
---|
| 986 | |
---|
[1271] | 987 | def mainWork(self) : |
---|
[1229] | 988 | """Main work is done here.""" |
---|
| 989 | (policy, printer, user, userpquota) = self.getPrinterUserAndUserPQuota() |
---|
[1271] | 990 | # TODO : check for last user's quota in case pykota filter is used with querying |
---|
[1229] | 991 | if policy == "EXTERNALERROR" : |
---|
| 992 | # Policy was 'EXTERNAL' and the external command returned an error code |
---|
[1271] | 993 | return self.removeJob() |
---|
[1229] | 994 | elif policy == "EXTERNAL" : |
---|
| 995 | # Policy was 'EXTERNAL' and the external command wasn't able |
---|
| 996 | # to add either the printer, user or user print quota |
---|
[1271] | 997 | return self.removeJob() |
---|
| 998 | elif policy == "DENY" : |
---|
[1229] | 999 | # Either printer, user or user print quota doesn't exist, |
---|
| 1000 | # and the job should be rejected. |
---|
[1271] | 1001 | return self.removeJob() |
---|
| 1002 | else : |
---|
| 1003 | if policy not in ("OK", "ALLOW") : |
---|
[1584] | 1004 | self.printInfo(_("Invalid policy %s for printer %s") % (policy, self.printername)) |
---|
[1271] | 1005 | return self.removeJob() |
---|
| 1006 | else : |
---|
| 1007 | return self.doWork(policy, printer, user, userpquota) |
---|