/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos-monitor

  • Committer: Teddy Hogeborn
  • Date: 2010-09-25 23:52:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100925235217-4hhqfryz1ste6uw3
* mandos (ClientDBus.__init__): Bug fix: Translate "-" in client names
                                to "_" in D-Bus object paths.
  (MandosServer.handle_ipc): Bug fix: Send only address string to
                             D-Bus signal, not whole tuple.

* mandos-ctl: New options "--approve-by-default", "--deny-by-default",
              "--approval-delay", and "--approval-duration".
* mandos-ctl.xml (SYNOPSIS, OPTIONS): Document new options.

* mandos-monitor (MandosClientWidget.update): Fix spelling.

Show diffs side-by-side

added added

removed removed

Lines of Context:
40
40
urwid.curses_display.curses.A_UNDERLINE |= (
41
41
    urwid.curses_display.curses.A_BLINK)
42
42
 
 
43
def isoformat_to_datetime(iso):
 
44
    "Parse an ISO 8601 date string to a datetime.datetime()"
 
45
    if not iso:
 
46
        return None
 
47
    d, t = iso.split(u"T", 1)
 
48
    year, month, day = d.split(u"-", 2)
 
49
    hour, minute, second = t.split(u":", 2)
 
50
    second, fraction = divmod(float(second), 1)
 
51
    return datetime.datetime(int(year),
 
52
                             int(month),
 
53
                             int(day),
 
54
                             int(hour),
 
55
                             int(minute),
 
56
                             int(second),           # Whole seconds
 
57
                             int(fraction*1000000)) # Microseconds
 
58
 
43
59
class MandosClientPropertyCache(object):
44
60
    """This wraps a Mandos Client D-Bus proxy object, caches the
45
61
    properties and calls a hook function when any of them are
57
73
        self.properties.update(
58
74
            self.proxy.GetAll(client_interface,
59
75
                              dbus_interface = dbus.PROPERTIES_IFACE))
60
 
        super(MandosClientPropertyCache, self).__init__(
61
 
            *args, **kwargs)
 
76
 
 
77
        #XXX This break good super behaviour!
 
78
#        super(MandosClientPropertyCache, self).__init__(
 
79
#            *args, **kwargs)
62
80
    
63
81
    def property_changed(self, property=None, value=None):
64
82
        """This is called whenever we get a PropertyChanged signal
83
101
        # Logger
84
102
        self.logger = logger
85
103
        
 
104
        self._update_timer_callback_tag = None
 
105
        self.last_checker_failed = False
 
106
        
86
107
        # The widget shown normally
87
108
        self._text_widget = urwid.Text(u"")
88
109
        # The widget shown when we have focus
112
133
                                     self.rejected,
113
134
                                     client_interface,
114
135
                                     byte_arrays=True)
 
136
        last_checked_ok = isoformat_to_datetime(self.properties
 
137
                                                [u"LastCheckedOK"])
 
138
        if last_checked_ok is None:
 
139
            self.last_checker_failed = True
 
140
        else:
 
141
            self.last_checker_failed = ((datetime.datetime.utcnow()
 
142
                                         - last_checked_ok)
 
143
                                        > datetime.timedelta
 
144
                                        (milliseconds=
 
145
                                         self.properties
 
146
                                         [u"Interval"]))
 
147
        if self.last_checker_failed:
 
148
            self._update_timer_callback_tag = (gobject.timeout_add
 
149
                                               (1000,
 
150
                                                self.update_timer))
115
151
    
116
152
    def checker_completed(self, exitstatus, condition, command):
117
153
        if exitstatus == 0:
 
154
            if self.last_checker_failed:
 
155
                self.last_checker_failed = False
 
156
                gobject.source_remove(self._update_timer_callback_tag)
 
157
                self._update_timer_callback_tag = None
118
158
            #self.logger(u'Checker for client %s (command "%s")'
119
159
            #            u' was successful'
120
 
            #            % (self.properties[u"name"], command))
 
160
            #            % (self.properties[u"Name"], command))
 
161
            self.update()
121
162
            return
 
163
        # Checker failed
 
164
        if not self.last_checker_failed:
 
165
            self.last_checker_failed = True
 
166
            self._update_timer_callback_tag = (gobject.timeout_add
 
167
                                               (1000,
 
168
                                                self.update_timer))
122
169
        if os.WIFEXITED(condition):
123
170
            self.logger(u'Checker for client %s (command "%s")'
124
171
                        u' failed with exit code %s'
125
 
                        % (self.properties[u"name"], command,
 
172
                        % (self.properties[u"Name"], command,
126
173
                           os.WEXITSTATUS(condition)))
127
 
            return
128
 
        if os.WIFSIGNALED(condition):
 
174
        elif os.WIFSIGNALED(condition):
129
175
            self.logger(u'Checker for client %s (command "%s")'
130
176
                        u' was killed by signal %s'
131
 
                        % (self.properties[u"name"], command,
 
177
                        % (self.properties[u"Name"], command,
132
178
                           os.WTERMSIG(condition)))
133
 
            return
134
 
        if os.WCOREDUMP(condition):
 
179
        elif os.WCOREDUMP(condition):
135
180
            self.logger(u'Checker for client %s (command "%s")'
136
181
                        u' dumped core'
137
 
                        % (self.properties[u"name"], command))
138
 
        self.logger(u'Checker for client %s completed mysteriously')
 
182
                        % (self.properties[u"Name"], command))
 
183
        else:
 
184
            self.logger(u'Checker for client %s completed'
 
185
                        u' mysteriously')
 
186
        self.update()
139
187
    
140
188
    def checker_started(self, command):
141
189
        #self.logger(u'Client %s started checker "%s"'
142
 
        #            % (self.properties[u"name"], unicode(command)))
 
190
        #            % (self.properties[u"Name"], unicode(command)))
143
191
        pass
144
192
    
145
193
    def got_secret(self):
 
194
        self.last_checker_failed = False
146
195
        self.logger(u'Client %s received its secret'
147
 
                    % self.properties[u"name"])
 
196
                    % self.properties[u"Name"])
148
197
    
149
198
    def need_approval(self, timeout, default):
150
199
        if not default:
152
201
        else:
153
202
            message = u'Client %s will get its secret in %s seconds'
154
203
        self.logger(message
155
 
                    % (self.properties[u"name"], timeout/1000))
 
204
                    % (self.properties[u"Name"], timeout/1000))
156
205
    
157
206
    def rejected(self, reason):
158
207
        self.logger(u'Client %s was rejected; reason: %s'
159
 
                    % (self.properties[u"name"], reason))
 
208
                    % (self.properties[u"Name"], reason))
160
209
    
161
210
    def selectable(self):
162
211
        """Make this a "selectable" widget.
184
233
                          u"bold-underline-blink":
185
234
                              u"bold-underline-blink-standout",
186
235
                          }
187
 
        
 
236
 
188
237
        # Rebuild focus and non-focus widgets using current properties
189
 
        self._text = (u'%(name)s: %(enabled)s'
190
 
                      % { u"name": self.properties[u"name"],
191
 
                          u"enabled":
192
 
                              (u"enabled"
193
 
                               if self.properties[u"enabled"]
194
 
                               else u"DISABLED")})
 
238
 
 
239
        # Base part of a client. Name!
 
240
        base = (u'%(name)s: '
 
241
                      % {u"name": self.properties[u"Name"]})
 
242
        if not self.properties[u"Enabled"]:
 
243
            message = u"DISABLED"
 
244
        elif self.properties[u"ApprovalPending"]:
 
245
            if self.properties[u"ApprovedByDefault"]:
 
246
                message = u"Connection established to client. (d)eny?"
 
247
            else:
 
248
                message = u"Seeks approval to send secret. (a)pprove?"
 
249
        elif self.last_checker_failed:
 
250
            timeout = datetime.timedelta(milliseconds
 
251
                                         = self.properties
 
252
                                         [u"Timeout"])
 
253
            last_ok = isoformat_to_datetime(
 
254
                max((self.properties[u"LastCheckedOK"]
 
255
                     or self.properties[u"Created"]),
 
256
                    self.properties[u"LastEnabled"]))
 
257
            timer = timeout - (datetime.datetime.utcnow() - last_ok)
 
258
            message = (u'A checker has failed! Time until client'
 
259
                       u' gets disabled: %s'
 
260
                           % unicode(timer).rsplit(".", 1)[0])
 
261
        else:
 
262
            message = u"enabled"
 
263
        self._text = "%s%s" % (base, message)
 
264
            
195
265
        if not urwid.supports_unicode():
196
266
            self._text = self._text.encode("ascii", "replace")
197
267
        textlist = [(u"normal", self._text)]
208
278
        if self.update_hook is not None:
209
279
            self.update_hook()
210
280
    
 
281
    def update_timer(self):
 
282
        "called by gobject"
 
283
        self.update()
 
284
        return True             # Keep calling this
 
285
    
211
286
    def delete(self):
 
287
        if self._update_timer_callback_tag is not None:
 
288
            gobject.source_remove(self._update_timer_callback_tag)
 
289
            self._update_timer_callback_tag = None
212
290
        if self.delete_hook is not None:
213
291
            self.delete_hook(self)
214
292
    
221
299
    def keypress(self, (maxcol,), key):
222
300
        """Handle keys.
223
301
        This overrides the method from urwid.FlowWidget"""
224
 
        if key == u"e" or key == u"+":
225
 
            self.proxy.Enable()
226
 
        elif key == u"d" or key == u"-":
227
 
            self.proxy.Disable()
 
302
        if key == u"+":
 
303
            self.proxy.Enable(dbus_interface = client_interface)
 
304
        elif key == u"-":
 
305
            self.proxy.Disable(dbus_interface = client_interface)
 
306
        elif key == u"a":
 
307
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
 
308
                               dbus_interface = client_interface)
 
309
        elif key == u"d":
 
310
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
 
311
                                  dbus_interface = client_interface)
228
312
        elif key == u"r" or key == u"_" or key == u"ctrl k":
229
313
            self.server_proxy_object.RemoveClient(self.proxy
230
314
                                                  .object_path)
231
315
        elif key == u"s":
232
 
            self.proxy.StartChecker()
 
316
            self.proxy.StartChecker(dbus_interface = client_interface)
233
317
        elif key == u"S":
234
 
            self.proxy.StopChecker()
 
318
            self.proxy.StopChecker(dbus_interface = client_interface)
235
319
        elif key == u"C":
236
 
            self.proxy.CheckedOK()
 
320
            self.proxy.CheckedOK(dbus_interface = client_interface)
237
321
        # xxx
238
322
#         elif key == u"p" or key == "=":
239
323
#             self.proxy.pause()
241
325
#             self.proxy.unpause()
242
326
#         elif key == u"RET":
243
327
#             self.open()
244
 
        elif key == u"+":
245
 
            self.proxy.Approve(True)
246
 
        elif key == u"-":
247
 
            self.proxy.Approve(False)
248
328
        else:
249
329
            return key
250
330
    
266
346
    use them as an excuse to shift focus away from this widget.
267
347
    """
268
348
    def keypress(self, (maxcol, maxrow), key):
269
 
        ret = super(ConstrainedListBox, self).keypress((maxcol, maxrow), key)
 
349
        ret = super(ConstrainedListBox, self).keypress((maxcol,
 
350
                                                        maxrow), key)
270
351
        if ret in (u"up", u"down"):
271
352
            return
272
353
        return ret
389
470
        Call this when the widget layout needs to change"""
390
471
        self.uilist = []
391
472
        #self.uilist.append(urwid.ListBox(self.clients))
392
 
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.clients),
 
473
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.
 
474
                                                          clients),
393
475
                                       #header=urwid.Divider(),
394
476
                                       header=None,
395
 
                                       footer=urwid.Divider(div_char=self.divider)))
 
477
                                       footer=
 
478
                                       urwid.Divider(div_char=
 
479
                                                     self.divider)))
396
480
        if self.log_visible:
397
481
            self.uilist.append(self.logbox)
398
482
            pass
416
500
        """Toggle visibility of the log buffer."""
417
501
        self.log_visible = not self.log_visible
418
502
        self.rebuild()
419
 
        self.log_message(u"Log visibility changed to: "
420
 
                         + unicode(self.log_visible))
 
503
        #self.log_message(u"Log visibility changed to: "
 
504
        #                 + unicode(self.log_visible))
421
505
    
422
506
    def change_log_display(self):
423
507
        """Change type of log display.
428
512
            self.log_wrap = u"clip"
429
513
        for textwidget in self.log:
430
514
            textwidget.set_wrap_mode(self.log_wrap)
431
 
        self.log_message(u"Wrap mode: " + self.log_wrap)
 
515
        #self.log_message(u"Wrap mode: " + self.log_wrap)
432
516
    
433
517
    def find_and_remove_client(self, path, name):
434
518
        """Find an client from its object path and remove it.
461
545
        if path is None:
462
546
            path = client.proxy.object_path
463
547
        self.clients_dict[path] = client
464
 
        self.clients.sort(None, lambda c: c.properties[u"name"])
 
548
        self.clients.sort(None, lambda c: c.properties[u"Name"])
465
549
        self.refresh()
466
550
    
467
551
    def remove_client(self, client, path=None):
542
626
                self.log_message_raw((u"bold",
543
627
                                      u"  "
544
628
                                      .join((u"Clients:",
545
 
                                             u"e: Enable",
546
 
                                             u"d: Disable",
 
629
                                             u"+: Enable",
 
630
                                             u"-: Disable",
547
631
                                             u"r: Remove",
548
632
                                             u"s: Start new checker",
549
633
                                             u"S: Stop checker",
550
 
                                             u"C: Checker OK"))))
 
634
                                             u"C: Checker OK",
 
635
                                             u"a: Approve",
 
636
                                             u"d: Deny"))))
551
637
                self.refresh()
552
638
            elif key == u"tab":
553
639
                if self.topwidget.get_focus() is self.logbox:
581
667
ui = UserInterface()
582
668
try:
583
669
    ui.run()
 
670
except KeyboardInterrupt:
 
671
    ui.screen.stop()
584
672
except Exception, e:
585
673
    ui.log_message(unicode(e))
586
674
    ui.screen.stop()