/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

  • Committer: Teddy Hogeborn
  • Date: 2009-01-18 00:18:50 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090118001850-pvg8xjwmbyt23fom
* debian/rules (install-indep): Removed "--no-start" from
                                dh_installinit.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008 Teddy Hogeborn
15
 
# Copyright © 2008 Björn Påhlsson
 
14
# Copyright © 2008,2009 Teddy Hogeborn
 
15
# Copyright © 2008,2009 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
35
35
 
36
36
import SocketServer
37
37
import socket
38
 
from optparse import OptionParser
 
38
import optparse
39
39
import datetime
40
40
import errno
41
41
import gnutls.crypto
66
66
import ctypes
67
67
import ctypes.util
68
68
 
69
 
version = "1.0.2"
 
69
version = "1.0.5"
70
70
 
71
71
logger = logging.Logger('mandos')
72
72
syslogger = (logging.handlers.SysLogHandler
82
82
logger.addHandler(console)
83
83
 
84
84
class AvahiError(Exception):
85
 
    def __init__(self, value):
 
85
    def __init__(self, value, *args, **kwargs):
86
86
        self.value = value
87
 
        super(AvahiError, self).__init__()
88
 
    def __str__(self):
89
 
        return repr(self.value)
 
87
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
88
    def __unicode__(self):
 
89
        return unicode(repr(self.value))
90
90
 
91
91
class AvahiServiceError(AvahiError):
92
92
    pass
129
129
            logger.critical(u"No suitable Zeroconf service name found"
130
130
                            u" after %i retries, exiting.",
131
131
                            self.rename_count)
132
 
            raise AvahiServiceError("Too many renames")
 
132
            raise AvahiServiceError(u"Too many renames")
133
133
        self.name = server.GetAlternativeServiceName(self.name)
134
134
        logger.info(u"Changing Zeroconf service name to %r ...",
135
135
                    str(self.name))
170
170
# End of Avahi example code
171
171
 
172
172
 
173
 
def _datetime_to_dbus_struct(dt, variant_level=0):
174
 
    """Convert a UTC datetime.datetime() to a D-Bus struct.
175
 
    The format is special to this application, since we could not find
176
 
    any other standard way."""
177
 
    return dbus.Struct((dbus.Int16(dt.year),
178
 
                        dbus.Byte(dt.month),
179
 
                        dbus.Byte(dt.day),
180
 
                        dbus.Byte(dt.hour),
181
 
                        dbus.Byte(dt.minute),
182
 
                        dbus.Byte(dt.second),
183
 
                        dbus.UInt32(dt.microsecond)),
184
 
                       signature="nyyyyyu",
185
 
                       variant_level=variant_level)
 
173
def _datetime_to_dbus(dt, variant_level=0):
 
174
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
175
    return dbus.String(dt.isoformat(), variant_level=variant_level)
186
176
 
187
177
 
188
178
class Client(dbus.service.Object):
194
184
    secret:     bytestring; sent verbatim (over TLS) to client
195
185
    host:       string; available for use by the checker command
196
186
    created:    datetime.datetime(); (UTC) object creation
197
 
    last_started: datetime.datetime(); (UTC)
198
 
    started:    bool()
 
187
    last_enabled: datetime.datetime(); (UTC)
 
188
    enabled:    bool()
199
189
    last_checked_ok: datetime.datetime(); (UTC) or None
200
190
    timeout:    datetime.timedelta(); How long from last_checked_ok
201
191
                                      until this client is invalid
202
192
    interval:   datetime.timedelta(); How often to start a new checker
203
 
    stop_hook:  If set, called by stop() as stop_hook(self)
 
193
    disable_hook:  If set, called by disable() as disable_hook(self)
204
194
    checker:    subprocess.Popen(); a running checker process used
205
195
                                    to see if the client lives.
206
196
                                    'None' if no process is running.
207
197
    checker_initiator_tag: a gobject event source tag, or None
208
 
    stop_initiator_tag:    - '' -
 
198
    disable_initiator_tag:    - '' -
209
199
    checker_callback_tag:  - '' -
210
200
    checker_command: string; External command which is run to check if
211
201
                     client lives.  %() expansions are done at
212
202
                     runtime with vars(self) as dict, so that for
213
203
                     instance %(name)s can be used in the command.
214
 
    dbus_object_path: dbus.ObjectPath
215
 
    Private attibutes:
216
 
    _timeout: Real variable for 'timeout'
217
 
    _interval: Real variable for 'interval'
218
 
    _timeout_milliseconds: Used when calling gobject.timeout_add()
219
 
    _interval_milliseconds: - '' -
 
204
    use_dbus: bool(); Whether to provide D-Bus interface and signals
 
205
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
220
206
    """
221
 
    def _set_timeout(self, timeout):
222
 
        "Setter function for the 'timeout' attribute"
223
 
        self._timeout = timeout
224
 
        self._timeout_milliseconds = ((self.timeout.days
225
 
                                       * 24 * 60 * 60 * 1000)
226
 
                                      + (self.timeout.seconds * 1000)
227
 
                                      + (self.timeout.microseconds
228
 
                                         // 1000))
229
 
        # Emit D-Bus signal
230
 
        self.PropertyChanged(dbus.String(u"timeout"),
231
 
                             (dbus.UInt64(self._timeout_milliseconds,
232
 
                                          variant_level=1)))
233
 
    timeout = property(lambda self: self._timeout, _set_timeout)
234
 
    del _set_timeout
235
 
    
236
 
    def _set_interval(self, interval):
237
 
        "Setter function for the 'interval' attribute"
238
 
        self._interval = interval
239
 
        self._interval_milliseconds = ((self.interval.days
240
 
                                        * 24 * 60 * 60 * 1000)
241
 
                                       + (self.interval.seconds
242
 
                                          * 1000)
243
 
                                       + (self.interval.microseconds
244
 
                                          // 1000))
245
 
        # Emit D-Bus signal
246
 
        self.PropertyChanged(dbus.String(u"interval"),
247
 
                             (dbus.UInt64(self._interval_milliseconds,
248
 
                                          variant_level=1)))
249
 
    interval = property(lambda self: self._interval, _set_interval)
250
 
    del _set_interval
251
 
    
252
 
    def __init__(self, name = None, stop_hook=None, config=None):
 
207
    def timeout_milliseconds(self):
 
208
        "Return the 'timeout' attribute in milliseconds"
 
209
        return ((self.timeout.days * 24 * 60 * 60 * 1000)
 
210
                + (self.timeout.seconds * 1000)
 
211
                + (self.timeout.microseconds // 1000))
 
212
    
 
213
    def interval_milliseconds(self):
 
214
        "Return the 'interval' attribute in milliseconds"
 
215
        return ((self.interval.days * 24 * 60 * 60 * 1000)
 
216
                + (self.interval.seconds * 1000)
 
217
                + (self.interval.microseconds // 1000))
 
218
    
 
219
    def __init__(self, name = None, disable_hook=None, config=None,
 
220
                 use_dbus=True):
253
221
        """Note: the 'checker' key in 'config' sets the
254
222
        'checker_command' attribute and *not* the 'checker'
255
223
        attribute."""
256
 
        self.dbus_object_path = (dbus.ObjectPath
257
 
                                 ("/Mandos/clients/"
258
 
                                  + name.replace(".", "_")))
259
 
        dbus.service.Object.__init__(self, bus,
260
 
                                     self.dbus_object_path)
 
224
        self.name = name
261
225
        if config is None:
262
226
            config = {}
263
 
        self.name = name
264
227
        logger.debug(u"Creating client %r", self.name)
 
228
        self.use_dbus = use_dbus
 
229
        if self.use_dbus:
 
230
            self.dbus_object_path = (dbus.ObjectPath
 
231
                                     ("/Mandos/clients/"
 
232
                                      + self.name.replace(".", "_")))
 
233
            dbus.service.Object.__init__(self, bus,
 
234
                                         self.dbus_object_path)
265
235
        # Uppercase and remove spaces from fingerprint for later
266
236
        # comparison purposes with return value from the fingerprint()
267
237
        # function
280
250
                            % self.name)
281
251
        self.host = config.get("host", "")
282
252
        self.created = datetime.datetime.utcnow()
283
 
        self.started = False
284
 
        self.last_started = None
 
253
        self.enabled = False
 
254
        self.last_enabled = None
285
255
        self.last_checked_ok = None
286
256
        self.timeout = string_to_delta(config["timeout"])
287
257
        self.interval = string_to_delta(config["interval"])
288
 
        self.stop_hook = stop_hook
 
258
        self.disable_hook = disable_hook
289
259
        self.checker = None
290
260
        self.checker_initiator_tag = None
291
 
        self.stop_initiator_tag = None
 
261
        self.disable_initiator_tag = None
292
262
        self.checker_callback_tag = None
293
263
        self.checker_command = config["checker"]
294
264
    
295
 
    def start(self):
 
265
    def enable(self):
296
266
        """Start this client's checker and timeout hooks"""
297
 
        self.last_started = datetime.datetime.utcnow()
 
267
        self.last_enabled = datetime.datetime.utcnow()
298
268
        # Schedule a new checker to be started an 'interval' from now,
299
269
        # and every interval from then on.
300
270
        self.checker_initiator_tag = (gobject.timeout_add
301
 
                                      (self._interval_milliseconds,
 
271
                                      (self.interval_milliseconds(),
302
272
                                       self.start_checker))
303
273
        # Also start a new checker *right now*.
304
274
        self.start_checker()
305
 
        # Schedule a stop() when 'timeout' has passed
306
 
        self.stop_initiator_tag = (gobject.timeout_add
307
 
                                   (self._timeout_milliseconds,
308
 
                                    self.stop))
309
 
        self.started = True
310
 
        # Emit D-Bus signal
311
 
        self.PropertyChanged(dbus.String(u"started"),
312
 
                             dbus.Boolean(True, variant_level=1))
313
 
        self.PropertyChanged(dbus.String(u"last_started"),
314
 
                             (_datetime_to_dbus_struct
315
 
                              (self.last_started, variant_level=1)))
 
275
        # Schedule a disable() when 'timeout' has passed
 
276
        self.disable_initiator_tag = (gobject.timeout_add
 
277
                                   (self.timeout_milliseconds(),
 
278
                                    self.disable))
 
279
        self.enabled = True
 
280
        if self.use_dbus:
 
281
            # Emit D-Bus signals
 
282
            self.PropertyChanged(dbus.String(u"enabled"),
 
283
                                 dbus.Boolean(True, variant_level=1))
 
284
            self.PropertyChanged(dbus.String(u"last_enabled"),
 
285
                                 (_datetime_to_dbus(self.last_enabled,
 
286
                                                    variant_level=1)))
316
287
    
317
 
    def stop(self):
318
 
        """Stop this client."""
319
 
        if not getattr(self, "started", False):
 
288
    def disable(self):
 
289
        """Disable this client."""
 
290
        if not getattr(self, "enabled", False):
320
291
            return False
321
 
        logger.info(u"Stopping client %s", self.name)
322
 
        if getattr(self, "stop_initiator_tag", False):
323
 
            gobject.source_remove(self.stop_initiator_tag)
324
 
            self.stop_initiator_tag = None
 
292
        logger.info(u"Disabling client %s", self.name)
 
293
        if getattr(self, "disable_initiator_tag", False):
 
294
            gobject.source_remove(self.disable_initiator_tag)
 
295
            self.disable_initiator_tag = None
325
296
        if getattr(self, "checker_initiator_tag", False):
326
297
            gobject.source_remove(self.checker_initiator_tag)
327
298
            self.checker_initiator_tag = None
328
299
        self.stop_checker()
329
 
        if self.stop_hook:
330
 
            self.stop_hook(self)
331
 
        self.started = False
332
 
        # Emit D-Bus signal
333
 
        self.PropertyChanged(dbus.String(u"started"),
334
 
                             dbus.Boolean(False, variant_level=1))
 
300
        if self.disable_hook:
 
301
            self.disable_hook(self)
 
302
        self.enabled = False
 
303
        if self.use_dbus:
 
304
            # Emit D-Bus signal
 
305
            self.PropertyChanged(dbus.String(u"enabled"),
 
306
                                 dbus.Boolean(False, variant_level=1))
335
307
        # Do not run this again if called by a gobject.timeout_add
336
308
        return False
337
309
    
338
310
    def __del__(self):
339
 
        self.stop_hook = None
340
 
        self.stop()
 
311
        self.disable_hook = None
 
312
        self.disable()
341
313
    
342
314
    def checker_callback(self, pid, condition, command):
343
315
        """The checker has completed, so take appropriate actions."""
344
316
        self.checker_callback_tag = None
345
317
        self.checker = None
346
 
        # Emit D-Bus signal
347
 
        self.PropertyChanged(dbus.String(u"checker_running"),
348
 
                             dbus.Boolean(False, variant_level=1))
 
318
        if self.use_dbus:
 
319
            # Emit D-Bus signal
 
320
            self.PropertyChanged(dbus.String(u"checker_running"),
 
321
                                 dbus.Boolean(False, variant_level=1))
349
322
        if (os.WIFEXITED(condition)
350
323
            and (os.WEXITSTATUS(condition) == 0)):
351
324
            logger.info(u"Checker for %(name)s succeeded",
352
325
                        vars(self))
353
 
            # Emit D-Bus signal
354
 
            self.CheckerCompleted(dbus.Boolean(True),
355
 
                                  dbus.UInt16(condition),
356
 
                                  dbus.String(command))
 
326
            if self.use_dbus:
 
327
                # Emit D-Bus signal
 
328
                self.CheckerCompleted(dbus.Boolean(True),
 
329
                                      dbus.UInt16(condition),
 
330
                                      dbus.String(command))
357
331
            self.bump_timeout()
358
332
        elif not os.WIFEXITED(condition):
359
333
            logger.warning(u"Checker for %(name)s crashed?",
360
334
                           vars(self))
361
 
            # Emit D-Bus signal
362
 
            self.CheckerCompleted(dbus.Boolean(False),
363
 
                                  dbus.UInt16(condition),
364
 
                                  dbus.String(command))
 
335
            if self.use_dbus:
 
336
                # Emit D-Bus signal
 
337
                self.CheckerCompleted(dbus.Boolean(False),
 
338
                                      dbus.UInt16(condition),
 
339
                                      dbus.String(command))
365
340
        else:
366
341
            logger.info(u"Checker for %(name)s failed",
367
342
                        vars(self))
368
 
            # Emit D-Bus signal
369
 
            self.CheckerCompleted(dbus.Boolean(False),
370
 
                                  dbus.UInt16(condition),
371
 
                                  dbus.String(command))
 
343
            if self.use_dbus:
 
344
                # Emit D-Bus signal
 
345
                self.CheckerCompleted(dbus.Boolean(False),
 
346
                                      dbus.UInt16(condition),
 
347
                                      dbus.String(command))
372
348
    
373
349
    def bump_timeout(self):
374
350
        """Bump up the timeout for this client.
376
352
        alive and well.
377
353
        """
378
354
        self.last_checked_ok = datetime.datetime.utcnow()
379
 
        gobject.source_remove(self.stop_initiator_tag)
380
 
        self.stop_initiator_tag = (gobject.timeout_add
381
 
                                   (self._timeout_milliseconds,
382
 
                                    self.stop))
383
 
        self.PropertyChanged(dbus.String(u"last_checked_ok"),
384
 
                             (_datetime_to_dbus_struct
385
 
                              (self.last_checked_ok,
386
 
                               variant_level=1)))
 
355
        gobject.source_remove(self.disable_initiator_tag)
 
356
        self.disable_initiator_tag = (gobject.timeout_add
 
357
                                      (self.timeout_milliseconds(),
 
358
                                       self.disable))
 
359
        if self.use_dbus:
 
360
            # Emit D-Bus signal
 
361
            self.PropertyChanged(
 
362
                dbus.String(u"last_checked_ok"),
 
363
                (_datetime_to_dbus(self.last_checked_ok,
 
364
                                   variant_level=1)))
387
365
    
388
366
    def start_checker(self):
389
367
        """Start a new checker subprocess if one is not running.
422
400
                self.checker = subprocess.Popen(command,
423
401
                                                close_fds=True,
424
402
                                                shell=True, cwd="/")
425
 
                # Emit D-Bus signal
426
 
                self.CheckerStarted(command)
427
 
                self.PropertyChanged(dbus.String("checker_running"),
428
 
                                     dbus.Boolean(True, variant_level=1))
 
403
                if self.use_dbus:
 
404
                    # Emit D-Bus signal
 
405
                    self.CheckerStarted(command)
 
406
                    self.PropertyChanged(
 
407
                        dbus.String("checker_running"),
 
408
                        dbus.Boolean(True, variant_level=1))
429
409
                self.checker_callback_tag = (gobject.child_watch_add
430
410
                                             (self.checker.pid,
431
411
                                              self.checker_callback,
453
433
            if error.errno != errno.ESRCH: # No such process
454
434
                raise
455
435
        self.checker = None
456
 
        self.PropertyChanged(dbus.String(u"checker_running"),
457
 
                             dbus.Boolean(False, variant_level=1))
 
436
        if self.use_dbus:
 
437
            self.PropertyChanged(dbus.String(u"checker_running"),
 
438
                                 dbus.Boolean(False, variant_level=1))
458
439
    
459
440
    def still_valid(self):
460
441
        """Has the timeout not yet passed for this client?"""
461
 
        if not getattr(self, "started", False):
 
442
        if not getattr(self, "enabled", False):
462
443
            return False
463
444
        now = datetime.datetime.utcnow()
464
445
        if self.last_checked_ok is None:
497
478
                dbus.String("host"):
498
479
                    dbus.String(self.host, variant_level=1),
499
480
                dbus.String("created"):
500
 
                    _datetime_to_dbus_struct(self.created,
501
 
                                             variant_level=1),
502
 
                dbus.String("last_started"):
503
 
                    (_datetime_to_dbus_struct(self.last_started,
504
 
                                              variant_level=1)
505
 
                     if self.last_started is not None
 
481
                    _datetime_to_dbus(self.created, variant_level=1),
 
482
                dbus.String("last_enabled"):
 
483
                    (_datetime_to_dbus(self.last_enabled,
 
484
                                       variant_level=1)
 
485
                     if self.last_enabled is not None
506
486
                     else dbus.Boolean(False, variant_level=1)),
507
 
                dbus.String("started"):
508
 
                    dbus.Boolean(self.started, variant_level=1),
 
487
                dbus.String("enabled"):
 
488
                    dbus.Boolean(self.enabled, variant_level=1),
509
489
                dbus.String("last_checked_ok"):
510
 
                    (_datetime_to_dbus_struct(self.last_checked_ok,
511
 
                                              variant_level=1)
 
490
                    (_datetime_to_dbus(self.last_checked_ok,
 
491
                                       variant_level=1)
512
492
                     if self.last_checked_ok is not None
513
493
                     else dbus.Boolean (False, variant_level=1)),
514
494
                dbus.String("timeout"):
515
 
                    dbus.UInt64(self._timeout_milliseconds,
 
495
                    dbus.UInt64(self.timeout_milliseconds(),
516
496
                                variant_level=1),
517
497
                dbus.String("interval"):
518
 
                    dbus.UInt64(self._interval_milliseconds,
 
498
                    dbus.UInt64(self.interval_milliseconds(),
519
499
                                variant_level=1),
520
500
                dbus.String("checker"):
521
501
                    dbus.String(self.checker_command,
541
521
    def SetChecker(self, checker):
542
522
        "D-Bus setter method"
543
523
        self.checker_command = checker
 
524
        # Emit D-Bus signal
 
525
        self.PropertyChanged(dbus.String(u"checker"),
 
526
                             dbus.String(self.checker_command,
 
527
                                         variant_level=1))
544
528
    
545
529
    # SetHost - method
546
530
    @dbus.service.method(_interface, in_signature="s")
547
531
    def SetHost(self, host):
548
532
        "D-Bus setter method"
549
533
        self.host = host
 
534
        # Emit D-Bus signal
 
535
        self.PropertyChanged(dbus.String(u"host"),
 
536
                             dbus.String(self.host, variant_level=1))
550
537
    
551
538
    # SetInterval - method
552
539
    @dbus.service.method(_interface, in_signature="t")
553
540
    def SetInterval(self, milliseconds):
554
 
        self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
 
541
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
542
        # Emit D-Bus signal
 
543
        self.PropertyChanged(dbus.String(u"interval"),
 
544
                             (dbus.UInt64(self.interval_milliseconds(),
 
545
                                          variant_level=1)))
555
546
    
556
547
    # SetSecret - method
557
548
    @dbus.service.method(_interface, in_signature="ay",
564
555
    @dbus.service.method(_interface, in_signature="t")
565
556
    def SetTimeout(self, milliseconds):
566
557
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
558
        # Emit D-Bus signal
 
559
        self.PropertyChanged(dbus.String(u"timeout"),
 
560
                             (dbus.UInt64(self.timeout_milliseconds(),
 
561
                                          variant_level=1)))
567
562
    
568
 
    # Start - method
569
 
    Start = dbus.service.method(_interface)(start)
570
 
    Start.__name__ = "Start"
 
563
    # Enable - method
 
564
    Enable = dbus.service.method(_interface)(enable)
 
565
    Enable.__name__ = "Enable"
571
566
    
572
567
    # StartChecker - method
573
568
    @dbus.service.method(_interface)
575
570
        "D-Bus method"
576
571
        self.start_checker()
577
572
    
578
 
    # Stop - method
 
573
    # Disable - method
579
574
    @dbus.service.method(_interface)
580
 
    def Stop(self):
 
575
    def Disable(self):
581
576
        "D-Bus method"
582
 
        self.stop()
 
577
        self.disable()
583
578
    
584
579
    # StopChecker - method
585
580
    StopChecker = dbus.service.method(_interface)(stop_checker)
845
840
    elif state == avahi.ENTRY_GROUP_FAILURE:
846
841
        logger.critical(u"Avahi: Error in group state changed %s",
847
842
                        unicode(error))
848
 
        raise AvahiGroupError("State changed: %s", str(error))
 
843
        raise AvahiGroupError(u"State changed: %s" % unicode(error))
849
844
 
850
845
def if_nametoindex(interface):
851
846
    """Call the C function if_nametoindex(), or equivalent"""
894
889
 
895
890
 
896
891
def main():
897
 
    parser = OptionParser(version = "%%prog %s" % version)
 
892
    parser = optparse.OptionParser(version = "%%prog %s" % version)
898
893
    parser.add_option("-i", "--interface", type="string",
899
894
                      metavar="IF", help="Bind to interface IF")
900
895
    parser.add_option("-a", "--address", type="string",
901
896
                      help="Address to listen for requests on")
902
897
    parser.add_option("-p", "--port", type="int",
903
898
                      help="Port number to receive requests on")
904
 
    parser.add_option("--check", action="store_true", default=False,
 
899
    parser.add_option("--check", action="store_true",
905
900
                      help="Run self-test")
906
901
    parser.add_option("--debug", action="store_true",
907
902
                      help="Debug mode; run in foreground and log to"
914
909
                      default="/etc/mandos", metavar="DIR",
915
910
                      help="Directory to search for configuration"
916
911
                      " files")
 
912
    parser.add_option("--no-dbus", action="store_false",
 
913
                      dest="use_dbus",
 
914
                      help="Do not provide D-Bus system bus"
 
915
                      " interface")
917
916
    options = parser.parse_args()[0]
918
917
    
919
918
    if options.check:
929
928
                        "priority":
930
929
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
931
930
                        "servicename": "Mandos",
 
931
                        "use_dbus": "True",
932
932
                        }
933
933
    
934
934
    # Parse config file for server-global settings
937
937
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
938
938
    # Convert the SafeConfigParser object to a dict
939
939
    server_settings = server_config.defaults()
940
 
    # Use getboolean on the boolean config option
 
940
    # Use getboolean on the boolean config options
941
941
    server_settings["debug"] = (server_config.getboolean
942
942
                                ("DEFAULT", "debug"))
 
943
    server_settings["use_dbus"] = (server_config.getboolean
 
944
                                   ("DEFAULT", "use_dbus"))
943
945
    del server_config
944
946
    
945
947
    # Override the settings from the config file with command line
946
948
    # options, if set.
947
949
    for option in ("interface", "address", "port", "debug",
948
 
                   "priority", "servicename", "configdir"):
 
950
                   "priority", "servicename", "configdir",
 
951
                   "use_dbus"):
949
952
        value = getattr(options, option)
950
953
        if value is not None:
951
954
            server_settings[option] = value
952
955
    del options
953
956
    # Now we have our good server settings in "server_settings"
954
957
    
 
958
    # For convenience
955
959
    debug = server_settings["debug"]
 
960
    use_dbus = server_settings["use_dbus"]
956
961
    
957
962
    if not debug:
958
963
        syslogger.setLevel(logging.WARNING)
967
972
    # Parse config file with clients
968
973
    client_defaults = { "timeout": "1h",
969
974
                        "interval": "5m",
970
 
                        "checker": "fping -q -- %(host)s",
 
975
                        "checker": "fping -q -- %%(host)s",
971
976
                        "host": "",
972
977
                        }
973
978
    client_config = ConfigParser.SafeConfigParser(client_defaults)
988
993
    
989
994
    try:
990
995
        uid = pwd.getpwnam("_mandos").pw_uid
 
996
        gid = pwd.getpwnam("_mandos").pw_gid
991
997
    except KeyError:
992
998
        try:
993
999
            uid = pwd.getpwnam("mandos").pw_uid
 
1000
            gid = pwd.getpwnam("mandos").pw_gid
994
1001
        except KeyError:
995
1002
            try:
996
1003
                uid = pwd.getpwnam("nobody").pw_uid
 
1004
                gid = pwd.getpwnam("nogroup").pw_gid
997
1005
            except KeyError:
998
1006
                uid = 65534
999
 
    try:
1000
 
        gid = pwd.getpwnam("_mandos").pw_gid
1001
 
    except KeyError:
1002
 
        try:
1003
 
            gid = pwd.getpwnam("mandos").pw_gid
1004
 
        except KeyError:
1005
 
            try:
1006
 
                gid = pwd.getpwnam("nogroup").pw_gid
1007
 
            except KeyError:
1008
1007
                gid = 65534
1009
1008
    try:
1010
1009
        os.setuid(uid)
1031
1030
                                           avahi.DBUS_PATH_SERVER),
1032
1031
                            avahi.DBUS_INTERFACE_SERVER)
1033
1032
    # End of Avahi example code
1034
 
    bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
 
1033
    if use_dbus:
 
1034
        bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
 
1035
                                        bus)
1035
1036
    
1036
1037
    clients.update(Set(Client(name = section,
1037
1038
                              config
1038
 
                              = dict(client_config.items(section)))
 
1039
                              = dict(client_config.items(section)),
 
1040
                              use_dbus = use_dbus)
1039
1041
                       for section in client_config.sections()))
1040
1042
    if not clients:
1041
 
        logger.critical(u"No clients defined")
1042
 
        sys.exit(1)
 
1043
        logger.warning(u"No clients defined")
1043
1044
    
1044
1045
    if debug:
1045
1046
        # Redirect stdin so all checkers get /dev/null
1077
1078
        
1078
1079
        while clients:
1079
1080
            client = clients.pop()
1080
 
            client.stop_hook = None
1081
 
            client.stop()
 
1081
            client.disable_hook = None
 
1082
            client.disable()
1082
1083
    
1083
1084
    atexit.register(cleanup)
1084
1085
    
1087
1088
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1088
1089
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1089
1090
    
1090
 
    class MandosServer(dbus.service.Object):
1091
 
        """A D-Bus proxy object"""
1092
 
        def __init__(self):
1093
 
            dbus.service.Object.__init__(self, bus,
1094
 
                                         "/Mandos")
1095
 
        _interface = u"org.mandos_system.Mandos"
1096
 
        
1097
 
        @dbus.service.signal(_interface, signature="oa{sv}")
1098
 
        def ClientAdded(self, objpath, properties):
1099
 
            "D-Bus signal"
1100
 
            pass
1101
 
        
1102
 
        @dbus.service.signal(_interface, signature="o")
1103
 
        def ClientRemoved(self, objpath):
1104
 
            "D-Bus signal"
1105
 
            pass
1106
 
        
1107
 
        @dbus.service.method(_interface, out_signature="ao")
1108
 
        def GetAllClients(self):
1109
 
            return dbus.Array(c.dbus_object_path for c in clients)
1110
 
        
1111
 
        @dbus.service.method(_interface, out_signature="a{oa{sv}}")
1112
 
        def GetAllClientsWithProperties(self):
1113
 
            return dbus.Dictionary(
1114
 
                ((c.dbus_object_path, c.GetAllProperties())
1115
 
                 for c in clients),
1116
 
                signature="oa{sv}")
1117
 
        
1118
 
        @dbus.service.method(_interface, in_signature="o")
1119
 
        def RemoveClient(self, object_path):
1120
 
            for c in clients:
1121
 
                if c.dbus_object_path == object_path:
1122
 
                    c.stop()
1123
 
                    clients.remove(c)
1124
 
                    return
1125
 
            raise KeyError
1126
 
        
1127
 
        del _interface
 
1091
    if use_dbus:
 
1092
        class MandosServer(dbus.service.Object):
 
1093
            """A D-Bus proxy object"""
 
1094
            def __init__(self):
 
1095
                dbus.service.Object.__init__(self, bus,
 
1096
                                             "/Mandos")
 
1097
            _interface = u"org.mandos_system.Mandos"
 
1098
 
 
1099
            @dbus.service.signal(_interface, signature="oa{sv}")
 
1100
            def ClientAdded(self, objpath, properties):
 
1101
                "D-Bus signal"
 
1102
                pass
 
1103
 
 
1104
            @dbus.service.signal(_interface, signature="o")
 
1105
            def ClientRemoved(self, objpath):
 
1106
                "D-Bus signal"
 
1107
                pass
 
1108
 
 
1109
            @dbus.service.method(_interface, out_signature="ao")
 
1110
            def GetAllClients(self):
 
1111
                return dbus.Array(c.dbus_object_path for c in clients)
 
1112
 
 
1113
            @dbus.service.method(_interface, out_signature="a{oa{sv}}")
 
1114
            def GetAllClientsWithProperties(self):
 
1115
                return dbus.Dictionary(
 
1116
                    ((c.dbus_object_path, c.GetAllProperties())
 
1117
                     for c in clients),
 
1118
                    signature="oa{sv}")
 
1119
 
 
1120
            @dbus.service.method(_interface, in_signature="o")
 
1121
            def RemoveClient(self, object_path):
 
1122
                for c in clients:
 
1123
                    if c.dbus_object_path == object_path:
 
1124
                        clients.remove(c)
 
1125
                        # Don't signal anything except ClientRemoved
 
1126
                        c.use_dbus = False
 
1127
                        c.disable()
 
1128
                        # Emit D-Bus signal
 
1129
                        self.ClientRemoved(object_path)
 
1130
                        return
 
1131
                raise KeyError
 
1132
            @dbus.service.method(_interface)
 
1133
            def Quit(self):
 
1134
                main_loop.quit()
 
1135
 
 
1136
            del _interface
1128
1137
    
1129
 
    mandos_server = MandosServer()
 
1138
        mandos_server = MandosServer()
1130
1139
    
1131
1140
    for client in clients:
1132
 
        # Emit D-Bus signal
1133
 
        mandos_server.ClientAdded(client.dbus_object_path,
1134
 
                                  client.GetAllProperties())
1135
 
        client.start()
 
1141
        if use_dbus:
 
1142
            # Emit D-Bus signal
 
1143
            mandos_server.ClientAdded(client.dbus_object_path,
 
1144
                                      client.GetAllProperties())
 
1145
        client.enable()
1136
1146
    
1137
1147
    tcp_server.enable()
1138
1148
    tcp_server.server_activate()
1162
1172
        logger.debug(u"Starting main loop")
1163
1173
        main_loop.run()
1164
1174
    except AvahiError, error:
1165
 
        logger.critical(u"AvahiError: %s" + unicode(error))
 
1175
        logger.critical(u"AvahiError: %s", error)
1166
1176
        sys.exit(1)
1167
1177
    except KeyboardInterrupt:
1168
1178
        if debug: