[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 |
---|
[1469] | 33 | import socket |
---|
[2783] | 34 | import time |
---|
[2643] | 35 | from email.MIMEText import MIMEText |
---|
| 36 | from email.Header import Header |
---|
[3013] | 37 | import email.Utils |
---|
[695] | 38 | |
---|
[708] | 39 | from mx import DateTime |
---|
| 40 | |
---|
[3006] | 41 | try : |
---|
| 42 | import chardet |
---|
| 43 | except ImportError : |
---|
| 44 | def detectCharset(text) : |
---|
| 45 | """Fakes a charset detection if the chardet module is not installed.""" |
---|
| 46 | return "ISO-8859-15" |
---|
| 47 | else : |
---|
| 48 | def detectCharset(text) : |
---|
| 49 | """Uses the chardet module to workaround CUPS lying to us.""" |
---|
| 50 | return chardet.detect(text)["encoding"] |
---|
| 51 | |
---|
[2830] | 52 | from pykota import config, storage, logger |
---|
[2344] | 53 | from pykota.version import __version__, __author__, __years__, __gplblurb__ |
---|
[695] | 54 | |
---|
[1795] | 55 | def N_(message) : |
---|
| 56 | """Fake translation marker for translatable strings extraction.""" |
---|
| 57 | return message |
---|
| 58 | |
---|
[695] | 59 | class PyKotaToolError(Exception): |
---|
[2512] | 60 | """An exception for PyKota related stuff.""" |
---|
[695] | 61 | def __init__(self, message = ""): |
---|
| 62 | self.message = message |
---|
| 63 | Exception.__init__(self, message) |
---|
| 64 | def __repr__(self): |
---|
| 65 | return self.message |
---|
| 66 | __str__ = __repr__ |
---|
| 67 | |
---|
[2512] | 68 | class PyKotaCommandLineError(PyKotaToolError) : |
---|
| 69 | """An exception for Pykota command line tools.""" |
---|
| 70 | pass |
---|
| 71 | |
---|
[2229] | 72 | def crashed(message="Bug in PyKota") : |
---|
[1546] | 73 | """Minimal crash method.""" |
---|
| 74 | import traceback |
---|
| 75 | lines = [] |
---|
| 76 | for line in traceback.format_exception(*sys.exc_info()) : |
---|
| 77 | lines.extend([l for l in line.split("\n") if l]) |
---|
[2344] | 78 | msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % __version__, message] + lines)]) |
---|
[1546] | 79 | sys.stderr.write(msg) |
---|
| 80 | sys.stderr.flush() |
---|
| 81 | return msg |
---|
| 82 | |
---|
[2782] | 83 | class Percent : |
---|
| 84 | """A class to display progress.""" |
---|
[2783] | 85 | def __init__(self, app, size=None) : |
---|
[2782] | 86 | """Initializes the engine.""" |
---|
| 87 | self.app = app |
---|
[2783] | 88 | self.size = None |
---|
| 89 | if size : |
---|
| 90 | self.setSize(size) |
---|
| 91 | self.previous = None |
---|
| 92 | self.before = time.time() |
---|
| 93 | |
---|
| 94 | def setSize(self, size) : |
---|
| 95 | """Sets the total size.""" |
---|
| 96 | self.number = 0 |
---|
[2782] | 97 | self.size = size |
---|
[2793] | 98 | if size : |
---|
| 99 | self.factor = 100.0 / float(size) |
---|
[2782] | 100 | |
---|
| 101 | def display(self, msg) : |
---|
| 102 | """Displays the value.""" |
---|
| 103 | self.app.display(msg) |
---|
| 104 | |
---|
| 105 | def oneMore(self) : |
---|
| 106 | """Increments internal counter.""" |
---|
[2783] | 107 | if self.size : |
---|
| 108 | self.number += 1 |
---|
| 109 | percent = "%.02f" % (float(self.number) * self.factor) |
---|
| 110 | if percent != self.previous : # optimize for large number of items |
---|
| 111 | self.display("\r%s%%" % percent) |
---|
| 112 | self.previous = percent |
---|
[2782] | 113 | |
---|
| 114 | def done(self) : |
---|
| 115 | """Displays the 'done' message.""" |
---|
[2783] | 116 | after = time.time() |
---|
| 117 | if self.size : |
---|
[2788] | 118 | speed = self.size / (after - self.before) |
---|
| 119 | self.display("\r100.00%%\r \r%s. %s : %.2f %s.\n" \ |
---|
[2783] | 120 | % (_("Done"), _("Average speed"), speed, _("entries per second"))) |
---|
| 121 | else : |
---|
| 122 | self.display("\r100.00%%\r \r%s.\n" % _("Done")) |
---|
[2782] | 123 | |
---|
[1911] | 124 | class Tool : |
---|
| 125 | """Base class for tools with no database access.""" |
---|
[2344] | 126 | def __init__(self, lang="", charset=None, doc="PyKota v%(__version__)s (c) %(__years__)s %(__author__)s") : |
---|
[695] | 127 | """Initializes the command line tool.""" |
---|
[2006] | 128 | # did we drop priviledges ? |
---|
| 129 | self.privdropped = 0 |
---|
| 130 | |
---|
[772] | 131 | # locale stuff |
---|
[788] | 132 | try : |
---|
[3055] | 133 | locale.setlocale(locale.LC_ALL, (lang, charset)) |
---|
[788] | 134 | except (locale.Error, IOError) : |
---|
[3055] | 135 | locale.setlocale(locale.LC_ALL, None) |
---|
| 136 | (self.language, self.charset) = locale.getlocale() |
---|
| 137 | self.language = self.language or "C" |
---|
| 138 | self.charset = self.charset or locale.getpreferredencoding() |
---|
| 139 | |
---|
| 140 | # translation stuff |
---|
[1898] | 141 | try : |
---|
[3055] | 142 | try : |
---|
| 143 | trans = gettext.translation("pykota", languages=["%s.%s" % (self.language, self.charset)], codeset=self.charset) |
---|
| 144 | except TypeError : # Python <2.4 |
---|
| 145 | trans = gettext.translation("pykota", languages=["%s.%s" % (self.language, self.charset)]) |
---|
| 146 | trans.install() |
---|
[1898] | 147 | except : |
---|
[788] | 148 | gettext.NullTranslations().install() |
---|
[772] | 149 | |
---|
| 150 | # pykota specific stuff |
---|
[715] | 151 | self.documentation = doc |
---|
[1960] | 152 | |
---|
[2210] | 153 | def deferredInit(self) : |
---|
| 154 | """Deferred initialization.""" |
---|
[3045] | 155 | confdir = os.environ.get("PYKOTA_HOME") |
---|
| 156 | environHome = True |
---|
| 157 | missingUser = False |
---|
| 158 | if confdir is None : |
---|
| 159 | environHome = False |
---|
| 160 | # check for config files in the 'pykota' user's home directory. |
---|
| 161 | try : |
---|
| 162 | self.pykotauser = pwd.getpwnam("pykota") |
---|
| 163 | confdir = self.pykotauser[5] |
---|
| 164 | except KeyError : |
---|
| 165 | self.pykotauser = None |
---|
| 166 | confdir = "/etc/pykota" |
---|
| 167 | missingUser = True |
---|
[1960] | 168 | |
---|
[2210] | 169 | self.config = config.PyKotaConfig(confdir) |
---|
| 170 | self.debug = self.config.getDebug() |
---|
| 171 | self.smtpserver = self.config.getSMTPServer() |
---|
| 172 | self.maildomain = self.config.getMailDomain() |
---|
| 173 | self.logger = logger.openLogger(self.config.getLoggingBackend()) |
---|
[1542] | 174 | |
---|
[2006] | 175 | # now drop priviledge if possible |
---|
| 176 | self.dropPriv() |
---|
| 177 | |
---|
[1960] | 178 | # We NEED this here, even when not in an accounting filter/backend |
---|
[1497] | 179 | self.softwareJobSize = 0 |
---|
[1495] | 180 | self.softwareJobPrice = 0.0 |
---|
[1960] | 181 | |
---|
[3045] | 182 | if environHome : |
---|
| 183 | self.printInfo("PYKOTA_HOME environment variable is set. Configuration files were searched in %s" % confdir, "info") |
---|
| 184 | else : |
---|
| 185 | if missingUser : |
---|
| 186 | self.printInfo("The 'pykota' system account is missing. Configuration files were searched in %s instead." % confdir, "warn") |
---|
[1960] | 187 | |
---|
[3055] | 188 | self.logdebug("Language in use : %s" % self.language) |
---|
[1761] | 189 | self.logdebug("Charset in use : %s" % self.charset) |
---|
[3055] | 190 | |
---|
[1872] | 191 | arguments = " ".join(['"%s"' % arg for arg in sys.argv]) |
---|
| 192 | self.logdebug("Command line arguments : %s" % arguments) |
---|
[695] | 193 | |
---|
[2006] | 194 | def dropPriv(self) : |
---|
| 195 | """Drops priviledges.""" |
---|
| 196 | uid = os.geteuid() |
---|
[2889] | 197 | try : |
---|
| 198 | self.originalUserName = pwd.getpwuid(uid)[0] |
---|
| 199 | except (KeyError, IndexError), msg : |
---|
| 200 | self.printInfo(_("Strange problem with uid(%s) : %s") % (uid, msg), "warn") |
---|
| 201 | self.originalUserName = None |
---|
| 202 | else : |
---|
| 203 | if uid : |
---|
| 204 | self.logdebug(_("Running as user '%s'.") % self.originalUserName) |
---|
[2006] | 205 | else : |
---|
[2889] | 206 | if self.pykotauser is None : |
---|
| 207 | self.logdebug(_("No user named 'pykota'. Not dropping priviledges.")) |
---|
[2006] | 208 | else : |
---|
[2889] | 209 | try : |
---|
| 210 | os.setegid(self.pykotauser[3]) |
---|
| 211 | os.seteuid(self.pykotauser[2]) |
---|
| 212 | except OSError, msg : |
---|
| 213 | self.printInfo(_("Impossible to drop priviledges : %s") % msg, "warn") |
---|
| 214 | else : |
---|
| 215 | self.logdebug(_("Priviledges dropped. Now running as user 'pykota'.")) |
---|
| 216 | self.privdropped = 1 |
---|
[2006] | 217 | |
---|
| 218 | def regainPriv(self) : |
---|
| 219 | """Drops priviledges.""" |
---|
| 220 | if self.privdropped : |
---|
| 221 | try : |
---|
| 222 | os.seteuid(0) |
---|
| 223 | os.setegid(0) |
---|
| 224 | except OSError, msg : |
---|
| 225 | self.printInfo(_("Impossible to regain priviledges : %s") % msg, "warn") |
---|
| 226 | else : |
---|
[2008] | 227 | self.logdebug(_("Regained priviledges. Now running as root.")) |
---|
[2006] | 228 | self.privdropped = 0 |
---|
| 229 | |
---|
[2804] | 230 | def UTF8ToUserCharset(self, text) : |
---|
| 231 | """Converts from UTF-8 to user's charset.""" |
---|
[3006] | 232 | if text is None : |
---|
| 233 | return None |
---|
| 234 | try : |
---|
| 235 | return text.decode("UTF-8").encode(self.charset, "replace") |
---|
| 236 | except (UnicodeError, AttributeError) : |
---|
[2804] | 237 | try : |
---|
[3006] | 238 | # Maybe already in Unicode ? |
---|
| 239 | return text.encode(self.charset, "replace") |
---|
| 240 | except (UnicodeError, AttributeError) : |
---|
| 241 | # Try to autodetect the charset |
---|
| 242 | return text.decode(detectCharset(text), "replace").encode(self.charset, "replace") |
---|
[2804] | 243 | |
---|
| 244 | def userCharsetToUTF8(self, text) : |
---|
| 245 | """Converts from user's charset to UTF-8.""" |
---|
[3006] | 246 | if text is None : |
---|
| 247 | return None |
---|
| 248 | try : |
---|
| 249 | # We don't necessarily trust the default charset, because |
---|
| 250 | # xprint sends us titles in UTF-8 but CUPS gives us an ISO-8859-1 charset ! |
---|
| 251 | # So we first try to see if the text is already in UTF-8 or not, and |
---|
| 252 | # if it is, we delete characters which can't be converted to the user's charset, |
---|
| 253 | # then convert back to UTF-8. PostgreSQL 7.3.x used to reject some unicode characters, |
---|
| 254 | # this is fixed by the ugly line below : |
---|
| 255 | return text.decode("UTF-8").encode(self.charset, "replace").decode(self.charset).encode("UTF-8", "replace") |
---|
| 256 | except (UnicodeError, AttributeError) : |
---|
[2804] | 257 | try : |
---|
[3006] | 258 | return text.decode(self.charset).encode("UTF-8", "replace") |
---|
| 259 | except (UnicodeError, AttributeError) : |
---|
[2804] | 260 | try : |
---|
[3006] | 261 | # Maybe already in Unicode ? |
---|
| 262 | return text.encode("UTF-8", "replace") |
---|
| 263 | except (UnicodeError, AttributeError) : |
---|
| 264 | # Try to autodetect the charset |
---|
| 265 | return text.decode(detectCharset(text), "replace").encode("UTF-8", "replace") |
---|
| 266 | return newtext |
---|
[2804] | 267 | |
---|
[2657] | 268 | def display(self, message) : |
---|
| 269 | """Display a message but only if stdout is a tty.""" |
---|
| 270 | if sys.stdout.isatty() : |
---|
| 271 | sys.stdout.write(message) |
---|
| 272 | sys.stdout.flush() |
---|
| 273 | |
---|
[1130] | 274 | def logdebug(self, message) : |
---|
| 275 | """Logs something to debug output if debug is enabled.""" |
---|
| 276 | if self.debug : |
---|
| 277 | self.logger.log_message(message, "debug") |
---|
[1582] | 278 | |
---|
[1584] | 279 | def printInfo(self, message, level="info") : |
---|
[1582] | 280 | """Sends a message to standard error.""" |
---|
[1584] | 281 | sys.stderr.write("%s: %s\n" % (level.upper(), message)) |
---|
[1582] | 282 | sys.stderr.flush() |
---|
[1130] | 283 | |
---|
[2210] | 284 | def matchString(self, s, patterns) : |
---|
[2650] | 285 | """Returns True if the string s matches one of the patterns, else False.""" |
---|
| 286 | if not patterns : |
---|
| 287 | return True # No pattern, always matches. |
---|
| 288 | else : |
---|
| 289 | for pattern in patterns : |
---|
| 290 | if fnmatch.fnmatchcase(s, pattern) : |
---|
| 291 | return True |
---|
| 292 | return False |
---|
[2210] | 293 | |
---|
[2762] | 294 | def sanitizeNames(self, options, names) : |
---|
| 295 | """Ensures that an user can only see the datas he is allowed to see, by modifying the list of names.""" |
---|
| 296 | if not self.config.isAdmin : |
---|
| 297 | username = pwd.getpwuid(os.geteuid())[0] |
---|
| 298 | if not options["list"] : |
---|
| 299 | raise PyKotaCommandLineError, "%s : %s" % (username, _("You're not allowed to use this command.")) |
---|
| 300 | else : |
---|
| 301 | if options["groups"] : |
---|
| 302 | user = self.storage.getUser(username) |
---|
| 303 | if user.Exists : |
---|
| 304 | return [ g.Name for g in self.storage.getUserGroups(user) ] |
---|
| 305 | return [ username ] |
---|
| 306 | elif not names : |
---|
| 307 | return ["*"] |
---|
| 308 | else : |
---|
| 309 | return names |
---|
| 310 | |
---|
[715] | 311 | def display_version_and_quit(self) : |
---|
| 312 | """Displays version number, then exists successfully.""" |
---|
[1923] | 313 | try : |
---|
| 314 | self.clean() |
---|
| 315 | except AttributeError : |
---|
| 316 | pass |
---|
[2344] | 317 | print __version__ |
---|
[715] | 318 | sys.exit(0) |
---|
| 319 | |
---|
| 320 | def display_usage_and_quit(self) : |
---|
| 321 | """Displays command line usage, then exists successfully.""" |
---|
[1923] | 322 | try : |
---|
| 323 | self.clean() |
---|
| 324 | except AttributeError : |
---|
| 325 | pass |
---|
[2344] | 326 | print _(self.documentation) % globals() |
---|
| 327 | print __gplblurb__ |
---|
| 328 | print |
---|
| 329 | print _("Please report bugs to :"), __author__ |
---|
[715] | 330 | sys.exit(0) |
---|
| 331 | |
---|
[2229] | 332 | def crashed(self, message="Bug in PyKota") : |
---|
[1517] | 333 | """Outputs a crash message, and optionally sends it to software author.""" |
---|
[1546] | 334 | msg = crashed(message) |
---|
[2229] | 335 | fullmessage = "========== Traceback :\n\n%s\n\n========== sys.argv :\n\n%s\n\n========== Environment :\n\n%s\n" % \ |
---|
| 336 | (msg, \ |
---|
| 337 | "\n".join([" %s" % repr(a) for a in sys.argv]), \ |
---|
| 338 | "\n".join([" %s=%s" % (k, v) for (k, v) in os.environ.items()])) |
---|
[1541] | 339 | try : |
---|
| 340 | crashrecipient = self.config.getCrashRecipient() |
---|
| 341 | if crashrecipient : |
---|
[1517] | 342 | admin = self.config.getAdminMail("global") # Nice trick, isn't it ? |
---|
| 343 | server = smtplib.SMTP(self.smtpserver) |
---|
[2795] | 344 | msg = MIMEText(fullmessage, _charset=self.charset) |
---|
| 345 | msg["Subject"] = str(Header("PyKota v%s crash traceback !" \ |
---|
| 346 | % __version__, charset=self.charset)) |
---|
| 347 | msg["From"] = admin |
---|
| 348 | msg["To"] = crashrecipient |
---|
| 349 | msg["Cc"] = admin |
---|
[3013] | 350 | msg["Date"] = email.Utils.formatdate(localtime=True) |
---|
[2795] | 351 | server.sendmail(admin, [admin, crashrecipient], msg.as_string()) |
---|
[1517] | 352 | server.quit() |
---|
[1541] | 353 | except : |
---|
| 354 | pass |
---|
[2229] | 355 | return fullmessage |
---|
[1517] | 356 | |
---|
[729] | 357 | def parseCommandline(self, argv, short, long, allownothing=0) : |
---|
[715] | 358 | """Parses the command line, controlling options.""" |
---|
| 359 | # split options in two lists: those which need an argument, those which don't need any |
---|
[2605] | 360 | short = "%sA:" % short |
---|
| 361 | long.append("arguments=") |
---|
[715] | 362 | withoutarg = [] |
---|
| 363 | witharg = [] |
---|
| 364 | lgs = len(short) |
---|
| 365 | i = 0 |
---|
| 366 | while i < lgs : |
---|
| 367 | ii = i + 1 |
---|
| 368 | if (ii < lgs) and (short[ii] == ':') : |
---|
| 369 | # needs an argument |
---|
| 370 | witharg.append(short[i]) |
---|
| 371 | ii = ii + 1 # skip the ':' |
---|
| 372 | else : |
---|
| 373 | # doesn't need an argument |
---|
| 374 | withoutarg.append(short[i]) |
---|
| 375 | i = ii |
---|
| 376 | |
---|
| 377 | for option in long : |
---|
| 378 | if option[-1] == '=' : |
---|
| 379 | # needs an argument |
---|
| 380 | witharg.append(option[:-1]) |
---|
| 381 | else : |
---|
| 382 | # doesn't need an argument |
---|
| 383 | withoutarg.append(option) |
---|
| 384 | |
---|
| 385 | # then we parse the command line |
---|
[2605] | 386 | done = 0 |
---|
| 387 | while not done : |
---|
| 388 | # we begin with all possible options unset |
---|
| 389 | parsed = {} |
---|
| 390 | for option in withoutarg + witharg : |
---|
| 391 | parsed[option] = None |
---|
| 392 | args = [] # to not break if something unexpected happened |
---|
| 393 | try : |
---|
| 394 | options, args = getopt.getopt(argv, short, long) |
---|
| 395 | if options : |
---|
| 396 | for (o, v) in options : |
---|
| 397 | # we skip the '-' chars |
---|
| 398 | lgo = len(o) |
---|
| 399 | i = 0 |
---|
| 400 | while (i < lgo) and (o[i] == '-') : |
---|
| 401 | i = i + 1 |
---|
| 402 | o = o[i:] |
---|
| 403 | if o in witharg : |
---|
| 404 | # needs an argument : set it |
---|
| 405 | parsed[o] = v |
---|
| 406 | elif o in withoutarg : |
---|
| 407 | # doesn't need an argument : boolean |
---|
| 408 | parsed[o] = 1 |
---|
| 409 | else : |
---|
| 410 | # should never occur |
---|
[2610] | 411 | raise PyKotaCommandLineError, "Unexpected problem when parsing command line" |
---|
[2605] | 412 | elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty |
---|
| 413 | self.display_usage_and_quit() |
---|
| 414 | except getopt.error, msg : |
---|
[2610] | 415 | raise PyKotaCommandLineError, str(msg) |
---|
[2605] | 416 | else : |
---|
| 417 | if parsed["arguments"] or parsed["A"] : |
---|
| 418 | # arguments are in a file, we ignore all other arguments |
---|
| 419 | # and reset the list of arguments to the lines read from |
---|
| 420 | # the file. |
---|
| 421 | argsfile = open(parsed["arguments"] or parsed["A"], "r") |
---|
| 422 | argv = [ l.strip() for l in argsfile.readlines() ] |
---|
| 423 | argsfile.close() |
---|
| 424 | for i in range(len(argv)) : |
---|
| 425 | argi = argv[i] |
---|
| 426 | if argi.startswith('"') and argi.endswith('"') : |
---|
| 427 | argv[i] = argi[1:-1] |
---|
| 428 | else : |
---|
| 429 | done = 1 |
---|
[715] | 430 | return (parsed, args) |
---|
| 431 | |
---|
[1911] | 432 | class PyKotaTool(Tool) : |
---|
| 433 | """Base class for all PyKota command line tools.""" |
---|
[2344] | 434 | def __init__(self, lang="", charset=None, doc="PyKota v%(__version__)s (c) %(__years__)s %(__author__)s") : |
---|
[1911] | 435 | """Initializes the command line tool and opens the database.""" |
---|
| 436 | Tool.__init__(self, lang, charset, doc) |
---|
[2210] | 437 | |
---|
| 438 | def deferredInit(self) : |
---|
| 439 | """Deferred initialization.""" |
---|
| 440 | Tool.deferredInit(self) |
---|
| 441 | self.storage = storage.openConnection(self) |
---|
| 442 | if self.config.isAdmin : # TODO : We don't know this before, fix this ! |
---|
| 443 | self.logdebug("Beware : running as a PyKota administrator !") |
---|
[2093] | 444 | else : |
---|
[2210] | 445 | self.logdebug("Don't Panic : running as a mere mortal !") |
---|
[1911] | 446 | |
---|
| 447 | def clean(self) : |
---|
| 448 | """Ensures that the database is closed.""" |
---|
| 449 | try : |
---|
| 450 | self.storage.close() |
---|
| 451 | except (TypeError, NameError, AttributeError) : |
---|
| 452 | pass |
---|
| 453 | |
---|
[764] | 454 | def isValidName(self, name) : |
---|
| 455 | """Checks if a user or printer name is valid.""" |
---|
[1725] | 456 | invalidchars = "/@?*,;&|" |
---|
[1637] | 457 | for c in list(invalidchars) : |
---|
[1593] | 458 | if c in name : |
---|
[1394] | 459 | return 0 |
---|
| 460 | return 1 |
---|
[764] | 461 | |
---|
[802] | 462 | def sendMessage(self, adminmail, touser, fullmessage) : |
---|
[695] | 463 | """Sends an email message containing headers to some user.""" |
---|
[1469] | 464 | try : |
---|
| 465 | server = smtplib.SMTP(self.smtpserver) |
---|
| 466 | except socket.error, msg : |
---|
[1584] | 467 | self.printInfo(_("Impossible to connect to SMTP server : %s") % msg, "error") |
---|
[1469] | 468 | else : |
---|
| 469 | try : |
---|
[2795] | 470 | server.sendmail(adminmail, [touser], fullmessage) |
---|
[1469] | 471 | except smtplib.SMTPException, answer : |
---|
| 472 | for (k, v) in answer.recipients.items() : |
---|
[1584] | 473 | self.printInfo(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error") |
---|
[1469] | 474 | server.quit() |
---|
[695] | 475 | |
---|
[1079] | 476 | def sendMessageToUser(self, admin, adminmail, user, subject, message) : |
---|
[695] | 477 | """Sends an email message to a user.""" |
---|
[802] | 478 | message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail) |
---|
[2795] | 479 | usermail = user.Email or user.Name |
---|
| 480 | if "@" not in usermail : |
---|
| 481 | usermail = "%s@%s" % (usermail, self.maildomain or self.smtpserver or "localhost") |
---|
| 482 | msg = MIMEText(message, _charset=self.charset) |
---|
| 483 | msg["Subject"] = str(Header(subject, charset=self.charset)) |
---|
| 484 | msg["From"] = adminmail |
---|
| 485 | msg["To"] = usermail |
---|
[3013] | 486 | msg["Date"] = email.Utils.formatdate(localtime=True) |
---|
[2795] | 487 | self.sendMessage(adminmail, usermail, msg.as_string()) |
---|
[695] | 488 | |
---|
[802] | 489 | def sendMessageToAdmin(self, adminmail, subject, message) : |
---|
[695] | 490 | """Sends an email message to the Print Quota administrator.""" |
---|
[2795] | 491 | if "@" not in adminmail : |
---|
| 492 | adminmail = "%s@%s" % (adminmail, self.maildomain or self.smtpserver or "localhost") |
---|
| 493 | msg = MIMEText(message, _charset=self.charset) |
---|
| 494 | msg["Subject"] = str(Header(subject, charset=self.charset)) |
---|
| 495 | msg["From"] = adminmail |
---|
| 496 | msg["To"] = adminmail |
---|
| 497 | self.sendMessage(adminmail, adminmail, msg.as_string()) |
---|
[695] | 498 | |
---|
[1365] | 499 | def _checkUserPQuota(self, userpquota) : |
---|
| 500 | """Checks the user quota on a printer and deny or accept the job.""" |
---|
| 501 | # then we check the user's own quota |
---|
| 502 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 503 | user = userpquota.User |
---|
| 504 | printer = userpquota.Printer |
---|
[1495] | 505 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 506 | self.logdebug("Checking user %s's quota on printer %s" % (user.Name, printer.Name)) |
---|
| 507 | (policy, dummy) = self.config.getPrinterPolicy(userpquota.Printer.Name) |
---|
| 508 | if not userpquota.Exists : |
---|
| 509 | # Unknown userquota |
---|
| 510 | if policy == "ALLOW" : |
---|
| 511 | action = "POLICY_ALLOW" |
---|
| 512 | else : |
---|
| 513 | action = "POLICY_DENY" |
---|
[1584] | 514 | self.printInfo(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action)) |
---|
[1365] | 515 | else : |
---|
| 516 | pagecounter = int(userpquota.PageCounter or 0) |
---|
[1495] | 517 | if enforcement == "STRICT" : |
---|
| 518 | pagecounter += self.softwareJobSize |
---|
[1365] | 519 | if userpquota.SoftLimit is not None : |
---|
| 520 | softlimit = int(userpquota.SoftLimit) |
---|
| 521 | if pagecounter < softlimit : |
---|
| 522 | action = "ALLOW" |
---|
| 523 | else : |
---|
| 524 | if userpquota.HardLimit is None : |
---|
| 525 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 526 | action = "DENY" |
---|
| 527 | else : |
---|
| 528 | hardlimit = int(userpquota.HardLimit) |
---|
| 529 | if softlimit <= pagecounter < hardlimit : |
---|
| 530 | now = DateTime.now() |
---|
| 531 | if userpquota.DateLimit is not None : |
---|
[3050] | 532 | datelimit = DateTime.ISO.ParseDateTime(str(userpquota.DateLimit)[:19]) |
---|
[1365] | 533 | else : |
---|
| 534 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 535 | userpquota.setDateLimit(datelimit) |
---|
| 536 | if now < datelimit : |
---|
| 537 | action = "WARN" |
---|
| 538 | else : |
---|
| 539 | action = "DENY" |
---|
| 540 | else : |
---|
| 541 | action = "DENY" |
---|
| 542 | else : |
---|
| 543 | if userpquota.HardLimit is not None : |
---|
| 544 | # no soft limit, only a hard one. |
---|
| 545 | hardlimit = int(userpquota.HardLimit) |
---|
| 546 | if pagecounter < hardlimit : |
---|
| 547 | action = "ALLOW" |
---|
| 548 | else : |
---|
| 549 | action = "DENY" |
---|
| 550 | else : |
---|
| 551 | # Both are unset, no quota, i.e. accounting only |
---|
| 552 | action = "ALLOW" |
---|
| 553 | return action |
---|
| 554 | |
---|
[1041] | 555 | def checkGroupPQuota(self, grouppquota) : |
---|
[927] | 556 | """Checks the group quota on a printer and deny or accept the job.""" |
---|
[1041] | 557 | group = grouppquota.Group |
---|
| 558 | printer = grouppquota.Printer |
---|
[1495] | 559 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 560 | self.logdebug("Checking group %s's quota on printer %s" % (group.Name, printer.Name)) |
---|
[1061] | 561 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
[1666] | 562 | val = group.AccountBalance or 0.0 |
---|
[1495] | 563 | if enforcement == "STRICT" : |
---|
| 564 | val -= self.softwareJobPrice # use precomputed size. |
---|
[2692] | 565 | balancezero = self.config.getBalanceZero() |
---|
| 566 | if val <= balancezero : |
---|
[1041] | 567 | action = "DENY" |
---|
[1495] | 568 | elif val <= self.config.getPoorMan() : |
---|
[1077] | 569 | action = "WARN" |
---|
[927] | 570 | else : |
---|
[1041] | 571 | action = "ALLOW" |
---|
[2692] | 572 | if (enforcement == "STRICT") and (val == balancezero) : |
---|
[1529] | 573 | action = "WARN" # we can still print until account is 0 |
---|
[927] | 574 | else : |
---|
[1665] | 575 | val = grouppquota.PageCounter or 0 |
---|
[1495] | 576 | if enforcement == "STRICT" : |
---|
[2992] | 577 | val += int(self.softwareJobSize) # TODO : this is not a fix, problem is elsewhere in grouppquota.PageCounter |
---|
[1041] | 578 | if grouppquota.SoftLimit is not None : |
---|
| 579 | softlimit = int(grouppquota.SoftLimit) |
---|
[1495] | 580 | if val < softlimit : |
---|
[1041] | 581 | action = "ALLOW" |
---|
[927] | 582 | else : |
---|
[1041] | 583 | if grouppquota.HardLimit is None : |
---|
| 584 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 585 | action = "DENY" |
---|
[927] | 586 | else : |
---|
[1041] | 587 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 588 | if softlimit <= val < hardlimit : |
---|
[1041] | 589 | now = DateTime.now() |
---|
| 590 | if grouppquota.DateLimit is not None : |
---|
[3050] | 591 | datelimit = DateTime.ISO.ParseDateTime(str(grouppquota.DateLimit)[:19]) |
---|
[1041] | 592 | else : |
---|
| 593 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 594 | grouppquota.setDateLimit(datelimit) |
---|
| 595 | if now < datelimit : |
---|
| 596 | action = "WARN" |
---|
| 597 | else : |
---|
[927] | 598 | action = "DENY" |
---|
[1041] | 599 | else : |
---|
[927] | 600 | action = "DENY" |
---|
[1041] | 601 | else : |
---|
| 602 | if grouppquota.HardLimit is not None : |
---|
| 603 | # no soft limit, only a hard one. |
---|
| 604 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 605 | if val < hardlimit : |
---|
[927] | 606 | action = "ALLOW" |
---|
[1041] | 607 | else : |
---|
| 608 | action = "DENY" |
---|
| 609 | else : |
---|
| 610 | # Both are unset, no quota, i.e. accounting only |
---|
| 611 | action = "ALLOW" |
---|
[927] | 612 | return action |
---|
| 613 | |
---|
[1041] | 614 | def checkUserPQuota(self, userpquota) : |
---|
[1365] | 615 | """Checks the user quota on a printer and all its parents and deny or accept the job.""" |
---|
[1041] | 616 | user = userpquota.User |
---|
| 617 | printer = userpquota.Printer |
---|
| 618 | |
---|
[1365] | 619 | # indicates that a warning needs to be sent |
---|
| 620 | warned = 0 |
---|
| 621 | |
---|
[927] | 622 | # first we check any group the user is a member of |
---|
[1041] | 623 | for group in self.storage.getUserGroups(user) : |
---|
[2452] | 624 | # No need to check anything if the group is in noquota mode |
---|
| 625 | if group.LimitBy != "noquota" : |
---|
| 626 | grouppquota = self.storage.getGroupPQuota(group, printer) |
---|
| 627 | # for the printer and all its parents |
---|
| 628 | for gpquota in [ grouppquota ] + grouppquota.ParentPrintersGroupPQuota : |
---|
| 629 | if gpquota.Exists : |
---|
| 630 | action = self.checkGroupPQuota(gpquota) |
---|
| 631 | if action == "DENY" : |
---|
| 632 | return action |
---|
| 633 | elif action == "WARN" : |
---|
| 634 | warned = 1 |
---|
[1365] | 635 | |
---|
| 636 | # Then we check the user's account balance |
---|
[1152] | 637 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 638 | (policy, dummy) = self.config.getPrinterPolicy(printer.Name) |
---|
[1061] | 639 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
[1365] | 640 | self.logdebug("Checking account balance for user %s" % user.Name) |
---|
[1041] | 641 | if user.AccountBalance is None : |
---|
[956] | 642 | if policy == "ALLOW" : |
---|
[925] | 643 | action = "POLICY_ALLOW" |
---|
| 644 | else : |
---|
| 645 | action = "POLICY_DENY" |
---|
[1584] | 646 | self.printInfo(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name)) |
---|
[1365] | 647 | return action |
---|
[713] | 648 | else : |
---|
[2054] | 649 | if user.OverCharge == 0.0 : |
---|
| 650 | self.printInfo(_("User %s will not be charged for printing.") % user.Name) |
---|
| 651 | action = "ALLOW" |
---|
[1529] | 652 | else : |
---|
[2054] | 653 | val = float(user.AccountBalance or 0.0) |
---|
| 654 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
| 655 | if enforcement == "STRICT" : |
---|
| 656 | val -= self.softwareJobPrice # use precomputed size. |
---|
[2692] | 657 | balancezero = self.config.getBalanceZero() |
---|
| 658 | if val <= balancezero : |
---|
[2054] | 659 | action = "DENY" |
---|
| 660 | elif val <= self.config.getPoorMan() : |
---|
| 661 | action = "WARN" |
---|
| 662 | else : |
---|
| 663 | action = "ALLOW" |
---|
[2692] | 664 | if (enforcement == "STRICT") and (val == balancezero) : |
---|
[2054] | 665 | action = "WARN" # we can still print until account is 0 |
---|
[1529] | 666 | return action |
---|
[925] | 667 | else : |
---|
[1365] | 668 | # Then check the user quota on current printer and all its parents. |
---|
| 669 | policyallowed = 0 |
---|
| 670 | for upquota in [ userpquota ] + userpquota.ParentPrintersUserPQuota : |
---|
| 671 | action = self._checkUserPQuota(upquota) |
---|
| 672 | if action in ("DENY", "POLICY_DENY") : |
---|
| 673 | return action |
---|
| 674 | elif action == "WARN" : |
---|
| 675 | warned = 1 |
---|
| 676 | elif action == "POLICY_ALLOW" : |
---|
| 677 | policyallowed = 1 |
---|
| 678 | if warned : |
---|
| 679 | return "WARN" |
---|
| 680 | elif policyallowed : |
---|
| 681 | return "POLICY_ALLOW" |
---|
[925] | 682 | else : |
---|
[1365] | 683 | return "ALLOW" |
---|
| 684 | |
---|
[1196] | 685 | def externalMailTo(self, cmd, action, user, printer, message) : |
---|
[1192] | 686 | """Warns the user with an external command.""" |
---|
| 687 | username = user.Name |
---|
[1196] | 688 | printername = printer.Name |
---|
[1192] | 689 | email = user.Email or user.Name |
---|
| 690 | if "@" not in email : |
---|
[1353] | 691 | email = "%s@%s" % (email, self.maildomain or self.smtpserver) |
---|
[1192] | 692 | os.system(cmd % locals()) |
---|
| 693 | |
---|
[1196] | 694 | def formatCommandLine(self, cmd, user, printer) : |
---|
| 695 | """Executes an external command.""" |
---|
| 696 | username = user.Name |
---|
| 697 | printername = printer.Name |
---|
| 698 | return cmd % locals() |
---|
| 699 | |
---|
[1041] | 700 | def warnGroupPQuota(self, grouppquota) : |
---|
[927] | 701 | """Checks a group quota and send messages if quota is exceeded on current printer.""" |
---|
[1041] | 702 | group = grouppquota.Group |
---|
| 703 | printer = grouppquota.Printer |
---|
| 704 | admin = self.config.getAdmin(printer.Name) |
---|
| 705 | adminmail = self.config.getAdminMail(printer.Name) |
---|
[1192] | 706 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[2547] | 707 | if group.LimitBy in ("noquota", "nochange") : |
---|
| 708 | action = "ALLOW" |
---|
| 709 | else : |
---|
| 710 | action = self.checkGroupPQuota(grouppquota) |
---|
| 711 | if action.startswith("POLICY_") : |
---|
| 712 | action = action[7:] |
---|
| 713 | if action == "DENY" : |
---|
| 714 | adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name) |
---|
| 715 | self.printInfo(adminmessage) |
---|
| 716 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 717 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 718 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 719 | for user in self.storage.getGroupMembers(group) : |
---|
| 720 | if mailto != "EXTERNAL" : |
---|
| 721 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name)) |
---|
| 722 | else : |
---|
| 723 | self.externalMailTo(arguments, action, user, printer, self.config.getHardWarn(printer.Name)) |
---|
| 724 | elif action == "WARN" : |
---|
| 725 | adminmessage = _("Print Quota low for group %s on printer %s") % (group.Name, printer.Name) |
---|
| 726 | self.printInfo(adminmessage) |
---|
| 727 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 728 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 729 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
| 730 | message = self.config.getPoorWarn() |
---|
| 731 | else : |
---|
| 732 | message = self.config.getSoftWarn(printer.Name) |
---|
| 733 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 734 | for user in self.storage.getGroupMembers(group) : |
---|
| 735 | if mailto != "EXTERNAL" : |
---|
| 736 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 737 | else : |
---|
| 738 | self.externalMailTo(arguments, action, user, printer, message) |
---|
[927] | 739 | return action |
---|
[728] | 740 | |
---|
[1041] | 741 | def warnUserPQuota(self, userpquota) : |
---|
[728] | 742 | """Checks a user quota and send him a message if quota is exceeded on current printer.""" |
---|
[1041] | 743 | user = userpquota.User |
---|
[1245] | 744 | printer = userpquota.Printer |
---|
| 745 | admin = self.config.getAdmin(printer.Name) |
---|
| 746 | adminmail = self.config.getAdminMail(printer.Name) |
---|
| 747 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[2547] | 748 | |
---|
| 749 | if user.LimitBy in ("noquota", "nochange") : |
---|
| 750 | action = "ALLOW" |
---|
| 751 | elif user.LimitBy == "noprint" : |
---|
| 752 | action = "DENY" |
---|
[2558] | 753 | message = _("User %s is not allowed to print at this time.") % user.Name |
---|
| 754 | self.printInfo(message) |
---|
[1245] | 755 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 756 | if mailto != "EXTERNAL" : |
---|
[2547] | 757 | self.sendMessageToUser(admin, adminmail, user, _("Printing denied."), message) |
---|
[1245] | 758 | else : |
---|
| 759 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 760 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
[2547] | 761 | self.sendMessageToAdmin(adminmail, _("Print Quota"), message) |
---|
| 762 | else : |
---|
| 763 | action = self.checkUserPQuota(userpquota) |
---|
| 764 | if action.startswith("POLICY_") : |
---|
| 765 | action = action[7:] |
---|
| 766 | |
---|
| 767 | if action == "DENY" : |
---|
| 768 | adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 769 | self.printInfo(adminmessage) |
---|
| 770 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 771 | message = self.config.getHardWarn(printer.Name) |
---|
| 772 | if mailto != "EXTERNAL" : |
---|
| 773 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 774 | else : |
---|
| 775 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 776 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 777 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 778 | elif action == "WARN" : |
---|
| 779 | adminmessage = _("Print Quota low for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 780 | self.printInfo(adminmessage) |
---|
| 781 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 782 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
| 783 | message = self.config.getPoorWarn() |
---|
| 784 | else : |
---|
| 785 | message = self.config.getSoftWarn(printer.Name) |
---|
| 786 | if mailto != "EXTERNAL" : |
---|
| 787 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message) |
---|
| 788 | else : |
---|
| 789 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 790 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 791 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1245] | 792 | return action |
---|
[1196] | 793 | |
---|