/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-09-16 23:28:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090916232839-3o7i8qmcdcz5j1ya
* init.d-mandos (Required-Start, Required-Stop): Bug fix: Added
                 "$syslog", thanks to Petter Reinholdtsen
                 <pere@hungry.com> (Debian bug #546928).

* initramfs-tools-script: Removed erroneous comment.

* plugins.d/askpass-fifo.c: Removed TEMP_FAILURE_RETRY since it is
                            not needed.

* plugins.d/mandos-client.c (main): Bug fix: Initialize
                                    "old_sigterm_action".

* plugins.d/splashy.c (main): Bug fix: really check return value from
                              "sigaddset".  Fix some warnings on
                              64-bit systems.

* plugins.d/usplash.c (termination_handler, main): Save received
                                                   signal and
                                                   re-raise it on
                                                   exit.
  (usplash_write): Do not close FIFO, instead, take an additional file
                   descriptor pointer to it and open only when needed
                   (all callers changed).  Abort immediately on EINTR.
                   Bug fix:  Add NUL byte on single-word commands.
                   Ignore "interrupted_by_signal".
  (makeprompt, find_usplash): New; broken out from "main()".
  (find_usplash): Bug fix: close /proc/<pid>/cmdline FD on error.
  (main): Reorganized to jump to a new "failure" label on any error.
          Bug fix: check return values from sigaddset.
          New variable "usplash_accessed" to flag if usplash(8) needs
          to be killed and restarted.  Removed the "an_error_occured"
          variable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
55
55
import logging
56
56
import logging.handlers
57
57
import pwd
58
 
import contextlib
 
58
from contextlib import closing
59
59
import struct
60
60
import fcntl
61
61
import functools
62
 
import cPickle as pickle
63
 
import select
64
62
 
65
63
import dbus
66
64
import dbus.service
69
67
from dbus.mainloop.glib import DBusGMainLoop
70
68
import ctypes
71
69
import ctypes.util
72
 
import xml.dom.minidom
73
 
import inspect
74
70
 
75
71
try:
76
72
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
81
77
        SO_BINDTODEVICE = None
82
78
 
83
79
 
84
 
version = "1.0.14"
 
80
version = "1.0.11"
85
81
 
86
82
logger = logging.Logger(u'mandos')
87
83
syslogger = (logging.handlers.SysLogHandler
178
174
                                    self.server.EntryGroupNew()),
179
175
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
180
176
            self.group.connect_to_signal('StateChanged',
181
 
                                         self
182
 
                                         .entry_group_state_changed)
 
177
                                         self.entry_group_state_changed)
183
178
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
184
179
                     self.name, self.type)
185
180
        self.group.AddService(
193
188
        self.group.Commit()
194
189
    def entry_group_state_changed(self, state, error):
195
190
        """Derived from the Avahi example code"""
196
 
        logger.debug(u"Avahi entry group state change: %i", state)
 
191
        logger.debug(u"Avahi state change: %i", state)
197
192
        
198
193
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
199
194
            logger.debug(u"Zeroconf service established.")
212
207
            self.group = None
213
208
    def server_state_changed(self, state):
214
209
        """Derived from the Avahi example code"""
215
 
        logger.debug(u"Avahi server state change: %i", state)
216
210
        if state == avahi.SERVER_COLLISION:
217
211
            logger.error(u"Zeroconf server name collision")
218
212
            self.remove()
245
239
    enabled:    bool()
246
240
    last_checked_ok: datetime.datetime(); (UTC) or None
247
241
    timeout:    datetime.timedelta(); How long from last_checked_ok
248
 
                                      until this client is disabled
 
242
                                      until this client is invalid
249
243
    interval:   datetime.timedelta(); How often to start a new checker
250
244
    disable_hook:  If set, called by disable() as disable_hook(self)
251
245
    checker:    subprocess.Popen(); a running checker process used
252
246
                                    to see if the client lives.
253
247
                                    'None' if no process is running.
254
248
    checker_initiator_tag: a gobject event source tag, or None
255
 
    disable_initiator_tag: - '' -
 
249
    disable_initiator_tag:    - '' -
256
250
    checker_callback_tag:  - '' -
257
251
    checker_command: string; External command which is run to check if
258
252
                     client lives.  %() expansions are done at
262
256
    """
263
257
    
264
258
    @staticmethod
265
 
    def _timedelta_to_milliseconds(td):
266
 
        "Convert a datetime.timedelta() to milliseconds"
267
 
        return ((td.days * 24 * 60 * 60 * 1000)
268
 
                + (td.seconds * 1000)
269
 
                + (td.microseconds // 1000))
 
259
    def _datetime_to_milliseconds(dt):
 
260
        "Convert a datetime.datetime() to milliseconds"
 
261
        return ((dt.days * 24 * 60 * 60 * 1000)
 
262
                + (dt.seconds * 1000)
 
263
                + (dt.microseconds // 1000))
270
264
    
271
265
    def timeout_milliseconds(self):
272
266
        "Return the 'timeout' attribute in milliseconds"
273
 
        return self._timedelta_to_milliseconds(self.timeout)
 
267
        return self._datetime_to_milliseconds(self.timeout)
274
268
    
275
269
    def interval_milliseconds(self):
276
270
        "Return the 'interval' attribute in milliseconds"
277
 
        return self._timedelta_to_milliseconds(self.interval)
 
271
        return self._datetime_to_milliseconds(self.interval)
278
272
    
279
273
    def __init__(self, name = None, disable_hook=None, config=None):
280
274
        """Note: the 'checker' key in 'config' sets the
293
287
        if u"secret" in config:
294
288
            self.secret = config[u"secret"].decode(u"base64")
295
289
        elif u"secfile" in config:
296
 
            with open(os.path.expanduser(os.path.expandvars
297
 
                                         (config[u"secfile"])),
298
 
                      "rb") as secfile:
 
290
            with closing(open(os.path.expanduser
 
291
                              (os.path.expandvars
 
292
                               (config[u"secfile"])))) as secfile:
299
293
                self.secret = secfile.read()
300
294
        else:
301
295
            raise TypeError(u"No secret or secfile for client %s"
327
321
        self.checker_initiator_tag = (gobject.timeout_add
328
322
                                      (self.interval_milliseconds(),
329
323
                                       self.start_checker))
 
324
        # Also start a new checker *right now*.
 
325
        self.start_checker()
330
326
        # Schedule a disable() when 'timeout' has passed
331
327
        self.disable_initiator_tag = (gobject.timeout_add
332
328
                                   (self.timeout_milliseconds(),
333
329
                                    self.disable))
334
330
        self.enabled = True
335
 
        # Also start a new checker *right now*.
336
 
        self.start_checker()
337
331
    
338
 
    def disable(self, quiet=True):
 
332
    def disable(self):
339
333
        """Disable this client."""
340
334
        if not getattr(self, "enabled", False):
341
335
            return False
342
 
        if not quiet:
343
 
            logger.info(u"Disabling client %s", self.name)
 
336
        logger.info(u"Disabling client %s", self.name)
344
337
        if getattr(self, u"disable_initiator_tag", False):
345
338
            gobject.source_remove(self.disable_initiator_tag)
346
339
            self.disable_initiator_tag = None
398
391
        # client would inevitably timeout, since no checker would get
399
392
        # a chance to run to completion.  If we instead leave running
400
393
        # checkers alone, the checker would have to take more time
401
 
        # than 'timeout' for the client to be disabled, which is as it
402
 
        # should be.
 
394
        # than 'timeout' for the client to be declared invalid, which
 
395
        # is as it should be.
403
396
        
404
397
        # If a checker exists, make sure it is not a zombie
405
 
        try:
 
398
        if self.checker is not None:
406
399
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
407
 
        except (AttributeError, OSError), error:
408
 
            if (isinstance(error, OSError)
409
 
                and error.errno != errno.ECHILD):
410
 
                raise error
411
 
        else:
412
400
            if pid:
413
401
                logger.warning(u"Checker was a zombie")
414
402
                gobject.source_remove(self.checker_callback_tag)
470
458
        logger.debug(u"Stopping checker for %(name)s", vars(self))
471
459
        try:
472
460
            os.kill(self.checker.pid, signal.SIGTERM)
473
 
            #time.sleep(0.5)
 
461
            #os.sleep(0.5)
474
462
            #if self.checker.poll() is None:
475
463
            #    os.kill(self.checker.pid, signal.SIGKILL)
476
464
        except OSError, error:
477
465
            if error.errno != errno.ESRCH: # No such process
478
466
                raise
479
467
        self.checker = None
480
 
 
481
 
 
482
 
def dbus_service_property(dbus_interface, signature=u"v",
483
 
                          access=u"readwrite", byte_arrays=False):
484
 
    """Decorators for marking methods of a DBusObjectWithProperties to
485
 
    become properties on the D-Bus.
486
 
    
487
 
    The decorated method will be called with no arguments by "Get"
488
 
    and with one argument by "Set".
489
 
    
490
 
    The parameters, where they are supported, are the same as
491
 
    dbus.service.method, except there is only "signature", since the
492
 
    type from Get() and the type sent to Set() is the same.
493
 
    """
494
 
    # Encoding deeply encoded byte arrays is not supported yet by the
495
 
    # "Set" method, so we fail early here:
496
 
    if byte_arrays and signature != u"ay":
497
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
498
 
                         u" signature %r" % signature)
499
 
    def decorator(func):
500
 
        func._dbus_is_property = True
501
 
        func._dbus_interface = dbus_interface
502
 
        func._dbus_signature = signature
503
 
        func._dbus_access = access
504
 
        func._dbus_name = func.__name__
505
 
        if func._dbus_name.endswith(u"_dbus_property"):
506
 
            func._dbus_name = func._dbus_name[:-14]
507
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
508
 
        return func
509
 
    return decorator
510
 
 
511
 
 
512
 
class DBusPropertyException(dbus.exceptions.DBusException):
513
 
    """A base class for D-Bus property-related exceptions
514
 
    """
515
 
    def __unicode__(self):
516
 
        return unicode(str(self))
517
 
 
518
 
 
519
 
class DBusPropertyAccessException(DBusPropertyException):
520
 
    """A property's access permissions disallows an operation.
521
 
    """
522
 
    pass
523
 
 
524
 
 
525
 
class DBusPropertyNotFound(DBusPropertyException):
526
 
    """An attempt was made to access a non-existing property.
527
 
    """
528
 
    pass
529
 
 
530
 
 
531
 
class DBusObjectWithProperties(dbus.service.Object):
532
 
    """A D-Bus object with properties.
533
 
 
534
 
    Classes inheriting from this can use the dbus_service_property
535
 
    decorator to expose methods as D-Bus properties.  It exposes the
536
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
537
 
    """
538
 
    
539
 
    @staticmethod
540
 
    def _is_dbus_property(obj):
541
 
        return getattr(obj, u"_dbus_is_property", False)
542
 
    
543
 
    def _get_all_dbus_properties(self):
544
 
        """Returns a generator of (name, attribute) pairs
545
 
        """
546
 
        return ((prop._dbus_name, prop)
547
 
                for name, prop in
548
 
                inspect.getmembers(self, self._is_dbus_property))
549
 
    
550
 
    def _get_dbus_property(self, interface_name, property_name):
551
 
        """Returns a bound method if one exists which is a D-Bus
552
 
        property with the specified name and interface.
553
 
        """
554
 
        for name in (property_name,
555
 
                     property_name + u"_dbus_property"):
556
 
            prop = getattr(self, name, None)
557
 
            if (prop is None
558
 
                or not self._is_dbus_property(prop)
559
 
                or prop._dbus_name != property_name
560
 
                or (interface_name and prop._dbus_interface
561
 
                    and interface_name != prop._dbus_interface)):
562
 
                continue
563
 
            return prop
564
 
        # No such property
565
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
566
 
                                   + interface_name + u"."
567
 
                                   + property_name)
568
 
    
569
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
570
 
                         out_signature=u"v")
571
 
    def Get(self, interface_name, property_name):
572
 
        """Standard D-Bus property Get() method, see D-Bus standard.
573
 
        """
574
 
        prop = self._get_dbus_property(interface_name, property_name)
575
 
        if prop._dbus_access == u"write":
576
 
            raise DBusPropertyAccessException(property_name)
577
 
        value = prop()
578
 
        if not hasattr(value, u"variant_level"):
579
 
            return value
580
 
        return type(value)(value, variant_level=value.variant_level+1)
581
 
    
582
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
583
 
    def Set(self, interface_name, property_name, value):
584
 
        """Standard D-Bus property Set() method, see D-Bus standard.
585
 
        """
586
 
        prop = self._get_dbus_property(interface_name, property_name)
587
 
        if prop._dbus_access == u"read":
588
 
            raise DBusPropertyAccessException(property_name)
589
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
590
 
            # The byte_arrays option is not supported yet on
591
 
            # signatures other than "ay".
592
 
            if prop._dbus_signature != u"ay":
593
 
                raise ValueError
594
 
            value = dbus.ByteArray(''.join(unichr(byte)
595
 
                                           for byte in value))
596
 
        prop(value)
597
 
    
598
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
599
 
                         out_signature=u"a{sv}")
600
 
    def GetAll(self, interface_name):
601
 
        """Standard D-Bus property GetAll() method, see D-Bus
602
 
        standard.
603
 
 
604
 
        Note: Will not include properties with access="write".
605
 
        """
606
 
        all = {}
607
 
        for name, prop in self._get_all_dbus_properties():
608
 
            if (interface_name
609
 
                and interface_name != prop._dbus_interface):
610
 
                # Interface non-empty but did not match
611
 
                continue
612
 
            # Ignore write-only properties
613
 
            if prop._dbus_access == u"write":
614
 
                continue
615
 
            value = prop()
616
 
            if not hasattr(value, u"variant_level"):
617
 
                all[name] = value
618
 
                continue
619
 
            all[name] = type(value)(value, variant_level=
620
 
                                    value.variant_level+1)
621
 
        return dbus.Dictionary(all, signature=u"sv")
622
 
    
623
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
624
 
                         out_signature=u"s",
625
 
                         path_keyword='object_path',
626
 
                         connection_keyword='connection')
627
 
    def Introspect(self, object_path, connection):
628
 
        """Standard D-Bus method, overloaded to insert property tags.
629
 
        """
630
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
631
 
                                                   connection)
632
 
        try:
633
 
            document = xml.dom.minidom.parseString(xmlstring)
634
 
            def make_tag(document, name, prop):
635
 
                e = document.createElement(u"property")
636
 
                e.setAttribute(u"name", name)
637
 
                e.setAttribute(u"type", prop._dbus_signature)
638
 
                e.setAttribute(u"access", prop._dbus_access)
639
 
                return e
640
 
            for if_tag in document.getElementsByTagName(u"interface"):
641
 
                for tag in (make_tag(document, name, prop)
642
 
                            for name, prop
643
 
                            in self._get_all_dbus_properties()
644
 
                            if prop._dbus_interface
645
 
                            == if_tag.getAttribute(u"name")):
646
 
                    if_tag.appendChild(tag)
647
 
                # Add the names to the return values for the
648
 
                # "org.freedesktop.DBus.Properties" methods
649
 
                if (if_tag.getAttribute(u"name")
650
 
                    == u"org.freedesktop.DBus.Properties"):
651
 
                    for cn in if_tag.getElementsByTagName(u"method"):
652
 
                        if cn.getAttribute(u"name") == u"Get":
653
 
                            for arg in cn.getElementsByTagName(u"arg"):
654
 
                                if (arg.getAttribute(u"direction")
655
 
                                    == u"out"):
656
 
                                    arg.setAttribute(u"name", u"value")
657
 
                        elif cn.getAttribute(u"name") == u"GetAll":
658
 
                            for arg in cn.getElementsByTagName(u"arg"):
659
 
                                if (arg.getAttribute(u"direction")
660
 
                                    == u"out"):
661
 
                                    arg.setAttribute(u"name", u"props")
662
 
            xmlstring = document.toxml(u"utf-8")
663
 
            document.unlink()
664
 
        except (AttributeError, xml.dom.DOMException,
665
 
                xml.parsers.expat.ExpatError), error:
666
 
            logger.error(u"Failed to override Introspection method",
667
 
                         error)
668
 
        return xmlstring
669
 
 
670
 
 
671
 
class ClientDBus(Client, DBusObjectWithProperties):
 
468
    
 
469
    def still_valid(self):
 
470
        """Has the timeout not yet passed for this client?"""
 
471
        if not getattr(self, u"enabled", False):
 
472
            return False
 
473
        now = datetime.datetime.utcnow()
 
474
        if self.last_checked_ok is None:
 
475
            return now < (self.created + self.timeout)
 
476
        else:
 
477
            return now < (self.last_checked_ok + self.timeout)
 
478
 
 
479
 
 
480
class ClientDBus(Client, dbus.service.Object):
672
481
    """A Client class using D-Bus
673
482
    
674
483
    Attributes:
685
494
        self.dbus_object_path = (dbus.ObjectPath
686
495
                                 (u"/clients/"
687
496
                                  + self.name.replace(u".", u"_")))
688
 
        DBusObjectWithProperties.__init__(self, self.bus,
689
 
                                          self.dbus_object_path)
 
497
        dbus.service.Object.__init__(self, self.bus,
 
498
                                     self.dbus_object_path)
690
499
    
691
500
    @staticmethod
692
501
    def _datetime_to_dbus(dt, variant_level=0):
707
516
                                       variant_level=1))
708
517
        return r
709
518
    
710
 
    def disable(self, quiet = False):
 
519
    def disable(self, signal = True):
711
520
        oldstate = getattr(self, u"enabled", False)
712
 
        r = Client.disable(self, quiet=quiet)
713
 
        if not quiet and oldstate != self.enabled:
 
521
        r = Client.disable(self)
 
522
        if signal and oldstate != self.enabled:
714
523
            # Emit D-Bus signal
715
524
            self.PropertyChanged(dbus.String(u"enabled"),
716
525
                                 dbus.Boolean(False, variant_level=1))
721
530
            self.remove_from_connection()
722
531
        except LookupError:
723
532
            pass
724
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
725
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
533
        if hasattr(dbus.service.Object, u"__del__"):
 
534
            dbus.service.Object.__del__(self, *args, **kwargs)
726
535
        Client.__del__(self, *args, **kwargs)
727
536
    
728
537
    def checker_callback(self, pid, condition, command,
782
591
                                 dbus.Boolean(False, variant_level=1))
783
592
        return r
784
593
    
785
 
    ## D-Bus methods, signals & properties
 
594
    ## D-Bus methods & signals
786
595
    _interface = u"se.bsnet.fukt.Mandos.Client"
787
596
    
788
 
    ## Signals
 
597
    # CheckedOK - method
 
598
    @dbus.service.method(_interface)
 
599
    def CheckedOK(self):
 
600
        return self.checked_ok()
789
601
    
790
602
    # CheckerCompleted - signal
791
603
    @dbus.service.signal(_interface, signature=u"nxs")
799
611
        "D-Bus signal"
800
612
        pass
801
613
    
 
614
    # GetAllProperties - method
 
615
    @dbus.service.method(_interface, out_signature=u"a{sv}")
 
616
    def GetAllProperties(self):
 
617
        "D-Bus method"
 
618
        return dbus.Dictionary({
 
619
                dbus.String(u"name"):
 
620
                    dbus.String(self.name, variant_level=1),
 
621
                dbus.String(u"fingerprint"):
 
622
                    dbus.String(self.fingerprint, variant_level=1),
 
623
                dbus.String(u"host"):
 
624
                    dbus.String(self.host, variant_level=1),
 
625
                dbus.String(u"created"):
 
626
                    self._datetime_to_dbus(self.created,
 
627
                                           variant_level=1),
 
628
                dbus.String(u"last_enabled"):
 
629
                    (self._datetime_to_dbus(self.last_enabled,
 
630
                                            variant_level=1)
 
631
                     if self.last_enabled is not None
 
632
                     else dbus.Boolean(False, variant_level=1)),
 
633
                dbus.String(u"enabled"):
 
634
                    dbus.Boolean(self.enabled, variant_level=1),
 
635
                dbus.String(u"last_checked_ok"):
 
636
                    (self._datetime_to_dbus(self.last_checked_ok,
 
637
                                            variant_level=1)
 
638
                     if self.last_checked_ok is not None
 
639
                     else dbus.Boolean (False, variant_level=1)),
 
640
                dbus.String(u"timeout"):
 
641
                    dbus.UInt64(self.timeout_milliseconds(),
 
642
                                variant_level=1),
 
643
                dbus.String(u"interval"):
 
644
                    dbus.UInt64(self.interval_milliseconds(),
 
645
                                variant_level=1),
 
646
                dbus.String(u"checker"):
 
647
                    dbus.String(self.checker_command,
 
648
                                variant_level=1),
 
649
                dbus.String(u"checker_running"):
 
650
                    dbus.Boolean(self.checker is not None,
 
651
                                 variant_level=1),
 
652
                dbus.String(u"object_path"):
 
653
                    dbus.ObjectPath(self.dbus_object_path,
 
654
                                    variant_level=1)
 
655
                }, signature=u"sv")
 
656
    
 
657
    # IsStillValid - method
 
658
    @dbus.service.method(_interface, out_signature=u"b")
 
659
    def IsStillValid(self):
 
660
        return self.still_valid()
 
661
    
802
662
    # PropertyChanged - signal
803
663
    @dbus.service.signal(_interface, signature=u"sv")
804
664
    def PropertyChanged(self, property, value):
805
665
        "D-Bus signal"
806
666
        pass
807
667
    
808
 
    # GotSecret - signal
 
668
    # ReceivedSecret - signal
809
669
    @dbus.service.signal(_interface)
810
 
    def GotSecret(self):
 
670
    def ReceivedSecret(self):
811
671
        "D-Bus signal"
812
672
        pass
813
673
    
817
677
        "D-Bus signal"
818
678
        pass
819
679
    
820
 
    ## Methods
821
 
    
822
 
    # CheckedOK - method
823
 
    @dbus.service.method(_interface)
824
 
    def CheckedOK(self):
825
 
        return self.checked_ok()
 
680
    # SetChecker - method
 
681
    @dbus.service.method(_interface, in_signature=u"s")
 
682
    def SetChecker(self, checker):
 
683
        "D-Bus setter method"
 
684
        self.checker_command = checker
 
685
        # Emit D-Bus signal
 
686
        self.PropertyChanged(dbus.String(u"checker"),
 
687
                             dbus.String(self.checker_command,
 
688
                                         variant_level=1))
 
689
    
 
690
    # SetHost - method
 
691
    @dbus.service.method(_interface, in_signature=u"s")
 
692
    def SetHost(self, host):
 
693
        "D-Bus setter method"
 
694
        self.host = host
 
695
        # Emit D-Bus signal
 
696
        self.PropertyChanged(dbus.String(u"host"),
 
697
                             dbus.String(self.host, variant_level=1))
 
698
    
 
699
    # SetInterval - method
 
700
    @dbus.service.method(_interface, in_signature=u"t")
 
701
    def SetInterval(self, milliseconds):
 
702
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
703
        # Emit D-Bus signal
 
704
        self.PropertyChanged(dbus.String(u"interval"),
 
705
                             (dbus.UInt64(self.interval_milliseconds(),
 
706
                                          variant_level=1)))
 
707
    
 
708
    # SetSecret - method
 
709
    @dbus.service.method(_interface, in_signature=u"ay",
 
710
                         byte_arrays=True)
 
711
    def SetSecret(self, secret):
 
712
        "D-Bus setter method"
 
713
        self.secret = str(secret)
 
714
    
 
715
    # SetTimeout - method
 
716
    @dbus.service.method(_interface, in_signature=u"t")
 
717
    def SetTimeout(self, milliseconds):
 
718
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
719
        # Emit D-Bus signal
 
720
        self.PropertyChanged(dbus.String(u"timeout"),
 
721
                             (dbus.UInt64(self.timeout_milliseconds(),
 
722
                                          variant_level=1)))
826
723
    
827
724
    # Enable - method
828
725
    @dbus.service.method(_interface)
847
744
    def StopChecker(self):
848
745
        self.stop_checker()
849
746
    
850
 
    ## Properties
851
 
    
852
 
    # name - property
853
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
854
 
    def name_dbus_property(self):
855
 
        return dbus.String(self.name)
856
 
    
857
 
    # fingerprint - property
858
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
859
 
    def fingerprint_dbus_property(self):
860
 
        return dbus.String(self.fingerprint)
861
 
    
862
 
    # host - property
863
 
    @dbus_service_property(_interface, signature=u"s",
864
 
                           access=u"readwrite")
865
 
    def host_dbus_property(self, value=None):
866
 
        if value is None:       # get
867
 
            return dbus.String(self.host)
868
 
        self.host = value
869
 
        # Emit D-Bus signal
870
 
        self.PropertyChanged(dbus.String(u"host"),
871
 
                             dbus.String(value, variant_level=1))
872
 
    
873
 
    # created - property
874
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
875
 
    def created_dbus_property(self):
876
 
        return dbus.String(self._datetime_to_dbus(self.created))
877
 
    
878
 
    # last_enabled - property
879
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
880
 
    def last_enabled_dbus_property(self):
881
 
        if self.last_enabled is None:
882
 
            return dbus.String(u"")
883
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
884
 
    
885
 
    # enabled - property
886
 
    @dbus_service_property(_interface, signature=u"b",
887
 
                           access=u"readwrite")
888
 
    def enabled_dbus_property(self, value=None):
889
 
        if value is None:       # get
890
 
            return dbus.Boolean(self.enabled)
891
 
        if value:
892
 
            self.enable()
893
 
        else:
894
 
            self.disable()
895
 
    
896
 
    # last_checked_ok - property
897
 
    @dbus_service_property(_interface, signature=u"s",
898
 
                           access=u"readwrite")
899
 
    def last_checked_ok_dbus_property(self, value=None):
900
 
        if value is not None:
901
 
            self.checked_ok()
902
 
            return
903
 
        if self.last_checked_ok is None:
904
 
            return dbus.String(u"")
905
 
        return dbus.String(self._datetime_to_dbus(self
906
 
                                                  .last_checked_ok))
907
 
    
908
 
    # timeout - property
909
 
    @dbus_service_property(_interface, signature=u"t",
910
 
                           access=u"readwrite")
911
 
    def timeout_dbus_property(self, value=None):
912
 
        if value is None:       # get
913
 
            return dbus.UInt64(self.timeout_milliseconds())
914
 
        self.timeout = datetime.timedelta(0, 0, 0, value)
915
 
        # Emit D-Bus signal
916
 
        self.PropertyChanged(dbus.String(u"timeout"),
917
 
                             dbus.UInt64(value, variant_level=1))
918
 
        if getattr(self, u"disable_initiator_tag", None) is None:
919
 
            return
920
 
        # Reschedule timeout
921
 
        gobject.source_remove(self.disable_initiator_tag)
922
 
        self.disable_initiator_tag = None
923
 
        time_to_die = (self.
924
 
                       _timedelta_to_milliseconds((self
925
 
                                                   .last_checked_ok
926
 
                                                   + self.timeout)
927
 
                                                  - datetime.datetime
928
 
                                                  .utcnow()))
929
 
        if time_to_die <= 0:
930
 
            # The timeout has passed
931
 
            self.disable()
932
 
        else:
933
 
            self.disable_initiator_tag = (gobject.timeout_add
934
 
                                          (time_to_die, self.disable))
935
 
    
936
 
    # interval - property
937
 
    @dbus_service_property(_interface, signature=u"t",
938
 
                           access=u"readwrite")
939
 
    def interval_dbus_property(self, value=None):
940
 
        if value is None:       # get
941
 
            return dbus.UInt64(self.interval_milliseconds())
942
 
        self.interval = datetime.timedelta(0, 0, 0, value)
943
 
        # Emit D-Bus signal
944
 
        self.PropertyChanged(dbus.String(u"interval"),
945
 
                             dbus.UInt64(value, variant_level=1))
946
 
        if getattr(self, u"checker_initiator_tag", None) is None:
947
 
            return
948
 
        # Reschedule checker run
949
 
        gobject.source_remove(self.checker_initiator_tag)
950
 
        self.checker_initiator_tag = (gobject.timeout_add
951
 
                                      (value, self.start_checker))
952
 
        self.start_checker()    # Start one now, too
953
 
 
954
 
    # checker - property
955
 
    @dbus_service_property(_interface, signature=u"s",
956
 
                           access=u"readwrite")
957
 
    def checker_dbus_property(self, value=None):
958
 
        if value is None:       # get
959
 
            return dbus.String(self.checker_command)
960
 
        self.checker_command = value
961
 
        # Emit D-Bus signal
962
 
        self.PropertyChanged(dbus.String(u"checker"),
963
 
                             dbus.String(self.checker_command,
964
 
                                         variant_level=1))
965
 
    
966
 
    # checker_running - property
967
 
    @dbus_service_property(_interface, signature=u"b",
968
 
                           access=u"readwrite")
969
 
    def checker_running_dbus_property(self, value=None):
970
 
        if value is None:       # get
971
 
            return dbus.Boolean(self.checker is not None)
972
 
        if value:
973
 
            self.start_checker()
974
 
        else:
975
 
            self.stop_checker()
976
 
    
977
 
    # object_path - property
978
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
979
 
    def object_path_dbus_property(self):
980
 
        return self.dbus_object_path # is already a dbus.ObjectPath
981
 
    
982
 
    # secret = property
983
 
    @dbus_service_property(_interface, signature=u"ay",
984
 
                           access=u"write", byte_arrays=True)
985
 
    def secret_dbus_property(self, value):
986
 
        self.secret = str(value)
987
 
    
988
747
    del _interface
989
748
 
990
749
 
997
756
    def handle(self):
998
757
        logger.info(u"TCP connection from: %s",
999
758
                    unicode(self.client_address))
1000
 
        logger.debug(u"IPC Pipe FD: %d",
1001
 
                     self.server.child_pipe[1].fileno())
 
759
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
1002
760
        # Open IPC pipe to parent process
1003
 
        with contextlib.nested(self.server.child_pipe[1],
1004
 
                               self.server.parent_pipe[0]
1005
 
                               ) as (ipc, ipc_return):
 
761
        with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1006
762
            session = (gnutls.connection
1007
763
                       .ClientSession(self.request,
1008
764
                                      gnutls.connection
1009
765
                                      .X509Credentials()))
1010
766
            
 
767
            line = self.request.makefile().readline()
 
768
            logger.debug(u"Protocol version: %r", line)
 
769
            try:
 
770
                if int(line.strip().split()[0]) > 1:
 
771
                    raise RuntimeError
 
772
            except (ValueError, IndexError, RuntimeError), error:
 
773
                logger.error(u"Unknown protocol version: %s", error)
 
774
                return
 
775
            
1011
776
            # Note: gnutls.connection.X509Credentials is really a
1012
777
            # generic GnuTLS certificate credentials object so long as
1013
778
            # no X.509 keys are added to it.  Therefore, we can use it
1025
790
             .gnutls_priority_set_direct(session._c_object,
1026
791
                                         priority, None))
1027
792
            
1028
 
            # Start communication using the Mandos protocol
1029
 
            # Get protocol number
1030
 
            line = self.request.makefile().readline()
1031
 
            logger.debug(u"Protocol version: %r", line)
1032
 
            try:
1033
 
                if int(line.strip().split()[0]) > 1:
1034
 
                    raise RuntimeError
1035
 
            except (ValueError, IndexError, RuntimeError), error:
1036
 
                logger.error(u"Unknown protocol version: %s", error)
1037
 
                return
1038
 
            
1039
 
            # Start GnuTLS connection
1040
793
            try:
1041
794
                session.handshake()
1042
795
            except gnutls.errors.GNUTLSError, error:
1046
799
                return
1047
800
            logger.debug(u"Handshake succeeded")
1048
801
            try:
1049
 
                try:
1050
 
                    fpr = self.fingerprint(self.peer_certificate
1051
 
                                           (session))
1052
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
1053
 
                    logger.warning(u"Bad certificate: %s", error)
1054
 
                    return
1055
 
                logger.debug(u"Fingerprint: %s", fpr)
1056
 
 
1057
 
                for c in self.server.clients:
1058
 
                    if c.fingerprint == fpr:
1059
 
                        client = c
1060
 
                        break
1061
 
                else:
1062
 
                    ipc.write(u"NOTFOUND %s %s\n"
1063
 
                              % (fpr, unicode(self.client_address)))
1064
 
                    return
1065
 
                
1066
 
                class ClientProxy(object):
1067
 
                    """Client proxy object.  Not for calling methods."""
1068
 
                    def __init__(self, client):
1069
 
                        self.client = client
1070
 
                    def __getattr__(self, name):
1071
 
                        if name.startswith("ipc_"):
1072
 
                            def tempfunc():
1073
 
                                ipc.write("%s %s\n" % (name[4:].upper(),
1074
 
                                                       self.client.name))
1075
 
                            return tempfunc
1076
 
                        if not hasattr(self.client, name):
1077
 
                            raise AttributeError
1078
 
                        ipc.write(u"GETATTR %s %s\n"
1079
 
                                  % (name, self.client.fingerprint))
1080
 
                        return pickle.load(ipc_return)
1081
 
                clientproxy = ClientProxy(client)
1082
 
                # Have to check if client.enabled, since it is
1083
 
                # possible that the client was disabled since the
1084
 
                # GnuTLS session was established.
1085
 
                if not clientproxy.enabled:
1086
 
                    clientproxy.ipc_disabled()
1087
 
                    return
1088
 
                
1089
 
                clientproxy.ipc_sending()
1090
 
                sent_size = 0
1091
 
                while sent_size < len(client.secret):
1092
 
                    sent = session.send(client.secret[sent_size:])
1093
 
                    logger.debug(u"Sent: %d, remaining: %d",
1094
 
                                 sent, len(client.secret)
1095
 
                                 - (sent_size + sent))
1096
 
                    sent_size += sent
1097
 
            finally:
1098
 
                session.bye()
 
802
                fpr = self.fingerprint(self.peer_certificate(session))
 
803
            except (TypeError, gnutls.errors.GNUTLSError), error:
 
804
                logger.warning(u"Bad certificate: %s", error)
 
805
                session.bye()
 
806
                return
 
807
            logger.debug(u"Fingerprint: %s", fpr)
 
808
            
 
809
            for c in self.server.clients:
 
810
                if c.fingerprint == fpr:
 
811
                    client = c
 
812
                    break
 
813
            else:
 
814
                ipc.write(u"NOTFOUND %s %s\n"
 
815
                          % (fpr, unicode(self.client_address)))
 
816
                session.bye()
 
817
                return
 
818
            # Have to check if client.still_valid(), since it is
 
819
            # possible that the client timed out while establishing
 
820
            # the GnuTLS session.
 
821
            if not client.still_valid():
 
822
                ipc.write(u"INVALID %s\n" % client.name)
 
823
                session.bye()
 
824
                return
 
825
            ipc.write(u"SENDING %s\n" % client.name)
 
826
            sent_size = 0
 
827
            while sent_size < len(client.secret):
 
828
                sent = session.send(client.secret[sent_size:])
 
829
                logger.debug(u"Sent: %d, remaining: %d",
 
830
                             sent, len(client.secret)
 
831
                             - (sent_size + sent))
 
832
                sent_size += sent
 
833
            session.bye()
1099
834
    
1100
835
    @staticmethod
1101
836
    def peer_certificate(session):
1161
896
        return hex_fpr
1162
897
 
1163
898
 
1164
 
class ForkingMixInWithPipes(socketserver.ForkingMixIn, object):
1165
 
    """Like socketserver.ForkingMixIn, but also pass a pipe pair."""
 
899
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
 
900
    """Like socketserver.ForkingMixIn, but also pass a pipe."""
1166
901
    def process_request(self, request, client_address):
1167
902
        """Overrides and wraps the original process_request().
1168
903
        
1169
904
        This function creates a new pipe in self.pipe
1170
905
        """
1171
 
        # Child writes to child_pipe
1172
 
        self.child_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1173
 
        # Parent writes to parent_pipe
1174
 
        self.parent_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1175
 
        super(ForkingMixInWithPipes,
 
906
        self.pipe = os.pipe()
 
907
        super(ForkingMixInWithPipe,
1176
908
              self).process_request(request, client_address)
1177
 
        # Close unused ends for parent
1178
 
        self.parent_pipe[0].close() # close read end
1179
 
        self.child_pipe[1].close()  # close write end
1180
 
        self.add_pipe_fds(self.child_pipe[0], self.parent_pipe[1])
1181
 
    def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
 
909
        os.close(self.pipe[1])  # close write end
 
910
        self.add_pipe(self.pipe[0])
 
911
    def add_pipe(self, pipe):
1182
912
        """Dummy function; override as necessary"""
1183
 
        child_pipe_fd.close()
1184
 
        parent_pipe_fd.close()
1185
 
 
1186
 
 
1187
 
class IPv6_TCPServer(ForkingMixInWithPipes,
 
913
        os.close(pipe)
 
914
 
 
915
 
 
916
class IPv6_TCPServer(ForkingMixInWithPipe,
1188
917
                     socketserver.TCPServer, object):
1189
918
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1190
919
    
1254
983
        clients:        set of Client objects
1255
984
        gnutls_priority GnuTLS priority string
1256
985
        use_dbus:       Boolean; to emit D-Bus signals or not
 
986
        clients:        set of Client objects
 
987
        gnutls_priority GnuTLS priority string
 
988
        use_dbus:       Boolean; to emit D-Bus signals or not
1257
989
    
1258
990
    Assumes a gobject.MainLoop event loop.
1259
991
    """
1275
1007
            return socketserver.TCPServer.server_activate(self)
1276
1008
    def enable(self):
1277
1009
        self.enabled = True
1278
 
    def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
 
1010
    def add_pipe(self, pipe):
1279
1011
        # Call "handle_ipc" for both data and EOF events
1280
 
        gobject.io_add_watch(child_pipe_fd.fileno(),
1281
 
                             gobject.IO_IN | gobject.IO_HUP,
1282
 
                             functools.partial(self.handle_ipc,
1283
 
                                               reply = parent_pipe_fd,
1284
 
                                               sender= child_pipe_fd))
1285
 
    def handle_ipc(self, source, condition, reply=None, sender=None):
 
1012
        gobject.io_add_watch(pipe, gobject.IO_IN | gobject.IO_HUP,
 
1013
                             self.handle_ipc)
 
1014
    def handle_ipc(self, source, condition, file_objects={}):
1286
1015
        condition_names = {
1287
1016
            gobject.IO_IN: u"IN",   # There is data to read.
1288
1017
            gobject.IO_OUT: u"OUT", # Data can be written (without
1300
1029
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1301
1030
                     conditions_string)
1302
1031
        
 
1032
        # Turn the pipe file descriptor into a Python file object
 
1033
        if source not in file_objects:
 
1034
            file_objects[source] = os.fdopen(source, u"r", 1)
 
1035
        
1303
1036
        # Read a line from the file object
1304
 
        cmdline = sender.readline()
 
1037
        cmdline = file_objects[source].readline()
1305
1038
        if not cmdline:             # Empty line means end of file
1306
 
            # close the IPC pipes
1307
 
            sender.close()
1308
 
            reply.close()
 
1039
            # close the IPC pipe
 
1040
            file_objects[source].close()
 
1041
            del file_objects[source]
1309
1042
            
1310
1043
            # Stop calling this function
1311
1044
            return False
1316
1049
        cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
1317
1050
        
1318
1051
        if cmd == u"NOTFOUND":
1319
 
            fpr, address = args.split(None, 1)
1320
 
            logger.warning(u"Client not found for fingerprint: %s, ad"
1321
 
                           u"dress: %s", fpr, address)
 
1052
            logger.warning(u"Client not found for fingerprint: %s",
 
1053
                           args)
1322
1054
            if self.use_dbus:
1323
1055
                # Emit D-Bus signal
1324
 
                mandos_dbus_service.ClientNotFound(fpr, address)
1325
 
        elif cmd == u"DISABLED":
 
1056
                mandos_dbus_service.ClientNotFound(args)
 
1057
        elif cmd == u"INVALID":
1326
1058
            for client in self.clients:
1327
1059
                if client.name == args:
1328
 
                    logger.warning(u"Client %s is disabled", args)
 
1060
                    logger.warning(u"Client %s is invalid", args)
1329
1061
                    if self.use_dbus:
1330
1062
                        # Emit D-Bus signal
1331
1063
                        client.Rejected()
1332
1064
                    break
1333
1065
            else:
1334
 
                logger.error(u"Unknown client %s is disabled", args)
 
1066
                logger.error(u"Unknown client %s is invalid", args)
1335
1067
        elif cmd == u"SENDING":
1336
1068
            for client in self.clients:
1337
1069
                if client.name == args:
1339
1071
                    client.checked_ok()
1340
1072
                    if self.use_dbus:
1341
1073
                        # Emit D-Bus signal
1342
 
                        client.GotSecret()
 
1074
                        client.ReceivedSecret()
1343
1075
                    break
1344
1076
            else:
1345
1077
                logger.error(u"Sending secret to unknown client %s",
1346
1078
                             args)
1347
 
        elif cmd == u"GETATTR":
1348
 
            attr_name, fpr = args.split(None, 1)
1349
 
            for client in self.clients:
1350
 
                if client.fingerprint == fpr:
1351
 
                    attr_value = getattr(client, attr_name, None)
1352
 
                    logger.debug("IPC reply: %r", attr_value)
1353
 
                    pickle.dump(attr_value, reply)
1354
 
                    break
1355
 
            else:
1356
 
                logger.error(u"Client %s on address %s requesting "
1357
 
                             u"attribute %s not found", fpr, address,
1358
 
                             attr_name)
1359
 
                pickle.dump(None, reply)
1360
1079
        else:
1361
1080
            logger.error(u"Unknown IPC command: %r", cmdline)
1362
1081
        
1396
1115
            elif suffix == u"w":
1397
1116
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1398
1117
            else:
1399
 
                raise ValueError(u"Unknown suffix %r" % suffix)
1400
 
        except (ValueError, IndexError), e:
1401
 
            raise ValueError(e.message)
 
1118
                raise ValueError
 
1119
        except (ValueError, IndexError):
 
1120
            raise ValueError
1402
1121
        timevalue += delta
1403
1122
    return timevalue
1404
1123
 
1417
1136
        def if_nametoindex(interface):
1418
1137
            "Get an interface index the hard way, i.e. using fcntl()"
1419
1138
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1420
 
            with contextlib.closing(socket.socket()) as s:
 
1139
            with closing(socket.socket()) as s:
1421
1140
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1422
1141
                                    struct.pack(str(u"16s16x"),
1423
1142
                                                interface))
1443
1162
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1444
1163
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1445
1164
            raise OSError(errno.ENODEV,
1446
 
                          u"%s not a character device"
1447
 
                          % os.path.devnull)
 
1165
                          u"/dev/null not a character device")
1448
1166
        os.dup2(null, sys.stdin.fileno())
1449
1167
        os.dup2(null, sys.stdout.fileno())
1450
1168
        os.dup2(null, sys.stderr.fileno())
1454
1172
 
1455
1173
def main():
1456
1174
    
1457
 
    ##################################################################
 
1175
    ######################################################################
1458
1176
    # Parsing of options, both command line and config file
1459
1177
    
1460
1178
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1565
1283
    tcp_server = MandosServer((server_settings[u"address"],
1566
1284
                               server_settings[u"port"]),
1567
1285
                              ClientHandler,
1568
 
                              interface=(server_settings[u"interface"]
1569
 
                                         or None),
 
1286
                              interface=server_settings[u"interface"],
1570
1287
                              use_ipv6=use_ipv6,
1571
1288
                              gnutls_priority=
1572
1289
                              server_settings[u"priority"],
1618
1335
    bus = dbus.SystemBus()
1619
1336
    # End of Avahi example code
1620
1337
    if use_dbus:
1621
 
        try:
1622
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1623
 
                                            bus, do_not_queue=True)
1624
 
        except dbus.exceptions.NameExistsException, e:
1625
 
            logger.error(unicode(e) + u", disabling D-Bus")
1626
 
            use_dbus = False
1627
 
            server_settings[u"use_dbus"] = False
1628
 
            tcp_server.use_dbus = False
 
1338
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1629
1339
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1630
1340
    service = AvahiService(name = server_settings[u"servicename"],
1631
1341
                           servicetype = u"_mandos._tcp",
1657
1367
        daemon()
1658
1368
    
1659
1369
    try:
1660
 
        with pidfile:
 
1370
        with closing(pidfile):
1661
1371
            pid = os.getpid()
1662
1372
            pidfile.write(str(pid) + "\n")
1663
1373
        del pidfile
1669
1379
        pass
1670
1380
    del pidfilename
1671
1381
    
 
1382
    def cleanup():
 
1383
        "Cleanup function; run on exit"
 
1384
        service.cleanup()
 
1385
        
 
1386
        while tcp_server.clients:
 
1387
            client = tcp_server.clients.pop()
 
1388
            client.disable_hook = None
 
1389
            client.disable()
 
1390
    
 
1391
    atexit.register(cleanup)
 
1392
    
1672
1393
    if not debug:
1673
1394
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1674
1395
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1681
1402
                dbus.service.Object.__init__(self, bus, u"/")
1682
1403
            _interface = u"se.bsnet.fukt.Mandos"
1683
1404
            
1684
 
            @dbus.service.signal(_interface, signature=u"o")
1685
 
            def ClientAdded(self, objpath):
 
1405
            @dbus.service.signal(_interface, signature=u"oa{sv}")
 
1406
            def ClientAdded(self, objpath, properties):
1686
1407
                "D-Bus signal"
1687
1408
                pass
1688
1409
            
1689
 
            @dbus.service.signal(_interface, signature=u"ss")
1690
 
            def ClientNotFound(self, fingerprint, address):
 
1410
            @dbus.service.signal(_interface, signature=u"s")
 
1411
            def ClientNotFound(self, fingerprint):
1691
1412
                "D-Bus signal"
1692
1413
                pass
1693
1414
            
1707
1428
            def GetAllClientsWithProperties(self):
1708
1429
                "D-Bus method"
1709
1430
                return dbus.Dictionary(
1710
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1431
                    ((c.dbus_object_path, c.GetAllProperties())
1711
1432
                     for c in tcp_server.clients),
1712
1433
                    signature=u"oa{sv}")
1713
1434
            
1719
1440
                        tcp_server.clients.remove(c)
1720
1441
                        c.remove_from_connection()
1721
1442
                        # Don't signal anything except ClientRemoved
1722
 
                        c.disable(quiet=True)
 
1443
                        c.disable(signal=False)
1723
1444
                        # Emit D-Bus signal
1724
1445
                        self.ClientRemoved(object_path, c.name)
1725
1446
                        return
1726
 
                raise KeyError(object_path)
 
1447
                raise KeyError
1727
1448
            
1728
1449
            del _interface
1729
1450
        
1730
1451
        mandos_dbus_service = MandosDBusService()
1731
1452
    
1732
 
    def cleanup():
1733
 
        "Cleanup function; run on exit"
1734
 
        service.cleanup()
1735
 
        
1736
 
        while tcp_server.clients:
1737
 
            client = tcp_server.clients.pop()
1738
 
            if use_dbus:
1739
 
                client.remove_from_connection()
1740
 
            client.disable_hook = None
1741
 
            # Don't signal anything except ClientRemoved
1742
 
            client.disable(quiet=True)
1743
 
            if use_dbus:
1744
 
                # Emit D-Bus signal
1745
 
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1746
 
                                                  client.name)
1747
 
    
1748
 
    atexit.register(cleanup)
1749
 
    
1750
1453
    for client in tcp_server.clients:
1751
1454
        if use_dbus:
1752
1455
            # Emit D-Bus signal
1753
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
1456
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1457
                                            client.GetAllProperties())
1754
1458
        client.enable()
1755
1459
    
1756
1460
    tcp_server.enable()
1774
1478
            service.activate()
1775
1479
        except dbus.exceptions.DBusException, error:
1776
1480
            logger.critical(u"DBusException: %s", error)
1777
 
            cleanup()
1778
1481
            sys.exit(1)
1779
1482
        # End of Avahi example code
1780
1483
        
1787
1490
        main_loop.run()
1788
1491
    except AvahiError, error:
1789
1492
        logger.critical(u"AvahiError: %s", error)
1790
 
        cleanup()
1791
1493
        sys.exit(1)
1792
1494
    except KeyboardInterrupt:
1793
1495
        if debug:
1794
1496
            print >> sys.stderr
1795
1497
        logger.debug(u"Server received KeyboardInterrupt")
1796
1498
    logger.debug(u"Server exiting")
1797
 
    # Must run before the D-Bus bus name gets deregistered
1798
 
    cleanup()
1799
1499
 
1800
1500
if __name__ == '__main__':
1801
1501
    main()