Debian Codegraph @

asyncpk1.py

raw
1 #!/usr/bin/python3
2
3 ## Copyright (C) 2007, 2008, 2009, 2010, 2012, 2013, 2014 Red Hat, Inc.
4 ## Copyright (C) 2008 Novell, Inc.
5 ## Authors: Tim Waugh <[email protected]>, Vincent Untz
6
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 import cups
22 import dbus
23 from functools import reduce
24 try:
25 import gi
26 gi.require_version('Gdk', '3.0')
27 from gi.repository import Gdk
28 gi.require_version('Gtk', '3.0')
29 from gi.repository import Gtk
30 except:
31 pass
32 import os
33 import sys
34 import tempfile
35 import xml.etree.ElementTree
36
37 import asyncipp
38 from debug import *
39 import debug
40
41 CUPS_PK_NAME = 'org.opensuse.CupsPkHelper.Mechanism'
42 CUPS_PK_PATH = '/'
43 CUPS_PK_IFACE = 'org.opensuse.CupsPkHelper.Mechanism'
44 CUPS_PK_NEED_AUTH = 'org.opensuse.CupsPkHelper.Mechanism.NotPrivileged'
45
46 ######
47 ###### A polkit-1 based asynchronous CupsPkHelper interface made to
48 ###### look just like a normal IPPAuthConnection class. For method
49 ###### calls that have no equivalent in the CupsPkHelper API, IPP
50 ###### authentication is used over a CUPS connection in a separate
51 ###### thread.
52 ######
53
54 _DevicesGet_uses_new_api = None
55
56 ###
57 ### A class to handle an asynchronous method call.
58 ###
59 class _PK1AsyncMethodCall:
60 def __init__ (self, bus, conn, pk_method_name, pk_args,
61 reply_handler, error_handler, unpack_fn,
62 fallback_fn, args, kwds):
63 self._bus = bus
64 self._conn = conn
65 self._pk_method_name = pk_method_name
66 self._pk_args = pk_args
67 self._client_reply_handler = reply_handler
68 self._client_error_handler = error_handler
69 self._unpack_fn = unpack_fn
70 self._fallback_fn = fallback_fn
71 self._fallback_args = args
72 self._fallback_kwds = kwds
73 self._destroyed = False
74 debugprint ("+_PK1AsyncMethodCall: %s" % self)
75
76 def __del__ (self):
77 debug.debugprint ("-_PK1AsyncMethodCall: %s" % self)
78
79 def call (self):
80 object = self._bus.get_object(CUPS_PK_NAME, CUPS_PK_PATH)
81 proxy = dbus.Interface (object, CUPS_PK_IFACE)
82 pk_method = proxy.get_dbus_method (self._pk_method_name)
83
84 try:
85 debugprint ("%s: calling %s" % (self, pk_method))
86 pk_method (*self._pk_args,
87 reply_handler=self._pk_reply_handler,
88 error_handler=self._pk_error_handler,
89 timeout=3600)
90 except TypeError as e:
91 debugprint ("Type error in PK call: %s" % repr (e))
92 self.call_fallback_fn ()
93
94 def _destroy (self):
95 debugprint ("DESTROY: %s" % self)
96 self._destroyed = True
97 del self._bus
98 del self._conn
99 del self._pk_method_name
100 del self._pk_args
101 del self._client_reply_handler
102 del self._client_error_handler
103 del self._unpack_fn
104 del self._fallback_fn
105 del self._fallback_args
106 del self._fallback_kwds
107
108 def _pk_reply_handler (self, error, *args):
109 if self._destroyed:
110 return
111
112 if str (error) == '':
113 try:
114 Gdk.threads_enter ()
115 except:
116 pass
117 debugprint ("%s: no error, calling reply handler %s" %
118 (self, self._client_reply_handler))
119 self._client_reply_handler (self._conn, self._unpack_fn (*args))
120 try:
121 Gdk.threads_leave ()
122 except:
123 pass
124 self._destroy ()
125 return
126
127 debugprint ("PolicyKit method failed with: %s" % repr (error))
128 self.call_fallback_fn ()
129
130 def _pk_error_handler (self, exc):
131 if self._destroyed:
132 return
133
134 if exc.get_dbus_name () == CUPS_PK_NEED_AUTH:
135 exc = cups.IPPError (cups.IPP_NOT_AUTHORIZED, 'pkcancel')
136 try:
137 Gdk.threads_enter ()
138 except:
139 pass
140 debugprint ("%s: no auth, calling error handler %s" %
141 (self, self._client_error_handler))
142 self._client_error_handler (self._conn, exc)
143 try:
144 Gdk.threads_leave ()
145 except:
146 pass
147 self._destroy ()
148 return
149
150 debugprint ("PolicyKit call to %s did not work: %s" %
151 (self._pk_method_name, repr (exc)))
152 self.call_fallback_fn ()
153
154 def call_fallback_fn (self):
155 # Make the 'connection' parameter consistent with PK callbacks.
156 self._fallback_kwds["reply_handler"] = self._ipp_reply_handler
157 self._fallback_kwds["error_handler"] = self._ipp_error_handler
158 debugprint ("%s: calling %s" % (self, self._fallback_fn))
159 self._fallback_fn (*self._fallback_args, **self._fallback_kwds)
160
161 def _ipp_reply_handler (self, conn, *args):
162 if self._destroyed:
163 return
164
165 debugprint ("%s: chaining up to %s" % (self,
166 self._client_reply_handler))
167 self._client_reply_handler (self._conn, *args)
168 self._destroy ()
169
170 def _ipp_error_handler (self, conn, *args):
171 if self._destroyed:
172 return
173
174 debugprint ("%s: chaining up to %s" % (self,
175 self._client_error_handler))
176 self._client_error_handler (self._conn, *args)
177 self._destroy ()
178
179 ###
180 ### A class for handling FileGet when a temporary file is needed.
181 ###
182 class _WriteToTmpFile:
183 def __init__ (self, kwds, reply_handler, error_handler):
184 self._reply_handler = reply_handler
185 self._error_handler = error_handler
186
187 # Create the temporary file in /tmp to ensure that
188 # cups-pk-helper-mechanism is able to write to it.
189 (tmpfd, tmpfname) = tempfile.mkstemp (dir="/tmp")
190 os.close (tmpfd)
191 self._filename = tmpfname
192 debugprint ("Created tempfile %s" % tmpfname)
193 self._kwds = kwds
194
195 def __del__ (self):
196 try:
197 os.unlink (self._filename)
198 debug.debugprint ("Removed tempfile %s" % self._filename)
199 except:
200 debug.debugprint ("No tempfile to remove")
201
202 def get_filename (self):
203 return self._filename
204
205 def reply_handler (self, conn, none):
206 tmpfd = os.open (self._filename, os.O_RDONLY)
207 tmpfile = os.fdopen (tmpfd, 'rt')
208 if "fd" in self._kwds:
209 fd = self._kwds["fd"]
210 os.lseek (fd, 0, os.SEEK_SET)
211 line = tmpfile.readline ()
212 while line != '':
213 os.write (fd, line.encode('UTF-8'))
214 line = tmpfile.readline ()
215 else:
216 file_object = self._kwds["file"]
217 file_object.seek (0)
218 line = tmpfile.readline ()
219 while line != '':
220 file_object.write (line.encode('UTF-8'))
221 line = tmpfile.readline ()
222
223 tmpfile.close ()
224 self._reply_handler (conn, none)
225
226 def error_handler (self, conn, exc):
227 self._error_handler (conn, exc)
228
229 ###
230 ### The user-visible class.
231 ###
232 class PK1Connection:
233 def __init__(self, reply_handler=None, error_handler=None,
234 host=None, port=None, encryption=None, parent=None):
235 self._conn = asyncipp.IPPAuthConnection (reply_handler=reply_handler,
236 error_handler=error_handler,
237 host=host, port=port,
238 encryption=encryption,
239 parent=parent)
240
241 try:
242 self._system_bus = dbus.SystemBus()
243 except (dbus.exceptions.DBusException, AttributeError):
244 # No system D-Bus.
245 self._system_bus = None
246
247 global _DevicesGet_uses_new_api
248 if _DevicesGet_uses_new_api is None and self._system_bus:
249 try:
250 obj = self._system_bus.get_object(CUPS_PK_NAME, CUPS_PK_PATH)
251 proxy = dbus.Interface (obj, dbus.INTROSPECTABLE_IFACE)
252 api = proxy.Introspect ()
253 top = xml.etree.ElementTree.XML (api)
254 for interface in top.findall ("interface"):
255 if interface.attrib.get ("name") != CUPS_PK_IFACE:
256 continue
257
258 for method in interface.findall ("method"):
259 if method.attrib.get ("name") != "DevicesGet":
260 continue
261
262 num_args = 0
263 for arg in method.findall ("arg"):
264 direction = arg.attrib.get ("direction")
265 if direction != "in":
266 continue
267
268 num_args += 1
269
270 _DevicesGet_uses_new_api = num_args == 4
271 debugprint ("DevicesGet new API: %s" % (num_args == 4))
272 break
273
274 break
275
276 except Exception as e:
277 debugprint ("Exception assessing DevicesGet API: %s" % repr (e))
278
279 methodtype = type (self._conn.getPrinters)
280 bindings = []
281 for fname in dir (self._conn):
282 if fname.startswith ('_'):
283 continue
284 fn = getattr (self._conn, fname)
285 if type (fn) != methodtype:
286 continue
287 if not hasattr (self, fname):
288 setattr (self, fname, self._make_binding (fn))
289 bindings.append (fname)
290
291 self._bindings = bindings
292 debugprint ("+%s" % self)
293
294 def __del__ (self):
295 debug.debugprint ("-%s" % self)
296
297 def _make_binding (self, fn):
298 def binding (*args, **kwds):
299 op = _PK1AsyncMethodCall (None, self, None, None,
300 kwds.get ("reply_handler"),
301 kwds.get ("error_handler"),
302 None, fn, args, kwds)
303 op.call_fallback_fn ()
304
305 return binding
306
307 def destroy (self):
308 debugprint ("DESTROY: %s" % self)
309 self._conn.destroy ()
310
311 for binding in self._bindings:
312 delattr (self, binding)
313
314 def _coerce (self, typ, val):
315 return typ (val)
316
317 def _args_kwds_to_tuple (self, types, params, args, kwds):
318 """Collapse args and kwds into a single tuple."""
319 leftover_kwds = kwds.copy ()
320 reply_handler = leftover_kwds.get ("reply_handler")
321 error_handler = leftover_kwds.get ("error_handler")
322 if "reply_handler" in leftover_kwds:
323 del leftover_kwds["reply_handler"]
324 if "error_handler" in leftover_kwds:
325 del leftover_kwds["error_handler"]
326 if "auth_handler" in leftover_kwds:
327 del leftover_kwds["auth_handler"]
328
329 result = [True, reply_handler, error_handler, ()]
330 if self._system_bus is None:
331 return result
332
333 tup = []
334 argindex = 0
335 for arg in args:
336 try:
337 val = self._coerce (types[argindex], arg)
338 except IndexError:
339 # More args than types.
340 kw, default = params[argindex]
341 if default != arg:
342 return result
343
344 # It's OK, this is the default value anyway and can be
345 # ignored. Skip to the next one.
346 argindex += 1
347 continue
348 except TypeError as e:
349 debugprint ("Error converting %s to %s" %
350 (repr (arg), types[argindex]))
351 return result
352
353 tup.append (val)
354 argindex += 1
355
356 for kw, default in params[argindex:]:
357 if kw in leftover_kwds:
358 try:
359 val = self._coerce (types[argindex], leftover_kwds[kw])
360 except TypeError as e:
361 debugprint ("Error converting %s to %s" %
362 (repr (leftover_kwds[kw]), types[argindex]))
363 return result
364
365 tup.append (val)
366 del leftover_kwds[kw]
367 else:
368 tup.append (default)
369
370 argindex += 1
371
372 if leftover_kwds:
373 debugprint ("Leftover keywords: %s" % repr (list(leftover_kwds.keys ())))
374 return result
375
376 result[0] = False
377 result[3] = tuple (tup)
378 debugprint ("Converted %s/%s to %s" % (args, kwds, tuple (tup)))
379 return result
380
381 def _call_with_pk (self, use_pycups, pk_method_name, pk_args,
382 reply_handler, error_handler, unpack_fn,
383 fallback_fn, args, kwds):
384 asyncmethodcall = _PK1AsyncMethodCall (self._system_bus, self,
385 pk_method_name, pk_args,
386 reply_handler,
387 error_handler,
388 unpack_fn, fallback_fn,
389 args, kwds)
390
391 if not use_pycups:
392 try:
393 debugprint ("Calling PK method %s" % pk_method_name)
394 asyncmethodcall.call ()
395 except dbus.DBusException as e:
396 debugprint ("D-Bus call failed: %s" % repr (e))
397 use_pycups = True
398
399 if use_pycups:
400 return asyncmethodcall.call_fallback_fn ()
401
402 def _nothing_to_unpack (self):
403 return None
404
405 def getDevices (self, *args, **kwds):
406 global _DevicesGet_uses_new_api
407 if _DevicesGet_uses_new_api:
408 (use_pycups, reply_handler, error_handler,
409 tup) = self._args_kwds_to_tuple ([int, int, list, list],
410 [("timeout", 0),
411 ("limit", 0),
412 ("include_schemes", []),
413 ("exclude_schemes", [])],
414 args, kwds)
415 else:
416 (use_pycups, reply_handler, error_handler,
417 tup) = self._args_kwds_to_tuple ([int, list, list],
418 [("limit", 0),
419 ("include_schemes", []),
420 ("exclude_schemes", [])],
421 args, kwds)
422
423 if not use_pycups:
424 # Special handling for include_schemes/exclude_schemes.
425 # Convert from list to ","-separated string.
426 newtup = list (tup)
427 for paramindex in [1, 2]:
428 if len (newtup[paramindex]) > 0:
429 newtup[paramindex] = reduce (lambda x, y:
430 x + "," + y,
431 newtup[paramindex])
432 else:
433 newtup[paramindex] = ""
434
435 tup = tuple (newtup)
436
437 self._call_with_pk (use_pycups,
438 'DevicesGet', tup, reply_handler, error_handler,
439 self._unpack_getDevices_reply,
440 self._conn.getDevices, args, kwds)
441
442 def _unpack_getDevices_reply (self, dbusdict):
443 result_str = dict()
444 for key, value in dbusdict.items ():
445 if type (key) == dbus.String:
446 result_str[str (key)] = str (value)
447 else:
448 result_str[key] = value
449
450 # cups-pk-helper returns all devices in one dictionary.
451 # Keys of different devices are distinguished by ':n' postfix.
452
453 devices = dict()
454 n = 0
455 affix = ':' + str (n)
456 device_keys = [x for x in result_str.keys () if x.endswith (affix)]
457 while len (device_keys) > 0:
458 device_uri = None
459 device_dict = dict()
460 for keywithaffix in device_keys:
461 key = keywithaffix[:len (keywithaffix) - len (affix)]
462 if key != 'device-uri':
463 device_dict[key] = result_str[keywithaffix]
464 else:
465 device_uri = result_str[keywithaffix]
466
467 if device_uri is not None:
468 devices[device_uri] = device_dict
469
470 n += 1
471 affix = ':' + str (n)
472 device_keys = [x for x in result_str.keys () if x.endswith (affix)]
473
474 return devices
475
476 def cancelJob (self, *args, **kwds):
477 (use_pycups, reply_handler, error_handler,
478 tup) = self._args_kwds_to_tuple ([int, bool],
479 [(None, None),
480 (None, False)], # purge_job
481 args, kwds)
482
483 self._call_with_pk (use_pycups,
484 'JobCancelPurge', tup, reply_handler, error_handler,
485 self._nothing_to_unpack,
486 self._conn.cancelJob, args, kwds)
487
488 def setJobHoldUntil (self, *args, **kwds):
489 (use_pycups, reply_handler, error_handler,
490 tup) = self._args_kwds_to_tuple ([int, str],
491 [(None, None),
492 (None, None)],
493 args, kwds)
494
495 self._call_with_pk (use_pycups,
496 'JobSetHoldUntil', tup, reply_handler,
497 error_handler, self._nothing_to_unpack,
498 self._conn.setJobHoldUntil, args, kwds)
499
500 def restartJob (self, *args, **kwds):
501 (use_pycups, reply_handler, error_handler,
502 tup) = self._args_kwds_to_tuple ([int],
503 [(None, None)],
504 args, kwds)
505
506 self._call_with_pk (use_pycups,
507 'JobRestart', tup, reply_handler,
508 error_handler, self._nothing_to_unpack,
509 self._conn.restartJob, args, kwds)
510
511 def getFile (self, *args, **kwds):
512 (use_pycups, reply_handler, error_handler,
513 tup) = self._args_kwds_to_tuple ([str, str],
514 [("resource", None),
515 ("filename", None)],
516 args, kwds)
517
518 # getFile(resource, filename=None, fd=-1, file=None) -> None
519 if use_pycups:
520 if ((len (args) == 0 and 'resource' in kwds) or
521 (len (args) == 1)):
522 can_use_tempfile = True
523 for each in kwds.keys ():
524 if each not in ['resource', 'fd', 'file',
525 'reply_handler', 'error_handler']:
526 can_use_tempfile = False
527 break
528
529 if can_use_tempfile:
530 # We can still use PackageKit for this.
531 if len (args) == 0:
532 resource = kwds["resource"]
533 else:
534 resource = args[0]
535
536 wrapper = _WriteToTmpFile (kwds,
537 reply_handler,
538 error_handler)
539 self._call_with_pk (False,
540 'FileGet',
541 (resource, wrapper.get_filename ()),
542 wrapper.reply_handler,
543 wrapper.error_handler,
544 self._nothing_to_unpack,
545 self._conn.getFile, args, kwds)
546 return
547
548 self._call_with_pk (use_pycups,
549 'FileGet', tup, reply_handler,
550 error_handler, self._nothing_to_unpack,
551 self._conn.getFile, args, kwds)
552
553 ## etc
554 ## Still to implement:
555 ## putFile
556 ## addPrinter
557 ## setPrinterDevice
558 ## setPrinterInfo
559 ## setPrinterLocation
560 ## setPrinterShared
561 ## setPrinterJobSheets
562 ## setPrinterErrorPolicy
563 ## setPrinterOpPolicy
564 ## setPrinterUsersAllowed
565 ## setPrinterUsersDenied
566 ## addPrinterOptionDefault
567 ## deletePrinterOptionDefault
568 ## deletePrinter
569 ## addPrinterToClass
570 ## deletePrinterFromClass
571 ## deleteClass
572 ## setDefault
573 ## enablePrinter
574 ## disablePrinter
575 ## acceptJobs
576 ## rejectJobs
577 ## adminGetServerSettings
578 ## adminSetServerSettings
579 ## ...
580
581 if __name__ == '__main__':
582 from gi.repository import GObject
583 from debug import set_debugging
584 set_debugging (True)
585 class UI:
586 def __init__ (self):
587 w = Gtk.Window ()
588 v = Gtk.VBox ()
589 w.add (v)
590 b = Gtk.Button.new_with_label ("Go")
591 v.pack_start (b, False, False, 0)
592 b.connect ("clicked", self.button_clicked)
593 b = Gtk.Button.new_with_label ("Fetch")
594 v.pack_start (b, False, False, 0)
595 b.connect ("clicked", self.fetch_clicked)
596 b.set_sensitive (False)
597 self.fetch_button = b
598 b = Gtk.Button.new_with_label ("Cancel job")
599 v.pack_start (b, False, False, 0)
600 b.connect ("clicked", self.cancel_clicked)
601 b.set_sensitive (False)
602 self.cancel_button = b
603 b = Gtk.Button.new_with_label ("Get file")
604 v.pack_start (b, False, False, 0)
605 b.connect ("clicked", self.get_file_clicked)
606 b.set_sensitive (False)
607 self.get_file_button = b
608 b = Gtk.Button.new_with_label ("Something harmless")
609 v.pack_start (b, False, False, 0)
610 b.connect ("clicked", self.harmless_clicked)
611 b.set_sensitive (False)
612 self.harmless_button = b
613 w.connect ("destroy", self.destroy)
614 w.show_all ()
615 self.conn = None
616 debugprint ("+%s" % self)
617
618 def __del__ (self):
619 debug.debugprint ("-%s" % self)
620
621 def destroy (self, window):
622 debugprint ("DESTROY: %s" % self)
623 try:
624 self.conn.destroy ()
625 del self.conn
626 except AttributeError:
627 pass
628
629 Gtk.main_quit ()
630
631 def button_clicked (self, button):
632 if self.conn:
633 self.conn.destroy ()
634
635 self.conn = PK1Connection (reply_handler=self.connected,
636 error_handler=self.connection_error)
637
638 def connected (self, conn, result):
639 print("Connected")
640 self.fetch_button.set_sensitive (True)
641 self.cancel_button.set_sensitive (True)
642 self.get_file_button.set_sensitive (True)
643 self.harmless_button.set_sensitive (True)
644
645 def connection_error (self, conn, error):
646 print("Failed to connect")
647 raise error
648
649 def fetch_clicked (self, button):
650 print ("fetch devices...")
651 self.conn.getDevices (reply_handler=self.got_devices,
652 error_handler=self.get_devices_error)
653
654 def got_devices (self, conn, devices):
655 if conn != self.conn:
656 print("Ignoring stale reply")
657 return
658
659 print("got devices: %s" % devices)
660
661 def get_devices_error (self, conn, exc):
662 if conn != self.conn:
663 print("Ignoring stale error")
664 return
665
666 print("devices error: %s" % repr (exc))
667
668 def cancel_clicked (self, button):
669 print("Cancel job...")
670 self.conn.cancelJob (1,
671 reply_handler=self.job_canceled,
672 error_handler=self.cancel_job_error)
673
674 def job_canceled (self, conn, none):
675 if conn != self.conn:
676 print("Ignoring stale reply for %s" % conn)
677 return
678
679 print("Job canceled")
680
681 def cancel_job_error (self, conn, exc):
682 if conn != self.conn:
683 print("Ignoring stale error for %s" % conn)
684 return
685
686 print("cancel error: %s" % repr (exc))
687
688 def get_file_clicked (self, button):
689 self.my_file = open ("cupsd.conf", "w")
690 self.conn.getFile ("/admin/conf/cupsd.conf", file=self.my_file,
691 reply_handler=self.got_file,
692 error_handler=self.get_file_error)
693
694 def got_file (self, conn, none):
695 if conn != self.conn:
696 print("Ignoring stale reply for %s" % conn)
697 return
698
699 print("Got file")
700
701 def get_file_error (self, conn, exc):
702 if conn != self.conn:
703 print("Ignoring stale error")
704 return
705
706 print("get file error: %s" % repr (exc))
707
708 def harmless_clicked (self, button):
709 self.conn.getJobs (reply_handler=self.got_jobs,
710 error_handler=self.get_jobs_error)
711
712 def got_jobs (self, conn, result):
713 if conn != self.conn:
714 print("Ignoring stale reply from %s" % repr (conn))
715 return
716 print(result)
717
718 def get_jobs_error (self, exc):
719 print("get jobs error: %s" % repr (exc))
720
721 UI ()
722 from dbus.mainloop.glib import DBusGMainLoop
723 DBusGMainLoop (set_as_default=True)
724 Gtk.main ()