/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: Björn Påhlsson
  • Date: 2011-09-26 18:47:38 UTC
  • mto: This revision was merged to the branch mainline in revision 502.
  • Revision ID: belorn@fukt.bsnet.se-20110926184738-ee8kz5vc9pb3393m
updated TODO

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.1"
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
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):
464
459
        if timeout is None:
465
460
            timeout = self.timeout
466
461
        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
 
462
        gobject.source_remove(self.disable_initiator_tag)
 
463
        self.expires = datetime.datetime.utcnow() + timeout
 
464
        self.disable_initiator_tag = (gobject.timeout_add
 
465
                                      (_timedelta_to_milliseconds(timeout),
 
466
                                       self.disable))
474
467
    
475
468
    def need_approval(self):
476
469
        self.last_approval_request = datetime.datetime.utcnow()
516
509
                                       'replace')))
517
510
                    for attr in
518
511
                    self.runtime_expansions)
519
 
                
 
512
 
520
513
                try:
521
514
                    command = self.checker_command % escaped_attrs
522
515
                except TypeError as error:
568
561
                raise
569
562
        self.checker = None
570
563
 
571
 
 
572
564
def dbus_service_property(dbus_interface, signature="v",
573
565
                          access="readwrite", byte_arrays=False):
574
566
    """Decorators for marking methods of a DBusObjectWithProperties to
620
612
 
621
613
class DBusObjectWithProperties(dbus.service.Object):
622
614
    """A D-Bus object with properties.
623
 
    
 
615
 
624
616
    Classes inheriting from this can use the dbus_service_property
625
617
    decorator to expose methods as D-Bus properties.  It exposes the
626
618
    standard Get(), Set(), and GetAll() methods on the D-Bus.
633
625
    def _get_all_dbus_properties(self):
634
626
        """Returns a generator of (name, attribute) pairs
635
627
        """
636
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
637
 
                for cls in self.__class__.__mro__
 
628
        return ((prop._dbus_name, prop)
638
629
                for name, prop in
639
 
                inspect.getmembers(cls, self._is_dbus_property))
 
630
                inspect.getmembers(self, self._is_dbus_property))
640
631
    
641
632
    def _get_dbus_property(self, interface_name, property_name):
642
633
        """Returns a bound method if one exists which is a D-Bus
643
634
        property with the specified name and interface.
644
635
        """
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
 
        
 
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
652
646
        # No such property
653
647
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
654
648
                                   + interface_name + "."
688
682
    def GetAll(self, interface_name):
689
683
        """Standard D-Bus property GetAll() method, see D-Bus
690
684
        standard.
691
 
        
 
685
 
692
686
        Note: Will not include properties with access="write".
693
687
        """
694
688
        all = {}
763
757
    return dbus.String(dt.isoformat(),
764
758
                       variant_level=variant_level)
765
759
 
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
760
class ClientDBus(Client, DBusObjectWithProperties):
864
761
    """A Client class using D-Bus
865
762
    
890
787
    def notifychangeproperty(transform_func,
891
788
                             dbus_name, type_func=lambda x: x,
892
789
                             variant_level=1):
893
 
        """ Modify a variable so that it's a property which announces
894
 
        its changes to DBus.
895
 
 
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
 
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
899
795
        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
 
796
                   to DBus
 
797
        variant_level: DBus variant level. default: 1
902
798
        """
903
 
        attrname = "_{0}".format(dbus_name)
 
799
        real_value = [None,]
904
800
        def setter(self, value):
 
801
            old_value = real_value[0]
 
802
            real_value[0] = value
905
803
            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)
 
804
                if type_func(old_value) != type_func(real_value[0]):
 
805
                    dbus_value = transform_func(type_func(real_value[0]),
 
806
                                                variant_level)
912
807
                    self.PropertyChanged(dbus.String(dbus_name),
913
808
                                         dbus_value)
914
 
            setattr(self, attrname, value)
915
 
        
916
 
        return property(lambda self: getattr(self, attrname), setter)
917
 
    
918
 
    
 
809
 
 
810
        return property(lambda self: real_value[0], setter)
 
811
 
 
812
 
919
813
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
920
814
    approvals_pending = notifychangeproperty(dbus.Boolean,
921
815
                                             "ApprovalPending",
924
818
    last_enabled = notifychangeproperty(datetime_to_dbus,
925
819
                                        "LastEnabled")
926
820
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
927
 
                                   type_func = lambda checker:
928
 
                                       checker is not None)
 
821
                                   type_func = lambda checker: checker is not None)
929
822
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
930
823
                                           "LastCheckedOK")
931
 
    last_approval_request = notifychangeproperty(
932
 
        datetime_to_dbus, "LastApprovalRequest")
 
824
    last_approval_request = notifychangeproperty(datetime_to_dbus,
 
825
                                                 "LastApprovalRequest")
933
826
    approved_by_default = notifychangeproperty(dbus.Boolean,
934
827
                                               "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)
 
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)
942
832
    host = notifychangeproperty(dbus.String, "Host")
943
833
    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)
 
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)
953
839
    checker_command = notifychangeproperty(dbus.String, "Checker")
954
840
    
955
841
    del notifychangeproperty
981
867
        
982
868
        return Client.checker_callback(self, pid, condition, command,
983
869
                                       *args, **kwargs)
984
 
    
 
870
 
985
871
    def start_checker(self, *args, **kwargs):
986
872
        old_checker = self.checker
987
873
        if self.checker is not None:
1009
895
    
1010
896
    
1011
897
    ## D-Bus methods, signals & properties
1012
 
    _interface = "se.recompile.Mandos.Client"
 
898
    _interface = "se.bsnet.fukt.Mandos.Client"
1013
899
    
1014
900
    ## Signals
1015
901
    
1190
1076
        gobject.source_remove(self.disable_initiator_tag)
1191
1077
        self.disable_initiator_tag = None
1192
1078
        self.expires = None
1193
 
        time_to_die = _timedelta_to_milliseconds((self
1194
 
                                                  .last_checked_ok
1195
 
                                                  + self.timeout)
1196
 
                                                 - datetime.datetime
1197
 
                                                 .utcnow())
 
1079
        time_to_die = (self.
 
1080
                       _timedelta_to_milliseconds((self
 
1081
                                                   .last_checked_ok
 
1082
                                                   + self.timeout)
 
1083
                                                  - datetime.datetime
 
1084
                                                  .utcnow()))
1198
1085
        if time_to_die <= 0:
1199
1086
            # The timeout has passed
1200
1087
            self.disable()
1201
1088
        else:
1202
1089
            self.expires = (datetime.datetime.utcnow()
1203
 
                            + datetime.timedelta(milliseconds =
1204
 
                                                 time_to_die))
 
1090
                            + datetime.timedelta(milliseconds = time_to_die))
1205
1091
            self.disable_initiator_tag = (gobject.timeout_add
1206
1092
                                          (time_to_die, self.disable))
1207
 
    
 
1093
 
1208
1094
    # ExtendedTimeout - property
1209
1095
    @dbus_service_property(_interface, signature="t",
1210
1096
                           access="readwrite")
1212
1098
        if value is None:       # get
1213
1099
            return dbus.UInt64(self.extended_timeout_milliseconds())
1214
1100
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1215
 
    
 
1101
 
1216
1102
    # Interval - property
1217
1103
    @dbus_service_property(_interface, signature="t",
1218
1104
                           access="readwrite")
1227
1113
        self.checker_initiator_tag = (gobject.timeout_add
1228
1114
                                      (value, self.start_checker))
1229
1115
        self.start_checker()    # Start one now, too
1230
 
    
 
1116
 
1231
1117
    # Checker - property
1232
1118
    @dbus_service_property(_interface, signature="s",
1233
1119
                           access="readwrite")
1267
1153
        self._pipe.send(('init', fpr, address))
1268
1154
        if not self._pipe.recv():
1269
1155
            raise KeyError()
1270
 
    
 
1156
 
1271
1157
    def __getattribute__(self, name):
1272
1158
        if(name == '_pipe'):
1273
1159
            return super(ProxyClient, self).__getattribute__(name)
1280
1166
                self._pipe.send(('funcall', name, args, kwargs))
1281
1167
                return self._pipe.recv()[1]
1282
1168
            return func
1283
 
    
 
1169
 
1284
1170
    def __setattr__(self, name, value):
1285
1171
        if(name == '_pipe'):
1286
1172
            return super(ProxyClient, self).__setattr__(name, value)
1287
1173
        self._pipe.send(('setattr', name, value))
1288
1174
 
1289
 
class ClientDBusTransitional(ClientDBus):
1290
 
    __metaclass__ = AlternateDBusNamesMetaclass
1291
1175
 
1292
1176
class ClientHandler(socketserver.BaseRequestHandler, object):
1293
1177
    """A class to handle client connections.
1301
1185
                        unicode(self.client_address))
1302
1186
            logger.debug("Pipe FD: %d",
1303
1187
                         self.server.child_pipe.fileno())
1304
 
            
 
1188
 
1305
1189
            session = (gnutls.connection
1306
1190
                       .ClientSession(self.request,
1307
1191
                                      gnutls.connection
1308
1192
                                      .X509Credentials()))
1309
 
            
 
1193
 
1310
1194
            # Note: gnutls.connection.X509Credentials is really a
1311
1195
            # generic GnuTLS certificate credentials object so long as
1312
1196
            # no X.509 keys are added to it.  Therefore, we can use it
1313
1197
            # here despite using OpenPGP certificates.
1314
 
            
 
1198
 
1315
1199
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1316
1200
            #                      "+AES-256-CBC", "+SHA1",
1317
1201
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1323
1207
            (gnutls.library.functions
1324
1208
             .gnutls_priority_set_direct(session._c_object,
1325
1209
                                         priority, None))
1326
 
            
 
1210
 
1327
1211
            # Start communication using the Mandos protocol
1328
1212
            # Get protocol number
1329
1213
            line = self.request.makefile().readline()
1334
1218
            except (ValueError, IndexError, RuntimeError) as error:
1335
1219
                logger.error("Unknown protocol version: %s", error)
1336
1220
                return
1337
 
            
 
1221
 
1338
1222
            # Start GnuTLS connection
1339
1223
            try:
1340
1224
                session.handshake()
1344
1228
                # established.  Just abandon the request.
1345
1229
                return
1346
1230
            logger.debug("Handshake succeeded")
1347
 
            
 
1231
 
1348
1232
            approval_required = False
1349
1233
            try:
1350
1234
                try:
1355
1239
                    logger.warning("Bad certificate: %s", error)
1356
1240
                    return
1357
1241
                logger.debug("Fingerprint: %s", fpr)
1358
 
                
 
1242
 
1359
1243
                try:
1360
1244
                    client = ProxyClient(child_pipe, fpr,
1361
1245
                                         self.client_address)
1373
1257
                                       client.name)
1374
1258
                        if self.server.use_dbus:
1375
1259
                            # Emit D-Bus signal
1376
 
                            client.Rejected("Disabled")
 
1260
                            client.Rejected("Disabled")                    
1377
1261
                        return
1378
1262
                    
1379
1263
                    if client._approved or not client.approval_delay:
1396
1280
                        return
1397
1281
                    
1398
1282
                    #wait until timeout or approved
 
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
 
                # bump the timeout using extended_timeout
 
1316
                # bump the timeout as if seen
1434
1317
                client.checked_ok(client.extended_timeout)
1435
1318
                if self.server.use_dbus:
1436
1319
                    # Emit D-Bus signal
1516
1399
        except:
1517
1400
            self.handle_error(request, address)
1518
1401
        self.close_request(request)
1519
 
    
 
1402
            
1520
1403
    def process_request(self, request, address):
1521
1404
        """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
 
 
 
1405
        multiprocessing.Process(target = self.sub_process_main,
 
1406
                                args = (request, address)).start()
1528
1407
 
1529
1408
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1530
1409
    """ adds a pipe to the MixIn """
1534
1413
        This function creates a new pipe in self.pipe
1535
1414
        """
1536
1415
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1537
 
        
1538
 
        proc = MultiprocessingMixIn.process_request(self, request,
1539
 
                                                    client_address)
 
1416
 
 
1417
        super(MultiprocessingMixInWithPipe,
 
1418
              self).process_request(request, client_address)
1540
1419
        self.child_pipe.close()
1541
 
        self.add_pipe(parent_pipe, proc)
1542
 
    
1543
 
    def add_pipe(self, parent_pipe, proc):
 
1420
        self.add_pipe(parent_pipe)
 
1421
 
 
1422
    def add_pipe(self, parent_pipe):
1544
1423
        """Dummy function; override as necessary"""
1545
1424
        raise NotImplementedError
1546
1425
 
1547
 
 
1548
1426
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1549
1427
                     socketserver.TCPServer, object):
1550
1428
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1634
1512
    def server_activate(self):
1635
1513
        if self.enabled:
1636
1514
            return socketserver.TCPServer.server_activate(self)
1637
 
    
1638
1515
    def enable(self):
1639
1516
        self.enabled = True
1640
 
    
1641
 
    def add_pipe(self, parent_pipe, proc):
 
1517
    def add_pipe(self, parent_pipe):
1642
1518
        # Call "handle_ipc" for both data and EOF events
1643
1519
        gobject.io_add_watch(parent_pipe.fileno(),
1644
1520
                             gobject.IO_IN | gobject.IO_HUP,
1645
1521
                             functools.partial(self.handle_ipc,
1646
 
                                               parent_pipe =
1647
 
                                               parent_pipe,
1648
 
                                               proc = proc))
1649
 
    
 
1522
                                               parent_pipe = parent_pipe))
 
1523
        
1650
1524
    def handle_ipc(self, source, condition, parent_pipe=None,
1651
 
                   proc = None, client_object=None):
 
1525
                   client_object=None):
1652
1526
        condition_names = {
1653
1527
            gobject.IO_IN: "IN",   # There is data to read.
1654
1528
            gobject.IO_OUT: "OUT", # Data can be written (without
1663
1537
                                       for cond, name in
1664
1538
                                       condition_names.iteritems()
1665
1539
                                       if cond & condition)
1666
 
        # error, or the other end of multiprocessing.Pipe has closed
 
1540
        # error or the other end of multiprocessing.Pipe has closed
1667
1541
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1668
 
            # Wait for other process to exit
1669
 
            proc.join()
1670
1542
            return False
1671
1543
        
1672
1544
        # Read a request from the child
1686
1558
                            "dress: %s", fpr, address)
1687
1559
                if self.use_dbus:
1688
1560
                    # Emit D-Bus signal
1689
 
                    mandos_dbus_service.ClientNotFound(fpr,
1690
 
                                                       address[0])
 
1561
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1691
1562
                parent_pipe.send(False)
1692
1563
                return False
1693
1564
            
1694
1565
            gobject.io_add_watch(parent_pipe.fileno(),
1695
1566
                                 gobject.IO_IN | gobject.IO_HUP,
1696
1567
                                 functools.partial(self.handle_ipc,
1697
 
                                                   parent_pipe =
1698
 
                                                   parent_pipe,
1699
 
                                                   proc = proc,
1700
 
                                                   client_object =
1701
 
                                                   client))
 
1568
                                                   parent_pipe = parent_pipe,
 
1569
                                                   client_object = client))
1702
1570
            parent_pipe.send(True)
1703
 
            # remove the old hook in favor of the new above hook on
1704
 
            # same fileno
 
1571
            # remove the old hook in favor of the new above hook on same fileno
1705
1572
            return False
1706
1573
        if command == 'funcall':
1707
1574
            funcname = request[1]
1708
1575
            args = request[2]
1709
1576
            kwargs = request[3]
1710
1577
            
1711
 
            parent_pipe.send(('data', getattr(client_object,
1712
 
                                              funcname)(*args,
1713
 
                                                         **kwargs)))
1714
 
        
 
1578
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1579
 
1715
1580
        if command == 'getattr':
1716
1581
            attrname = request[1]
1717
1582
            if callable(client_object.__getattribute__(attrname)):
1718
1583
                parent_pipe.send(('function',))
1719
1584
            else:
1720
 
                parent_pipe.send(('data', client_object
1721
 
                                  .__getattribute__(attrname)))
 
1585
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1722
1586
        
1723
1587
        if command == 'setattr':
1724
1588
            attrname = request[1]
1725
1589
            value = request[2]
1726
1590
            setattr(client_object, attrname, value)
1727
 
        
 
1591
 
1728
1592
        return True
1729
1593
 
1730
1594
 
1909
1773
    debuglevel = server_settings["debuglevel"]
1910
1774
    use_dbus = server_settings["use_dbus"]
1911
1775
    use_ipv6 = server_settings["use_ipv6"]
1912
 
    
 
1776
 
1913
1777
    if server_settings["servicename"] != "Mandos":
1914
1778
        syslogger.setFormatter(logging.Formatter
1915
1779
                               ('Mandos (%s) [%%(process)d]:'
1976
1840
        level = getattr(logging, debuglevel.upper())
1977
1841
        syslogger.setLevel(level)
1978
1842
        console.setLevel(level)
1979
 
    
 
1843
 
1980
1844
    if debug:
1981
1845
        # Enable all possible GnuTLS debugging
1982
1846
        
2013
1877
    # End of Avahi example code
2014
1878
    if use_dbus:
2015
1879
        try:
2016
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1880
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2017
1881
                                            bus, do_not_queue=True)
2018
 
            old_bus_name = (dbus.service.BusName
2019
 
                            ("se.bsnet.fukt.Mandos", bus,
2020
 
                             do_not_queue=True))
2021
1882
        except dbus.exceptions.NameExistsException as e:
2022
1883
            logger.error(unicode(e) + ", disabling D-Bus")
2023
1884
            use_dbus = False
2036
1897
    
2037
1898
    client_class = Client
2038
1899
    if use_dbus:
2039
 
        client_class = functools.partial(ClientDBusTransitional,
2040
 
                                         bus = bus)
 
1900
        client_class = functools.partial(ClientDBus, bus = bus)
2041
1901
    def client_config_items(config, section):
2042
1902
        special_settings = {
2043
1903
            "approved_by_default":
2073
1933
        del pidfilename
2074
1934
        
2075
1935
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2076
 
    
 
1936
 
2077
1937
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2078
1938
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2079
1939
    
2082
1942
            """A D-Bus proxy object"""
2083
1943
            def __init__(self):
2084
1944
                dbus.service.Object.__init__(self, bus, "/")
2085
 
            _interface = "se.recompile.Mandos"
 
1945
            _interface = "se.bsnet.fukt.Mandos"
2086
1946
            
2087
1947
            @dbus.service.signal(_interface, signature="o")
2088
1948
            def ClientAdded(self, objpath):
2130
1990
            
2131
1991
            del _interface
2132
1992
        
2133
 
        class MandosDBusServiceTransitional(MandosDBusService):
2134
 
            __metaclass__ = AlternateDBusNamesMetaclass
2135
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1993
        mandos_dbus_service = MandosDBusService()
2136
1994
    
2137
1995
    def cleanup():
2138
1996
        "Cleanup function; run on exit"
2139
1997
        service.cleanup()
2140
1998
        
2141
 
        multiprocessing.active_children()
2142
1999
        while tcp_server.clients:
2143
2000
            client = tcp_server.clients.pop()
2144
2001
            if use_dbus:
2148
2005
            client.disable(quiet=True)
2149
2006
            if use_dbus:
2150
2007
                # Emit D-Bus signal
2151
 
                mandos_dbus_service.ClientRemoved(client
2152
 
                                                  .dbus_object_path,
 
2008
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2153
2009
                                                  client.name)
2154
2010
    
2155
2011
    atexit.register(cleanup)
2204
2060
    # Must run before the D-Bus bus name gets deregistered
2205
2061
    cleanup()
2206
2062
 
2207
 
 
2208
2063
if __name__ == '__main__':
2209
2064
    main()