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

Revision 2147, 6.4 kB (checked in by jerome, 19 years ago)

Removed all references to $Log$

  • 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 parseTag(self) :   
113        """Extracts information from an IPP tag."""
114        pos = self.position
115        valuetag = self.tags[ord(self.data[pos])]
116        # print valuetag.get("name")
117        pos += 1
118        posend = pos2 = pos + 2
119        namelength = unpack(">H", self.data[pos:pos2])[0]
120        if not namelength :
121            name = self.curname
122        else :   
123            posend += namelength
124            self.curname = name = self.data[pos2:posend]
125        pos2 = posend + 2
126        valuelength = unpack(">H", self.data[posend:pos2])[0]
127        posend = pos2 + valuelength
128        value = self.data[pos2:posend]
129        oldval = self._attributes.setdefault(name, [])
130        oldval.append(value)
131        return posend - self.position
132       
133    def operation_attributes_tag(self) : 
134        """Indicates that the parser enters into an operation-attributes-tag group."""
135        return self.parseTag()
136       
137    def job_attributes_tag(self) : 
138        """Indicates that the parser enters into an operation-attributes-tag group."""
139        return self.parseTag()
140       
141    def printer_attributes_tag(self) : 
142        """Indicates that the parser enters into an operation-attributes-tag group."""
143        return self.parseTag()
144       
145    def parse(self) :
146        """Parses an IPP Message.
147       
148           NB : Only a subset of RFC2910 is implemented.
149           We are only interested in textual informations for now anyway.
150        """
151        self.version = "%s.%s" % (ord(self.data[0]), ord(self.data[1]))
152        self.operation_id = "0x%04x" % unpack(">H", self.data[2:4])[0]
153        self.request_id = "0x%08x" % unpack(">I", self.data[4:8])[0]
154        self.position = 8
155        try :
156            tag = ord(self.data[self.position])
157            while tag != END_OF_ATTRIBUTES_TAG :
158                self.position += 1
159                name = self.tags[tag]
160                if name is not None :
161                    func = getattr(self, name.replace("-", "_"), None)
162                    if func is not None :
163                        self.position += func()
164                        if ord(self.data[self.position]) > UNSUPPORTED_ATTRIBUTES_TAG :
165                            self.position -= 1
166                            continue
167                tag = ord(self.data[self.position])
168        except IndexError :
169            raise PyKotaIPPError, "Unexpected end of IPP message."
170           
171if __name__ == "__main__" :           
172    if len(sys.argv) < 2 :
173        print "usage : python ipp.py /var/spool/cups/c00005 (for example)\n"
174    else :   
175        infile = open(sys.argv[1])
176        message = IPPMessage(infile.read())
177        infile.close()
178        print "Client hostname : %s" % message["job-originating-host-name"]
Note: See TracBrowser for help on using the browser.