| 1 |
#!/usr/bin/python3 |
| 2 |
|
| 3 |
## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2013, 2014 Red Hat, Inc. |
| 4 |
## Author: Tim Waugh <[email protected]> |
| 5 |
|
| 6 |
## This program is free software; you can redistribute it and/or modify |
| 7 |
## it under the terms of the GNU General Public License as published by |
| 8 |
## the Free Software Foundation; either version 2 of the License, or |
| 9 |
## (at your option) any later version. |
| 10 |
|
| 11 |
## This program is distributed in the hope that it will be useful, |
| 12 |
## but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
## GNU General Public License for more details. |
| 15 |
|
| 16 |
## You should have received a copy of the GNU General Public License |
| 17 |
## along with this program; if not, write to the Free Software |
| 18 |
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 19 |
|
| 20 |
import threading |
| 21 |
import config |
| 22 |
import cups |
| 23 |
import cupspk |
| 24 |
import gi |
| 25 |
from gi.repository import GLib |
| 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 |
import os |
| 31 |
from errordialogs import * |
| 32 |
from debug import * |
| 33 |
import gettext |
| 34 |
gettext.install(domain=config.PACKAGE, localedir=config.localedir) |
| 35 |
N_ = lambda x: x |
| 36 |
|
| 37 |
cups.require("1.9.60") |
| 38 |
class AuthDialog(Gtk.Dialog): |
| 39 |
AUTH_FIELD={'username': N_("Username:"), |
| 40 |
'password': N_("Password:"), |
| 41 |
'domain': N_("Domain:")} |
| 42 |
|
| 43 |
def __init__ (self, title=None, parent=None, |
| 44 |
flags=Gtk.DialogFlags.MODAL, |
| 45 |
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, |
| 46 |
Gtk.STOCK_OK, Gtk.ResponseType.OK), |
| 47 |
auth_info_required=None, |
| 48 |
allow_remember=False): |
| 49 |
if title is None: |
| 50 |
title = _("Authentication") |
| 51 |
if auth_info_required is None: |
| 52 |
auth_info_required = ['username', 'password'] |
| 53 |
Gtk.Dialog.__init__ (self, title, parent, flags, buttons) |
| 54 |
self.auth_info_required = auth_info_required |
| 55 |
self.set_default_response (Gtk.ResponseType.OK) |
| 56 |
self.set_border_width (6) |
| 57 |
self.set_resizable (False) |
| 58 |
hbox = Gtk.HBox.new (False, 12) |
| 59 |
hbox.set_border_width (6) |
| 60 |
image = Gtk.Image () |
| 61 |
image.set_from_stock (Gtk.STOCK_DIALOG_AUTHENTICATION, |
| 62 |
Gtk.IconSize.DIALOG) |
| 63 |
image.set_alignment (0.0, 0.0) |
| 64 |
hbox.pack_start (image, False, False, 0) |
| 65 |
vbox = Gtk.VBox.new (False, 12) |
| 66 |
self.prompt_label = Gtk.Label () |
| 67 |
vbox.pack_start (self.prompt_label, False, False, 0) |
| 68 |
|
| 69 |
num_fields = len (auth_info_required) |
| 70 |
grid = Gtk.Grid() |
| 71 |
grid.insert_row(num_fields) |
| 72 |
grid.insert_column(2) |
| 73 |
grid.set_row_spacing (6) |
| 74 |
grid.set_column_spacing (6) |
| 75 |
|
| 76 |
self.field_entry = [] |
| 77 |
for i in range (num_fields): |
| 78 |
field = auth_info_required[i] |
| 79 |
label = Gtk.Label (label=_(self.AUTH_FIELD.get (field, field))) |
| 80 |
label.set_alignment (0, 0.5) |
| 81 |
grid.attach (label, 0, i, 1, 1) |
| 82 |
entry = Gtk.Entry () |
| 83 |
entry.set_visibility (field != 'password') |
| 84 |
grid.attach (entry, 1, i, 1, 1) |
| 85 |
self.field_entry.append (entry) |
| 86 |
|
| 87 |
self.field_entry[num_fields - 1].set_activates_default (True) |
| 88 |
vbox.pack_start (grid, False, False, 0) |
| 89 |
hbox.pack_start (vbox, False, False, 0) |
| 90 |
self.vbox.pack_start (hbox, False, False, 0) |
| 91 |
|
| 92 |
if allow_remember: |
| 93 |
cb = Gtk.CheckButton.new_with_label (_("Remember password")) |
| 94 |
cb.set_active (False) |
| 95 |
vbox.pack_start (cb, False, False, 0) |
| 96 |
self.remember_checkbox = cb |
| 97 |
|
| 98 |
self.vbox.show_all () |
| 99 |
|
| 100 |
def set_prompt (self, prompt): |
| 101 |
self.prompt_label.set_markup ('<span weight="bold" size="larger">' + |
| 102 |
prompt + '</span>') |
| 103 |
self.prompt_label.set_use_markup (True) |
| 104 |
self.prompt_label.set_alignment (0, 0) |
| 105 |
self.prompt_label.set_line_wrap (True) |
| 106 |
|
| 107 |
def set_auth_info (self, auth_info): |
| 108 |
for i in range (len (self.field_entry)): |
| 109 |
self.field_entry[i].set_text (auth_info[i]) |
| 110 |
|
| 111 |
def get_auth_info (self): |
| 112 |
return [x.get_text () for x in self.field_entry] |
| 113 |
|
| 114 |
def get_remember_password (self): |
| 115 |
try: |
| 116 |
return self.remember_checkbox.get_active () |
| 117 |
except AttributeError: |
| 118 |
return False |
| 119 |
|
| 120 |
def field_grab_focus (self, field): |
| 121 |
i = self.auth_info_required.index (field) |
| 122 |
self.field_entry[i].grab_focus () |
| 123 |
|
| 124 |
### |
| 125 |
### An auth-info cache. |
| 126 |
### |
| 127 |
class _AuthInfoCache: |
| 128 |
def __init__ (self): |
| 129 |
self.creds = dict() # by (host,port) |
| 130 |
|
| 131 |
def cache_auth_info (self, data, host=None, port=None): |
| 132 |
if port is None: |
| 133 |
port = 631 |
| 134 |
|
| 135 |
self.creds[(host,port)] = data |
| 136 |
|
| 137 |
def lookup_auth_info (self, host=None, port=None): |
| 138 |
if port is None: |
| 139 |
port = 631 |
| 140 |
|
| 141 |
try: |
| 142 |
return self.creds[(host,port)] |
| 143 |
except KeyError: |
| 144 |
return None |
| 145 |
|
| 146 |
def remove_auth_info (self, host=None, port=None): |
| 147 |
if port is None: |
| 148 |
port = 631 |
| 149 |
|
| 150 |
try: |
| 151 |
del self.creds[(host,port)] |
| 152 |
except KeyError: |
| 153 |
return None |
| 154 |
|
| 155 |
global_authinfocache = _AuthInfoCache () |
| 156 |
|
| 157 |
class Connection: |
| 158 |
def __init__ (self, parent=None, try_as_root=True, lock=False, |
| 159 |
host=None, port=None, encryption=None): |
| 160 |
if host is not None: |
| 161 |
cups.setServer (host) |
| 162 |
if port is not None: |
| 163 |
cups.setPort (port) |
| 164 |
if encryption is not None: |
| 165 |
cups.setEncryption (encryption) |
| 166 |
|
| 167 |
self._use_password = '' |
| 168 |
self._parent = parent |
| 169 |
self._try_as_root = try_as_root |
| 170 |
self._use_user = cups.getUser () |
| 171 |
self._server = cups.getServer () |
| 172 |
self._port = cups.getPort() |
| 173 |
self._encryption = cups.getEncryption () |
| 174 |
self._prompt_allowed = True |
| 175 |
self._operation_stack = [] |
| 176 |
self._lock = lock |
| 177 |
self._gui_event = threading.Event () |
| 178 |
|
| 179 |
self._connect () |
| 180 |
|
| 181 |
def _begin_operation (self, operation): |
| 182 |
debugprint ("%s: Operation += %s" % (self, operation)) |
| 183 |
self._operation_stack.append (operation) |
| 184 |
|
| 185 |
def _end_operation (self): |
| 186 |
debugprint ("%s: Operation ended" % self) |
| 187 |
self._operation_stack.pop () |
| 188 |
|
| 189 |
def _get_prompt_allowed (self, ): |
| 190 |
return self._prompt_allowed |
| 191 |
|
| 192 |
def _set_prompt_allowed (self, allowed): |
| 193 |
self._prompt_allowed = allowed |
| 194 |
|
| 195 |
def _set_lock (self, whether): |
| 196 |
self._lock = whether |
| 197 |
|
| 198 |
def _connect (self, allow_pk=True): |
| 199 |
cups.setUser (self._use_user) |
| 200 |
|
| 201 |
self._use_pk = (allow_pk and |
| 202 |
(self._server[0] == '/' or self._server == 'localhost') |
| 203 |
and os.getuid () != 0) |
| 204 |
if self._use_pk: |
| 205 |
create_object = cupspk.Connection |
| 206 |
else: |
| 207 |
create_object = cups.Connection |
| 208 |
|
| 209 |
self._connection = create_object (host=self._server, |
| 210 |
port=self._port, |
| 211 |
encryption=self._encryption) |
| 212 |
|
| 213 |
if self._use_pk: |
| 214 |
self._connection.set_parent(self._parent) |
| 215 |
|
| 216 |
self._user = self._use_user |
| 217 |
debugprint ("Connected as user %s" % self._user) |
| 218 |
methodtype_lambda = type (self._connection.getPrinters) |
| 219 |
methodtype_real = type (self._connection.addPrinter) |
| 220 |
for fname in dir (self._connection): |
| 221 |
if fname[0] == '_': |
| 222 |
continue |
| 223 |
fn = getattr (self._connection, fname) |
| 224 |
if not type (fn) in [methodtype_lambda, methodtype_real]: |
| 225 |
continue |
| 226 |
setattr (self, fname, self._make_binding (fname, fn)) |
| 227 |
|
| 228 |
def _using_polkit (self): |
| 229 |
return isinstance (self._connection, cupspk.Connection) |
| 230 |
|
| 231 |
def _make_binding (self, fname, fn): |
| 232 |
return lambda *args, **kwds: self._authloop (fname, fn, *args, **kwds) |
| 233 |
|
| 234 |
def _authloop (self, fname, fn, *args, **kwds): |
| 235 |
self._passes = 0 |
| 236 |
# remove signature if dbus is not being used and signature is provided |
| 237 |
if not self._using_polkit(): |
| 238 |
kwds.pop('signature', None) |
| 239 |
|
| 240 |
c = self._connection |
| 241 |
retry = False |
| 242 |
while True: |
| 243 |
try: |
| 244 |
if self._perform_authentication () == 0: |
| 245 |
break |
| 246 |
|
| 247 |
if c != self._connection: |
| 248 |
# We have reconnected. |
| 249 |
fn = getattr (self._connection, fname) |
| 250 |
c = self._connection |
| 251 |
|
| 252 |
cups.setUser (self._use_user) |
| 253 |
|
| 254 |
result = fn.__call__ (*args, **kwds) |
| 255 |
|
| 256 |
if fname == 'adminGetServerSettings': |
| 257 |
# Special case for a rubbish bit of API. |
| 258 |
if result == {}: |
| 259 |
# Authentication failed, but we aren't told that. |
| 260 |
raise cups.IPPError (cups.IPP_NOT_AUTHORIZED, '') |
| 261 |
break |
| 262 |
except cups.IPPError as e: |
| 263 |
(e, m) = e.args |
| 264 |
if self._use_pk and m == 'pkcancel': |
| 265 |
raise cups.IPPError (0, _("Operation canceled")) |
| 266 |
|
| 267 |
if not self._cancel and (e == cups.IPP_NOT_AUTHORIZED or |
| 268 |
e == cups.IPP_FORBIDDEN or |
| 269 |
e == cups.IPP_AUTHENTICATION_CANCELED): |
| 270 |
self._failed (e == cups.IPP_FORBIDDEN) |
| 271 |
elif not self._cancel and e == cups.IPP_SERVICE_UNAVAILABLE: |
| 272 |
debugprint ("Got IPP_SERVICE_UNAVAILABLE") |
| 273 |
debugprint (m) |
| 274 |
if self._lock: |
| 275 |
self._gui_event.clear () |
| 276 |
GLib.timeout_add (1, self._ask_retry_server_error, m) |
| 277 |
self._gui_event.wait () |
| 278 |
else: |
| 279 |
self._ask_retry_server_error (m) |
| 280 |
|
| 281 |
if self._retry_response == Gtk.ResponseType.OK: |
| 282 |
debugprint ("retrying operation...") |
| 283 |
retry = True |
| 284 |
self._passes -= 1 |
| 285 |
self._has_failed = True |
| 286 |
else: |
| 287 |
self._cancel = True |
| 288 |
raise |
| 289 |
else: |
| 290 |
if self._cancel and not self._cannot_auth: |
| 291 |
raise cups.IPPError (0, _("Operation canceled")) |
| 292 |
|
| 293 |
debugprint ("%s: %s" % (e, repr (m))) |
| 294 |
raise |
| 295 |
except cups.HTTPError as e: |
| 296 |
(s,) = e.args |
| 297 |
if not self._cancel: |
| 298 |
self._failed (s == cups.HTTP_FORBIDDEN) |
| 299 |
else: |
| 300 |
raise |
| 301 |
|
| 302 |
return result |
| 303 |
|
| 304 |
def _ask_retry_server_error (self, message): |
| 305 |
if self._lock: |
| 306 |
Gdk.threads_enter () |
| 307 |
|
| 308 |
try: |
| 309 |
msg = (_("CUPS server error (%s)") % self._operation_stack[0]) |
| 310 |
except IndexError: |
| 311 |
msg = _("CUPS server error") |
| 312 |
|
| 313 |
d = Gtk.MessageDialog (transient_for=self._parent, |
| 314 |
modal=True, destroy_with_parent=True, |
| 315 |
message_type=Gtk.MessageType.ERROR, |
| 316 |
buttons=Gtk.ButtonsType.NONE, |
| 317 |
text=msg) |
| 318 |
|
| 319 |
d.format_secondary_text (_("There was an error during the " |
| 320 |
"CUPS operation: '%s'.") % message) |
| 321 |
d.add_buttons (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, |
| 322 |
_("Retry"), Gtk.ResponseType.OK) |
| 323 |
d.set_default_response (Gtk.ResponseType.OK) |
| 324 |
if self._lock: |
| 325 |
d.connect ("response", self._on_retry_server_error_response) |
| 326 |
Gdk.threads_leave () |
| 327 |
else: |
| 328 |
self._retry_response = d.run () |
| 329 |
d.destroy () |
| 330 |
|
| 331 |
def _on_retry_server_error_response (self, dialog, response): |
| 332 |
self._retry_response = response |
| 333 |
dialog.destroy () |
| 334 |
self._gui_event.set () |
| 335 |
|
| 336 |
def _failed (self, forbidden=False): |
| 337 |
self._has_failed = True |
| 338 |
self._forbidden = forbidden |
| 339 |
|
| 340 |
def _password_callback (self, prompt): |
| 341 |
debugprint ("Got password callback") |
| 342 |
if self._cancel or self._auth_called: |
| 343 |
return '' |
| 344 |
|
| 345 |
self._auth_called = True |
| 346 |
self._prompt = prompt |
| 347 |
return self._use_password |
| 348 |
|
| 349 |
def _perform_authentication (self): |
| 350 |
self._passes += 1 |
| 351 |
|
| 352 |
creds = global_authinfocache.lookup_auth_info (host=self._server, port=self._port) |
| 353 |
if creds is not None: |
| 354 |
if (creds[0] != 'root' or self._try_as_root): |
| 355 |
(self._use_user, self._use_password) = creds |
| 356 |
del creds |
| 357 |
|
| 358 |
debugprint ("Authentication pass: %d" % self._passes) |
| 359 |
if self._passes == 1: |
| 360 |
# Haven't yet tried the operation. Set the password |
| 361 |
# callback and return > 0 so we try it for the first time. |
| 362 |
self._has_failed = False |
| 363 |
self._forbidden = False |
| 364 |
self._auth_called = False |
| 365 |
self._cancel = False |
| 366 |
self._cannot_auth = False |
| 367 |
self._dialog_shown = False |
| 368 |
cups.setPasswordCB (self._password_callback) |
| 369 |
debugprint ("Authentication: password callback set") |
| 370 |
return 1 |
| 371 |
|
| 372 |
debugprint ("Forbidden: %s" % self._forbidden) |
| 373 |
if not self._has_failed: |
| 374 |
# Tried the operation and it worked. Return 0 to signal to |
| 375 |
# break out of the loop. |
| 376 |
debugprint ("Authentication: Operation successful") |
| 377 |
return 0 |
| 378 |
|
| 379 |
# Reset failure flag. |
| 380 |
self._has_failed = False |
| 381 |
|
| 382 |
if self._passes >= 2: |
| 383 |
# Tried the operation without a password and it failed. |
| 384 |
if (self._try_as_root and |
| 385 |
self._user != 'root' and |
| 386 |
(self._server[0] == '/' or self._forbidden)): |
| 387 |
# This is a UNIX domain socket connection so we should |
| 388 |
# not have needed a password (or it is not a UDS but |
| 389 |
# we got an HTTP_FORBIDDEN response), and so the |
| 390 |
# operation must not be something that the current |
| 391 |
# user is authorised to do. They need to try as root, |
| 392 |
# and supply the password. However, to get the right |
| 393 |
# prompt, we need to try as root but with no password |
| 394 |
# first. |
| 395 |
debugprint ("Authentication: Try as root") |
| 396 |
self._use_user = 'root' |
| 397 |
self._auth_called = False |
| 398 |
try: |
| 399 |
self._connect (allow_pk=False) |
| 400 |
except RuntimeError: |
| 401 |
raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE, |
| 402 |
'server-error-service-unavailable') |
| 403 |
|
| 404 |
return 1 |
| 405 |
|
| 406 |
if not self._prompt_allowed: |
| 407 |
debugprint ("Authentication: prompting not allowed") |
| 408 |
self._cancel = True |
| 409 |
return 1 |
| 410 |
|
| 411 |
if not self._auth_called: |
| 412 |
# We aren't even getting a chance to supply credentials. |
| 413 |
debugprint ("Authentication: giving up") |
| 414 |
self._cancel = True |
| 415 |
self._cannot_auth = True |
| 416 |
return 1 |
| 417 |
|
| 418 |
# Reset the flag indicating whether we were given an auth callback. |
| 419 |
self._auth_called = False |
| 420 |
|
| 421 |
# If we're previously prompted, explain why we're prompting again. |
| 422 |
if self._dialog_shown: |
| 423 |
if self._lock: |
| 424 |
self._gui_event.clear () |
| 425 |
GLib.timeout_add (1, self._show_not_authorized_dialog) |
| 426 |
self._gui_event.wait () |
| 427 |
else: |
| 428 |
self._show_not_authorized_dialog () |
| 429 |
|
| 430 |
if self._lock: |
| 431 |
self._gui_event.clear () |
| 432 |
GLib.timeout_add (1, self._perform_authentication_with_dialog) |
| 433 |
self._gui_event.wait () |
| 434 |
else: |
| 435 |
self._perform_authentication_with_dialog () |
| 436 |
|
| 437 |
if self._cancel: |
| 438 |
debugprint ("cancelled") |
| 439 |
return -1 |
| 440 |
|
| 441 |
cups.setUser (self._use_user) |
| 442 |
debugprint ("Authentication: Reconnect") |
| 443 |
try: |
| 444 |
self._connect (allow_pk=False) |
| 445 |
except RuntimeError: |
| 446 |
raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE, |
| 447 |
'server-error-service-unavailable') |
| 448 |
|
| 449 |
return 1 |
| 450 |
|
| 451 |
def _show_not_authorized_dialog (self): |
| 452 |
if self._lock: |
| 453 |
Gdk.threads_enter () |
| 454 |
d = Gtk.MessageDialog (transient_for=self._parent, |
| 455 |
modal=True, destroy_with_parent=True, |
| 456 |
message_type=Gtk.MessageType.ERROR, |
| 457 |
buttons=Gtk.ButtonsType.CLOSE) |
| 458 |
d.set_title (_("Not authorized")) |
| 459 |
d.set_markup ('<span weight="bold" size="larger">' + |
| 460 |
_("Not authorized") + '</span>\n\n' + |
| 461 |
_("The password may be incorrect.")) |
| 462 |
if self._lock: |
| 463 |
d.connect ("response", self._on_not_authorized_dialog_response) |
| 464 |
d.show_all () |
| 465 |
d.show_now () |
| 466 |
Gdk.threads_leave () |
| 467 |
else: |
| 468 |
d.run () |
| 469 |
d.destroy () |
| 470 |
|
| 471 |
def _on_not_authorized_dialog_response (self, dialog, response): |
| 472 |
self._gui_event.set () |
| 473 |
dialog.destroy () |
| 474 |
|
| 475 |
def _perform_authentication_with_dialog (self): |
| 476 |
if self._lock: |
| 477 |
Gdk.threads_enter () |
| 478 |
|
| 479 |
# Prompt. |
| 480 |
if len (self._operation_stack) > 0: |
| 481 |
try: |
| 482 |
title = (_("Authentication (%s)") % self._operation_stack[0]) |
| 483 |
except IndexError: |
| 484 |
title = _("Authentication") |
| 485 |
|
| 486 |
d = AuthDialog (title=title, |
| 487 |
parent=self._parent) |
| 488 |
else: |
| 489 |
d = AuthDialog (parent=self._parent) |
| 490 |
|
| 491 |
d.set_prompt ('') |
| 492 |
d.set_auth_info (['', '']) |
| 493 |
d.field_grab_focus ('username') |
| 494 |
d.set_keep_above (True) |
| 495 |
d.show_all () |
| 496 |
d.show_now () |
| 497 |
self._dialog_shown = True |
| 498 |
if self._lock: |
| 499 |
d.connect ("response", self._on_authentication_response) |
| 500 |
Gdk.threads_leave () |
| 501 |
else: |
| 502 |
response = d.run () |
| 503 |
self._on_authentication_response (d, response) |
| 504 |
|
| 505 |
def _on_authentication_response (self, dialog, response): |
| 506 |
(user, self._use_password) = dialog.get_auth_info () |
| 507 |
if user != '': |
| 508 |
self._use_user = user |
| 509 |
global_authinfocache.cache_auth_info ((self._use_user, |
| 510 |
self._use_password), |
| 511 |
host=self._server, |
| 512 |
port=self._port) |
| 513 |
dialog.destroy () |
| 514 |
|
| 515 |
if (response == Gtk.ResponseType.CANCEL or |
| 516 |
response == Gtk.ResponseType.DELETE_EVENT): |
| 517 |
self._cancel = True |
| 518 |
|
| 519 |
if self._lock: |
| 520 |
self._gui_event.set () |
| 521 |
|
| 522 |
if __name__ == '__main__': |
| 523 |
# Test it out. |
| 524 |
Gdk.threads_init () |
| 525 |
from timedops import TimedOperation |
| 526 |
set_debugging (True) |
| 527 |
c = TimedOperation (Connection, args=(None,)).run () |
| 528 |
debugprint ("Connected") |
| 529 |
c._set_lock (True) |
| 530 |
print(TimedOperation (c.getFile, |
| 531 |
args=('/admin/conf/cupsd.conf', |
| 532 |
'/dev/stdout')).run ()) |