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 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 | |
---|
25 | import sys |
---|
26 | import urllib2 |
---|
27 | from struct import pack, unpack |
---|
28 | |
---|
29 | IPP_VERSION = "1.1" # default version number |
---|
30 | |
---|
31 | IPP_PORT = 631 |
---|
32 | |
---|
33 | IPP_MAX_NAME = 256 |
---|
34 | IPP_MAX_VALUES = 8 |
---|
35 | |
---|
36 | IPP_TAG_ZERO = 0x00 |
---|
37 | IPP_TAG_OPERATION = 0x01 |
---|
38 | IPP_TAG_JOB = 0x02 |
---|
39 | IPP_TAG_END = 0x03 |
---|
40 | IPP_TAG_PRINTER = 0x04 |
---|
41 | IPP_TAG_UNSUPPORTED_GROUP = 0x05 |
---|
42 | IPP_TAG_SUBSCRIPTION = 0x06 |
---|
43 | IPP_TAG_EVENT_NOTIFICATION = 0x07 |
---|
44 | IPP_TAG_UNSUPPORTED_VALUE = 0x10 |
---|
45 | IPP_TAG_DEFAULT = 0x11 |
---|
46 | IPP_TAG_UNKNOWN = 0x12 |
---|
47 | IPP_TAG_NOVALUE = 0x13 |
---|
48 | IPP_TAG_NOTSETTABLE = 0x15 |
---|
49 | IPP_TAG_DELETEATTR = 0x16 |
---|
50 | IPP_TAG_ADMINDEFINE = 0x17 |
---|
51 | IPP_TAG_INTEGER = 0x21 |
---|
52 | IPP_TAG_BOOLEAN = 0x22 |
---|
53 | IPP_TAG_ENUM = 0x23 |
---|
54 | IPP_TAG_STRING = 0x30 |
---|
55 | IPP_TAG_DATE = 0x31 |
---|
56 | IPP_TAG_RESOLUTION = 0x32 |
---|
57 | IPP_TAG_RANGE = 0x33 |
---|
58 | IPP_TAG_BEGIN_COLLECTION = 0x34 |
---|
59 | IPP_TAG_TEXTLANG = 0x35 |
---|
60 | IPP_TAG_NAMELANG = 0x36 |
---|
61 | IPP_TAG_END_COLLECTION = 0x37 |
---|
62 | IPP_TAG_TEXT = 0x41 |
---|
63 | IPP_TAG_NAME = 0x42 |
---|
64 | IPP_TAG_KEYWORD = 0x44 |
---|
65 | IPP_TAG_URI = 0x45 |
---|
66 | IPP_TAG_URISCHEME = 0x46 |
---|
67 | IPP_TAG_CHARSET = 0x47 |
---|
68 | IPP_TAG_LANGUAGE = 0x48 |
---|
69 | IPP_TAG_MIMETYPE = 0x49 |
---|
70 | IPP_TAG_MEMBERNAME = 0x4a |
---|
71 | IPP_TAG_MASK = 0x7fffffff |
---|
72 | IPP_TAG_COPY = -0x7fffffff-1 |
---|
73 | |
---|
74 | IPP_RES_PER_INCH = 3 |
---|
75 | IPP_RES_PER_CM = 4 |
---|
76 | |
---|
77 | IPP_FINISHINGS_NONE = 3 |
---|
78 | IPP_FINISHINGS_STAPLE = 4 |
---|
79 | IPP_FINISHINGS_PUNCH = 5 |
---|
80 | IPP_FINISHINGS_COVER = 6 |
---|
81 | IPP_FINISHINGS_BIND = 7 |
---|
82 | IPP_FINISHINGS_SADDLE_STITCH = 8 |
---|
83 | IPP_FINISHINGS_EDGE_STITCH = 9 |
---|
84 | IPP_FINISHINGS_FOLD = 10 |
---|
85 | IPP_FINISHINGS_TRIM = 11 |
---|
86 | IPP_FINISHINGS_BALE = 12 |
---|
87 | IPP_FINISHINGS_BOOKLET_MAKER = 13 |
---|
88 | IPP_FINISHINGS_JOB_OFFSET = 14 |
---|
89 | IPP_FINISHINGS_STAPLE_TOP_LEFT = 20 |
---|
90 | IPP_FINISHINGS_STAPLE_BOTTOM_LEFT = 21 |
---|
91 | IPP_FINISHINGS_STAPLE_TOP_RIGHT = 22 |
---|
92 | IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT = 23 |
---|
93 | IPP_FINISHINGS_EDGE_STITCH_LEFT = 24 |
---|
94 | IPP_FINISHINGS_EDGE_STITCH_TOP = 25 |
---|
95 | IPP_FINISHINGS_EDGE_STITCH_RIGHT = 26 |
---|
96 | IPP_FINISHINGS_EDGE_STITCH_BOTTOM = 27 |
---|
97 | IPP_FINISHINGS_STAPLE_DUAL_LEFT = 28 |
---|
98 | IPP_FINISHINGS_STAPLE_DUAL_TOP = 29 |
---|
99 | IPP_FINISHINGS_STAPLE_DUAL_RIGHT = 30 |
---|
100 | IPP_FINISHINGS_STAPLE_DUAL_BOTTOM = 31 |
---|
101 | IPP_FINISHINGS_BIND_LEFT = 50 |
---|
102 | IPP_FINISHINGS_BIND_TOP = 51 |
---|
103 | IPP_FINISHINGS_BIND_RIGHT = 52 |
---|
104 | IPP_FINISHINGS_BIND_BOTTO = 53 |
---|
105 | |
---|
106 | IPP_PORTRAIT = 3 |
---|
107 | IPP_LANDSCAPE = 4 |
---|
108 | IPP_REVERSE_LANDSCAPE = 5 |
---|
109 | IPP_REVERSE_PORTRAIT = 6 |
---|
110 | |
---|
111 | IPP_QUALITY_DRAFT = 3 |
---|
112 | IPP_QUALITY_NORMAL = 4 |
---|
113 | IPP_QUALITY_HIGH = 5 |
---|
114 | |
---|
115 | IPP_JOB_PENDING = 3 |
---|
116 | IPP_JOB_HELD = 4 |
---|
117 | IPP_JOB_PROCESSING = 5 |
---|
118 | IPP_JOB_STOPPED = 6 |
---|
119 | IPP_JOB_CANCELLED = 7 |
---|
120 | IPP_JOB_ABORTED = 8 |
---|
121 | IPP_JOB_COMPLETE = 9 |
---|
122 | |
---|
123 | IPP_PRINTER_IDLE = 3 |
---|
124 | IPP_PRINTER_PROCESSING = 4 |
---|
125 | IPP_PRINTER_STOPPED = 5 |
---|
126 | |
---|
127 | IPP_ERROR = -1 |
---|
128 | IPP_IDLE = 0 |
---|
129 | IPP_HEADER = 1 |
---|
130 | IPP_ATTRIBUTE = 2 |
---|
131 | IPP_DATA = 3 |
---|
132 | |
---|
133 | IPP_PRINT_JOB = 0x0002 |
---|
134 | IPP_PRINT_URI = 0x0003 |
---|
135 | IPP_VALIDATE_JOB = 0x0004 |
---|
136 | IPP_CREATE_JOB = 0x0005 |
---|
137 | IPP_SEND_DOCUMENT = 0x0006 |
---|
138 | IPP_SEND_URI = 0x0007 |
---|
139 | IPP_CANCEL_JOB = 0x0008 |
---|
140 | IPP_GET_JOB_ATTRIBUTES = 0x0009 |
---|
141 | IPP_GET_JOBS = 0x000a |
---|
142 | IPP_GET_PRINTER_ATTRIBUTES = 0x000b |
---|
143 | IPP_HOLD_JOB = 0x000c |
---|
144 | IPP_RELEASE_JOB = 0x000d |
---|
145 | IPP_RESTART_JOB = 0x000e |
---|
146 | IPP_PAUSE_PRINTER = 0x0010 |
---|
147 | IPP_RESUME_PRINTER = 0x0011 |
---|
148 | IPP_PURGE_JOBS = 0x0012 |
---|
149 | IPP_SET_PRINTER_ATTRIBUTES = 0x0013 |
---|
150 | IPP_SET_JOB_ATTRIBUTES = 0x0014 |
---|
151 | IPP_GET_PRINTER_SUPPORTED_VALUES = 0x0015 |
---|
152 | IPP_CREATE_PRINTER_SUBSCRIPTION = 0x0016 |
---|
153 | IPP_CREATE_JOB_SUBSCRIPTION = 0x0017 |
---|
154 | IPP_GET_SUBSCRIPTION_ATTRIBUTES = 0x0018 |
---|
155 | IPP_GET_SUBSCRIPTIONS = 0x0019 |
---|
156 | IPP_RENEW_SUBSCRIPTION = 0x001a |
---|
157 | IPP_CANCEL_SUBSCRIPTION = 0x001b |
---|
158 | IPP_GET_NOTIFICATIONS = 0x001c |
---|
159 | IPP_SEND_NOTIFICATIONS = 0x001d |
---|
160 | IPP_GET_PRINT_SUPPORT_FILES = 0x0021 |
---|
161 | IPP_ENABLE_PRINTER = 0x0022 |
---|
162 | IPP_DISABLE_PRINTER = 0x0023 |
---|
163 | IPP_PAUSE_PRINTER_AFTER_CURRENT_JOB = 0x0024 |
---|
164 | IPP_HOLD_NEW_JOBS = 0x0025 |
---|
165 | IPP_RELEASE_HELD_NEW_JOBS = 0x0026 |
---|
166 | IPP_DEACTIVATE_PRINTER = 0x0027 |
---|
167 | IPP_ACTIVATE_PRINTER = 0x0028 |
---|
168 | IPP_RESTART_PRINTER = 0x0029 |
---|
169 | IPP_SHUTDOWN_PRINTER = 0x002a |
---|
170 | IPP_STARTUP_PRINTER = 0x002b |
---|
171 | IPP_REPROCESS_JOB = 0x002c |
---|
172 | IPP_CANCEL_CURRENT_JOB = 0x002d |
---|
173 | IPP_SUSPEND_CURRENT_JOB = 0x002e |
---|
174 | IPP_RESUME_JOB = 0x002f |
---|
175 | IPP_PROMOTE_JOB = 0x0030 |
---|
176 | IPP_SCHEDULE_JOB_AFTER = 0x0031 |
---|
177 | IPP_PRIVATE = 0x4000 |
---|
178 | CUPS_GET_DEFAULT = 0x4001 |
---|
179 | CUPS_GET_PRINTERS = 0x4002 |
---|
180 | CUPS_ADD_PRINTER = 0x4003 |
---|
181 | CUPS_DELETE_PRINTER = 0x4004 |
---|
182 | CUPS_GET_CLASSES = 0x4005 |
---|
183 | CUPS_ADD_CLASS = 0x4006 |
---|
184 | CUPS_DELETE_CLASS = 0x4007 |
---|
185 | CUPS_ACCEPT_JOBS = 0x4008 |
---|
186 | CUPS_REJECT_JOBS = 0x4009 |
---|
187 | CUPS_SET_DEFAULT = 0x400a |
---|
188 | CUPS_GET_DEVICES = 0x400b |
---|
189 | CUPS_GET_PPDS = 0x400c |
---|
190 | CUPS_MOVE_JOB = 0x400d |
---|
191 | CUPS_AUTHENTICATE_JOB = 0x400e |
---|
192 | |
---|
193 | IPP_OK = 0x0000 |
---|
194 | IPP_OK_SUBST = 0x0001 |
---|
195 | IPP_OK_CONFLICT = 0x0002 |
---|
196 | IPP_OK_IGNORED_SUBSCRIPTIONS = 0x0003 |
---|
197 | IPP_OK_IGNORED_NOTIFICATIONS = 0x0004 |
---|
198 | IPP_OK_TOO_MANY_EVENTS = 0x0005 |
---|
199 | IPP_OK_BUT_CANCEL_SUBSCRIPTION = 0x0006 |
---|
200 | IPP_REDIRECTION_OTHER_SITE = 0x0300 |
---|
201 | IPP_BAD_REQUEST = 0x0400 |
---|
202 | IPP_FORBIDDEN = 0x0401 |
---|
203 | IPP_NOT_AUTHENTICATED = 0x0402 |
---|
204 | IPP_NOT_AUTHORIZED = 0x0403 |
---|
205 | IPP_NOT_POSSIBLE = 0x0404 |
---|
206 | IPP_TIMEOUT = 0x0405 |
---|
207 | IPP_NOT_FOUND = 0x0406 |
---|
208 | IPP_GONE = 0x0407 |
---|
209 | IPP_REQUEST_ENTITY = 0x0408 |
---|
210 | IPP_REQUEST_VALUE = 0x0409 |
---|
211 | IPP_DOCUMENT_FORMAT = 0x040a |
---|
212 | IPP_ATTRIBUTES = 0x040b |
---|
213 | IPP_URI_SCHEME = 0x040c |
---|
214 | IPP_CHARSET = 0x040d |
---|
215 | IPP_CONFLICT = 0x040e |
---|
216 | IPP_COMPRESSION_NOT_SUPPORTED = 0x040f |
---|
217 | IPP_COMPRESSION_ERROR = 0x0410 |
---|
218 | IPP_DOCUMENT_FORMAT_ERROR = 0x0411 |
---|
219 | IPP_DOCUMENT_ACCESS_ERROR = 0x0412 |
---|
220 | IPP_ATTRIBUTES_NOT_SETTABLE = 0x0413 |
---|
221 | IPP_IGNORED_ALL_SUBSCRIPTIONS = 0x0414 |
---|
222 | IPP_TOO_MANY_SUBSCRIPTIONS = 0x0415 |
---|
223 | IPP_IGNORED_ALL_NOTIFICATIONS = 0x0416 |
---|
224 | IPP_PRINT_SUPPORT_FILE_NOT_FOUND = 0x0417 |
---|
225 | |
---|
226 | IPP_INTERNAL_ERROR = 0x0500 |
---|
227 | IPP_OPERATION_NOT_SUPPORTED = 0x0501 |
---|
228 | IPP_SERVICE_UNAVAILABLE = 0x0502 |
---|
229 | IPP_VERSION_NOT_SUPPORTED = 0x0503 |
---|
230 | IPP_DEVICE_ERROR = 0x0504 |
---|
231 | IPP_TEMPORARY_ERROR = 0x0505 |
---|
232 | IPP_NOT_ACCEPTING = 0x0506 |
---|
233 | IPP_PRINTER_BUSY = 0x0507 |
---|
234 | IPP_ERROR_JOB_CANCELLED = 0x0508 |
---|
235 | IPP_MULTIPLE_JOBS_NOT_SUPPORTED = 0x0509 |
---|
236 | IPP_PRINTER_IS_DEACTIVATED = 0x50a |
---|
237 | |
---|
238 | class IPPError(Exception) : |
---|
239 | """An exception for IPP related stuff.""" |
---|
240 | def __init__(self, message = ""): |
---|
241 | self.message = message |
---|
242 | Exception.__init__(self, message) |
---|
243 | def __repr__(self): |
---|
244 | return self.message |
---|
245 | __str__ = __repr__ |
---|
246 | |
---|
247 | class FakeAttribute : |
---|
248 | """Fakes an IPPRequest attribute to simplify usage syntax.""" |
---|
249 | def __init__(self, request, name) : |
---|
250 | """Initializes the fake attribute.""" |
---|
251 | self.request = request |
---|
252 | self.name = name |
---|
253 | |
---|
254 | def __setitem__(self, key, value) : |
---|
255 | """Appends the value to the real attribute.""" |
---|
256 | attributeslist = getattr(self.request, "_%s_attributes" % self.name) |
---|
257 | for i in range(len(attributeslist)) : |
---|
258 | attribute = attributeslist[i] |
---|
259 | for j in range(len(attribute)) : |
---|
260 | (attrname, attrvalue) = attribute[j] |
---|
261 | if attrname == key : |
---|
262 | attribute[j][1].append(value) |
---|
263 | return |
---|
264 | attribute.append((key, [value])) |
---|
265 | |
---|
266 | def __getitem__(self, key) : |
---|
267 | """Returns an attribute's value.""" |
---|
268 | attributeslist = getattr(self.request, "_%s_attributes" % self.name) |
---|
269 | for i in range(len(attributeslist)) : |
---|
270 | attribute = attributeslist[i] |
---|
271 | for j in range(len(attribute)) : |
---|
272 | (attrname, attrvalue) = attribute[j] |
---|
273 | if attrname == key : |
---|
274 | return attrvalue |
---|
275 | raise KeyError, key |
---|
276 | |
---|
277 | class IPPRequest : |
---|
278 | """A class for IPP requests.""" |
---|
279 | attributes_types = ("operation", "job", "printer", "unsupported", \ |
---|
280 | "subscription", "event_notification") |
---|
281 | def __init__(self, data="", version=IPP_VERSION, |
---|
282 | operation_id=None, \ |
---|
283 | request_id=None, \ |
---|
284 | url = "http://localhost:631", \ |
---|
285 | username = None, \ |
---|
286 | password = None, \ |
---|
287 | debug=False) : |
---|
288 | """Initializes an IPP Message object. |
---|
289 | |
---|
290 | Parameters : |
---|
291 | |
---|
292 | data : the complete IPP Message's content. |
---|
293 | debug : a boolean value to output debug info on stderr. |
---|
294 | """ |
---|
295 | self.url = url |
---|
296 | self.username = username |
---|
297 | self.password = password |
---|
298 | self.debug = debug |
---|
299 | self._data = data |
---|
300 | self.parsed = False |
---|
301 | |
---|
302 | # Initializes message |
---|
303 | self.setVersion(version) |
---|
304 | self.setOperationId(operation_id) |
---|
305 | self.setRequestId(request_id) |
---|
306 | self.data = "" |
---|
307 | |
---|
308 | for attrtype in self.attributes_types : |
---|
309 | setattr(self, "_%s_attributes" % attrtype, [[]]) |
---|
310 | |
---|
311 | # Initialize tags |
---|
312 | self.tags = [ None ] * 256 # by default all tags reserved |
---|
313 | |
---|
314 | # Delimiter tags |
---|
315 | self.tags[0x01] = "operation-attributes-tag" |
---|
316 | self.tags[0x02] = "job-attributes-tag" |
---|
317 | self.tags[0x03] = "end-of-attributes-tag" |
---|
318 | self.tags[0x04] = "printer-attributes-tag" |
---|
319 | self.tags[0x05] = "unsupported-attributes-tag" |
---|
320 | self.tags[0x06] = "subscription-attributes-tag" |
---|
321 | self.tags[0x07] = "event-notification-attributes-tag" |
---|
322 | |
---|
323 | # out of band values |
---|
324 | self.tags[0x10] = "unsupported" |
---|
325 | self.tags[0x11] = "reserved-for-future-default" |
---|
326 | self.tags[0x12] = "unknown" |
---|
327 | self.tags[0x13] = "no-value" |
---|
328 | self.tags[0x15] = "not-settable" |
---|
329 | self.tags[0x16] = "delete-attribute" |
---|
330 | self.tags[0x17] = "admin-define" |
---|
331 | |
---|
332 | # integer values |
---|
333 | self.tags[0x20] = "generic-integer" |
---|
334 | self.tags[0x21] = "integer" |
---|
335 | self.tags[0x22] = "boolean" |
---|
336 | self.tags[0x23] = "enum" |
---|
337 | |
---|
338 | # octetString |
---|
339 | self.tags[0x30] = "octetString-with-an-unspecified-format" |
---|
340 | self.tags[0x31] = "dateTime" |
---|
341 | self.tags[0x32] = "resolution" |
---|
342 | self.tags[0x33] = "rangeOfInteger" |
---|
343 | self.tags[0x34] = "begCollection" # TODO : find sample files for testing |
---|
344 | self.tags[0x35] = "textWithLanguage" |
---|
345 | self.tags[0x36] = "nameWithLanguage" |
---|
346 | self.tags[0x37] = "endCollection" |
---|
347 | |
---|
348 | # character strings |
---|
349 | self.tags[0x40] = "generic-character-string" |
---|
350 | self.tags[0x41] = "textWithoutLanguage" |
---|
351 | self.tags[0x42] = "nameWithoutLanguage" |
---|
352 | self.tags[0x44] = "keyword" |
---|
353 | self.tags[0x45] = "uri" |
---|
354 | self.tags[0x46] = "uriScheme" |
---|
355 | self.tags[0x47] = "charset" |
---|
356 | self.tags[0x48] = "naturalLanguage" |
---|
357 | self.tags[0x49] = "mimeMediaType" |
---|
358 | self.tags[0x4a] = "memberAttrName" |
---|
359 | |
---|
360 | # Reverse mapping to generate IPP messages |
---|
361 | self.tagvalues = {} |
---|
362 | for i in range(len(self.tags)) : |
---|
363 | value = self.tags[i] |
---|
364 | if value is not None : |
---|
365 | self.tagvalues[value] = i |
---|
366 | |
---|
367 | def __getattr__(self, name) : |
---|
368 | """Fakes attribute access.""" |
---|
369 | if name in self.attributes_types : |
---|
370 | return FakeAttribute(self, name) |
---|
371 | else : |
---|
372 | raise AttributeError, name |
---|
373 | |
---|
374 | def __str__(self) : |
---|
375 | """Returns the parsed IPP message in a readable form.""" |
---|
376 | if not self.parsed : |
---|
377 | return "" |
---|
378 | mybuffer = [] |
---|
379 | mybuffer.append("IPP version : %s.%s" % self.version) |
---|
380 | mybuffer.append("IPP operation Id : 0x%04x" % self.operation_id) |
---|
381 | mybuffer.append("IPP request Id : 0x%08x" % self.request_id) |
---|
382 | for attrtype in self.attributes_types : |
---|
383 | for attribute in getattr(self, "_%s_attributes" % attrtype) : |
---|
384 | if attribute : |
---|
385 | mybuffer.append("%s attributes :" % attrtype.title()) |
---|
386 | for (name, value) in attribute : |
---|
387 | mybuffer.append(" %s : %s" % (name, value)) |
---|
388 | if self.data : |
---|
389 | mybuffer.append("IPP datas : %s" % repr(self.data)) |
---|
390 | return "\n".join(mybuffer) |
---|
391 | |
---|
392 | def logDebug(self, msg) : |
---|
393 | """Prints a debug message.""" |
---|
394 | if self.debug : |
---|
395 | sys.stderr.write("%s\n" % msg) |
---|
396 | sys.stderr.flush() |
---|
397 | |
---|
398 | def setVersion(self, version) : |
---|
399 | """Sets the request's operation id.""" |
---|
400 | if version is not None : |
---|
401 | try : |
---|
402 | self.version = [int(p) for p in version.split(".")] |
---|
403 | except AttributeError : |
---|
404 | if len(version) == 2 : # 2-tuple |
---|
405 | self.version = version |
---|
406 | else : |
---|
407 | try : |
---|
408 | self.version = [int(p) for p in str(float(version)).split(".")] |
---|
409 | except : |
---|
410 | self.version = [int(p) for p in IPP_VERSION.split(".")] |
---|
411 | |
---|
412 | def setOperationId(self, opid) : |
---|
413 | """Sets the request's operation id.""" |
---|
414 | self.operation_id = opid |
---|
415 | |
---|
416 | def setRequestId(self, reqid) : |
---|
417 | """Sets the request's request id.""" |
---|
418 | self.request_id = reqid |
---|
419 | |
---|
420 | def nextRequestId(self) : |
---|
421 | """Increments the current request id and returns the new value.""" |
---|
422 | try : |
---|
423 | self.request_id += 1 |
---|
424 | except TypeError : |
---|
425 | self.request_id = 1 |
---|
426 | return self.request_id |
---|
427 | |
---|
428 | def dump(self) : |
---|
429 | """Generates an IPP Message. |
---|
430 | |
---|
431 | Returns the message as a string of text. |
---|
432 | """ |
---|
433 | mybuffer = [] |
---|
434 | if None not in (self.version, self.operation_id) : |
---|
435 | if self.request_id is None : |
---|
436 | self.nextRequestId() |
---|
437 | mybuffer.append(chr(self.version[0]) + chr(self.version[1])) |
---|
438 | mybuffer.append(pack(">H", self.operation_id)) |
---|
439 | mybuffer.append(pack(">I", self.request_id)) |
---|
440 | for attrtype in self.attributes_types : |
---|
441 | for attribute in getattr(self, "_%s_attributes" % attrtype) : |
---|
442 | if attribute : |
---|
443 | mybuffer.append(chr(self.tagvalues["%s-attributes-tag" % attrtype])) |
---|
444 | for (attrname, value) in attribute : |
---|
445 | nameprinted = 0 |
---|
446 | for (vtype, val) in value : |
---|
447 | mybuffer.append(chr(self.tagvalues[vtype])) |
---|
448 | if not nameprinted : |
---|
449 | mybuffer.append(pack(">H", len(attrname))) |
---|
450 | mybuffer.append(attrname) |
---|
451 | nameprinted = 1 |
---|
452 | else : |
---|
453 | mybuffer.append(pack(">H", 0)) |
---|
454 | if vtype in ("integer", "enum") : |
---|
455 | mybuffer.append(pack(">H", 4)) |
---|
456 | mybuffer.append(pack(">I", val)) |
---|
457 | elif vtype == "boolean" : |
---|
458 | mybuffer.append(pack(">H", 1)) |
---|
459 | mybuffer.append(chr(val)) |
---|
460 | else : |
---|
461 | mybuffer.append(pack(">H", len(val))) |
---|
462 | mybuffer.append(val) |
---|
463 | mybuffer.append(chr(self.tagvalues["end-of-attributes-tag"])) |
---|
464 | mybuffer.append(self.data) |
---|
465 | return "".join(mybuffer) |
---|
466 | |
---|
467 | def parse(self) : |
---|
468 | """Parses an IPP Request. |
---|
469 | |
---|
470 | NB : Only a subset of RFC2910 is implemented. |
---|
471 | """ |
---|
472 | self._curname = None |
---|
473 | self._curattributes = None |
---|
474 | |
---|
475 | self.setVersion((ord(self._data[0]), ord(self._data[1]))) |
---|
476 | self.setOperationId(unpack(">H", self._data[2:4])[0]) |
---|
477 | self.setRequestId(unpack(">I", self._data[4:8])[0]) |
---|
478 | self.position = 8 |
---|
479 | endofattributes = self.tagvalues["end-of-attributes-tag"] |
---|
480 | maxdelimiter = self.tagvalues["event-notification-attributes-tag"] |
---|
481 | nulloffset = lambda : 0 |
---|
482 | try : |
---|
483 | tag = ord(self._data[self.position]) |
---|
484 | while tag != endofattributes : |
---|
485 | self.position += 1 |
---|
486 | name = self.tags[tag] |
---|
487 | if name is not None : |
---|
488 | func = getattr(self, name.replace("-", "_"), nulloffset) |
---|
489 | self.position += func() |
---|
490 | if ord(self._data[self.position]) > maxdelimiter : |
---|
491 | self.position -= 1 |
---|
492 | continue |
---|
493 | oldtag = tag |
---|
494 | tag = ord(self._data[self.position]) |
---|
495 | if tag == oldtag : |
---|
496 | self._curattributes.append([]) |
---|
497 | except IndexError : |
---|
498 | raise IPPError, "Unexpected end of IPP message." |
---|
499 | |
---|
500 | self.data = self._data[self.position+1:] |
---|
501 | self.parsed = True |
---|
502 | |
---|
503 | def parseTag(self) : |
---|
504 | """Extracts information from an IPP tag.""" |
---|
505 | pos = self.position |
---|
506 | tagtype = self.tags[ord(self._data[pos])] |
---|
507 | pos += 1 |
---|
508 | posend = pos2 = pos + 2 |
---|
509 | namelength = unpack(">H", self._data[pos:pos2])[0] |
---|
510 | if not namelength : |
---|
511 | name = self._curname |
---|
512 | else : |
---|
513 | posend += namelength |
---|
514 | self._curname = name = self._data[pos2:posend] |
---|
515 | pos2 = posend + 2 |
---|
516 | valuelength = unpack(">H", self._data[posend:pos2])[0] |
---|
517 | posend = pos2 + valuelength |
---|
518 | value = self._data[pos2:posend] |
---|
519 | if tagtype in ("integer", "enum") : |
---|
520 | value = unpack(">I", value)[0] |
---|
521 | elif tagtype == "boolean" : |
---|
522 | value = ord(value) |
---|
523 | try : |
---|
524 | (oldname, oldval) = self._curattributes[-1][-1] |
---|
525 | if oldname == name : |
---|
526 | oldval.append((tagtype, value)) |
---|
527 | else : |
---|
528 | raise IndexError |
---|
529 | except IndexError : |
---|
530 | self._curattributes[-1].append((name, [(tagtype, value)])) |
---|
531 | self.logDebug("%s(%s) : %s" % (name, tagtype, value)) |
---|
532 | return posend - self.position |
---|
533 | |
---|
534 | def operation_attributes_tag(self) : |
---|
535 | """Indicates that the parser enters into an operation-attributes-tag group.""" |
---|
536 | self._curattributes = self._operation_attributes |
---|
537 | return self.parseTag() |
---|
538 | |
---|
539 | def job_attributes_tag(self) : |
---|
540 | """Indicates that the parser enters into a job-attributes-tag group.""" |
---|
541 | self._curattributes = self._job_attributes |
---|
542 | return self.parseTag() |
---|
543 | |
---|
544 | def printer_attributes_tag(self) : |
---|
545 | """Indicates that the parser enters into a printer-attributes-tag group.""" |
---|
546 | self._curattributes = self._printer_attributes |
---|
547 | return self.parseTag() |
---|
548 | |
---|
549 | def unsupported_attributes_tag(self) : |
---|
550 | """Indicates that the parser enters into an unsupported-attributes-tag group.""" |
---|
551 | self._curattributes = self._unsupported_attributes |
---|
552 | return self.parseTag() |
---|
553 | |
---|
554 | def subscription_attributes_tag(self) : |
---|
555 | """Indicates that the parser enters into a subscription-attributes-tag group.""" |
---|
556 | self._curattributes = self._subscription_attributes |
---|
557 | return self.parseTag() |
---|
558 | |
---|
559 | def event_notification_attributes_tag(self) : |
---|
560 | """Indicates that the parser enters into an event-notification-attributes-tag group.""" |
---|
561 | self._curattributes = self._event_notification_attributes |
---|
562 | return self.parseTag() |
---|
563 | |
---|
564 | def doRequest(self, url=None, username=None, password=None, samerequestid=False) : |
---|
565 | """Sends the current request to the URL. |
---|
566 | NB : only ipp:// URLs are currently unsupported so use |
---|
567 | either http://host:631/ or https://host:443 instead... |
---|
568 | |
---|
569 | returns a new IPPRequest object, containing the parsed answer. |
---|
570 | """ |
---|
571 | if not samerequestid : |
---|
572 | self.nextRequestId() |
---|
573 | cx = urllib2.Request(url=url or self.url or "http://localhost:631/", |
---|
574 | data=self.dump()) |
---|
575 | cx.add_header("Content-Type", "application/ipp") |
---|
576 | response = urllib2.urlopen(cx) |
---|
577 | datas = response.read() |
---|
578 | ippresponse = IPPRequest(datas) |
---|
579 | ippresponse.parse() |
---|
580 | return ippresponse |
---|
581 | |
---|
582 | |
---|
583 | class CUPS : |
---|
584 | """A class for a CUPS instance.""" |
---|
585 | def __init__(self, url="http://localhost:631", username=None, password=None, charset="utf-8", language="en-us") : |
---|
586 | """Initializes the CUPS instance.""" |
---|
587 | self.url = url |
---|
588 | self.username = username |
---|
589 | self.password = password |
---|
590 | self.charset = charset |
---|
591 | self.language = language |
---|
592 | |
---|
593 | def identifierToURI(self, service, ident) : |
---|
594 | """Transforms an identifier into a particular URI depending on requested service.""" |
---|
595 | return "%s/%s/%s" % (self.url.replace("http://", "ipp://"), |
---|
596 | service, |
---|
597 | ident) |
---|
598 | |
---|
599 | def newRequest(self, operationid=None) : |
---|
600 | """Generates a new empty request.""" |
---|
601 | if operationid is not None : |
---|
602 | req = IPPRequest(operation_id=operationid, \ |
---|
603 | url=self.url, \ |
---|
604 | username=self.username, \ |
---|
605 | password=self.password) |
---|
606 | req.operation["attributes-charset"] = ("charset", self.charset) |
---|
607 | req.operation["attributes-natural-language"] = ("naturalLanguage", self.language) |
---|
608 | return req |
---|
609 | |
---|
610 | def getDefault(self) : |
---|
611 | """Retrieves CUPS' default printer.""" |
---|
612 | return self.newRequest(CUPS_GET_DEFAULT).doRequest() |
---|
613 | |
---|
614 | def getJobAttributes(self, jobid) : |
---|
615 | """Retrieves a print job's attributes.""" |
---|
616 | req = self.newRequest(IPP_GET_JOB_ATTRIBUTES) |
---|
617 | req.operation["job-uri"] = ("uri", self.identifierToURI("jobs", jobid)) |
---|
618 | return req.doRequest() |
---|
619 | |
---|
620 | def getPPD(self, queuename) : |
---|
621 | """Retrieves the PPD for a particular queuename.""" |
---|
622 | req = self.newRequest(IPP_GET_PRINTER_ATTRIBUTES) |
---|
623 | req.operation["printer-uri"] = ("uri", self.identifierToURI("printers", queuename)) |
---|
624 | for attrib in ("printer-uri-supported", "printer-type", "member-uris") : |
---|
625 | req.operation["requested-attributes"] = ("nameWithoutLanguage", attrib) |
---|
626 | return req.doRequest() # TODO : get the PPD from the actual print server |
---|
627 | |
---|
628 | |
---|
629 | if __name__ == "__main__" : |
---|
630 | if (len(sys.argv) < 2) or (sys.argv[1] == "--debug") : |
---|
631 | print "usage : python ipp.py /var/spool/cups/c00005 [--debug] (for example)\n" |
---|
632 | else : |
---|
633 | infile = open(sys.argv[1], "rb") |
---|
634 | data = infile.read() |
---|
635 | infile.close() |
---|
636 | |
---|
637 | message = IPPRequest(data, debug=(sys.argv[-1]=="--debug")) |
---|
638 | message.parse() |
---|
639 | message2 = IPPRequest(message.dump()) |
---|
640 | message2.parse() |
---|
641 | data2 = message2.dump() |
---|
642 | |
---|
643 | if data == data2 : |
---|
644 | print "Test OK : parsing original and parsing the output of the dump produce the same dump !" |
---|
645 | print str(message) |
---|
646 | else : |
---|
647 | print "Test Failed !" |
---|
648 | print str(message) |
---|
649 | print |
---|
650 | print str(message2) |
---|
651 | |
---|