/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: 2014-08-06 21:45:09 UTC
  • mfrom: (237.4.53 release)
  • Revision ID: teddy@recompile.se-20140806214509-d6sprf3gnmahcfax
Merge from release branch.

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-2013 Teddy Hogeborn
7
 
# Copyright © 2009-2013 Björn Påhlsson
 
6
# Copyright © 2009-2014 Teddy Hogeborn
 
7
# Copyright © 2009-2014 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
36
35
 
37
36
import datetime
38
37
 
49
48
 
50
49
import locale
51
50
 
52
 
if sys.version_info[0] == 2:
 
51
if sys.version_info.major == 2:
53
52
    str = unicode
54
53
 
55
54
locale.setlocale(locale.LC_ALL, '')
61
60
domain = 'se.recompile'
62
61
server_interface = domain + '.Mandos'
63
62
client_interface = domain + '.Mandos.Client'
64
 
version = "1.6.1"
 
63
version = "1.6.8"
65
64
 
66
65
def isoformat_to_datetime(iso):
67
66
    "Parse an ISO 8601 date string to a datetime.datetime()"
162
161
                                         self.rejected,
163
162
                                         client_interface,
164
163
                                         byte_arrays=True))
165
 
        #self.logger('Created client {0}'
166
 
        #            .format(self.properties["Name"]))
 
164
        self.logger('Created client {}'
 
165
                    .format(self.properties["Name"]), level=0)
167
166
    
168
167
    def using_timer(self, flag):
169
168
        """Call this method with True or False when timer should be
180
179
    
181
180
    def checker_completed(self, exitstatus, condition, command):
182
181
        if exitstatus == 0:
 
182
            self.logger('Checker for client {} (command "{}")'
 
183
                        ' succeeded'.format(self.properties["Name"],
 
184
                                            command), level=0)
183
185
            self.update()
184
186
            return
185
187
        # Checker failed
186
188
        if os.WIFEXITED(condition):
187
 
            self.logger('Checker for client {0} (command "{1}")'
188
 
                        ' failed with exit code {2}'
 
189
            self.logger('Checker for client {} (command "{}") failed'
 
190
                        ' with exit code {}'
189
191
                        .format(self.properties["Name"], command,
190
192
                                os.WEXITSTATUS(condition)))
191
193
        elif os.WIFSIGNALED(condition):
192
 
            self.logger('Checker for client {0} (command "{1}") was'
193
 
                        ' killed by signal {2}'
 
194
            self.logger('Checker for client {} (command "{}") was'
 
195
                        ' killed by signal {}'
194
196
                        .format(self.properties["Name"], command,
195
197
                                os.WTERMSIG(condition)))
196
198
        elif os.WCOREDUMP(condition):
197
 
            self.logger('Checker for client {0} (command "{1}")'
198
 
                        ' dumped core'
199
 
                        .format(self.properties["Name"], command))
 
199
            self.logger('Checker for client {} (command "{}") dumped'
 
200
                        ' core'.format(self.properties["Name"],
 
201
                                       command))
200
202
        else:
201
 
            self.logger('Checker for client {0} completed'
 
203
            self.logger('Checker for client {} completed'
202
204
                        ' mysteriously'
203
205
                        .format(self.properties["Name"]))
204
206
        self.update()
205
207
    
206
208
    def checker_started(self, command):
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
 
209
        """Server signals that a checker started."""
 
210
        self.logger('Client {} started checker "{}"'
 
211
                    .format(self.properties["Name"],
 
212
                            command), level=0)
213
213
    
214
214
    def got_secret(self):
215
 
        self.logger('Client {0} received its secret'
 
215
        self.logger('Client {} 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 {0} needs approval within {1} seconds'
 
220
            message = 'Client {} needs approval within {} seconds'
221
221
        else:
222
 
            message = 'Client {0} will get its secret in {1} seconds'
 
222
            message = 'Client {} will get its secret in {} 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 {0} was rejected; reason: {1}'
 
227
        self.logger('Client {} was rejected; reason: {}'
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 {0}. (d)eny?"
 
277
                message = "Approval in {}. (d)eny?"
278
278
            else:
279
 
                message = "Denial in {0}. (a)pprove?"
 
279
                message = "Denial in {}. (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: {0}'
 
293
                       ' gets disabled: {}'
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 = "{0}{1}".format(base, message)
 
299
        self._text = "{}{}".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):
 
407
    def __init__(self, max_log_length=1000, log_level=1):
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
        
451
453
        # We keep a reference to the log widget so we can remove it
452
454
        # from the ListWalker without it getting destroyed
453
455
        self.logbox = ConstrainedListBox(self.log)
467
469
        self.main_loop = gobject.MainLoop()
468
470
    
469
471
    def client_not_found(self, fingerprint, address):
470
 
        self.log_message("Client with address {0} and fingerprint"
471
 
                         " {1} could not be found"
 
472
        self.log_message("Client with address {} and fingerprint {}"
 
473
                         " could not be found"
472
474
                         .format(address, fingerprint))
473
475
    
474
476
    def rebuild(self):
487
489
            self.uilist.append(self.logbox)
488
490
        self.topwidget = urwid.Pile(self.uilist)
489
491
    
490
 
    def log_message(self, message):
 
492
    def log_message(self, message, level=1):
491
493
        """Log message formatted with timestamp"""
 
494
        if level < self.log_level:
 
495
            return
492
496
        timestamp = datetime.datetime.now().isoformat()
493
 
        self.log_message_raw(timestamp + ": " + message)
 
497
        self.log_message_raw("{}: {}".format(timestamp, message),
 
498
                             level=level)
494
499
    
495
 
    def log_message_raw(self, markup):
 
500
    def log_message_raw(self, markup, level=1):
496
501
        """Add a log message to the log buffer."""
 
502
        if level < self.log_level:
 
503
            return
497
504
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
498
505
        if (self.max_log_length
499
506
            and len(self.log) > self.max_log_length):
506
513
        """Toggle visibility of the log buffer."""
507
514
        self.log_visible = not self.log_visible
508
515
        self.rebuild()
509
 
        #self.log_message("Log visibility changed to: "
510
 
        #                 + str(self.log_visible))
 
516
        self.log_message("Log visibility changed to: {}"
 
517
                         .format(self.log_visible), level=0)
511
518
    
512
519
    def change_log_display(self):
513
520
        """Change type of log display.
518
525
            self.log_wrap = "clip"
519
526
        for textwidget in self.log:
520
527
            textwidget.set_wrap_mode(self.log_wrap)
521
 
        #self.log_message("Wrap mode: " + self.log_wrap)
 
528
        self.log_message("Wrap mode: {}".format(self.log_wrap),
 
529
                         level=0)
522
530
    
523
531
    def find_and_remove_client(self, path, name):
524
532
        """Find a client by its object path and remove it.
529
537
            client = self.clients_dict[path]
530
538
        except KeyError:
531
539
            # not found?
532
 
            self.log_message("Unknown client {0!r} ({1!r}) removed"
 
540
            self.log_message("Unknown client {!r} ({!r}) removed"
533
541
                             .format(name, path))
534
542
            return
535
543
        client.delete()
653
661
            elif key == "window resize":
654
662
                self.size = self.screen.get_cols_rows()
655
663
                self.refresh()
656
 
            elif key == "\f":  # Ctrl-L
 
664
            elif key == "ctrl l":
 
665
                self.screen.clear()
657
666
                self.refresh()
658
667
            elif key == "l" or key == "D":
659
668
                self.toggle_log_display()
671
680
                                            "?: Help",
672
681
                                            "l: Log window toggle",
673
682
                                            "TAB: Switch window",
674
 
                                            "w: Wrap (log)"))))
 
683
                                            "w: Wrap (log lines)",
 
684
                                            "v: Toggle verbose log",
 
685
                                            ))))
675
686
                self.log_message_raw(("bold",
676
687
                                      "  "
677
688
                                      .join(("Clients:",
690
701
                else:
691
702
                    self.topwidget.set_focus(self.logbox)
692
703
                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")
693
711
            #elif (key == "end" or key == "meta >" or key == "G"
694
712
            #      or key == ">"):
695
713
            #    pass            # xxx end-of-buffer