root / pykota / trunk / pykota / ipp.py @ 2139

Revision 2139, 6.7 kB (checked in by jerome, 19 years ago)

Added the Log keyword property

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision Log
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 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# $Log$
24# Revision 1.2  2004/12/03 20:29:33  jalet
25# ipp.py can now be run in standalone mode for testing purposes
26#
27# Revision 1.1  2004/11/06 22:35:58  jalet
28# Added a miniparser for IPP messages (RFC 2910). The job-originating-host-name
29# retrieval is now fiable, unless the CUPS developpers change something...
30#
31#
32
33import sys
34from struct import unpack
35
36OPERATION_ATTRIBUTES_TAG = 0x01
37JOB_ATTRIBUTES_TAG = 0x02
38END_OF_ATTRIBUTES_TAG = 0x03
39PRINTER_ATTRIBUTES_TAG = 0x04
40UNSUPPORTED_ATTRIBUTES_TAG = 0x05
41
42class PyKotaIPPError(Exception):
43    """An exception for PyKota IPP related stuff."""
44    def __init__(self, message = ""):
45        self.message = message
46        Exception.__init__(self, message)
47    def __repr__(self):
48        return self.message
49    __str__ = __repr__
50
51class IPPMessage :
52    """A class for IPP message files."""
53    def __init__(self, data) :
54        """Initializes an IPP Message object."""
55        self.data = data
56        self._attributes = {}
57        self.curname = None
58        self.tags = [ None ] * 256      # by default all tags reserved
59       
60        # Delimiter tags
61        self.tags[0x01] = "operation-attributes-tag"
62        self.tags[0x02] = "job-attributes-tag"
63        self.tags[0x03] = "end-of-attributes-tag"
64        self.tags[0x04] = "printer-attributes-tag"
65        self.tags[0x05] = "unsupported-attributes-tag"
66       
67        # out of band values
68        self.tags[0x10] = "unsupported"
69        self.tags[0x11] = "reserved-for-future-default"
70        self.tags[0x12] = "unknown"
71        self.tags[0x13] = "no-value"
72       
73        # integer values
74        self.tags[0x20] = "generic-integer"
75        self.tags[0x21] = "integer"
76        self.tags[0x22] = "boolean"
77        self.tags[0x23] = "enum"
78       
79        # octetString
80        self.tags[0x30] = "octetString-with-an-unspecified-format"
81        self.tags[0x31] = "dateTime"
82        self.tags[0x32] = "resolution"
83        self.tags[0x33] = "rangeOfInteger"
84        self.tags[0x34] = "reserved-for-collection"
85        self.tags[0x35] = "textWithLanguage"
86        self.tags[0x36] = "nameWithLanguage"
87       
88        # character strings
89        self.tags[0x20] = "generic-character-string"
90        self.tags[0x41] = "textWithoutLanguage"
91        self.tags[0x42] = "nameWithoutLanguage"
92        # self.tags[0x43] = "reserved"
93        self.tags[0x44] = "keyword"
94        self.tags[0x45] = "uri"
95        self.tags[0x46] = "uriScheme"
96        self.tags[0x47] = "charset"
97        self.tags[0x48] = "naturalLanguage"
98        self.tags[0x49] = "mimeMediaType"
99       
100        # now parses the IPP message
101        self.parse()
102       
103    def __getattr__(self, attrname) :   
104        """Allows self.attributes to return the attributes names."""
105        if attrname == "attributes" :
106            keys = self._attributes.keys()
107            keys.sort()
108            return keys
109        raise AttributeError, attrname
110           
111    def __getitem__(self, ippattrname) :   
112        """Fakes a dictionnary d['key'] notation."""
113        value = self._attributes.get(ippattrname)
114        if value is not None :
115            if len(value) == 1 :
116                value = value[0]
117        return value       
118    get = __getitem__   
119       
120    def parseTag(self) :   
121        """Extracts information from an IPP tag."""
122        pos = self.position
123        valuetag = self.tags[ord(self.data[pos])]
124        # print valuetag.get("name")
125        pos += 1
126        posend = pos2 = pos + 2
127        namelength = unpack(">H", self.data[pos:pos2])[0]
128        if not namelength :
129            name = self.curname
130        else :   
131            posend += namelength
132            self.curname = name = self.data[pos2:posend]
133        pos2 = posend + 2
134        valuelength = unpack(">H", self.data[posend:pos2])[0]
135        posend = pos2 + valuelength
136        value = self.data[pos2:posend]
137        oldval = self._attributes.setdefault(name, [])
138        oldval.append(value)
139        return posend - self.position
140       
141    def operation_attributes_tag(self) : 
142        """Indicates that the parser enters into an operation-attributes-tag group."""
143        return self.parseTag()
144       
145    def job_attributes_tag(self) : 
146        """Indicates that the parser enters into an operation-attributes-tag group."""
147        return self.parseTag()
148       
149    def printer_attributes_tag(self) : 
150        """Indicates that the parser enters into an operation-attributes-tag group."""
151        return self.parseTag()
152       
153    def parse(self) :
154        """Parses an IPP Message.
155       
156           NB : Only a subset of RFC2910 is implemented.
157           We are only interested in textual informations for now anyway.
158        """
159        self.version = "%s.%s" % (ord(self.data[0]), ord(self.data[1]))
160        self.operation_id = "0x%04x" % unpack(">H", self.data[2:4])[0]
161        self.request_id = "0x%08x" % unpack(">I", self.data[4:8])[0]
162        self.position = 8
163        try :
164            tag = ord(self.data[self.position])
165            while tag != END_OF_ATTRIBUTES_TAG :
166                self.position += 1
167                name = self.tags[tag]
168                if name is not None :
169                    func = getattr(self, name.replace("-", "_"), None)
170                    if func is not None :
171                        self.position += func()
172                        if ord(self.data[self.position]) > UNSUPPORTED_ATTRIBUTES_TAG :
173                            self.position -= 1
174                            continue
175                tag = ord(self.data[self.position])
176        except IndexError :
177            raise PyKotaIPPError, "Unexpected end of IPP message."
178           
179if __name__ == "__main__" :           
180    if len(sys.argv) < 2 :
181        print "usage : python ipp.py /var/spool/cups/c00005 (for example)\n"
182    else :   
183        infile = open(sys.argv[1])
184        message = IPPMessage(infile.read())
185        infile.close()
186        print "Client hostname : %s" % message["job-originating-host-name"]
Note: See TracBrowser for help on using the browser.