/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk
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
#!/usr/bin/python
# -*- mode: python; coding: utf-8 -*-

from __future__ import division, absolute_import, with_statement

import sys
import signal

import urwid.curses_display
import urwid

from dbus.mainloop.glib import DBusGMainLoop
import gobject

import dbus

import UserList

# Some useful constants
domain = 'se.bsnet.fukt'
server_interface = domain + '.Mandos'
client_interface = domain + '.Mandos.Client'
version = "1.0.14"

# Always run in monochrome mode
urwid.curses_display.curses.has_colors = lambda : False

# Urwid doesn't support blinking, but we want it.  Since we have no
# use for underline on its own, we make underline also always blink.
urwid.curses_display.curses.A_UNDERLINE |= (
    urwid.curses_display.curses.A_BLINK)

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, *args,
                 **kwargs):
        # Type conversion mapping
        self.type_map = {
            dbus.ObjectPath: unicode,
            dbus.ByteArray: str,
            dbus.Signature: unicode,
            dbus.Byte: chr,
            dbus.Int16: int,
            dbus.UInt16: int,
            dbus.Int32: int,
            dbus.UInt32: int,
            dbus.Int64: int,
            dbus.UInt64: int,
            dbus.Dictionary: dict,
            dbus.Array: list,
            dbus.String: unicode,
            dbus.Boolean: bool,
            dbus.Double: float,
            dbus.Struct: tuple,
            }
        self.proxy = proxy_object # Mandos Client proxy object
        
        if properties is None:
            self.properties = dict()
        else:
            self.properties = dict(self.convert_property(prop, val)
                                   for prop, val in
                                   properties.iteritems())
        self.proxy.connect_to_signal("PropertyChanged",
                                     self.property_changed,
                                     client_interface,
                                     byte_arrays=True)
        
        if properties is None:
            self.properties.update(
                self.convert_property(prop, val)
                for prop, val in
                self.proxy.GetAll(client_interface,
                                  dbus_interface =
                                  dbus.PROPERTIES_IFACE).iteritems())
        super(MandosClientPropertyCache, self).__init__(
            proxy_object=proxy_object,
            properties=properties, *args, **kwargs)
    
    def convert_property(self, property, value):
        """This converts the arguments from a D-Bus signal, which are
        D-Bus types, into normal Python types, using a conversion
        function from "self.type_map".
        """
        property_name = unicode(property) # Always a dbus.String
        if isinstance(value, dbus.UTF8String):
            # Should not happen, but prepare for it anyway
            value = dbus.String(str(value).decode("utf-8"))
        try:
            convfunc = self.type_map[type(value)]
        except KeyError:
            # Unknown type, return unmodified
            return property_name, value
        return property_name, convfunc(value)
    def property_changed(self, property=None, value=None):
        """This is called whenever we get a PropertyChanged signal
        It updates the changed property in the "properties" dict.
        """
        # Convert name and value
        property_name, cvalue = self.convert_property(property, value)
        # Update properties dict with new value
        self.properties[property_name] = cvalue


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, *args, **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
        
        # 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__(
            update_hook=update_hook, delete_hook=delete_hook,
            *args, **kwargs)
        self.update()
        self.opened = False
    
    def selectable(self):
        """Make this a "selectable" widget.
        This overrides the method from urwid.FlowWidget."""
        return True
    
    def rows(self, (maxcol,), 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((maxcol,), 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 = { u"normal": u"standout",
                          u"bold": u"bold-standout",
                          u"underline-blink":
                              u"underline-blink-standout",
                          u"bold-underline-blink":
                              u"bold-underline-blink-standout",
                          }
        
        # Rebuild focus and non-focus widgets using current properties
        self._text = (u'name="%(name)s", enabled=%(enabled)s'
                      % self.properties)
        if not urwid.supports_unicode():
            self._text = self._text.encode("ascii", "replace")
        textlist = [(u"normal", u"BLĂ„RGH: "), (u"bold", 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 delete(self):
        if self.delete_hook is not None:
            self.delete_hook(self)
    
    def render(self, (maxcol,), focus=False):
        """Render differently if we have focus.
        This overrides the method from urwid.FlowWidget"""
        return self.current_widget(focus).render((maxcol,),
                                                 focus=focus)
    
    def keypress(self, (maxcol,), key):
        """Handle keys.
        This overrides the method from urwid.FlowWidget"""
        if key == u"e" or key == u"+":
            self.proxy.Enable()
        elif key == u"d" or key == u"-":
            self.proxy.Disable()
        elif key == u"r" or key == u"_":
            self.server_proxy_object.RemoveClient(self.proxy
                                                  .object_path)
        elif key == u"s":
            self.proxy.StartChecker()
        elif key == u"c":
            self.proxy.StopChecker()
        elif key == u"S":
            self.proxy.CheckedOK()
        # xxx
#         elif key == u"p" or key == "=":
#             self.proxy.pause()
#         elif key == u"u" or key == ":":
#             self.proxy.unpause()
#         elif key == u"RET":
#             self.open()
        else:
            return key
    
    def property_changed(self, property=None, value=None,
                         *args, **kwargs):
        """Call self.update() if old value is not new value.
        This overrides the method from MandosClientPropertyCache"""
        property_name = unicode(property)
        old_value = self.properties.get(property_name)
        super(MandosClientWidget, self).property_changed(
            property=property, value=value, *args, **kwargs)
        if self.properties.get(property_name) != old_value:
            self.update()


class UserInterface(object):
    """This is the entire user interface - the whole screen
    with boxes, lists of client widgets, etc.
    """
    def __init__(self):
        DBusGMainLoop(set_as_default=True )
        
        self.screen = urwid.curses_display.Screen()
        
        self.screen.register_palette((
                (u"normal",
                 u"default", u"default", None),
                (u"bold",
                 u"default", u"default", u"bold"),
                (u"underline-blink",
                 u"default", u"default", u"underline"),
                (u"standout",
                 u"default", u"default", u"standout"),
                (u"bold-underline-blink",
                 u"default", u"default", (u"bold", u"underline")),
                (u"bold-standout",
                 u"default", u"default", (u"bold", u"standout")),
                (u"underline-blink-standout",
                 u"default", u"default", (u"underline", u"standout")),
                (u"bold-underline-blink-standout",
                 u"default", u"default", (u"bold", u"underline",
                                          u"standout")),
                ))
        
        self.screen.start()
        
        self.size = self.screen.get_cols_rows()
        
        self.clients = urwid.SimpleListWalker([])
        self.clients_dict = {}
        self.topwidget = urwid.LineBox(urwid.ListBox(self.clients))
        #self.topwidget = urwid.ListBox(clients)
        
        self.busname = domain + '.Mandos'
        self.main_loop = gobject.MainLoop()
        self.bus = dbus.SystemBus()
        mandos_dbus_objc = self.bus.get_object(
            self.busname, u"/", follow_name_owner_changes=True)
        self.mandos_serv = dbus.Interface(mandos_dbus_objc,
                                          dbus_interface
                                          = server_interface)
        try:
            mandos_clients = (self.mandos_serv
                              .GetAllClientsWithProperties())
        except dbus.exceptions.DBusException:
            mandos_clients = dbus.Dictionary()
        
        (self.mandos_serv
         .connect_to_signal("ClientRemoved",
                            self.find_and_remove_client,
                            dbus_interface=server_interface,
                            byte_arrays=True))
        (self.mandos_serv
         .connect_to_signal("ClientAdded",
                            self.add_new_client,
                            dbus_interface=server_interface,
                            byte_arrays=True))
        for path, client in (mandos_clients.iteritems()):
            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)
    
    def find_and_remove_client(self, path, name):
        """Find an client from its object path and remove it.
        
        This is connected to the ClientRemoved signal from the
        Mandos server object."""
        try:
            client = self.clients_dict[path]
        except KeyError:
            # not found?
            return
        self.remove_client(client, path)
    
    def add_new_client(self, path, properties):
        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=properties,
                                           update_hook
                                           =self.refresh,
                                           delete_hook
                                           =self.remove_client),
                        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(None, lambda c: c.properties[u"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."""
        self.refresh()
        self._input_callback_tag = (gobject.io_add_watch
                                    (sys.stdin.fileno(),
                                     gobject.IO_IN,
                                     self.process_input))
        self.main_loop.run()
        # Main loop has finished, we should close everything now
        gobject.source_remove(self._input_callback_tag)
        self.screen.stop()
    
    def stop(self):
        self.main_loop.quit()
    
    def process_input(self, source, condition):
        keys = self.screen.get_input()
        translations = { u"j": u"down",
                         u"k": u"up",
                         }
        for key in keys:
            try:
                key = translations[key]
            except KeyError:    # :-)
                pass
            
            if key == u"q" or key == u"Q":
                self.stop()
                break
            elif key == u"window resize":
                self.size = self.screen.get_cols_rows()
                self.refresh()
            elif key == "":
                self.refresh()
            elif self.topwidget.selectable():
                self.topwidget.keypress(self.size, key)
                self.refresh()
        return True

ui = UserInterface()
try:
    ui.run()
except:
    ui.screen.stop()
    raise