Debian Codegraph @

asyncipp.py

raw
1 #!/usr/bin/python3
2
3 ## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015 Red Hat, Inc.
4 ## Copyright (C) 2008 Novell, Inc.
5 ## Author: Tim Waugh <[email protected]>
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 threading
22 import config
23 import cups
24 from gi.repository import GObject
25 from gi.repository import GLib
26 from gi.repository import Gdk
27 from gi.repository import Gtk
28 import queue
29
30 cups.require ("1.9.60")
31
32 import authconn
33 from debug import *
34 import debug
35 import gettext
36 gettext.install(domain=config.PACKAGE, localedir=config.localedir)
37
38
39 ######
40 ###### An asynchronous libcups API using IPP with a separate worker
41 ###### thread.
42 ######
43
44 ###
45 ### This is the worker thread.
46 ###
47 class _IPPConnectionThread(threading.Thread):
48 def __init__ (self, myqueue, conn, reply_handler=None, error_handler=None,
49 auth_handler=None, user=None, host=None, port=None,
50 encryption=None):
51
52 threading.Thread.__init__ (self)
53 self.setDaemon (True)
54 self._queue = myqueue
55 self._conn = conn
56 self.host = host
57 self.port = port
58 self._encryption = encryption
59 self._reply_handler = reply_handler
60 self._error_handler = error_handler
61 self._auth_handler = auth_handler
62 self._auth_queue = queue.Queue(1)
63 self.user = user
64 self._destroyed = False
65 debugprint ("+%s" % self)
66
67 def __del__ (self):
68 debug.debugprint ("-%s" % self)
69
70 def set_auth_info (self, password):
71 self._auth_queue.put (password)
72
73 def run (self):
74 if self.host is None:
75 self.host = cups.getServer ()
76 if self.port is None:
77 self.port = cups.getPort ()
78 if self._encryption is None:
79 self._encryption = cups.getEncryption ()
80
81 if self.user:
82 cups.setUser (self.user)
83 else:
84 self.user = cups.getUser ()
85
86 cups.setPasswordCB2 (self._auth)
87
88 try:
89 conn = cups.Connection (host=self.host,
90 port=self.port,
91 encryption=self._encryption)
92 self._reply (None)
93 except RuntimeError as e:
94 conn = None
95 self._error (e)
96
97 while True:
98 # Wait to find out what operation to try.
99 debugprint ("Awaiting further instructions")
100 self.idle = self._queue.empty ()
101 item = self._queue.get ()
102 debugprint ("Next task: %s" % repr (item))
103 if item is None:
104 # Our signal to quit.
105 self._queue.task_done ()
106 break
107 elif self._destroyed:
108 # Just mark all tasks done
109 self._queue.task_done ()
110 continue
111
112 self.idle = False
113 (fn, args, kwds, rh, eh, ah) = item
114 if rh != False:
115 self._reply_handler = rh
116 if eh != False:
117 self._error_handler = eh
118 if ah != False:
119 self._auth_handler = ah
120
121 if fn == True:
122 # Our signal to change user and reconnect.
123 self.user = args[0]
124 cups.setUser (self.user)
125 debugprint ("Set user=%s; reconnecting..." % self.user)
126 cups.setPasswordCB2 (self._auth)
127
128 try:
129 conn = cups.Connection (host=self.host,
130 port=self.port,
131 encryption=self._encryption)
132 debugprint ("...reconnected")
133
134 self._queue.task_done ()
135 self._reply (None)
136 except RuntimeError as e:
137 debugprint ("...failed")
138 self._queue.task_done ()
139 self._error (e)
140
141 continue
142
143 # Normal IPP operation. Try to perform it.
144 try:
145 debugprint ("Call %s" % fn)
146 result = fn (conn, *args, **kwds)
147 if fn == cups.Connection.adminGetServerSettings.__call__:
148 # Special case for a rubbish bit of API.
149 if result == {}:
150 # Authentication failed, but we aren't told that.
151 raise cups.IPPError (cups.IPP_NOT_AUTHORIZED, '')
152
153 debugprint ("...success")
154 self._reply (result)
155 except Exception as e:
156 debugprint ("...failure (%s)" % repr (e))
157 self._error (e)
158
159 self._queue.task_done ()
160
161 debugprint ("Thread exiting")
162 del self._conn # already destroyed
163 del self._reply_handler
164 del self._error_handler
165 del self._auth_handler
166 del self._queue
167 del self._auth_queue
168 del conn
169
170 cups.setPasswordCB2 (None)
171
172 def stop (self):
173 self._destroyed = True
174 self._queue.put (None)
175
176 def _auth (self, prompt, conn=None, method=None, resource=None):
177 def prompt_auth (prompt):
178 Gdk.threads_enter ()
179 if conn is None:
180 self._auth_handler (prompt, self._conn)
181 else:
182 self._auth_handler (prompt, self._conn, method, resource)
183
184 Gdk.threads_leave ()
185 return False
186
187 if self._auth_handler is None:
188 return ""
189
190 GLib.idle_add (prompt_auth, prompt)
191 password = self._auth_queue.get ()
192 return password
193
194 def _reply (self, result):
195 def send_reply (handler, result):
196 if not self._destroyed:
197 Gdk.threads_enter ()
198 handler (self._conn, result)
199 Gdk.threads_leave ()
200 return False
201
202 if not self._destroyed and self._reply_handler:
203 GLib.idle_add (send_reply, self._reply_handler, result)
204
205 def _error (self, exc):
206 def send_error (handler, exc):
207 if not self._destroyed:
208 Gdk.threads_enter ()
209 handler (self._conn, exc)
210 Gdk.threads_leave ()
211 return False
212
213 if not self._destroyed and self._error_handler:
214 debugprint ("Add %s to idle" % self._error_handler)
215 GLib.idle_add (send_error, self._error_handler, exc)
216
217 ###
218 ### This is the user-visible class. Although it does not inherit from
219 ### cups.Connection it implements the same functions.
220 ###
221 class IPPConnection:
222 """
223 This class starts a new thread to handle IPP operations.
224
225 Each IPP operation method takes optional reply_handler,
226 error_handler and auth_handler parameters.
227
228 If an operation requires a password to proceed, the auth_handler
229 function will be called. The operation will continue once
230 set_auth_info (in this class) is called.
231
232 Once the operation has finished either reply_handler or
233 error_handler will be called.
234 """
235
236 def __init__ (self, reply_handler=None, error_handler=None,
237 auth_handler=None, user=None, host=None, port=None,
238 encryption=None, parent=None):
239 debugprint ("New IPPConnection")
240 self._parent = parent
241 self.queue = queue.Queue ()
242 self.thread = _IPPConnectionThread (self.queue, self,
243 reply_handler=reply_handler,
244 error_handler=error_handler,
245 auth_handler=auth_handler,
246 user=user, host=host, port=port,
247 encryption=encryption)
248 self.thread.start ()
249
250 methodtype = type (cups.Connection.getPrinters)
251 bindings = []
252 for fname in dir (cups.Connection):
253 if fname[0] == ' ':
254 continue
255 fn = getattr (cups.Connection, fname)
256 if type (fn) != methodtype:
257 continue
258 setattr (self, fname, self._make_binding (fn))
259 bindings.append (fname)
260
261 self.bindings = bindings
262 debugprint ("+%s" % self)
263
264 def __del__ (self):
265 debug.debugprint ("-%s" % self)
266
267 def destroy (self):
268 debugprint ("DESTROY: %s" % self)
269 for binding in self.bindings:
270 delattr (self, binding)
271
272 if self.thread.is_alive ():
273 debugprint ("Stopping worker thread")
274 self.thread.stop ()
275 GLib.timeout_add_seconds (1, self._reap_thread)
276
277 def _reap_thread (self):
278 if self.thread.idle:
279 self.queue.join ()
280 return False
281
282 debugprint ("Thread %s still processing tasks" % self.thread)
283 return True
284
285 def set_auth_info (self, password):
286 """Call this from your auth_handler function."""
287 self.thread.set_auth_info (password)
288
289 def reconnect (self, user, reply_handler=None, error_handler=None):
290 debugprint ("Reconnect...")
291 self.queue.put ((True, (user,), {},
292 reply_handler, error_handler, False))
293
294 def _make_binding (self, fn):
295 return lambda *args, **kwds: self._call_function (fn, *args, **kwds)
296
297 def _call_function (self, fn, *args, **kwds):
298 reply_handler = error_handler = auth_handler = False
299 if "reply_handler" in kwds:
300 reply_handler = kwds["reply_handler"]
301 del kwds["reply_handler"]
302 if "error_handler" in kwds:
303 error_handler = kwds["error_handler"]
304 del kwds["error_handler"]
305 if "auth_handler" in kwds:
306 auth_handler = kwds["auth_handler"]
307 del kwds["auth_handler"]
308
309 self.queue.put ((fn, args, kwds,
310 reply_handler, error_handler, auth_handler))
311
312 ######
313 ###### An asynchronous libcups API with graphical authentication and
314 ###### retrying.
315 ######
316
317 ###
318 ### A class to take care of an individual operation.
319 ###
320 class _IPPAuthOperation:
321 def __init__ (self, reply_handler, error_handler, conn,
322 user=None, fn=None, args=None, kwds=None):
323 self._auth_called = False
324 self._dialog_shown = False
325 self._use_password = ''
326 self._cancel = False
327 self._reconnect = False
328 self._reconnected = False
329 self._user = user
330 self._conn = conn
331 self._try_as_root = self._conn.try_as_root
332 self._client_fn = fn
333 self._client_args = args
334 self._client_kwds = kwds
335 self._client_reply_handler = reply_handler
336 self._client_error_handler = error_handler
337
338 debugprint ("+%s" % self)
339
340 def __del__ (self):
341 debug.debugprint ("-%s" % self)
342
343 def _destroy (self):
344 del self._conn
345 del self._client_fn
346 del self._client_args
347 del self._client_kwds
348 del self._client_reply_handler
349 del self._client_error_handler
350
351 def error_handler (self, conn, exc):
352 if self._client_fn is None:
353 # This is the initial "connection" operation, or a
354 # subsequent reconnection attempt.
355 debugprint ("Connection/reconnection failed")
356 return self._reconnect_error (conn, exc)
357
358 if self._cancel:
359 debugprint ("%s (_error_handler): canceled so chaining up" % self)
360 return self._error (exc)
361
362 if self._reconnect:
363 self._reconnect = False
364 self._reconnected = True
365 debugprint ("%s (_error_handler): reconnecting (as %s)..." %
366 (self, self._user))
367 conn.reconnect (self._user,
368 reply_handler=self._reconnect_reply,
369 error_handler=self._reconnect_error)
370 return
371
372 forbidden = False
373 if type (exc) == cups.IPPError:
374 (e, m) = exc.args
375 if (e == cups.IPP_NOT_AUTHORIZED or
376 e == cups.IPP_FORBIDDEN or
377 e == cups.IPP_AUTHENTICATION_CANCELED):
378 forbidden = (e == cups.IPP_FORBIDDEN)
379 elif e == cups.IPP_SERVICE_UNAVAILABLE:
380 return self._reconnect_error (conn, exc)
381 else:
382 return self._error (exc)
383 elif type (exc) == cups.HTTPError:
384 (s,) = exc.args
385 if (s == cups.HTTP_UNAUTHORIZED or
386 s == cups.HTTP_FORBIDDEN):
387 forbidden = (s == cups.HTTP_FORBIDDEN)
388 else:
389 return self._error (exc)
390 else:
391 return self._error (exc)
392
393 # Not authorized.
394 if forbidden:
395 debugprint ("%s (_error_handler): forbidden" % self)
396 else:
397 debugprint ("%s (_error_handler): not authorized" % self)
398
399 if (self._try_as_root and
400 self._user != 'root' and
401 (self._conn.thread.host[0] == '/' or forbidden)):
402 # This is a UNIX domain socket connection so we should
403 # not have needed a password (or it is not a UDS but
404 # we got an HTTP_FORBIDDEN response), and so the
405 # operation must not be something that the current
406 # user is authorised to do. They need to try as root,
407 # and supply the password. However, to get the right
408 # prompt, we need to try as root but with no password
409 # first.
410 debugprint ("Authentication: Try as root")
411 self._user = "root"
412 conn.reconnect (self._user,
413 reply_handler=self._reconnect_reply,
414 error_handler=self._reconnect_error)
415 # Don't submit the task until we've connected.
416 return
417
418 if not self._auth_called:
419 # We aren't even getting a chance to supply credentials.
420 return self._error (exc)
421
422 # Now reconnect and retry.
423 host = conn.thread.host
424 port = conn.thread.port
425 authconn.global_authinfocache.remove_auth_info (host=host,
426 port=port)
427 self._use_password = ''
428 debugprint ("%s (_error_handler): reconnecting (as %s)..." %
429 (self, self._user))
430 conn.reconnect (self._user,
431 reply_handler=self._reconnect_reply,
432 error_handler=self._reconnect_error)
433
434 def auth_handler (self, prompt, conn, method=None, resource=None):
435 if self._auth_called == False:
436 if self._user is None:
437 self._user = cups.getUser()
438 if self._user:
439 host = conn.thread.host
440 port = conn.thread.port
441 creds = authconn.global_authinfocache.lookup_auth_info (host=host,
442 port=port)
443 if creds:
444 if creds[0] == self._user:
445 self._use_password = creds[1]
446 self._reconnected = True
447 del creds
448 else:
449 host = conn.thread.host
450 port = conn.thread.port
451 authconn.global_authinfocache.remove_auth_info (host=host,
452 port=port)
453 self._use_password = ''
454
455 self._auth_called = True
456 if self._reconnected:
457 debugprint ("Supplying password after reconnection")
458 self._reconnected = False
459 conn.set_auth_info (self._use_password)
460 return
461
462 self._reconnected = False
463 if not conn.prompt_allowed:
464 conn.set_auth_info (self._use_password)
465 return
466
467 # If we've previously prompted, explain why we're prompting again.
468 if self._dialog_shown:
469 d = Gtk.MessageDialog (parent=self._conn.parent,
470 modal=True, destroy_with_parent=True,
471 message_type=Gtk.MessageType.ERROR,
472 buttons=Gtk.ButtonsType.CLOSE,
473 text=_("Not authorized"))
474 d.format_secondary_text (_("The password may be incorrect."))
475 d.run ()
476 d.destroy ()
477
478 op = None
479 if conn.semantic:
480 op = conn.semantic.current_operation ()
481
482 if op is None:
483 d = authconn.AuthDialog (parent=conn.parent)
484 else:
485 title = _("Authentication (%s)") % op
486 d = authconn.AuthDialog (title=title,
487 parent=conn.parent)
488
489 d.set_prompt ('')
490 if self._user is None:
491 self._user = cups.getUser()
492 d.set_auth_info (['', ''])
493 d.field_grab_focus ('username')
494 d.set_keep_above (True)
495 d.show_all ()
496 d.connect ("response", self._on_auth_dialog_response)
497 self._dialog_shown = True
498
499 def submit_task (self):
500 self._auth_called = False
501 self._conn.queue.put ((self._client_fn, self._client_args,
502 self._client_kwds,
503 self._client_reply_handler,
504
505 # Use our own error and auth handlers.
506 self.error_handler,
507 self.auth_handler))
508
509 def _on_auth_dialog_response (self, dialog, response):
510 (user, password) = dialog.get_auth_info ()
511 if user == '':
512 user = self._user;
513 authconn.global_authinfocache.cache_auth_info ((user,
514 password),
515 host=self._conn.thread.host,
516 port=self._conn.thread.port)
517 self._dialog = dialog
518 dialog.hide ()
519
520 if (response == Gtk.ResponseType.CANCEL or
521 response == Gtk.ResponseType.DELETE_EVENT):
522 self._cancel = True
523 self._conn.set_auth_info ('')
524 authconn.global_authinfocache.remove_auth_info (host=self._conn.thread.host,
525 port=self._conn.thread.port)
526 debugprint ("Auth canceled")
527 return
528
529 if user == self._user:
530 self._use_password = password
531 self._conn.set_auth_info (password)
532 debugprint ("Password supplied.")
533 return
534
535 self._user = user
536 self._use_password = password
537 self._reconnect = True
538 self._conn.set_auth_info ('')
539 debugprint ("Will try as %s" % self._user)
540
541 def _reconnect_reply (self, conn, result):
542 # A different username was given in the authentication dialog,
543 # so we've reconnected as that user. Alternatively, the
544 # connection has failed and we're retrying.
545 debugprint ("Connected as %s" % self._user)
546 if self._client_fn is not None:
547 self.submit_task ()
548
549 def _reconnect_error (self, conn, exc):
550 debugprint ("Failed to connect as %s" % self._user)
551 if not self._conn.prompt_allowed:
552 self._error (exc)
553 return
554
555 op = None
556 if conn.semantic:
557 op = conn.semantic.current_operation ()
558
559 if op is None:
560 msg = _("CUPS server error")
561 else:
562 msg = _("CUPS server error (%s)") % op
563
564 d = Gtk.MessageDialog (parent=self._conn.parent,
565 modal=True, destroy_with_parent=True,
566 message_type=Gtk.MessageType.ERROR,
567 buttons=Gtk.ButtonsType.NONE,
568 text=msg)
569
570 if self._client_fn is None and type (exc) == RuntimeError:
571 # This was a connection failure.
572 message = 'service-error-service-unavailable'
573 elif type (exc) == cups.IPPError:
574 message = exc.args[1]
575 else:
576 message = repr (exc)
577
578 d.format_secondary_text (_("There was an error during the "
579 "CUPS operation: '%s'." % message))
580 d.add_buttons (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
581 _("Retry"), Gtk.ResponseType.OK)
582 d.set_default_response (Gtk.ResponseType.OK)
583 d.connect ("response", self._on_retry_server_error_response)
584 debugprint ("%s (_reconnect_error): presenting error dialog (%s; %s)" %
585 (self, msg, message))
586 d.show ()
587
588 def _on_retry_server_error_response (self, dialog, response):
589 dialog.destroy ()
590 if response == Gtk.ResponseType.OK:
591 debugprint ("%s: got retry response, reconnecting (as %s)..." %
592 (self, self._conn.thread.user))
593 self._conn.reconnect (self._conn.thread.user,
594 reply_handler=self._reconnect_reply,
595 error_handler=self._reconnect_error)
596 else:
597 debugprint ("%s: got cancel response" % self)
598 self._error (cups.IPPError (0, _("Operation canceled")))
599
600 def _error (self, exc):
601 debugprint ("%s (_error): handling %s" % (self, repr (exc)))
602 if self._client_error_handler:
603 debugprint ("%s (_error): calling %s" %
604 (self, self._client_error_handler))
605 self._client_error_handler (self._conn, exc)
606 self._destroy ()
607 else:
608 debugprint ("%s (_error): no client error handler set" % self)
609
610 ###
611 ### The user-visible class.
612 ###
613 class IPPAuthConnection(IPPConnection):
614 def __init__ (self, reply_handler=None, error_handler=None,
615 auth_handler=None, host=None, port=None, encryption=None,
616 parent=None, try_as_root=True, prompt_allowed=True,
617 semantic=None):
618 self.parent = parent
619 self.prompt_allowed = prompt_allowed
620 self.try_as_root = try_as_root
621 self.semantic = semantic
622
623 user = None
624 creds = authconn.global_authinfocache.lookup_auth_info (host=host,
625 port=port)
626 if creds:
627 if creds[0] != 'root' or try_as_root:
628 user = creds[0]
629 del creds
630
631 # The "connect" operation.
632 op = _IPPAuthOperation (reply_handler, error_handler, self)
633 IPPConnection.__init__ (self, reply_handler=reply_handler,
634 error_handler=op.error_handler,
635 auth_handler=op.auth_handler, user=user,
636 host=host, port=port, encryption=encryption)
637
638 def destroy (self):
639 self.semantic = None
640 IPPConnection.destroy (self)
641
642 def _call_function (self, fn, *args, **kwds):
643 reply_handler = error_handler = auth_handler = False
644 if "reply_handler" in kwds:
645 reply_handler = kwds["reply_handler"]
646 del kwds["reply_handler"]
647 if "error_handler" in kwds:
648 error_handler = kwds["error_handler"]
649 del kwds["error_handler"]
650 if "auth_handler" in kwds:
651 auth_handler = kwds["auth_handler"]
652 del kwds["auth_handler"]
653
654 # Store enough information about the current operation to
655 # restart it if necessary.
656 op = _IPPAuthOperation (reply_handler, error_handler, self,
657 self.thread.user, fn, args, kwds)
658
659 # Run the operation but use our own error and auth handlers.
660 op.submit_task ()
661
662 if __name__ == "__main__":
663 # Demo
664 set_debugging (True)
665 class UI:
666 def __init__ (self):
667 w = Gtk.Window ()
668 w.connect ("destroy", self.destroy)
669 b = Gtk.Button.new_with_label ("Connect")
670 b.connect ("clicked", self.connect_clicked)
671 vbox = Gtk.VBox ()
672 vbox.pack_start (b, False, False, 0)
673 w.add (vbox)
674 self.get_devices_button = Gtk.Button.new_with_label ("Get Devices")
675 self.get_devices_button.connect ("clicked", self.get_devices)
676 self.get_devices_button.set_sensitive (False)
677 vbox.pack_start (self.get_devices_button, False, False, 0)
678 self.conn = None
679 w.show_all ()
680
681 def destroy (self, window):
682 try:
683 self.conn.destroy ()
684 except AttributeError:
685 pass
686
687 Gtk.main_quit ()
688
689 def connect_clicked (self, button):
690 if self.conn:
691 self.conn.destroy ()
692
693 self.conn = IPPAuthConnection (reply_handler=self.connected,
694 error_handler=self.connect_failed)
695
696 def connected (self, conn, result):
697 debugprint ("Success: %s" % repr (result))
698 self.get_devices_button.set_sensitive (True)
699
700 def connect_failed (self, conn, exc):
701 debugprint ("Exc %s" % repr (exc))
702 self.get_devices_button.set_sensitive (False)
703 self.conn.destroy ()
704
705 def get_devices (self, button):
706 button.set_sensitive (False)
707 debugprint ("Getting devices")
708 self.conn.getDevices (reply_handler=self.get_devices_reply,
709 error_handler=self.get_devices_error)
710
711 def get_devices_reply (self, conn, result):
712 if conn != self.conn:
713 debugprint ("Ignoring stale reply")
714 return
715
716 debugprint ("Got devices: %s" % repr (result))
717 self.get_devices_button.set_sensitive (True)
718
719 def get_devices_error (self, conn, exc):
720 if conn != self.conn:
721 debugprint ("Ignoring stale error")
722 return
723
724 debugprint ("Error getting devices: %s" % repr (exc))
725 self.get_devices_button.set_sensitive (True)
726
727 UI ()
728 Gtk.main ()