/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-09-26 19:36:18 UTC
  • mfrom: (24.1.184 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20110926193618-vtj5c9hena1maixx
Merge from Björn

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
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
315
313
                          "created", "enabled", "fingerprint",
316
314
                          "host", "interval", "last_checked_ok",
317
315
                          "last_enabled", "name", "timeout")
318
 
    
 
316
        
319
317
    def timeout_milliseconds(self):
320
318
        "Return the 'timeout' attribute in milliseconds"
321
319
        return _timedelta_to_milliseconds(self.timeout)
322
 
    
 
320
 
323
321
    def extended_timeout_milliseconds(self):
324
322
        "Return the 'extended_timeout' attribute in milliseconds"
325
 
        return _timedelta_to_milliseconds(self.extended_timeout)
 
323
        return _timedelta_to_milliseconds(self.extended_timeout)    
326
324
    
327
325
    def interval_milliseconds(self):
328
326
        "Return the 'interval' attribute in milliseconds"
329
327
        return _timedelta_to_milliseconds(self.interval)
330
 
    
 
328
 
331
329
    def approval_delay_milliseconds(self):
332
330
        return _timedelta_to_milliseconds(self.approval_delay)
333
331
    
362
360
        self.last_enabled = None
363
361
        self.last_checked_ok = None
364
362
        self.timeout = string_to_delta(config["timeout"])
365
 
        self.extended_timeout = string_to_delta(config
366
 
                                                ["extended_timeout"])
 
363
        self.extended_timeout = string_to_delta(config["extended_timeout"])
367
364
        self.interval = string_to_delta(config["interval"])
368
365
        self.disable_hook = disable_hook
369
366
        self.checker = None
382
379
            config["approval_delay"])
383
380
        self.approval_duration = string_to_delta(
384
381
            config["approval_duration"])
385
 
        self.changedstate = (multiprocessing_manager
386
 
                             .Condition(multiprocessing_manager
387
 
                                        .Lock()))
 
382
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
388
383
    
389
384
    def send_changedstate(self):
390
385
        self.changedstate.acquire()
391
386
        self.changedstate.notify_all()
392
387
        self.changedstate.release()
393
 
    
 
388
        
394
389
    def enable(self):
395
390
        """Start this client's checker and timeout hooks"""
396
391
        if getattr(self, "enabled", False):
467
462
        gobject.source_remove(self.disable_initiator_tag)
468
463
        self.expires = datetime.datetime.utcnow() + timeout
469
464
        self.disable_initiator_tag = (gobject.timeout_add
470
 
                                      (_timedelta_to_milliseconds
471
 
                                       (timeout), self.disable))
 
465
                                      (_timedelta_to_milliseconds(timeout),
 
466
                                       self.disable))
472
467
    
473
468
    def need_approval(self):
474
469
        self.last_approval_request = datetime.datetime.utcnow()
514
509
                                       'replace')))
515
510
                    for attr in
516
511
                    self.runtime_expansions)
517
 
                
 
512
 
518
513
                try:
519
514
                    command = self.checker_command % escaped_attrs
520
515
                except TypeError as error:
566
561
                raise
567
562
        self.checker = None
568
563
 
569
 
 
570
564
def dbus_service_property(dbus_interface, signature="v",
571
565
                          access="readwrite", byte_arrays=False):
572
566
    """Decorators for marking methods of a DBusObjectWithProperties to
618
612
 
619
613
class DBusObjectWithProperties(dbus.service.Object):
620
614
    """A D-Bus object with properties.
621
 
    
 
615
 
622
616
    Classes inheriting from this can use the dbus_service_property
623
617
    decorator to expose methods as D-Bus properties.  It exposes the
624
618
    standard Get(), Set(), and GetAll() methods on the D-Bus.
631
625
    def _get_all_dbus_properties(self):
632
626
        """Returns a generator of (name, attribute) pairs
633
627
        """
634
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
635
 
                for cls in self.__class__.__mro__
 
628
        return ((prop._dbus_name, prop)
636
629
                for name, prop in
637
 
                inspect.getmembers(cls, self._is_dbus_property))
 
630
                inspect.getmembers(self, self._is_dbus_property))
638
631
    
639
632
    def _get_dbus_property(self, interface_name, property_name):
640
633
        """Returns a bound method if one exists which is a D-Bus
641
634
        property with the specified name and interface.
642
635
        """
643
 
        for cls in  self.__class__.__mro__:
644
 
            for name, value in (inspect.getmembers
645
 
                                (cls, self._is_dbus_property)):
646
 
                if (value._dbus_name == property_name
647
 
                    and value._dbus_interface == interface_name):
648
 
                    return value.__get__(self)
649
 
        
 
636
        for name in (property_name,
 
637
                     property_name + "_dbus_property"):
 
638
            prop = getattr(self, name, None)
 
639
            if (prop is None
 
640
                or not self._is_dbus_property(prop)
 
641
                or prop._dbus_name != property_name
 
642
                or (interface_name and prop._dbus_interface
 
643
                    and interface_name != prop._dbus_interface)):
 
644
                continue
 
645
            return prop
650
646
        # No such property
651
647
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
652
648
                                   + interface_name + "."
686
682
    def GetAll(self, interface_name):
687
683
        """Standard D-Bus property GetAll() method, see D-Bus
688
684
        standard.
689
 
        
 
685
 
690
686
        Note: Will not include properties with access="write".
691
687
        """
692
688
        all = {}
761
757
    return dbus.String(dt.isoformat(),
762
758
                       variant_level=variant_level)
763
759
 
764
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
765
 
                                  .__metaclass__):
766
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
767
 
    will add additional D-Bus attributes matching a certain pattern.
768
 
    """
769
 
    def __new__(mcs, name, bases, attr):
770
 
        # Go through all the base classes which could have D-Bus
771
 
        # methods, signals, or properties in them
772
 
        for base in (b for b in bases
773
 
                     if issubclass(b, dbus.service.Object)):
774
 
            # Go though all attributes of the base class
775
 
            for attrname, attribute in inspect.getmembers(base):
776
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
777
 
                # with the wrong interface name
778
 
                if (not hasattr(attribute, "_dbus_interface")
779
 
                    or not attribute._dbus_interface
780
 
                    .startswith("se.recompile.Mandos")):
781
 
                    continue
782
 
                # Create an alternate D-Bus interface name based on
783
 
                # the current name
784
 
                alt_interface = (attribute._dbus_interface
785
 
                                 .replace("se.recompile.Mandos",
786
 
                                          "se.bsnet.fukt.Mandos"))
787
 
                # Is this a D-Bus signal?
788
 
                if getattr(attribute, "_dbus_is_signal", False):
789
 
                    # Extract the original non-method function by
790
 
                    # black magic
791
 
                    nonmethod_func = (dict(
792
 
                            zip(attribute.func_code.co_freevars,
793
 
                                attribute.__closure__))["func"]
794
 
                                      .cell_contents)
795
 
                    # Create a new, but exactly alike, function
796
 
                    # object, and decorate it to be a new D-Bus signal
797
 
                    # with the alternate D-Bus interface name
798
 
                    new_function = (dbus.service.signal
799
 
                                    (alt_interface,
800
 
                                     attribute._dbus_signature)
801
 
                                    (types.FunctionType(
802
 
                                nonmethod_func.func_code,
803
 
                                nonmethod_func.func_globals,
804
 
                                nonmethod_func.func_name,
805
 
                                nonmethod_func.func_defaults,
806
 
                                nonmethod_func.func_closure)))
807
 
                    # Define a creator of a function to call both the
808
 
                    # old and new functions, so both the old and new
809
 
                    # signals gets sent when the function is called
810
 
                    def fixscope(func1, func2):
811
 
                        """This function is a scope container to pass
812
 
                        func1 and func2 to the "call_both" function
813
 
                        outside of its arguments"""
814
 
                        def call_both(*args, **kwargs):
815
 
                            """This function will emit two D-Bus
816
 
                            signals by calling func1 and func2"""
817
 
                            func1(*args, **kwargs)
818
 
                            func2(*args, **kwargs)
819
 
                        return call_both
820
 
                    # Create the "call_both" function and add it to
821
 
                    # the class
822
 
                    attr[attrname] = fixscope(attribute,
823
 
                                              new_function)
824
 
                # Is this a D-Bus method?
825
 
                elif getattr(attribute, "_dbus_is_method", False):
826
 
                    # Create a new, but exactly alike, function
827
 
                    # object.  Decorate it to be a new D-Bus method
828
 
                    # with the alternate D-Bus interface name.  Add it
829
 
                    # to the class.
830
 
                    attr[attrname] = (dbus.service.method
831
 
                                      (alt_interface,
832
 
                                       attribute._dbus_in_signature,
833
 
                                       attribute._dbus_out_signature)
834
 
                                      (types.FunctionType
835
 
                                       (attribute.func_code,
836
 
                                        attribute.func_globals,
837
 
                                        attribute.func_name,
838
 
                                        attribute.func_defaults,
839
 
                                        attribute.func_closure)))
840
 
                # Is this a D-Bus property?
841
 
                elif getattr(attribute, "_dbus_is_property", False):
842
 
                    # Create a new, but exactly alike, function
843
 
                    # object, and decorate it to be a new D-Bus
844
 
                    # property with the alternate D-Bus interface
845
 
                    # name.  Add it to the class.
846
 
                    attr[attrname] = (dbus_service_property
847
 
                                      (alt_interface,
848
 
                                       attribute._dbus_signature,
849
 
                                       attribute._dbus_access,
850
 
                                       attribute
851
 
                                       ._dbus_get_args_options
852
 
                                       ["byte_arrays"])
853
 
                                      (types.FunctionType
854
 
                                       (attribute.func_code,
855
 
                                        attribute.func_globals,
856
 
                                        attribute.func_name,
857
 
                                        attribute.func_defaults,
858
 
                                        attribute.func_closure)))
859
 
        return type.__new__(mcs, name, bases, attr)
860
 
 
861
760
class ClientDBus(Client, DBusObjectWithProperties):
862
761
    """A Client class using D-Bus
863
762
    
888
787
    def notifychangeproperty(transform_func,
889
788
                             dbus_name, type_func=lambda x: x,
890
789
                             variant_level=1):
891
 
        """ Modify a variable so that it's a property which announces
892
 
        its changes to DBus.
893
 
 
894
 
        transform_fun: Function that takes a value and transforms it
895
 
                       to a D-Bus type.
896
 
        dbus_name: D-Bus name of the variable
 
790
        """ Modify a variable so that its a property that announce its
 
791
        changes to DBus.
 
792
        transform_fun: Function that takes a value and transform it to
 
793
                       DBus type.
 
794
        dbus_name: DBus name of the variable
897
795
        type_func: Function that transform the value before sending it
898
 
                   to the D-Bus.  Default: no transform
899
 
        variant_level: D-Bus variant level.  Default: 1
 
796
                   to DBus
 
797
        variant_level: DBus variant level. default: 1
900
798
        """
901
799
        real_value = [None,]
902
800
        def setter(self, value):
904
802
            real_value[0] = value
905
803
            if hasattr(self, "dbus_object_path"):
906
804
                if type_func(old_value) != type_func(real_value[0]):
907
 
                    dbus_value = transform_func(type_func
908
 
                                                (real_value[0]),
 
805
                    dbus_value = transform_func(type_func(real_value[0]),
909
806
                                                variant_level)
910
807
                    self.PropertyChanged(dbus.String(dbus_name),
911
808
                                         dbus_value)
912
 
        
 
809
 
913
810
        return property(lambda self: real_value[0], setter)
914
 
    
915
 
    
 
811
 
 
812
 
916
813
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
917
814
    approvals_pending = notifychangeproperty(dbus.Boolean,
918
815
                                             "ApprovalPending",
921
818
    last_enabled = notifychangeproperty(datetime_to_dbus,
922
819
                                        "LastEnabled")
923
820
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
924
 
                                   type_func = lambda checker:
925
 
                                       checker is not None)
 
821
                                   type_func = lambda checker: checker is not None)
926
822
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
927
823
                                           "LastCheckedOK")
928
 
    last_approval_request = notifychangeproperty(
929
 
        datetime_to_dbus, "LastApprovalRequest")
 
824
    last_approval_request = notifychangeproperty(datetime_to_dbus,
 
825
                                                 "LastApprovalRequest")
930
826
    approved_by_default = notifychangeproperty(dbus.Boolean,
931
827
                                               "ApprovedByDefault")
932
 
    approval_delay = notifychangeproperty(dbus.UInt16,
933
 
                                          "ApprovalDelay",
934
 
                                          type_func =
935
 
                                          _timedelta_to_milliseconds)
936
 
    approval_duration = notifychangeproperty(
937
 
        dbus.UInt16, "ApprovalDuration",
938
 
        type_func = _timedelta_to_milliseconds)
 
828
    approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
 
829
                                          type_func = _timedelta_to_milliseconds)
 
830
    approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
 
831
                                             type_func = _timedelta_to_milliseconds)
939
832
    host = notifychangeproperty(dbus.String, "Host")
940
833
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
941
 
                                   type_func =
942
 
                                   _timedelta_to_milliseconds)
943
 
    extended_timeout = notifychangeproperty(
944
 
        dbus.UInt16, "ExtendedTimeout",
945
 
        type_func = _timedelta_to_milliseconds)
946
 
    interval = notifychangeproperty(dbus.UInt16,
947
 
                                    "Interval",
948
 
                                    type_func =
949
 
                                    _timedelta_to_milliseconds)
 
834
                                   type_func = _timedelta_to_milliseconds)
 
835
    extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
 
836
                                            type_func = _timedelta_to_milliseconds)
 
837
    interval = notifychangeproperty(dbus.UInt16, "Interval",
 
838
                                    type_func = _timedelta_to_milliseconds)
950
839
    checker_command = notifychangeproperty(dbus.String, "Checker")
951
840
    
952
841
    del notifychangeproperty
978
867
        
979
868
        return Client.checker_callback(self, pid, condition, command,
980
869
                                       *args, **kwargs)
981
 
    
 
870
 
982
871
    def start_checker(self, *args, **kwargs):
983
872
        old_checker = self.checker
984
873
        if self.checker is not None:
1006
895
    
1007
896
    
1008
897
    ## D-Bus methods, signals & properties
1009
 
    _interface = "se.recompile.Mandos.Client"
 
898
    _interface = "se.bsnet.fukt.Mandos.Client"
1010
899
    
1011
900
    ## Signals
1012
901
    
1198
1087
            self.disable()
1199
1088
        else:
1200
1089
            self.expires = (datetime.datetime.utcnow()
1201
 
                            + datetime.timedelta(milliseconds =
1202
 
                                                 time_to_die))
 
1090
                            + datetime.timedelta(milliseconds = time_to_die))
1203
1091
            self.disable_initiator_tag = (gobject.timeout_add
1204
1092
                                          (time_to_die, self.disable))
1205
 
    
 
1093
 
1206
1094
    # ExtendedTimeout - property
1207
1095
    @dbus_service_property(_interface, signature="t",
1208
1096
                           access="readwrite")
1210
1098
        if value is None:       # get
1211
1099
            return dbus.UInt64(self.extended_timeout_milliseconds())
1212
1100
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1213
 
    
 
1101
 
1214
1102
    # Interval - property
1215
1103
    @dbus_service_property(_interface, signature="t",
1216
1104
                           access="readwrite")
1225
1113
        self.checker_initiator_tag = (gobject.timeout_add
1226
1114
                                      (value, self.start_checker))
1227
1115
        self.start_checker()    # Start one now, too
1228
 
    
 
1116
 
1229
1117
    # Checker - property
1230
1118
    @dbus_service_property(_interface, signature="s",
1231
1119
                           access="readwrite")
1265
1153
        self._pipe.send(('init', fpr, address))
1266
1154
        if not self._pipe.recv():
1267
1155
            raise KeyError()
1268
 
    
 
1156
 
1269
1157
    def __getattribute__(self, name):
1270
1158
        if(name == '_pipe'):
1271
1159
            return super(ProxyClient, self).__getattribute__(name)
1278
1166
                self._pipe.send(('funcall', name, args, kwargs))
1279
1167
                return self._pipe.recv()[1]
1280
1168
            return func
1281
 
    
 
1169
 
1282
1170
    def __setattr__(self, name, value):
1283
1171
        if(name == '_pipe'):
1284
1172
            return super(ProxyClient, self).__setattr__(name, value)
1285
1173
        self._pipe.send(('setattr', name, value))
1286
1174
 
1287
 
class ClientDBusTransitional(ClientDBus):
1288
 
    __metaclass__ = AlternateDBusNamesMetaclass
1289
1175
 
1290
1176
class ClientHandler(socketserver.BaseRequestHandler, object):
1291
1177
    """A class to handle client connections.
1299
1185
                        unicode(self.client_address))
1300
1186
            logger.debug("Pipe FD: %d",
1301
1187
                         self.server.child_pipe.fileno())
1302
 
            
 
1188
 
1303
1189
            session = (gnutls.connection
1304
1190
                       .ClientSession(self.request,
1305
1191
                                      gnutls.connection
1306
1192
                                      .X509Credentials()))
1307
 
            
 
1193
 
1308
1194
            # Note: gnutls.connection.X509Credentials is really a
1309
1195
            # generic GnuTLS certificate credentials object so long as
1310
1196
            # no X.509 keys are added to it.  Therefore, we can use it
1311
1197
            # here despite using OpenPGP certificates.
1312
 
            
 
1198
 
1313
1199
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1314
1200
            #                      "+AES-256-CBC", "+SHA1",
1315
1201
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1321
1207
            (gnutls.library.functions
1322
1208
             .gnutls_priority_set_direct(session._c_object,
1323
1209
                                         priority, None))
1324
 
            
 
1210
 
1325
1211
            # Start communication using the Mandos protocol
1326
1212
            # Get protocol number
1327
1213
            line = self.request.makefile().readline()
1332
1218
            except (ValueError, IndexError, RuntimeError) as error:
1333
1219
                logger.error("Unknown protocol version: %s", error)
1334
1220
                return
1335
 
            
 
1221
 
1336
1222
            # Start GnuTLS connection
1337
1223
            try:
1338
1224
                session.handshake()
1342
1228
                # established.  Just abandon the request.
1343
1229
                return
1344
1230
            logger.debug("Handshake succeeded")
1345
 
            
 
1231
 
1346
1232
            approval_required = False
1347
1233
            try:
1348
1234
                try:
1353
1239
                    logger.warning("Bad certificate: %s", error)
1354
1240
                    return
1355
1241
                logger.debug("Fingerprint: %s", fpr)
1356
 
                
 
1242
 
1357
1243
                try:
1358
1244
                    client = ProxyClient(child_pipe, fpr,
1359
1245
                                         self.client_address)
1371
1257
                                       client.name)
1372
1258
                        if self.server.use_dbus:
1373
1259
                            # Emit D-Bus signal
1374
 
                            client.Rejected("Disabled")
 
1260
                            client.Rejected("Disabled")                    
1375
1261
                        return
1376
1262
                    
1377
1263
                    if client._approved or not client.approval_delay:
1394
1280
                        return
1395
1281
                    
1396
1282
                    #wait until timeout or approved
1397
 
                    #x = float(client
1398
 
                    #          ._timedelta_to_milliseconds(delay))
 
1283
                    #x = float(client._timedelta_to_milliseconds(delay))
1399
1284
                    time = datetime.datetime.now()
1400
1285
                    client.changedstate.acquire()
1401
 
                    (client.changedstate.wait
1402
 
                     (float(client._timedelta_to_milliseconds(delay)
1403
 
                            / 1000)))
 
1286
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1404
1287
                    client.changedstate.release()
1405
1288
                    time2 = datetime.datetime.now()
1406
1289
                    if (time2 - time) >= delay:
1428
1311
                                 sent, len(client.secret)
1429
1312
                                 - (sent_size + sent))
1430
1313
                    sent_size += sent
1431
 
                
 
1314
 
1432
1315
                logger.info("Sending secret to %s", client.name)
1433
1316
                # bump the timeout as if seen
1434
1317
                client.checked_ok(client.extended_timeout)
1522
1405
        multiprocessing.Process(target = self.sub_process_main,
1523
1406
                                args = (request, address)).start()
1524
1407
 
1525
 
 
1526
1408
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1527
1409
    """ adds a pipe to the MixIn """
1528
1410
    def process_request(self, request, client_address):
1531
1413
        This function creates a new pipe in self.pipe
1532
1414
        """
1533
1415
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1534
 
        
 
1416
 
1535
1417
        super(MultiprocessingMixInWithPipe,
1536
1418
              self).process_request(request, client_address)
1537
1419
        self.child_pipe.close()
1538
1420
        self.add_pipe(parent_pipe)
1539
 
    
 
1421
 
1540
1422
    def add_pipe(self, parent_pipe):
1541
1423
        """Dummy function; override as necessary"""
1542
1424
        raise NotImplementedError
1543
1425
 
1544
 
 
1545
1426
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1546
1427
                     socketserver.TCPServer, object):
1547
1428
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1638
1519
        gobject.io_add_watch(parent_pipe.fileno(),
1639
1520
                             gobject.IO_IN | gobject.IO_HUP,
1640
1521
                             functools.partial(self.handle_ipc,
1641
 
                                               parent_pipe =
1642
 
                                               parent_pipe))
 
1522
                                               parent_pipe = parent_pipe))
1643
1523
        
1644
1524
    def handle_ipc(self, source, condition, parent_pipe=None,
1645
1525
                   client_object=None):
1678
1558
                            "dress: %s", fpr, address)
1679
1559
                if self.use_dbus:
1680
1560
                    # Emit D-Bus signal
1681
 
                    mandos_dbus_service.ClientNotFound(fpr,
1682
 
                                                       address[0])
 
1561
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1683
1562
                parent_pipe.send(False)
1684
1563
                return False
1685
1564
            
1686
1565
            gobject.io_add_watch(parent_pipe.fileno(),
1687
1566
                                 gobject.IO_IN | gobject.IO_HUP,
1688
1567
                                 functools.partial(self.handle_ipc,
1689
 
                                                   parent_pipe =
1690
 
                                                   parent_pipe,
1691
 
                                                   client_object =
1692
 
                                                   client))
 
1568
                                                   parent_pipe = parent_pipe,
 
1569
                                                   client_object = client))
1693
1570
            parent_pipe.send(True)
1694
 
            # remove the old hook in favor of the new above hook on
1695
 
            # same fileno
 
1571
            # remove the old hook in favor of the new above hook on same fileno
1696
1572
            return False
1697
1573
        if command == 'funcall':
1698
1574
            funcname = request[1]
1699
1575
            args = request[2]
1700
1576
            kwargs = request[3]
1701
1577
            
1702
 
            parent_pipe.send(('data', getattr(client_object,
1703
 
                                              funcname)(*args,
1704
 
                                                         **kwargs)))
1705
 
        
 
1578
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1579
 
1706
1580
        if command == 'getattr':
1707
1581
            attrname = request[1]
1708
1582
            if callable(client_object.__getattribute__(attrname)):
1709
1583
                parent_pipe.send(('function',))
1710
1584
            else:
1711
 
                parent_pipe.send(('data', client_object
1712
 
                                  .__getattribute__(attrname)))
 
1585
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1713
1586
        
1714
1587
        if command == 'setattr':
1715
1588
            attrname = request[1]
1716
1589
            value = request[2]
1717
1590
            setattr(client_object, attrname, value)
1718
 
        
 
1591
 
1719
1592
        return True
1720
1593
 
1721
1594
 
1900
1773
    debuglevel = server_settings["debuglevel"]
1901
1774
    use_dbus = server_settings["use_dbus"]
1902
1775
    use_ipv6 = server_settings["use_ipv6"]
1903
 
    
 
1776
 
1904
1777
    if server_settings["servicename"] != "Mandos":
1905
1778
        syslogger.setFormatter(logging.Formatter
1906
1779
                               ('Mandos (%s) [%%(process)d]:'
1967
1840
        level = getattr(logging, debuglevel.upper())
1968
1841
        syslogger.setLevel(level)
1969
1842
        console.setLevel(level)
1970
 
    
 
1843
 
1971
1844
    if debug:
1972
1845
        # Enable all possible GnuTLS debugging
1973
1846
        
2004
1877
    # End of Avahi example code
2005
1878
    if use_dbus:
2006
1879
        try:
2007
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1880
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2008
1881
                                            bus, do_not_queue=True)
2009
 
            old_bus_name = (dbus.service.BusName
2010
 
                            ("se.bsnet.fukt.Mandos", bus,
2011
 
                             do_not_queue=True))
2012
1882
        except dbus.exceptions.NameExistsException as e:
2013
1883
            logger.error(unicode(e) + ", disabling D-Bus")
2014
1884
            use_dbus = False
2027
1897
    
2028
1898
    client_class = Client
2029
1899
    if use_dbus:
2030
 
        client_class = functools.partial(ClientDBusTransitional,
2031
 
                                         bus = bus)
 
1900
        client_class = functools.partial(ClientDBus, bus = bus)
2032
1901
    def client_config_items(config, section):
2033
1902
        special_settings = {
2034
1903
            "approved_by_default":
2064
1933
        del pidfilename
2065
1934
        
2066
1935
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2067
 
    
 
1936
 
2068
1937
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2069
1938
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2070
1939
    
2073
1942
            """A D-Bus proxy object"""
2074
1943
            def __init__(self):
2075
1944
                dbus.service.Object.__init__(self, bus, "/")
2076
 
            _interface = "se.recompile.Mandos"
 
1945
            _interface = "se.bsnet.fukt.Mandos"
2077
1946
            
2078
1947
            @dbus.service.signal(_interface, signature="o")
2079
1948
            def ClientAdded(self, objpath):
2121
1990
            
2122
1991
            del _interface
2123
1992
        
2124
 
        class MandosDBusServiceTransitional(MandosDBusService):
2125
 
            __metaclass__ = AlternateDBusNamesMetaclass
2126
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1993
        mandos_dbus_service = MandosDBusService()
2127
1994
    
2128
1995
    def cleanup():
2129
1996
        "Cleanup function; run on exit"
2138
2005
            client.disable(quiet=True)
2139
2006
            if use_dbus:
2140
2007
                # Emit D-Bus signal
2141
 
                mandos_dbus_service.ClientRemoved(client
2142
 
                                                  .dbus_object_path,
 
2008
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2143
2009
                                                  client.name)
2144
2010
    
2145
2011
    atexit.register(cleanup)
2194
2060
    # Must run before the D-Bus bus name gets deregistered
2195
2061
    cleanup()
2196
2062
 
2197
 
 
2198
2063
if __name__ == '__main__':
2199
2064
    main()