/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

Merge in branch to interpret an empty device name to mean
"autodetect".

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
 
from contextlib import closing
 
58
import contextlib
59
59
import struct
60
60
import fcntl
61
61
import functools
 
62
import cPickle as pickle
 
63
import select
62
64
 
63
65
import dbus
64
66
import dbus.service
67
69
from dbus.mainloop.glib import DBusGMainLoop
68
70
import ctypes
69
71
import ctypes.util
 
72
import xml.dom.minidom
 
73
import inspect
70
74
 
71
75
try:
72
76
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
77
81
        SO_BINDTODEVICE = None
78
82
 
79
83
 
80
 
version = "1.0.11"
 
84
version = "1.0.14"
81
85
 
82
86
logger = logging.Logger(u'mandos')
83
87
syslogger = (logging.handlers.SysLogHandler
174
178
                                    self.server.EntryGroupNew()),
175
179
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
176
180
            self.group.connect_to_signal('StateChanged',
177
 
                                         self.entry_group_state_changed)
 
181
                                         self
 
182
                                         .entry_group_state_changed)
178
183
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
179
184
                     self.name, self.type)
180
185
        self.group.AddService(
188
193
        self.group.Commit()
189
194
    def entry_group_state_changed(self, state, error):
190
195
        """Derived from the Avahi example code"""
191
 
        logger.debug(u"Avahi state change: %i", state)
 
196
        logger.debug(u"Avahi entry group state change: %i", state)
192
197
        
193
198
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
194
199
            logger.debug(u"Zeroconf service established.")
207
212
            self.group = None
208
213
    def server_state_changed(self, state):
209
214
        """Derived from the Avahi example code"""
 
215
        logger.debug(u"Avahi server state change: %i", state)
210
216
        if state == avahi.SERVER_COLLISION:
211
217
            logger.error(u"Zeroconf server name collision")
212
218
            self.remove()
239
245
    enabled:    bool()
240
246
    last_checked_ok: datetime.datetime(); (UTC) or None
241
247
    timeout:    datetime.timedelta(); How long from last_checked_ok
242
 
                                      until this client is invalid
 
248
                                      until this client is disabled
243
249
    interval:   datetime.timedelta(); How often to start a new checker
244
250
    disable_hook:  If set, called by disable() as disable_hook(self)
245
251
    checker:    subprocess.Popen(); a running checker process used
246
252
                                    to see if the client lives.
247
253
                                    'None' if no process is running.
248
254
    checker_initiator_tag: a gobject event source tag, or None
249
 
    disable_initiator_tag:    - '' -
 
255
    disable_initiator_tag: - '' -
250
256
    checker_callback_tag:  - '' -
251
257
    checker_command: string; External command which is run to check if
252
258
                     client lives.  %() expansions are done at
256
262
    """
257
263
    
258
264
    @staticmethod
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))
 
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))
264
270
    
265
271
    def timeout_milliseconds(self):
266
272
        "Return the 'timeout' attribute in milliseconds"
267
 
        return self._datetime_to_milliseconds(self.timeout)
 
273
        return self._timedelta_to_milliseconds(self.timeout)
268
274
    
269
275
    def interval_milliseconds(self):
270
276
        "Return the 'interval' attribute in milliseconds"
271
 
        return self._datetime_to_milliseconds(self.interval)
 
277
        return self._timedelta_to_milliseconds(self.interval)
272
278
    
273
279
    def __init__(self, name = None, disable_hook=None, config=None):
274
280
        """Note: the 'checker' key in 'config' sets the
287
293
        if u"secret" in config:
288
294
            self.secret = config[u"secret"].decode(u"base64")
289
295
        elif u"secfile" in config:
290
 
            with closing(open(os.path.expanduser
291
 
                              (os.path.expandvars
292
 
                               (config[u"secfile"])))) as secfile:
 
296
            with open(os.path.expanduser(os.path.expandvars
 
297
                                         (config[u"secfile"])),
 
298
                      "rb") as secfile:
293
299
                self.secret = secfile.read()
294
300
        else:
295
301
            raise TypeError(u"No secret or secfile for client %s"
321
327
        self.checker_initiator_tag = (gobject.timeout_add
322
328
                                      (self.interval_milliseconds(),
323
329
                                       self.start_checker))
324
 
        # Also start a new checker *right now*.
325
 
        self.start_checker()
326
330
        # Schedule a disable() when 'timeout' has passed
327
331
        self.disable_initiator_tag = (gobject.timeout_add
328
332
                                   (self.timeout_milliseconds(),
329
333
                                    self.disable))
330
334
        self.enabled = True
 
335
        # Also start a new checker *right now*.
 
336
        self.start_checker()
331
337
    
332
 
    def disable(self):
 
338
    def disable(self, quiet=True):
333
339
        """Disable this client."""
334
340
        if not getattr(self, "enabled", False):
335
341
            return False
336
 
        logger.info(u"Disabling client %s", self.name)
 
342
        if not quiet:
 
343
            logger.info(u"Disabling client %s", self.name)
337
344
        if getattr(self, u"disable_initiator_tag", False):
338
345
            gobject.source_remove(self.disable_initiator_tag)
339
346
            self.disable_initiator_tag = None
391
398
        # client would inevitably timeout, since no checker would get
392
399
        # a chance to run to completion.  If we instead leave running
393
400
        # checkers alone, the checker would have to take more time
394
 
        # than 'timeout' for the client to be declared invalid, which
395
 
        # is as it should be.
 
401
        # than 'timeout' for the client to be disabled, which is as it
 
402
        # should be.
396
403
        
397
404
        # If a checker exists, make sure it is not a zombie
398
 
        if self.checker is not None:
 
405
        try:
399
406
            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:
400
412
            if pid:
401
413
                logger.warning(u"Checker was a zombie")
402
414
                gobject.source_remove(self.checker_callback_tag)
458
470
        logger.debug(u"Stopping checker for %(name)s", vars(self))
459
471
        try:
460
472
            os.kill(self.checker.pid, signal.SIGTERM)
461
 
            #os.sleep(0.5)
 
473
            #time.sleep(0.5)
462
474
            #if self.checker.poll() is None:
463
475
            #    os.kill(self.checker.pid, signal.SIGKILL)
464
476
        except OSError, error:
465
477
            if error.errno != errno.ESRCH: # No such process
466
478
                raise
467
479
        self.checker = None
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):
 
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):
481
672
    """A Client class using D-Bus
482
673
    
483
674
    Attributes:
494
685
        self.dbus_object_path = (dbus.ObjectPath
495
686
                                 (u"/clients/"
496
687
                                  + self.name.replace(u".", u"_")))
497
 
        dbus.service.Object.__init__(self, self.bus,
498
 
                                     self.dbus_object_path)
 
688
        DBusObjectWithProperties.__init__(self, self.bus,
 
689
                                          self.dbus_object_path)
499
690
    
500
691
    @staticmethod
501
692
    def _datetime_to_dbus(dt, variant_level=0):
516
707
                                       variant_level=1))
517
708
        return r
518
709
    
519
 
    def disable(self, signal = True):
 
710
    def disable(self, quiet = False):
520
711
        oldstate = getattr(self, u"enabled", False)
521
 
        r = Client.disable(self)
522
 
        if signal and oldstate != self.enabled:
 
712
        r = Client.disable(self, quiet=quiet)
 
713
        if not quiet and oldstate != self.enabled:
523
714
            # Emit D-Bus signal
524
715
            self.PropertyChanged(dbus.String(u"enabled"),
525
716
                                 dbus.Boolean(False, variant_level=1))
530
721
            self.remove_from_connection()
531
722
        except LookupError:
532
723
            pass
533
 
        if hasattr(dbus.service.Object, u"__del__"):
534
 
            dbus.service.Object.__del__(self, *args, **kwargs)
 
724
        if hasattr(DBusObjectWithProperties, u"__del__"):
 
725
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
535
726
        Client.__del__(self, *args, **kwargs)
536
727
    
537
728
    def checker_callback(self, pid, condition, command,
591
782
                                 dbus.Boolean(False, variant_level=1))
592
783
        return r
593
784
    
594
 
    ## D-Bus methods & signals
 
785
    ## D-Bus methods, signals & properties
595
786
    _interface = u"se.bsnet.fukt.Mandos.Client"
596
787
    
597
 
    # CheckedOK - method
598
 
    @dbus.service.method(_interface)
599
 
    def CheckedOK(self):
600
 
        return self.checked_ok()
 
788
    ## Signals
601
789
    
602
790
    # CheckerCompleted - signal
603
791
    @dbus.service.signal(_interface, signature=u"nxs")
611
799
        "D-Bus signal"
612
800
        pass
613
801
    
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
 
    
662
802
    # PropertyChanged - signal
663
803
    @dbus.service.signal(_interface, signature=u"sv")
664
804
    def PropertyChanged(self, property, value):
665
805
        "D-Bus signal"
666
806
        pass
667
807
    
668
 
    # ReceivedSecret - signal
 
808
    # GotSecret - signal
669
809
    @dbus.service.signal(_interface)
670
 
    def ReceivedSecret(self):
 
810
    def GotSecret(self):
671
811
        "D-Bus signal"
672
812
        pass
673
813
    
677
817
        "D-Bus signal"
678
818
        pass
679
819
    
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)))
 
820
    ## Methods
 
821
    
 
822
    # CheckedOK - method
 
823
    @dbus.service.method(_interface)
 
824
    def CheckedOK(self):
 
825
        return self.checked_ok()
723
826
    
724
827
    # Enable - method
725
828
    @dbus.service.method(_interface)
744
847
    def StopChecker(self):
745
848
        self.stop_checker()
746
849
    
 
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
    
747
988
    del _interface
748
989
 
749
990
 
756
997
    def handle(self):
757
998
        logger.info(u"TCP connection from: %s",
758
999
                    unicode(self.client_address))
759
 
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
 
1000
        logger.debug(u"IPC Pipe FD: %d",
 
1001
                     self.server.child_pipe[1].fileno())
760
1002
        # Open IPC pipe to parent process
761
 
        with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
 
1003
        with contextlib.nested(self.server.child_pipe[1],
 
1004
                               self.server.parent_pipe[0]
 
1005
                               ) as (ipc, ipc_return):
762
1006
            session = (gnutls.connection
763
1007
                       .ClientSession(self.request,
764
1008
                                      gnutls.connection
765
1009
                                      .X509Credentials()))
766
1010
            
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
 
            
776
1011
            # Note: gnutls.connection.X509Credentials is really a
777
1012
            # generic GnuTLS certificate credentials object so long as
778
1013
            # no X.509 keys are added to it.  Therefore, we can use it
790
1025
             .gnutls_priority_set_direct(session._c_object,
791
1026
                                         priority, None))
792
1027
            
 
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
793
1040
            try:
794
1041
                session.handshake()
795
1042
            except gnutls.errors.GNUTLSError, error:
799
1046
                return
800
1047
            logger.debug(u"Handshake succeeded")
801
1048
            try:
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()
 
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()
834
1099
    
835
1100
    @staticmethod
836
1101
    def peer_certificate(session):
896
1161
        return hex_fpr
897
1162
 
898
1163
 
899
 
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
900
 
    """Like socketserver.ForkingMixIn, but also pass a pipe."""
 
1164
class ForkingMixInWithPipes(socketserver.ForkingMixIn, object):
 
1165
    """Like socketserver.ForkingMixIn, but also pass a pipe pair."""
901
1166
    def process_request(self, request, client_address):
902
1167
        """Overrides and wraps the original process_request().
903
1168
        
904
1169
        This function creates a new pipe in self.pipe
905
1170
        """
906
 
        self.pipe = os.pipe()
907
 
        super(ForkingMixInWithPipe,
 
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,
908
1176
              self).process_request(request, client_address)
909
 
        os.close(self.pipe[1])  # close write end
910
 
        self.add_pipe(self.pipe[0])
911
 
    def add_pipe(self, pipe):
 
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):
912
1182
        """Dummy function; override as necessary"""
913
 
        os.close(pipe)
914
 
 
915
 
 
916
 
class IPv6_TCPServer(ForkingMixInWithPipe,
 
1183
        child_pipe_fd.close()
 
1184
        parent_pipe_fd.close()
 
1185
 
 
1186
 
 
1187
class IPv6_TCPServer(ForkingMixInWithPipes,
917
1188
                     socketserver.TCPServer, object):
918
1189
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
919
1190
    
983
1254
        clients:        set of Client objects
984
1255
        gnutls_priority GnuTLS priority string
985
1256
        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
989
1257
    
990
1258
    Assumes a gobject.MainLoop event loop.
991
1259
    """
1007
1275
            return socketserver.TCPServer.server_activate(self)
1008
1276
    def enable(self):
1009
1277
        self.enabled = True
1010
 
    def add_pipe(self, pipe):
 
1278
    def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
1011
1279
        # Call "handle_ipc" for both data and EOF events
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={}):
 
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):
1015
1286
        condition_names = {
1016
1287
            gobject.IO_IN: u"IN",   # There is data to read.
1017
1288
            gobject.IO_OUT: u"OUT", # Data can be written (without
1029
1300
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1030
1301
                     conditions_string)
1031
1302
        
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
 
        
1036
1303
        # Read a line from the file object
1037
 
        cmdline = file_objects[source].readline()
 
1304
        cmdline = sender.readline()
1038
1305
        if not cmdline:             # Empty line means end of file
1039
 
            # close the IPC pipe
1040
 
            file_objects[source].close()
1041
 
            del file_objects[source]
 
1306
            # close the IPC pipes
 
1307
            sender.close()
 
1308
            reply.close()
1042
1309
            
1043
1310
            # Stop calling this function
1044
1311
            return False
1049
1316
        cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
1050
1317
        
1051
1318
        if cmd == u"NOTFOUND":
1052
 
            logger.warning(u"Client not found for fingerprint: %s",
1053
 
                           args)
 
1319
            fpr, address = args.split(None, 1)
 
1320
            logger.warning(u"Client not found for fingerprint: %s, ad"
 
1321
                           u"dress: %s", fpr, address)
1054
1322
            if self.use_dbus:
1055
1323
                # Emit D-Bus signal
1056
 
                mandos_dbus_service.ClientNotFound(args)
1057
 
        elif cmd == u"INVALID":
 
1324
                mandos_dbus_service.ClientNotFound(fpr, address)
 
1325
        elif cmd == u"DISABLED":
1058
1326
            for client in self.clients:
1059
1327
                if client.name == args:
1060
 
                    logger.warning(u"Client %s is invalid", args)
 
1328
                    logger.warning(u"Client %s is disabled", args)
1061
1329
                    if self.use_dbus:
1062
1330
                        # Emit D-Bus signal
1063
1331
                        client.Rejected()
1064
1332
                    break
1065
1333
            else:
1066
 
                logger.error(u"Unknown client %s is invalid", args)
 
1334
                logger.error(u"Unknown client %s is disabled", args)
1067
1335
        elif cmd == u"SENDING":
1068
1336
            for client in self.clients:
1069
1337
                if client.name == args:
1071
1339
                    client.checked_ok()
1072
1340
                    if self.use_dbus:
1073
1341
                        # Emit D-Bus signal
1074
 
                        client.ReceivedSecret()
 
1342
                        client.GotSecret()
1075
1343
                    break
1076
1344
            else:
1077
1345
                logger.error(u"Sending secret to unknown client %s",
1078
1346
                             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)
1079
1360
        else:
1080
1361
            logger.error(u"Unknown IPC command: %r", cmdline)
1081
1362
        
1115
1396
            elif suffix == u"w":
1116
1397
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1117
1398
            else:
1118
 
                raise ValueError
1119
 
        except (ValueError, IndexError):
1120
 
            raise ValueError
 
1399
                raise ValueError(u"Unknown suffix %r" % suffix)
 
1400
        except (ValueError, IndexError), e:
 
1401
            raise ValueError(e.message)
1121
1402
        timevalue += delta
1122
1403
    return timevalue
1123
1404
 
1136
1417
        def if_nametoindex(interface):
1137
1418
            "Get an interface index the hard way, i.e. using fcntl()"
1138
1419
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1139
 
            with closing(socket.socket()) as s:
 
1420
            with contextlib.closing(socket.socket()) as s:
1140
1421
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1141
1422
                                    struct.pack(str(u"16s16x"),
1142
1423
                                                interface))
1162
1443
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1163
1444
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1164
1445
            raise OSError(errno.ENODEV,
1165
 
                          u"/dev/null not a character device")
 
1446
                          u"%s not a character device"
 
1447
                          % os.path.devnull)
1166
1448
        os.dup2(null, sys.stdin.fileno())
1167
1449
        os.dup2(null, sys.stdout.fileno())
1168
1450
        os.dup2(null, sys.stderr.fileno())
1172
1454
 
1173
1455
def main():
1174
1456
    
1175
 
    ######################################################################
 
1457
    ##################################################################
1176
1458
    # Parsing of options, both command line and config file
1177
1459
    
1178
1460
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1196
1478
                      help=u"Directory to search for configuration"
1197
1479
                      u" files")
1198
1480
    parser.add_option("--no-dbus", action=u"store_false",
1199
 
                      dest=u"use_dbus",
1200
 
                      help=optparse.SUPPRESS_HELP) # XXX: Not done yet
 
1481
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
 
1482
                      u" system bus interface")
1201
1483
    parser.add_option("--no-ipv6", action=u"store_false",
1202
1484
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1203
1485
    options = parser.parse_args()[0]
1255
1537
    # For convenience
1256
1538
    debug = server_settings[u"debug"]
1257
1539
    use_dbus = server_settings[u"use_dbus"]
1258
 
    use_dbus = False            # XXX: Not done yet
1259
1540
    use_ipv6 = server_settings[u"use_ipv6"]
1260
1541
    
1261
1542
    if not debug:
1284
1565
    tcp_server = MandosServer((server_settings[u"address"],
1285
1566
                               server_settings[u"port"]),
1286
1567
                              ClientHandler,
1287
 
                              interface=server_settings[u"interface"],
 
1568
                              interface=(server_settings[u"interface"]
 
1569
                                         or None),
1288
1570
                              use_ipv6=use_ipv6,
1289
1571
                              gnutls_priority=
1290
1572
                              server_settings[u"priority"],
1336
1618
    bus = dbus.SystemBus()
1337
1619
    # End of Avahi example code
1338
1620
    if use_dbus:
1339
 
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
 
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
1340
1629
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1341
1630
    service = AvahiService(name = server_settings[u"servicename"],
1342
1631
                           servicetype = u"_mandos._tcp",
1368
1657
        daemon()
1369
1658
    
1370
1659
    try:
1371
 
        with closing(pidfile):
 
1660
        with pidfile:
1372
1661
            pid = os.getpid()
1373
1662
            pidfile.write(str(pid) + "\n")
1374
1663
        del pidfile
1380
1669
        pass
1381
1670
    del pidfilename
1382
1671
    
1383
 
    def cleanup():
1384
 
        "Cleanup function; run on exit"
1385
 
        service.cleanup()
1386
 
        
1387
 
        while tcp_server.clients:
1388
 
            client = tcp_server.clients.pop()
1389
 
            client.disable_hook = None
1390
 
            client.disable()
1391
 
    
1392
 
    atexit.register(cleanup)
1393
 
    
1394
1672
    if not debug:
1395
1673
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1396
1674
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1403
1681
                dbus.service.Object.__init__(self, bus, u"/")
1404
1682
            _interface = u"se.bsnet.fukt.Mandos"
1405
1683
            
1406
 
            @dbus.service.signal(_interface, signature=u"oa{sv}")
1407
 
            def ClientAdded(self, objpath, properties):
 
1684
            @dbus.service.signal(_interface, signature=u"o")
 
1685
            def ClientAdded(self, objpath):
1408
1686
                "D-Bus signal"
1409
1687
                pass
1410
1688
            
1411
 
            @dbus.service.signal(_interface, signature=u"s")
1412
 
            def ClientNotFound(self, fingerprint):
 
1689
            @dbus.service.signal(_interface, signature=u"ss")
 
1690
            def ClientNotFound(self, fingerprint, address):
1413
1691
                "D-Bus signal"
1414
1692
                pass
1415
1693
            
1429
1707
            def GetAllClientsWithProperties(self):
1430
1708
                "D-Bus method"
1431
1709
                return dbus.Dictionary(
1432
 
                    ((c.dbus_object_path, c.GetAllProperties())
 
1710
                    ((c.dbus_object_path, c.GetAll(u""))
1433
1711
                     for c in tcp_server.clients),
1434
1712
                    signature=u"oa{sv}")
1435
1713
            
1441
1719
                        tcp_server.clients.remove(c)
1442
1720
                        c.remove_from_connection()
1443
1721
                        # Don't signal anything except ClientRemoved
1444
 
                        c.disable(signal=False)
 
1722
                        c.disable(quiet=True)
1445
1723
                        # Emit D-Bus signal
1446
1724
                        self.ClientRemoved(object_path, c.name)
1447
1725
                        return
1448
 
                raise KeyError
 
1726
                raise KeyError(object_path)
1449
1727
            
1450
1728
            del _interface
1451
1729
        
1452
1730
        mandos_dbus_service = MandosDBusService()
1453
1731
    
 
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
    
1454
1750
    for client in tcp_server.clients:
1455
1751
        if use_dbus:
1456
1752
            # Emit D-Bus signal
1457
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
1458
 
                                            client.GetAllProperties())
 
1753
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
1459
1754
        client.enable()
1460
1755
    
1461
1756
    tcp_server.enable()
1479
1774
            service.activate()
1480
1775
        except dbus.exceptions.DBusException, error:
1481
1776
            logger.critical(u"DBusException: %s", error)
 
1777
            cleanup()
1482
1778
            sys.exit(1)
1483
1779
        # End of Avahi example code
1484
1780
        
1491
1787
        main_loop.run()
1492
1788
    except AvahiError, error:
1493
1789
        logger.critical(u"AvahiError: %s", error)
 
1790
        cleanup()
1494
1791
        sys.exit(1)
1495
1792
    except KeyboardInterrupt:
1496
1793
        if debug:
1497
1794
            print >> sys.stderr
1498
1795
        logger.debug(u"Server received KeyboardInterrupt")
1499
1796
    logger.debug(u"Server exiting")
 
1797
    # Must run before the D-Bus bus name gets deregistered
 
1798
    cleanup()
1500
1799
 
1501
1800
if __name__ == '__main__':
1502
1801
    main()