[565] | 1 | #! /usr/bin/env python |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
| 3 | |
---|
[576] | 4 | # Tea4CUPS : Tee for CUPS |
---|
[565] | 5 | # |
---|
| 6 | # (c) 2005 Jerome Alet <alet@librelogiciel.com> |
---|
| 7 | # This program is free software; you can redistribute it and/or modify |
---|
| 8 | # it under the terms of the GNU General Public License as published by |
---|
| 9 | # the Free Software Foundation; either version 2 of the License, or |
---|
| 10 | # (at your option) any later version. |
---|
| 11 | # |
---|
| 12 | # This program is distributed in the hope that it will be useful, |
---|
| 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
| 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
| 15 | # GNU General Public License for more details. |
---|
| 16 | # |
---|
| 17 | # You should have received a copy of the GNU General Public License |
---|
| 18 | # along with this program; if not, write to the Free Software |
---|
| 19 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. |
---|
| 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
| 23 | # |
---|
| 24 | |
---|
| 25 | import sys |
---|
| 26 | import os |
---|
[584] | 27 | import popen2 |
---|
[568] | 28 | import errno |
---|
[577] | 29 | import md5 |
---|
[565] | 30 | import cStringIO |
---|
| 31 | import shlex |
---|
[568] | 32 | import tempfile |
---|
[570] | 33 | import ConfigParser |
---|
[588] | 34 | import select |
---|
| 35 | import signal |
---|
| 36 | import time |
---|
[581] | 37 | from struct import unpack |
---|
[565] | 38 | |
---|
[615] | 39 | version = "2.10_unofficial" |
---|
[585] | 40 | |
---|
[570] | 41 | class TeeError(Exception): |
---|
[576] | 42 | """Base exception for Tea4CUPS related stuff.""" |
---|
[570] | 43 | def __init__(self, message = ""): |
---|
| 44 | self.message = message |
---|
| 45 | Exception.__init__(self, message) |
---|
| 46 | def __repr__(self): |
---|
| 47 | return self.message |
---|
| 48 | __str__ = __repr__ |
---|
| 49 | |
---|
| 50 | class ConfigError(TeeError) : |
---|
| 51 | """Configuration related exceptions.""" |
---|
| 52 | pass |
---|
| 53 | |
---|
[581] | 54 | class IPPError(TeeError) : |
---|
| 55 | """IPP related exceptions.""" |
---|
| 56 | pass |
---|
| 57 | |
---|
[584] | 58 | class Popen4ForCUPS(popen2.Popen4) : |
---|
| 59 | """Our own class to execute real backends. |
---|
| 60 | |
---|
| 61 | Their first argument is different from their path so using |
---|
| 62 | native popen2.Popen3 would not be feasible. |
---|
| 63 | """ |
---|
| 64 | def __init__(self, cmd, bufsize=-1, arg0=None) : |
---|
| 65 | self.arg0 = arg0 |
---|
| 66 | popen2.Popen4.__init__(self, cmd, bufsize) |
---|
| 67 | |
---|
| 68 | def _run_child(self, cmd): |
---|
| 69 | try : |
---|
| 70 | MAXFD = os.sysconf("SC_OPEN_MAX") |
---|
| 71 | except (AttributeError, ValueError) : |
---|
| 72 | MAXFD = 256 |
---|
| 73 | for i in range(3, MAXFD) : |
---|
| 74 | try: |
---|
| 75 | os.close(i) |
---|
| 76 | except OSError: |
---|
| 77 | pass |
---|
| 78 | try: |
---|
| 79 | os.execvpe(cmd[0], [self.arg0 or cmd[0]] + cmd[1:], os.environ) |
---|
| 80 | finally: |
---|
| 81 | os._exit(1) |
---|
| 82 | |
---|
[582] | 83 | # Some IPP constants |
---|
| 84 | OPERATION_ATTRIBUTES_TAG = 0x01 |
---|
| 85 | JOB_ATTRIBUTES_TAG = 0x02 |
---|
| 86 | END_OF_ATTRIBUTES_TAG = 0x03 |
---|
| 87 | PRINTER_ATTRIBUTES_TAG = 0x04 |
---|
| 88 | UNSUPPORTED_ATTRIBUTES_TAG = 0x05 |
---|
| 89 | |
---|
[581] | 90 | class IPPMessage : |
---|
| 91 | """A class for IPP message files.""" |
---|
| 92 | def __init__(self, data) : |
---|
| 93 | """Initializes an IPP Message object.""" |
---|
| 94 | self.data = data |
---|
| 95 | self._attributes = {} |
---|
| 96 | self.curname = None |
---|
| 97 | self.tags = [ None ] * 256 # by default all tags reserved |
---|
| 98 | |
---|
| 99 | # Delimiter tags |
---|
| 100 | self.tags[0x01] = "operation-attributes-tag" |
---|
| 101 | self.tags[0x02] = "job-attributes-tag" |
---|
| 102 | self.tags[0x03] = "end-of-attributes-tag" |
---|
| 103 | self.tags[0x04] = "printer-attributes-tag" |
---|
| 104 | self.tags[0x05] = "unsupported-attributes-tag" |
---|
| 105 | |
---|
| 106 | # out of band values |
---|
| 107 | self.tags[0x10] = "unsupported" |
---|
| 108 | self.tags[0x11] = "reserved-for-future-default" |
---|
| 109 | self.tags[0x12] = "unknown" |
---|
| 110 | self.tags[0x13] = "no-value" |
---|
| 111 | |
---|
| 112 | # integer values |
---|
| 113 | self.tags[0x20] = "generic-integer" |
---|
| 114 | self.tags[0x21] = "integer" |
---|
| 115 | self.tags[0x22] = "boolean" |
---|
| 116 | self.tags[0x23] = "enum" |
---|
| 117 | |
---|
| 118 | # octetString |
---|
| 119 | self.tags[0x30] = "octetString-with-an-unspecified-format" |
---|
| 120 | self.tags[0x31] = "dateTime" |
---|
| 121 | self.tags[0x32] = "resolution" |
---|
| 122 | self.tags[0x33] = "rangeOfInteger" |
---|
| 123 | self.tags[0x34] = "reserved-for-collection" |
---|
| 124 | self.tags[0x35] = "textWithLanguage" |
---|
| 125 | self.tags[0x36] = "nameWithLanguage" |
---|
| 126 | |
---|
| 127 | # character strings |
---|
| 128 | self.tags[0x20] = "generic-character-string" |
---|
| 129 | self.tags[0x41] = "textWithoutLanguage" |
---|
| 130 | self.tags[0x42] = "nameWithoutLanguage" |
---|
| 131 | # self.tags[0x43] = "reserved" |
---|
| 132 | self.tags[0x44] = "keyword" |
---|
| 133 | self.tags[0x45] = "uri" |
---|
| 134 | self.tags[0x46] = "uriScheme" |
---|
| 135 | self.tags[0x47] = "charset" |
---|
| 136 | self.tags[0x48] = "naturalLanguage" |
---|
| 137 | self.tags[0x49] = "mimeMediaType" |
---|
| 138 | |
---|
| 139 | # now parses the IPP message |
---|
| 140 | self.parse() |
---|
| 141 | |
---|
| 142 | def __getattr__(self, attrname) : |
---|
| 143 | """Allows self.attributes to return the attributes names.""" |
---|
| 144 | if attrname == "attributes" : |
---|
| 145 | keys = self._attributes.keys() |
---|
| 146 | keys.sort() |
---|
| 147 | return keys |
---|
| 148 | raise AttributeError, attrname |
---|
| 149 | |
---|
| 150 | def __getitem__(self, ippattrname) : |
---|
| 151 | """Fakes a dictionnary d['key'] notation.""" |
---|
| 152 | value = self._attributes.get(ippattrname) |
---|
| 153 | if value is not None : |
---|
| 154 | if len(value) == 1 : |
---|
| 155 | value = value[0] |
---|
| 156 | return value |
---|
| 157 | get = __getitem__ |
---|
| 158 | |
---|
| 159 | def parseTag(self) : |
---|
| 160 | """Extracts information from an IPP tag.""" |
---|
| 161 | pos = self.position |
---|
| 162 | valuetag = self.tags[ord(self.data[pos])] |
---|
| 163 | # print valuetag.get("name") |
---|
| 164 | pos += 1 |
---|
| 165 | posend = pos2 = pos + 2 |
---|
| 166 | namelength = unpack(">H", self.data[pos:pos2])[0] |
---|
| 167 | if not namelength : |
---|
| 168 | name = self.curname |
---|
| 169 | else : |
---|
| 170 | posend += namelength |
---|
| 171 | self.curname = name = self.data[pos2:posend] |
---|
| 172 | pos2 = posend + 2 |
---|
| 173 | valuelength = unpack(">H", self.data[posend:pos2])[0] |
---|
| 174 | posend = pos2 + valuelength |
---|
| 175 | value = self.data[pos2:posend] |
---|
| 176 | oldval = self._attributes.setdefault(name, []) |
---|
| 177 | oldval.append(value) |
---|
| 178 | return posend - self.position |
---|
| 179 | |
---|
| 180 | def operation_attributes_tag(self) : |
---|
| 181 | """Indicates that the parser enters into an operation-attributes-tag group.""" |
---|
| 182 | return self.parseTag() |
---|
| 183 | |
---|
| 184 | def job_attributes_tag(self) : |
---|
| 185 | """Indicates that the parser enters into an operation-attributes-tag group.""" |
---|
| 186 | return self.parseTag() |
---|
| 187 | |
---|
| 188 | def printer_attributes_tag(self) : |
---|
| 189 | """Indicates that the parser enters into an operation-attributes-tag group.""" |
---|
| 190 | return self.parseTag() |
---|
| 191 | |
---|
| 192 | def parse(self) : |
---|
| 193 | """Parses an IPP Message. |
---|
| 194 | |
---|
| 195 | NB : Only a subset of RFC2910 is implemented. |
---|
| 196 | We are only interested in textual informations for now anyway. |
---|
| 197 | """ |
---|
| 198 | self.version = "%s.%s" % (ord(self.data[0]), ord(self.data[1])) |
---|
| 199 | self.operation_id = "0x%04x" % unpack(">H", self.data[2:4])[0] |
---|
| 200 | self.request_id = "0x%08x" % unpack(">I", self.data[4:8])[0] |
---|
| 201 | self.position = 8 |
---|
| 202 | try : |
---|
| 203 | tag = ord(self.data[self.position]) |
---|
| 204 | while tag != END_OF_ATTRIBUTES_TAG : |
---|
| 205 | self.position += 1 |
---|
| 206 | name = self.tags[tag] |
---|
| 207 | if name is not None : |
---|
| 208 | func = getattr(self, name.replace("-", "_"), None) |
---|
| 209 | if func is not None : |
---|
| 210 | self.position += func() |
---|
| 211 | if ord(self.data[self.position]) > UNSUPPORTED_ATTRIBUTES_TAG : |
---|
| 212 | self.position -= 1 |
---|
| 213 | continue |
---|
| 214 | tag = ord(self.data[self.position]) |
---|
| 215 | except IndexError : |
---|
| 216 | raise IPPError, "Unexpected end of IPP message." |
---|
| 217 | |
---|
[570] | 218 | class FakeConfig : |
---|
| 219 | """Fakes a configuration file parser.""" |
---|
| 220 | def get(self, section, option, raw=0) : |
---|
| 221 | """Fakes the retrieval of a global option.""" |
---|
| 222 | raise ConfigError, "Invalid configuration file : no option %s in section [%s]" % (option, section) |
---|
| 223 | |
---|
[568] | 224 | class CupsBackend : |
---|
| 225 | """Base class for tools with no database access.""" |
---|
| 226 | def __init__(self) : |
---|
| 227 | """Initializes the CUPS backend wrapper.""" |
---|
[588] | 228 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
---|
| 229 | signal.signal(signal.SIGPIPE, signal.SIG_IGN) |
---|
[577] | 230 | self.MyName = "Tea4CUPS" |
---|
| 231 | self.myname = "tea4cups" |
---|
| 232 | self.pid = os.getpid() |
---|
[570] | 233 | confdir = os.environ.get("CUPS_SERVERROOT", ".") |
---|
[577] | 234 | self.conffile = os.path.join(confdir, "%s.conf" % self.myname) |
---|
[570] | 235 | if os.path.isfile(self.conffile) : |
---|
| 236 | self.config = ConfigParser.ConfigParser() |
---|
| 237 | self.config.read([self.conffile]) |
---|
[573] | 238 | self.debug = self.isTrue(self.getGlobalOption("debug", ignore=1)) |
---|
[570] | 239 | else : |
---|
| 240 | self.config = FakeConfig() |
---|
| 241 | self.debug = 1 # no config, so force debug mode ! |
---|
| 242 | |
---|
[574] | 243 | def logInfo(self, message, level="info") : |
---|
| 244 | """Logs a message to CUPS' error_log file.""" |
---|
[589] | 245 | sys.stderr.write("%s: %s v%s (PID %i) : %s\n" % (level.upper(), self.MyName, version, os.getpid(), message)) |
---|
[574] | 246 | sys.stderr.flush() |
---|
| 247 | |
---|
[585] | 248 | def logDebug(self, message) : |
---|
| 249 | """Logs something to debug output if debug is enabled.""" |
---|
| 250 | if self.debug : |
---|
| 251 | self.logInfo(message, level="debug") |
---|
| 252 | |
---|
[570] | 253 | def isTrue(self, option) : |
---|
| 254 | """Returns 1 if option is set to true, else 0.""" |
---|
| 255 | if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) : |
---|
| 256 | return 1 |
---|
| 257 | else : |
---|
| 258 | return 0 |
---|
| 259 | |
---|
| 260 | def getGlobalOption(self, option, ignore=0) : |
---|
| 261 | """Returns an option from the global section, or raises a ConfigError if ignore is not set, else returns None.""" |
---|
| 262 | try : |
---|
| 263 | return self.config.get("global", option, raw=1) |
---|
| 264 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
[577] | 265 | if not ignore : |
---|
[570] | 266 | raise ConfigError, "Option %s not found in section global of %s" % (option, self.conffile) |
---|
| 267 | |
---|
[577] | 268 | def getPrintQueueOption(self, printqueuename, option, ignore=0) : |
---|
[570] | 269 | """Returns an option from the printer section, or the global section, or raises a ConfigError.""" |
---|
| 270 | globaloption = self.getGlobalOption(option, ignore=1) |
---|
| 271 | try : |
---|
[574] | 272 | return self.config.get(printqueuename, option, raw=1) |
---|
[570] | 273 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
| 274 | if globaloption is not None : |
---|
| 275 | return globaloption |
---|
[577] | 276 | elif not ignore : |
---|
[574] | 277 | raise ConfigError, "Option %s not found in section [%s] of %s" % (option, printqueuename, self.conffile) |
---|
[571] | 278 | |
---|
[597] | 279 | def enumBranches(self, printqueuename, branchtype="tee") : |
---|
| 280 | """Returns the list of branchtypes branches for a particular section's.""" |
---|
| 281 | branchbasename = "%s_" % branchtype.lower() |
---|
[573] | 282 | try : |
---|
[597] | 283 | globalbranches = [ (k, v) for (k, v) in self.config.items("global") if k.startswith(branchbasename) ] |
---|
[573] | 284 | except ConfigParser.NoSectionError, msg : |
---|
[579] | 285 | raise ConfigError, "Invalid configuration file : %s" % msg |
---|
[573] | 286 | try : |
---|
[597] | 287 | sectionbranches = [ (k, v) for (k, v) in self.config.items(printqueuename) if k.startswith(branchbasename) ] |
---|
[573] | 288 | except ConfigParser.NoSectionError, msg : |
---|
[583] | 289 | self.logInfo("No section for print queue %s : %s" % (printqueuename, msg)) |
---|
[573] | 290 | sectionbranches = [] |
---|
| 291 | branches = {} |
---|
| 292 | for (k, v) in globalbranches : |
---|
| 293 | value = v.strip() |
---|
| 294 | if value : |
---|
| 295 | branches[k] = value |
---|
| 296 | for (k, v) in sectionbranches : |
---|
| 297 | value = v.strip() |
---|
| 298 | if value : |
---|
| 299 | branches[k] = value # overwrite any global option or set a new value |
---|
| 300 | else : |
---|
| 301 | del branches[k] # empty value disables a global option |
---|
| 302 | return branches |
---|
[568] | 303 | |
---|
| 304 | def discoverOtherBackends(self) : |
---|
| 305 | """Discovers the other CUPS backends. |
---|
| 306 | |
---|
| 307 | Executes each existing backend in turn in device enumeration mode. |
---|
| 308 | Returns the list of available backends. |
---|
| 309 | """ |
---|
[569] | 310 | # Unfortunately this method can't output any debug information |
---|
| 311 | # to stdout or stderr, else CUPS considers that the device is |
---|
| 312 | # not available. |
---|
[568] | 313 | available = [] |
---|
[569] | 314 | (directory, myname) = os.path.split(sys.argv[0]) |
---|
[588] | 315 | if not directory : |
---|
| 316 | directory = "./" |
---|
[568] | 317 | tmpdir = tempfile.gettempdir() |
---|
[569] | 318 | lockfilename = os.path.join(tmpdir, "%s..LCK" % myname) |
---|
[568] | 319 | if os.path.exists(lockfilename) : |
---|
| 320 | lockfile = open(lockfilename, "r") |
---|
| 321 | pid = int(lockfile.read()) |
---|
| 322 | lockfile.close() |
---|
| 323 | try : |
---|
| 324 | # see if the pid contained in the lock file is still running |
---|
| 325 | os.kill(pid, 0) |
---|
| 326 | except OSError, e : |
---|
| 327 | if e.errno != errno.EPERM : |
---|
| 328 | # process doesn't exist anymore |
---|
| 329 | os.remove(lockfilename) |
---|
| 330 | |
---|
| 331 | if not os.path.exists(lockfilename) : |
---|
| 332 | lockfile = open(lockfilename, "w") |
---|
[577] | 333 | lockfile.write("%i" % self.pid) |
---|
[568] | 334 | lockfile.close() |
---|
[569] | 335 | allbackends = [ os.path.join(directory, b) \ |
---|
| 336 | for b in os.listdir(directory) |
---|
| 337 | if os.access(os.path.join(directory, b), os.X_OK) \ |
---|
| 338 | and (b != myname)] |
---|
| 339 | for backend in allbackends : |
---|
[568] | 340 | answer = os.popen(backend, "r") |
---|
| 341 | try : |
---|
| 342 | devices = [line.strip() for line in answer.readlines()] |
---|
| 343 | except : |
---|
| 344 | devices = [] |
---|
| 345 | status = answer.close() |
---|
| 346 | if status is None : |
---|
| 347 | for d in devices : |
---|
| 348 | # each line is of the form : |
---|
| 349 | # 'xxxx xxxx "xxxx xxx" "xxxx xxx"' |
---|
| 350 | # so we have to decompose it carefully |
---|
| 351 | fdevice = cStringIO.StringIO(d) |
---|
| 352 | tokenizer = shlex.shlex(fdevice) |
---|
| 353 | tokenizer.wordchars = tokenizer.wordchars + \ |
---|
| 354 | r".:,?!~/\_$*-+={}[]()#" |
---|
| 355 | arguments = [] |
---|
| 356 | while 1 : |
---|
| 357 | token = tokenizer.get_token() |
---|
| 358 | if token : |
---|
| 359 | arguments.append(token) |
---|
| 360 | else : |
---|
| 361 | break |
---|
| 362 | fdevice.close() |
---|
| 363 | try : |
---|
| 364 | (devicetype, device, name, fullname) = arguments |
---|
| 365 | except ValueError : |
---|
| 366 | pass # ignore this 'bizarre' device |
---|
| 367 | else : |
---|
| 368 | if name.startswith('"') and name.endswith('"') : |
---|
| 369 | name = name[1:-1] |
---|
| 370 | if fullname.startswith('"') and fullname.endswith('"') : |
---|
| 371 | fullname = fullname[1:-1] |
---|
[577] | 372 | available.append('%s %s:%s "%s+%s" "%s managed %s"' \ |
---|
| 373 | % (devicetype, self.myname, device, self.MyName, name, self.MyName, fullname)) |
---|
[568] | 374 | os.remove(lockfilename) |
---|
[599] | 375 | available.append('direct %s:// "%s+Nothing" "%s managed Virtual Printer"' \ |
---|
| 376 | % (self.myname, self.MyName, self.MyName)) |
---|
[568] | 377 | return available |
---|
| 378 | |
---|
[577] | 379 | def initBackend(self) : |
---|
| 380 | """Initializes the backend's attributes.""" |
---|
| 381 | # check that the DEVICE_URI environment variable's value is |
---|
| 382 | # prefixed with self.myname otherwise don't touch it. |
---|
| 383 | # If this is the case, we have to remove the prefix from |
---|
| 384 | # the environment before launching the real backend |
---|
| 385 | muststartwith = "%s:" % self.myname |
---|
| 386 | device_uri = os.environ.get("DEVICE_URI", "") |
---|
| 387 | if device_uri.startswith(muststartwith) : |
---|
| 388 | fulldevice_uri = device_uri[:] |
---|
| 389 | device_uri = fulldevice_uri[len(muststartwith):] |
---|
[583] | 390 | for i in range(2) : |
---|
| 391 | if device_uri.startswith("/") : |
---|
| 392 | device_uri = device_uri[1:] |
---|
[577] | 393 | try : |
---|
| 394 | (backend, destination) = device_uri.split(":", 1) |
---|
| 395 | except ValueError : |
---|
[583] | 396 | if not device_uri : |
---|
[600] | 397 | self.logDebug("Not attached to an existing print queue.") |
---|
[583] | 398 | backend = "" |
---|
| 399 | else : |
---|
| 400 | raise TeeError, "Invalid DEVICE_URI : %s\n" % device_uri |
---|
[577] | 401 | |
---|
| 402 | self.JobId = sys.argv[1].strip() |
---|
| 403 | self.UserName = sys.argv[2].strip() |
---|
| 404 | self.Title = sys.argv[3].strip() |
---|
| 405 | self.Copies = int(sys.argv[4].strip()) |
---|
| 406 | self.Options = sys.argv[5].strip() |
---|
| 407 | if len(sys.argv) == 7 : |
---|
| 408 | self.InputFile = sys.argv[6] # read job's datas from file |
---|
| 409 | else : |
---|
| 410 | self.InputFile = None # read job's datas from stdin |
---|
| 411 | |
---|
| 412 | self.RealBackend = backend |
---|
| 413 | self.DeviceURI = device_uri |
---|
| 414 | self.PrinterName = os.environ.get("PRINTER", "") |
---|
| 415 | self.Directory = self.getPrintQueueOption(self.PrinterName, "directory") |
---|
[581] | 416 | self.DataFile = os.path.join(self.Directory, "%s-%s-%s-%s" % (self.myname, self.PrinterName, self.UserName, self.JobId)) |
---|
[615] | 417 | (ippfilename, ippmessage) = self.parseIPPMessageFile() |
---|
| 418 | self.ControlFile = ippfilename |
---|
| 419 | self.ClientHost = ippmessage.get("job-originating-host-name") |
---|
| 420 | self.JobBilling = ippmessage.get("job-billing") |
---|
[577] | 421 | |
---|
[583] | 422 | def getCupsConfigDirectives(self, directives=[]) : |
---|
| 423 | """Retrieves some CUPS directives from its configuration file. |
---|
| 424 | |
---|
| 425 | Returns a mapping with lowercased directives as keys and |
---|
| 426 | their setting as values. |
---|
| 427 | """ |
---|
| 428 | dirvalues = {} |
---|
| 429 | cupsroot = os.environ.get("CUPS_SERVERROOT", "/etc/cups") |
---|
| 430 | cupsdconf = os.path.join(cupsroot, "cupsd.conf") |
---|
| 431 | try : |
---|
| 432 | conffile = open(cupsdconf, "r") |
---|
| 433 | except IOError : |
---|
| 434 | raise TeeError, "Unable to open %s" % cupsdconf |
---|
| 435 | else : |
---|
| 436 | for line in conffile.readlines() : |
---|
| 437 | linecopy = line.strip().lower() |
---|
| 438 | for di in [d.lower() for d in directives] : |
---|
| 439 | if linecopy.startswith("%s " % di) : |
---|
| 440 | try : |
---|
| 441 | val = line.split()[1] |
---|
| 442 | except : |
---|
| 443 | pass # ignore errors, we take the last value in any case. |
---|
| 444 | else : |
---|
| 445 | dirvalues[di] = val |
---|
| 446 | conffile.close() |
---|
| 447 | return dirvalues |
---|
| 448 | |
---|
[615] | 449 | def parseIPPMessageFile(self) : |
---|
[582] | 450 | """Extracts the client's hostname or IP address from the CUPS message file for current job.""" |
---|
[583] | 451 | cupsdconf = self.getCupsConfigDirectives(["RequestRoot"]) |
---|
[582] | 452 | requestroot = cupsdconf.get("requestroot", "/var/spool/cups") |
---|
| 453 | if (len(self.JobId) < 5) and self.JobId.isdigit() : |
---|
| 454 | ippmessagefile = "c%05i" % int(self.JobId) |
---|
| 455 | else : |
---|
| 456 | ippmessagefile = "c%s" % self.JobId |
---|
| 457 | ippmessagefile = os.path.join(requestroot, ippmessagefile) |
---|
| 458 | ippmessage = {} |
---|
| 459 | try : |
---|
| 460 | ippdatafile = open(ippmessagefile) |
---|
| 461 | except : |
---|
| 462 | self.logInfo("Unable to open IPP message file %s" % ippmessagefile, "warn") |
---|
| 463 | else : |
---|
| 464 | self.logDebug("Parsing of IPP message file %s begins." % ippmessagefile) |
---|
| 465 | try : |
---|
| 466 | ippmessage = IPPMessage(ippdatafile.read()) |
---|
| 467 | except IPPError, msg : |
---|
| 468 | self.logInfo("Error while parsing %s : %s" % (ippmessagefile, msg), "warn") |
---|
| 469 | else : |
---|
| 470 | self.logDebug("Parsing of IPP message file %s ends." % ippmessagefile) |
---|
| 471 | ippdatafile.close() |
---|
[615] | 472 | return (ippmessagefile, ippmessage) |
---|
[582] | 473 | |
---|
[577] | 474 | def exportAttributes(self) : |
---|
| 475 | """Exports our backend's attributes to the environment.""" |
---|
| 476 | os.environ["DEVICE_URI"] = self.DeviceURI # WARNING ! |
---|
| 477 | os.environ["TEAPRINTERNAME"] = self.PrinterName |
---|
| 478 | os.environ["TEADIRECTORY"] = self.Directory |
---|
| 479 | os.environ["TEADATAFILE"] = self.DataFile |
---|
[579] | 480 | os.environ["TEAJOBSIZE"] = str(self.JobSize) |
---|
[577] | 481 | os.environ["TEAMD5SUM"] = self.JobMD5Sum |
---|
[582] | 482 | os.environ["TEACLIENTHOST"] = self.ClientHost or "" |
---|
[577] | 483 | os.environ["TEAJOBID"] = self.JobId |
---|
| 484 | os.environ["TEAUSERNAME"] = self.UserName |
---|
| 485 | os.environ["TEATITLE"] = self.Title |
---|
| 486 | os.environ["TEACOPIES"] = str(self.Copies) |
---|
| 487 | os.environ["TEAOPTIONS"] = self.Options |
---|
| 488 | os.environ["TEAINPUTFILE"] = self.InputFile or "" |
---|
[615] | 489 | os.environ["TEABILLING"] = self.JobBilling or "" |
---|
| 490 | os.environ["TEACONTROLFILE"] = self.ControlFile |
---|
[577] | 491 | |
---|
| 492 | def saveDatasAndCheckSum(self) : |
---|
| 493 | """Saves the input datas into a static file.""" |
---|
[583] | 494 | self.logDebug("Duplicating data stream into %s" % self.DataFile) |
---|
[577] | 495 | mustclose = 0 |
---|
| 496 | if self.InputFile is not None : |
---|
| 497 | infile = open(self.InputFile, "rb") |
---|
| 498 | mustclose = 1 |
---|
| 499 | else : |
---|
| 500 | infile = sys.stdin |
---|
| 501 | CHUNK = 64*1024 # read 64 Kb at a time |
---|
| 502 | dummy = 0 |
---|
| 503 | sizeread = 0 |
---|
| 504 | checksum = md5.new() |
---|
| 505 | outfile = open(self.DataFile, "wb") |
---|
| 506 | while 1 : |
---|
| 507 | data = infile.read(CHUNK) |
---|
| 508 | if not data : |
---|
| 509 | break |
---|
| 510 | sizeread += len(data) |
---|
| 511 | outfile.write(data) |
---|
| 512 | checksum.update(data) |
---|
| 513 | if not (dummy % 32) : # Only display every 2 Mb |
---|
| 514 | self.logDebug("%s bytes saved..." % sizeread) |
---|
| 515 | dummy += 1 |
---|
| 516 | outfile.close() |
---|
| 517 | if mustclose : |
---|
[579] | 518 | infile.close() |
---|
[577] | 519 | self.JobSize = sizeread |
---|
| 520 | self.JobMD5Sum = checksum.hexdigest() |
---|
| 521 | self.logDebug("Job %s is %s bytes long." % (self.JobId, self.JobSize)) |
---|
| 522 | self.logDebug("Job %s MD5 sum is %s" % (self.JobId, self.JobMD5Sum)) |
---|
[568] | 523 | |
---|
[577] | 524 | def cleanUp(self) : |
---|
| 525 | """Cleans up the place.""" |
---|
| 526 | if not self.isTrue(self.getPrintQueueOption(self.PrinterName, "keepfiles", ignore=1)) : |
---|
| 527 | os.remove(self.DataFile) |
---|
[579] | 528 | |
---|
[588] | 529 | def sigtermHandler(self, signum, frame) : |
---|
| 530 | """Sets an attribute whenever SIGTERM is received.""" |
---|
| 531 | self.gotSigTerm = 1 |
---|
| 532 | self.logInfo("SIGTERM received for Job %s." % self.JobId) |
---|
| 533 | |
---|
[579] | 534 | def runBranches(self) : |
---|
[598] | 535 | """Launches each hook or tee defined for the current print queue.""" |
---|
[584] | 536 | exitcode = 0 |
---|
[604] | 537 | self.isCancelled = 0 # did a prehook cancel the print job ? |
---|
| 538 | self.gotSigTerm = 0 |
---|
[588] | 539 | signal.signal(signal.SIGTERM, self.sigtermHandler) |
---|
[598] | 540 | serialize = self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1)) |
---|
| 541 | for branchtype in ["prehook", "tee", "posthook"] : |
---|
| 542 | branches = self.enumBranches(self.PrinterName, branchtype) |
---|
| 543 | status = self.runCommands(branchtype, branches, serialize) |
---|
| 544 | if status : |
---|
| 545 | exitcode = status |
---|
[602] | 546 | if (branchtype == "prehook") and self.isCancelled : |
---|
[601] | 547 | break # We don't want to execute tees or posthooks in this case |
---|
[598] | 548 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
---|
[600] | 549 | if not exitcode : |
---|
| 550 | self.logInfo("OK") |
---|
| 551 | else : |
---|
| 552 | self.logInfo("An error occured, please check CUPS' error_log file.") |
---|
[598] | 553 | return exitcode |
---|
| 554 | |
---|
| 555 | def runCommands(self, btype, branches, serialize) : |
---|
| 556 | """Runs the commands for a particular branch type.""" |
---|
| 557 | exitcode = 0 |
---|
| 558 | btype = btype.lower() |
---|
| 559 | btypetitle = btype.title() |
---|
| 560 | branchlist = branches.keys() |
---|
| 561 | branchlist.sort() |
---|
| 562 | if serialize : |
---|
[600] | 563 | self.logDebug("Begin serialized %ss" % btypetitle) |
---|
[598] | 564 | if (btype == "tee") and self.RealBackend : |
---|
[587] | 565 | self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName)) |
---|
[608] | 566 | retcode = self.runOriginalBackend() |
---|
| 567 | if os.WIFEXITED(retcode) : |
---|
| 568 | retcode = os.WEXITSTATUS(retcode) |
---|
| 569 | os.environ["TEASTATUS"] = str(retcode) |
---|
| 570 | exitcode = retcode |
---|
[598] | 571 | for branch in branchlist : |
---|
| 572 | command = branches[branch] |
---|
[588] | 573 | if self.gotSigTerm : |
---|
| 574 | break |
---|
[581] | 575 | self.logDebug("Launching %s : %s" % (branch, command)) |
---|
[584] | 576 | retcode = os.system(command) |
---|
[598] | 577 | self.logDebug("Exit code for %s %s on printer %s is %s" % (btype, branch, self.PrinterName, retcode)) |
---|
[584] | 578 | if os.WIFEXITED(retcode) : |
---|
| 579 | retcode = os.WEXITSTATUS(retcode) |
---|
| 580 | if retcode : |
---|
[601] | 581 | if (btype == "prehook") and (retcode == 255) : # -1 |
---|
| 582 | self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch)) |
---|
[602] | 583 | self.isCancelled = 1 |
---|
[601] | 584 | else : |
---|
| 585 | self.logInfo("%s %s on printer %s didn't exit successfully." % (btypetitle, branch, self.PrinterName), "error") |
---|
| 586 | exitcode = 1 |
---|
[600] | 587 | self.logDebug("End serialized %ss" % btypetitle) |
---|
[581] | 588 | else : |
---|
[600] | 589 | self.logDebug("Begin forked %ss" % btypetitle) |
---|
[584] | 590 | pids = {} |
---|
[598] | 591 | if (btype == "tee") and self.RealBackend : |
---|
[587] | 592 | branches["Original backend"] = None # Fakes a tee to launch one more child |
---|
[598] | 593 | branchlist = ["Original backend"] + branchlist |
---|
| 594 | for branch in branchlist : |
---|
| 595 | command = branches[branch] |
---|
[588] | 596 | if self.gotSigTerm : |
---|
| 597 | break |
---|
[584] | 598 | pid = os.fork() |
---|
| 599 | if pid : |
---|
| 600 | pids[branch] = pid |
---|
| 601 | else : |
---|
[587] | 602 | if branch == "Original backend" : |
---|
| 603 | self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName)) |
---|
| 604 | sys.exit(self.runOriginalBackend()) |
---|
| 605 | else : |
---|
| 606 | self.logDebug("Launching %s : %s" % (branch, command)) |
---|
| 607 | retcode = os.system(command) |
---|
| 608 | if os.WIFEXITED(retcode) : |
---|
| 609 | retcode = os.WEXITSTATUS(retcode) |
---|
| 610 | else : |
---|
| 611 | retcode = -1 |
---|
| 612 | sys.exit(retcode) |
---|
[584] | 613 | for (branch, pid) in pids.items() : |
---|
| 614 | (childpid, retcode) = os.waitpid(pid, 0) |
---|
[598] | 615 | self.logDebug("Exit code for %s %s (PID %s) on printer %s is %s" % (btype, branch, childpid, self.PrinterName, retcode)) |
---|
[584] | 616 | if os.WIFEXITED(retcode) : |
---|
| 617 | retcode = os.WEXITSTATUS(retcode) |
---|
| 618 | if retcode : |
---|
[601] | 619 | if (btype == "prehook") and (retcode == 255) : # -1 |
---|
| 620 | self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch)) |
---|
[602] | 621 | self.isCancelled = 1 |
---|
[601] | 622 | else : |
---|
| 623 | self.logInfo("%s %s (PID %s) on printer %s didn't exit successfully." % (btypetitle, branch, childpid, self.PrinterName), "error") |
---|
| 624 | exitcode = 1 |
---|
[598] | 625 | if branch == "Original backend" : |
---|
| 626 | os.environ["TEASTATUS"] = str(retcode) |
---|
[600] | 627 | self.logDebug("End forked %ss" % btypetitle) |
---|
[584] | 628 | return exitcode |
---|
[577] | 629 | |
---|
[588] | 630 | def unregisterFileNo(self, pollobj, fileno) : |
---|
| 631 | """Removes a file handle from the polling object.""" |
---|
| 632 | try : |
---|
| 633 | pollobj.unregister(fileno) |
---|
| 634 | except KeyError : |
---|
| 635 | self.logInfo("File number %s unregistered twice from polling object, ignored." % fileno, "warn") |
---|
| 636 | except : |
---|
| 637 | self.logDebug("Error while unregistering file number %s from polling object." % fileno) |
---|
| 638 | else : |
---|
| 639 | self.logDebug("File number %s unregistered from polling object." % fileno) |
---|
| 640 | |
---|
| 641 | def formatFileEvent(self, fd, mask) : |
---|
| 642 | """Formats file debug info.""" |
---|
| 643 | maskval = [] |
---|
| 644 | if mask & select.POLLIN : |
---|
| 645 | maskval.append("POLLIN") |
---|
| 646 | if mask & select.POLLOUT : |
---|
| 647 | maskval.append("POLLOUT") |
---|
| 648 | if mask & select.POLLPRI : |
---|
| 649 | maskval.append("POLLPRI") |
---|
| 650 | if mask & select.POLLERR : |
---|
| 651 | maskval.append("POLLERR") |
---|
| 652 | if mask & select.POLLHUP : |
---|
| 653 | maskval.append("POLLHUP") |
---|
| 654 | if mask & select.POLLNVAL : |
---|
| 655 | maskval.append("POLLNVAL") |
---|
| 656 | return "%s (%s)" % (fd, " | ".join(maskval)) |
---|
| 657 | |
---|
[587] | 658 | def runOriginalBackend(self) : |
---|
| 659 | """Launches the original backend.""" |
---|
| 660 | originalbackend = os.path.join(os.path.split(sys.argv[0])[0], self.RealBackend) |
---|
| 661 | arguments = sys.argv |
---|
| 662 | self.logDebug("Starting original backend %s with args %s" % (originalbackend, " ".join(['"%s"' % a for a in ([os.environ["DEVICE_URI"]] + arguments[1:])]))) |
---|
| 663 | subprocess = Popen4ForCUPS([originalbackend] + arguments[1:], bufsize=0, arg0=os.environ["DEVICE_URI"]) |
---|
[588] | 664 | |
---|
| 665 | # Save file descriptors, we will need them later. |
---|
| 666 | stderrfno = sys.stderr.fileno() |
---|
| 667 | fromcfno = subprocess.fromchild.fileno() |
---|
| 668 | tocfno = subprocess.tochild.fileno() |
---|
| 669 | |
---|
| 670 | # We will have to be careful when dealing with I/O |
---|
| 671 | # So we use a poll object to know when to read or write |
---|
| 672 | pollster = select.poll() |
---|
| 673 | pollster.register(fromcfno, select.POLLIN | select.POLLPRI) |
---|
| 674 | pollster.register(stderrfno, select.POLLOUT) |
---|
| 675 | pollster.register(tocfno, select.POLLOUT) |
---|
| 676 | |
---|
| 677 | # Initialize our buffers |
---|
| 678 | indata = "" |
---|
| 679 | outdata = "" |
---|
| 680 | endinput = endoutput = 0 |
---|
| 681 | inputclosed = outputclosed = 0 |
---|
| 682 | totaltochild = totalfromcups = 0 |
---|
| 683 | totalfromchild = totaltocups = 0 |
---|
| 684 | |
---|
[587] | 685 | if self.InputFile is None : |
---|
[588] | 686 | # this is not a real file, we read the job's data |
---|
| 687 | # from our temporary file which is a copy of stdin |
---|
| 688 | inf = open(self.DataFile, "rb") |
---|
| 689 | infno = inf.fileno() |
---|
| 690 | pollster.register(infno, select.POLLIN | select.POLLPRI) |
---|
| 691 | else : |
---|
| 692 | # job's data is in a file, no need to pass the data |
---|
| 693 | # to the original backend |
---|
| 694 | self.logDebug("Job's data is in %s" % self.InputFile) |
---|
| 695 | infno = None |
---|
| 696 | endinput = 1 |
---|
| 697 | |
---|
| 698 | self.logDebug("Entering streams polling loop...") |
---|
| 699 | MEGABYTE = 1024*1024 |
---|
| 700 | killed = 0 |
---|
| 701 | status = -1 |
---|
| 702 | while (status == -1) and (not killed) and not (inputclosed and outputclosed) : |
---|
| 703 | # First check if original backend is still alive |
---|
| 704 | status = subprocess.poll() |
---|
[587] | 705 | |
---|
[588] | 706 | # Now if we got SIGTERM, we have |
---|
| 707 | # to kill -TERM the original backend |
---|
| 708 | if self.gotSigTerm and not killed : |
---|
| 709 | try : |
---|
| 710 | os.kill(subprocess.pid, signal.SIGTERM) |
---|
| 711 | except OSError, msg : # ignore but logs if process was already killed. |
---|
| 712 | self.logDebug("Error while sending signal to pid %s : %s" % (subprocess.pid, msg)) |
---|
| 713 | else : |
---|
| 714 | self.logInfo(_("SIGTERM was sent to original backend %s (PID %s)") % (originalbackend, subprocess.pid)) |
---|
| 715 | killed = 1 |
---|
| 716 | |
---|
| 717 | # In any case, deal with any remaining I/O |
---|
| 718 | try : |
---|
| 719 | availablefds = pollster.poll(5000) |
---|
| 720 | except select.error, msg : |
---|
| 721 | self.logDebug("Interrupted poll : %s" % msg) |
---|
| 722 | availablefds = [] |
---|
| 723 | if not availablefds : |
---|
| 724 | self.logDebug("Nothing to do, sleeping a bit...") |
---|
| 725 | time.sleep(0.01) # give some time to the system |
---|
| 726 | else : |
---|
| 727 | for (fd, mask) in availablefds : |
---|
| 728 | try : |
---|
| 729 | if mask & select.POLLOUT : |
---|
| 730 | # We can write |
---|
| 731 | if fd == tocfno : |
---|
| 732 | if indata : |
---|
| 733 | try : |
---|
| 734 | nbwritten = os.write(fd, indata) |
---|
| 735 | except (OSError, IOError), msg : |
---|
| 736 | self.logDebug("Error while writing to original backend's stdin %s : %s" % (fd, msg)) |
---|
| 737 | else : |
---|
| 738 | if len(indata) != nbwritten : |
---|
| 739 | self.logDebug("Short write to original backend's input !") |
---|
| 740 | totaltochild += nbwritten |
---|
| 741 | self.logDebug("%s bytes sent to original backend so far..." % totaltochild) |
---|
| 742 | indata = indata[nbwritten:] |
---|
| 743 | else : |
---|
| 744 | self.logDebug("No data to send to original backend yet, sleeping a bit...") |
---|
| 745 | time.sleep(0.01) |
---|
| 746 | |
---|
| 747 | if endinput : |
---|
| 748 | self.unregisterFileNo(pollster, tocfno) |
---|
| 749 | self.logDebug("Closing original backend's stdin.") |
---|
| 750 | os.close(tocfno) |
---|
| 751 | inputclosed = 1 |
---|
| 752 | elif fd == stderrfno : |
---|
| 753 | if outdata : |
---|
| 754 | try : |
---|
| 755 | nbwritten = os.write(fd, outdata) |
---|
| 756 | except (OSError, IOError), msg : |
---|
| 757 | self.logDebug("Error while writing to CUPS back channel (stderr) %s : %s" % (fd, msg)) |
---|
| 758 | else : |
---|
| 759 | if len(outdata) != nbwritten : |
---|
| 760 | self.logDebug("Short write to stderr (CUPS) !") |
---|
| 761 | totaltocups += nbwritten |
---|
| 762 | self.logDebug("%s bytes sent back to CUPS so far..." % totaltocups) |
---|
| 763 | outdata = outdata[nbwritten:] |
---|
| 764 | else : |
---|
| 765 | # self.logDebug("No data to send back to CUPS yet, sleeping a bit...") # Uncommenting this fills your logs |
---|
| 766 | time.sleep(0.01) # Give some time to the system, stderr is ALWAYS writeable it seems. |
---|
| 767 | |
---|
| 768 | if endoutput : |
---|
| 769 | self.unregisterFileNo(pollster, stderrfno) |
---|
| 770 | outputclosed = 1 |
---|
| 771 | else : |
---|
| 772 | self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask)) |
---|
| 773 | time.sleep(0.01) |
---|
| 774 | |
---|
| 775 | if mask & (select.POLLIN | select.POLLPRI) : |
---|
| 776 | # We have something to read |
---|
| 777 | try : |
---|
| 778 | data = os.read(fd, MEGABYTE) |
---|
| 779 | except (IOError, OSError), msg : |
---|
| 780 | self.logDebug("Error while reading file %s : %s" % (fd, msg)) |
---|
| 781 | else : |
---|
| 782 | if fd == infno : |
---|
| 783 | if not data : # If yes, then no more input data |
---|
| 784 | self.unregisterFileNo(pollster, infno) |
---|
| 785 | self.logDebug("Input data ends.") |
---|
| 786 | endinput = 1 # this happens with real files. |
---|
| 787 | else : |
---|
| 788 | indata += data |
---|
| 789 | totalfromcups += len(data) |
---|
| 790 | self.logDebug("%s bytes read from CUPS so far..." % totalfromcups) |
---|
| 791 | elif fd == fromcfno : |
---|
| 792 | if not data : |
---|
| 793 | self.logDebug("No back channel data to read from original backend yet, sleeping a bit...") |
---|
| 794 | time.sleep(0.01) |
---|
| 795 | else : |
---|
| 796 | outdata += data |
---|
| 797 | totalfromchild += len(data) |
---|
| 798 | self.logDebug("%s bytes read from original backend so far..." % totalfromchild) |
---|
| 799 | else : |
---|
| 800 | self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask)) |
---|
| 801 | time.sleep(0.01) |
---|
| 802 | |
---|
| 803 | if mask & (select.POLLHUP | select.POLLERR) : |
---|
| 804 | # Treat POLLERR as an EOF. |
---|
| 805 | # Some standard I/O stream has no more datas |
---|
| 806 | self.unregisterFileNo(pollster, fd) |
---|
| 807 | if fd == infno : |
---|
| 808 | # Here we are in the case where the input file is stdin. |
---|
| 809 | # which has no more data to be read. |
---|
| 810 | self.logDebug("Input data ends.") |
---|
| 811 | endinput = 1 |
---|
| 812 | elif fd == fromcfno : |
---|
| 813 | # We are no more interested in this file descriptor |
---|
| 814 | self.logDebug("Closing original backend's stdout+stderr.") |
---|
| 815 | os.close(fromcfno) |
---|
| 816 | endoutput = 1 |
---|
| 817 | else : |
---|
| 818 | self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask)) |
---|
| 819 | time.sleep(0.01) |
---|
| 820 | |
---|
| 821 | if mask & select.POLLNVAL : |
---|
| 822 | self.logDebug("File %s was closed. Unregistering from polling object." % fd) |
---|
| 823 | self.unregisterFileNo(pollster, fd) |
---|
| 824 | except IOError, msg : |
---|
| 825 | self.logDebug("Got an IOError : %s" % msg) # we got signalled during an I/O |
---|
| 826 | |
---|
| 827 | # We must close the original backend's input stream |
---|
| 828 | if killed and not inputclosed : |
---|
| 829 | self.logDebug("Forcing close of original backend's stdin.") |
---|
| 830 | os.close(tocfno) |
---|
| 831 | |
---|
| 832 | self.logDebug("Exiting streams polling loop...") |
---|
| 833 | |
---|
| 834 | self.logDebug("input data's final length : %s" % len(indata)) |
---|
| 835 | self.logDebug("back-channel data's final length : %s" % len(outdata)) |
---|
| 836 | |
---|
| 837 | self.logDebug("Total bytes read from CUPS (job's datas) : %s" % totalfromcups) |
---|
| 838 | self.logDebug("Total bytes sent to original backend (job's datas) : %s" % totaltochild) |
---|
| 839 | |
---|
| 840 | self.logDebug("Total bytes read from original backend (back-channel datas) : %s" % totalfromchild) |
---|
| 841 | self.logDebug("Total bytes sent back to CUPS (back-channel datas) : %s" % totaltocups) |
---|
| 842 | |
---|
| 843 | # Check exit code of original CUPS backend. |
---|
| 844 | if status == -1 : |
---|
| 845 | # we exited the loop before the original backend exited |
---|
| 846 | # now we have to wait for it to finish and get its status |
---|
| 847 | self.logDebug("Waiting for original backend to exit...") |
---|
| 848 | try : |
---|
| 849 | status = subprocess.wait() |
---|
| 850 | except OSError : # already dead : TODO : detect when abnormal |
---|
| 851 | status = 0 |
---|
[587] | 852 | if os.WIFEXITED(status) : |
---|
| 853 | return os.WEXITSTATUS(status) |
---|
[588] | 854 | elif not killed : |
---|
| 855 | self.logInfo("CUPS backend %s died abnormally." % originalbackend, "error") |
---|
| 856 | return -1 |
---|
[587] | 857 | else : |
---|
| 858 | return 1 |
---|
| 859 | |
---|
[565] | 860 | if __name__ == "__main__" : |
---|
| 861 | # This is a CUPS backend, we should act and die like a CUPS backend |
---|
[568] | 862 | wrapper = CupsBackend() |
---|
[565] | 863 | if len(sys.argv) == 1 : |
---|
[568] | 864 | print "\n".join(wrapper.discoverOtherBackends()) |
---|
| 865 | sys.exit(0) |
---|
[565] | 866 | elif len(sys.argv) not in (6, 7) : |
---|
[568] | 867 | sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\ |
---|
| 868 | % sys.argv[0]) |
---|
| 869 | sys.exit(1) |
---|
[565] | 870 | else : |
---|
[585] | 871 | try : |
---|
| 872 | wrapper.initBackend() |
---|
| 873 | wrapper.saveDatasAndCheckSum() |
---|
| 874 | wrapper.exportAttributes() |
---|
| 875 | retcode = wrapper.runBranches() |
---|
| 876 | wrapper.cleanUp() |
---|
| 877 | except SystemExit, e : |
---|
| 878 | retcode = e.code |
---|
| 879 | except : |
---|
| 880 | import traceback |
---|
| 881 | lines = [] |
---|
| 882 | for line in traceback.format_exception(*sys.exc_info()) : |
---|
| 883 | lines.extend([l for l in line.split("\n") if l]) |
---|
| 884 | msg = "ERROR: ".join(["%s (PID %s) : %s\n" % (wrapper.MyName, wrapper.pid, l) for l in (["ERROR: Tea4CUPS v%s" % version] + lines)]) |
---|
| 885 | sys.stderr.write(msg) |
---|
| 886 | sys.stderr.flush() |
---|
| 887 | retcode = 1 |
---|
[579] | 888 | sys.exit(retcode) |
---|