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