/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: 2011-04-02 06:37:18 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110402063718-13ldrcuu0t33sdc4
* mandos: Tolerate restarting Avahi servers.  Also Changed to new
          "except x as y" exception syntax.
  (AvahiService.entry_group_state_changed_match): New; contains the
                                                  SignalMatch object.
  (AvahiService.remove): Really remove the group and the signal
                         connection, if any.
  (AvahiService.add): Always create a new group and signal connection.
  (AvahiService.cleanup): Changed to simply call remove().
  (AvahiService.server_state_changed): Handle and log more bad states.
  (AvahiService.activate): Set "follow_name_owner_changes=True" on the
                           Avahi Server proxy object.
  (ClientDBus.checked_ok): Do not return anything.
  (ClientDBus.CheckedOK): Do not return anything, as documented.
* mandos-monitor: Call D-Bus methods asynchronously.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
# along with this program.  If not, see
29
29
# <http://www.gnu.org/licenses/>.
30
30
31
 
# Contact the authors at <mandos@recompile.se>.
 
31
# Contact the authors at <mandos@fukt.bsnet.se>.
32
32
33
33
 
34
34
from __future__ import (division, absolute_import, print_function,
62
62
import functools
63
63
import cPickle as pickle
64
64
import multiprocessing
65
 
import types
66
65
 
67
66
import dbus
68
67
import dbus.service
83
82
        SO_BINDTODEVICE = None
84
83
 
85
84
 
86
 
version = "1.4.1"
 
85
version = "1.3.0"
87
86
 
88
87
#logger = logging.getLogger('mandos')
89
88
logger = logging.Logger('mandos')
160
159
                            " after %i retries, exiting.",
161
160
                            self.rename_count)
162
161
            raise AvahiServiceError("Too many renames")
163
 
        self.name = unicode(self.server
164
 
                            .GetAlternativeServiceName(self.name))
 
162
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
165
163
        logger.info("Changing Zeroconf service name to %r ...",
166
164
                    self.name)
167
165
        syslogger.setFormatter(logging.Formatter
178
176
        self.rename_count += 1
179
177
    def remove(self):
180
178
        """Derived from the Avahi example code"""
 
179
        if self.group is not None:
 
180
            try:
 
181
                self.group.Free()
 
182
            except (dbus.exceptions.UnknownMethodException,
 
183
                    dbus.exceptions.DBusException) as e:
 
184
                pass
 
185
            self.group = None
181
186
        if self.entry_group_state_changed_match is not None:
182
187
            self.entry_group_state_changed_match.remove()
183
188
            self.entry_group_state_changed_match = None
184
 
        if self.group is not None:
185
 
            self.group.Reset()
186
189
    def add(self):
187
190
        """Derived from the Avahi example code"""
188
191
        self.remove()
189
 
        if self.group is None:
190
 
            self.group = dbus.Interface(
191
 
                self.bus.get_object(avahi.DBUS_NAME,
192
 
                                    self.server.EntryGroupNew()),
193
 
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
192
        self.group = dbus.Interface(
 
193
            self.bus.get_object(avahi.DBUS_NAME,
 
194
                                self.server.EntryGroupNew(),
 
195
                                follow_name_owner_changes=True),
 
196
            avahi.DBUS_INTERFACE_ENTRY_GROUP)
194
197
        self.entry_group_state_changed_match = (
195
198
            self.group.connect_to_signal(
196
199
                'StateChanged', self .entry_group_state_changed))
221
224
                                  % unicode(error))
222
225
    def cleanup(self):
223
226
        """Derived from the Avahi example code"""
224
 
        if self.group is not None:
225
 
            try:
226
 
                self.group.Free()
227
 
            except (dbus.exceptions.UnknownMethodException,
228
 
                    dbus.exceptions.DBusException) as e:
229
 
                pass
230
 
            self.group = None
231
227
        self.remove()
232
228
    def server_state_changed(self, state, error=None):
233
229
        """Derived from the Avahi example code"""
240
236
                       avahi.SERVER_FAILURE:
241
237
                           "Zeroconf server failure" }
242
238
        if state in bad_states:
243
 
            if bad_states[state] is not None:
244
 
                if error is None:
245
 
                    logger.error(bad_states[state])
246
 
                else:
247
 
                    logger.error(bad_states[state] + ": %r", error)
248
 
            self.cleanup()
 
239
            if bad_states[state]:
 
240
                logger.error(bad_states[state])
 
241
            self.remove()
249
242
        elif state == avahi.SERVER_RUNNING:
250
243
            self.add()
251
244
        else:
252
 
            if error is None:
253
 
                logger.debug("Unknown state: %r", state)
254
 
            else:
255
 
                logger.debug("Unknown state: %r: %r", state, error)
 
245
            logger.debug("Unknown state: %r", state)
256
246
    def activate(self):
257
247
        """Derived from the Avahi example code"""
258
248
        if self.server is None:
266
256
        self.server_state_changed(self.server.GetState())
267
257
 
268
258
 
269
 
def _timedelta_to_milliseconds(td):
270
 
    "Convert a datetime.timedelta() to milliseconds"
271
 
    return ((td.days * 24 * 60 * 60 * 1000)
272
 
            + (td.seconds * 1000)
273
 
            + (td.microseconds // 1000))
274
 
        
275
259
class Client(object):
276
260
    """A representation of a client host served by this server.
277
261
    
305
289
    secret:     bytestring; sent verbatim (over TLS) to client
306
290
    timeout:    datetime.timedelta(); How long from last_checked_ok
307
291
                                      until this client is disabled
308
 
    extended_timeout:   extra long timeout when password has been sent
309
292
    runtime_expansions: Allowed attributes for runtime expansion.
310
 
    expires:    datetime.datetime(); time (UTC) when a client will be
311
 
                disabled, or None
312
293
    """
313
294
    
314
295
    runtime_expansions = ("approval_delay", "approval_duration",
316
297
                          "host", "interval", "last_checked_ok",
317
298
                          "last_enabled", "name", "timeout")
318
299
    
 
300
    @staticmethod
 
301
    def _timedelta_to_milliseconds(td):
 
302
        "Convert a datetime.timedelta() to milliseconds"
 
303
        return ((td.days * 24 * 60 * 60 * 1000)
 
304
                + (td.seconds * 1000)
 
305
                + (td.microseconds // 1000))
 
306
    
319
307
    def timeout_milliseconds(self):
320
308
        "Return the 'timeout' attribute in milliseconds"
321
 
        return _timedelta_to_milliseconds(self.timeout)
322
 
    
323
 
    def extended_timeout_milliseconds(self):
324
 
        "Return the 'extended_timeout' attribute in milliseconds"
325
 
        return _timedelta_to_milliseconds(self.extended_timeout)
 
309
        return self._timedelta_to_milliseconds(self.timeout)
326
310
    
327
311
    def interval_milliseconds(self):
328
312
        "Return the 'interval' attribute in milliseconds"
329
 
        return _timedelta_to_milliseconds(self.interval)
330
 
    
 
313
        return self._timedelta_to_milliseconds(self.interval)
 
314
 
331
315
    def approval_delay_milliseconds(self):
332
 
        return _timedelta_to_milliseconds(self.approval_delay)
 
316
        return self._timedelta_to_milliseconds(self.approval_delay)
333
317
    
334
318
    def __init__(self, name = None, disable_hook=None, config=None):
335
319
        """Note: the 'checker' key in 'config' sets the
362
346
        self.last_enabled = None
363
347
        self.last_checked_ok = None
364
348
        self.timeout = string_to_delta(config["timeout"])
365
 
        self.extended_timeout = string_to_delta(config
366
 
                                                ["extended_timeout"])
367
349
        self.interval = string_to_delta(config["interval"])
368
350
        self.disable_hook = disable_hook
369
351
        self.checker = None
370
352
        self.checker_initiator_tag = None
371
353
        self.disable_initiator_tag = None
372
 
        self.expires = None
373
354
        self.checker_callback_tag = None
374
355
        self.checker_command = config["checker"]
375
356
        self.current_checker_command = None
382
363
            config["approval_delay"])
383
364
        self.approval_duration = string_to_delta(
384
365
            config["approval_duration"])
385
 
        self.changedstate = (multiprocessing_manager
386
 
                             .Condition(multiprocessing_manager
387
 
                                        .Lock()))
 
366
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
388
367
    
389
368
    def send_changedstate(self):
390
369
        self.changedstate.acquire()
391
370
        self.changedstate.notify_all()
392
371
        self.changedstate.release()
393
 
    
 
372
        
394
373
    def enable(self):
395
374
        """Start this client's checker and timeout hooks"""
396
375
        if getattr(self, "enabled", False):
397
376
            # Already enabled
398
377
            return
399
378
        self.send_changedstate()
 
379
        self.last_enabled = datetime.datetime.utcnow()
400
380
        # Schedule a new checker to be started an 'interval' from now,
401
381
        # and every interval from then on.
402
382
        self.checker_initiator_tag = (gobject.timeout_add
403
383
                                      (self.interval_milliseconds(),
404
384
                                       self.start_checker))
405
385
        # Schedule a disable() when 'timeout' has passed
406
 
        self.expires = datetime.datetime.utcnow() + self.timeout
407
386
        self.disable_initiator_tag = (gobject.timeout_add
408
387
                                   (self.timeout_milliseconds(),
409
388
                                    self.disable))
410
389
        self.enabled = True
411
 
        self.last_enabled = datetime.datetime.utcnow()
412
390
        # Also start a new checker *right now*.
413
391
        self.start_checker()
414
392
    
423
401
        if getattr(self, "disable_initiator_tag", False):
424
402
            gobject.source_remove(self.disable_initiator_tag)
425
403
            self.disable_initiator_tag = None
426
 
        self.expires = None
427
404
        if getattr(self, "checker_initiator_tag", False):
428
405
            gobject.source_remove(self.checker_initiator_tag)
429
406
            self.checker_initiator_tag = None
455
432
            logger.warning("Checker for %(name)s crashed?",
456
433
                           vars(self))
457
434
    
458
 
    def checked_ok(self, timeout=None):
 
435
    def checked_ok(self):
459
436
        """Bump up the timeout for this client.
460
437
        
461
438
        This should only be called when the client has been seen,
462
439
        alive and well.
463
440
        """
464
 
        if timeout is None:
465
 
            timeout = self.timeout
466
441
        self.last_checked_ok = datetime.datetime.utcnow()
467
 
        if self.disable_initiator_tag is not None:
468
 
            gobject.source_remove(self.disable_initiator_tag)
469
 
        if getattr(self, "enabled", False):
470
 
            self.disable_initiator_tag = (gobject.timeout_add
471
 
                                          (_timedelta_to_milliseconds
472
 
                                           (timeout), self.disable))
473
 
            self.expires = datetime.datetime.utcnow() + timeout
 
442
        gobject.source_remove(self.disable_initiator_tag)
 
443
        self.disable_initiator_tag = (gobject.timeout_add
 
444
                                      (self.timeout_milliseconds(),
 
445
                                       self.disable))
474
446
    
475
447
    def need_approval(self):
476
448
        self.last_approval_request = datetime.datetime.utcnow()
516
488
                                       'replace')))
517
489
                    for attr in
518
490
                    self.runtime_expansions)
519
 
                
 
491
 
520
492
                try:
521
493
                    command = self.checker_command % escaped_attrs
522
494
                except TypeError as error:
568
540
                raise
569
541
        self.checker = None
570
542
 
571
 
 
572
543
def dbus_service_property(dbus_interface, signature="v",
573
544
                          access="readwrite", byte_arrays=False):
574
545
    """Decorators for marking methods of a DBusObjectWithProperties to
620
591
 
621
592
class DBusObjectWithProperties(dbus.service.Object):
622
593
    """A D-Bus object with properties.
623
 
    
 
594
 
624
595
    Classes inheriting from this can use the dbus_service_property
625
596
    decorator to expose methods as D-Bus properties.  It exposes the
626
597
    standard Get(), Set(), and GetAll() methods on the D-Bus.
633
604
    def _get_all_dbus_properties(self):
634
605
        """Returns a generator of (name, attribute) pairs
635
606
        """
636
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
637
 
                for cls in self.__class__.__mro__
 
607
        return ((prop._dbus_name, prop)
638
608
                for name, prop in
639
 
                inspect.getmembers(cls, self._is_dbus_property))
 
609
                inspect.getmembers(self, self._is_dbus_property))
640
610
    
641
611
    def _get_dbus_property(self, interface_name, property_name):
642
612
        """Returns a bound method if one exists which is a D-Bus
643
613
        property with the specified name and interface.
644
614
        """
645
 
        for cls in  self.__class__.__mro__:
646
 
            for name, value in (inspect.getmembers
647
 
                                (cls, self._is_dbus_property)):
648
 
                if (value._dbus_name == property_name
649
 
                    and value._dbus_interface == interface_name):
650
 
                    return value.__get__(self)
651
 
        
 
615
        for name in (property_name,
 
616
                     property_name + "_dbus_property"):
 
617
            prop = getattr(self, name, None)
 
618
            if (prop is None
 
619
                or not self._is_dbus_property(prop)
 
620
                or prop._dbus_name != property_name
 
621
                or (interface_name and prop._dbus_interface
 
622
                    and interface_name != prop._dbus_interface)):
 
623
                continue
 
624
            return prop
652
625
        # No such property
653
626
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
654
627
                                   + interface_name + "."
688
661
    def GetAll(self, interface_name):
689
662
        """Standard D-Bus property GetAll() method, see D-Bus
690
663
        standard.
691
 
        
 
664
 
692
665
        Note: Will not include properties with access="write".
693
666
        """
694
667
        all = {}
756
729
        return xmlstring
757
730
 
758
731
 
759
 
def datetime_to_dbus (dt, variant_level=0):
760
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
761
 
    if dt is None:
762
 
        return dbus.String("", variant_level = variant_level)
763
 
    return dbus.String(dt.isoformat(),
764
 
                       variant_level=variant_level)
765
 
 
766
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
767
 
                                  .__metaclass__):
768
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
769
 
    will add additional D-Bus attributes matching a certain pattern.
770
 
    """
771
 
    def __new__(mcs, name, bases, attr):
772
 
        # Go through all the base classes which could have D-Bus
773
 
        # methods, signals, or properties in them
774
 
        for base in (b for b in bases
775
 
                     if issubclass(b, dbus.service.Object)):
776
 
            # Go though all attributes of the base class
777
 
            for attrname, attribute in inspect.getmembers(base):
778
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
779
 
                # with the wrong interface name
780
 
                if (not hasattr(attribute, "_dbus_interface")
781
 
                    or not attribute._dbus_interface
782
 
                    .startswith("se.recompile.Mandos")):
783
 
                    continue
784
 
                # Create an alternate D-Bus interface name based on
785
 
                # the current name
786
 
                alt_interface = (attribute._dbus_interface
787
 
                                 .replace("se.recompile.Mandos",
788
 
                                          "se.bsnet.fukt.Mandos"))
789
 
                # Is this a D-Bus signal?
790
 
                if getattr(attribute, "_dbus_is_signal", False):
791
 
                    # Extract the original non-method function by
792
 
                    # black magic
793
 
                    nonmethod_func = (dict(
794
 
                            zip(attribute.func_code.co_freevars,
795
 
                                attribute.__closure__))["func"]
796
 
                                      .cell_contents)
797
 
                    # Create a new, but exactly alike, function
798
 
                    # object, and decorate it to be a new D-Bus signal
799
 
                    # with the alternate D-Bus interface name
800
 
                    new_function = (dbus.service.signal
801
 
                                    (alt_interface,
802
 
                                     attribute._dbus_signature)
803
 
                                    (types.FunctionType(
804
 
                                nonmethod_func.func_code,
805
 
                                nonmethod_func.func_globals,
806
 
                                nonmethod_func.func_name,
807
 
                                nonmethod_func.func_defaults,
808
 
                                nonmethod_func.func_closure)))
809
 
                    # Define a creator of a function to call both the
810
 
                    # old and new functions, so both the old and new
811
 
                    # signals gets sent when the function is called
812
 
                    def fixscope(func1, func2):
813
 
                        """This function is a scope container to pass
814
 
                        func1 and func2 to the "call_both" function
815
 
                        outside of its arguments"""
816
 
                        def call_both(*args, **kwargs):
817
 
                            """This function will emit two D-Bus
818
 
                            signals by calling func1 and func2"""
819
 
                            func1(*args, **kwargs)
820
 
                            func2(*args, **kwargs)
821
 
                        return call_both
822
 
                    # Create the "call_both" function and add it to
823
 
                    # the class
824
 
                    attr[attrname] = fixscope(attribute,
825
 
                                              new_function)
826
 
                # Is this a D-Bus method?
827
 
                elif getattr(attribute, "_dbus_is_method", False):
828
 
                    # Create a new, but exactly alike, function
829
 
                    # object.  Decorate it to be a new D-Bus method
830
 
                    # with the alternate D-Bus interface name.  Add it
831
 
                    # to the class.
832
 
                    attr[attrname] = (dbus.service.method
833
 
                                      (alt_interface,
834
 
                                       attribute._dbus_in_signature,
835
 
                                       attribute._dbus_out_signature)
836
 
                                      (types.FunctionType
837
 
                                       (attribute.func_code,
838
 
                                        attribute.func_globals,
839
 
                                        attribute.func_name,
840
 
                                        attribute.func_defaults,
841
 
                                        attribute.func_closure)))
842
 
                # Is this a D-Bus property?
843
 
                elif getattr(attribute, "_dbus_is_property", False):
844
 
                    # Create a new, but exactly alike, function
845
 
                    # object, and decorate it to be a new D-Bus
846
 
                    # property with the alternate D-Bus interface
847
 
                    # name.  Add it to the class.
848
 
                    attr[attrname] = (dbus_service_property
849
 
                                      (alt_interface,
850
 
                                       attribute._dbus_signature,
851
 
                                       attribute._dbus_access,
852
 
                                       attribute
853
 
                                       ._dbus_get_args_options
854
 
                                       ["byte_arrays"])
855
 
                                      (types.FunctionType
856
 
                                       (attribute.func_code,
857
 
                                        attribute.func_globals,
858
 
                                        attribute.func_name,
859
 
                                        attribute.func_defaults,
860
 
                                        attribute.func_closure)))
861
 
        return type.__new__(mcs, name, bases, attr)
862
 
 
863
732
class ClientDBus(Client, DBusObjectWithProperties):
864
733
    """A Client class using D-Bus
865
734
    
887
756
        DBusObjectWithProperties.__init__(self, self.bus,
888
757
                                          self.dbus_object_path)
889
758
        
890
 
    def notifychangeproperty(transform_func,
891
 
                             dbus_name, type_func=lambda x: x,
892
 
                             variant_level=1):
893
 
        """ Modify a variable so that it's a property which announces
894
 
        its changes to DBus.
 
759
    def _get_approvals_pending(self):
 
760
        return self._approvals_pending
 
761
    def _set_approvals_pending(self, value):
 
762
        old_value = self._approvals_pending
 
763
        self._approvals_pending = value
 
764
        bval = bool(value)
 
765
        if (hasattr(self, "dbus_object_path")
 
766
            and bval is not bool(old_value)):
 
767
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
768
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
769
                                 dbus_bool)
895
770
 
896
 
        transform_fun: Function that takes a value and a variant_level
897
 
                       and transforms it to a D-Bus type.
898
 
        dbus_name: D-Bus name of the variable
899
 
        type_func: Function that transform the value before sending it
900
 
                   to the D-Bus.  Default: no transform
901
 
        variant_level: D-Bus variant level.  Default: 1
902
 
        """
903
 
        attrname = "_{0}".format(dbus_name)
904
 
        def setter(self, value):
905
 
            if hasattr(self, "dbus_object_path"):
906
 
                if (not hasattr(self, attrname) or
907
 
                    type_func(getattr(self, attrname, None))
908
 
                    != type_func(value)):
909
 
                    dbus_value = transform_func(type_func(value),
910
 
                                                variant_level
911
 
                                                =variant_level)
912
 
                    self.PropertyChanged(dbus.String(dbus_name),
913
 
                                         dbus_value)
914
 
            setattr(self, attrname, value)
915
 
        
916
 
        return property(lambda self: getattr(self, attrname), setter)
917
 
    
918
 
    
919
 
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
920
 
    approvals_pending = notifychangeproperty(dbus.Boolean,
921
 
                                             "ApprovalPending",
922
 
                                             type_func = bool)
923
 
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
924
 
    last_enabled = notifychangeproperty(datetime_to_dbus,
925
 
                                        "LastEnabled")
926
 
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
927
 
                                   type_func = lambda checker:
928
 
                                       checker is not None)
929
 
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
930
 
                                           "LastCheckedOK")
931
 
    last_approval_request = notifychangeproperty(
932
 
        datetime_to_dbus, "LastApprovalRequest")
933
 
    approved_by_default = notifychangeproperty(dbus.Boolean,
934
 
                                               "ApprovedByDefault")
935
 
    approval_delay = notifychangeproperty(dbus.UInt16,
936
 
                                          "ApprovalDelay",
937
 
                                          type_func =
938
 
                                          _timedelta_to_milliseconds)
939
 
    approval_duration = notifychangeproperty(
940
 
        dbus.UInt16, "ApprovalDuration",
941
 
        type_func = _timedelta_to_milliseconds)
942
 
    host = notifychangeproperty(dbus.String, "Host")
943
 
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
944
 
                                   type_func =
945
 
                                   _timedelta_to_milliseconds)
946
 
    extended_timeout = notifychangeproperty(
947
 
        dbus.UInt16, "ExtendedTimeout",
948
 
        type_func = _timedelta_to_milliseconds)
949
 
    interval = notifychangeproperty(dbus.UInt16,
950
 
                                    "Interval",
951
 
                                    type_func =
952
 
                                    _timedelta_to_milliseconds)
953
 
    checker_command = notifychangeproperty(dbus.String, "Checker")
954
 
    
955
 
    del notifychangeproperty
 
771
    approvals_pending = property(_get_approvals_pending,
 
772
                                 _set_approvals_pending)
 
773
    del _get_approvals_pending, _set_approvals_pending
 
774
    
 
775
    @staticmethod
 
776
    def _datetime_to_dbus(dt, variant_level=0):
 
777
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
778
        return dbus.String(dt.isoformat(),
 
779
                           variant_level=variant_level)
 
780
    
 
781
    def enable(self):
 
782
        oldstate = getattr(self, "enabled", False)
 
783
        r = Client.enable(self)
 
784
        if oldstate != self.enabled:
 
785
            # Emit D-Bus signals
 
786
            self.PropertyChanged(dbus.String("Enabled"),
 
787
                                 dbus.Boolean(True, variant_level=1))
 
788
            self.PropertyChanged(
 
789
                dbus.String("LastEnabled"),
 
790
                self._datetime_to_dbus(self.last_enabled,
 
791
                                       variant_level=1))
 
792
        return r
 
793
    
 
794
    def disable(self, quiet = False):
 
795
        oldstate = getattr(self, "enabled", False)
 
796
        r = Client.disable(self, quiet=quiet)
 
797
        if not quiet and oldstate != self.enabled:
 
798
            # Emit D-Bus signal
 
799
            self.PropertyChanged(dbus.String("Enabled"),
 
800
                                 dbus.Boolean(False, variant_level=1))
 
801
        return r
956
802
    
957
803
    def __del__(self, *args, **kwargs):
958
804
        try:
967
813
                         *args, **kwargs):
968
814
        self.checker_callback_tag = None
969
815
        self.checker = None
 
816
        # Emit D-Bus signal
 
817
        self.PropertyChanged(dbus.String("CheckerRunning"),
 
818
                             dbus.Boolean(False, variant_level=1))
970
819
        if os.WIFEXITED(condition):
971
820
            exitstatus = os.WEXITSTATUS(condition)
972
821
            # Emit D-Bus signal
982
831
        return Client.checker_callback(self, pid, condition, command,
983
832
                                       *args, **kwargs)
984
833
    
 
834
    def checked_ok(self, *args, **kwargs):
 
835
        Client.checked_ok(self, *args, **kwargs)
 
836
        # Emit D-Bus signal
 
837
        self.PropertyChanged(
 
838
            dbus.String("LastCheckedOK"),
 
839
            (self._datetime_to_dbus(self.last_checked_ok,
 
840
                                    variant_level=1)))
 
841
    
 
842
    def need_approval(self, *args, **kwargs):
 
843
        r = Client.need_approval(self, *args, **kwargs)
 
844
        # Emit D-Bus signal
 
845
        self.PropertyChanged(
 
846
            dbus.String("LastApprovalRequest"),
 
847
            (self._datetime_to_dbus(self.last_approval_request,
 
848
                                    variant_level=1)))
 
849
        return r
 
850
    
985
851
    def start_checker(self, *args, **kwargs):
986
852
        old_checker = self.checker
987
853
        if self.checker is not None:
994
860
            and old_checker_pid != self.checker.pid):
995
861
            # Emit D-Bus signal
996
862
            self.CheckerStarted(self.current_checker_command)
 
863
            self.PropertyChanged(
 
864
                dbus.String("CheckerRunning"),
 
865
                dbus.Boolean(True, variant_level=1))
997
866
        return r
998
867
    
 
868
    def stop_checker(self, *args, **kwargs):
 
869
        old_checker = getattr(self, "checker", None)
 
870
        r = Client.stop_checker(self, *args, **kwargs)
 
871
        if (old_checker is not None
 
872
            and getattr(self, "checker", None) is None):
 
873
            self.PropertyChanged(dbus.String("CheckerRunning"),
 
874
                                 dbus.Boolean(False, variant_level=1))
 
875
        return r
 
876
 
999
877
    def _reset_approved(self):
1000
878
        self._approved = None
1001
879
        return False
1003
881
    def approve(self, value=True):
1004
882
        self.send_changedstate()
1005
883
        self._approved = value
1006
 
        gobject.timeout_add(_timedelta_to_milliseconds
 
884
        gobject.timeout_add(self._timedelta_to_milliseconds
1007
885
                            (self.approval_duration),
1008
886
                            self._reset_approved)
1009
887
    
1010
888
    
1011
889
    ## D-Bus methods, signals & properties
1012
 
    _interface = "se.recompile.Mandos.Client"
 
890
    _interface = "se.bsnet.fukt.Mandos.Client"
1013
891
    
1014
892
    ## Signals
1015
893
    
1101
979
        if value is None:       # get
1102
980
            return dbus.Boolean(self.approved_by_default)
1103
981
        self.approved_by_default = bool(value)
 
982
        # Emit D-Bus signal
 
983
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
 
984
                             dbus.Boolean(value, variant_level=1))
1104
985
    
1105
986
    # ApprovalDelay - property
1106
987
    @dbus_service_property(_interface, signature="t",
1109
990
        if value is None:       # get
1110
991
            return dbus.UInt64(self.approval_delay_milliseconds())
1111
992
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
 
993
        # Emit D-Bus signal
 
994
        self.PropertyChanged(dbus.String("ApprovalDelay"),
 
995
                             dbus.UInt64(value, variant_level=1))
1112
996
    
1113
997
    # ApprovalDuration - property
1114
998
    @dbus_service_property(_interface, signature="t",
1115
999
                           access="readwrite")
1116
1000
    def ApprovalDuration_dbus_property(self, value=None):
1117
1001
        if value is None:       # get
1118
 
            return dbus.UInt64(_timedelta_to_milliseconds(
 
1002
            return dbus.UInt64(self._timedelta_to_milliseconds(
1119
1003
                    self.approval_duration))
1120
1004
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
 
1005
        # Emit D-Bus signal
 
1006
        self.PropertyChanged(dbus.String("ApprovalDuration"),
 
1007
                             dbus.UInt64(value, variant_level=1))
1121
1008
    
1122
1009
    # Name - property
1123
1010
    @dbus_service_property(_interface, signature="s", access="read")
1136
1023
        if value is None:       # get
1137
1024
            return dbus.String(self.host)
1138
1025
        self.host = value
 
1026
        # Emit D-Bus signal
 
1027
        self.PropertyChanged(dbus.String("Host"),
 
1028
                             dbus.String(value, variant_level=1))
1139
1029
    
1140
1030
    # Created - property
1141
1031
    @dbus_service_property(_interface, signature="s", access="read")
1142
1032
    def Created_dbus_property(self):
1143
 
        return dbus.String(datetime_to_dbus(self.created))
 
1033
        return dbus.String(self._datetime_to_dbus(self.created))
1144
1034
    
1145
1035
    # LastEnabled - property
1146
1036
    @dbus_service_property(_interface, signature="s", access="read")
1147
1037
    def LastEnabled_dbus_property(self):
1148
 
        return datetime_to_dbus(self.last_enabled)
 
1038
        if self.last_enabled is None:
 
1039
            return dbus.String("")
 
1040
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
1149
1041
    
1150
1042
    # Enabled - property
1151
1043
    @dbus_service_property(_interface, signature="b",
1165
1057
        if value is not None:
1166
1058
            self.checked_ok()
1167
1059
            return
1168
 
        return datetime_to_dbus(self.last_checked_ok)
1169
 
    
1170
 
    # Expires - property
1171
 
    @dbus_service_property(_interface, signature="s", access="read")
1172
 
    def Expires_dbus_property(self):
1173
 
        return datetime_to_dbus(self.expires)
 
1060
        if self.last_checked_ok is None:
 
1061
            return dbus.String("")
 
1062
        return dbus.String(self._datetime_to_dbus(self
 
1063
                                                  .last_checked_ok))
1174
1064
    
1175
1065
    # LastApprovalRequest - property
1176
1066
    @dbus_service_property(_interface, signature="s", access="read")
1177
1067
    def LastApprovalRequest_dbus_property(self):
1178
 
        return datetime_to_dbus(self.last_approval_request)
 
1068
        if self.last_approval_request is None:
 
1069
            return dbus.String("")
 
1070
        return dbus.String(self.
 
1071
                           _datetime_to_dbus(self
 
1072
                                             .last_approval_request))
1179
1073
    
1180
1074
    # Timeout - property
1181
1075
    @dbus_service_property(_interface, signature="t",
1184
1078
        if value is None:       # get
1185
1079
            return dbus.UInt64(self.timeout_milliseconds())
1186
1080
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1081
        # Emit D-Bus signal
 
1082
        self.PropertyChanged(dbus.String("Timeout"),
 
1083
                             dbus.UInt64(value, variant_level=1))
1187
1084
        if getattr(self, "disable_initiator_tag", None) is None:
1188
1085
            return
1189
1086
        # Reschedule timeout
1190
1087
        gobject.source_remove(self.disable_initiator_tag)
1191
1088
        self.disable_initiator_tag = None
1192
 
        self.expires = None
1193
 
        time_to_die = _timedelta_to_milliseconds((self
1194
 
                                                  .last_checked_ok
1195
 
                                                  + self.timeout)
1196
 
                                                 - datetime.datetime
1197
 
                                                 .utcnow())
 
1089
        time_to_die = (self.
 
1090
                       _timedelta_to_milliseconds((self
 
1091
                                                   .last_checked_ok
 
1092
                                                   + self.timeout)
 
1093
                                                  - datetime.datetime
 
1094
                                                  .utcnow()))
1198
1095
        if time_to_die <= 0:
1199
1096
            # The timeout has passed
1200
1097
            self.disable()
1201
1098
        else:
1202
 
            self.expires = (datetime.datetime.utcnow()
1203
 
                            + datetime.timedelta(milliseconds =
1204
 
                                                 time_to_die))
1205
1099
            self.disable_initiator_tag = (gobject.timeout_add
1206
1100
                                          (time_to_die, self.disable))
1207
1101
    
1208
 
    # ExtendedTimeout - property
1209
 
    @dbus_service_property(_interface, signature="t",
1210
 
                           access="readwrite")
1211
 
    def ExtendedTimeout_dbus_property(self, value=None):
1212
 
        if value is None:       # get
1213
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
1214
 
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1215
 
    
1216
1102
    # Interval - property
1217
1103
    @dbus_service_property(_interface, signature="t",
1218
1104
                           access="readwrite")
1220
1106
        if value is None:       # get
1221
1107
            return dbus.UInt64(self.interval_milliseconds())
1222
1108
        self.interval = datetime.timedelta(0, 0, 0, value)
 
1109
        # Emit D-Bus signal
 
1110
        self.PropertyChanged(dbus.String("Interval"),
 
1111
                             dbus.UInt64(value, variant_level=1))
1223
1112
        if getattr(self, "checker_initiator_tag", None) is None:
1224
1113
            return
1225
1114
        # Reschedule checker run
1227
1116
        self.checker_initiator_tag = (gobject.timeout_add
1228
1117
                                      (value, self.start_checker))
1229
1118
        self.start_checker()    # Start one now, too
1230
 
    
 
1119
 
1231
1120
    # Checker - property
1232
1121
    @dbus_service_property(_interface, signature="s",
1233
1122
                           access="readwrite")
1235
1124
        if value is None:       # get
1236
1125
            return dbus.String(self.checker_command)
1237
1126
        self.checker_command = value
 
1127
        # Emit D-Bus signal
 
1128
        self.PropertyChanged(dbus.String("Checker"),
 
1129
                             dbus.String(self.checker_command,
 
1130
                                         variant_level=1))
1238
1131
    
1239
1132
    # CheckerRunning - property
1240
1133
    @dbus_service_property(_interface, signature="b",
1267
1160
        self._pipe.send(('init', fpr, address))
1268
1161
        if not self._pipe.recv():
1269
1162
            raise KeyError()
1270
 
    
 
1163
 
1271
1164
    def __getattribute__(self, name):
1272
1165
        if(name == '_pipe'):
1273
1166
            return super(ProxyClient, self).__getattribute__(name)
1280
1173
                self._pipe.send(('funcall', name, args, kwargs))
1281
1174
                return self._pipe.recv()[1]
1282
1175
            return func
1283
 
    
 
1176
 
1284
1177
    def __setattr__(self, name, value):
1285
1178
        if(name == '_pipe'):
1286
1179
            return super(ProxyClient, self).__setattr__(name, value)
1287
1180
        self._pipe.send(('setattr', name, value))
1288
1181
 
1289
 
class ClientDBusTransitional(ClientDBus):
1290
 
    __metaclass__ = AlternateDBusNamesMetaclass
1291
1182
 
1292
1183
class ClientHandler(socketserver.BaseRequestHandler, object):
1293
1184
    """A class to handle client connections.
1301
1192
                        unicode(self.client_address))
1302
1193
            logger.debug("Pipe FD: %d",
1303
1194
                         self.server.child_pipe.fileno())
1304
 
            
 
1195
 
1305
1196
            session = (gnutls.connection
1306
1197
                       .ClientSession(self.request,
1307
1198
                                      gnutls.connection
1308
1199
                                      .X509Credentials()))
1309
 
            
 
1200
 
1310
1201
            # Note: gnutls.connection.X509Credentials is really a
1311
1202
            # generic GnuTLS certificate credentials object so long as
1312
1203
            # no X.509 keys are added to it.  Therefore, we can use it
1313
1204
            # here despite using OpenPGP certificates.
1314
 
            
 
1205
 
1315
1206
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1316
1207
            #                      "+AES-256-CBC", "+SHA1",
1317
1208
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1323
1214
            (gnutls.library.functions
1324
1215
             .gnutls_priority_set_direct(session._c_object,
1325
1216
                                         priority, None))
1326
 
            
 
1217
 
1327
1218
            # Start communication using the Mandos protocol
1328
1219
            # Get protocol number
1329
1220
            line = self.request.makefile().readline()
1334
1225
            except (ValueError, IndexError, RuntimeError) as error:
1335
1226
                logger.error("Unknown protocol version: %s", error)
1336
1227
                return
1337
 
            
 
1228
 
1338
1229
            # Start GnuTLS connection
1339
1230
            try:
1340
1231
                session.handshake()
1344
1235
                # established.  Just abandon the request.
1345
1236
                return
1346
1237
            logger.debug("Handshake succeeded")
1347
 
            
 
1238
 
1348
1239
            approval_required = False
1349
1240
            try:
1350
1241
                try:
1355
1246
                    logger.warning("Bad certificate: %s", error)
1356
1247
                    return
1357
1248
                logger.debug("Fingerprint: %s", fpr)
1358
 
                
 
1249
 
1359
1250
                try:
1360
1251
                    client = ProxyClient(child_pipe, fpr,
1361
1252
                                         self.client_address)
1369
1260
                
1370
1261
                while True:
1371
1262
                    if not client.enabled:
1372
 
                        logger.info("Client %s is disabled",
 
1263
                        logger.warning("Client %s is disabled",
1373
1264
                                       client.name)
1374
1265
                        if self.server.use_dbus:
1375
1266
                            # Emit D-Bus signal
1376
 
                            client.Rejected("Disabled")
 
1267
                            client.Rejected("Disabled")                    
1377
1268
                        return
1378
1269
                    
1379
1270
                    if client._approved or not client.approval_delay:
1396
1287
                        return
1397
1288
                    
1398
1289
                    #wait until timeout or approved
 
1290
                    #x = float(client._timedelta_to_milliseconds(delay))
1399
1291
                    time = datetime.datetime.now()
1400
1292
                    client.changedstate.acquire()
1401
 
                    (client.changedstate.wait
1402
 
                     (float(client._timedelta_to_milliseconds(delay)
1403
 
                            / 1000)))
 
1293
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1404
1294
                    client.changedstate.release()
1405
1295
                    time2 = datetime.datetime.now()
1406
1296
                    if (time2 - time) >= delay:
1428
1318
                                 sent, len(client.secret)
1429
1319
                                 - (sent_size + sent))
1430
1320
                    sent_size += sent
1431
 
                
 
1321
 
1432
1322
                logger.info("Sending secret to %s", client.name)
1433
 
                # bump the timeout using extended_timeout
1434
 
                client.checked_ok(client.extended_timeout)
 
1323
                # bump the timeout as if seen
 
1324
                client.checked_ok()
1435
1325
                if self.server.use_dbus:
1436
1326
                    # Emit D-Bus signal
1437
1327
                    client.GotSecret()
1516
1406
        except:
1517
1407
            self.handle_error(request, address)
1518
1408
        self.close_request(request)
1519
 
    
 
1409
            
1520
1410
    def process_request(self, request, address):
1521
1411
        """Start a new process to process the request."""
1522
 
        proc = multiprocessing.Process(target = self.sub_process_main,
1523
 
                                       args = (request,
1524
 
                                               address))
1525
 
        proc.start()
1526
 
        return proc
1527
 
 
 
1412
        multiprocessing.Process(target = self.sub_process_main,
 
1413
                                args = (request, address)).start()
1528
1414
 
1529
1415
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1530
1416
    """ adds a pipe to the MixIn """
1534
1420
        This function creates a new pipe in self.pipe
1535
1421
        """
1536
1422
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1537
 
        
1538
 
        proc = MultiprocessingMixIn.process_request(self, request,
1539
 
                                                    client_address)
 
1423
 
 
1424
        super(MultiprocessingMixInWithPipe,
 
1425
              self).process_request(request, client_address)
1540
1426
        self.child_pipe.close()
1541
 
        self.add_pipe(parent_pipe, proc)
1542
 
    
1543
 
    def add_pipe(self, parent_pipe, proc):
 
1427
        self.add_pipe(parent_pipe)
 
1428
 
 
1429
    def add_pipe(self, parent_pipe):
1544
1430
        """Dummy function; override as necessary"""
1545
1431
        raise NotImplementedError
1546
1432
 
1547
 
 
1548
1433
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1549
1434
                     socketserver.TCPServer, object):
1550
1435
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1634
1519
    def server_activate(self):
1635
1520
        if self.enabled:
1636
1521
            return socketserver.TCPServer.server_activate(self)
1637
 
    
1638
1522
    def enable(self):
1639
1523
        self.enabled = True
1640
 
    
1641
 
    def add_pipe(self, parent_pipe, proc):
 
1524
    def add_pipe(self, parent_pipe):
1642
1525
        # Call "handle_ipc" for both data and EOF events
1643
1526
        gobject.io_add_watch(parent_pipe.fileno(),
1644
1527
                             gobject.IO_IN | gobject.IO_HUP,
1645
1528
                             functools.partial(self.handle_ipc,
1646
 
                                               parent_pipe =
1647
 
                                               parent_pipe,
1648
 
                                               proc = proc))
1649
 
    
 
1529
                                               parent_pipe = parent_pipe))
 
1530
        
1650
1531
    def handle_ipc(self, source, condition, parent_pipe=None,
1651
 
                   proc = None, client_object=None):
 
1532
                   client_object=None):
1652
1533
        condition_names = {
1653
1534
            gobject.IO_IN: "IN",   # There is data to read.
1654
1535
            gobject.IO_OUT: "OUT", # Data can be written (without
1663
1544
                                       for cond, name in
1664
1545
                                       condition_names.iteritems()
1665
1546
                                       if cond & condition)
1666
 
        # error, or the other end of multiprocessing.Pipe has closed
 
1547
        # error or the other end of multiprocessing.Pipe has closed
1667
1548
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1668
 
            # Wait for other process to exit
1669
 
            proc.join()
1670
1549
            return False
1671
1550
        
1672
1551
        # Read a request from the child
1682
1561
                    client = c
1683
1562
                    break
1684
1563
            else:
1685
 
                logger.info("Client not found for fingerprint: %s, ad"
1686
 
                            "dress: %s", fpr, address)
 
1564
                logger.warning("Client not found for fingerprint: %s, ad"
 
1565
                               "dress: %s", fpr, address)
1687
1566
                if self.use_dbus:
1688
1567
                    # Emit D-Bus signal
1689
 
                    mandos_dbus_service.ClientNotFound(fpr,
1690
 
                                                       address[0])
 
1568
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1691
1569
                parent_pipe.send(False)
1692
1570
                return False
1693
1571
            
1694
1572
            gobject.io_add_watch(parent_pipe.fileno(),
1695
1573
                                 gobject.IO_IN | gobject.IO_HUP,
1696
1574
                                 functools.partial(self.handle_ipc,
1697
 
                                                   parent_pipe =
1698
 
                                                   parent_pipe,
1699
 
                                                   proc = proc,
1700
 
                                                   client_object =
1701
 
                                                   client))
 
1575
                                                   parent_pipe = parent_pipe,
 
1576
                                                   client_object = client))
1702
1577
            parent_pipe.send(True)
1703
 
            # remove the old hook in favor of the new above hook on
1704
 
            # same fileno
 
1578
            # remove the old hook in favor of the new above hook on same fileno
1705
1579
            return False
1706
1580
        if command == 'funcall':
1707
1581
            funcname = request[1]
1708
1582
            args = request[2]
1709
1583
            kwargs = request[3]
1710
1584
            
1711
 
            parent_pipe.send(('data', getattr(client_object,
1712
 
                                              funcname)(*args,
1713
 
                                                         **kwargs)))
1714
 
        
 
1585
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1586
 
1715
1587
        if command == 'getattr':
1716
1588
            attrname = request[1]
1717
1589
            if callable(client_object.__getattribute__(attrname)):
1718
1590
                parent_pipe.send(('function',))
1719
1591
            else:
1720
 
                parent_pipe.send(('data', client_object
1721
 
                                  .__getattribute__(attrname)))
 
1592
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1722
1593
        
1723
1594
        if command == 'setattr':
1724
1595
            attrname = request[1]
1725
1596
            value = request[2]
1726
1597
            setattr(client_object, attrname, value)
1727
 
        
 
1598
 
1728
1599
        return True
1729
1600
 
1730
1601
 
1909
1780
    debuglevel = server_settings["debuglevel"]
1910
1781
    use_dbus = server_settings["use_dbus"]
1911
1782
    use_ipv6 = server_settings["use_ipv6"]
1912
 
    
 
1783
 
1913
1784
    if server_settings["servicename"] != "Mandos":
1914
1785
        syslogger.setFormatter(logging.Formatter
1915
1786
                               ('Mandos (%s) [%%(process)d]:'
1917
1788
                                % server_settings["servicename"]))
1918
1789
    
1919
1790
    # Parse config file with clients
1920
 
    client_defaults = { "timeout": "5m",
1921
 
                        "extended_timeout": "15m",
1922
 
                        "interval": "2m",
 
1791
    client_defaults = { "timeout": "1h",
 
1792
                        "interval": "5m",
1923
1793
                        "checker": "fping -q -- %%(host)s",
1924
1794
                        "host": "",
1925
1795
                        "approval_delay": "0s",
1976
1846
        level = getattr(logging, debuglevel.upper())
1977
1847
        syslogger.setLevel(level)
1978
1848
        console.setLevel(level)
1979
 
    
 
1849
 
1980
1850
    if debug:
1981
1851
        # Enable all possible GnuTLS debugging
1982
1852
        
2013
1883
    # End of Avahi example code
2014
1884
    if use_dbus:
2015
1885
        try:
2016
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1886
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2017
1887
                                            bus, do_not_queue=True)
2018
 
            old_bus_name = (dbus.service.BusName
2019
 
                            ("se.bsnet.fukt.Mandos", bus,
2020
 
                             do_not_queue=True))
2021
1888
        except dbus.exceptions.NameExistsException as e:
2022
1889
            logger.error(unicode(e) + ", disabling D-Bus")
2023
1890
            use_dbus = False
2036
1903
    
2037
1904
    client_class = Client
2038
1905
    if use_dbus:
2039
 
        client_class = functools.partial(ClientDBusTransitional,
2040
 
                                         bus = bus)
 
1906
        client_class = functools.partial(ClientDBus, bus = bus)
2041
1907
    def client_config_items(config, section):
2042
1908
        special_settings = {
2043
1909
            "approved_by_default":
2073
1939
        del pidfilename
2074
1940
        
2075
1941
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2076
 
    
 
1942
 
2077
1943
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2078
1944
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2079
1945
    
2082
1948
            """A D-Bus proxy object"""
2083
1949
            def __init__(self):
2084
1950
                dbus.service.Object.__init__(self, bus, "/")
2085
 
            _interface = "se.recompile.Mandos"
 
1951
            _interface = "se.bsnet.fukt.Mandos"
2086
1952
            
2087
1953
            @dbus.service.signal(_interface, signature="o")
2088
1954
            def ClientAdded(self, objpath):
2130
1996
            
2131
1997
            del _interface
2132
1998
        
2133
 
        class MandosDBusServiceTransitional(MandosDBusService):
2134
 
            __metaclass__ = AlternateDBusNamesMetaclass
2135
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1999
        mandos_dbus_service = MandosDBusService()
2136
2000
    
2137
2001
    def cleanup():
2138
2002
        "Cleanup function; run on exit"
2139
2003
        service.cleanup()
2140
2004
        
2141
 
        multiprocessing.active_children()
2142
2005
        while tcp_server.clients:
2143
2006
            client = tcp_server.clients.pop()
2144
2007
            if use_dbus:
2148
2011
            client.disable(quiet=True)
2149
2012
            if use_dbus:
2150
2013
                # Emit D-Bus signal
2151
 
                mandos_dbus_service.ClientRemoved(client
2152
 
                                                  .dbus_object_path,
 
2014
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2153
2015
                                                  client.name)
2154
2016
    
2155
2017
    atexit.register(cleanup)
2204
2066
    # Must run before the D-Bus bus name gets deregistered
2205
2067
    cleanup()
2206
2068
 
2207
 
 
2208
2069
if __name__ == '__main__':
2209
2070
    main()