/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
#!/usr/bin/python3 -bb
# -*- mode: python; coding: utf-8 -*-
#
# Mandos Monitor - Control and monitor the Mandos server
#
# Copyright © 2009-2019 Teddy Hogeborn
# Copyright © 2009-2019 Björn Påhlsson
#
# This file is part of Mandos.
#
# Mandos is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#     Mandos is distributed in the hope that it will be useful, but
#     WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact the authors at <mandos@recompile.se>.
#

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)
try:
    from future_builtins import *
except ImportError:
    pass

import sys
import os
import warnings
import datetime

import urwid.curses_display
import urwid

from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

import dbus

import locale

import logging

if sys.version_info.major == 2:
    str = unicode

log = logging.getLogger(os.path.basename(sys.argv[0]))
logging.basicConfig(level="NOTSET", # Show all messages
                    format="%(message)s") # Show basic log messages

logging.captureWarnings(True)   # Show warnings via the logging system

locale.setlocale(locale.LC_ALL, '')

logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)

# Some useful constants
domain = 'se.recompile'
server_interface = domain + '.Mandos'
client_interface = domain + '.Mandos.Client'
version = "1.8.9"

try:
    dbus.OBJECT_MANAGER_IFACE
except AttributeError:
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"


def isoformat_to_datetime(iso):
    "Parse an ISO 8601 date string to a datetime.datetime()"
    if not iso:
        return None
    d, t = iso.split("T", 1)
    year, month, day = d.split("-", 2)
    hour, minute, second = t.split(":", 2)
    second, fraction = divmod(float(second), 1)
    return datetime.datetime(int(year),
                             int(month),
                             int(day),
                             int(hour),
                             int(minute),
                             int(second),            # Whole seconds
                             int(fraction*1000000))  # Microseconds


class MandosClientPropertyCache(object):
    """This wraps a Mandos Client D-Bus proxy object, caches the
    properties and calls a hook function when any of them are
    changed.
    """
    def __init__(self, proxy_object=None, properties=None, **kwargs):
        self.proxy = proxy_object  # Mandos Client proxy object
        self.properties = dict() if properties is None else properties
        self.property_changed_match = (
            self.proxy.connect_to_signal("PropertiesChanged",
                                         self.properties_changed,
                                         dbus.PROPERTIES_IFACE,
                                         byte_arrays=True))

        if properties is None:
            self.properties.update(self.proxy.GetAll(
                client_interface,
                dbus_interface=dbus.PROPERTIES_IFACE))

        super(MandosClientPropertyCache, self).__init__(**kwargs)

    def properties_changed(self, interface, properties, invalidated):
        """This is called whenever we get a PropertiesChanged signal
        It updates the changed properties in the "properties" dict.
        """
        # Update properties dict with new value
        if interface == client_interface:
            self.properties.update(properties)

    def delete(self):
        self.property_changed_match.remove()


class MandosClientWidget(urwid.FlowWidget, MandosClientPropertyCache):
    """A Mandos Client which is visible on the screen.
    """

    def __init__(self, server_proxy_object=None, update_hook=None,
                 delete_hook=None, **kwargs):
        # Called on update
        self.update_hook = update_hook
        # Called on delete
        self.delete_hook = delete_hook
        # Mandos Server proxy object
        self.server_proxy_object = server_proxy_object

        self._update_timer_callback_tag = None

        # The widget shown normally
        self._text_widget = urwid.Text("")
        # The widget shown when we have focus
        self._focus_text_widget = urwid.Text("")
        super(MandosClientWidget, self).__init__(**kwargs)
        self.update()
        self.opened = False

        self.match_objects = (
            self.proxy.connect_to_signal("CheckerCompleted",
                                         self.checker_completed,
                                         client_interface,
                                         byte_arrays=True),
            self.proxy.connect_to_signal("CheckerStarted",
                                         self.checker_started,
                                         client_interface,
                                         byte_arrays=True),
            self.proxy.connect_to_signal("GotSecret",
                                         self.got_secret,
                                         client_interface,
                                         byte_arrays=True),
            self.proxy.connect_to_signal("NeedApproval",
                                         self.need_approval,
                                         client_interface,
                                         byte_arrays=True),
            self.proxy.connect_to_signal("Rejected",
                                         self.rejected,
                                         client_interface,
                                         byte_arrays=True))
        log.debug('Created client %s', self.properties["Name"])

    def using_timer(self, flag):
        """Call this method with True or False when timer should be
        activated or deactivated.
        """
        if flag and self._update_timer_callback_tag is None:
            # Will update the shown timer value every second
            self._update_timer_callback_tag = (
                GLib.timeout_add(1000,
                                 glib_safely(self.update_timer)))
        elif not (flag or self._update_timer_callback_tag is None):
            GLib.source_remove(self._update_timer_callback_tag)
            self._update_timer_callback_tag = None

    def checker_completed(self, exitstatus, condition, command):
        if exitstatus == 0:
            log.debug('Checker for client %s (command "%s")'
                      ' succeeded', self.properties["Name"], command)
            self.update()
            return
        # Checker failed
        if os.WIFEXITED(condition):
            log.info('Checker for client %s (command "%s") failed'
                     ' with exit code %d', self.properties["Name"],
                     command, os.WEXITSTATUS(condition))
        elif os.WIFSIGNALED(condition):
            log.info('Checker for client %s (command "%s") was'
                     ' killed by signal %d', self.properties["Name"],
                     command, os.WTERMSIG(condition))
        self.update()

    def checker_started(self, command):
        """Server signals that a checker started."""
        log.debug('Client %s started checker "%s"',
                  self.properties["Name"], command)

    def got_secret(self):
        log.info("Client %s received its secret",
                 self.properties["Name"])

    def need_approval(self, timeout, default):
        if not default:
            message = "Client %s needs approval within %f seconds"
        else:
            message = "Client %s will get its secret in %f seconds"
        log.info(message, self.properties["Name"], timeout/1000)

    def rejected(self, reason):
        log.info("Client %s was rejected; reason: %s",
                 self.properties["Name"], reason)

    def selectable(self):
        """Make this a "selectable" widget.
        This overrides the method from urwid.FlowWidget."""
        return True

    def rows(self, maxcolrow, focus=False):
        """How many rows this widget will occupy might depend on
        whether we have focus or not.
        This overrides the method from urwid.FlowWidget"""
        return self.current_widget(focus).rows(maxcolrow, focus=focus)

    def current_widget(self, focus=False):
        if focus or self.opened:
            return self._focus_widget
        return self._widget

    def update(self):
        "Called when what is visible on the screen should be updated."
        # How to add standout mode to a style
        with_standout = {"normal": "standout",
                         "bold": "bold-standout",
                         "underline-blink":
                         "underline-blink-standout",
                         "bold-underline-blink":
                         "bold-underline-blink-standout",
                         }

        # Rebuild focus and non-focus widgets using current properties

        # Base part of a client. Name!
        base = '{name}: '.format(name=self.properties["Name"])
        if not self.properties["Enabled"]:
            message = "DISABLED"
            self.using_timer(False)
        elif self.properties["ApprovalPending"]:
            timeout = datetime.timedelta(
                milliseconds=self.properties["ApprovalDelay"])
            last_approval_request = isoformat_to_datetime(
                self.properties["LastApprovalRequest"])
            if last_approval_request is not None:
                timer = max(timeout - (datetime.datetime.utcnow()
                                       - last_approval_request),
                            datetime.timedelta())
            else:
                timer = datetime.timedelta()
            if self.properties["ApprovedByDefault"]:
                message = "Approval in {}. (d)eny?"
            else:
                message = "Denial in {}. (a)pprove?"
            message = message.format(str(timer).rsplit(".", 1)[0])
            self.using_timer(True)
        elif self.properties["LastCheckerStatus"] != 0:
            # When checker has failed, show timer until client expires
            expires = self.properties["Expires"]
            if expires == "":
                timer = datetime.timedelta(0)
            else:
                expires = (datetime.datetime.strptime
                           (expires, '%Y-%m-%dT%H:%M:%S.%f'))
                timer = max(expires - datetime.datetime.utcnow(),
                            datetime.timedelta())
            message = ('A checker has failed! Time until client'
                       ' gets disabled: {}'
                       .format(str(timer).rsplit(".", 1)[0]))
            self.using_timer(True)
        else:
            message = "enabled"
            self.using_timer(False)
        self._text = "{}{}".format(base, message)

        if not urwid.supports_unicode():
            self._text = self._text.encode("ascii", "replace")
        textlist = [("normal", self._text)]
        self._text_widget.set_text(textlist)
        self._focus_text_widget.set_text([(with_standout[text[0]],
                                           text[1])
                                          if isinstance(text, tuple)
                                          else text
                                          for text in textlist])
        self._widget = self._text_widget
        self._focus_widget = urwid.AttrWrap(self._focus_text_widget,
                                            "standout")
        # Run update hook, if any
        if self.update_hook is not None:
            self.update_hook()

    def update_timer(self):
        """called by GLib. Will indefinitely loop until
        GLib.source_remove() on tag is called
        """
        self.update()
        return True             # Keep calling this

    def delete(self, **kwargs):
        if self._update_timer_callback_tag is not None:
            GLib.source_remove(self._update_timer_callback_tag)
            self._update_timer_callback_tag = None
        for match in self.match_objects:
            match.remove()
        self.match_objects = ()
        if self.delete_hook is not None:
            self.delete_hook(self)
        return super(MandosClientWidget, self).delete(**kwargs)

    def render(self, maxcolrow, focus=False):
        """Render differently if we have focus.
        This overrides the method from urwid.FlowWidget"""
        return self.current_widget(focus).render(maxcolrow,
                                                 focus=focus)

    def keypress(self, maxcolrow, key):
        """Handle keys.
        This overrides the method from urwid.FlowWidget"""
        if key == "+":
            self.proxy.Set(client_interface, "Enabled",
                           dbus.Boolean(True), ignore_reply=True,
                           dbus_interface=dbus.PROPERTIES_IFACE)
        elif key == "-":
            self.proxy.Set(client_interface, "Enabled", False,
                           ignore_reply=True,
                           dbus_interface=dbus.PROPERTIES_IFACE)
        elif key == "a":
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
                               dbus_interface=client_interface,
                               ignore_reply=True)
        elif key == "d":
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
                               dbus_interface=client_interface,
                               ignore_reply=True)
        elif key == "R" or key == "_" or key == "ctrl k":
            self.server_proxy_object.RemoveClient(self.proxy
                                                  .object_path,
                                                  ignore_reply=True)
        elif key == "s":
            self.proxy.Set(client_interface, "CheckerRunning",
                           dbus.Boolean(True), ignore_reply=True,
                           dbus_interface=dbus.PROPERTIES_IFACE)
        elif key == "S":
            self.proxy.Set(client_interface, "CheckerRunning",
                           dbus.Boolean(False), ignore_reply=True,
                           dbus_interface=dbus.PROPERTIES_IFACE)
        elif key == "C":
            self.proxy.CheckedOK(dbus_interface=client_interface,
                                 ignore_reply=True)
        # xxx
#         elif key == "p" or key == "=":
#             self.proxy.pause()
#         elif key == "u" or key == ":":
#             self.proxy.unpause()
#         elif key == "RET":
#             self.open()
        else:
            return key

    def properties_changed(self, interface, properties, invalidated):
        """Call self.update() if any properties changed.
        This overrides the method from MandosClientPropertyCache"""
        old_values = {key: self.properties.get(key)
                      for key in properties.keys()}
        super(MandosClientWidget, self).properties_changed(
            interface, properties, invalidated)
        if any(old_values[key] != self.properties.get(key)
               for key in old_values):
            self.update()


def glib_safely(func, retval=True):
    def safe_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            log.exception("")
            return retval
    return safe_func


class ConstrainedListBox(urwid.ListBox):
    """Like a normal urwid.ListBox, but will consume all "up" or
    "down" key presses, thus not allowing any containing widgets to
    use them as an excuse to shift focus away from this widget.
    """
    def keypress(self, *args, **kwargs):
        ret = (super(ConstrainedListBox, self)
               .keypress(*args, **kwargs))
        if ret in ("up", "down"):
            return
        return ret


class UserInterface(object):
    """This is the entire user interface - the whole screen
    with boxes, lists of client widgets, etc.
    """
    def __init__(self, max_log_length=1000):
        DBusGMainLoop(set_as_default=True)

        self.screen = urwid.curses_display.Screen()

        self.screen.register_palette((
                ("normal",
                 "default", "default", None),
                ("bold",
                 "bold", "default", "bold"),
                ("underline-blink",
                 "underline,blink", "default", "underline,blink"),
                ("standout",
                 "standout", "default", "standout"),
                ("bold-underline-blink",
                 "bold,underline,blink", "default",
                 "bold,underline,blink"),
                ("bold-standout",
                 "bold,standout", "default", "bold,standout"),
                ("underline-blink-standout",
                 "underline,blink,standout", "default",
                 "underline,blink,standout"),
                ("bold-underline-blink-standout",
                 "bold,underline,blink,standout", "default",
                 "bold,underline,blink,standout"),
                ))

        if urwid.supports_unicode():
            self.divider = "─"  # \u2500
        else:
            self.divider = "_"  # \u005f

        self.screen.start()

        self.size = self.screen.get_cols_rows()

        self.clients = urwid.SimpleListWalker([])
        self.clients_dict = {}

        # We will add Text widgets to this list
        self.log = urwid.SimpleListWalker([])
        self.max_log_length = max_log_length

        # We keep a reference to the log widget so we can remove it
        # from the ListWalker without it getting destroyed
        self.logbox = ConstrainedListBox(self.log)

        # This keeps track of whether self.uilist currently has
        # self.logbox in it or not
        self.log_visible = True
        self.log_wrap = "any"

        self.loghandler = UILogHandler(self)

        self.rebuild()
        self.add_log_line(("bold",
                           "Mandos Monitor version " + version))
        self.add_log_line(("bold", "q: Quit  ?: Help"))

        self.busname = domain + '.Mandos'
        self.main_loop = GLib.MainLoop()

    def client_not_found(self, key_id, address):
        log.info("Client with address %s and key ID %s could"
                 " not be found", address, key_id)

    def rebuild(self):
        """This rebuilds the User Interface.
        Call this when the widget layout needs to change"""
        self.uilist = []
        # self.uilist.append(urwid.ListBox(self.clients))
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.
                                                          clients),
                                       # header=urwid.Divider(),
                                       header=None,
                                       footer=urwid.Divider(
                                           div_char=self.divider)))
        if self.log_visible:
            self.uilist.append(self.logbox)
        self.topwidget = urwid.Pile(self.uilist)

    def add_log_line(self, markup):
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
        if self.max_log_length:
            if len(self.log) > self.max_log_length:
                del self.log[0:(len(self.log) - self.max_log_length)]
        self.logbox.set_focus(len(self.logbox.body.contents)-1,
                              coming_from="above")
        self.refresh()

    def toggle_log_display(self):
        """Toggle visibility of the log buffer."""
        self.log_visible = not self.log_visible
        self.rebuild()
        log.debug("Log visibility changed to: %s", self.log_visible)

    def change_log_display(self):
        """Change type of log display.
        Currently, this toggles wrapping of text lines."""
        if self.log_wrap == "clip":
            self.log_wrap = "any"
        else:
            self.log_wrap = "clip"
        for textwidget in self.log:
            textwidget.set_wrap_mode(self.log_wrap)
        log.debug("Wrap mode: %s", self.log_wrap)

    def find_and_remove_client(self, path, interfaces):
        """Find a client by its object path and remove it.

        This is connected to the InterfacesRemoved signal from the
        Mandos server object."""
        if client_interface not in interfaces:
            # Not a Mandos client object; ignore
            return
        try:
            client = self.clients_dict[path]
        except KeyError:
            # not found?
            log.warning("Unknown client %s removed", path)
            return
        client.delete()

    def add_new_client(self, path, ifs_and_props):
        """Find a client by its object path and remove it.

        This is connected to the InterfacesAdded signal from the
        Mandos server object.
        """
        if client_interface not in ifs_and_props:
            # Not a Mandos client object; ignore
            return
        client_proxy_object = self.bus.get_object(self.busname, path)
        self.add_client(MandosClientWidget(
            server_proxy_object=self.mandos_serv,
            proxy_object=client_proxy_object,
            update_hook=self.refresh,
            delete_hook=self.remove_client,
            properties=dict(ifs_and_props[client_interface])),
                        path=path)

    def add_client(self, client, path=None):
        self.clients.append(client)
        if path is None:
            path = client.proxy.object_path
        self.clients_dict[path] = client
        self.clients.sort(key=lambda c: c.properties["Name"])
        self.refresh()

    def remove_client(self, client, path=None):
        self.clients.remove(client)
        if path is None:
            path = client.proxy.object_path
        del self.clients_dict[path]
        self.refresh()

    def refresh(self):
        """Redraw the screen"""
        canvas = self.topwidget.render(self.size, focus=True)
        self.screen.draw_screen(self.size, canvas)

    def run(self):
        """Start the main loop and exit when it's done."""
        log.addHandler(self.loghandler)
        self.orig_log_propagate = log.propagate
        log.propagate = False
        self.orig_log_level = log.level
        log.setLevel("INFO")
        self.bus = dbus.SystemBus()
        mandos_dbus_objc = self.bus.get_object(
            self.busname, "/", follow_name_owner_changes=True)
        self.mandos_serv = dbus.Interface(
            mandos_dbus_objc, dbus_interface=server_interface)
        try:
            mandos_clients = (self.mandos_serv
                              .GetAllClientsWithProperties())
            if not mandos_clients:
                log.warning("Note: Server has no clients.")
        except dbus.exceptions.DBusException:
            log.warning("Note: No Mandos server running.")
            mandos_clients = dbus.Dictionary()

        (self.mandos_serv
         .connect_to_signal("InterfacesRemoved",
                            self.find_and_remove_client,
                            dbus_interface=dbus.OBJECT_MANAGER_IFACE,
                            byte_arrays=True))
        (self.mandos_serv
         .connect_to_signal("InterfacesAdded",
                            self.add_new_client,
                            dbus_interface=dbus.OBJECT_MANAGER_IFACE,
                            byte_arrays=True))
        (self.mandos_serv
         .connect_to_signal("ClientNotFound",
                            self.client_not_found,
                            dbus_interface=server_interface,
                            byte_arrays=True))
        for path, client in mandos_clients.items():
            client_proxy_object = self.bus.get_object(self.busname,
                                                      path)
            self.add_client(MandosClientWidget(
                server_proxy_object=self.mandos_serv,
                proxy_object=client_proxy_object,
                properties=client,
                update_hook=self.refresh,
                delete_hook=self.remove_client),
                            path=path)

        self.refresh()
        self._input_callback_tag = (
            GLib.io_add_watch(
                GLib.IOChannel.unix_new(sys.stdin.fileno()),
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
                glib_safely(self.process_input)))
        self.main_loop.run()
        # Main loop has finished, we should close everything now
        GLib.source_remove(self._input_callback_tag)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", BytesWarning)
            self.screen.stop()

    def stop(self):
        self.main_loop.quit()
        log.removeHandler(self.loghandler)
        log.propagate = self.orig_log_propagate

    def process_input(self, source, condition):
        keys = self.screen.get_input()
        translations = {"ctrl n": "down",       # Emacs
                        "ctrl p": "up",         # Emacs
                        "ctrl v": "page down",  # Emacs
                        "meta v": "page up",    # Emacs
                        " ": "page down",       # less
                        "f": "page down",       # less
                        "b": "page up",         # less
                        "j": "down",            # vi
                        "k": "up",              # vi
                        }
        for key in keys:
            try:
                key = translations[key]
            except KeyError:    # :-)
                pass

            if key == "q" or key == "Q":
                self.stop()
                break
            elif key == "window resize":
                self.size = self.screen.get_cols_rows()
                self.refresh()
            elif key == "ctrl l":
                self.screen.clear()
                self.refresh()
            elif key == "l" or key == "D":
                self.toggle_log_display()
                self.refresh()
            elif key == "w" or key == "i":
                self.change_log_display()
                self.refresh()
            elif key == "?" or key == "f1" or key == "esc":
                if not self.log_visible:
                    self.log_visible = True
                    self.rebuild()
                self.add_log_line(("bold",
                                   "  ".join(("q: Quit",
                                              "?: Help",
                                              "l: Log window toggle",
                                              "TAB: Switch window",
                                              "w: Wrap (log lines)",
                                              "v: Toggle verbose log",
                                   ))))
                self.add_log_line(("bold",
                                   "  ".join(("Clients:",
                                              "+: Enable",
                                              "-: Disable",
                                              "R: Remove",
                                              "s: Start new checker",
                                              "S: Stop checker",
                                              "C: Checker OK",
                                              "a: Approve",
                                              "d: Deny",
                                   ))))
                self.refresh()
            elif key == "tab":
                if self.topwidget.get_focus() is self.logbox:
                    self.topwidget.set_focus(0)
                else:
                    self.topwidget.set_focus(self.logbox)
                self.refresh()
            elif key == "v":
                if log.level < logging.INFO:
                    log.setLevel(logging.INFO)
                    log.info("Verbose mode: Off")
                else:
                    log.setLevel(logging.NOTSET)
                    log.info("Verbose mode: On")
            # elif (key == "end" or key == "meta >" or key == "G"
            #       or key == ">"):
            #     pass            # xxx end-of-buffer
            # elif (key == "home" or key == "meta <" or key == "g"
            #       or key == "<"):
            #     pass            # xxx beginning-of-buffer
            # elif key == "ctrl e" or key == "$":
            #     pass            # xxx move-end-of-line
            # elif key == "ctrl a" or key == "^":
            #     pass            # xxx move-beginning-of-line
            # elif key == "ctrl b" or key == "meta (" or key == "h":
            #     pass            # xxx left
            # elif key == "ctrl f" or key == "meta )" or key == "l":
            #     pass            # xxx right
            # elif key == "a":
            #     pass            # scroll up log
            # elif key == "z":
            #     pass            # scroll down log
            elif self.topwidget.selectable():
                self.topwidget.keypress(self.size, key)
                self.refresh()
        return True


class UILogHandler(logging.Handler):
    def __init__(self, ui, *args, **kwargs):
        self.ui = ui
        super(UILogHandler, self).__init__(*args, **kwargs)
        self.setFormatter(
            logging.Formatter("%(asctime)s: %(message)s"))
    def emit(self, record):
        msg = self.format(record)
        if record.levelno > logging.INFO:
            msg = ("bold", msg)
        self.ui.add_log_line(msg)


ui = UserInterface()
try:
    ui.run()
except KeyboardInterrupt:
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", "", BytesWarning)
        ui.screen.stop()
except Exception:
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", "", BytesWarning)
        ui.screen.stop()
    raise