1 | #! /usr/bin/env python |
---|
2 | # -*- coding: ISO-8859-15 -*- |
---|
3 | |
---|
4 | # Tea4CUPS : Tee for CUPS |
---|
5 | # |
---|
6 | # (c) 2005 Jerome Alet <alet@librelogiciel.com> |
---|
7 | # (c) 2005 Peter Stuge <stuge-tea4cups@cdy.org> |
---|
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. |
---|
17 | # |
---|
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 |
---|
20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
21 | # |
---|
22 | # $Id$ |
---|
23 | # |
---|
24 | # |
---|
25 | |
---|
26 | import sys |
---|
27 | import os |
---|
28 | import pwd |
---|
29 | import errno |
---|
30 | import md5 |
---|
31 | import cStringIO |
---|
32 | import shlex |
---|
33 | import tempfile |
---|
34 | import ConfigParser |
---|
35 | import signal |
---|
36 | from struct import pack, unpack |
---|
37 | |
---|
38 | __version__ = "3.11_unofficial" |
---|
39 | |
---|
40 | class TeeError(Exception): |
---|
41 | """Base exception for Tea4CUPS related stuff.""" |
---|
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__ |
---|
48 | |
---|
49 | class ConfigError(TeeError) : |
---|
50 | """Configuration related exceptions.""" |
---|
51 | pass |
---|
52 | |
---|
53 | class IPPError(TeeError) : |
---|
54 | """IPP related exceptions.""" |
---|
55 | pass |
---|
56 | |
---|
57 | class IPPRequest : |
---|
58 | """A class for IPP requests. |
---|
59 | |
---|
60 | Usage : |
---|
61 | |
---|
62 | fp = open("/var/spool/cups/c00001", "rb") |
---|
63 | message = IPPRequest(fp.read()) |
---|
64 | fp.close() |
---|
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 : |
---|
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]) |
---|
77 | if message.data : |
---|
78 | print "IPP datas : ", repr(message.data) |
---|
79 | """ |
---|
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 | |
---|
86 | Parameters : |
---|
87 | |
---|
88 | data : the complete IPP Message's content. |
---|
89 | debug : a boolean value to output debug info on stderr. |
---|
90 | """ |
---|
91 | self.debug = debug |
---|
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 |
---|
112 | for attrtype in self.attributes_types : |
---|
113 | setattr(self, "%s_attributes" % attrtype, {}) |
---|
114 | |
---|
115 | # Initialize tags |
---|
116 | self.tags = [ None ] * 256 # by default all tags reserved |
---|
117 | |
---|
118 | # Delimiter tags |
---|
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 | |
---|
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" |
---|
132 | self.tags[0x15] = "not-settable" |
---|
133 | self.tags[0x16] = "delete-attribute" |
---|
134 | self.tags[0x17] = "admin-define" |
---|
135 | |
---|
136 | # integer values |
---|
137 | self.tags[0x20] = "generic-integer" |
---|
138 | self.tags[0x21] = "integer" |
---|
139 | self.tags[0x22] = "boolean" |
---|
140 | self.tags[0x23] = "enum" |
---|
141 | |
---|
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" |
---|
147 | self.tags[0x34] = "begCollection" # TODO : find sample files for testing |
---|
148 | self.tags[0x35] = "textWithLanguage" |
---|
149 | self.tags[0x36] = "nameWithLanguage" |
---|
150 | self.tags[0x37] = "endCollection" |
---|
151 | |
---|
152 | # character strings |
---|
153 | self.tags[0x40] = "generic-character-string" |
---|
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" |
---|
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 | |
---|
171 | def logDebug(self, msg) : |
---|
172 | """Prints a debug message.""" |
---|
173 | if self.debug : |
---|
174 | sys.stderr.write("%s\n" % msg) |
---|
175 | sys.stderr.flush() |
---|
176 | |
---|
177 | def __str__(self) : |
---|
178 | """Returns the parsed IPP message in a readable form.""" |
---|
179 | if not self.parsed : |
---|
180 | return "" |
---|
181 | else : |
---|
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) |
---|
186 | for attrtype in self.attributes_types : |
---|
187 | attrdict = getattr(self, "%s_attributes" % attrtype) |
---|
188 | if attrdict : |
---|
189 | mybuffer.append("%s attributes :" % attrtype.title()) |
---|
190 | for key in attrdict.keys() : |
---|
191 | mybuffer.append(" %s : %s" % (key, attrdict[key])) |
---|
192 | if self.data : |
---|
193 | mybuffer.append("IPP datas : %s" % repr(self.data)) |
---|
194 | return "\n".join(mybuffer) |
---|
195 | |
---|
196 | def dump(self) : |
---|
197 | """Generates an IPP Message. |
---|
198 | |
---|
199 | Returns the message as a string of text. |
---|
200 | """ |
---|
201 | mybuffer = [] |
---|
202 | if None not in (self.version, self.operation_id, self.request_id) : |
---|
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)) |
---|
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 : |
---|
210 | mybuffer.append(chr(self.dictags["%s-attributes-tag" % attrtype])) |
---|
211 | tagprinted = 1 |
---|
212 | if type(value) != type([]) : |
---|
213 | value = [ value ] |
---|
214 | for (vtype, val) in value : |
---|
215 | mybuffer.append(chr(self.dictags[vtype])) |
---|
216 | mybuffer.append(pack(">H", len(attrname))) |
---|
217 | mybuffer.append(attrname) |
---|
218 | if vtype in ("integer", "enum") : |
---|
219 | mybuffer.append(pack(">H", 4)) |
---|
220 | mybuffer.append(pack(">I", val)) |
---|
221 | elif vtype == "boolean" : |
---|
222 | mybuffer.append(pack(">H", 1)) |
---|
223 | mybuffer.append(chr(val)) |
---|
224 | else : |
---|
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) |
---|
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) : |
---|
270 | """Extracts information from an IPP tag.""" |
---|
271 | pos = self.position |
---|
272 | tagtype = self.tags[ord(self._data[pos])] |
---|
273 | pos += 1 |
---|
274 | posend = pos2 = pos + 2 |
---|
275 | namelength = unpack(">H", self._data[pos:pos2])[0] |
---|
276 | if not namelength : |
---|
277 | name = self._curname |
---|
278 | else : |
---|
279 | posend += namelength |
---|
280 | self._curname = name = self._data[pos2:posend] |
---|
281 | pos2 = posend + 2 |
---|
282 | valuelength = unpack(">H", self._data[posend:pos2])[0] |
---|
283 | posend = pos2 + valuelength |
---|
284 | value = self._data[pos2:posend] |
---|
285 | if tagtype in ("integer", "enum") : |
---|
286 | value = unpack(">I", value)[0] |
---|
287 | elif tagtype == "boolean" : |
---|
288 | value = ord(value) |
---|
289 | oldval = self._curdict.setdefault(name, []) |
---|
290 | oldval.append((tagtype, value)) |
---|
291 | self.logDebug("%s(%s) : %s" % (name, tagtype, value)) |
---|
292 | return posend - self.position |
---|
293 | |
---|
294 | def operation_attributes_tag(self) : |
---|
295 | """Indicates that the parser enters into an operation-attributes-tag group.""" |
---|
296 | self.logDebug("Start of operation_attributes_tag") |
---|
297 | self._curdict = self.operation_attributes |
---|
298 | return self.parseTag() |
---|
299 | |
---|
300 | def job_attributes_tag(self) : |
---|
301 | """Indicates that the parser enters into a job-attributes-tag group.""" |
---|
302 | self.logDebug("Start of job_attributes_tag") |
---|
303 | self._curdict = self.job_attributes |
---|
304 | return self.parseTag() |
---|
305 | |
---|
306 | def printer_attributes_tag(self) : |
---|
307 | """Indicates that the parser enters into a printer-attributes-tag group.""" |
---|
308 | self.logDebug("Start of printer_attributes_tag") |
---|
309 | self._curdict = self.printer_attributes |
---|
310 | return self.parseTag() |
---|
311 | |
---|
312 | def unsupported_attributes_tag(self) : |
---|
313 | """Indicates that the parser enters into an unsupported-attributes-tag group.""" |
---|
314 | self.logDebug("Start of unsupported_attributes_tag") |
---|
315 | self._curdict = self.unsupported_attributes |
---|
316 | return self.parseTag() |
---|
317 | |
---|
318 | def subscription_attributes_tag(self) : |
---|
319 | """Indicates that the parser enters into a subscription-attributes-tag group.""" |
---|
320 | self.logDebug("Start of subscription_attributes_tag") |
---|
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.""" |
---|
326 | self.logDebug("Start of event_notification_attributes_tag") |
---|
327 | self._curdict = self.event_notification_attributes |
---|
328 | return self.parseTag() |
---|
329 | |
---|
330 | class FakeConfig : |
---|
331 | """Fakes a configuration file parser.""" |
---|
332 | def get(self, section, option, raw=0) : |
---|
333 | """Fakes the retrieval of an option.""" |
---|
334 | raise ConfigError, "Invalid configuration file : no option %s in section [%s]" % (option, section) |
---|
335 | |
---|
336 | class CupsBackend : |
---|
337 | """Base class for tools with no database access.""" |
---|
338 | def __init__(self) : |
---|
339 | """Initializes the CUPS backend wrapper.""" |
---|
340 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
---|
341 | signal.signal(signal.SIGPIPE, signal.SIG_IGN) |
---|
342 | self.MyName = "Tea4CUPS" |
---|
343 | self.myname = "tea4cups" |
---|
344 | self.pid = os.getpid() |
---|
345 | |
---|
346 | def readConfig(self) : |
---|
347 | """Reads the configuration file.""" |
---|
348 | confdir = os.environ.get("CUPS_SERVERROOT", ".") |
---|
349 | self.conffile = os.path.join(confdir, "%s.conf" % self.myname) |
---|
350 | if os.path.isfile(self.conffile) : |
---|
351 | self.config = ConfigParser.ConfigParser() |
---|
352 | self.config.read([self.conffile]) |
---|
353 | self.debug = self.isTrue(self.getGlobalOption("debug", ignore=1)) |
---|
354 | else : |
---|
355 | self.config = FakeConfig() |
---|
356 | self.debug = 1 # no config, so force debug mode ! |
---|
357 | |
---|
358 | def logInfo(self, message, level="info") : |
---|
359 | """Logs a message to CUPS' error_log file.""" |
---|
360 | try : |
---|
361 | sys.stderr.write("%s: %s v%s (PID %i) : %s\n" % (level.upper(), self.MyName, __version__, os.getpid(), message)) |
---|
362 | sys.stderr.flush() |
---|
363 | except IOError : |
---|
364 | pass |
---|
365 | |
---|
366 | def logDebug(self, message) : |
---|
367 | """Logs something to debug output if debug is enabled.""" |
---|
368 | if self.debug : |
---|
369 | self.logInfo(message, level="debug") |
---|
370 | |
---|
371 | def isTrue(self, option) : |
---|
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 |
---|
375 | else : |
---|
376 | return 0 |
---|
377 | |
---|
378 | def getGlobalOption(self, option, ignore=0) : |
---|
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) |
---|
382 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
383 | if not ignore : |
---|
384 | raise ConfigError, "Option %s not found in section global of %s" % (option, self.conffile) |
---|
385 | |
---|
386 | def getPrintQueueOption(self, printqueuename, option, ignore=0) : |
---|
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 : |
---|
390 | return self.config.get(printqueuename, option, raw=1) |
---|
391 | except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) : |
---|
392 | if globaloption is not None : |
---|
393 | return globaloption |
---|
394 | elif not ignore : |
---|
395 | raise ConfigError, "Option %s not found in section [%s] of %s" % (option, printqueuename, self.conffile) |
---|
396 | |
---|
397 | def enumBranches(self, printqueuename, branchtype="tee") : |
---|
398 | """Returns the list of branchtypes branches for a particular section's.""" |
---|
399 | branchbasename = "%s_" % branchtype.lower() |
---|
400 | try : |
---|
401 | globalbranches = [ (k, self.config.get("global", k)) for k in self.config.options("global") if k.startswith(branchbasename) ] |
---|
402 | except ConfigParser.NoSectionError, msg : |
---|
403 | raise ConfigError, "Invalid configuration file : %s" % msg |
---|
404 | try : |
---|
405 | sectionbranches = [ (k, self.config.get(printqueuename, k)) for k in self.config.options(printqueuename) if k.startswith(branchbasename) ] |
---|
406 | except ConfigParser.NoSectionError, msg : |
---|
407 | self.logInfo("No section for print queue %s : %s" % (printqueuename, msg)) |
---|
408 | sectionbranches = [] |
---|
409 | branches = {} |
---|
410 | for (k, v) in globalbranches : |
---|
411 | value = v.strip() |
---|
412 | if value : |
---|
413 | branches[k] = value |
---|
414 | for (k, v) in sectionbranches : |
---|
415 | value = v.strip() |
---|
416 | if value : |
---|
417 | branches[k] = value # overwrite any global option or set a new value |
---|
418 | else : |
---|
419 | del branches[k] # empty value disables a global option |
---|
420 | return branches |
---|
421 | |
---|
422 | def discoverOtherBackends(self) : |
---|
423 | """Discovers the other CUPS backends. |
---|
424 | |
---|
425 | Executes each existing backend in turn in device enumeration mode. |
---|
426 | Returns the list of available backends. |
---|
427 | """ |
---|
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. |
---|
431 | available = [] |
---|
432 | (directory, myname) = os.path.split(sys.argv[0]) |
---|
433 | if not directory : |
---|
434 | directory = "./" |
---|
435 | tmpdir = tempfile.gettempdir() |
---|
436 | lockfilename = os.path.join(tmpdir, "%s..LCK" % myname) |
---|
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) |
---|
444 | except OSError, e : |
---|
445 | if e.errno != errno.EPERM : |
---|
446 | # process doesn't exist anymore |
---|
447 | os.remove(lockfilename) |
---|
448 | |
---|
449 | if not os.path.exists(lockfilename) : |
---|
450 | lockfile = open(lockfilename, "w") |
---|
451 | lockfile.write("%i" % self.pid) |
---|
452 | lockfile.close() |
---|
453 | allbackends = [ os.path.join(directory, b) \ |
---|
454 | for b in os.listdir(directory) |
---|
455 | if os.access(os.path.join(directory, b), os.X_OK) \ |
---|
456 | and (b != myname)] |
---|
457 | for backend in allbackends : |
---|
458 | answer = os.popen(backend, "r") |
---|
459 | try : |
---|
460 | devices = [line.strip() for line in answer.readlines()] |
---|
461 | except : |
---|
462 | devices = [] |
---|
463 | status = answer.close() |
---|
464 | if status is None : |
---|
465 | for d in devices : |
---|
466 | # each line is of the form : |
---|
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 |
---|
483 | except ValueError : |
---|
484 | pass # ignore this 'bizarre' device |
---|
485 | else : |
---|
486 | if name.startswith('"') and name.endswith('"') : |
---|
487 | name = name[1:-1] |
---|
488 | if fullname.startswith('"') and fullname.endswith('"') : |
---|
489 | fullname = fullname[1:-1] |
---|
490 | available.append('%s %s:%s "%s+%s" "%s managed %s"' \ |
---|
491 | % (devicetype, self.myname, device, self.MyName, name, self.MyName, fullname)) |
---|
492 | os.remove(lockfilename) |
---|
493 | available.append('direct %s:// "%s+Nothing" "%s managed Virtual Printer"' \ |
---|
494 | % (self.myname, self.MyName, self.MyName)) |
---|
495 | return available |
---|
496 | |
---|
497 | def initBackend(self) : |
---|
498 | """Initializes the backend's attributes.""" |
---|
499 | # check that the DEVICE_URI environment variable's value is |
---|
500 | # prefixed with self.myname otherwise don't touch it. |
---|
501 | # If this is the case, we have to remove the prefix from |
---|
502 | # the environment before launching the real backend |
---|
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):] |
---|
508 | for i in range(2) : |
---|
509 | if device_uri.startswith("/") : |
---|
510 | device_uri = device_uri[1:] |
---|
511 | try : |
---|
512 | (backend, destination) = device_uri.split(":", 1) |
---|
513 | except ValueError : |
---|
514 | if not device_uri : |
---|
515 | self.logDebug("Not attached to an existing print queue.") |
---|
516 | backend = "" |
---|
517 | else : |
---|
518 | raise TeeError, "Invalid DEVICE_URI : %s\n" % device_uri |
---|
519 | |
---|
520 | self.JobId = sys.argv[1].strip() |
---|
521 | self.UserName = sys.argv[2].strip() or pwd.getpwuid(os.geteuid())[0] # use CUPS' user when printing test pages from CUPS' web interface |
---|
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 |
---|
527 | else : |
---|
528 | self.InputFile = None # read job's datas from stdin |
---|
529 | |
---|
530 | self.RealBackend = backend |
---|
531 | self.DeviceURI = device_uri |
---|
532 | self.PrinterName = os.environ.get("PRINTER", "") |
---|
533 | self.Directory = self.getPrintQueueOption(self.PrinterName, "directory") |
---|
534 | self.DataFile = os.path.join(self.Directory, "%s-%s-%s-%s" % (self.myname, self.PrinterName, self.UserName, self.JobId)) |
---|
535 | (ippfilename, ippmessage) = self.parseIPPRequestFile() |
---|
536 | self.ControlFile = ippfilename |
---|
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 |
---|
543 | (jbtype, self.JobBilling) = ippmessage.job_attributes.get("job-billing", (None, None)) |
---|
544 | |
---|
545 | def getCupsConfigDirectives(self, directives=[]) : |
---|
546 | """Retrieves some CUPS directives from its configuration file. |
---|
547 | |
---|
548 | Returns a mapping with lowercased directives as keys and |
---|
549 | their setting as values. |
---|
550 | """ |
---|
551 | dirvalues = {} |
---|
552 | cupsroot = os.environ.get("CUPS_SERVERROOT", "/etc/cups") |
---|
553 | cupsdconf = os.path.join(cupsroot, "cupsd.conf") |
---|
554 | try : |
---|
555 | conffile = open(cupsdconf, "r") |
---|
556 | except IOError : |
---|
557 | raise TeeError, "Unable to open %s" % cupsdconf |
---|
558 | else : |
---|
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] |
---|
565 | except : |
---|
566 | pass # ignore errors, we take the last value in any case. |
---|
567 | else : |
---|
568 | dirvalues[di] = val |
---|
569 | conffile.close() |
---|
570 | return dirvalues |
---|
571 | |
---|
572 | def parseIPPRequestFile(self) : |
---|
573 | """Parses the IPP message file and returns a tuple (filename, parsedvalue).""" |
---|
574 | cupsdconf = self.getCupsConfigDirectives(["RequestRoot"]) |
---|
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) |
---|
578 | else : |
---|
579 | ippmessagefile = "c%s" % self.JobId |
---|
580 | ippmessagefile = os.path.join(requestroot, ippmessagefile) |
---|
581 | ippmessage = {} |
---|
582 | try : |
---|
583 | ippdatafile = open(ippmessagefile) |
---|
584 | except : |
---|
585 | self.logInfo("Unable to open IPP message file %s" % ippmessagefile, "warn") |
---|
586 | else : |
---|
587 | self.logDebug("Parsing of IPP message file %s begins." % ippmessagefile) |
---|
588 | try : |
---|
589 | ippmessage = IPPRequest(ippdatafile.read()) |
---|
590 | ippmessage.parse() |
---|
591 | except IPPError, msg : |
---|
592 | self.logInfo("Error while parsing %s : %s" % (ippmessagefile, msg), "warn") |
---|
593 | else : |
---|
594 | self.logDebug("Parsing of IPP message file %s ends." % ippmessagefile) |
---|
595 | ippdatafile.close() |
---|
596 | return (ippmessagefile, ippmessage) |
---|
597 | |
---|
598 | def exportAttributes(self) : |
---|
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 |
---|
604 | os.environ["TEAJOBSIZE"] = str(self.JobSize) |
---|
605 | os.environ["TEAMD5SUM"] = self.JobMD5Sum |
---|
606 | os.environ["TEACLIENTHOST"] = self.ClientHost or "" |
---|
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 "" |
---|
613 | os.environ["TEABILLING"] = self.JobBilling or "" |
---|
614 | os.environ["TEACONTROLFILE"] = self.ControlFile |
---|
615 | |
---|
616 | def saveDatasAndCheckSum(self) : |
---|
617 | """Saves the input datas into a static file.""" |
---|
618 | self.logDebug("Duplicating data stream into %s" % self.DataFile) |
---|
619 | mustclose = 0 |
---|
620 | if self.InputFile is not None : |
---|
621 | infile = open(self.InputFile, "rb") |
---|
622 | mustclose = 1 |
---|
623 | else : |
---|
624 | infile = sys.stdin |
---|
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 | |
---|
642 | CHUNK = 64*1024 # read 64 Kb at a time |
---|
643 | dummy = 0 |
---|
644 | sizeread = 0 |
---|
645 | checksum = md5.new() |
---|
646 | outfile = open(self.DataFile, "wb") |
---|
647 | while 1 : |
---|
648 | data = infile.read(CHUNK) |
---|
649 | if not data : |
---|
650 | break |
---|
651 | sizeread += len(data) |
---|
652 | outfile.write(data) |
---|
653 | checksum.update(data) |
---|
654 | if not (dummy % 32) : # Only display every 2 Mb |
---|
655 | self.logDebug("%s bytes saved..." % sizeread) |
---|
656 | dummy += 1 |
---|
657 | outfile.close() |
---|
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 | |
---|
666 | if mustclose : |
---|
667 | infile.close() |
---|
668 | |
---|
669 | self.logDebug("%s bytes saved..." % sizeread) |
---|
670 | self.JobSize = sizeread |
---|
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)) |
---|
674 | |
---|
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) |
---|
679 | |
---|
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) |
---|
684 | |
---|
685 | def runBranches(self) : |
---|
686 | """Launches each hook defined for the current print queue.""" |
---|
687 | self.isCancelled = 0 # did a prehook cancel the print job ? |
---|
688 | self.gotSigTerm = 0 |
---|
689 | signal.signal(signal.SIGTERM, self.sigtermHandler) |
---|
690 | serialize = self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1)) |
---|
691 | self.pipes = { 0: (0, 1) } |
---|
692 | branches = self.enumBranches(self.PrinterName, "prehook") |
---|
693 | for b in branches.keys() : |
---|
694 | self.pipes[b.split("_", 1)[1]] = os.pipe() |
---|
695 | retcode = self.runCommands("prehook", branches, serialize) |
---|
696 | for p in [ (k, v) for (k, v) in self.pipes.items() if k != 0 ] : |
---|
697 | os.close(p[1][1]) |
---|
698 | if not self.isCancelled and not self.gotSigTerm : |
---|
699 | if self.RealBackend : |
---|
700 | retcode = self.runOriginalBackend() |
---|
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) |
---|
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) : |
---|
711 | self.logInfo("An error occured during the execution of posthooks.", "warn") |
---|
712 | for p in [ (k, v) for (k, v) in self.pipes.items() if k != 0 ] : |
---|
713 | os.close(p[1][0]) |
---|
714 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
---|
715 | if not retcode : |
---|
716 | self.logInfo("OK") |
---|
717 | else : |
---|
718 | self.logInfo("An error occured, please check CUPS' error_log file.") |
---|
719 | return retcode |
---|
720 | |
---|
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 |
---|
724 | pid = os.fork() |
---|
725 | if pid == 0 : |
---|
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) |
---|
734 | except OSError, msg : |
---|
735 | self.logDebug("execl() failed: %s" % msg) |
---|
736 | os._exit(-1) |
---|
737 | status = os.waitpid(pid, 0)[1] |
---|
738 | if os.WIFEXITED(status) : |
---|
739 | return os.WEXITSTATUS(status) |
---|
740 | return -1 |
---|
741 | |
---|
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) |
---|
747 | if bname not in self.pipes.keys() : |
---|
748 | bname = 0 |
---|
749 | if btype == "prehook" : |
---|
750 | return self.stdioRedirSystem(command, 0, self.pipes[bname][1]) |
---|
751 | else : |
---|
752 | return self.stdioRedirSystem(command, self.pipes[bname][0]) |
---|
753 | |
---|
754 | def runCommands(self, btype, branches, serialize) : |
---|
755 | """Runs the commands for a particular branch type.""" |
---|
756 | exitcode = 0 |
---|
757 | btype = btype.lower() |
---|
758 | btypetitle = btype.title() |
---|
759 | branchlist = branches.keys() |
---|
760 | branchlist.sort() |
---|
761 | if serialize : |
---|
762 | self.logDebug("Begin serialized %ss" % btypetitle) |
---|
763 | for branch in branchlist : |
---|
764 | if self.gotSigTerm : |
---|
765 | break |
---|
766 | retcode = self.runCommand(branch, branches[branch]) |
---|
767 | self.logDebug("Exit code for %s %s on printer %s is %s" % (btype, branch, self.PrinterName, retcode)) |
---|
768 | if retcode : |
---|
769 | if (btype == "prehook") and (retcode == 255) : # -1 |
---|
770 | self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch)) |
---|
771 | self.isCancelled = 1 |
---|
772 | else : |
---|
773 | self.logInfo("%s %s on printer %s didn't exit successfully." % (btypetitle, branch, self.PrinterName), "error") |
---|
774 | exitcode = 1 |
---|
775 | self.logDebug("End serialized %ss" % btypetitle) |
---|
776 | else : |
---|
777 | self.logDebug("Begin forked %ss" % btypetitle) |
---|
778 | pids = {} |
---|
779 | for branch in branchlist : |
---|
780 | if self.gotSigTerm : |
---|
781 | break |
---|
782 | pid = os.fork() |
---|
783 | if pid : |
---|
784 | pids[branch] = pid |
---|
785 | else : |
---|
786 | os._exit(self.runCommand(branch, branches[branch])) |
---|
787 | for (branch, pid) in pids.items() : |
---|
788 | retcode = os.waitpid(pid, 0)[1] |
---|
789 | if os.WIFEXITED(retcode) : |
---|
790 | retcode = os.WEXITSTATUS(retcode) |
---|
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)) |
---|
794 | if retcode : |
---|
795 | if (btype == "prehook") and (retcode == 255) : # -1 |
---|
796 | self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch)) |
---|
797 | self.isCancelled = 1 |
---|
798 | else : |
---|
799 | self.logInfo("%s %s (PID %s) on printer %s didn't exit successfully." % (btypetitle, branch, pid, self.PrinterName), "error") |
---|
800 | exitcode = 1 |
---|
801 | self.logDebug("End forked %ss" % btypetitle) |
---|
802 | return exitcode |
---|
803 | |
---|
804 | def runOriginalBackend(self) : |
---|
805 | """Launches the original backend.""" |
---|
806 | originalbackend = os.path.join(os.path.split(sys.argv[0])[0], self.RealBackend) |
---|
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 : |
---|
813 | f = open(self.DataFile, "rb") |
---|
814 | os.dup2(f.fileno(), 0) |
---|
815 | f.close() |
---|
816 | try : |
---|
817 | os.execve(originalbackend, arguments, os.environ) |
---|
818 | except OSError, msg : |
---|
819 | self.logDebug("execve() failed: %s" % msg) |
---|
820 | os._exit(-1) |
---|
821 | killed = 0 |
---|
822 | status = -1 |
---|
823 | while status == -1 : |
---|
824 | try : |
---|
825 | status = os.waitpid(pid, 0)[1] |
---|
826 | except OSError, (err, msg) : |
---|
827 | if (err == 4) and self.gotSigTerm : |
---|
828 | os.kill(pid, signal.SIGTERM) |
---|
829 | killed = 1 |
---|
830 | if os.WIFEXITED(status) : |
---|
831 | status = os.WEXITSTATUS(status) |
---|
832 | if status : |
---|
833 | self.logInfo("CUPS backend %s returned %d." % (originalbackend,\ |
---|
834 | status), "error") |
---|
835 | return status |
---|
836 | elif not killed : |
---|
837 | self.logInfo("CUPS backend %s died abnormally." % originalbackend,\ |
---|
838 | "error") |
---|
839 | return -1 |
---|
840 | else : |
---|
841 | return 1 |
---|
842 | |
---|
843 | if __name__ == "__main__" : |
---|
844 | # This is a CUPS backend, we should act and die like a CUPS backend |
---|
845 | wrapper = CupsBackend() |
---|
846 | if len(sys.argv) == 1 : |
---|
847 | print "\n".join(wrapper.discoverOtherBackends()) |
---|
848 | sys.exit(0) |
---|
849 | elif len(sys.argv) not in (6, 7) : |
---|
850 | sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\ |
---|
851 | % sys.argv[0]) |
---|
852 | sys.exit(1) |
---|
853 | else : |
---|
854 | try : |
---|
855 | wrapper.readConfig() |
---|
856 | wrapper.initBackend() |
---|
857 | wrapper.saveDatasAndCheckSum() |
---|
858 | wrapper.exportAttributes() |
---|
859 | retcode = wrapper.runBranches() |
---|
860 | wrapper.cleanUp() |
---|
861 | except SystemExit, e : |
---|
862 | retcode = e.code |
---|
863 | except : |
---|
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]) |
---|
868 | msg = "ERROR: ".join(["%s (PID %s) : %s\n" % (wrapper.MyName, \ |
---|
869 | wrapper.pid, l) \ |
---|
870 | for l in (["ERROR: Tea4CUPS v%s" % __version__] + lines)]) |
---|
871 | sys.stderr.write(msg) |
---|
872 | sys.stderr.flush() |
---|
873 | retcode = 1 |
---|
874 | sys.exit(retcode) |
---|