/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: 2015-05-31 15:29:22 UTC
  • Revision ID: teddy@recompile.se-20150531152922-o1xv6qr3hbj1twm0
mandos: Use codecs.open() and print() for PID file.

Use more Pythonic code, closer to the Python 3 style.

Show diffs side-by-side

added added

removed removed

Lines of Context:
104
104
if sys.version_info.major == 2:
105
105
    str = unicode
106
106
 
107
 
version = "1.7.1"
 
107
version = "1.6.9"
108
108
stored_state_file = "clients.pickle"
109
109
 
110
110
logger = logging.getLogger()
395
395
                    logger.error(bad_states[state] + ": %r", error)
396
396
            self.cleanup()
397
397
        elif state == avahi.SERVER_RUNNING:
398
 
            try:
399
 
                self.add()
400
 
            except dbus.exceptions.DBusException as error:
401
 
                if (error.get_dbus_name()
402
 
                    == "org.freedesktop.Avahi.CollisionError"):
403
 
                    logger.info("Local Zeroconf service name"
404
 
                                " collision.")
405
 
                    return self.rename(remove=False)
406
 
                else:
407
 
                    logger.critical("D-Bus Exception", exc_info=error)
408
 
                    self.cleanup()
409
 
                    os._exit(1)
 
398
            self.add()
410
399
        else:
411
400
            if error is None:
412
401
                logger.debug("Unknown state: %r", state)
435
424
            .format(self.name)))
436
425
        return ret
437
426
 
438
 
def call_pipe(connection,       # : multiprocessing.Connection
439
 
              func, *args, **kwargs):
440
 
    """This function is meant to be called by multiprocessing.Process
441
 
    
442
 
    This function runs func(*args, **kwargs), and writes the resulting
443
 
    return value on the provided multiprocessing.Connection.
444
 
    """
445
 
    connection.send(func(*args, **kwargs))
446
 
    connection.close()
447
427
 
448
428
class Client(object):
449
429
    """A representation of a client host served by this server.
476
456
    last_checker_status: integer between 0 and 255 reflecting exit
477
457
                         status of last checker. -1 reflects crashed
478
458
                         checker, -2 means no checker completed yet.
479
 
    last_checker_signal: The signal which killed the last checker, if
480
 
                         last_checker_status is -1
481
459
    last_enabled: datetime.datetime(); (UTC) or None
482
460
    name:       string; from the config file, used in log messages and
483
461
                        D-Bus identifiers
657
635
        # Also start a new checker *right now*.
658
636
        self.start_checker()
659
637
    
660
 
    def checker_callback(self, source, condition, connection,
661
 
                         command):
 
638
    def checker_callback(self, pid, condition, command):
662
639
        """The checker has completed, so take appropriate actions."""
663
640
        self.checker_callback_tag = None
664
641
        self.checker = None
665
 
        # Read return code from connection (see call_pipe)
666
 
        returncode = connection.recv()
667
 
        connection.close()
668
 
        
669
 
        if returncode >= 0:
670
 
            self.last_checker_status = returncode
671
 
            self.last_checker_signal = None
 
642
        if os.WIFEXITED(condition):
 
643
            self.last_checker_status = os.WEXITSTATUS(condition)
672
644
            if self.last_checker_status == 0:
673
645
                logger.info("Checker for %(name)s succeeded",
674
646
                            vars(self))
677
649
                logger.info("Checker for %(name)s failed", vars(self))
678
650
        else:
679
651
            self.last_checker_status = -1
680
 
            self.last_checker_signal = -returncode
681
652
            logger.warning("Checker for %(name)s crashed?",
682
653
                           vars(self))
683
 
        return False
684
654
    
685
655
    def checked_ok(self):
686
656
        """Assert that the client has been seen, alive and well."""
687
657
        self.last_checked_ok = datetime.datetime.utcnow()
688
658
        self.last_checker_status = 0
689
 
        self.last_checker_signal = None
690
659
        self.bump_timeout()
691
660
    
692
661
    def bump_timeout(self, timeout=None):
718
687
        # than 'timeout' for the client to be disabled, which is as it
719
688
        # should be.
720
689
        
721
 
        if self.checker is not None and not self.checker.is_alive():
722
 
            logger.warning("Checker was not alive; joining")
723
 
            self.checker.join()
724
 
            self.checker = None
 
690
        # If a checker exists, make sure it is not a zombie
 
691
        try:
 
692
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
693
        except AttributeError:
 
694
            pass
 
695
        except OSError as error:
 
696
            if error.errno != errno.ECHILD:
 
697
                raise
 
698
        else:
 
699
            if pid:
 
700
                logger.warning("Checker was a zombie")
 
701
                gobject.source_remove(self.checker_callback_tag)
 
702
                self.checker_callback(pid, status,
 
703
                                      self.current_checker_command)
725
704
        # Start a new checker if needed
726
705
        if self.checker is None:
727
706
            # Escape attributes for the shell
736
715
                             exc_info=error)
737
716
                return True     # Try again later
738
717
            self.current_checker_command = command
739
 
            logger.info("Starting checker %r for %s", command,
740
 
                        self.name)
741
 
            # We don't need to redirect stdout and stderr, since
742
 
            # in normal mode, that is already done by daemon(),
743
 
            # and in debug mode we don't want to.  (Stdin is
744
 
            # always replaced by /dev/null.)
745
 
            # The exception is when not debugging but nevertheless
746
 
            # running in the foreground; use the previously
747
 
            # created wnull.
748
 
            popen_args = { "close_fds": True,
749
 
                           "shell": True,
750
 
                           "cwd": "/" }
751
 
            if (not self.server_settings["debug"]
752
 
                and self.server_settings["foreground"]):
753
 
                popen_args.update({"stdout": wnull,
754
 
                                   "stderr": wnull })
755
 
            pipe = multiprocessing.Pipe(duplex = False)
756
 
            self.checker = multiprocessing.Process(
757
 
                target = call_pipe,
758
 
                args = (pipe[1], subprocess.call, command),
759
 
                kwargs = popen_args)
760
 
            self.checker.start()
761
 
            self.checker_callback_tag = gobject.io_add_watch(
762
 
                pipe[0].fileno(), gobject.IO_IN,
763
 
                self.checker_callback, pipe[0], command)
 
718
            try:
 
719
                logger.info("Starting checker %r for %s", command,
 
720
                            self.name)
 
721
                # We don't need to redirect stdout and stderr, since
 
722
                # in normal mode, that is already done by daemon(),
 
723
                # and in debug mode we don't want to.  (Stdin is
 
724
                # always replaced by /dev/null.)
 
725
                # The exception is when not debugging but nevertheless
 
726
                # running in the foreground; use the previously
 
727
                # created wnull.
 
728
                popen_args = {}
 
729
                if (not self.server_settings["debug"]
 
730
                    and self.server_settings["foreground"]):
 
731
                    popen_args.update({"stdout": wnull,
 
732
                                       "stderr": wnull })
 
733
                self.checker = subprocess.Popen(command,
 
734
                                                close_fds=True,
 
735
                                                shell=True,
 
736
                                                cwd="/",
 
737
                                                **popen_args)
 
738
            except OSError as error:
 
739
                logger.error("Failed to start subprocess",
 
740
                             exc_info=error)
 
741
                return True
 
742
            self.checker_callback_tag = gobject.child_watch_add(
 
743
                self.checker.pid, self.checker_callback, data=command)
 
744
            # The checker may have completed before the gobject
 
745
            # watch was added.  Check for this.
 
746
            try:
 
747
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
748
            except OSError as error:
 
749
                if error.errno == errno.ECHILD:
 
750
                    # This should never happen
 
751
                    logger.error("Child process vanished",
 
752
                                 exc_info=error)
 
753
                    return True
 
754
                raise
 
755
            if pid:
 
756
                gobject.source_remove(self.checker_callback_tag)
 
757
                self.checker_callback(pid, status, command)
764
758
        # Re-run this periodically if run by gobject.timeout_add
765
759
        return True
766
760
    
772
766
        if getattr(self, "checker", None) is None:
773
767
            return
774
768
        logger.debug("Stopping checker for %(name)s", vars(self))
775
 
        self.checker.terminate()
 
769
        try:
 
770
            self.checker.terminate()
 
771
            #time.sleep(0.5)
 
772
            #if self.checker.poll() is None:
 
773
            #    self.checker.kill()
 
774
        except OSError as error:
 
775
            if error.errno != errno.ESRCH: # No such process
 
776
                raise
776
777
        self.checker = None
777
778
 
778
779
 
842
843
                           access="r")
843
844
    def Property_dbus_property(self):
844
845
        return dbus.Boolean(False)
845
 
    
846
 
    See also the DBusObjectWithAnnotations class.
847
846
    """
848
847
    
849
848
    def decorator(func):
871
870
    pass
872
871
 
873
872
 
874
 
class DBusObjectWithAnnotations(dbus.service.Object):
875
 
    """A D-Bus object with annotations.
 
873
class DBusObjectWithProperties(dbus.service.Object):
 
874
    """A D-Bus object with properties.
876
875
    
877
 
    Classes inheriting from this can use the dbus_annotations
878
 
    decorator to add annotations to methods or signals.
 
876
    Classes inheriting from this can use the dbus_service_property
 
877
    decorator to expose methods as D-Bus properties.  It exposes the
 
878
    standard Get(), Set(), and GetAll() methods on the D-Bus.
879
879
    """
880
880
    
881
881
    @staticmethod
897
897
                for name, athing in
898
898
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
899
899
    
900
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
901
 
                         out_signature = "s",
902
 
                         path_keyword = 'object_path',
903
 
                         connection_keyword = 'connection')
904
 
    def Introspect(self, object_path, connection):
905
 
        """Overloading of standard D-Bus method.
906
 
        
907
 
        Inserts annotation tags on methods and signals.
908
 
        """
909
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
910
 
                                                   connection)
911
 
        try:
912
 
            document = xml.dom.minidom.parseString(xmlstring)
913
 
            
914
 
            for if_tag in document.getElementsByTagName("interface"):
915
 
                # Add annotation tags
916
 
                for typ in ("method", "signal"):
917
 
                    for tag in if_tag.getElementsByTagName(typ):
918
 
                        annots = dict()
919
 
                        for name, prop in (self.
920
 
                                           _get_all_dbus_things(typ)):
921
 
                            if (name == tag.getAttribute("name")
922
 
                                and prop._dbus_interface
923
 
                                == if_tag.getAttribute("name")):
924
 
                                annots.update(getattr(
925
 
                                    prop, "_dbus_annotations", {}))
926
 
                        for name, value in annots.items():
927
 
                            ann_tag = document.createElement(
928
 
                                "annotation")
929
 
                            ann_tag.setAttribute("name", name)
930
 
                            ann_tag.setAttribute("value", value)
931
 
                            tag.appendChild(ann_tag)
932
 
                # Add interface annotation tags
933
 
                for annotation, value in dict(
934
 
                    itertools.chain.from_iterable(
935
 
                        annotations().items()
936
 
                        for name, annotations
937
 
                        in self._get_all_dbus_things("interface")
938
 
                        if name == if_tag.getAttribute("name")
939
 
                        )).items():
940
 
                    ann_tag = document.createElement("annotation")
941
 
                    ann_tag.setAttribute("name", annotation)
942
 
                    ann_tag.setAttribute("value", value)
943
 
                    if_tag.appendChild(ann_tag)
944
 
                # Fix argument name for the Introspect method itself
945
 
                if (if_tag.getAttribute("name")
946
 
                                == dbus.INTROSPECTABLE_IFACE):
947
 
                    for cn in if_tag.getElementsByTagName("method"):
948
 
                        if cn.getAttribute("name") == "Introspect":
949
 
                            for arg in cn.getElementsByTagName("arg"):
950
 
                                if (arg.getAttribute("direction")
951
 
                                    == "out"):
952
 
                                    arg.setAttribute("name",
953
 
                                                     "xml_data")
954
 
            xmlstring = document.toxml("utf-8")
955
 
            document.unlink()
956
 
        except (AttributeError, xml.dom.DOMException,
957
 
                xml.parsers.expat.ExpatError) as error:
958
 
            logger.error("Failed to override Introspection method",
959
 
                         exc_info=error)
960
 
        return xmlstring
961
 
 
962
 
 
963
 
class DBusObjectWithProperties(DBusObjectWithAnnotations):
964
 
    """A D-Bus object with properties.
965
 
    
966
 
    Classes inheriting from this can use the dbus_service_property
967
 
    decorator to expose methods as D-Bus properties.  It exposes the
968
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
969
 
    """
970
 
    
971
900
    def _get_dbus_property(self, interface_name, property_name):
972
901
        """Returns a bound method if one exists which is a D-Bus
973
902
        property with the specified name and interface.
983
912
        raise DBusPropertyNotFound("{}:{}.{}".format(
984
913
            self.dbus_object_path, interface_name, property_name))
985
914
    
986
 
    @classmethod
987
 
    def _get_all_interface_names(cls):
988
 
        """Get a sequence of all interfaces supported by an object"""
989
 
        return (name for name in set(getattr(getattr(x, attr),
990
 
                                             "_dbus_interface", None)
991
 
                                     for x in (inspect.getmro(cls))
992
 
                                     for attr in dir(x))
993
 
                if name is not None)
994
 
    
995
915
    @dbus.service.method(dbus.PROPERTIES_IFACE,
996
916
                         in_signature="ss",
997
917
                         out_signature="v")
1067
987
        
1068
988
        Inserts property tags and interface annotation tags.
1069
989
        """
1070
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1071
 
                                                         object_path,
1072
 
                                                         connection)
 
990
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
991
                                                   connection)
1073
992
        try:
1074
993
            document = xml.dom.minidom.parseString(xmlstring)
1075
994
            
1088
1007
                            if prop._dbus_interface
1089
1008
                            == if_tag.getAttribute("name")):
1090
1009
                    if_tag.appendChild(tag)
1091
 
                # Add annotation tags for properties
1092
 
                for tag in if_tag.getElementsByTagName("property"):
1093
 
                    annots = dict()
1094
 
                    for name, prop in self._get_all_dbus_things(
1095
 
                            "property"):
1096
 
                        if (name == tag.getAttribute("name")
1097
 
                            and prop._dbus_interface
1098
 
                            == if_tag.getAttribute("name")):
1099
 
                            annots.update(getattr(
1100
 
                                prop, "_dbus_annotations", {}))
1101
 
                    for name, value in annots.items():
1102
 
                        ann_tag = document.createElement(
1103
 
                            "annotation")
1104
 
                        ann_tag.setAttribute("name", name)
1105
 
                        ann_tag.setAttribute("value", value)
1106
 
                        tag.appendChild(ann_tag)
 
1010
                # Add annotation tags
 
1011
                for typ in ("method", "signal", "property"):
 
1012
                    for tag in if_tag.getElementsByTagName(typ):
 
1013
                        annots = dict()
 
1014
                        for name, prop in (self.
 
1015
                                           _get_all_dbus_things(typ)):
 
1016
                            if (name == tag.getAttribute("name")
 
1017
                                and prop._dbus_interface
 
1018
                                == if_tag.getAttribute("name")):
 
1019
                                annots.update(getattr(
 
1020
                                    prop, "_dbus_annotations", {}))
 
1021
                        for name, value in annots.items():
 
1022
                            ann_tag = document.createElement(
 
1023
                                "annotation")
 
1024
                            ann_tag.setAttribute("name", name)
 
1025
                            ann_tag.setAttribute("value", value)
 
1026
                            tag.appendChild(ann_tag)
 
1027
                # Add interface annotation tags
 
1028
                for annotation, value in dict(
 
1029
                    itertools.chain.from_iterable(
 
1030
                        annotations().items()
 
1031
                        for name, annotations
 
1032
                        in self._get_all_dbus_things("interface")
 
1033
                        if name == if_tag.getAttribute("name")
 
1034
                        )).items():
 
1035
                    ann_tag = document.createElement("annotation")
 
1036
                    ann_tag.setAttribute("name", annotation)
 
1037
                    ann_tag.setAttribute("value", value)
 
1038
                    if_tag.appendChild(ann_tag)
1107
1039
                # Add the names to the return values for the
1108
1040
                # "org.freedesktop.DBus.Properties" methods
1109
1041
                if (if_tag.getAttribute("name")
1127
1059
                         exc_info=error)
1128
1060
        return xmlstring
1129
1061
 
1130
 
try:
1131
 
    dbus.OBJECT_MANAGER_IFACE
1132
 
except AttributeError:
1133
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1134
 
 
1135
 
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1136
 
    """A D-Bus object with an ObjectManager.
1137
 
    
1138
 
    Classes inheriting from this exposes the standard
1139
 
    GetManagedObjects call and the InterfacesAdded and
1140
 
    InterfacesRemoved signals on the standard
1141
 
    "org.freedesktop.DBus.ObjectManager" interface.
1142
 
    
1143
 
    Note: No signals are sent automatically; they must be sent
1144
 
    manually.
1145
 
    """
1146
 
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1147
 
                         out_signature = "a{oa{sa{sv}}}")
1148
 
    def GetManagedObjects(self):
1149
 
        """This function must be overridden"""
1150
 
        raise NotImplementedError()
1151
 
    
1152
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1153
 
                         signature = "oa{sa{sv}}")
1154
 
    def InterfacesAdded(self, object_path, interfaces_and_properties):
1155
 
        pass
1156
 
    
1157
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1158
 
    def InterfacesRemoved(self, object_path, interfaces):
1159
 
        pass
1160
 
    
1161
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1162
 
                         out_signature = "s",
1163
 
                         path_keyword = 'object_path',
1164
 
                         connection_keyword = 'connection')
1165
 
    def Introspect(self, object_path, connection):
1166
 
        """Overloading of standard D-Bus method.
1167
 
        
1168
 
        Override return argument name of GetManagedObjects to be
1169
 
        "objpath_interfaces_and_properties"
1170
 
        """
1171
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1172
 
                                                         object_path,
1173
 
                                                         connection)
1174
 
        try:
1175
 
            document = xml.dom.minidom.parseString(xmlstring)
1176
 
            
1177
 
            for if_tag in document.getElementsByTagName("interface"):
1178
 
                # Fix argument name for the GetManagedObjects method
1179
 
                if (if_tag.getAttribute("name")
1180
 
                                == dbus.OBJECT_MANAGER_IFACE):
1181
 
                    for cn in if_tag.getElementsByTagName("method"):
1182
 
                        if (cn.getAttribute("name")
1183
 
                            == "GetManagedObjects"):
1184
 
                            for arg in cn.getElementsByTagName("arg"):
1185
 
                                if (arg.getAttribute("direction")
1186
 
                                    == "out"):
1187
 
                                    arg.setAttribute(
1188
 
                                        "name",
1189
 
                                        "objpath_interfaces"
1190
 
                                        "_and_properties")
1191
 
            xmlstring = document.toxml("utf-8")
1192
 
            document.unlink()
1193
 
        except (AttributeError, xml.dom.DOMException,
1194
 
                xml.parsers.expat.ExpatError) as error:
1195
 
            logger.error("Failed to override Introspection method",
1196
 
                         exc_info = error)
1197
 
        return xmlstring
1198
1062
 
1199
1063
def datetime_to_dbus(dt, variant_level=0):
1200
1064
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1247
1111
                interface_names.add(alt_interface)
1248
1112
                # Is this a D-Bus signal?
1249
1113
                if getattr(attribute, "_dbus_is_signal", False):
1250
 
                    if sys.version_info.major == 2:
1251
 
                        # Extract the original non-method undecorated
1252
 
                        # function by black magic
1253
 
                        nonmethod_func = (dict(
1254
 
                            zip(attribute.func_code.co_freevars,
1255
 
                                attribute.__closure__))
1256
 
                                          ["func"].cell_contents)
1257
 
                    else:
1258
 
                        nonmethod_func = attribute
 
1114
                    # Extract the original non-method undecorated
 
1115
                    # function by black magic
 
1116
                    nonmethod_func = (dict(
 
1117
                        zip(attribute.func_code.co_freevars,
 
1118
                            attribute.__closure__))
 
1119
                                      ["func"].cell_contents)
1259
1120
                    # Create a new, but exactly alike, function
1260
1121
                    # object, and decorate it to be a new D-Bus signal
1261
1122
                    # with the alternate D-Bus interface name
1262
 
                    if sys.version_info.major == 2:
1263
 
                        new_function = types.FunctionType(
1264
 
                            nonmethod_func.func_code,
1265
 
                            nonmethod_func.func_globals,
1266
 
                            nonmethod_func.func_name,
1267
 
                            nonmethod_func.func_defaults,
1268
 
                            nonmethod_func.func_closure)
1269
 
                    else:
1270
 
                        new_function = types.FunctionType(
1271
 
                            nonmethod_func.__code__,
1272
 
                            nonmethod_func.__globals__,
1273
 
                            nonmethod_func.__name__,
1274
 
                            nonmethod_func.__defaults__,
1275
 
                            nonmethod_func.__closure__)
1276
1123
                    new_function = (dbus.service.signal(
1277
 
                        alt_interface,
1278
 
                        attribute._dbus_signature)(new_function))
 
1124
                        alt_interface, attribute._dbus_signature)
 
1125
                                    (types.FunctionType(
 
1126
                                        nonmethod_func.func_code,
 
1127
                                        nonmethod_func.func_globals,
 
1128
                                        nonmethod_func.func_name,
 
1129
                                        nonmethod_func.func_defaults,
 
1130
                                        nonmethod_func.func_closure)))
1279
1131
                    # Copy annotations, if any
1280
1132
                    try:
1281
1133
                        new_function._dbus_annotations = dict(
1291
1143
                        func1 and func2 to the "call_both" function
1292
1144
                        outside of its arguments"""
1293
1145
                        
1294
 
                        @functools.wraps(func2)
1295
1146
                        def call_both(*args, **kwargs):
1296
1147
                            """This function will emit two D-Bus
1297
1148
                            signals by calling func1 and func2"""
1298
1149
                            func1(*args, **kwargs)
1299
1150
                            func2(*args, **kwargs)
1300
 
                        # Make wrapper function look like a D-Bus signal
1301
 
                        for name, attr in inspect.getmembers(func2):
1302
 
                            if name.startswith("_dbus_"):
1303
 
                                setattr(call_both, name, attr)
1304
1151
                        
1305
1152
                        return call_both
1306
1153
                    # Create the "call_both" function and add it to
1509
1356
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1510
1357
        Client.__del__(self, *args, **kwargs)
1511
1358
    
1512
 
    def checker_callback(self, source, condition,
1513
 
                         connection, command, *args, **kwargs):
1514
 
        ret = Client.checker_callback(self, source, condition,
1515
 
                                      connection, command, *args,
1516
 
                                      **kwargs)
1517
 
        exitstatus = self.last_checker_status
1518
 
        if exitstatus >= 0:
 
1359
    def checker_callback(self, pid, condition, command,
 
1360
                         *args, **kwargs):
 
1361
        self.checker_callback_tag = None
 
1362
        self.checker = None
 
1363
        if os.WIFEXITED(condition):
 
1364
            exitstatus = os.WEXITSTATUS(condition)
1519
1365
            # Emit D-Bus signal
1520
1366
            self.CheckerCompleted(dbus.Int16(exitstatus),
1521
 
                                  # This is specific to GNU libC
1522
 
                                  dbus.Int64(exitstatus << 8),
 
1367
                                  dbus.Int64(condition),
1523
1368
                                  dbus.String(command))
1524
1369
        else:
1525
1370
            # Emit D-Bus signal
1526
1371
            self.CheckerCompleted(dbus.Int16(-1),
1527
 
                                  dbus.Int64(
1528
 
                                      # This is specific to GNU libC
1529
 
                                      (exitstatus << 8)
1530
 
                                      | self.last_checker_signal),
 
1372
                                  dbus.Int64(condition),
1531
1373
                                  dbus.String(command))
1532
 
        return ret
 
1374
        
 
1375
        return Client.checker_callback(self, pid, condition, command,
 
1376
                                       *args, **kwargs)
1533
1377
    
1534
1378
    def start_checker(self, *args, **kwargs):
1535
1379
        old_checker_pid = getattr(self.checker, "pid", None)
1610
1454
        self.checked_ok()
1611
1455
    
1612
1456
    # Enable - method
1613
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1614
1457
    @dbus.service.method(_interface)
1615
1458
    def Enable(self):
1616
1459
        "D-Bus method"
1617
1460
        self.enable()
1618
1461
    
1619
1462
    # StartChecker - method
1620
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1621
1463
    @dbus.service.method(_interface)
1622
1464
    def StartChecker(self):
1623
1465
        "D-Bus method"
1624
1466
        self.start_checker()
1625
1467
    
1626
1468
    # Disable - method
1627
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1628
1469
    @dbus.service.method(_interface)
1629
1470
    def Disable(self):
1630
1471
        "D-Bus method"
1631
1472
        self.disable()
1632
1473
    
1633
1474
    # StopChecker - method
1634
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1635
1475
    @dbus.service.method(_interface)
1636
1476
    def StopChecker(self):
1637
1477
        self.stop_checker()
1673
1513
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1674
1514
    
1675
1515
    # Name - property
1676
 
    @dbus_annotations(
1677
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1678
1516
    @dbus_service_property(_interface, signature="s", access="read")
1679
1517
    def Name_dbus_property(self):
1680
1518
        return dbus.String(self.name)
1681
1519
    
1682
1520
    # Fingerprint - property
1683
 
    @dbus_annotations(
1684
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1685
1521
    @dbus_service_property(_interface, signature="s", access="read")
1686
1522
    def Fingerprint_dbus_property(self):
1687
1523
        return dbus.String(self.fingerprint)
1696
1532
        self.host = str(value)
1697
1533
    
1698
1534
    # Created - property
1699
 
    @dbus_annotations(
1700
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1701
1535
    @dbus_service_property(_interface, signature="s", access="read")
1702
1536
    def Created_dbus_property(self):
1703
1537
        return datetime_to_dbus(self.created)
1818
1652
            self.stop_checker()
1819
1653
    
1820
1654
    # ObjectPath - property
1821
 
    @dbus_annotations(
1822
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
1823
 
         "org.freedesktop.DBus.Deprecated": "true"})
1824
1655
    @dbus_service_property(_interface, signature="o", access="read")
1825
1656
    def ObjectPath_dbus_property(self):
1826
1657
        return self.dbus_object_path # is already a dbus.ObjectPath
1827
1658
    
1828
1659
    # Secret = property
1829
 
    @dbus_annotations(
1830
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
1831
 
         "invalidates"})
1832
1660
    @dbus_service_property(_interface,
1833
1661
                           signature="ay",
1834
1662
                           access="write",
1844
1672
        self._pipe = child_pipe
1845
1673
        self._pipe.send(('init', fpr, address))
1846
1674
        if not self._pipe.recv():
1847
 
            raise KeyError(fpr)
 
1675
            raise KeyError()
1848
1676
    
1849
1677
    def __getattribute__(self, name):
1850
1678
        if name == '_pipe':
2313
2141
        
2314
2142
        if command == 'getattr':
2315
2143
            attrname = request[1]
2316
 
            if isinstance(client_object.__getattribute__(attrname),
2317
 
                          collections.Callable):
 
2144
            if callable(client_object.__getattribute__(attrname)):
2318
2145
                parent_pipe.send(('function', ))
2319
2146
            else:
2320
2147
                parent_pipe.send((
2355
2182
    # avoid excessive use of external libraries.
2356
2183
    
2357
2184
    # New type for defining tokens, syntax, and semantics all-in-one
 
2185
    Token = collections.namedtuple("Token",
 
2186
                                   ("regexp", # To match token; if
 
2187
                                              # "value" is not None,
 
2188
                                              # must have a "group"
 
2189
                                              # containing digits
 
2190
                                    "value",  # datetime.timedelta or
 
2191
                                              # None
 
2192
                                    "followers")) # Tokens valid after
 
2193
                                                  # this token
2358
2194
    Token = collections.namedtuple("Token", (
2359
2195
        "regexp",  # To match token; if "value" is not None, must have
2360
2196
                   # a "group" containing digits
2395
2231
    # Define starting values
2396
2232
    value = datetime.timedelta() # Value so far
2397
2233
    found_token = None
2398
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2234
    followers = frozenset((token_duration,)) # Following valid tokens
2399
2235
    s = duration                # String left to parse
2400
2236
    # Loop until end token is found
2401
2237
    while found_token is not token_end:
2418
2254
                break
2419
2255
        else:
2420
2256
            # No currently valid tokens were found
2421
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2422
 
                             .format(duration))
 
2257
            raise ValueError("Invalid RFC 3339 duration")
2423
2258
    # End token found
2424
2259
    return value
2425
2260
 
2558
2393
                        "debug": "False",
2559
2394
                        "priority":
2560
2395
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2561
 
                        ":+SIGN-DSA-SHA256",
 
2396
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2562
2397
                        "servicename": "Mandos",
2563
2398
                        "use_dbus": "True",
2564
2399
                        "use_ipv6": "True",
2820
2655
                    pass
2821
2656
            
2822
2657
            # Clients who has passed its expire date can still be
2823
 
            # enabled if its last checker was successful.  A Client
 
2658
            # enabled if its last checker was successful.  Clients
2824
2659
            # whose checker succeeded before we stored its state is
2825
2660
            # assumed to have successfully run all checkers during
2826
2661
            # downtime.
2895
2730
        
2896
2731
        @alternate_dbus_interfaces(
2897
2732
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2898
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2733
        class MandosDBusService(DBusObjectWithProperties):
2899
2734
            """A D-Bus proxy object"""
2900
2735
            
2901
2736
            def __init__(self):
2903
2738
            
2904
2739
            _interface = "se.recompile.Mandos"
2905
2740
            
 
2741
            @dbus_interface_annotations(_interface)
 
2742
            def _foo(self):
 
2743
                return {
 
2744
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2745
                    "false" }
 
2746
            
2906
2747
            @dbus.service.signal(_interface, signature="o")
2907
2748
            def ClientAdded(self, objpath):
2908
2749
                "D-Bus signal"
2913
2754
                "D-Bus signal"
2914
2755
                pass
2915
2756
            
2916
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2917
 
                               "true"})
2918
2757
            @dbus.service.signal(_interface, signature="os")
2919
2758
            def ClientRemoved(self, objpath, name):
2920
2759
                "D-Bus signal"
2921
2760
                pass
2922
2761
            
2923
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2924
 
                               "true"})
2925
2762
            @dbus.service.method(_interface, out_signature="ao")
2926
2763
            def GetAllClients(self):
2927
2764
                "D-Bus method"
2928
2765
                return dbus.Array(c.dbus_object_path for c in
2929
2766
                                  tcp_server.clients.itervalues())
2930
2767
            
2931
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2932
 
                               "true"})
2933
2768
            @dbus.service.method(_interface,
2934
2769
                                 out_signature="a{oa{sv}}")
2935
2770
            def GetAllClientsWithProperties(self):
2936
2771
                "D-Bus method"
2937
2772
                return dbus.Dictionary(
2938
 
                    { c.dbus_object_path: c.GetAll(
2939
 
                        "se.recompile.Mandos.Client")
 
2773
                    { c.dbus_object_path: c.GetAll("")
2940
2774
                      for c in tcp_server.clients.itervalues() },
2941
2775
                    signature="oa{sv}")
2942
2776
            
2947
2781
                    if c.dbus_object_path == object_path:
2948
2782
                        del tcp_server.clients[c.name]
2949
2783
                        c.remove_from_connection()
2950
 
                        # Don't signal the disabling
 
2784
                        # Don't signal anything except ClientRemoved
2951
2785
                        c.disable(quiet=True)
2952
 
                        # Emit D-Bus signal for removal
2953
 
                        self.client_removed_signal(c)
 
2786
                        # Emit D-Bus signal
 
2787
                        self.ClientRemoved(object_path, c.name)
2954
2788
                        return
2955
2789
                raise KeyError(object_path)
2956
2790
            
2957
2791
            del _interface
2958
 
            
2959
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
2960
 
                                 out_signature = "a{oa{sa{sv}}}")
2961
 
            def GetManagedObjects(self):
2962
 
                """D-Bus method"""
2963
 
                return dbus.Dictionary(
2964
 
                    { client.dbus_object_path:
2965
 
                      dbus.Dictionary(
2966
 
                          { interface: client.GetAll(interface)
2967
 
                            for interface in
2968
 
                                 client._get_all_interface_names()})
2969
 
                      for client in tcp_server.clients.values()})
2970
 
            
2971
 
            def client_added_signal(self, client):
2972
 
                """Send the new standard signal and the old signal"""
2973
 
                if use_dbus:
2974
 
                    # New standard signal
2975
 
                    self.InterfacesAdded(
2976
 
                        client.dbus_object_path,
2977
 
                        dbus.Dictionary(
2978
 
                            { interface: client.GetAll(interface)
2979
 
                              for interface in
2980
 
                              client._get_all_interface_names()}))
2981
 
                    # Old signal
2982
 
                    self.ClientAdded(client.dbus_object_path)
2983
 
            
2984
 
            def client_removed_signal(self, client):
2985
 
                """Send the new standard signal and the old signal"""
2986
 
                if use_dbus:
2987
 
                    # New standard signal
2988
 
                    self.InterfacesRemoved(
2989
 
                        client.dbus_object_path,
2990
 
                        client._get_all_interface_names())
2991
 
                    # Old signal
2992
 
                    self.ClientRemoved(client.dbus_object_path,
2993
 
                                       client.name)
2994
2792
        
2995
2793
        mandos_dbus_service = MandosDBusService()
2996
2794
    
3061
2859
            name, client = tcp_server.clients.popitem()
3062
2860
            if use_dbus:
3063
2861
                client.remove_from_connection()
3064
 
            # Don't signal the disabling
 
2862
            # Don't signal anything except ClientRemoved
3065
2863
            client.disable(quiet=True)
3066
 
            # Emit D-Bus signal for removal
3067
 
            mandos_dbus_service.client_removed_signal(client)
 
2864
            if use_dbus:
 
2865
                # Emit D-Bus signal
 
2866
                mandos_dbus_service.ClientRemoved(
 
2867
                    client.dbus_object_path, client.name)
3068
2868
        client_settings.clear()
3069
2869
    
3070
2870
    atexit.register(cleanup)
3071
2871
    
3072
2872
    for client in tcp_server.clients.itervalues():
3073
2873
        if use_dbus:
3074
 
            # Emit D-Bus signal for adding
3075
 
            mandos_dbus_service.client_added_signal(client)
 
2874
            # Emit D-Bus signal
 
2875
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3076
2876
        # Need to initiate checking of clients
3077
2877
        if client.enabled:
3078
2878
            client.init_checker()