/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 21:24:49 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100925212449-h9hpy9n406tkkakb
* mandos.xml (APPROVAL): New section.

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
85
101
        # Logger
86
102
        self.logger = logger
87
103
        
 
104
        self._update_timer_callback_tag = None
 
105
        self.last_checker_failed = False
 
106
        
88
107
        # The widget shown normally
89
108
        self._text_widget = urwid.Text(u"")
90
109
        # The widget shown when we have focus
114
133
                                     self.rejected,
115
134
                                     client_interface,
116
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))
117
151
    
118
152
    def checker_completed(self, exitstatus, condition, command):
119
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
120
158
            #self.logger(u'Checker for client %s (command "%s")'
121
159
            #            u' was successful'
122
 
            #            % (self.properties[u"name"], command))
 
160
            #            % (self.properties[u"Name"], command))
 
161
            self.update()
123
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))
124
169
        if os.WIFEXITED(condition):
125
170
            self.logger(u'Checker for client %s (command "%s")'
126
171
                        u' failed with exit code %s'
127
 
                        % (self.properties[u"name"], command,
 
172
                        % (self.properties[u"Name"], command,
128
173
                           os.WEXITSTATUS(condition)))
129
 
            return
130
 
        if os.WIFSIGNALED(condition):
 
174
        elif os.WIFSIGNALED(condition):
131
175
            self.logger(u'Checker for client %s (command "%s")'
132
176
                        u' was killed by signal %s'
133
 
                        % (self.properties[u"name"], command,
 
177
                        % (self.properties[u"Name"], command,
134
178
                           os.WTERMSIG(condition)))
135
 
            return
136
 
        if os.WCOREDUMP(condition):
 
179
        elif os.WCOREDUMP(condition):
137
180
            self.logger(u'Checker for client %s (command "%s")'
138
181
                        u' dumped core'
139
 
                        % (self.properties[u"name"], command))
140
 
        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()
141
187
    
142
188
    def checker_started(self, command):
143
189
        #self.logger(u'Client %s started checker "%s"'
144
 
        #            % (self.properties[u"name"], unicode(command)))
 
190
        #            % (self.properties[u"Name"], unicode(command)))
145
191
        pass
146
192
    
147
193
    def got_secret(self):
 
194
        self.last_checker_failed = False
148
195
        self.logger(u'Client %s received its secret'
149
 
                    % self.properties[u"name"])
 
196
                    % self.properties[u"Name"])
150
197
    
151
198
    def need_approval(self, timeout, default):
152
199
        if not default:
154
201
        else:
155
202
            message = u'Client %s will get its secret in %s seconds'
156
203
        self.logger(message
157
 
                    % (self.properties[u"name"], timeout/1000))
 
204
                    % (self.properties[u"Name"], timeout/1000))
158
205
    
159
206
    def rejected(self, reason):
160
207
        self.logger(u'Client %s was rejected; reason: %s'
161
 
                    % (self.properties[u"name"], reason))
 
208
                    % (self.properties[u"Name"], reason))
162
209
    
163
210
    def selectable(self):
164
211
        """Make this a "selectable" widget.
190
237
        # Rebuild focus and non-focus widgets using current properties
191
238
 
192
239
        # 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?"
 
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?"
199
247
            else:
200
 
                self._text += u"Seeks approval to send secret. (a)pprove?"
 
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])
201
261
        else:
202
 
            self._text += (u'%(enabled)s'
203
 
                           % {u"enabled":
204
 
                               (u"enabled"
205
 
                                if self.properties[u"enabled"]
206
 
                                else u"DISABLED")})
 
262
            message = u"enabled"
 
263
        self._text = "%s%s" % (base, message)
 
264
            
207
265
        if not urwid.supports_unicode():
208
266
            self._text = self._text.encode("ascii", "replace")
209
267
        textlist = [(u"normal", self._text)]
220
278
        if self.update_hook is not None:
221
279
            self.update_hook()
222
280
    
 
281
    def update_timer(self):
 
282
        "called by gobject"
 
283
        self.update()
 
284
        return True             # Keep calling this
 
285
    
223
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
224
290
        if self.delete_hook is not None:
225
291
            self.delete_hook(self)
226
292
    
259
325
#             self.proxy.unpause()
260
326
#         elif key == u"RET":
261
327
#             self.open()
262
 
#        elif key == u"+":
263
 
#            self.proxy.Approve(True)
264
 
#        elif key == u"-":
265
 
#            self.proxy.Approve(False)
266
328
        else:
267
329
            return key
268
330
    
284
346
    use them as an excuse to shift focus away from this widget.
285
347
    """
286
348
    def keypress(self, (maxcol, maxrow), key):
287
 
        ret = super(ConstrainedListBox, self).keypress((maxcol, maxrow), key)
 
349
        ret = super(ConstrainedListBox, self).keypress((maxcol,
 
350
                                                        maxrow), key)
288
351
        if ret in (u"up", u"down"):
289
352
            return
290
353
        return ret
407
470
        Call this when the widget layout needs to change"""
408
471
        self.uilist = []
409
472
        #self.uilist.append(urwid.ListBox(self.clients))
410
 
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.clients),
 
473
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.
 
474
                                                          clients),
411
475
                                       #header=urwid.Divider(),
412
476
                                       header=None,
413
 
                                       footer=urwid.Divider(div_char=self.divider)))
 
477
                                       footer=
 
478
                                       urwid.Divider(div_char=
 
479
                                                     self.divider)))
414
480
        if self.log_visible:
415
481
            self.uilist.append(self.logbox)
416
482
            pass
434
500
        """Toggle visibility of the log buffer."""
435
501
        self.log_visible = not self.log_visible
436
502
        self.rebuild()
437
 
        self.log_message(u"Log visibility changed to: "
438
 
                         + unicode(self.log_visible))
 
503
        #self.log_message(u"Log visibility changed to: "
 
504
        #                 + unicode(self.log_visible))
439
505
    
440
506
    def change_log_display(self):
441
507
        """Change type of log display.
446
512
            self.log_wrap = u"clip"
447
513
        for textwidget in self.log:
448
514
            textwidget.set_wrap_mode(self.log_wrap)
449
 
        self.log_message(u"Wrap mode: " + self.log_wrap)
 
515
        #self.log_message(u"Wrap mode: " + self.log_wrap)
450
516
    
451
517
    def find_and_remove_client(self, path, name):
452
518
        """Find an client from its object path and remove it.
479
545
        if path is None:
480
546
            path = client.proxy.object_path
481
547
        self.clients_dict[path] = client
482
 
        self.clients.sort(None, lambda c: c.properties[u"name"])
 
548
        self.clients.sort(None, lambda c: c.properties[u"Name"])
483
549
        self.refresh()
484
550
    
485
551
    def remove_client(self, client, path=None):
560
626
                self.log_message_raw((u"bold",
561
627
                                      u"  "
562
628
                                      .join((u"Clients:",
563
 
                                             u"e: Enable",
564
 
                                             u"d: Disable",
 
629
                                             u"+: Enable",
 
630
                                             u"-: Disable",
565
631
                                             u"r: Remove",
566
632
                                             u"s: Start new checker",
567
633
                                             u"S: Stop checker",
568
634
                                             u"C: Checker OK",
569
 
                                             u"A: Approve",
570
 
                                             u"D: Deny"))))
 
635
                                             u"a: Approve",
 
636
                                             u"d: Deny"))))
571
637
                self.refresh()
572
638
            elif key == u"tab":
573
639
                if self.topwidget.get_focus() is self.logbox:
601
667
ui = UserInterface()
602
668
try:
603
669
    ui.run()
 
670
except KeyboardInterrupt:
 
671
    ui.screen.stop()
604
672
except Exception, e:
605
673
    ui.log_message(unicode(e))
606
674
    ui.screen.stop()