/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

merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
 
24
24
locale.setlocale(locale.LC_ALL, u'')
25
25
 
 
26
import logging
 
27
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
 
28
 
26
29
# Some useful constants
27
30
domain = 'se.bsnet.fukt'
28
31
server_interface = domain + '.Mandos'
29
32
client_interface = domain + '.Mandos.Client'
30
 
version = "1.0.14"
 
33
version = "1.0.15"
31
34
 
32
35
# Always run in monochrome mode
33
36
urwid.curses_display.curses.has_colors = lambda : False
70
73
        self.properties.update(
71
74
            self.proxy.GetAll(client_interface,
72
75
                              dbus_interface = dbus.PROPERTIES_IFACE))
73
 
        super(MandosClientPropertyCache, self).__init__(
74
 
            proxy_object=proxy_object, *args, **kwargs)
 
76
 
 
77
        #XXX This break good super behaviour!
 
78
#        super(MandosClientPropertyCache, self).__init__(
 
79
#            *args, **kwargs)
75
80
    
76
81
    def property_changed(self, property=None, value=None):
77
82
        """This is called whenever we get a PropertyChanged signal
120
125
                                     self.got_secret,
121
126
                                     client_interface,
122
127
                                     byte_arrays=True)
 
128
        self.proxy.connect_to_signal(u"NeedApproval",
 
129
                                     self.need_approval,
 
130
                                     client_interface,
 
131
                                     byte_arrays=True)
123
132
        self.proxy.connect_to_signal(u"Rejected",
124
133
                                     self.rejected,
125
134
                                     client_interface,
126
135
                                     byte_arrays=True)
127
136
        last_checked_ok = isoformat_to_datetime(self.properties
128
 
                                                ["last_checked_ok"])
 
137
                                                [u"LastCheckedOK"])
129
138
        if last_checked_ok is None:
130
139
            self.last_checker_failed = True
131
140
        else:
133
142
                                         - last_checked_ok)
134
143
                                        > datetime.timedelta
135
144
                                        (milliseconds=
136
 
                                         self.properties["interval"]))
 
145
                                         self.properties
 
146
                                         [u"Interval"]))
137
147
        if self.last_checker_failed:
138
148
            self._update_timer_callback_tag = (gobject.timeout_add
139
149
                                               (1000,
145
155
                self.last_checker_failed = False
146
156
                gobject.source_remove(self._update_timer_callback_tag)
147
157
                self._update_timer_callback_tag = None
148
 
            self.logger(u'Checker for client %s (command "%s")'
149
 
                        u' was successful'
150
 
                        % (self.properties[u"name"], command))
 
158
            #self.logger(u'Checker for client %s (command "%s")'
 
159
            #            u' was successful'
 
160
            #            % (self.properties[u"Name"], command))
151
161
            self.update()
152
162
            return
153
163
        # Checker failed
159
169
        if os.WIFEXITED(condition):
160
170
            self.logger(u'Checker for client %s (command "%s")'
161
171
                        u' failed with exit code %s'
162
 
                        % (self.properties[u"name"], command,
 
172
                        % (self.properties[u"Name"], command,
163
173
                           os.WEXITSTATUS(condition)))
164
174
        elif os.WIFSIGNALED(condition):
165
175
            self.logger(u'Checker for client %s (command "%s")'
166
176
                        u' was killed by signal %s'
167
 
                        % (self.properties[u"name"], command,
 
177
                        % (self.properties[u"Name"], command,
168
178
                           os.WTERMSIG(condition)))
169
179
        elif os.WCOREDUMP(condition):
170
180
            self.logger(u'Checker for client %s (command "%s")'
171
181
                        u' dumped core'
172
 
                        % (self.properties[u"name"], command))
 
182
                        % (self.properties[u"Name"], command))
173
183
        else:
174
 
            self.logger(u'Checker for client %s completed mysteriously')
 
184
            self.logger(u'Checker for client %s completed'
 
185
                        u' mysteriously')
175
186
        self.update()
176
187
    
177
188
    def checker_started(self, command):
178
 
        self.logger(u'Client %s started checker "%s"'
179
 
                    % (self.properties[u"name"], unicode(command)))
 
189
        #self.logger(u'Client %s started checker "%s"'
 
190
        #            % (self.properties[u"Name"], unicode(command)))
 
191
        pass
180
192
    
181
193
    def got_secret(self):
 
194
        self.last_checker_failed = False
182
195
        self.logger(u'Client %s received its secret'
183
 
                    % self.properties[u"name"])
184
 
    
185
 
    def rejected(self):
186
 
        self.logger(u'Client %s was rejected'
187
 
                    % self.properties[u"name"])
 
196
                    % self.properties[u"Name"])
 
197
    
 
198
    def need_approval(self, timeout, default):
 
199
        if not default:
 
200
            message = u'Client %s needs approval within %s seconds'
 
201
        else:
 
202
            message = u'Client %s will get its secret in %s seconds'
 
203
        self.logger(message
 
204
                    % (self.properties[u"Name"], timeout/1000))
 
205
    
 
206
    def rejected(self, reason):
 
207
        self.logger(u'Client %s was rejected; reason: %s'
 
208
                    % (self.properties[u"Name"], reason))
188
209
    
189
210
    def selectable(self):
190
211
        """Make this a "selectable" widget.
212
233
                          u"bold-underline-blink":
213
234
                              u"bold-underline-blink-standout",
214
235
                          }
215
 
        
 
236
 
216
237
        # Rebuild focus and non-focus widgets using current properties
217
 
        self._text = (u'%(name)s: %(enabled)s%(timer)s'
218
 
                      % { u"name": self.properties[u"name"],
219
 
                          u"enabled":
220
 
                              (u"enabled"
221
 
                               if self.properties[u"enabled"]
222
 
                               else u"DISABLED"),
223
 
                          u"timer": (unicode(datetime.timedelta
224
 
                                             (milliseconds =
225
 
                                              self.properties
226
 
                                              [u"timeout"])
227
 
                                             - (datetime.datetime
228
 
                                                .utcnow()
229
 
                                                - isoformat_to_datetime
230
 
                                                (max((self.properties
231
 
                                                 ["last_checked_ok"]
232
 
                                                 or
233
 
                                                 self.properties
234
 
                                                 ["created"]),
235
 
                                                    self.properties[u"last_enabled"]))))
236
 
                                     if (self.last_checker_failed
237
 
                                         and self.properties
238
 
                                         [u"enabled"])
239
 
                                     else u"")})
 
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 diabled: %s'
 
260
                           % unicode(timer).rsplit(".", 1)[0])
 
261
        else:
 
262
            message = u"enabled"
 
263
        self._text = "%s%s" % (base, message)
 
264
            
240
265
        if not urwid.supports_unicode():
241
266
            self._text = self._text.encode("ascii", "replace")
242
267
        textlist = [(u"normal", self._text)]
274
299
    def keypress(self, (maxcol,), key):
275
300
        """Handle keys.
276
301
        This overrides the method from urwid.FlowWidget"""
277
 
        if key == u"e" or key == u"+":
278
 
            self.proxy.Enable()
279
 
        elif key == u"d" or key == u"-":
280
 
            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)
281
312
        elif key == u"r" or key == u"_" or key == u"ctrl k":
282
313
            self.server_proxy_object.RemoveClient(self.proxy
283
314
                                                  .object_path)
284
315
        elif key == u"s":
285
 
            self.proxy.StartChecker()
 
316
            self.proxy.StartChecker(dbus_interface = client_interface)
286
317
        elif key == u"S":
287
 
            self.proxy.StopChecker()
 
318
            self.proxy.StopChecker(dbus_interface = client_interface)
288
319
        elif key == u"C":
289
 
            self.proxy.CheckedOK()
 
320
            self.proxy.CheckedOK(dbus_interface = client_interface)
290
321
        # xxx
291
322
#         elif key == u"p" or key == "=":
292
323
#             self.proxy.pause()
315
346
    use them as an excuse to shift focus away from this widget.
316
347
    """
317
348
    def keypress(self, (maxcol, maxrow), key):
318
 
        ret = super(ConstrainedListBox, self).keypress((maxcol, maxrow), key)
 
349
        ret = super(ConstrainedListBox, self).keypress((maxcol,
 
350
                                                        maxrow), key)
319
351
        if ret in (u"up", u"down"):
320
352
            return
321
353
        return ret
438
470
        Call this when the widget layout needs to change"""
439
471
        self.uilist = []
440
472
        #self.uilist.append(urwid.ListBox(self.clients))
441
 
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.clients),
 
473
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.
 
474
                                                          clients),
442
475
                                       #header=urwid.Divider(),
443
476
                                       header=None,
444
 
                                       footer=urwid.Divider(div_char=self.divider)))
 
477
                                       footer=
 
478
                                       urwid.Divider(div_char=
 
479
                                                     self.divider)))
445
480
        if self.log_visible:
446
481
            self.uilist.append(self.logbox)
447
482
            pass
465
500
        """Toggle visibility of the log buffer."""
466
501
        self.log_visible = not self.log_visible
467
502
        self.rebuild()
468
 
        self.log_message(u"Log visibility changed to: "
469
 
                         + unicode(self.log_visible))
 
503
        #self.log_message(u"Log visibility changed to: "
 
504
        #                 + unicode(self.log_visible))
470
505
    
471
506
    def change_log_display(self):
472
507
        """Change type of log display.
477
512
            self.log_wrap = u"clip"
478
513
        for textwidget in self.log:
479
514
            textwidget.set_wrap_mode(self.log_wrap)
480
 
        self.log_message(u"Wrap mode: " + self.log_wrap)
 
515
        #self.log_message(u"Wrap mode: " + self.log_wrap)
481
516
    
482
517
    def find_and_remove_client(self, path, name):
483
518
        """Find an client from its object path and remove it.
510
545
        if path is None:
511
546
            path = client.proxy.object_path
512
547
        self.clients_dict[path] = client
513
 
        self.clients.sort(None, lambda c: c.properties[u"name"])
 
548
        self.clients.sort(None, lambda c: c.properties[u"Name"])
514
549
        self.refresh()
515
550
    
516
551
    def remove_client(self, client, path=None):
591
626
                self.log_message_raw((u"bold",
592
627
                                      u"  "
593
628
                                      .join((u"Clients:",
594
 
                                             u"e: Enable",
595
 
                                             u"d: Disable",
 
629
                                             u"+: Enable",
 
630
                                             u"-: Disable",
596
631
                                             u"r: Remove",
597
632
                                             u"s: Start new checker",
598
633
                                             u"S: Stop checker",
599
 
                                             u"C: Checker OK"))))
 
634
                                             u"C: Checker OK",
 
635
                                             u"a: Approve",
 
636
                                             u"d: Deny"))))
600
637
                self.refresh()
601
638
            elif key == u"tab":
602
639
                if self.topwidget.get_focus() is self.logbox:
630
667
ui = UserInterface()
631
668
try:
632
669
    ui.run()
 
670
except KeyboardInterrupt:
 
671
    ui.screen.stop()
633
672
except Exception, e:
634
673
    ui.log_message(unicode(e))
635
674
    ui.screen.stop()