/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos-monitor

* mandos-monitor (MandosClientPropertyCache): Remove conversion of
                                              D-Bus types to native
                                              Python types.
  (MandosClientPropertyCache.type_map): Removed attribute.
  (MandosClientPropertyCache.conversion): Removed method.
  (ConstrainedListBox): New; a ListBox which will keep the focus.
  (UserInterface.__init__): Take new argument "max_log_length".
  (UserInterface.divider, UserInterface.log,
  UserInterface.max_log_length, UserInterface.logbox,
  UserInterface.log_visible, UserInterface.log_wrap): New attributes.
  (UserInterface.rebuild, UserInterface.log_message,
  UserInterface.toggle_log_display, UserInterface.change_log_display):
  New methods.
  (UserInterface.remove_client): Bug fix: Eliminate double client
                                 listing when an empty list gets a
                                 ClientAdded signal.
  (UserInterface.process_input): Add more key translations.

Show diffs side-by-side

added added

removed removed

Lines of Context:
4
4
from __future__ import division, absolute_import, with_statement
5
5
 
6
6
import sys
7
 
import os
8
7
import signal
9
8
 
10
 
import datetime
11
 
 
12
9
import urwid.curses_display
13
10
import urwid
14
11
 
19
16
 
20
17
import UserList
21
18
 
22
 
import locale
23
 
 
24
 
locale.setlocale(locale.LC_ALL, u'')
25
 
 
26
 
import logging
27
 
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
28
 
 
29
19
# Some useful constants
30
20
domain = 'se.bsnet.fukt'
31
21
server_interface = domain + '.Mandos'
32
22
client_interface = domain + '.Mandos.Client'
33
 
version = "1.0.15"
 
23
version = "1.0.14"
34
24
 
35
25
# Always run in monochrome mode
36
26
urwid.curses_display.curses.has_colors = lambda : False
45
35
    properties and calls a hook function when any of them are
46
36
    changed.
47
37
    """
48
 
    def __init__(self, proxy_object=None, *args, **kwargs):
 
38
    def __init__(self, proxy_object=None, properties=None, *args,
 
39
                 **kwargs):
49
40
        self.proxy = proxy_object # Mandos Client proxy object
50
41
        
51
 
        self.properties = dict()
52
 
        self.proxy.connect_to_signal(u"PropertyChanged",
 
42
        if properties is None:
 
43
            self.properties = dict()
 
44
        else:
 
45
            self.properties = properties
 
46
        self.proxy.connect_to_signal("PropertyChanged",
53
47
                                     self.property_changed,
54
48
                                     client_interface,
55
49
                                     byte_arrays=True)
56
50
        
57
 
        self.properties.update(
58
 
            self.proxy.GetAll(client_interface,
59
 
                              dbus_interface = dbus.PROPERTIES_IFACE))
60
 
 
61
 
        #XXX This break good super behaviour!
62
 
#        super(MandosClientPropertyCache, self).__init__(
63
 
#            *args, **kwargs)
 
51
        if properties is None:
 
52
            self.properties.update(self.proxy.GetAll(client_interface,
 
53
                                                     dbus_interface =
 
54
                                                     dbus.PROPERTIES_IFACE))
 
55
        super(MandosClientPropertyCache, self).__init__(
 
56
            proxy_object=proxy_object,
 
57
            properties=properties, *args, **kwargs)
64
58
    
65
59
    def property_changed(self, property=None, value=None):
66
60
        """This is called whenever we get a PropertyChanged signal
75
69
    """
76
70
    
77
71
    def __init__(self, server_proxy_object=None, update_hook=None,
78
 
                 delete_hook=None, logger=None, *args, **kwargs):
 
72
                 delete_hook=None, *args, **kwargs):
79
73
        # Called on update
80
74
        self.update_hook = update_hook
81
75
        # Called on delete
82
76
        self.delete_hook = delete_hook
83
77
        # Mandos Server proxy object
84
78
        self.server_proxy_object = server_proxy_object
85
 
        # Logger
86
 
        self.logger = logger
87
79
        
88
80
        # The widget shown normally
89
 
        self._text_widget = urwid.Text(u"")
 
81
        self._text_widget = urwid.Text("")
90
82
        # The widget shown when we have focus
91
 
        self._focus_text_widget = urwid.Text(u"")
 
83
        self._focus_text_widget = urwid.Text("")
92
84
        super(MandosClientWidget, self).__init__(
93
85
            update_hook=update_hook, delete_hook=delete_hook,
94
86
            *args, **kwargs)
95
87
        self.update()
96
88
        self.opened = False
97
 
        self.proxy.connect_to_signal(u"CheckerCompleted",
98
 
                                     self.checker_completed,
99
 
                                     client_interface,
100
 
                                     byte_arrays=True)
101
 
        self.proxy.connect_to_signal(u"CheckerStarted",
102
 
                                     self.checker_started,
103
 
                                     client_interface,
104
 
                                     byte_arrays=True)
105
 
        self.proxy.connect_to_signal(u"GotSecret",
106
 
                                     self.got_secret,
107
 
                                     client_interface,
108
 
                                     byte_arrays=True)
109
 
        self.proxy.connect_to_signal(u"NeedApproval",
110
 
                                     self.need_approval,
111
 
                                     client_interface,
112
 
                                     byte_arrays=True)
113
 
        self.proxy.connect_to_signal(u"Rejected",
114
 
                                     self.rejected,
115
 
                                     client_interface,
116
 
                                     byte_arrays=True)
117
 
    
118
 
    def checker_completed(self, exitstatus, condition, command):
119
 
        if exitstatus == 0:
120
 
            #self.logger(u'Checker for client %s (command "%s")'
121
 
            #            u' was successful'
122
 
            #            % (self.properties[u"name"], command))
123
 
            return
124
 
        if os.WIFEXITED(condition):
125
 
            self.logger(u'Checker for client %s (command "%s")'
126
 
                        u' failed with exit code %s'
127
 
                        % (self.properties[u"name"], command,
128
 
                           os.WEXITSTATUS(condition)))
129
 
            return
130
 
        if os.WIFSIGNALED(condition):
131
 
            self.logger(u'Checker for client %s (command "%s")'
132
 
                        u' was killed by signal %s'
133
 
                        % (self.properties[u"name"], command,
134
 
                           os.WTERMSIG(condition)))
135
 
            return
136
 
        if os.WCOREDUMP(condition):
137
 
            self.logger(u'Checker for client %s (command "%s")'
138
 
                        u' dumped core'
139
 
                        % (self.properties[u"name"], command))
140
 
        self.logger(u'Checker for client %s completed mysteriously')
141
 
    
142
 
    def checker_started(self, command):
143
 
        #self.logger(u'Client %s started checker "%s"'
144
 
        #            % (self.properties[u"name"], unicode(command)))
145
 
        pass
146
 
    
147
 
    def got_secret(self):
148
 
        self.logger(u'Client %s received its secret'
149
 
                    % self.properties[u"name"])
150
 
    
151
 
    def need_approval(self, timeout, default):
152
 
        if not default:
153
 
            message = u'Client %s needs approval within %s seconds'
154
 
        else:
155
 
            message = u'Client %s will get its secret in %s seconds'
156
 
        self.logger(message
157
 
                    % (self.properties[u"name"], timeout/1000))
158
 
    
159
 
    def rejected(self, reason):
160
 
        self.logger(u'Client %s was rejected; reason: %s'
161
 
                    % (self.properties[u"name"], reason))
162
89
    
163
90
    def selectable(self):
164
91
        """Make this a "selectable" widget.
186
113
                          u"bold-underline-blink":
187
114
                              u"bold-underline-blink-standout",
188
115
                          }
189
 
 
 
116
        
190
117
        # Rebuild focus and non-focus widgets using current properties
191
 
 
192
 
        # Base part of a client. Name!
193
 
        self._text = (u'%(name)s: '
194
 
                      % {u"name": self.properties[u"name"]})
195
 
 
196
 
        if self.properties[u"approved_pending"]:
197
 
            if self.properties[u"approved_by_default"]:
198
 
                self._text += u"Connection established to client. (d)eny?"
199
 
            else:
200
 
                self._text += u"Seeks approval to send secret. (a)pprove?"
201
 
        else:
202
 
            self._text += (u'%(enabled)s'
203
 
                           % {u"enabled":
204
 
                               (u"enabled"
205
 
                                if self.properties[u"enabled"]
206
 
                                else u"DISABLED")})
 
118
        self._text = (u'name="%(name)s", enabled=%(enabled)s'
 
119
                      % self.properties)
207
120
        if not urwid.supports_unicode():
208
121
            self._text = self._text.encode("ascii", "replace")
209
 
        textlist = [(u"normal", self._text)]
 
122
        textlist = [(u"normal", u"BLARGH: "), (u"bold", self._text)]
210
123
        self._text_widget.set_text(textlist)
211
124
        self._focus_text_widget.set_text([(with_standout[text[0]],
212
125
                                           text[1])
233
146
    def keypress(self, (maxcol,), key):
234
147
        """Handle keys.
235
148
        This overrides the method from urwid.FlowWidget"""
236
 
        if key == u"+":
237
 
            self.proxy.Enable(dbus_interface = client_interface)
238
 
        elif key == u"-":
239
 
            self.proxy.Disable(dbus_interface = client_interface)
240
 
        elif key == u"a":
241
 
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
242
 
                               dbus_interface = client_interface)
243
 
        elif key == u"d":
244
 
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
245
 
                                  dbus_interface = client_interface)
246
 
        elif key == u"r" or key == u"_" or key == u"ctrl k":
 
149
        if key == u"e" or key == u"+":
 
150
            self.proxy.Enable()
 
151
        elif key == u"d" or key == u"-":
 
152
            self.proxy.Disable()
 
153
        elif key == u"r" or key == u"_":
247
154
            self.server_proxy_object.RemoveClient(self.proxy
248
155
                                                  .object_path)
249
156
        elif key == u"s":
250
 
            self.proxy.StartChecker(dbus_interface = client_interface)
 
157
            self.proxy.StartChecker()
 
158
        elif key == u"c":
 
159
            self.proxy.StopChecker()
251
160
        elif key == u"S":
252
 
            self.proxy.StopChecker(dbus_interface = client_interface)
253
 
        elif key == u"C":
254
 
            self.proxy.CheckedOK(dbus_interface = client_interface)
 
161
            self.proxy.CheckedOK()
255
162
        # xxx
256
163
#         elif key == u"p" or key == "=":
257
164
#             self.proxy.pause()
259
166
#             self.proxy.unpause()
260
167
#         elif key == u"RET":
261
168
#             self.open()
262
 
#        elif key == u"+":
263
 
#            self.proxy.Approve(True)
264
 
#        elif key == u"-":
265
 
#            self.proxy.Approve(False)
266
169
        else:
267
170
            return key
268
171
    
320
223
                ))
321
224
        
322
225
        if urwid.supports_unicode():
323
 
            self.divider = u"─" # \u2500
324
 
            #self.divider = u"━" # \u2501
 
226
            #self.divider = u"─" # \u2500
 
227
            self.divider = u"━" # \u2501
325
228
        else:
326
229
            #self.divider = u"-" # \u002d
327
230
            self.divider = u"_" # \u005f
347
250
        self.log_wrap = u"any"
348
251
        
349
252
        self.rebuild()
350
 
        self.log_message_raw((u"bold",
351
 
                              u"Mandos Monitor version " + version))
352
 
        self.log_message_raw((u"bold",
353
 
                              u"q: Quit  ?: Help"))
 
253
        self.log_message(u"Message")
 
254
        self.log_message(u"Message0 Message1 Message2 Message3 Message4 Message5 Message6 Message7 Message8 Message9")
 
255
        self.log_message(u"Message10 Message11 Message12 Message13 Message14 Message15 Message16 Message17 Message18 Message19")
 
256
        self.log_message(u"Message20 Message21 Message22 Message23 Message24 Message25 Message26 Message27 Message28 Message29")
354
257
        
355
258
        self.busname = domain + '.Mandos'
356
259
        self.main_loop = gobject.MainLoop()
367
270
            mandos_clients = dbus.Dictionary()
368
271
        
369
272
        (self.mandos_serv
370
 
         .connect_to_signal(u"ClientRemoved",
 
273
         .connect_to_signal("ClientRemoved",
371
274
                            self.find_and_remove_client,
372
275
                            dbus_interface=server_interface,
373
276
                            byte_arrays=True))
374
277
        (self.mandos_serv
375
 
         .connect_to_signal(u"ClientAdded",
 
278
         .connect_to_signal("ClientAdded",
376
279
                            self.add_new_client,
377
280
                            dbus_interface=server_interface,
378
281
                            byte_arrays=True))
379
 
        (self.mandos_serv
380
 
         .connect_to_signal(u"ClientNotFound",
381
 
                            self.client_not_found,
382
 
                            dbus_interface=server_interface,
383
 
                            byte_arrays=True))
384
282
        for path, client in mandos_clients.iteritems():
385
283
            client_proxy_object = self.bus.get_object(self.busname,
386
284
                                                      path)
392
290
                                               update_hook
393
291
                                               =self.refresh,
394
292
                                               delete_hook
395
 
                                               =self.remove_client,
396
 
                                               logger
397
 
                                               =self.log_message),
 
293
                                               =self.remove_client),
398
294
                            path=path)
399
295
    
400
 
    def client_not_found(self, fingerprint, address):
401
 
        self.log_message((u"Client with address %s and fingerprint %s"
402
 
                          u" could not be found" % (address,
403
 
                                                    fingerprint)))
404
 
    
405
296
    def rebuild(self):
406
297
        """This rebuilds the User Interface.
407
298
        Call this when the widget layout needs to change"""
416
307
            pass
417
308
        self.topwidget = urwid.Pile(self.uilist)
418
309
    
419
 
    def log_message(self, message):
420
 
        timestamp = datetime.datetime.now().isoformat()
421
 
        self.log_message_raw(timestamp + u": " + message)
422
 
    
423
 
    def log_message_raw(self, markup):
 
310
    def log_message(self, markup):
424
311
        """Add a log message to the log buffer."""
425
312
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
426
313
        if (self.max_log_length
427
314
            and len(self.log) > self.max_log_length):
428
315
            del self.log[0:len(self.log)-self.max_log_length-1]
429
 
        self.logbox.set_focus(len(self.logbox.body.contents),
430
 
                              coming_from=u"above")
431
 
        self.refresh()
432
316
    
433
317
    def toggle_log_display(self):
434
318
        """Toggle visibility of the log buffer."""
460
344
            return
461
345
        self.remove_client(client, path)
462
346
    
463
 
    def add_new_client(self, path):
 
347
    def add_new_client(self, path, properties):
464
348
        client_proxy_object = self.bus.get_object(self.busname, path)
465
349
        self.add_client(MandosClientWidget(server_proxy_object
466
350
                                           =self.mandos_serv,
467
351
                                           proxy_object
468
352
                                           =client_proxy_object,
 
353
                                           properties=properties,
469
354
                                           update_hook
470
355
                                           =self.refresh,
471
356
                                           delete_hook
472
 
                                           =self.remove_client,
473
 
                                           logger
474
 
                                           =self.log_message),
 
357
                                           =self.remove_client),
475
358
                        path=path)
476
359
    
477
360
    def add_client(self, client, path=None):
546
429
            elif key == u"w" or key == u"i":
547
430
                self.change_log_display()
548
431
                self.refresh()
549
 
            elif key == u"?" or key == u"f1" or key == u"esc":
550
 
                if not self.log_visible:
551
 
                    self.log_visible = True
552
 
                    self.rebuild()
553
 
                self.log_message_raw((u"bold",
554
 
                                      u"  ".
555
 
                                      join((u"q: Quit",
556
 
                                            u"?: Help",
557
 
                                            u"l: Log window toggle",
558
 
                                            u"TAB: Switch window",
559
 
                                            u"w: Wrap (log)"))))
560
 
                self.log_message_raw((u"bold",
561
 
                                      u"  "
562
 
                                      .join((u"Clients:",
563
 
                                             u"+: Enable",
564
 
                                             u"-: Disable",
565
 
                                             u"r: Remove",
566
 
                                             u"s: Start new checker",
567
 
                                             u"S: Stop checker",
568
 
                                             u"C: Checker OK",
569
 
                                             u"a: Approve",
570
 
                                             u"d: Deny"))))
 
432
            elif key == u"?" or key == u"f1":
 
433
                self.log_message(u"Help!")
571
434
                self.refresh()
572
435
            elif key == u"tab":
573
436
                if self.topwidget.get_focus() is self.logbox:
575
438
                else:
576
439
                    self.topwidget.set_focus(self.logbox)
577
440
                self.refresh()
578
 
            #elif (key == u"end" or key == u"meta >" or key == u"G"
579
 
            #      or key == u">"):
580
 
            #    pass            # xxx end-of-buffer
581
 
            #elif (key == u"home" or key == u"meta <" or key == u"g"
582
 
            #      or key == u"<"):
583
 
            #    pass            # xxx beginning-of-buffer
584
 
            #elif key == u"ctrl e" or key == u"$":
585
 
            #    pass            # xxx move-end-of-line
586
 
            #elif key == u"ctrl a" or key == u"^":
587
 
            #    pass            # xxx move-beginning-of-line
588
 
            #elif key == u"ctrl b" or key == u"meta (" or key == u"h":
589
 
            #    pass            # xxx left
590
 
            #elif key == u"ctrl f" or key == u"meta )" or key == u"l":
591
 
            #    pass            # xxx right
592
 
            #elif key == u"a":
593
 
            #    pass            # scroll up log
594
 
            #elif key == u"z":
595
 
            #    pass            # scroll down log
 
441
            elif (key == u"end" or key == u"meta >" or key == u"G"
 
442
                  or key == u">"):
 
443
                pass            # xxx end-of-buffer
 
444
            elif (key == u"home" or key == u"meta <" or key == u"g"
 
445
                  or key == u"<"):
 
446
                pass            # xxx beginning-of-buffer
 
447
            elif key == u"ctrl e" or key == u"$":
 
448
                pass            # xxx move-end-of-line
 
449
            elif key == u"ctrl a" or key == u"^":
 
450
                pass            # xxx move-beginning-of-line
 
451
            elif key == u"ctrl b" or key == u"meta (" or key == u"h":
 
452
                pass            # xxx left
 
453
            elif key == u"ctrl f" or key == u"meta )" or key == u"l":
 
454
                pass            # xxx right
 
455
            elif key == u"a":
 
456
                pass            # scroll up log
 
457
            elif key == u"z":
 
458
                pass            # scroll down log
596
459
            elif self.topwidget.selectable():
597
460
                self.topwidget.keypress(self.size, key)
598
461
                self.refresh()
601
464
ui = UserInterface()
602
465
try:
603
466
    ui.run()
604
 
except Exception, e:
605
 
    ui.log_message(unicode(e))
 
467
except:
606
468
    ui.screen.stop()
607
469
    raise