root / tea4cups / trunk / tea4cups @ 583

Revision 583, 21.2 kB (checked in by jerome, 19 years ago)

Better handling of DEVICE_URI

  • 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# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23#
24
25import sys
26import os
27import errno
28import md5
29import cStringIO
30import shlex
31import tempfile
32import ConfigParser
33from struct import unpack
34
35class TeeError(Exception):
36    """Base exception for Tea4CUPS related stuff."""
37    def __init__(self, message = ""):
38        self.message = message
39        Exception.__init__(self, message)
40    def __repr__(self):
41        return self.message
42    __str__ = __repr__
43   
44class ConfigError(TeeError) :   
45    """Configuration related exceptions."""
46    pass 
47   
48class IPPError(TeeError) :   
49    """IPP related exceptions."""
50    pass 
51   
52# Some IPP constants   
53OPERATION_ATTRIBUTES_TAG = 0x01
54JOB_ATTRIBUTES_TAG = 0x02
55END_OF_ATTRIBUTES_TAG = 0x03
56PRINTER_ATTRIBUTES_TAG = 0x04
57UNSUPPORTED_ATTRIBUTES_TAG = 0x05
58
59class IPPMessage :
60    """A class for IPP message files."""
61    def __init__(self, data) :
62        """Initializes an IPP Message object."""
63        self.data = data
64        self._attributes = {}
65        self.curname = None
66        self.tags = [ None ] * 256      # by default all tags reserved
67       
68        # Delimiter tags
69        self.tags[0x01] = "operation-attributes-tag"
70        self.tags[0x02] = "job-attributes-tag"
71        self.tags[0x03] = "end-of-attributes-tag"
72        self.tags[0x04] = "printer-attributes-tag"
73        self.tags[0x05] = "unsupported-attributes-tag"
74       
75        # out of band values
76        self.tags[0x10] = "unsupported"
77        self.tags[0x11] = "reserved-for-future-default"
78        self.tags[0x12] = "unknown"
79        self.tags[0x13] = "no-value"
80       
81        # integer values
82        self.tags[0x20] = "generic-integer"
83        self.tags[0x21] = "integer"
84        self.tags[0x22] = "boolean"
85        self.tags[0x23] = "enum"
86       
87        # octetString
88        self.tags[0x30] = "octetString-with-an-unspecified-format"
89        self.tags[0x31] = "dateTime"
90        self.tags[0x32] = "resolution"
91        self.tags[0x33] = "rangeOfInteger"
92        self.tags[0x34] = "reserved-for-collection"
93        self.tags[0x35] = "textWithLanguage"
94        self.tags[0x36] = "nameWithLanguage"
95       
96        # character strings
97        self.tags[0x20] = "generic-character-string"
98        self.tags[0x41] = "textWithoutLanguage"
99        self.tags[0x42] = "nameWithoutLanguage"
100        # self.tags[0x43] = "reserved"
101        self.tags[0x44] = "keyword"
102        self.tags[0x45] = "uri"
103        self.tags[0x46] = "uriScheme"
104        self.tags[0x47] = "charset"
105        self.tags[0x48] = "naturalLanguage"
106        self.tags[0x49] = "mimeMediaType"
107       
108        # now parses the IPP message
109        self.parse()
110       
111    def __getattr__(self, attrname) :   
112        """Allows self.attributes to return the attributes names."""
113        if attrname == "attributes" :
114            keys = self._attributes.keys()
115            keys.sort()
116            return keys
117        raise AttributeError, attrname
118           
119    def __getitem__(self, ippattrname) :   
120        """Fakes a dictionnary d['key'] notation."""
121        value = self._attributes.get(ippattrname)
122        if value is not None :
123            if len(value) == 1 :
124                value = value[0]
125        return value       
126    get = __getitem__   
127       
128    def parseTag(self) :   
129        """Extracts information from an IPP tag."""
130        pos = self.position
131        valuetag = self.tags[ord(self.data[pos])]
132        # print valuetag.get("name")
133        pos += 1
134        posend = pos2 = pos + 2
135        namelength = unpack(">H", self.data[pos:pos2])[0]
136        if not namelength :
137            name = self.curname
138        else :   
139            posend += namelength
140            self.curname = name = self.data[pos2:posend]
141        pos2 = posend + 2
142        valuelength = unpack(">H", self.data[posend:pos2])[0]
143        posend = pos2 + valuelength
144        value = self.data[pos2:posend]
145        oldval = self._attributes.setdefault(name, [])
146        oldval.append(value)
147        return posend - self.position
148       
149    def operation_attributes_tag(self) : 
150        """Indicates that the parser enters into an operation-attributes-tag group."""
151        return self.parseTag()
152       
153    def job_attributes_tag(self) : 
154        """Indicates that the parser enters into an operation-attributes-tag group."""
155        return self.parseTag()
156       
157    def printer_attributes_tag(self) : 
158        """Indicates that the parser enters into an operation-attributes-tag group."""
159        return self.parseTag()
160       
161    def parse(self) :
162        """Parses an IPP Message.
163       
164           NB : Only a subset of RFC2910 is implemented.
165           We are only interested in textual informations for now anyway.
166        """
167        self.version = "%s.%s" % (ord(self.data[0]), ord(self.data[1]))
168        self.operation_id = "0x%04x" % unpack(">H", self.data[2:4])[0]
169        self.request_id = "0x%08x" % unpack(">I", self.data[4:8])[0]
170        self.position = 8
171        try :
172            tag = ord(self.data[self.position])
173            while tag != END_OF_ATTRIBUTES_TAG :
174                self.position += 1
175                name = self.tags[tag]
176                if name is not None :
177                    func = getattr(self, name.replace("-", "_"), None)
178                    if func is not None :
179                        self.position += func()
180                        if ord(self.data[self.position]) > UNSUPPORTED_ATTRIBUTES_TAG :
181                            self.position -= 1
182                            continue
183                tag = ord(self.data[self.position])
184        except IndexError :
185            raise IPPError, "Unexpected end of IPP message."
186           
187class FakeConfig :   
188    """Fakes a configuration file parser."""
189    def get(self, section, option, raw=0) :
190        """Fakes the retrieval of a global option."""
191        raise ConfigError, "Invalid configuration file : no option %s in section [%s]" % (option, section)
192       
193class CupsBackend :
194    """Base class for tools with no database access."""
195    def __init__(self) :
196        """Initializes the CUPS backend wrapper."""
197        self.MyName = "Tea4CUPS"
198        self.myname = "tea4cups"
199        self.pid = os.getpid()
200        confdir = os.environ.get("CUPS_SERVERROOT", ".") 
201        self.conffile = os.path.join(confdir, "%s.conf" % self.myname)
202        if os.path.isfile(self.conffile) :
203            self.config = ConfigParser.ConfigParser()
204            self.config.read([self.conffile])
205            self.debug = self.isTrue(self.getGlobalOption("debug", ignore=1))
206        else :   
207            self.config = FakeConfig()
208            self.debug = 1      # no config, so force debug mode !
209       
210    def logDebug(self, message) :   
211        """Logs something to debug output if debug is enabled."""
212        if self.debug :
213            sys.stderr.write("DEBUG: %s (PID %i) : %s\n" % (self.MyName, self.pid, message))
214            sys.stderr.flush()
215           
216    def logInfo(self, message, level="info") :       
217        """Logs a message to CUPS' error_log file."""
218        sys.stderr.write("%s: %s (PID %i) : %s\n" % (level.upper(), self.MyName, self.pid, message))
219        sys.stderr.flush()
220       
221    def isTrue(self, option) :       
222        """Returns 1 if option is set to true, else 0."""
223        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
224            return 1
225        else :   
226            return 0
227                       
228    def getGlobalOption(self, option, ignore=0) :   
229        """Returns an option from the global section, or raises a ConfigError if ignore is not set, else returns None."""
230        try :
231            return self.config.get("global", option, raw=1)
232        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
233            if not ignore :
234                raise ConfigError, "Option %s not found in section global of %s" % (option, self.conffile)
235               
236    def getPrintQueueOption(self, printqueuename, option, ignore=0) :   
237        """Returns an option from the printer section, or the global section, or raises a ConfigError."""
238        globaloption = self.getGlobalOption(option, ignore=1)
239        try :
240            return self.config.get(printqueuename, option, raw=1)
241        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
242            if globaloption is not None :
243                return globaloption
244            elif not ignore :
245                raise ConfigError, "Option %s not found in section [%s] of %s" % (option, printqueuename, self.conffile)
246               
247    def enumTeeBranches(self, printqueuename) :
248        """Returns the list of branches for a particular section's Tee."""
249        try :
250            globalbranches = [ (k, v) for (k, v) in self.config.items("global") if k.startswith("tee_") ]
251        except ConfigParser.NoSectionError, msg :   
252            raise ConfigError, "Invalid configuration file : %s" % msg
253        try :
254            sectionbranches = [ (k, v) for (k, v) in self.config.items(printqueuename) if k.startswith("tee_") ]
255        except ConfigParser.NoSectionError, msg :   
256            self.logInfo("No section for print queue %s : %s" % (printqueuename, msg))
257            sectionbranches = []
258        branches = {}
259        for (k, v) in globalbranches :
260            value = v.strip()
261            if value :
262                branches[k] = value
263        for (k, v) in sectionbranches :   
264            value = v.strip()
265            if value :
266                branches[k] = value # overwrite any global option or set a new value
267            else :   
268                del branches[k] # empty value disables a global option
269        return branches
270       
271    def discoverOtherBackends(self) :   
272        """Discovers the other CUPS backends.
273       
274           Executes each existing backend in turn in device enumeration mode.
275           Returns the list of available backends.
276        """
277        # Unfortunately this method can't output any debug information
278        # to stdout or stderr, else CUPS considers that the device is
279        # not available.
280        available = []
281        (directory, myname) = os.path.split(sys.argv[0])
282        tmpdir = tempfile.gettempdir()
283        lockfilename = os.path.join(tmpdir, "%s..LCK" % myname)
284        if os.path.exists(lockfilename) :
285            lockfile = open(lockfilename, "r")
286            pid = int(lockfile.read())
287            lockfile.close()
288            try :
289                # see if the pid contained in the lock file is still running
290                os.kill(pid, 0)
291            except OSError, e :   
292                if e.errno != errno.EPERM :
293                    # process doesn't exist anymore
294                    os.remove(lockfilename)
295           
296        if not os.path.exists(lockfilename) :
297            lockfile = open(lockfilename, "w")
298            lockfile.write("%i" % self.pid)
299            lockfile.close()
300            allbackends = [ os.path.join(directory, b) \
301                                for b in os.listdir(directory) 
302                                    if os.access(os.path.join(directory, b), os.X_OK) \
303                                        and (b != myname)] 
304            for backend in allbackends :                           
305                answer = os.popen(backend, "r")
306                try :
307                    devices = [line.strip() for line in answer.readlines()]
308                except :   
309                    devices = []
310                status = answer.close()
311                if status is None :
312                    for d in devices :
313                        # each line is of the form :
314                        # 'xxxx xxxx "xxxx xxx" "xxxx xxx"'
315                        # so we have to decompose it carefully
316                        fdevice = cStringIO.StringIO(d)
317                        tokenizer = shlex.shlex(fdevice)
318                        tokenizer.wordchars = tokenizer.wordchars + \
319                                                        r".:,?!~/\_$*-+={}[]()#"
320                        arguments = []
321                        while 1 :
322                            token = tokenizer.get_token()
323                            if token :
324                                arguments.append(token)
325                            else :
326                                break
327                        fdevice.close()
328                        try :
329                            (devicetype, device, name, fullname) = arguments
330                        except ValueError :   
331                            pass    # ignore this 'bizarre' device
332                        else :   
333                            if name.startswith('"') and name.endswith('"') :
334                                name = name[1:-1]
335                            if fullname.startswith('"') and fullname.endswith('"') :
336                                fullname = fullname[1:-1]
337                            available.append('%s %s:%s "%s+%s" "%s managed %s"' \
338                                                 % (devicetype, self.myname, device, self.MyName, name, self.MyName, fullname))
339            os.remove(lockfilename)
340        return available
341                       
342    def initBackend(self) :   
343        """Initializes the backend's attributes."""
344        # check that the DEVICE_URI environment variable's value is
345        # prefixed with self.myname otherwise don't touch it.
346        # If this is the case, we have to remove the prefix from
347        # the environment before launching the real backend
348        muststartwith = "%s:" % self.myname
349        device_uri = os.environ.get("DEVICE_URI", "")
350        if device_uri.startswith(muststartwith) :
351            fulldevice_uri = device_uri[:]
352            device_uri = fulldevice_uri[len(muststartwith):]
353            for i in range(2) :
354                if device_uri.startswith("/") : 
355                    device_uri = device_uri[1:]
356        try :
357            (backend, destination) = device_uri.split(":", 1) 
358        except ValueError :   
359            if not device_uri :
360                self.logInfo("Not attached to an existing print queue.")
361                backend = ""
362            else :   
363                raise TeeError, "Invalid DEVICE_URI : %s\n" % device_uri
364       
365        self.JobId = sys.argv[1].strip()
366        self.UserName = sys.argv[2].strip()
367        self.Title = sys.argv[3].strip()
368        self.Copies = int(sys.argv[4].strip())
369        self.Options = sys.argv[5].strip()
370        if len(sys.argv) == 7 :
371            self.InputFile = sys.argv[6] # read job's datas from file
372        else :   
373            self.InputFile = None        # read job's datas from stdin
374           
375        self.RealBackend = backend
376        self.DeviceURI = device_uri
377        self.PrinterName = os.environ.get("PRINTER", "")
378        self.Directory = self.getPrintQueueOption(self.PrinterName, "directory")
379        self.DataFile = os.path.join(self.Directory, "%s-%s-%s-%s" % (self.myname, self.PrinterName, self.UserName, self.JobId))
380        self.ClientHost = self.extractJobOriginatingHostName()
381           
382    def getCupsConfigDirectives(self, directives=[]) :
383        """Retrieves some CUPS directives from its configuration file.
384       
385           Returns a mapping with lowercased directives as keys and
386           their setting as values.
387        """
388        dirvalues = {} 
389        cupsroot = os.environ.get("CUPS_SERVERROOT", "/etc/cups")
390        cupsdconf = os.path.join(cupsroot, "cupsd.conf")
391        try :
392            conffile = open(cupsdconf, "r")
393        except IOError :   
394            raise TeeError, "Unable to open %s" % cupsdconf
395        else :   
396            for line in conffile.readlines() :
397                linecopy = line.strip().lower()
398                for di in [d.lower() for d in directives] :
399                    if linecopy.startswith("%s " % di) :
400                        try :
401                            val = line.split()[1]
402                        except :   
403                            pass # ignore errors, we take the last value in any case.
404                        else :   
405                            dirvalues[di] = val
406            conffile.close()           
407        return dirvalues       
408           
409    def extractJobOriginatingHostName(self) :       
410        """Extracts the client's hostname or IP address from the CUPS message file for current job."""
411        cupsdconf = self.getCupsConfigDirectives(["RequestRoot"])
412        requestroot = cupsdconf.get("requestroot", "/var/spool/cups")
413        if (len(self.JobId) < 5) and self.JobId.isdigit() :
414            ippmessagefile = "c%05i" % int(self.JobId)
415        else :   
416            ippmessagefile = "c%s" % self.JobId
417        ippmessagefile = os.path.join(requestroot, ippmessagefile)
418        ippmessage = {}
419        try :
420            ippdatafile = open(ippmessagefile)
421        except :   
422            self.logInfo("Unable to open IPP message file %s" % ippmessagefile, "warn")
423        else :   
424            self.logDebug("Parsing of IPP message file %s begins." % ippmessagefile)
425            try :
426                ippmessage = IPPMessage(ippdatafile.read())
427            except IPPError, msg :   
428                self.logInfo("Error while parsing %s : %s" % (ippmessagefile, msg), "warn")
429            else :   
430                self.logDebug("Parsing of IPP message file %s ends." % ippmessagefile)
431            ippdatafile.close()
432        return ippmessage.get("job-originating-host-name")   
433               
434    def exportAttributes(self) :   
435        """Exports our backend's attributes to the environment."""
436        os.environ["DEVICE_URI"] = self.DeviceURI       # WARNING !
437        os.environ["TEAPRINTERNAME"] = self.PrinterName
438        os.environ["TEADIRECTORY"] = self.Directory
439        os.environ["TEADATAFILE"] = self.DataFile
440        os.environ["TEAJOBSIZE"] = str(self.JobSize)
441        os.environ["TEAMD5SUM"] = self.JobMD5Sum
442        os.environ["TEACLIENTHOST"] = self.ClientHost or ""
443        os.environ["TEAJOBID"] = self.JobId
444        os.environ["TEAUSERNAME"] = self.UserName
445        os.environ["TEATITLE"] = self.Title
446        os.environ["TEACOPIES"] = str(self.Copies)
447        os.environ["TEAOPTIONS"] = self.Options
448        os.environ["TEAINPUTFILE"] = self.InputFile or ""
449       
450    def saveDatasAndCheckSum(self) :
451        """Saves the input datas into a static file."""
452        self.logDebug("Duplicating data stream into %s" % self.DataFile)
453        mustclose = 0
454        if self.InputFile is not None :
455            infile = open(self.InputFile, "rb")
456            mustclose = 1
457        else :   
458            infile = sys.stdin
459        CHUNK = 64*1024         # read 64 Kb at a time
460        dummy = 0
461        sizeread = 0
462        checksum = md5.new()
463        outfile = open(self.DataFile, "wb")   
464        while 1 :
465            data = infile.read(CHUNK) 
466            if not data :
467                break
468            sizeread += len(data)   
469            outfile.write(data)
470            checksum.update(data)   
471            if not (dummy % 32) : # Only display every 2 Mb
472                self.logDebug("%s bytes saved..." % sizeread)
473            dummy += 1   
474        outfile.close()
475        if mustclose :   
476            infile.close()
477        self.JobSize = sizeread   
478        self.JobMD5Sum = checksum.hexdigest()
479        self.logDebug("Job %s is %s bytes long." % (self.JobId, self.JobSize))
480        self.logDebug("Job %s MD5 sum is %s" % (self.JobId, self.JobMD5Sum))
481
482    def cleanUp(self) :
483        """Cleans up the place."""
484        if not self.isTrue(self.getPrintQueueOption(self.PrinterName, "keepfiles", ignore=1)) :
485            os.remove(self.DataFile)
486           
487    def runBranches(self) :         
488        """Launches each tee defined for the current print queue."""
489        branches = self.enumTeeBranches(self.PrinterName)
490        if self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1)) :
491            for (branch, command) in branches.items() :
492                self.logDebug("Launching %s : %s" % (branch, command))
493                os.system(command)
494        else :       
495            raise TeeError, "Forking tees not yet implemented."
496       
497if __name__ == "__main__" :   
498    # This is a CUPS backend, we should act and die like a CUPS backend
499    wrapper = CupsBackend()
500    if len(sys.argv) == 1 :
501        print "\n".join(wrapper.discoverOtherBackends())
502        sys.exit(0)               
503    elif len(sys.argv) not in (6, 7) :   
504        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\
505                              % sys.argv[0])
506        sys.exit(1)
507    else :   
508        wrapper.initBackend()
509        wrapper.saveDatasAndCheckSum()
510        wrapper.exportAttributes()
511        retcode = wrapper.runBranches()
512        wrapper.cleanUp()
513        sys.exit(retcode)
Note: See TracBrowser for help on using the browser.