root / tea4cups / trunk / tea4cups @ 648

Revision 648, 35.3 kB (checked in by jerome, 19 years ago)

3.00 is now out !
Official packages available later in the night...

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