root / tea4cups / trunk / tea4cups @ 659

Revision 659, 36.9 kB (checked in by jerome, 19 years ago)

Added filters.
Added the onfail directive to tea4cups.conf

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