root / tea4cups / trunk / tea4cups @ 655

Revision 655, 35.5 kB (checked in by jerome, 19 years ago)

Renamed a method

  • 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
36from struct import pack, unpack
37
38version = "3.02_unofficial"
39
40class 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
49class ConfigError(TeeError) :
50    """Configuration related exceptions."""
51    pass
52
53class IPPError(TeeError) :
54    """IPP related exceptions."""
55    pass
56
57class 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
330class 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
336class 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        CHUNK = 64*1024         # read 64 Kb at a time
626        dummy = 0
627        sizeread = 0
628        checksum = md5.new()
629        outfile = open(self.DataFile, "wb")
630        while 1 :
631            data = infile.read(CHUNK)
632            if not data :
633                break
634            sizeread += len(data)
635            outfile.write(data)
636            checksum.update(data)
637            if not (dummy % 32) : # Only display every 2 Mb
638                self.logDebug("%s bytes saved..." % sizeread)
639            dummy += 1
640        outfile.close()
641        if mustclose :
642            infile.close()
643        self.JobSize = sizeread
644        self.JobMD5Sum = checksum.hexdigest()
645        self.logDebug("Job %s is %s bytes long." % (self.JobId, self.JobSize))
646        self.logDebug("Job %s MD5 sum is %s" % (self.JobId, self.JobMD5Sum))
647
648    def cleanUp(self) :
649        """Cleans up the place."""
650        if not self.isTrue(self.getPrintQueueOption(self.PrinterName, "keepfiles", ignore=1)) :
651            os.remove(self.DataFile)
652
653    def sigtermHandler(self, signum, frame) :
654        """Sets an attribute whenever SIGTERM is received."""
655        self.gotSigTerm = 1
656        self.logInfo("SIGTERM received for Job %s." % self.JobId)
657
658    def runBranches(self) :
659        """Launches each hook defined for the current print queue."""
660        self.isCancelled = 0    # did a prehook cancel the print job ?
661        self.gotSigTerm = 0
662        signal.signal(signal.SIGTERM, self.sigtermHandler)
663        serialize = self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1))
664        self.pipes = { 0: (0, 1) }
665        branches = self.enumBranches(self.PrinterName, "prehook")
666        for b in branches :
667            self.pipes[b.split("_", 1)[1]] = os.pipe()
668        retcode = self.runCommands("prehook", branches, serialize)
669        for p in [ (k, v) for (k, v) in self.pipes.items() if k != 0 ] :
670            os.close(p[1][1])
671        if not self.isCancelled and not self.gotSigTerm :
672            if self.RealBackend :
673                retcode = self.runOriginalBackend()
674            if not self.gotSigTerm :
675                os.environ["TEASTATUS"] = str(retcode)
676                branches = self.enumBranches(self.PrinterName, "posthook")
677                if self.runCommands("posthook", branches, serialize) :
678                    self.logInfo("An error occured during the execution of posthooks.", "warn")
679        for p in [ (k, v) for (k, v) in self.pipes.items() if k != 0 ] :
680            os.close(p[1][0])
681        signal.signal(signal.SIGTERM, signal.SIG_IGN)
682        if not retcode :
683            self.logInfo("OK")
684        else :
685            self.logInfo("An error occured, please check CUPS' error_log file.")
686        return retcode
687
688    def stdioRedirSystem(self, cmd, stdin=0, stdout=1) :
689        """Launches a command with stdio redirected."""
690        # Code contributed by Peter Stuge on May 23rd and June 7th 2005
691        pid = os.fork()
692        if pid == 0 :
693            if stdin != 0 :
694                os.dup2(stdin, 0)
695                os.close(stdin)
696            if stdout != 1 :
697                os.dup2(stdout, 1)
698                os.close(stdout)
699            try :
700                os.execl("/bin/sh", "sh", "-c", cmd)
701            except OSError, msg :
702                self.logDebug("execl() failed: %s" % msg)
703            os._exit(-1)
704        status = os.waitpid(pid, 0)[1]
705        if os.WIFEXITED(status) :
706            return os.WEXITSTATUS(status)
707        return -1
708
709    def runCommand(self, branch, command) :
710        """Runs a particular branch command."""
711        # Code contributed by Peter Stuge on June 7th 2005
712        self.logDebug("Launching %s : %s" % (branch, command))
713        btype, bname = branch.split("_", 1)
714        if bname not in self.pipes.keys() :
715            bname = 0
716        if btype == "prehook" :
717            return self.stdioRedirSystem(command, 0, self.pipes[bname][1])
718        else :
719            return self.stdioRedirSystem(command, self.pipes[bname][0])
720
721    def runCommands(self, btype, branches, serialize) :
722        """Runs the commands for a particular branch type."""
723        exitcode = 0
724        btype = btype.lower()
725        btypetitle = btype.title()
726        branchlist = branches.keys()
727        branchlist.sort()
728        if serialize :
729            self.logDebug("Begin serialized %ss" % btypetitle)
730            for branch in branchlist :
731                if self.gotSigTerm :
732                    break
733                retcode = self.runCommand(branch, branches[branch])
734                self.logDebug("Exit code for %s %s on printer %s is %s" % (btype, branch, self.PrinterName, retcode))
735                if retcode :
736                    if (btype == "prehook") and (retcode == 255) : # -1
737                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
738                        self.isCancelled = 1
739                    else :
740                        self.logInfo("%s %s on printer %s didn't exit successfully." % (btypetitle, branch, self.PrinterName), "error")
741                        exitcode = 1
742            self.logDebug("End serialized %ss" % btypetitle)
743        else :
744            self.logDebug("Begin forked %ss" % btypetitle)
745            pids = {}
746            for branch in branchlist :
747                if self.gotSigTerm :
748                    break
749                pid = os.fork()
750                if pid :
751                    pids[branch] = pid
752                else :
753                    os._exit(self.runCommand(branch, branches[branch]))
754            for (branch, pid) in pids.items() :
755                retcode = os.waitpid(pid, 0)[1]
756                if os.WIFEXITED(retcode) :
757                    retcode = os.WEXITSTATUS(retcode)
758                else :
759                    retcode = -1
760                self.logDebug("Exit code for %s %s (PID %s) on printer %s is %s" % (btype, branch, pid, self.PrinterName, retcode))
761                if retcode :
762                    if (btype == "prehook") and (retcode == 255) : # -1
763                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
764                        self.isCancelled = 1
765                    else :
766                        self.logInfo("%s %s (PID %s) on printer %s didn't exit successfully." % (btypetitle, branch, pid, self.PrinterName), "error")
767                        exitcode = 1
768            self.logDebug("End forked %ss" % btypetitle)
769        return exitcode
770
771    def runOriginalBackend(self) :
772        """Launches the original backend."""
773        originalbackend = os.path.join(os.path.split(sys.argv[0])[0], self.RealBackend)
774        arguments = [os.environ["DEVICE_URI"]] + sys.argv[1:]
775        self.logDebug("Starting original backend %s with args %s" % (originalbackend, " ".join(['"%s"' % a for a in arguments])))
776
777        pid = os.fork()
778        if pid == 0 :
779            if self.InputFile is None :
780                f = open(self.DataFile, "rb")
781                os.dup2(f.fileno(), 0)
782                f.close()
783            try :
784                os.execve(originalbackend, arguments, os.environ)
785            except OSError, msg :
786                self.logDebug("execve() failed: %s" % msg)
787            os._exit(-1)
788        killed = 0
789        status = -1
790        while status == -1 :
791            try :
792                status = os.waitpid(pid, 0)[1]
793            except OSError, (err, msg) :
794                if (err == 4) and self.gotSigTerm :
795                    os.kill(pid, signal.SIGTERM)
796                    killed = 1
797        if os.WIFEXITED(status) :
798            status = os.WEXITSTATUS(status)
799            if status :
800              self.logInfo("CUPS backend %s returned %d." % (originalbackend,\
801                                                             status), "error")
802            return status
803        elif not killed :
804            self.logInfo("CUPS backend %s died abnormally." % originalbackend,\
805                                                              "error")
806            return -1
807        else :
808            return 1
809
810if __name__ == "__main__" :
811    # This is a CUPS backend, we should act and die like a CUPS backend
812    wrapper = CupsBackend()
813    if len(sys.argv) == 1 :
814        print "\n".join(wrapper.discoverOtherBackends())
815        sys.exit(0)
816    elif len(sys.argv) not in (6, 7) :
817        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\
818                              % sys.argv[0])
819        sys.exit(1)
820    else :
821        try :
822            wrapper.readConfig()
823            wrapper.initBackend()
824            wrapper.saveDatasAndCheckSum()
825            wrapper.exportAttributes()
826            retcode = wrapper.runBranches()
827            wrapper.cleanUp()
828        except SystemExit, e :
829            retcode = e.code
830        except :
831            import traceback
832            lines = []
833            for line in traceback.format_exception(*sys.exc_info()) :
834                lines.extend([l for l in line.split("\n") if l])
835            msg = "ERROR: ".join(["%s (PID %s) : %s\n" % (wrapper.MyName, \
836                                                          wrapper.pid, l) \
837                        for l in (["ERROR: Tea4CUPS v%s" % version] + lines)])
838            sys.stderr.write(msg)
839            sys.stderr.flush()
840            retcode = 1
841        sys.exit(retcode)
Note: See TracBrowser for help on using the browser.