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

Revision 2190, 6.5 kB (checked in by jerome, 19 years ago)

Makes ipp.py output all the available data when launched in test mode

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