/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
237.7.733 by Teddy Hogeborn
Add -I option to python 3 on the interpreter script ("shebang") line
1
#!/usr/bin/python3 -bbI
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
2
# -*- mode: python; coding: utf-8 -*-
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
3
#
237.2.207 by Teddy Hogeborn
Update copyright year to "2010" wherever appropriate.
4
# Mandos Monitor - Control and monitor the Mandos server
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
5
#
237.7.517 by Teddy Hogeborn
Update copyright year to 2019
6
# Copyright © 2009-2019 Teddy Hogeborn
7
# Copyright © 2009-2019 Björn Påhlsson
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
8
#
237.7.455 by Teddy Hogeborn
Alter copyright notices slightly. Actual license is unchanged!
9
# This file is part of Mandos.
10
#
11
# Mandos is free software: you can redistribute it and/or modify it
12
# under the terms of the GNU General Public License as published by
237.2.207 by Teddy Hogeborn
Update copyright year to "2010" wherever appropriate.
13
# the Free Software Foundation, either version 3 of the License, or
14
# (at your option) any later version.
15
#
237.7.455 by Teddy Hogeborn
Alter copyright notices slightly. Actual license is unchanged!
16
#     Mandos is distributed in the hope that it will be useful, but
17
#     WITHOUT ANY WARRANTY; without even the implied warranty of
237.2.207 by Teddy Hogeborn
Update copyright year to "2010" wherever appropriate.
18
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
#     GNU General Public License for more details.
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
20
#
237.2.207 by Teddy Hogeborn
Update copyright year to "2010" wherever appropriate.
21
# You should have received a copy of the GNU General Public License
237.7.455 by Teddy Hogeborn
Alter copyright notices slightly. Actual license is unchanged!
22
# along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
23
#
237.11.2 by Teddy Hogeborn
Change "fukt.bsnet.se" to "recompile.se" throughout.
24
# Contact the authors at <mandos@recompile.se>.
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
25
#
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
26
from __future__ import (division, absolute_import, print_function,
27
                        unicode_literals)
237.7.801 by Teddy Hogeborn
mandos-monitor: Update boilerplate code
28
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
29
try:
30
    from future_builtins import *
31
except ImportError:
32
    pass
237.7.127 by Teddy Hogeborn
* mandos: Use all new builtins.
33
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
34
import sys
237.7.801 by Teddy Hogeborn
mandos-monitor: Update boilerplate code
35
import logging
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
36
import os
237.7.722 by Teddy Hogeborn
Address Python 3 bytes/str warnings
37
import warnings
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
38
import datetime
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
39
import locale
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
40
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
41
import urwid.curses_display
42
import urwid
43
44
from dbus.mainloop.glib import DBusGMainLoop
237.7.378 by Teddy Hogeborn
Server: Use python-gi instead of old python-gobject
45
from gi.repository import GLib
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
46
47
import dbus
48
237.23.7 by Teddy Hogeborn
Use the .major attribute on sys.version_info instead of using "[0]".
49
if sys.version_info.major == 2:
237.7.740 by teddy at recompile
Simplification of Python 3 compatibility code
50
    __metaclass__ = type
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
51
    str = unicode
237.7.801 by Teddy Hogeborn
mandos-monitor: Update boilerplate code
52
    input = raw_input
53
54
# Show warnings by default
55
if not sys.warnoptions:
56
    warnings.simplefilter("default")
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
57
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
58
log = logging.getLogger(os.path.basename(sys.argv[0]))
59
logging.basicConfig(level="NOTSET", # Show all messages
60
                    format="%(message)s") # Show basic log messages
61
62
logging.captureWarnings(True)   # Show warnings via the logging system
63
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
64
locale.setlocale(locale.LC_ALL, "")
237.2.174 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
65
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
66
logging.getLogger("dbus.proxies").setLevel(logging.CRITICAL)
237.7.861 by Teddy Hogeborn
mandos-monitor: Avoid debug messages from urwid
67
logging.getLogger("urwid").setLevel(logging.INFO)
24.1.153 by Björn Påhlsson
early commit to ease todays coding
68
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
69
# Some useful constants
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
70
domain = "se.recompile"
71
server_interface = domain + ".Mandos"
72
client_interface = domain + ".Mandos.Client"
413 by Teddy Hogeborn
* Makefile (version): Change to "1.8.18".
73
version = "1.8.18"
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
74
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
75
try:
76
    dbus.OBJECT_MANAGER_IFACE
77
except AttributeError:
78
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
79
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
80
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
81
def isoformat_to_datetime(iso):
82
    "Parse an ISO 8601 date string to a datetime.datetime()"
83
    if not iso:
84
        return None
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
85
    d, t = iso.split("T", 1)
86
    year, month, day = d.split("-", 2)
87
    hour, minute, second = t.split(":", 2)
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
88
    second, fraction = divmod(float(second), 1)
89
    return datetime.datetime(int(year),
90
                             int(month),
91
                             int(day),
92
                             int(hour),
93
                             int(minute),
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
94
                             int(second),            # Whole seconds
95
                             int(fraction*1000000))  # Microseconds
96
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
97
237.7.740 by teddy at recompile
Simplification of Python 3 compatibility code
98
class MandosClientPropertyCache:
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
99
    """This wraps a Mandos Client D-Bus proxy object, caches the
100
    properties and calls a hook function when any of them are
101
    changed.
102
    """
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
103
    def __init__(self, proxy_object=None, properties=None, **kwargs):
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
104
        self.proxy = proxy_object  # Mandos Client proxy object
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
105
        self.properties = dict() if properties is None else properties
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
106
        self.property_changed_match = (
237.7.280 by Teddy Hogeborn
Emit D-Bus "org.freedesktop.DBus.Properties.PropertiesChanged" signal.
107
            self.proxy.connect_to_signal("PropertiesChanged",
108
                                         self.properties_changed,
109
                                         dbus.PROPERTIES_IFACE,
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
110
                                         byte_arrays=True))
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
111
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
112
        if properties is None:
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
113
            self.properties.update(self.proxy.GetAll(
114
                client_interface,
115
                dbus_interface=dbus.PROPERTIES_IFACE))
116
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
117
        super(MandosClientPropertyCache, self).__init__(**kwargs)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
118
237.7.280 by Teddy Hogeborn
Emit D-Bus "org.freedesktop.DBus.Properties.PropertiesChanged" signal.
119
    def properties_changed(self, interface, properties, invalidated):
120
        """This is called whenever we get a PropertiesChanged signal
121
        It updates the changed properties in the "properties" dict.
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
122
        """
123
        # Update properties dict with new value
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
124
        if interface == client_interface:
125
            self.properties.update(properties)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
126
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
127
    def delete(self):
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
128
        self.property_changed_match.remove()
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
129
130
237.7.862 by Teddy Hogeborn
mandos-monitor: avoid deprecation warnings from urwid
131
class MandosClientWidget(MandosClientPropertyCache, urwid.Widget):
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
132
    """A Mandos Client which is visible on the screen.
133
    """
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
134
237.7.862 by Teddy Hogeborn
mandos-monitor: avoid deprecation warnings from urwid
135
    _sizing = frozenset(["flow"])
136
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
137
    def __init__(self, server_proxy_object=None, update_hook=None,
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
138
                 delete_hook=None, **kwargs):
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
139
        # Called on update
140
        self.update_hook = update_hook
141
        # Called on delete
142
        self.delete_hook = delete_hook
143
        # Mandos Server proxy object
144
        self.server_proxy_object = server_proxy_object
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
145
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
146
        self._update_timer_callback_tag = None
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
147
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
148
        # The widget shown normally
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
149
        self._text_widget = urwid.Text("")
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
150
        # The widget shown when we have focus
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
151
        self._focus_text_widget = urwid.Text("")
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
152
        super(MandosClientWidget, self).__init__(**kwargs)
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
153
        self.update()
154
        self.opened = False
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
155
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
156
        self.match_objects = (
157
            self.proxy.connect_to_signal("CheckerCompleted",
158
                                         self.checker_completed,
159
                                         client_interface,
160
                                         byte_arrays=True),
161
            self.proxy.connect_to_signal("CheckerStarted",
162
                                         self.checker_started,
163
                                         client_interface,
164
                                         byte_arrays=True),
165
            self.proxy.connect_to_signal("GotSecret",
166
                                         self.got_secret,
167
                                         client_interface,
168
                                         byte_arrays=True),
169
            self.proxy.connect_to_signal("NeedApproval",
170
                                         self.need_approval,
171
                                         client_interface,
172
                                         byte_arrays=True),
173
            self.proxy.connect_to_signal("Rejected",
174
                                         self.rejected,
175
                                         client_interface,
176
                                         byte_arrays=True))
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
177
        log.debug("Created client %s", self.properties["Name"])
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
178
237.2.205 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
179
    def using_timer(self, flag):
180
        """Call this method with True or False when timer should be
181
        activated or deactivated.
182
        """
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
183
        if flag and self._update_timer_callback_tag is None:
24.1.179 by Björn Påhlsson
New feature:
184
            # Will update the shown timer value every second
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
185
            self._update_timer_callback_tag = (
186
                GLib.timeout_add(1000,
187
                                 glib_safely(self.update_timer)))
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
188
        elif not (flag or self._update_timer_callback_tag is None):
237.7.378 by Teddy Hogeborn
Server: Use python-gi instead of old python-gobject
189
            GLib.source_remove(self._update_timer_callback_tag)
237.2.205 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
190
            self._update_timer_callback_tag = None
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
191
237.7.331 by Teddy Hogeborn
Revert change to D-Bus API.
192
    def checker_completed(self, exitstatus, condition, command):
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
193
        if exitstatus == 0:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
194
            log.debug('Checker for client %s (command "%s")'
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
195
                      " succeeded", self.properties["Name"], command)
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
196
            self.update()
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
197
            return
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
198
        # Checker failed
237.7.331 by Teddy Hogeborn
Revert change to D-Bus API.
199
        if os.WIFEXITED(condition):
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
200
            log.info('Checker for client %s (command "%s") failed'
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
201
                     " with exit code %d", self.properties["Name"],
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
202
                     command, os.WEXITSTATUS(condition))
237.7.331 by Teddy Hogeborn
Revert change to D-Bus API.
203
        elif os.WIFSIGNALED(condition):
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
204
            log.info('Checker for client %s (command "%s") was'
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
205
                     " killed by signal %d", self.properties["Name"],
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
206
                     command, os.WTERMSIG(condition))
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
207
        self.update()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
208
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
209
    def checker_started(self, command):
237.7.261 by Teddy Hogeborn
mandos-monitor: New "verbose" mode to see less important log messages.
210
        """Server signals that a checker started."""
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
211
        log.debug('Client %s started checker "%s"',
212
                  self.properties["Name"], command)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
213
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
214
    def got_secret(self):
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
215
        log.info("Client %s received its secret",
216
                 self.properties["Name"])
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
217
24.1.153 by Björn Påhlsson
early commit to ease todays coding
218
    def need_approval(self, timeout, default):
219
        if not default:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
220
            message = "Client %s needs approval within %f seconds"
24.1.153 by Björn Påhlsson
early commit to ease todays coding
221
        else:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
222
            message = "Client %s will get its secret in %f seconds"
223
        log.info(message, self.properties["Name"], timeout/1000)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
224
24.1.153 by Björn Påhlsson
early commit to ease todays coding
225
    def rejected(self, reason):
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
226
        log.info("Client %s was rejected; reason: %s",
227
                 self.properties["Name"], reason)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
228
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
229
    def selectable(self):
230
        """Make this a "selectable" widget.
237.7.862 by Teddy Hogeborn
mandos-monitor: avoid deprecation warnings from urwid
231
        This overrides the method from urwid.Widget."""
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
232
        return True
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
233
237.8.1 by teddy at bsnet
* mandos-monitor: Use only unicode string literals.
234
    def rows(self, maxcolrow, focus=False):
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
235
        """How many rows this widget will occupy might depend on
236
        whether we have focus or not.
237.7.862 by Teddy Hogeborn
mandos-monitor: avoid deprecation warnings from urwid
237
        This overrides the method from urwid.Widget"""
237.8.1 by teddy at bsnet
* mandos-monitor: Use only unicode string literals.
238
        return self.current_widget(focus).rows(maxcolrow, focus=focus)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
239
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
240
    def current_widget(self, focus=False):
241
        if focus or self.opened:
242
            return self._focus_widget
243
        return self._widget
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
244
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
245
    def update(self):
246
        "Called when what is visible on the screen should be updated."
247
        # How to add standout mode to a style
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
248
        with_standout = {"normal": "standout",
249
                         "bold": "bold-standout",
250
                         "underline-blink":
251
                         "underline-blink-standout",
252
                         "bold-underline-blink":
253
                         "bold-underline-blink-standout",
254
                         }
255
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
256
        # Rebuild focus and non-focus widgets using current properties
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
257
24.1.154 by Björn Påhlsson
merge
258
        # Base part of a client. Name!
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
259
        base = "{name}: ".format(name=self.properties["Name"])
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
260
        if not self.properties["Enabled"]:
261
            message = "DISABLED"
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
262
            self.using_timer(False)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
263
        elif self.properties["ApprovalPending"]:
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
264
            timeout = datetime.timedelta(
265
                milliseconds=self.properties["ApprovalDelay"])
237.2.205 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
266
            last_approval_request = isoformat_to_datetime(
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
267
                self.properties["LastApprovalRequest"])
237.2.205 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
268
            if last_approval_request is not None:
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
269
                timer = max(timeout - (datetime.datetime.utcnow()
270
                                       - last_approval_request),
271
                            datetime.timedelta())
237.2.205 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
272
            else:
273
                timer = datetime.timedelta()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
274
            if self.properties["ApprovedByDefault"]:
237.23.5 by Teddy Hogeborn
Use the new auto-numbered "{}" syntax for the .format() string method.
275
                message = "Approval in {}. (d)eny?"
24.1.159 by Björn Påhlsson
added approval to mandos-ctl
276
            else:
237.23.5 by Teddy Hogeborn
Use the new auto-numbered "{}" syntax for the .format() string method.
277
                message = "Denial in {}. (a)pprove?"
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
278
            message = message.format(str(timer).rsplit(".", 1)[0])
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
279
            self.using_timer(True)
237.7.105 by Teddy Hogeborn
Use the new Client.LastCheckerStatus property.
280
        elif self.properties["LastCheckerStatus"] != 0:
237.7.120 by Teddy Hogeborn
* mandos-ctl: Break long lines.
281
            # When checker has failed, show timer until client expires
24.1.179 by Björn Påhlsson
New feature:
282
            expires = self.properties["Expires"]
283
            if expires == "":
284
                timer = datetime.timedelta(0)
285
            else:
237.7.120 by Teddy Hogeborn
* mandos-ctl: Break long lines.
286
                expires = (datetime.datetime.strptime
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
287
                           (expires, "%Y-%m-%dT%H:%M:%S.%f"))
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
288
                timer = max(expires - datetime.datetime.utcnow(),
289
                            datetime.timedelta())
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
290
            message = ("A checker has failed! Time until client"
291
                       " gets disabled: {}"
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
292
                       .format(str(timer).rsplit(".", 1)[0]))
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
293
            self.using_timer(True)
24.1.154 by Björn Påhlsson
merge
294
        else:
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
295
            message = "enabled"
237.7.129 by Teddy Hogeborn
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
296
            self.using_timer(False)
237.23.5 by Teddy Hogeborn
Use the new auto-numbered "{}" syntax for the .format() string method.
297
        self._text = "{}{}".format(base, message)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
298
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
299
        if not urwid.supports_unicode():
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
300
            self._text = self._text.encode("ascii", "replace")
301
        textlist = [("normal", self._text)]
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
302
        self._text_widget.set_text(textlist)
303
        self._focus_text_widget.set_text([(with_standout[text[0]],
304
                                           text[1])
305
                                          if isinstance(text, tuple)
306
                                          else text
307
                                          for text in textlist])
308
        self._widget = self._text_widget
309
        self._focus_widget = urwid.AttrWrap(self._focus_text_widget,
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
310
                                            "standout")
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
311
        # Run update hook, if any
312
        if self.update_hook is not None:
313
            self.update_hook()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
314
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
315
    def update_timer(self):
237.7.378 by Teddy Hogeborn
Server: Use python-gi instead of old python-gobject
316
        """called by GLib. Will indefinitely loop until
317
        GLib.source_remove() on tag is called
318
        """
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
319
        self.update()
320
        return True             # Keep calling this
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
321
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
322
    def delete(self, **kwargs):
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
323
        if self._update_timer_callback_tag is not None:
237.7.378 by Teddy Hogeborn
Server: Use python-gi instead of old python-gobject
324
            GLib.source_remove(self._update_timer_callback_tag)
237.2.180 by Teddy Hogeborn
* mandos (AvahiService.entry_group_state_changed): Better debug log
325
            self._update_timer_callback_tag = None
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
326
        for match in self.match_objects:
327
            match.remove()
328
        self.match_objects = ()
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
329
        if self.delete_hook is not None:
330
            self.delete_hook(self)
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
331
        return super(MandosClientWidget, self).delete(**kwargs)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
332
237.8.1 by teddy at bsnet
* mandos-monitor: Use only unicode string literals.
333
    def render(self, maxcolrow, focus=False):
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
334
        """Render differently if we have focus.
237.7.862 by Teddy Hogeborn
mandos-monitor: avoid deprecation warnings from urwid
335
        This overrides the method from urwid.Widget"""
237.8.1 by teddy at bsnet
* mandos-monitor: Use only unicode string literals.
336
        return self.current_widget(focus).render(maxcolrow,
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
337
                                                 focus=focus)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
338
237.8.1 by teddy at bsnet
* mandos-monitor: Use only unicode string literals.
339
    def keypress(self, maxcolrow, key):
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
340
        """Handle keys.
237.7.862 by Teddy Hogeborn
mandos-monitor: avoid deprecation warnings from urwid
341
        This overrides the method from urwid.Widget"""
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
342
        if key == "+":
237.7.329 by Teddy Hogeborn
Deprecate some D-Bus methods in favor of D-Bus properties.
343
            self.proxy.Set(client_interface, "Enabled",
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
344
                           dbus.Boolean(True), ignore_reply=True,
345
                           dbus_interface=dbus.PROPERTIES_IFACE)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
346
        elif key == "-":
237.7.329 by Teddy Hogeborn
Deprecate some D-Bus methods in favor of D-Bus properties.
347
            self.proxy.Set(client_interface, "Enabled", False,
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
348
                           ignore_reply=True,
349
                           dbus_interface=dbus.PROPERTIES_IFACE)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
350
        elif key == "a":
24.1.154 by Björn Påhlsson
merge
351
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
352
                               dbus_interface=client_interface,
237.7.30 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
353
                               ignore_reply=True)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
354
        elif key == "d":
24.1.154 by Björn Påhlsson
merge
355
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
356
                               dbus_interface=client_interface,
237.7.30 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
357
                               ignore_reply=True)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
358
        elif key == "R" or key == "_" or key == "ctrl k":
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
359
            self.server_proxy_object.RemoveClient(self.proxy
237.7.30 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
360
                                                  .object_path,
361
                                                  ignore_reply=True)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
362
        elif key == "s":
237.7.329 by Teddy Hogeborn
Deprecate some D-Bus methods in favor of D-Bus properties.
363
            self.proxy.Set(client_interface, "CheckerRunning",
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
364
                           dbus.Boolean(True), ignore_reply=True,
365
                           dbus_interface=dbus.PROPERTIES_IFACE)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
366
        elif key == "S":
237.7.329 by Teddy Hogeborn
Deprecate some D-Bus methods in favor of D-Bus properties.
367
            self.proxy.Set(client_interface, "CheckerRunning",
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
368
                           dbus.Boolean(False), ignore_reply=True,
369
                           dbus_interface=dbus.PROPERTIES_IFACE)
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
370
        elif key == "C":
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
371
            self.proxy.CheckedOK(dbus_interface=client_interface,
237.7.30 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
372
                                 ignore_reply=True)
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
373
        # xxx
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
374
#         elif key == "p" or key == "=":
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
375
#             self.proxy.pause()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
376
#         elif key == "u" or key == ":":
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
377
#             self.proxy.unpause()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
378
#         elif key == "RET":
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
379
#             self.open()
380
        else:
381
            return key
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
382
237.7.280 by Teddy Hogeborn
Emit D-Bus "org.freedesktop.DBus.Properties.PropertiesChanged" signal.
383
    def properties_changed(self, interface, properties, invalidated):
384
        """Call self.update() if any properties changed.
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
385
        This overrides the method from MandosClientPropertyCache"""
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
386
        old_values = {key: self.properties.get(key)
387
                      for key in properties.keys()}
237.7.280 by Teddy Hogeborn
Emit D-Bus "org.freedesktop.DBus.Properties.PropertiesChanged" signal.
388
        super(MandosClientWidget, self).properties_changed(
389
            interface, properties, invalidated)
390
        if any(old_values[key] != self.properties.get(key)
391
               for key in old_values):
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
392
            self.update()
393
394
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
395
def glib_safely(func, retval=True):
396
    def safe_func(*args, **kwargs):
397
        try:
398
            return func(*args, **kwargs)
399
        except Exception:
400
            log.exception("")
401
            return retval
402
    return safe_func
403
404
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
405
class ConstrainedListBox(urwid.ListBox):
406
    """Like a normal urwid.ListBox, but will consume all "up" or
407
    "down" key presses, thus not allowing any containing widgets to
408
    use them as an excuse to shift focus away from this widget.
409
    """
237.7.128 by Teddy Hogeborn
* mandos-monitor: Speedup: Use properties from D-Bus
410
    def keypress(self, *args, **kwargs):
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
411
        ret = (super(ConstrainedListBox, self)
412
               .keypress(*args, **kwargs))
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
413
        if ret in ("up", "down"):
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
414
            return
415
        return ret
416
417
237.7.740 by teddy at recompile
Simplification of Python 3 compatibility code
418
class UserInterface:
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
419
    """This is the entire user interface - the whole screen
420
    with boxes, lists of client widgets, etc.
421
    """
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
422
    def __init__(self, max_log_length=1000):
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
423
        DBusGMainLoop(set_as_default=True)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
424
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
425
        self.screen = urwid.curses_display.Screen()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
426
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
427
        self.screen.register_palette((
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
428
                ("normal",
429
                 "default", "default", None),
430
                ("bold",
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
431
                 "bold", "default", "bold"),
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
432
                ("underline-blink",
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
433
                 "underline,blink", "default", "underline,blink"),
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
434
                ("standout",
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
435
                 "standout", "default", "standout"),
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
436
                ("bold-underline-blink",
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
437
                 "bold,underline,blink", "default",
438
                 "bold,underline,blink"),
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
439
                ("bold-standout",
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
440
                 "bold,standout", "default", "bold,standout"),
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
441
                ("underline-blink-standout",
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
442
                 "underline,blink,standout", "default",
443
                 "underline,blink,standout"),
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
444
                ("bold-underline-blink-standout",
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
445
                 "bold,underline,blink,standout", "default",
446
                 "bold,underline,blink,standout"),
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
447
                ))
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
448
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
449
        if urwid.supports_unicode():
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
450
            self.divider = "─"  # \u2500
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
451
        else:
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
452
            self.divider = "_"  # \u005f
453
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
454
        self.screen.start()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
455
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
456
        self.size = self.screen.get_cols_rows()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
457
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
458
        self.clients = urwid.SimpleListWalker([])
459
        self.clients_dict = {}
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
460
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
461
        # We will add Text widgets to this list
237.7.516 by Teddy Hogeborn
Do minor fix to make mandos-monitor work with new python-urwid
462
        self.log = urwid.SimpleListWalker([])
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
463
        self.max_log_length = max_log_length
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
464
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
465
        # We keep a reference to the log widget so we can remove it
466
        # from the ListWalker without it getting destroyed
467
        self.logbox = ConstrainedListBox(self.log)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
468
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
469
        # This keeps track of whether self.uilist currently has
470
        # self.logbox in it or not
471
        self.log_visible = True
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
472
        self.log_wrap = "any"
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
473
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
474
        self.loghandler = UILogHandler(self)
475
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
476
        self.rebuild()
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
477
        self.add_log_line(("bold",
478
                           "Mandos Monitor version " + version))
479
        self.add_log_line(("bold", "q: Quit  ?: Help"))
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
480
237.7.732 by Teddy Hogeborn
mandos-monitor: Formatting changes only
481
        self.busname = domain + ".Mandos"
237.7.378 by Teddy Hogeborn
Server: Use python-gi instead of old python-gobject
482
        self.main_loop = GLib.MainLoop()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
483
237.7.723 by Teddy Hogeborn
mandos-monitor: Update message from "fingerprint" to "key ID"
484
    def client_not_found(self, key_id, address):
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
485
        log.info("Client with address %s and key ID %s could"
486
                 " not be found", address, key_id)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
487
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
488
    def rebuild(self):
489
        """This rebuilds the User Interface.
490
        Call this when the widget layout needs to change"""
491
        self.uilist = []
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
492
        # self.uilist.append(urwid.ListBox(self.clients))
237.2.185 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
493
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.
494
                                                          clients),
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
495
                                       # header=urwid.Divider(),
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
496
                                       header=None,
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
497
                                       footer=urwid.Divider(
498
                                           div_char=self.divider)))
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
499
        if self.log_visible:
500
            self.uilist.append(self.logbox)
501
        self.topwidget = urwid.Pile(self.uilist)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
502
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
503
    def add_log_line(self, markup):
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
504
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
505
        if self.max_log_length:
506
            if len(self.log) > self.max_log_length:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
507
                del self.log[0:(len(self.log) - self.max_log_length)]
237.7.516 by Teddy Hogeborn
Do minor fix to make mandos-monitor work with new python-urwid
508
        self.logbox.set_focus(len(self.logbox.body.contents)-1,
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
509
                              coming_from="above")
237.2.172 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
510
        self.refresh()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
511
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
512
    def toggle_log_display(self):
513
        """Toggle visibility of the log buffer."""
514
        self.log_visible = not self.log_visible
515
        self.rebuild()
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
516
        log.debug("Log visibility changed to: %s", self.log_visible)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
517
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
518
    def change_log_display(self):
519
        """Change type of log display.
520
        Currently, this toggles wrapping of text lines."""
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
521
        if self.log_wrap == "clip":
522
            self.log_wrap = "any"
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
523
        else:
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
524
            self.log_wrap = "clip"
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
525
        for textwidget in self.log:
526
            textwidget.set_wrap_mode(self.log_wrap)
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
527
        log.debug("Wrap mode: %s", self.log_wrap)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
528
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
529
    def find_and_remove_client(self, path, interfaces):
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
530
        """Find a client by its object path and remove it.
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
531
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
532
        This is connected to the InterfacesRemoved signal from the
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
533
        Mandos server object."""
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
534
        if client_interface not in interfaces:
535
            # Not a Mandos client object; ignore
536
            return
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
537
        try:
538
            client = self.clients_dict[path]
539
        except KeyError:
540
            # not found?
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
541
            log.warning("Unknown client %s removed", path)
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
542
            return
237.7.36 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Save match tag for
543
        client.delete()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
544
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
545
    def add_new_client(self, path, ifs_and_props):
546
        """Find a client by its object path and remove it.
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
547
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
548
        This is connected to the InterfacesAdded signal from the
549
        Mandos server object.
550
        """
551
        if client_interface not in ifs_and_props:
552
            # Not a Mandos client object; ignore
553
            return
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
554
        client_proxy_object = self.bus.get_object(self.busname, path)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
555
        self.add_client(MandosClientWidget(
556
            server_proxy_object=self.mandos_serv,
557
            proxy_object=client_proxy_object,
558
            update_hook=self.refresh,
559
            delete_hook=self.remove_client,
560
            properties=dict(ifs_and_props[client_interface])),
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
561
                        path=path)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
562
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
563
    def add_client(self, client, path=None):
564
        self.clients.append(client)
565
        if path is None:
566
            path = client.proxy.object_path
567
        self.clients_dict[path] = client
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
568
        self.clients.sort(key=lambda c: c.properties["Name"])
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
569
        self.refresh()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
570
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
571
    def remove_client(self, client, path=None):
572
        self.clients.remove(client)
573
        if path is None:
574
            path = client.proxy.object_path
575
        del self.clients_dict[path]
576
        self.refresh()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
577
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
578
    def refresh(self):
579
        """Redraw the screen"""
580
        canvas = self.topwidget.render(self.size, focus=True)
581
        self.screen.draw_screen(self.size, canvas)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
582
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
583
    def run(self):
584
        """Start the main loop and exit when it's done."""
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
585
        log.addHandler(self.loghandler)
586
        self.orig_log_propagate = log.propagate
587
        log.propagate = False
588
        self.orig_log_level = log.level
589
        log.setLevel("INFO")
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
590
        self.bus = dbus.SystemBus()
591
        mandos_dbus_objc = self.bus.get_object(
592
            self.busname, "/", follow_name_owner_changes=True)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
593
        self.mandos_serv = dbus.Interface(
594
            mandos_dbus_objc, dbus_interface=server_interface)
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
595
        try:
596
            mandos_clients = (self.mandos_serv
597
                              .GetAllClientsWithProperties())
237.7.160 by Björn Påhlsson
added note messages when mandos-monitor starts without running server,
598
            if not mandos_clients:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
599
                log.warning("Note: Server has no clients.")
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
600
        except dbus.exceptions.DBusException:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
601
            log.warning("Note: No Mandos server running.")
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
602
            mandos_clients = dbus.Dictionary()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
603
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
604
        (self.mandos_serv
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
605
         .connect_to_signal("InterfacesRemoved",
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
606
                            self.find_and_remove_client,
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
607
                            dbus_interface=dbus.OBJECT_MANAGER_IFACE,
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
608
                            byte_arrays=True))
609
        (self.mandos_serv
237.7.333 by Teddy Hogeborn
Support the standard org.freedesktop.DBus.ObjectManager interface.
610
         .connect_to_signal("InterfacesAdded",
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
611
                            self.add_new_client,
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
612
                            dbus_interface=dbus.OBJECT_MANAGER_IFACE,
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
613
                            byte_arrays=True))
614
        (self.mandos_serv
615
         .connect_to_signal("ClientNotFound",
616
                            self.client_not_found,
617
                            dbus_interface=server_interface,
618
                            byte_arrays=True))
237.7.165 by Teddy Hogeborn
* mandos: Bug fix: Don't print output from checkers when running in
619
        for path, client in mandos_clients.items():
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
620
            client_proxy_object = self.bus.get_object(self.busname,
621
                                                      path)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
622
            self.add_client(MandosClientWidget(
623
                server_proxy_object=self.mandos_serv,
624
                proxy_object=client_proxy_object,
625
                properties=client,
626
                update_hook=self.refresh,
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
627
                delete_hook=self.remove_client),
237.7.85 by Björn Påhlsson
nicer stacktrace when mandos-monitor fail during startup
628
                            path=path)
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
629
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
630
        self.refresh()
237.7.717 by Teddy Hogeborn
mandos-monitor: Use new GLib.io_add_watch() call signature
631
        self._input_callback_tag = (
632
            GLib.io_add_watch(
633
                GLib.IOChannel.unix_new(sys.stdin.fileno()),
634
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
635
                glib_safely(self.process_input)))
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
636
        self.main_loop.run()
637
        # Main loop has finished, we should close everything now
237.7.378 by Teddy Hogeborn
Server: Use python-gi instead of old python-gobject
638
        GLib.source_remove(self._input_callback_tag)
237.7.722 by Teddy Hogeborn
Address Python 3 bytes/str warnings
639
        with warnings.catch_warnings():
640
            warnings.simplefilter("ignore", BytesWarning)
641
            self.screen.stop()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
642
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
643
    def stop(self):
644
        self.main_loop.quit()
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
645
        log.removeHandler(self.loghandler)
646
        log.propagate = self.orig_log_propagate
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
647
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
648
    def process_input(self, source, condition):
649
        keys = self.screen.get_input()
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
650
        translations = {"ctrl n": "down",       # Emacs
651
                        "ctrl p": "up",         # Emacs
652
                        "ctrl v": "page down",  # Emacs
653
                        "meta v": "page up",    # Emacs
654
                        " ": "page down",       # less
655
                        "f": "page down",       # less
656
                        "b": "page up",         # less
657
                        "j": "down",            # vi
658
                        "k": "up",              # vi
659
                        }
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
660
        for key in keys:
661
            try:
662
                key = translations[key]
663
            except KeyError:    # :-)
664
                pass
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
665
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
666
            if key == "q" or key == "Q":
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
667
                self.stop()
668
                break
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
669
            elif key == "window resize":
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
670
                self.size = self.screen.get_cols_rows()
671
                self.refresh()
237.7.270 by Teddy Hogeborn
mandos-monitor: Bug fix: Make Ctrl-L actually redraw the screen.
672
            elif key == "ctrl l":
673
                self.screen.clear()
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
674
                self.refresh()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
675
            elif key == "l" or key == "D":
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
676
                self.toggle_log_display()
677
                self.refresh()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
678
            elif key == "w" or key == "i":
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
679
                self.change_log_display()
680
                self.refresh()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
681
            elif key == "?" or key == "f1" or key == "esc":
237.2.170 by Teddy Hogeborn
* mandos-monitor (MandosClientWidget): Change "StopChecker" key to "S"
682
                if not self.log_visible:
683
                    self.log_visible = True
684
                    self.rebuild()
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
685
                self.add_log_line(("bold",
686
                                   "  ".join(("q: Quit",
687
                                              "?: Help",
688
                                              "l: Log window toggle",
689
                                              "TAB: Switch window",
690
                                              "w: Wrap (log lines)",
691
                                              "v: Toggle verbose log",
692
                                   ))))
693
                self.add_log_line(("bold",
694
                                   "  ".join(("Clients:",
695
                                              "+: Enable",
696
                                              "-: Disable",
697
                                              "R: Remove",
698
                                              "s: Start new checker",
699
                                              "S: Stop checker",
700
                                              "C: Checker OK",
701
                                              "a: Approve",
702
                                              "d: Deny",
703
                                   ))))
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
704
                self.refresh()
237.8.2 by teddy at bsnet
* mandos-monitor: Use unicode string literals. Update __future__
705
            elif key == "tab":
237.2.168 by Teddy Hogeborn
* mandos-monitor (MandosClientPropertyCache): Remove conversion of
706
                if self.topwidget.get_focus() is self.logbox:
707
                    self.topwidget.set_focus(0)
708
                else:
709
                    self.topwidget.set_focus(self.logbox)
710
                self.refresh()
237.7.261 by Teddy Hogeborn
mandos-monitor: New "verbose" mode to see less important log messages.
711
            elif key == "v":
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
712
                if log.level < logging.INFO:
713
                    log.setLevel(logging.INFO)
714
                    log.info("Verbose mode: Off")
237.7.261 by Teddy Hogeborn
mandos-monitor: New "verbose" mode to see less important log messages.
715
                else:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
716
                    log.setLevel(logging.NOTSET)
717
                    log.info("Verbose mode: On")
237.7.421 by Teddy Hogeborn
PEP8 compliance: mandos-monitor
718
            # elif (key == "end" or key == "meta >" or key == "G"
719
            #       or key == ">"):
720
            #     pass            # xxx end-of-buffer
721
            # elif (key == "home" or key == "meta <" or key == "g"
722
            #       or key == "<"):
723
            #     pass            # xxx beginning-of-buffer
724
            # elif key == "ctrl e" or key == "$":
725
            #     pass            # xxx move-end-of-line
726
            # elif key == "ctrl a" or key == "^":
727
            #     pass            # xxx move-beginning-of-line
728
            # elif key == "ctrl b" or key == "meta (" or key == "h":
729
            #     pass            # xxx left
730
            # elif key == "ctrl f" or key == "meta )" or key == "l":
731
            #     pass            # xxx right
732
            # elif key == "a":
733
            #     pass            # scroll up log
734
            # elif key == "z":
735
            #     pass            # scroll down log
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
736
            elif self.topwidget.selectable():
737
                self.topwidget.keypress(self.size, key)
738
                self.refresh()
739
        return True
740
237.7.436 by Teddy Hogeborn
Add more PEP8 compliance (as per the "pycodestyle" tool).
741
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
742
class UILogHandler(logging.Handler):
743
    def __init__(self, ui, *args, **kwargs):
744
        self.ui = ui
745
        super(UILogHandler, self).__init__(*args, **kwargs)
746
        self.setFormatter(
747
            logging.Formatter("%(asctime)s: %(message)s"))
748
    def emit(self, record):
749
        msg = self.format(record)
750
        if record.levelno > logging.INFO:
751
            msg = ("bold", msg)
752
        self.ui.add_log_line(msg)
753
754
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
755
ui = UserInterface()
756
try:
757
    ui.run()
24.1.159 by Björn Påhlsson
added approval to mandos-ctl
758
except KeyboardInterrupt:
237.7.731 by Teddy Hogeborn
mandos-monitor: Use Python's standard loggging module
759
    with warnings.catch_warnings():
760
        warnings.filterwarnings("ignore", "", BytesWarning)
761
        ui.screen.stop()
762
except Exception:
763
    with warnings.catch_warnings():
764
        warnings.filterwarnings("ignore", "", BytesWarning)
765
        ui.screen.stop()
237.2.167 by Teddy Hogeborn
* mandos-monitor: New prototype version of interactive server
766
    raise