root / tea4cups / trunk / tea4cups @ 581

Revision 581, 18.5 kB (checked in by jerome, 19 years ago)

Added initial code for IPP messages parsing

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