/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

  • Committer: Teddy Hogeborn
  • Date: 2011-03-08 19:12:56 UTC
  • mfrom: (237.7.20 trunk)
  • Revision ID: teddy@fukt.bsnet.se-20110308191256-mjcukty9on3z0yhd
MergeĀ fromĀ trunk.

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,
36
36
 
37
37
import SocketServer as socketserver
38
38
import socket
39
 
import argparse
 
39
import optparse
40
40
import datetime
41
41
import errno
42
42
import gnutls.crypto
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.3.1"
 
85
version = "1.2.3"
87
86
 
88
87
#logger = logging.getLogger('mandos')
89
88
logger = logging.Logger('mandos')
152
151
        self.group = None       # our entry group
153
152
        self.server = None
154
153
        self.bus = bus
155
 
        self.entry_group_state_changed_match = None
156
154
    def rename(self):
157
155
        """Derived from the Avahi example code"""
158
156
        if self.rename_count >= self.max_renames:
170
168
        self.remove()
171
169
        try:
172
170
            self.add()
173
 
        except dbus.exceptions.DBusException as error:
 
171
        except dbus.exceptions.DBusException, error:
174
172
            logger.critical("DBusException: %s", error)
175
173
            self.cleanup()
176
174
            os._exit(1)
177
175
        self.rename_count += 1
178
176
    def remove(self):
179
177
        """Derived from the Avahi example code"""
180
 
        if self.entry_group_state_changed_match is not None:
181
 
            self.entry_group_state_changed_match.remove()
182
 
            self.entry_group_state_changed_match = None
183
178
        if self.group is not None:
184
179
            self.group.Reset()
185
180
    def add(self):
186
181
        """Derived from the Avahi example code"""
187
 
        self.remove()
188
182
        if self.group is None:
189
183
            self.group = dbus.Interface(
190
184
                self.bus.get_object(avahi.DBUS_NAME,
191
185
                                    self.server.EntryGroupNew()),
192
186
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
193
 
        self.entry_group_state_changed_match = (
194
 
            self.group.connect_to_signal(
195
 
                'StateChanged', self .entry_group_state_changed))
 
187
            self.group.connect_to_signal('StateChanged',
 
188
                                         self
 
189
                                         .entry_group_state_changed)
196
190
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
197
191
                     self.name, self.type)
198
192
        self.group.AddService(
221
215
    def cleanup(self):
222
216
        """Derived from the Avahi example code"""
223
217
        if self.group is not None:
224
 
            try:
225
 
                self.group.Free()
226
 
            except (dbus.exceptions.UnknownMethodException,
227
 
                    dbus.exceptions.DBusException) as e:
228
 
                pass
 
218
            self.group.Free()
229
219
            self.group = None
230
 
        self.remove()
231
 
    def server_state_changed(self, state, error=None):
 
220
    def server_state_changed(self, state):
232
221
        """Derived from the Avahi example code"""
233
222
        logger.debug("Avahi server state change: %i", state)
234
 
        bad_states = { avahi.SERVER_INVALID:
235
 
                           "Zeroconf server invalid",
236
 
                       avahi.SERVER_REGISTERING: None,
237
 
                       avahi.SERVER_COLLISION:
238
 
                           "Zeroconf server name collision",
239
 
                       avahi.SERVER_FAILURE:
240
 
                           "Zeroconf server failure" }
241
 
        if state in bad_states:
242
 
            if bad_states[state] is not None:
243
 
                if error is None:
244
 
                    logger.error(bad_states[state])
245
 
                else:
246
 
                    logger.error(bad_states[state] + ": %r", error)
247
 
            self.cleanup()
 
223
        if state == avahi.SERVER_COLLISION:
 
224
            logger.error("Zeroconf server name collision")
 
225
            self.remove()
248
226
        elif state == avahi.SERVER_RUNNING:
249
227
            self.add()
250
 
        else:
251
 
            if error is None:
252
 
                logger.debug("Unknown state: %r", state)
253
 
            else:
254
 
                logger.debug("Unknown state: %r: %r", state, error)
255
228
    def activate(self):
256
229
        """Derived from the Avahi example code"""
257
230
        if self.server is None:
258
231
            self.server = dbus.Interface(
259
232
                self.bus.get_object(avahi.DBUS_NAME,
260
 
                                    avahi.DBUS_PATH_SERVER,
261
 
                                    follow_name_owner_changes=True),
 
233
                                    avahi.DBUS_PATH_SERVER),
262
234
                avahi.DBUS_INTERFACE_SERVER)
263
235
        self.server.connect_to_signal("StateChanged",
264
236
                                 self.server_state_changed)
265
237
        self.server_state_changed(self.server.GetState())
266
238
 
267
239
 
268
 
def _timedelta_to_milliseconds(td):
269
 
    "Convert a datetime.timedelta() to milliseconds"
270
 
    return ((td.days * 24 * 60 * 60 * 1000)
271
 
            + (td.seconds * 1000)
272
 
            + (td.microseconds // 1000))
273
 
        
274
240
class Client(object):
275
241
    """A representation of a client host served by this server.
276
242
    
304
270
    secret:     bytestring; sent verbatim (over TLS) to client
305
271
    timeout:    datetime.timedelta(); How long from last_checked_ok
306
272
                                      until this client is disabled
307
 
    extended_timeout:   extra long timeout when password has been sent
308
273
    runtime_expansions: Allowed attributes for runtime expansion.
309
 
    expires:    datetime.datetime(); time (UTC) when a client will be
310
 
                disabled, or None
311
274
    """
312
275
    
313
276
    runtime_expansions = ("approval_delay", "approval_duration",
315
278
                          "host", "interval", "last_checked_ok",
316
279
                          "last_enabled", "name", "timeout")
317
280
    
 
281
    @staticmethod
 
282
    def _timedelta_to_milliseconds(td):
 
283
        "Convert a datetime.timedelta() to milliseconds"
 
284
        return ((td.days * 24 * 60 * 60 * 1000)
 
285
                + (td.seconds * 1000)
 
286
                + (td.microseconds // 1000))
 
287
    
318
288
    def timeout_milliseconds(self):
319
289
        "Return the 'timeout' attribute in milliseconds"
320
 
        return _timedelta_to_milliseconds(self.timeout)
321
 
    
322
 
    def extended_timeout_milliseconds(self):
323
 
        "Return the 'extended_timeout' attribute in milliseconds"
324
 
        return _timedelta_to_milliseconds(self.extended_timeout)    
 
290
        return self._timedelta_to_milliseconds(self.timeout)
325
291
    
326
292
    def interval_milliseconds(self):
327
293
        "Return the 'interval' attribute in milliseconds"
328
 
        return _timedelta_to_milliseconds(self.interval)
329
 
    
 
294
        return self._timedelta_to_milliseconds(self.interval)
 
295
 
330
296
    def approval_delay_milliseconds(self):
331
 
        return _timedelta_to_milliseconds(self.approval_delay)
 
297
        return self._timedelta_to_milliseconds(self.approval_delay)
332
298
    
333
299
    def __init__(self, name = None, disable_hook=None, config=None):
334
300
        """Note: the 'checker' key in 'config' sets the
361
327
        self.last_enabled = None
362
328
        self.last_checked_ok = None
363
329
        self.timeout = string_to_delta(config["timeout"])
364
 
        self.extended_timeout = string_to_delta(config["extended_timeout"])
365
330
        self.interval = string_to_delta(config["interval"])
366
331
        self.disable_hook = disable_hook
367
332
        self.checker = None
368
333
        self.checker_initiator_tag = None
369
334
        self.disable_initiator_tag = None
370
 
        self.expires = None
371
335
        self.checker_callback_tag = None
372
336
        self.checker_command = config["checker"]
373
337
        self.current_checker_command = None
393
357
            # Already enabled
394
358
            return
395
359
        self.send_changedstate()
 
360
        self.last_enabled = datetime.datetime.utcnow()
396
361
        # Schedule a new checker to be started an 'interval' from now,
397
362
        # and every interval from then on.
398
363
        self.checker_initiator_tag = (gobject.timeout_add
399
364
                                      (self.interval_milliseconds(),
400
365
                                       self.start_checker))
401
366
        # Schedule a disable() when 'timeout' has passed
402
 
        self.expires = datetime.datetime.utcnow() + self.timeout
403
367
        self.disable_initiator_tag = (gobject.timeout_add
404
368
                                   (self.timeout_milliseconds(),
405
369
                                    self.disable))
406
370
        self.enabled = True
407
 
        self.last_enabled = datetime.datetime.utcnow()
408
371
        # Also start a new checker *right now*.
409
372
        self.start_checker()
410
373
    
419
382
        if getattr(self, "disable_initiator_tag", False):
420
383
            gobject.source_remove(self.disable_initiator_tag)
421
384
            self.disable_initiator_tag = None
422
 
        self.expires = None
423
385
        if getattr(self, "checker_initiator_tag", False):
424
386
            gobject.source_remove(self.checker_initiator_tag)
425
387
            self.checker_initiator_tag = None
451
413
            logger.warning("Checker for %(name)s crashed?",
452
414
                           vars(self))
453
415
    
454
 
    def checked_ok(self, timeout=None):
 
416
    def checked_ok(self):
455
417
        """Bump up the timeout for this client.
456
418
        
457
419
        This should only be called when the client has been seen,
458
420
        alive and well.
459
421
        """
460
 
        if timeout is None:
461
 
            timeout = self.timeout
462
422
        self.last_checked_ok = datetime.datetime.utcnow()
463
423
        gobject.source_remove(self.disable_initiator_tag)
464
 
        self.expires = datetime.datetime.utcnow() + timeout
465
424
        self.disable_initiator_tag = (gobject.timeout_add
466
 
                                      (_timedelta_to_milliseconds(timeout),
 
425
                                      (self.timeout_milliseconds(),
467
426
                                       self.disable))
468
427
    
469
428
    def need_approval(self):
486
445
        # If a checker exists, make sure it is not a zombie
487
446
        try:
488
447
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
489
 
        except (AttributeError, OSError) as error:
 
448
        except (AttributeError, OSError), error:
490
449
            if (isinstance(error, OSError)
491
450
                and error.errno != errno.ECHILD):
492
451
                raise error
510
469
                                       'replace')))
511
470
                    for attr in
512
471
                    self.runtime_expansions)
513
 
                
 
472
 
514
473
                try:
515
474
                    command = self.checker_command % escaped_attrs
516
 
                except TypeError as error:
 
475
                except TypeError, error:
517
476
                    logger.error('Could not format string "%s":'
518
477
                                 ' %s', self.checker_command, error)
519
478
                    return True # Try again later
538
497
                if pid:
539
498
                    gobject.source_remove(self.checker_callback_tag)
540
499
                    self.checker_callback(pid, status, command)
541
 
            except OSError as error:
 
500
            except OSError, error:
542
501
                logger.error("Failed to start subprocess: %s",
543
502
                             error)
544
503
        # Re-run this periodically if run by gobject.timeout_add
557
516
            #time.sleep(0.5)
558
517
            #if self.checker.poll() is None:
559
518
            #    os.kill(self.checker.pid, signal.SIGKILL)
560
 
        except OSError as error:
 
519
        except OSError, error:
561
520
            if error.errno != errno.ESRCH: # No such process
562
521
                raise
563
522
        self.checker = None
564
523
 
565
 
 
566
524
def dbus_service_property(dbus_interface, signature="v",
567
525
                          access="readwrite", byte_arrays=False):
568
526
    """Decorators for marking methods of a DBusObjectWithProperties to
614
572
 
615
573
class DBusObjectWithProperties(dbus.service.Object):
616
574
    """A D-Bus object with properties.
617
 
    
 
575
 
618
576
    Classes inheriting from this can use the dbus_service_property
619
577
    decorator to expose methods as D-Bus properties.  It exposes the
620
578
    standard Get(), Set(), and GetAll() methods on the D-Bus.
627
585
    def _get_all_dbus_properties(self):
628
586
        """Returns a generator of (name, attribute) pairs
629
587
        """
630
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
631
 
                for cls in self.__class__.__mro__
632
 
                for name, prop in inspect.getmembers(cls, self._is_dbus_property))
 
588
        return ((prop._dbus_name, prop)
 
589
                for name, prop in
 
590
                inspect.getmembers(self, self._is_dbus_property))
633
591
    
634
592
    def _get_dbus_property(self, interface_name, property_name):
635
593
        """Returns a bound method if one exists which is a D-Bus
636
594
        property with the specified name and interface.
637
595
        """
638
 
        for cls in  self.__class__.__mro__:
639
 
            for name, value in inspect.getmembers(cls, self._is_dbus_property):
640
 
                if value._dbus_name == property_name and value._dbus_interface == interface_name:
641
 
                    return value.__get__(self)
642
 
        
 
596
        for name in (property_name,
 
597
                     property_name + "_dbus_property"):
 
598
            prop = getattr(self, name, None)
 
599
            if (prop is None
 
600
                or not self._is_dbus_property(prop)
 
601
                or prop._dbus_name != property_name
 
602
                or (interface_name and prop._dbus_interface
 
603
                    and interface_name != prop._dbus_interface)):
 
604
                continue
 
605
            return prop
643
606
        # No such property
644
607
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
645
608
                                   + interface_name + "."
679
642
    def GetAll(self, interface_name):
680
643
        """Standard D-Bus property GetAll() method, see D-Bus
681
644
        standard.
682
 
        
 
645
 
683
646
        Note: Will not include properties with access="write".
684
647
        """
685
648
        all = {}
741
704
            xmlstring = document.toxml("utf-8")
742
705
            document.unlink()
743
706
        except (AttributeError, xml.dom.DOMException,
744
 
                xml.parsers.expat.ExpatError) as error:
 
707
                xml.parsers.expat.ExpatError), error:
745
708
            logger.error("Failed to override Introspection method",
746
709
                         error)
747
710
        return xmlstring
748
711
 
749
712
 
750
 
def datetime_to_dbus (dt, variant_level=0):
751
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
752
 
    if dt is None:
753
 
        return dbus.String("", variant_level = variant_level)
754
 
    return dbus.String(dt.isoformat(),
755
 
                       variant_level=variant_level)
756
 
 
757
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties.__metaclass__):
758
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
759
 
    will add additional D-Bus attributes matching a certain pattern.
760
 
    """
761
 
    def __new__(mcs, name, bases, attr):
762
 
        # Go through all the base classes which could have D-Bus
763
 
        # methods, signals, or properties in them
764
 
        for base in (b for b in bases
765
 
                     if issubclass(b, dbus.service.Object)):
766
 
            # Go though all attributes of the base class
767
 
            for attrname, attribute in inspect.getmembers(base):
768
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
769
 
                # with the wrong interface name
770
 
                if (not hasattr(attribute, "_dbus_interface")
771
 
                    or not attribute._dbus_interface
772
 
                    .startswith("se.recompile.Mandos")):
773
 
                    continue
774
 
                # Create an alternate D-Bus interface name based on
775
 
                # the current name
776
 
                alt_interface = (attribute._dbus_interface
777
 
                                 .replace("se.recompile.Mandos",
778
 
                                          "se.bsnet.fukt.Mandos"))
779
 
                # Is this a D-Bus signal?
780
 
                if getattr(attribute, "_dbus_is_signal", False):
781
 
                    # Extract the original non-method function by
782
 
                    # black magic
783
 
                    nonmethod_func = (dict(
784
 
                            zip(attribute.func_code.co_freevars,
785
 
                                attribute.__closure__))["func"]
786
 
                                      .cell_contents)
787
 
                    # Create a new, but exactly alike, function
788
 
                    # object, and decorate it to be a new D-Bus signal
789
 
                    # with the alternate D-Bus interface name
790
 
                    new_function = (dbus.service.signal
791
 
                                    (alt_interface,
792
 
                                     attribute._dbus_signature)
793
 
                                    (types.FunctionType(
794
 
                                nonmethod_func.func_code,
795
 
                                nonmethod_func.func_globals,
796
 
                                nonmethod_func.func_name,
797
 
                                nonmethod_func.func_defaults,
798
 
                                nonmethod_func.func_closure)))
799
 
                    # Define a creator of a function to call both the
800
 
                    # old and new functions, so both the old and new
801
 
                    # signals gets sent when the function is called
802
 
                    def fixscope(func1, func2):
803
 
                        """This function is a scope container to pass
804
 
                        func1 and func2 to the "call_both" function
805
 
                        outside of its arguments"""
806
 
                        def call_both(*args, **kwargs):
807
 
                            """This function will emit two D-Bus
808
 
                            signals by calling func1 and func2"""
809
 
                            func1(*args, **kwargs)
810
 
                            func2(*args, **kwargs)
811
 
                        return call_both
812
 
                    # Create the "call_both" function and add it to
813
 
                    # the class
814
 
                    attr[attrname] = fixscope(attribute,
815
 
                                              new_function)
816
 
                # Is this a D-Bus method?
817
 
                elif getattr(attribute, "_dbus_is_method", False):
818
 
                    # Create a new, but exactly alike, function
819
 
                    # object.  Decorate it to be a new D-Bus method
820
 
                    # with the alternate D-Bus interface name.  Add it
821
 
                    # to the class.
822
 
                    attr[attrname] = (dbus.service.method
823
 
                                      (alt_interface,
824
 
                                       attribute._dbus_in_signature,
825
 
                                       attribute._dbus_out_signature)
826
 
                                      (types.FunctionType
827
 
                                       (attribute.func_code,
828
 
                                        attribute.func_globals,
829
 
                                        attribute.func_name,
830
 
                                        attribute.func_defaults,
831
 
                                        attribute.func_closure)))
832
 
                # Is this a D-Bus property?
833
 
                elif getattr(attribute, "_dbus_is_property", False):
834
 
                    # Create a new, but exactly alike, function
835
 
                    # object, and decorate it to be a new D-Bus
836
 
                    # property with the alternate D-Bus interface
837
 
                    # name.  Add it to the class.
838
 
                    attr[attrname] = (dbus_service_property
839
 
                                      (alt_interface,
840
 
                                       attribute._dbus_signature,
841
 
                                       attribute._dbus_access,
842
 
                                       attribute
843
 
                                       ._dbus_get_args_options
844
 
                                       ["byte_arrays"])
845
 
                                      (types.FunctionType
846
 
                                       (attribute.func_code,
847
 
                                        attribute.func_globals,
848
 
                                        attribute.func_name,
849
 
                                        attribute.func_defaults,
850
 
                                        attribute.func_closure)))
851
 
        return type.__new__(mcs, name, bases, attr)
852
 
 
853
713
class ClientDBus(Client, DBusObjectWithProperties):
854
714
    """A Client class using D-Bus
855
715
    
877
737
        DBusObjectWithProperties.__init__(self, self.bus,
878
738
                                          self.dbus_object_path)
879
739
        
880
 
    def notifychangeproperty(transform_func,
881
 
                             dbus_name, type_func=lambda x: x,
882
 
                             variant_level=1):
883
 
        """ Modify a variable so that it's a property which announces
884
 
        its changes to DBus.
 
740
    def _get_approvals_pending(self):
 
741
        return self._approvals_pending
 
742
    def _set_approvals_pending(self, value):
 
743
        old_value = self._approvals_pending
 
744
        self._approvals_pending = value
 
745
        bval = bool(value)
 
746
        if (hasattr(self, "dbus_object_path")
 
747
            and bval is not bool(old_value)):
 
748
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
749
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
750
                                 dbus_bool)
885
751
 
886
 
        transform_fun: Function that takes a value and transforms it
887
 
                       to a D-Bus type.
888
 
        dbus_name: D-Bus name of the variable
889
 
        type_func: Function that transform the value before sending it
890
 
                   to the D-Bus.  Default: no transform
891
 
        variant_level: D-Bus variant level.  Default: 1
892
 
        """
893
 
        real_value = [None,]
894
 
        def setter(self, value):
895
 
            old_value = real_value[0]
896
 
            real_value[0] = value
897
 
            if hasattr(self, "dbus_object_path"):
898
 
                if type_func(old_value) != type_func(real_value[0]):
899
 
                    dbus_value = transform_func(type_func(real_value[0]),
900
 
                                                variant_level)
901
 
                    self.PropertyChanged(dbus.String(dbus_name),
902
 
                                         dbus_value)
903
 
        
904
 
        return property(lambda self: real_value[0], setter)
905
 
    
906
 
    
907
 
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
908
 
    approvals_pending = notifychangeproperty(dbus.Boolean,
909
 
                                             "ApprovalPending",
910
 
                                             type_func = bool)
911
 
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
912
 
    last_enabled = notifychangeproperty(datetime_to_dbus,
913
 
                                        "LastEnabled")
914
 
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
915
 
                                   type_func = lambda checker: checker is not None)
916
 
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
917
 
                                           "LastCheckedOK")
918
 
    last_approval_request = notifychangeproperty(datetime_to_dbus,
919
 
                                                 "LastApprovalRequest")
920
 
    approved_by_default = notifychangeproperty(dbus.Boolean,
921
 
                                               "ApprovedByDefault")
922
 
    approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
923
 
                                          type_func = _timedelta_to_milliseconds)
924
 
    approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
925
 
                                             type_func = _timedelta_to_milliseconds)
926
 
    host = notifychangeproperty(dbus.String, "Host")
927
 
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
928
 
                                   type_func = _timedelta_to_milliseconds)
929
 
    extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
930
 
                                            type_func = _timedelta_to_milliseconds)
931
 
    interval = notifychangeproperty(dbus.UInt16, "Interval",
932
 
                                    type_func = _timedelta_to_milliseconds)
933
 
    checker_command = notifychangeproperty(dbus.String, "Checker")
934
 
    
935
 
    del notifychangeproperty
 
752
    approvals_pending = property(_get_approvals_pending,
 
753
                                 _set_approvals_pending)
 
754
    del _get_approvals_pending, _set_approvals_pending
 
755
    
 
756
    @staticmethod
 
757
    def _datetime_to_dbus(dt, variant_level=0):
 
758
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
759
        return dbus.String(dt.isoformat(),
 
760
                           variant_level=variant_level)
 
761
    
 
762
    def enable(self):
 
763
        oldstate = getattr(self, "enabled", False)
 
764
        r = Client.enable(self)
 
765
        if oldstate != self.enabled:
 
766
            # Emit D-Bus signals
 
767
            self.PropertyChanged(dbus.String("Enabled"),
 
768
                                 dbus.Boolean(True, variant_level=1))
 
769
            self.PropertyChanged(
 
770
                dbus.String("LastEnabled"),
 
771
                self._datetime_to_dbus(self.last_enabled,
 
772
                                       variant_level=1))
 
773
        return r
 
774
    
 
775
    def disable(self, quiet = False):
 
776
        oldstate = getattr(self, "enabled", False)
 
777
        r = Client.disable(self, quiet=quiet)
 
778
        if not quiet and oldstate != self.enabled:
 
779
            # Emit D-Bus signal
 
780
            self.PropertyChanged(dbus.String("Enabled"),
 
781
                                 dbus.Boolean(False, variant_level=1))
 
782
        return r
936
783
    
937
784
    def __del__(self, *args, **kwargs):
938
785
        try:
947
794
                         *args, **kwargs):
948
795
        self.checker_callback_tag = None
949
796
        self.checker = None
 
797
        # Emit D-Bus signal
 
798
        self.PropertyChanged(dbus.String("CheckerRunning"),
 
799
                             dbus.Boolean(False, variant_level=1))
950
800
        if os.WIFEXITED(condition):
951
801
            exitstatus = os.WEXITSTATUS(condition)
952
802
            # Emit D-Bus signal
962
812
        return Client.checker_callback(self, pid, condition, command,
963
813
                                       *args, **kwargs)
964
814
    
 
815
    def checked_ok(self, *args, **kwargs):
 
816
        r = Client.checked_ok(self, *args, **kwargs)
 
817
        # Emit D-Bus signal
 
818
        self.PropertyChanged(
 
819
            dbus.String("LastCheckedOK"),
 
820
            (self._datetime_to_dbus(self.last_checked_ok,
 
821
                                    variant_level=1)))
 
822
        return r
 
823
    
 
824
    def need_approval(self, *args, **kwargs):
 
825
        r = Client.need_approval(self, *args, **kwargs)
 
826
        # Emit D-Bus signal
 
827
        self.PropertyChanged(
 
828
            dbus.String("LastApprovalRequest"),
 
829
            (self._datetime_to_dbus(self.last_approval_request,
 
830
                                    variant_level=1)))
 
831
        return r
 
832
    
965
833
    def start_checker(self, *args, **kwargs):
966
834
        old_checker = self.checker
967
835
        if self.checker is not None:
974
842
            and old_checker_pid != self.checker.pid):
975
843
            # Emit D-Bus signal
976
844
            self.CheckerStarted(self.current_checker_command)
 
845
            self.PropertyChanged(
 
846
                dbus.String("CheckerRunning"),
 
847
                dbus.Boolean(True, variant_level=1))
977
848
        return r
978
849
    
 
850
    def stop_checker(self, *args, **kwargs):
 
851
        old_checker = getattr(self, "checker", None)
 
852
        r = Client.stop_checker(self, *args, **kwargs)
 
853
        if (old_checker is not None
 
854
            and getattr(self, "checker", None) is None):
 
855
            self.PropertyChanged(dbus.String("CheckerRunning"),
 
856
                                 dbus.Boolean(False, variant_level=1))
 
857
        return r
 
858
 
979
859
    def _reset_approved(self):
980
860
        self._approved = None
981
861
        return False
983
863
    def approve(self, value=True):
984
864
        self.send_changedstate()
985
865
        self._approved = value
986
 
        gobject.timeout_add(_timedelta_to_milliseconds
 
866
        gobject.timeout_add(self._timedelta_to_milliseconds
987
867
                            (self.approval_duration),
988
868
                            self._reset_approved)
989
869
    
990
870
    
991
871
    ## D-Bus methods, signals & properties
992
 
    _interface = "se.recompile.Mandos.Client"
 
872
    _interface = "se.bsnet.fukt.Mandos.Client"
993
873
    
994
874
    ## Signals
995
875
    
1042
922
    # CheckedOK - method
1043
923
    @dbus.service.method(_interface)
1044
924
    def CheckedOK(self):
1045
 
        self.checked_ok()
 
925
        return self.checked_ok()
1046
926
    
1047
927
    # Enable - method
1048
928
    @dbus.service.method(_interface)
1081
961
        if value is None:       # get
1082
962
            return dbus.Boolean(self.approved_by_default)
1083
963
        self.approved_by_default = bool(value)
 
964
        # Emit D-Bus signal
 
965
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
 
966
                             dbus.Boolean(value, variant_level=1))
1084
967
    
1085
968
    # ApprovalDelay - property
1086
969
    @dbus_service_property(_interface, signature="t",
1089
972
        if value is None:       # get
1090
973
            return dbus.UInt64(self.approval_delay_milliseconds())
1091
974
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
 
975
        # Emit D-Bus signal
 
976
        self.PropertyChanged(dbus.String("ApprovalDelay"),
 
977
                             dbus.UInt64(value, variant_level=1))
1092
978
    
1093
979
    # ApprovalDuration - property
1094
980
    @dbus_service_property(_interface, signature="t",
1095
981
                           access="readwrite")
1096
982
    def ApprovalDuration_dbus_property(self, value=None):
1097
983
        if value is None:       # get
1098
 
            return dbus.UInt64(_timedelta_to_milliseconds(
 
984
            return dbus.UInt64(self._timedelta_to_milliseconds(
1099
985
                    self.approval_duration))
1100
986
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
 
987
        # Emit D-Bus signal
 
988
        self.PropertyChanged(dbus.String("ApprovalDuration"),
 
989
                             dbus.UInt64(value, variant_level=1))
1101
990
    
1102
991
    # Name - property
1103
992
    @dbus_service_property(_interface, signature="s", access="read")
1116
1005
        if value is None:       # get
1117
1006
            return dbus.String(self.host)
1118
1007
        self.host = value
 
1008
        # Emit D-Bus signal
 
1009
        self.PropertyChanged(dbus.String("Host"),
 
1010
                             dbus.String(value, variant_level=1))
1119
1011
    
1120
1012
    # Created - property
1121
1013
    @dbus_service_property(_interface, signature="s", access="read")
1122
1014
    def Created_dbus_property(self):
1123
 
        return dbus.String(datetime_to_dbus(self.created))
 
1015
        return dbus.String(self._datetime_to_dbus(self.created))
1124
1016
    
1125
1017
    # LastEnabled - property
1126
1018
    @dbus_service_property(_interface, signature="s", access="read")
1127
1019
    def LastEnabled_dbus_property(self):
1128
 
        return datetime_to_dbus(self.last_enabled)
 
1020
        if self.last_enabled is None:
 
1021
            return dbus.String("")
 
1022
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
1129
1023
    
1130
1024
    # Enabled - property
1131
1025
    @dbus_service_property(_interface, signature="b",
1145
1039
        if value is not None:
1146
1040
            self.checked_ok()
1147
1041
            return
1148
 
        return datetime_to_dbus(self.last_checked_ok)
1149
 
    
1150
 
    # Expires - property
1151
 
    @dbus_service_property(_interface, signature="s", access="read")
1152
 
    def Expires_dbus_property(self):
1153
 
        return datetime_to_dbus(self.expires)
 
1042
        if self.last_checked_ok is None:
 
1043
            return dbus.String("")
 
1044
        return dbus.String(self._datetime_to_dbus(self
 
1045
                                                  .last_checked_ok))
1154
1046
    
1155
1047
    # LastApprovalRequest - property
1156
1048
    @dbus_service_property(_interface, signature="s", access="read")
1157
1049
    def LastApprovalRequest_dbus_property(self):
1158
 
        return datetime_to_dbus(self.last_approval_request)
 
1050
        if self.last_approval_request is None:
 
1051
            return dbus.String("")
 
1052
        return dbus.String(self.
 
1053
                           _datetime_to_dbus(self
 
1054
                                             .last_approval_request))
1159
1055
    
1160
1056
    # Timeout - property
1161
1057
    @dbus_service_property(_interface, signature="t",
1164
1060
        if value is None:       # get
1165
1061
            return dbus.UInt64(self.timeout_milliseconds())
1166
1062
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1063
        # Emit D-Bus signal
 
1064
        self.PropertyChanged(dbus.String("Timeout"),
 
1065
                             dbus.UInt64(value, variant_level=1))
1167
1066
        if getattr(self, "disable_initiator_tag", None) is None:
1168
1067
            return
1169
1068
        # Reschedule timeout
1170
1069
        gobject.source_remove(self.disable_initiator_tag)
1171
1070
        self.disable_initiator_tag = None
1172
 
        self.expires = None
1173
1071
        time_to_die = (self.
1174
1072
                       _timedelta_to_milliseconds((self
1175
1073
                                                   .last_checked_ok
1180
1078
            # The timeout has passed
1181
1079
            self.disable()
1182
1080
        else:
1183
 
            self.expires = (datetime.datetime.utcnow()
1184
 
                            + datetime.timedelta(milliseconds = time_to_die))
1185
1081
            self.disable_initiator_tag = (gobject.timeout_add
1186
1082
                                          (time_to_die, self.disable))
1187
1083
    
1188
 
    # ExtendedTimeout - property
1189
 
    @dbus_service_property(_interface, signature="t",
1190
 
                           access="readwrite")
1191
 
    def ExtendedTimeout_dbus_property(self, value=None):
1192
 
        if value is None:       # get
1193
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
1194
 
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1195
 
    
1196
1084
    # Interval - property
1197
1085
    @dbus_service_property(_interface, signature="t",
1198
1086
                           access="readwrite")
1200
1088
        if value is None:       # get
1201
1089
            return dbus.UInt64(self.interval_milliseconds())
1202
1090
        self.interval = datetime.timedelta(0, 0, 0, value)
 
1091
        # Emit D-Bus signal
 
1092
        self.PropertyChanged(dbus.String("Interval"),
 
1093
                             dbus.UInt64(value, variant_level=1))
1203
1094
        if getattr(self, "checker_initiator_tag", None) is None:
1204
1095
            return
1205
1096
        # Reschedule checker run
1207
1098
        self.checker_initiator_tag = (gobject.timeout_add
1208
1099
                                      (value, self.start_checker))
1209
1100
        self.start_checker()    # Start one now, too
1210
 
    
 
1101
 
1211
1102
    # Checker - property
1212
1103
    @dbus_service_property(_interface, signature="s",
1213
1104
                           access="readwrite")
1215
1106
        if value is None:       # get
1216
1107
            return dbus.String(self.checker_command)
1217
1108
        self.checker_command = value
 
1109
        # Emit D-Bus signal
 
1110
        self.PropertyChanged(dbus.String("Checker"),
 
1111
                             dbus.String(self.checker_command,
 
1112
                                         variant_level=1))
1218
1113
    
1219
1114
    # CheckerRunning - property
1220
1115
    @dbus_service_property(_interface, signature="b",
1247
1142
        self._pipe.send(('init', fpr, address))
1248
1143
        if not self._pipe.recv():
1249
1144
            raise KeyError()
1250
 
    
 
1145
 
1251
1146
    def __getattribute__(self, name):
1252
1147
        if(name == '_pipe'):
1253
1148
            return super(ProxyClient, self).__getattribute__(name)
1260
1155
                self._pipe.send(('funcall', name, args, kwargs))
1261
1156
                return self._pipe.recv()[1]
1262
1157
            return func
1263
 
    
 
1158
 
1264
1159
    def __setattr__(self, name, value):
1265
1160
        if(name == '_pipe'):
1266
1161
            return super(ProxyClient, self).__setattr__(name, value)
1267
1162
        self._pipe.send(('setattr', name, value))
1268
1163
 
1269
 
class ClientDBusTransitional(ClientDBus):
1270
 
    __metaclass__ = AlternateDBusNamesMetaclass
1271
1164
 
1272
1165
class ClientHandler(socketserver.BaseRequestHandler, object):
1273
1166
    """A class to handle client connections.
1281
1174
                        unicode(self.client_address))
1282
1175
            logger.debug("Pipe FD: %d",
1283
1176
                         self.server.child_pipe.fileno())
1284
 
            
 
1177
 
1285
1178
            session = (gnutls.connection
1286
1179
                       .ClientSession(self.request,
1287
1180
                                      gnutls.connection
1288
1181
                                      .X509Credentials()))
1289
 
            
 
1182
 
1290
1183
            # Note: gnutls.connection.X509Credentials is really a
1291
1184
            # generic GnuTLS certificate credentials object so long as
1292
1185
            # no X.509 keys are added to it.  Therefore, we can use it
1293
1186
            # here despite using OpenPGP certificates.
1294
 
            
 
1187
 
1295
1188
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1296
1189
            #                      "+AES-256-CBC", "+SHA1",
1297
1190
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1303
1196
            (gnutls.library.functions
1304
1197
             .gnutls_priority_set_direct(session._c_object,
1305
1198
                                         priority, None))
1306
 
            
 
1199
 
1307
1200
            # Start communication using the Mandos protocol
1308
1201
            # Get protocol number
1309
1202
            line = self.request.makefile().readline()
1311
1204
            try:
1312
1205
                if int(line.strip().split()[0]) > 1:
1313
1206
                    raise RuntimeError
1314
 
            except (ValueError, IndexError, RuntimeError) as error:
 
1207
            except (ValueError, IndexError, RuntimeError), error:
1315
1208
                logger.error("Unknown protocol version: %s", error)
1316
1209
                return
1317
 
            
 
1210
 
1318
1211
            # Start GnuTLS connection
1319
1212
            try:
1320
1213
                session.handshake()
1321
 
            except gnutls.errors.GNUTLSError as error:
 
1214
            except gnutls.errors.GNUTLSError, error:
1322
1215
                logger.warning("Handshake failed: %s", error)
1323
1216
                # Do not run session.bye() here: the session is not
1324
1217
                # established.  Just abandon the request.
1325
1218
                return
1326
1219
            logger.debug("Handshake succeeded")
1327
 
            
 
1220
 
1328
1221
            approval_required = False
1329
1222
            try:
1330
1223
                try:
1331
1224
                    fpr = self.fingerprint(self.peer_certificate
1332
1225
                                           (session))
1333
 
                except (TypeError,
1334
 
                        gnutls.errors.GNUTLSError) as error:
 
1226
                except (TypeError, gnutls.errors.GNUTLSError), error:
1335
1227
                    logger.warning("Bad certificate: %s", error)
1336
1228
                    return
1337
1229
                logger.debug("Fingerprint: %s", fpr)
1338
 
                
 
1230
 
1339
1231
                try:
1340
1232
                    client = ProxyClient(child_pipe, fpr,
1341
1233
                                         self.client_address)
1349
1241
                
1350
1242
                while True:
1351
1243
                    if not client.enabled:
1352
 
                        logger.info("Client %s is disabled",
 
1244
                        logger.warning("Client %s is disabled",
1353
1245
                                       client.name)
1354
1246
                        if self.server.use_dbus:
1355
1247
                            # Emit D-Bus signal
1400
1292
                while sent_size < len(client.secret):
1401
1293
                    try:
1402
1294
                        sent = session.send(client.secret[sent_size:])
1403
 
                    except gnutls.errors.GNUTLSError as error:
 
1295
                    except (gnutls.errors.GNUTLSError), error:
1404
1296
                        logger.warning("gnutls send failed")
1405
1297
                        return
1406
1298
                    logger.debug("Sent: %d, remaining: %d",
1407
1299
                                 sent, len(client.secret)
1408
1300
                                 - (sent_size + sent))
1409
1301
                    sent_size += sent
1410
 
                
 
1302
 
1411
1303
                logger.info("Sending secret to %s", client.name)
1412
1304
                # bump the timeout as if seen
1413
 
                client.checked_ok(client.extended_timeout)
 
1305
                client.checked_ok()
1414
1306
                if self.server.use_dbus:
1415
1307
                    # Emit D-Bus signal
1416
1308
                    client.GotSecret()
1420
1312
                    client.approvals_pending -= 1
1421
1313
                try:
1422
1314
                    session.bye()
1423
 
                except gnutls.errors.GNUTLSError as error:
 
1315
                except (gnutls.errors.GNUTLSError), error:
1424
1316
                    logger.warning("GnuTLS bye failed")
1425
1317
    
1426
1318
    @staticmethod
1501
1393
        multiprocessing.Process(target = self.sub_process_main,
1502
1394
                                args = (request, address)).start()
1503
1395
 
1504
 
 
1505
1396
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1506
1397
    """ adds a pipe to the MixIn """
1507
1398
    def process_request(self, request, client_address):
1510
1401
        This function creates a new pipe in self.pipe
1511
1402
        """
1512
1403
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1513
 
        
 
1404
 
1514
1405
        super(MultiprocessingMixInWithPipe,
1515
1406
              self).process_request(request, client_address)
1516
1407
        self.child_pipe.close()
1517
1408
        self.add_pipe(parent_pipe)
1518
 
    
 
1409
 
1519
1410
    def add_pipe(self, parent_pipe):
1520
1411
        """Dummy function; override as necessary"""
1521
1412
        raise NotImplementedError
1522
1413
 
1523
 
 
1524
1414
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1525
1415
                     socketserver.TCPServer, object):
1526
1416
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1552
1442
                                           SO_BINDTODEVICE,
1553
1443
                                           str(self.interface
1554
1444
                                               + '\0'))
1555
 
                except socket.error as error:
 
1445
                except socket.error, error:
1556
1446
                    if error[0] == errno.EPERM:
1557
1447
                        logger.error("No permission to"
1558
1448
                                     " bind to interface %s",
1652
1542
                    client = c
1653
1543
                    break
1654
1544
            else:
1655
 
                logger.info("Client not found for fingerprint: %s, ad"
1656
 
                            "dress: %s", fpr, address)
 
1545
                logger.warning("Client not found for fingerprint: %s, ad"
 
1546
                               "dress: %s", fpr, address)
1657
1547
                if self.use_dbus:
1658
1548
                    # Emit D-Bus signal
1659
1549
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1674
1564
            kwargs = request[3]
1675
1565
            
1676
1566
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1677
 
        
 
1567
 
1678
1568
        if command == 'getattr':
1679
1569
            attrname = request[1]
1680
1570
            if callable(client_object.__getattribute__(attrname)):
1686
1576
            attrname = request[1]
1687
1577
            value = request[2]
1688
1578
            setattr(client_object, attrname, value)
1689
 
        
 
1579
 
1690
1580
        return True
1691
1581
 
1692
1582
 
1723
1613
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1724
1614
            else:
1725
1615
                raise ValueError("Unknown suffix %r" % suffix)
1726
 
        except (ValueError, IndexError) as e:
 
1616
        except (ValueError, IndexError), e:
1727
1617
            raise ValueError(*(e.args))
1728
1618
        timevalue += delta
1729
1619
    return timevalue
1783
1673
    ##################################################################
1784
1674
    # Parsing of options, both command line and config file
1785
1675
    
1786
 
    parser = argparse.ArgumentParser()
1787
 
    parser.add_argument("-v", "--version", action="version",
1788
 
                        version = "%%(prog)s %s" % version,
1789
 
                        help="show version number and exit")
1790
 
    parser.add_argument("-i", "--interface", metavar="IF",
1791
 
                        help="Bind to interface IF")
1792
 
    parser.add_argument("-a", "--address",
1793
 
                        help="Address to listen for requests on")
1794
 
    parser.add_argument("-p", "--port", type=int,
1795
 
                        help="Port number to receive requests on")
1796
 
    parser.add_argument("--check", action="store_true",
1797
 
                        help="Run self-test")
1798
 
    parser.add_argument("--debug", action="store_true",
1799
 
                        help="Debug mode; run in foreground and log"
1800
 
                        " to terminal")
1801
 
    parser.add_argument("--debuglevel", metavar="LEVEL",
1802
 
                        help="Debug level for stdout output")
1803
 
    parser.add_argument("--priority", help="GnuTLS"
1804
 
                        " priority string (see GnuTLS documentation)")
1805
 
    parser.add_argument("--servicename",
1806
 
                        metavar="NAME", help="Zeroconf service name")
1807
 
    parser.add_argument("--configdir",
1808
 
                        default="/etc/mandos", metavar="DIR",
1809
 
                        help="Directory to search for configuration"
1810
 
                        " files")
1811
 
    parser.add_argument("--no-dbus", action="store_false",
1812
 
                        dest="use_dbus", help="Do not provide D-Bus"
1813
 
                        " system bus interface")
1814
 
    parser.add_argument("--no-ipv6", action="store_false",
1815
 
                        dest="use_ipv6", help="Do not use IPv6")
1816
 
    options = parser.parse_args()
 
1676
    parser = optparse.OptionParser(version = "%%prog %s" % version)
 
1677
    parser.add_option("-i", "--interface", type="string",
 
1678
                      metavar="IF", help="Bind to interface IF")
 
1679
    parser.add_option("-a", "--address", type="string",
 
1680
                      help="Address to listen for requests on")
 
1681
    parser.add_option("-p", "--port", type="int",
 
1682
                      help="Port number to receive requests on")
 
1683
    parser.add_option("--check", action="store_true",
 
1684
                      help="Run self-test")
 
1685
    parser.add_option("--debug", action="store_true",
 
1686
                      help="Debug mode; run in foreground and log to"
 
1687
                      " terminal")
 
1688
    parser.add_option("--debuglevel", type="string", metavar="LEVEL",
 
1689
                      help="Debug level for stdout output")
 
1690
    parser.add_option("--priority", type="string", help="GnuTLS"
 
1691
                      " priority string (see GnuTLS documentation)")
 
1692
    parser.add_option("--servicename", type="string",
 
1693
                      metavar="NAME", help="Zeroconf service name")
 
1694
    parser.add_option("--configdir", type="string",
 
1695
                      default="/etc/mandos", metavar="DIR",
 
1696
                      help="Directory to search for configuration"
 
1697
                      " files")
 
1698
    parser.add_option("--no-dbus", action="store_false",
 
1699
                      dest="use_dbus", help="Do not provide D-Bus"
 
1700
                      " system bus interface")
 
1701
    parser.add_option("--no-ipv6", action="store_false",
 
1702
                      dest="use_ipv6", help="Do not use IPv6")
 
1703
    options = parser.parse_args()[0]
1817
1704
    
1818
1705
    if options.check:
1819
1706
        import doctest
1871
1758
    debuglevel = server_settings["debuglevel"]
1872
1759
    use_dbus = server_settings["use_dbus"]
1873
1760
    use_ipv6 = server_settings["use_ipv6"]
1874
 
    
 
1761
 
1875
1762
    if server_settings["servicename"] != "Mandos":
1876
1763
        syslogger.setFormatter(logging.Formatter
1877
1764
                               ('Mandos (%s) [%%(process)d]:'
1879
1766
                                % server_settings["servicename"]))
1880
1767
    
1881
1768
    # Parse config file with clients
1882
 
    client_defaults = { "timeout": "5m",
1883
 
                        "extended_timeout": "15m",
1884
 
                        "interval": "2m",
 
1769
    client_defaults = { "timeout": "1h",
 
1770
                        "interval": "5m",
1885
1771
                        "checker": "fping -q -- %%(host)s",
1886
1772
                        "host": "",
1887
1773
                        "approval_delay": "0s",
1927
1813
    try:
1928
1814
        os.setgid(gid)
1929
1815
        os.setuid(uid)
1930
 
    except OSError as error:
 
1816
    except OSError, error:
1931
1817
        if error[0] != errno.EPERM:
1932
1818
            raise error
1933
1819
    
1938
1824
        level = getattr(logging, debuglevel.upper())
1939
1825
        syslogger.setLevel(level)
1940
1826
        console.setLevel(level)
1941
 
    
 
1827
 
1942
1828
    if debug:
1943
1829
        # Enable all possible GnuTLS debugging
1944
1830
        
1975
1861
    # End of Avahi example code
1976
1862
    if use_dbus:
1977
1863
        try:
1978
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1864
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1979
1865
                                            bus, do_not_queue=True)
1980
 
            old_bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1981
 
                                                bus, do_not_queue=True)
1982
 
        except dbus.exceptions.NameExistsException as e:
 
1866
        except dbus.exceptions.NameExistsException, e:
1983
1867
            logger.error(unicode(e) + ", disabling D-Bus")
1984
1868
            use_dbus = False
1985
1869
            server_settings["use_dbus"] = False
1997
1881
    
1998
1882
    client_class = Client
1999
1883
    if use_dbus:
2000
 
        client_class = functools.partial(ClientDBusTransitional, bus = bus)        
 
1884
        client_class = functools.partial(ClientDBus, bus = bus)
2001
1885
    def client_config_items(config, section):
2002
1886
        special_settings = {
2003
1887
            "approved_by_default":
2033
1917
        del pidfilename
2034
1918
        
2035
1919
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2036
 
    
 
1920
 
2037
1921
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2038
1922
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2039
1923
    
2042
1926
            """A D-Bus proxy object"""
2043
1927
            def __init__(self):
2044
1928
                dbus.service.Object.__init__(self, bus, "/")
2045
 
            _interface = "se.recompile.Mandos"
 
1929
            _interface = "se.bsnet.fukt.Mandos"
2046
1930
            
2047
1931
            @dbus.service.signal(_interface, signature="o")
2048
1932
            def ClientAdded(self, objpath):
2090
1974
            
2091
1975
            del _interface
2092
1976
        
2093
 
        class MandosDBusServiceTransitional(MandosDBusService):
2094
 
            __metaclass__ = AlternateDBusNamesMetaclass
2095
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1977
        mandos_dbus_service = MandosDBusService()
2096
1978
    
2097
1979
    def cleanup():
2098
1980
        "Cleanup function; run on exit"
2137
2019
        # From the Avahi example code
2138
2020
        try:
2139
2021
            service.activate()
2140
 
        except dbus.exceptions.DBusException as error:
 
2022
        except dbus.exceptions.DBusException, error:
2141
2023
            logger.critical("DBusException: %s", error)
2142
2024
            cleanup()
2143
2025
            sys.exit(1)
2150
2032
        
2151
2033
        logger.debug("Starting main loop")
2152
2034
        main_loop.run()
2153
 
    except AvahiError as error:
 
2035
    except AvahiError, error:
2154
2036
        logger.critical("AvahiError: %s", error)
2155
2037
        cleanup()
2156
2038
        sys.exit(1)
2162
2044
    # Must run before the D-Bus bus name gets deregistered
2163
2045
    cleanup()
2164
2046
 
2165
 
 
2166
2047
if __name__ == '__main__':
2167
2048
    main()