/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: 2013-06-23 15:30:34 UTC
  • Revision ID: teddy@recompile.se-20130623153034-u8oty17y51oc0xnl
TODO change only

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
6
 
# Copyright © 2009-2014 Teddy Hogeborn
7
 
# Copyright © 2009-2014 Björn Påhlsson
 
6
# Copyright © 2009-2012 Teddy Hogeborn
 
7
# Copyright © 2009-2012 Björn Påhlsson
8
8
9
9
# This program is free software: you can redistribute it and/or modify
10
10
# it under the terms of the GNU General Public License as published by
32
32
 
33
33
import sys
34
34
import os
 
35
import signal
35
36
 
36
37
import datetime
37
38
 
48
49
 
49
50
import locale
50
51
 
51
 
if sys.version_info.major == 2:
 
52
if sys.version_info[0] == 2:
52
53
    str = unicode
53
54
 
54
55
locale.setlocale(locale.LC_ALL, '')
60
61
domain = 'se.recompile'
61
62
server_interface = domain + '.Mandos'
62
63
client_interface = domain + '.Mandos.Client'
63
 
version = "1.6.8"
 
64
version = "1.6.0"
64
65
 
65
66
def isoformat_to_datetime(iso):
66
67
    "Parse an ISO 8601 date string to a datetime.datetime()"
161
162
                                         self.rejected,
162
163
                                         client_interface,
163
164
                                         byte_arrays=True))
164
 
        self.logger('Created client {}'
165
 
                    .format(self.properties["Name"]), level=0)
 
165
        #self.logger('Created client {0}'
 
166
        #            .format(self.properties["Name"]))
166
167
    
167
168
    def using_timer(self, flag):
168
169
        """Call this method with True or False when timer should be
179
180
    
180
181
    def checker_completed(self, exitstatus, condition, command):
181
182
        if exitstatus == 0:
182
 
            self.logger('Checker for client {} (command "{}")'
183
 
                        ' succeeded'.format(self.properties["Name"],
184
 
                                            command), level=0)
185
183
            self.update()
186
184
            return
187
185
        # Checker failed
188
186
        if os.WIFEXITED(condition):
189
 
            self.logger('Checker for client {} (command "{}") failed'
190
 
                        ' with exit code {}'
 
187
            self.logger('Checker for client {0} (command "{1}")'
 
188
                        ' failed with exit code {2}'
191
189
                        .format(self.properties["Name"], command,
192
190
                                os.WEXITSTATUS(condition)))
193
191
        elif os.WIFSIGNALED(condition):
194
 
            self.logger('Checker for client {} (command "{}") was'
195
 
                        ' killed by signal {}'
 
192
            self.logger('Checker for client {0} (command "{1}") was'
 
193
                        ' killed by signal {2}'
196
194
                        .format(self.properties["Name"], command,
197
195
                                os.WTERMSIG(condition)))
198
196
        elif os.WCOREDUMP(condition):
199
 
            self.logger('Checker for client {} (command "{}") dumped'
200
 
                        ' core'.format(self.properties["Name"],
201
 
                                       command))
 
197
            self.logger('Checker for client {0} (command "{1}")'
 
198
                        ' dumped core'
 
199
                        .format(self.properties["Name"], command))
202
200
        else:
203
 
            self.logger('Checker for client {} completed'
 
201
            self.logger('Checker for client {0} completed'
204
202
                        ' mysteriously'
205
203
                        .format(self.properties["Name"]))
206
204
        self.update()
207
205
    
208
206
    def checker_started(self, command):
209
 
        """Server signals that a checker started."""
210
 
        self.logger('Client {} started checker "{}"'
211
 
                    .format(self.properties["Name"],
212
 
                            command), level=0)
 
207
        """Server signals that a checker started. This could be useful
 
208
           to log in the future. """
 
209
        #self.logger('Client {0} started checker "{1}"'
 
210
        #            .format(self.properties["Name"],
 
211
        #                    str(command)))
 
212
        pass
213
213
    
214
214
    def got_secret(self):
215
 
        self.logger('Client {} received its secret'
 
215
        self.logger('Client {0} received its secret'
216
216
                    .format(self.properties["Name"]))
217
217
    
218
218
    def need_approval(self, timeout, default):
219
219
        if not default:
220
 
            message = 'Client {} needs approval within {} seconds'
 
220
            message = 'Client {0} needs approval within {1} seconds'
221
221
        else:
222
 
            message = 'Client {} will get its secret in {} seconds'
 
222
            message = 'Client {0} will get its secret in {1} seconds'
223
223
        self.logger(message.format(self.properties["Name"],
224
224
                                   timeout/1000))
225
225
    
226
226
    def rejected(self, reason):
227
 
        self.logger('Client {} was rejected; reason: {}'
 
227
        self.logger('Client {0} was rejected; reason: {1}'
228
228
                    .format(self.properties["Name"], reason))
229
229
    
230
230
    def selectable(self):
274
274
            else:
275
275
                timer = datetime.timedelta()
276
276
            if self.properties["ApprovedByDefault"]:
277
 
                message = "Approval in {}. (d)eny?"
 
277
                message = "Approval in {0}. (d)eny?"
278
278
            else:
279
 
                message = "Denial in {}. (a)pprove?"
 
279
                message = "Denial in {0}. (a)pprove?"
280
280
            message = message.format(str(timer).rsplit(".", 1)[0])
281
281
            self.using_timer(True)
282
282
        elif self.properties["LastCheckerStatus"] != 0:
290
290
                timer = max(expires - datetime.datetime.utcnow(),
291
291
                            datetime.timedelta())
292
292
            message = ('A checker has failed! Time until client'
293
 
                       ' gets disabled: {}'
 
293
                       ' gets disabled: {0}'
294
294
                       .format(str(timer).rsplit(".", 1)[0]))
295
295
            self.using_timer(True)
296
296
        else:
297
297
            message = "enabled"
298
298
            self.using_timer(False)
299
 
        self._text = "{}{}".format(base, message)
 
299
        self._text = "{0}{1}".format(base, message)
300
300
        
301
301
        if not urwid.supports_unicode():
302
302
            self._text = self._text.encode("ascii", "replace")
404
404
    """This is the entire user interface - the whole screen
405
405
    with boxes, lists of client widgets, etc.
406
406
    """
407
 
    def __init__(self, max_log_length=1000, log_level=1):
 
407
    def __init__(self, max_log_length=1000):
408
408
        DBusGMainLoop(set_as_default=True)
409
409
        
410
410
        self.screen = urwid.curses_display.Screen()
448
448
        self.log = []
449
449
        self.max_log_length = max_log_length
450
450
        
451
 
        self.log_level = log_level
452
 
        
453
451
        # We keep a reference to the log widget so we can remove it
454
452
        # from the ListWalker without it getting destroyed
455
453
        self.logbox = ConstrainedListBox(self.log)
469
467
        self.main_loop = gobject.MainLoop()
470
468
    
471
469
    def client_not_found(self, fingerprint, address):
472
 
        self.log_message("Client with address {} and fingerprint {}"
473
 
                         " could not be found"
 
470
        self.log_message("Client with address {0} and fingerprint"
 
471
                         " {1} could not be found"
474
472
                         .format(address, fingerprint))
475
473
    
476
474
    def rebuild(self):
489
487
            self.uilist.append(self.logbox)
490
488
        self.topwidget = urwid.Pile(self.uilist)
491
489
    
492
 
    def log_message(self, message, level=1):
 
490
    def log_message(self, message):
493
491
        """Log message formatted with timestamp"""
494
 
        if level < self.log_level:
495
 
            return
496
492
        timestamp = datetime.datetime.now().isoformat()
497
 
        self.log_message_raw("{}: {}".format(timestamp, message),
498
 
                             level=level)
 
493
        self.log_message_raw(timestamp + ": " + message)
499
494
    
500
 
    def log_message_raw(self, markup, level=1):
 
495
    def log_message_raw(self, markup):
501
496
        """Add a log message to the log buffer."""
502
 
        if level < self.log_level:
503
 
            return
504
497
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
505
498
        if (self.max_log_length
506
499
            and len(self.log) > self.max_log_length):
513
506
        """Toggle visibility of the log buffer."""
514
507
        self.log_visible = not self.log_visible
515
508
        self.rebuild()
516
 
        self.log_message("Log visibility changed to: {}"
517
 
                         .format(self.log_visible), level=0)
 
509
        #self.log_message("Log visibility changed to: "
 
510
        #                 + str(self.log_visible))
518
511
    
519
512
    def change_log_display(self):
520
513
        """Change type of log display.
525
518
            self.log_wrap = "clip"
526
519
        for textwidget in self.log:
527
520
            textwidget.set_wrap_mode(self.log_wrap)
528
 
        self.log_message("Wrap mode: {}".format(self.log_wrap),
529
 
                         level=0)
 
521
        #self.log_message("Wrap mode: " + self.log_wrap)
530
522
    
531
523
    def find_and_remove_client(self, path, name):
532
524
        """Find a client by its object path and remove it.
537
529
            client = self.clients_dict[path]
538
530
        except KeyError:
539
531
            # not found?
540
 
            self.log_message("Unknown client {!r} ({!r}) removed"
 
532
            self.log_message("Unknown client {0!r} ({1!r}) removed"
541
533
                             .format(name, path))
542
534
            return
543
535
        client.delete()
661
653
            elif key == "window resize":
662
654
                self.size = self.screen.get_cols_rows()
663
655
                self.refresh()
664
 
            elif key == "ctrl l":
665
 
                self.screen.clear()
 
656
            elif key == "\f":  # Ctrl-L
666
657
                self.refresh()
667
658
            elif key == "l" or key == "D":
668
659
                self.toggle_log_display()
680
671
                                            "?: Help",
681
672
                                            "l: Log window toggle",
682
673
                                            "TAB: Switch window",
683
 
                                            "w: Wrap (log lines)",
684
 
                                            "v: Toggle verbose log",
685
 
                                            ))))
 
674
                                            "w: Wrap (log)"))))
686
675
                self.log_message_raw(("bold",
687
676
                                      "  "
688
677
                                      .join(("Clients:",
701
690
                else:
702
691
                    self.topwidget.set_focus(self.logbox)
703
692
                self.refresh()
704
 
            elif key == "v":
705
 
                if self.log_level == 0:
706
 
                    self.log_level = 1
707
 
                    self.log_message("Verbose mode: Off")
708
 
                else:
709
 
                    self.log_level = 0
710
 
                    self.log_message("Verbose mode: On")
711
693
            #elif (key == "end" or key == "meta >" or key == "G"
712
694
            #      or key == ">"):
713
695
            #    pass            # xxx end-of-buffer