root / pkipplib / trunk / pkipplib / pkipplib.py @ 39

Revision 39, 29.3 kB (checked in by jerome, 17 years ago)

Added two newly added CUPS specific IPP operation codes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# pkipplib : IPP and CUPS support for Python
5#
6# (c) 2003, 2004, 2005, 2006, 2007 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import sys
26import os
27import urllib2
28import socket
29from struct import pack, unpack
30
31IPP_VERSION = "1.1"     # default version number
32
33IPP_PORT = 631
34
35IPP_MAX_NAME = 256
36IPP_MAX_VALUES = 8
37
38IPP_TAG_ZERO = 0x00
39IPP_TAG_OPERATION = 0x01
40IPP_TAG_JOB = 0x02
41IPP_TAG_END = 0x03
42IPP_TAG_PRINTER = 0x04
43IPP_TAG_UNSUPPORTED_GROUP = 0x05
44IPP_TAG_SUBSCRIPTION = 0x06
45IPP_TAG_EVENT_NOTIFICATION = 0x07
46IPP_TAG_UNSUPPORTED_VALUE = 0x10
47IPP_TAG_DEFAULT = 0x11
48IPP_TAG_UNKNOWN = 0x12
49IPP_TAG_NOVALUE = 0x13
50IPP_TAG_NOTSETTABLE = 0x15
51IPP_TAG_DELETEATTR = 0x16
52IPP_TAG_ADMINDEFINE = 0x17
53IPP_TAG_INTEGER = 0x21
54IPP_TAG_BOOLEAN = 0x22
55IPP_TAG_ENUM = 0x23
56IPP_TAG_STRING = 0x30
57IPP_TAG_DATE = 0x31
58IPP_TAG_RESOLUTION = 0x32
59IPP_TAG_RANGE = 0x33
60IPP_TAG_BEGIN_COLLECTION = 0x34
61IPP_TAG_TEXTLANG = 0x35
62IPP_TAG_NAMELANG = 0x36
63IPP_TAG_END_COLLECTION = 0x37
64IPP_TAG_TEXT = 0x41
65IPP_TAG_NAME = 0x42
66IPP_TAG_KEYWORD = 0x44
67IPP_TAG_URI = 0x45
68IPP_TAG_URISCHEME = 0x46
69IPP_TAG_CHARSET = 0x47
70IPP_TAG_LANGUAGE = 0x48
71IPP_TAG_MIMETYPE = 0x49
72IPP_TAG_MEMBERNAME = 0x4a
73IPP_TAG_MASK = 0x7fffffff
74IPP_TAG_COPY = -0x7fffffff-1
75
76IPP_RES_PER_INCH = 3
77IPP_RES_PER_CM = 4
78
79IPP_FINISHINGS_NONE = 3
80IPP_FINISHINGS_STAPLE = 4
81IPP_FINISHINGS_PUNCH = 5
82IPP_FINISHINGS_COVER = 6
83IPP_FINISHINGS_BIND = 7
84IPP_FINISHINGS_SADDLE_STITCH = 8
85IPP_FINISHINGS_EDGE_STITCH = 9
86IPP_FINISHINGS_FOLD = 10
87IPP_FINISHINGS_TRIM = 11
88IPP_FINISHINGS_BALE = 12
89IPP_FINISHINGS_BOOKLET_MAKER = 13
90IPP_FINISHINGS_JOB_OFFSET = 14
91IPP_FINISHINGS_STAPLE_TOP_LEFT = 20
92IPP_FINISHINGS_STAPLE_BOTTOM_LEFT = 21
93IPP_FINISHINGS_STAPLE_TOP_RIGHT = 22
94IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT = 23
95IPP_FINISHINGS_EDGE_STITCH_LEFT = 24
96IPP_FINISHINGS_EDGE_STITCH_TOP = 25
97IPP_FINISHINGS_EDGE_STITCH_RIGHT = 26
98IPP_FINISHINGS_EDGE_STITCH_BOTTOM = 27
99IPP_FINISHINGS_STAPLE_DUAL_LEFT = 28
100IPP_FINISHINGS_STAPLE_DUAL_TOP = 29
101IPP_FINISHINGS_STAPLE_DUAL_RIGHT = 30
102IPP_FINISHINGS_STAPLE_DUAL_BOTTOM = 31
103IPP_FINISHINGS_BIND_LEFT = 50
104IPP_FINISHINGS_BIND_TOP = 51
105IPP_FINISHINGS_BIND_RIGHT = 52
106IPP_FINISHINGS_BIND_BOTTO = 53
107
108IPP_PORTRAIT = 3
109IPP_LANDSCAPE = 4
110IPP_REVERSE_LANDSCAPE = 5
111IPP_REVERSE_PORTRAIT = 6
112
113IPP_QUALITY_DRAFT = 3
114IPP_QUALITY_NORMAL = 4
115IPP_QUALITY_HIGH = 5
116
117IPP_JOB_PENDING = 3
118IPP_JOB_HELD = 4
119IPP_JOB_PROCESSING = 5
120IPP_JOB_STOPPED = 6
121IPP_JOB_CANCELLED = 7
122IPP_JOB_ABORTED = 8
123IPP_JOB_COMPLETE = 9
124
125IPP_PRINTER_IDLE = 3
126IPP_PRINTER_PROCESSING = 4
127IPP_PRINTER_STOPPED = 5
128
129IPP_ERROR = -1
130IPP_IDLE = 0
131IPP_HEADER = 1
132IPP_ATTRIBUTE = 2
133IPP_DATA = 3
134
135IPP_PRINT_JOB = 0x0002
136IPP_PRINT_URI = 0x0003
137IPP_VALIDATE_JOB = 0x0004
138IPP_CREATE_JOB = 0x0005
139IPP_SEND_DOCUMENT = 0x0006
140IPP_SEND_URI = 0x0007
141IPP_CANCEL_JOB = 0x0008
142IPP_GET_JOB_ATTRIBUTES = 0x0009
143IPP_GET_JOBS = 0x000a
144IPP_GET_PRINTER_ATTRIBUTES = 0x000b
145IPP_HOLD_JOB = 0x000c
146IPP_RELEASE_JOB = 0x000d
147IPP_RESTART_JOB = 0x000e
148IPP_PAUSE_PRINTER = 0x0010
149IPP_RESUME_PRINTER = 0x0011
150IPP_PURGE_JOBS = 0x0012
151IPP_SET_PRINTER_ATTRIBUTES = 0x0013
152IPP_SET_JOB_ATTRIBUTES = 0x0014
153IPP_GET_PRINTER_SUPPORTED_VALUES = 0x0015
154IPP_CREATE_PRINTER_SUBSCRIPTION = 0x0016
155IPP_CREATE_JOB_SUBSCRIPTION = 0x0017
156IPP_GET_SUBSCRIPTION_ATTRIBUTES = 0x0018
157IPP_GET_SUBSCRIPTIONS = 0x0019
158IPP_RENEW_SUBSCRIPTION = 0x001a
159IPP_CANCEL_SUBSCRIPTION = 0x001b
160IPP_GET_NOTIFICATIONS = 0x001c
161IPP_SEND_NOTIFICATIONS = 0x001d
162IPP_GET_PRINT_SUPPORT_FILES = 0x0021
163IPP_ENABLE_PRINTER = 0x0022
164IPP_DISABLE_PRINTER = 0x0023
165IPP_PAUSE_PRINTER_AFTER_CURRENT_JOB = 0x0024
166IPP_HOLD_NEW_JOBS = 0x0025
167IPP_RELEASE_HELD_NEW_JOBS = 0x0026
168IPP_DEACTIVATE_PRINTER = 0x0027
169IPP_ACTIVATE_PRINTER = 0x0028
170IPP_RESTART_PRINTER = 0x0029
171IPP_SHUTDOWN_PRINTER = 0x002a
172IPP_STARTUP_PRINTER = 0x002b
173IPP_REPROCESS_JOB = 0x002c
174IPP_CANCEL_CURRENT_JOB = 0x002d
175IPP_SUSPEND_CURRENT_JOB = 0x002e
176IPP_RESUME_JOB = 0x002f
177IPP_PROMOTE_JOB = 0x0030
178IPP_SCHEDULE_JOB_AFTER = 0x0031
179IPP_PRIVATE = 0x4000
180CUPS_GET_DEFAULT = 0x4001
181CUPS_GET_PRINTERS = 0x4002
182CUPS_ADD_PRINTER = 0x4003
183CUPS_DELETE_PRINTER = 0x4004
184CUPS_GET_CLASSES = 0x4005
185CUPS_ADD_CLASS = 0x4006
186CUPS_DELETE_CLASS = 0x4007
187CUPS_ACCEPT_JOBS = 0x4008
188CUPS_REJECT_JOBS = 0x4009
189CUPS_SET_DEFAULT = 0x400a
190CUPS_GET_DEVICES = 0x400b
191CUPS_GET_PPDS = 0x400c
192CUPS_MOVE_JOB = 0x400d
193CUPS_AUTHENTICATE_JOB = 0x400e
194CUPS_GET_PPD = 0x400f
195CUPS_GET_DOCUMENT = 0x4027
196
197IPP_OK = 0x0000
198IPP_OK_SUBST = 0x0001
199IPP_OK_CONFLICT = 0x0002
200IPP_OK_IGNORED_SUBSCRIPTIONS = 0x0003
201IPP_OK_IGNORED_NOTIFICATIONS = 0x0004
202IPP_OK_TOO_MANY_EVENTS = 0x0005
203IPP_OK_BUT_CANCEL_SUBSCRIPTION = 0x0006
204IPP_REDIRECTION_OTHER_SITE = 0x0300
205IPP_BAD_REQUEST = 0x0400
206IPP_FORBIDDEN = 0x0401
207IPP_NOT_AUTHENTICATED = 0x0402
208IPP_NOT_AUTHORIZED = 0x0403
209IPP_NOT_POSSIBLE = 0x0404
210IPP_TIMEOUT = 0x0405
211IPP_NOT_FOUND = 0x0406
212IPP_GONE = 0x0407
213IPP_REQUEST_ENTITY = 0x0408
214IPP_REQUEST_VALUE = 0x0409
215IPP_DOCUMENT_FORMAT = 0x040a
216IPP_ATTRIBUTES = 0x040b
217IPP_URI_SCHEME = 0x040c
218IPP_CHARSET = 0x040d
219IPP_CONFLICT = 0x040e
220IPP_COMPRESSION_NOT_SUPPORTED = 0x040f
221IPP_COMPRESSION_ERROR = 0x0410
222IPP_DOCUMENT_FORMAT_ERROR = 0x0411
223IPP_DOCUMENT_ACCESS_ERROR = 0x0412
224IPP_ATTRIBUTES_NOT_SETTABLE = 0x0413
225IPP_IGNORED_ALL_SUBSCRIPTIONS = 0x0414
226IPP_TOO_MANY_SUBSCRIPTIONS = 0x0415
227IPP_IGNORED_ALL_NOTIFICATIONS = 0x0416
228IPP_PRINT_SUPPORT_FILE_NOT_FOUND = 0x0417
229
230IPP_INTERNAL_ERROR = 0x0500
231IPP_OPERATION_NOT_SUPPORTED = 0x0501
232IPP_SERVICE_UNAVAILABLE = 0x0502
233IPP_VERSION_NOT_SUPPORTED = 0x0503
234IPP_DEVICE_ERROR = 0x0504
235IPP_TEMPORARY_ERROR = 0x0505
236IPP_NOT_ACCEPTING = 0x0506
237IPP_PRINTER_BUSY = 0x0507
238IPP_ERROR_JOB_CANCELLED = 0x0508
239IPP_MULTIPLE_JOBS_NOT_SUPPORTED = 0x0509
240IPP_PRINTER_IS_DEACTIVATED = 0x50a
241 
242CUPS_PRINTER_LOCAL = 0x0000
243CUPS_PRINTER_CLASS = 0x0001
244CUPS_PRINTER_REMOTE = 0x0002
245CUPS_PRINTER_BW = 0x0004
246CUPS_PRINTER_COLOR = 0x0008
247CUPS_PRINTER_DUPLEX = 0x0010
248CUPS_PRINTER_STAPLE = 0x0020
249CUPS_PRINTER_COPIES = 0x0040
250CUPS_PRINTER_COLLATE = 0x0080
251CUPS_PRINTER_PUNCH = 0x0100
252CUPS_PRINTER_COVER = 0x0200
253CUPS_PRINTER_BIND = 0x0400
254CUPS_PRINTER_SORT = 0x0800
255CUPS_PRINTER_SMALL = 0x1000
256CUPS_PRINTER_MEDIUM = 0x2000
257CUPS_PRINTER_LARGE = 0x4000
258CUPS_PRINTER_VARIABLE = 0x8000
259CUPS_PRINTER_IMPLICIT = 0x1000
260CUPS_PRINTER_DEFAULT = 0x2000
261CUPS_PRINTER_FAX = 0x4000
262CUPS_PRINTER_REJECTING = 0x8000
263CUPS_PRINTER_DELETE = 0x1000
264CUPS_PRINTER_NOT_SHARED = 0x2000
265CUPS_PRINTER_AUTHENTICATED = 0x4000
266CUPS_PRINTER_COMMANDS = 0x8000
267CUPS_PRINTER_OPTIONS = 0xe6ff
268 
269 
270class IPPError(Exception) :
271    """An exception for IPP related stuff."""
272    def __init__(self, message = ""):
273        self.message = message
274        Exception.__init__(self, message)
275    def __repr__(self):
276        return self.message
277    __str__ = __repr__
278
279class FakeAttribute :
280    """Fakes an IPPRequest attribute to simplify usage syntax."""
281    def __init__(self, request, name) :
282        """Initializes the fake attribute."""
283        self.request = request
284        self.name = name
285       
286    def __setitem__(self, key, value) :
287        """Appends the value to the real attribute."""
288        attributeslist = getattr(self.request, "_%s_attributes" % self.name)
289        for i in range(len(attributeslist)) :
290            attribute = attributeslist[i]
291            for j in range(len(attribute)) :
292                (attrname, attrvalue) = attribute[j]
293                if attrname == key :
294                    attribute[j][1].append(value)
295                    return
296            attribute.append((key, [value]))       
297           
298    def __getitem__(self, key) :
299        """Returns an attribute's value."""
300        answer = []
301        attributeslist = getattr(self.request, "_%s_attributes" % self.name)
302        for i in range(len(attributeslist)) :
303            attribute = attributeslist[i]
304            for j in range(len(attribute)) :
305                (attrname, attrvalue) = attribute[j]
306                if attrname == key :
307                    answer.extend(attrvalue)
308        if answer :
309            return answer
310        raise KeyError, key           
311   
312class IPPRequest :
313    """A class for IPP requests."""
314    attributes_types = ("operation", "job", "printer", "unsupported", \
315                                     "subscription", "event_notification")
316    def __init__(self, data="", version=IPP_VERSION, 
317                                operation_id=None, \
318                                request_id=None, \
319                                debug=False) :
320        """Initializes an IPP Message object.
321       
322           Parameters :
323           
324             data : the complete IPP Message's content.
325             debug : a boolean value to output debug info on stderr.
326        """
327        self.debug = debug
328        self._data = data
329        self.parsed = False
330       
331        # Initializes message
332        self.setVersion(version)               
333        self.setOperationId(operation_id)
334        self.setRequestId(request_id)
335        self.data = ""
336       
337        for attrtype in self.attributes_types :
338            setattr(self, "_%s_attributes" % attrtype, [[]])
339       
340        # Initialize tags   
341        self.tags = [ None ] * 256 # by default all tags reserved
342       
343        # Delimiter tags
344        self.tags[0x01] = "operation-attributes-tag"
345        self.tags[0x02] = "job-attributes-tag"
346        self.tags[0x03] = "end-of-attributes-tag"
347        self.tags[0x04] = "printer-attributes-tag"
348        self.tags[0x05] = "unsupported-attributes-tag"
349        self.tags[0x06] = "subscription-attributes-tag"
350        self.tags[0x07] = "event_notification-attributes-tag"
351       
352        # out of band values
353        self.tags[0x10] = "unsupported"
354        self.tags[0x11] = "reserved-for-future-default"
355        self.tags[0x12] = "unknown"
356        self.tags[0x13] = "no-value"
357        self.tags[0x15] = "not-settable"
358        self.tags[0x16] = "delete-attribute"
359        self.tags[0x17] = "admin-define"
360 
361        # integer values
362        self.tags[0x20] = "generic-integer"
363        self.tags[0x21] = "integer"
364        self.tags[0x22] = "boolean"
365        self.tags[0x23] = "enum"
366       
367        # octetString
368        self.tags[0x30] = "octetString-with-an-unspecified-format"
369        self.tags[0x31] = "dateTime"
370        self.tags[0x32] = "resolution"
371        self.tags[0x33] = "rangeOfInteger"
372        self.tags[0x34] = "begCollection" # TODO : find sample files for testing
373        self.tags[0x35] = "textWithLanguage"
374        self.tags[0x36] = "nameWithLanguage"
375        self.tags[0x37] = "endCollection"
376       
377        # character strings
378        self.tags[0x40] = "generic-character-string"
379        self.tags[0x41] = "textWithoutLanguage"
380        self.tags[0x42] = "nameWithoutLanguage"
381        self.tags[0x44] = "keyword"
382        self.tags[0x45] = "uri"
383        self.tags[0x46] = "uriScheme"
384        self.tags[0x47] = "charset"
385        self.tags[0x48] = "naturalLanguage"
386        self.tags[0x49] = "mimeMediaType"
387        self.tags[0x4a] = "memberAttrName"
388       
389        # Reverse mapping to generate IPP messages
390        self.tagvalues = {}
391        for i in range(len(self.tags)) :
392            value = self.tags[i]
393            if value is not None :
394                self.tagvalues[value] = i
395                                     
396    def __getattr__(self, name) :                                 
397        """Fakes attribute access."""
398        if name in self.attributes_types :
399            return FakeAttribute(self, name)
400        else :
401            raise AttributeError, name
402           
403    def __str__(self) :       
404        """Returns the parsed IPP message in a readable form."""
405        if not self.parsed :
406            return ""
407        mybuffer = []
408        mybuffer.append("IPP version : %s.%s" % self.version)
409        mybuffer.append("IPP operation Id : 0x%04x" % self.operation_id)
410        mybuffer.append("IPP request Id : 0x%08x" % self.request_id)
411        for attrtype in self.attributes_types :
412            for attribute in getattr(self, "_%s_attributes" % attrtype) :
413                if attribute :
414                    mybuffer.append("%s attributes :" % attrtype.title())
415                for (name, value) in attribute :
416                    mybuffer.append("  %s : %s" % (name, value))
417        if self.data :           
418            mybuffer.append("IPP datas : %s" % repr(self.data))
419        return "\n".join(mybuffer)
420       
421    def logDebug(self, msg) :   
422        """Prints a debug message."""
423        if self.debug :
424            sys.stderr.write("%s\n" % msg)
425            sys.stderr.flush()
426           
427    def setVersion(self, version) :
428        """Sets the request's operation id."""
429        if version is not None :
430            try :
431                self.version = [int(p) for p in version.split(".")]
432            except AttributeError :
433                if len(version) == 2 : # 2-tuple
434                    self.version = version
435                else :   
436                    try :
437                        self.version = [int(p) for p in str(float(version)).split(".")]
438                    except :
439                        self.version = [int(p) for p in IPP_VERSION.split(".")]
440       
441    def setOperationId(self, opid) :       
442        """Sets the request's operation id."""
443        self.operation_id = opid
444       
445    def setRequestId(self, reqid) :       
446        """Sets the request's request id."""
447        self.request_id = reqid
448       
449    def dump(self) :   
450        """Generates an IPP Message.
451       
452           Returns the message as a string of text.
453        """   
454        mybuffer = []
455        if None not in (self.version, self.operation_id) :
456            mybuffer.append(chr(self.version[0]) + chr(self.version[1]))
457            mybuffer.append(pack(">H", self.operation_id))
458            mybuffer.append(pack(">I", self.request_id or 1))
459            for attrtype in self.attributes_types :
460                for attribute in getattr(self, "_%s_attributes" % attrtype) :
461                    if attribute :
462                        mybuffer.append(chr(self.tagvalues["%s-attributes-tag" % attrtype]))
463                    for (attrname, value) in attribute :
464                        nameprinted = 0
465                        for (vtype, val) in value :
466                            mybuffer.append(chr(self.tagvalues[vtype]))
467                            if not nameprinted :
468                                mybuffer.append(pack(">H", len(attrname)))
469                                mybuffer.append(attrname)
470                                nameprinted = 1
471                            else :     
472                                mybuffer.append(pack(">H", 0))
473                            if vtype in ("integer", "enum") :
474                                mybuffer.append(pack(">H", 4))
475                                mybuffer.append(pack(">I", val))
476                            elif vtype == "boolean" :
477                                mybuffer.append(pack(">H", 1))
478                                mybuffer.append(chr(val))
479                            else :   
480                                mybuffer.append(pack(">H", len(val)))
481                                mybuffer.append(val)
482            mybuffer.append(chr(self.tagvalues["end-of-attributes-tag"]))
483        mybuffer.append(self.data)   
484        return "".join(mybuffer)
485           
486    def parse(self) :
487        """Parses an IPP Request.
488       
489           NB : Only a subset of RFC2910 is implemented.
490        """
491        self._curname = None
492        self._curattributes = None
493       
494        self.setVersion((ord(self._data[0]), ord(self._data[1])))
495        self.setOperationId(unpack(">H", self._data[2:4])[0])
496        self.setRequestId(unpack(">I", self._data[4:8])[0])
497        self.position = 8
498        endofattributes = self.tagvalues["end-of-attributes-tag"]
499        maxdelimiter = self.tagvalues["event_notification-attributes-tag"]
500        nulloffset = lambda : 0
501        try :
502            tag = ord(self._data[self.position])
503            while tag != endofattributes :
504                self.position += 1
505                name = self.tags[tag]
506                if name is not None :
507                    func = getattr(self, name.replace("-", "_"), nulloffset)
508                    self.position += func()
509                    if ord(self._data[self.position]) > maxdelimiter :
510                        self.position -= 1
511                        continue
512                oldtag = tag       
513                tag = ord(self._data[self.position])
514                if tag == oldtag :
515                    self._curattributes.append([])
516        except IndexError :
517            raise IPPError, "Unexpected end of IPP message."
518           
519        self.data = self._data[self.position+1:]           
520        self.parsed = True
521       
522    def parseTag(self) :   
523        """Extracts information from an IPP tag."""
524        pos = self.position
525        tagtype = self.tags[ord(self._data[pos])]
526        pos += 1
527        posend = pos2 = pos + 2
528        namelength = unpack(">H", self._data[pos:pos2])[0]
529        if not namelength :
530            name = self._curname
531        else :   
532            posend += namelength
533            self._curname = name = self._data[pos2:posend]
534        pos2 = posend + 2
535        valuelength = unpack(">H", self._data[posend:pos2])[0]
536        posend = pos2 + valuelength
537        value = self._data[pos2:posend]
538        if tagtype in ("integer", "enum") :
539            value = unpack(">I", value)[0]
540        elif tagtype == "boolean" :   
541            value = ord(value)
542        try :   
543            (oldname, oldval) = self._curattributes[-1][-1]
544            if oldname == name :
545                oldval.append((tagtype, value))
546            else :   
547                raise IndexError
548        except IndexError :   
549            self._curattributes[-1].append((name, [(tagtype, value)]))
550        self.logDebug("%s(%s) : %s" % (name, tagtype, value))
551        return posend - self.position
552       
553    def operation_attributes_tag(self) : 
554        """Indicates that the parser enters into an operation-attributes-tag group."""
555        self._curattributes = self._operation_attributes
556        return self.parseTag()
557       
558    def job_attributes_tag(self) : 
559        """Indicates that the parser enters into a job-attributes-tag group."""
560        self._curattributes = self._job_attributes
561        return self.parseTag()
562       
563    def printer_attributes_tag(self) : 
564        """Indicates that the parser enters into a printer-attributes-tag group."""
565        self._curattributes = self._printer_attributes
566        return self.parseTag()
567       
568    def unsupported_attributes_tag(self) : 
569        """Indicates that the parser enters into an unsupported-attributes-tag group."""
570        self._curattributes = self._unsupported_attributes
571        return self.parseTag()
572       
573    def subscription_attributes_tag(self) : 
574        """Indicates that the parser enters into a subscription-attributes-tag group."""
575        self._curattributes = self._subscription_attributes
576        return self.parseTag()
577       
578    def event_notification_attributes_tag(self) : 
579        """Indicates that the parser enters into an event-notification-attributes-tag group."""
580        self._curattributes = self._event_notification_attributes
581        return self.parseTag()
582       
583           
584class CUPS :
585    """A class for a CUPS instance."""
586    def __init__(self, url=None, username=None, password=None, charset="utf-8", language="en-us", debug=False) :
587        """Initializes the CUPS instance."""
588        if url is not None :
589            self.url = url.replace("ipp://", "http://")
590            if self.url.endswith("/") :
591                self.url = self.url[:-1]
592        else :       
593            self.url = self.getDefaultURL()
594        self.username = username
595        self.password = password
596        self.charset = charset
597        self.language = language
598        self.debug = debug
599        self.lastError = None
600        self.lastErrorMessage = None
601        self.requestId = None
602       
603    def getDefaultURL(self) :   
604        """Builds a default URL."""
605        # TODO : encryption methods.
606        server = os.environ.get("CUPS_SERVER") or "localhost"
607        port = os.environ.get("IPP_PORT") or 631
608        if server.startswith("/") :
609            # it seems it's a unix domain socket.
610            # we can't handle this right now, so we use the default instead.
611            return "http://localhost:%s" % port
612        else :   
613            return "http://%s:%s" % (server, port)
614           
615    def identifierToURI(self, service, ident) :
616        """Transforms an identifier into a particular URI depending on requested service."""
617        return "%s/%s/%s" % (self.url.replace("http://", "ipp://"),
618                             service,
619                             ident)
620       
621    def nextRequestId(self) :       
622        """Increments the current request id and returns the new value."""
623        try :
624            self.requestId += 1
625        except TypeError :   
626            self.requestId = 1
627        return self.requestId
628           
629    def newRequest(self, operationid=None) :
630        """Generates a new empty request."""
631        if operationid is not None :
632            req = IPPRequest(operation_id=operationid, \
633                             request_id=self.nextRequestId(), \
634                             debug=self.debug)
635            req.operation["attributes-charset"] = ("charset", self.charset)
636            req.operation["attributes-natural-language"] = ("naturalLanguage", self.language)
637            return req
638   
639    def doRequest(self, req, url=None) :
640        """Sends a request to the CUPS server.
641           returns a new IPPRequest object, containing the parsed answer.
642        """   
643        connexion = urllib2.Request(url=url or self.url, \
644                             data=req.dump())
645        connexion.add_header("Content-Type", "application/ipp")
646        if self.username :
647            pwmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
648            pwmanager.add_password(None, \
649                                   "%s%s" % (connexion.get_host(), connexion.get_selector()), \
650                                   self.username, \
651                                   self.password or "")
652            authhandler = urllib2.HTTPBasicAuthHandler(pwmanager)                       
653            opener = urllib2.build_opener(authhandler)
654            urllib2.install_opener(opener)
655        self.lastError = None   
656        self.lastErrorMessage = None
657        try :   
658            response = urllib2.urlopen(connexion)
659        except (urllib2.URLError, urllib2.HTTPError, socket.error), error :   
660            self.lastError = error
661            self.lastErrorMessage = str(error)
662            return None
663        else :   
664            datas = response.read()
665            ippresponse = IPPRequest(datas)
666            ippresponse.parse()
667            return ippresponse
668   
669    def getPPD(self, queuename) :   
670        """Retrieves the PPD for a particular queuename."""
671        req = self.newRequest(IPP_GET_PRINTER_ATTRIBUTES)
672        req.operation["printer-uri"] = ("uri", self.identifierToURI("printers", queuename))
673        for attrib in ("printer-uri-supported", "printer-type", "member-uris") :
674            req.operation["requested-attributes"] = ("nameWithoutLanguage", attrib)
675        return self.doRequest(req)  # TODO : get the PPD from the actual print server
676       
677    def getDefault(self) :
678        """Retrieves CUPS' default printer."""
679        return self.doRequest(self.newRequest(CUPS_GET_DEFAULT))
680   
681    def getJobAttributes(self, jobid) :   
682        """Retrieves a print job's attributes."""
683        req = self.newRequest(IPP_GET_JOB_ATTRIBUTES)
684        req.operation["job-uri"] = ("uri", self.identifierToURI("jobs", jobid))
685        return self.doRequest(req)
686       
687    def getPrinters(self) :   
688        """Returns the list of print queues names."""
689        req = self.newRequest(CUPS_GET_PRINTERS)
690        req.operation["requested-attributes"] = ("keyword", "printer-name")
691        req.operation["printer-type"] = ("enum", 0)
692        req.operation["printer-type-mask"] = ("enum", CUPS_PRINTER_CLASS)
693        return [printer[1] for printer in self.doRequest(req).printer["printer-name"]]
694       
695    def getDevices(self) :   
696        """Returns a list of devices as (deviceclass, deviceinfo, devicemakeandmodel, deviceuri) tuples."""
697        answer = self.doRequest(self.newRequest(CUPS_GET_DEVICES))
698        return zip([d[1] for d in answer.printer["device-class"]], \
699                   [d[1] for d in answer.printer["device-info"]], \
700                   [d[1] for d in answer.printer["device-make-and-model"]], \
701                   [d[1] for d in answer.printer["device-uri"]])
702                   
703    def getPPDs(self) :   
704        """Returns a list of PPDs as (ppdnaturallanguage, ppdmake, ppdmakeandmodel, ppdname) tuples."""
705        answer = self.doRequest(self.newRequest(CUPS_GET_PPDS))
706        return zip([d[1] for d in answer.printer["ppd-natural-language"]], \
707                   [d[1] for d in answer.printer["ppd-make"]], \
708                   [d[1] for d in answer.printer["ppd-make-and-model"]], \
709                   [d[1] for d in answer.printer["ppd-name"]])
710                   
711    def createSubscription(self, uri, events=["all"],
712                                      userdata=None,
713                                      recipient=None,
714                                      pullmethod=None,
715                                      charset=None,
716                                      naturallanguage=None,
717                                      leaseduration=None,
718                                      timeinterval=None,
719                                      jobid=None) :
720        """Creates a job, printer or server subscription.
721         
722           uri : the subscription's uri, e.g. ipp://server
723           events : a list of events to subscribe to, e.g. ["printer-added", "printer-deleted"]
724           recipient : the notifier's uri
725           pullmethod : the pull method to use
726           charset : the charset to use when sending notifications
727           naturallanguage : the language to use when sending notifications
728           leaseduration : the duration of the lease in seconds
729           timeinterval : the interval of time during notifications
730           jobid : the optional job id in case of a job subscription
731        """   
732        if jobid is not None :
733            opid = IPP_CREATE_JOB_SUBSCRIPTION
734            uritype = "job-uri"
735        else :
736            opid = IPP_CREATE_PRINTER_SUBSCRIPTION
737            uritype = "printer-uri"
738        req = self.newRequest(opid)
739        req.operation[uritype] = ("uri", uri)
740        for event in events :
741            req.subscription["notify-events"] = ("keyword", event)
742        if userdata is not None :   
743            req.subscription["notify-user-data"] = ("octetString-with-an-unspecified-format", userdata)
744        if recipient is not None :   
745            req.subscription["notify-recipient"] = ("uri", recipient)
746        if pullmethod is not None :
747            req.subscription["notify-pull-method"] = ("keyword", pullmethod)
748        if charset is not None :
749            req.subscription["notify-charset"] = ("charset", charset)
750        if naturallanguage is not None :
751            req.subscription["notify-natural-language"] = ("naturalLanguage", naturallanguage)
752        if leaseduration is not None :
753            req.subscription["notify-lease-duration"] = ("integer", leaseduration)
754        if timeinterval is not None :
755            req.subscription["notify-time-interval"] = ("integer", timeinterval)
756        if jobid is not None :
757            req.subscription["notify-job-id"] = ("integer", jobid)
758        return self.doRequest(req)
759           
760    def cancelSubscription(self, uri, subscriptionid, jobid=None) :   
761        """Cancels a subscription.
762       
763           uri : the subscription's uri.
764           subscriptionid : the subscription's id.
765           jobid : the optional job's id.
766        """
767        req = self.newRequest(IPP_CANCEL_SUBSCRIPTION)
768        if jobid is not None :
769            uritype = "job-uri"
770        else :
771            uritype = "printer-uri"
772        req.operation[uritype] = ("uri", uri)
773        req.event_notification["notify-subscription-id"] = ("integer", subscriptionid)
774        return self.doRequest(req)
775       
776if __name__ == "__main__" :           
777    if (len(sys.argv) < 2) or (sys.argv[1] == "--debug") :
778        print "usage : python pkipplib.py /var/spool/cups/c00005 [--debug] (for example)\n"
779    else :   
780        infile = open(sys.argv[1], "rb")
781        filedata = infile.read()
782        infile.close()
783       
784        msg = IPPRequest(filedata, debug=(sys.argv[-1]=="--debug"))
785        msg.parse()
786        msg2 = IPPRequest(msg.dump())
787        msg2.parse()
788        filedata2 = msg2.dump()
789       
790        if filedata == filedata2 :
791            print "Test OK : parsing original and parsing the output of the dump produce the same dump !"
792            print str(msg)
793        else :   
794            print "Test Failed !"
795            print str(msg)
796            print
797            print str(msg2)
798       
Note: See TracBrowser for help on using the browser.