/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2015-07-12 01:41:14 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • Revision ID: teddy@recompile.se-20150712014114-qbala4mutkixxct3
Handle local Zeroconf service name collisions on startup, too.

* mandos (AvahiService.server_state_changed): Catch name collision
                                              error when adding
                                              server.

Show diffs side-by-side

added added

removed removed

Lines of Context:
842
842
                           access="r")
843
843
    def Property_dbus_property(self):
844
844
        return dbus.Boolean(False)
845
 
    
846
 
    See also the DBusObjectWithAnnotations class.
847
845
    """
848
846
    
849
847
    def decorator(func):
871
869
    pass
872
870
 
873
871
 
874
 
class DBusObjectWithAnnotations(dbus.service.Object):
875
 
    """A D-Bus object with annotations.
 
872
class DBusObjectWithProperties(dbus.service.Object):
 
873
    """A D-Bus object with properties.
876
874
    
877
 
    Classes inheriting from this can use the dbus_annotations
878
 
    decorator to add annotations to methods or signals.
 
875
    Classes inheriting from this can use the dbus_service_property
 
876
    decorator to expose methods as D-Bus properties.  It exposes the
 
877
    standard Get(), Set(), and GetAll() methods on the D-Bus.
879
878
    """
880
879
    
881
880
    @staticmethod
897
896
                for name, athing in
898
897
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
899
898
    
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
899
    def _get_dbus_property(self, interface_name, property_name):
972
900
        """Returns a bound method if one exists which is a D-Bus
973
901
        property with the specified name and interface.
983
911
        raise DBusPropertyNotFound("{}:{}.{}".format(
984
912
            self.dbus_object_path, interface_name, property_name))
985
913
    
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
914
    @dbus.service.method(dbus.PROPERTIES_IFACE,
996
915
                         in_signature="ss",
997
916
                         out_signature="v")
1067
986
        
1068
987
        Inserts property tags and interface annotation tags.
1069
988
        """
1070
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1071
 
                                                         object_path,
1072
 
                                                         connection)
 
989
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
990
                                                   connection)
1073
991
        try:
1074
992
            document = xml.dom.minidom.parseString(xmlstring)
1075
993
            
1088
1006
                            if prop._dbus_interface
1089
1007
                            == if_tag.getAttribute("name")):
1090
1008
                    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)
 
1009
                # Add annotation tags
 
1010
                for typ in ("method", "signal", "property"):
 
1011
                    for tag in if_tag.getElementsByTagName(typ):
 
1012
                        annots = dict()
 
1013
                        for name, prop in (self.
 
1014
                                           _get_all_dbus_things(typ)):
 
1015
                            if (name == tag.getAttribute("name")
 
1016
                                and prop._dbus_interface
 
1017
                                == if_tag.getAttribute("name")):
 
1018
                                annots.update(getattr(
 
1019
                                    prop, "_dbus_annotations", {}))
 
1020
                        for name, value in annots.items():
 
1021
                            ann_tag = document.createElement(
 
1022
                                "annotation")
 
1023
                            ann_tag.setAttribute("name", name)
 
1024
                            ann_tag.setAttribute("value", value)
 
1025
                            tag.appendChild(ann_tag)
 
1026
                # Add interface annotation tags
 
1027
                for annotation, value in dict(
 
1028
                    itertools.chain.from_iterable(
 
1029
                        annotations().items()
 
1030
                        for name, annotations
 
1031
                        in self._get_all_dbus_things("interface")
 
1032
                        if name == if_tag.getAttribute("name")
 
1033
                        )).items():
 
1034
                    ann_tag = document.createElement("annotation")
 
1035
                    ann_tag.setAttribute("name", annotation)
 
1036
                    ann_tag.setAttribute("value", value)
 
1037
                    if_tag.appendChild(ann_tag)
1107
1038
                # Add the names to the return values for the
1108
1039
                # "org.freedesktop.DBus.Properties" methods
1109
1040
                if (if_tag.getAttribute("name")
1127
1058
                         exc_info=error)
1128
1059
        return xmlstring
1129
1060
 
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,
1158
 
                         signature = "oas")
1159
 
    def InterfacesRemoved(self, object_path, interfaces):
1160
 
        pass
1161
 
    
1162
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1163
 
                         out_signature = "s",
1164
 
                         path_keyword = 'object_path',
1165
 
                         connection_keyword = 'connection')
1166
 
    def Introspect(self, object_path, connection):
1167
 
        """Overloading of standard D-Bus method.
1168
 
        
1169
 
        Override return argument name of GetManagedObjects to be
1170
 
        "objpath_interfaces_and_properties"
1171
 
        """
1172
 
        xmlstring = DBusObjectWithAnnotations(self, 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
1061
 
1199
1062
def datetime_to_dbus(dt, variant_level=0):
1200
1063
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1513
1376
        if exitstatus >= 0:
1514
1377
            # Emit D-Bus signal
1515
1378
            self.CheckerCompleted(dbus.Int16(exitstatus),
1516
 
                                  # This is specific to GNU libC
1517
 
                                  dbus.Int64(exitstatus << 8),
 
1379
                                  dbus.Int64(0),
1518
1380
                                  dbus.String(command))
1519
1381
        else:
1520
1382
            # Emit D-Bus signal
1521
1383
            self.CheckerCompleted(dbus.Int16(-1),
1522
1384
                                  dbus.Int64(
1523
 
                                      # This is specific to GNU libC
1524
 
                                      (exitstatus << 8)
1525
 
                                      | self.last_checker_signal),
 
1385
                                      self.last_checker_signal),
1526
1386
                                  dbus.String(command))
1527
1387
        return ret
1528
1388
    
1605
1465
        self.checked_ok()
1606
1466
    
1607
1467
    # Enable - method
1608
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1609
1468
    @dbus.service.method(_interface)
1610
1469
    def Enable(self):
1611
1470
        "D-Bus method"
1612
1471
        self.enable()
1613
1472
    
1614
1473
    # StartChecker - method
1615
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1616
1474
    @dbus.service.method(_interface)
1617
1475
    def StartChecker(self):
1618
1476
        "D-Bus method"
1619
1477
        self.start_checker()
1620
1478
    
1621
1479
    # Disable - method
1622
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1623
1480
    @dbus.service.method(_interface)
1624
1481
    def Disable(self):
1625
1482
        "D-Bus method"
1626
1483
        self.disable()
1627
1484
    
1628
1485
    # StopChecker - method
1629
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1630
1486
    @dbus.service.method(_interface)
1631
1487
    def StopChecker(self):
1632
1488
        self.stop_checker()
1668
1524
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1669
1525
    
1670
1526
    # Name - property
1671
 
    @dbus_annotations(
1672
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1673
1527
    @dbus_service_property(_interface, signature="s", access="read")
1674
1528
    def Name_dbus_property(self):
1675
1529
        return dbus.String(self.name)
1676
1530
    
1677
1531
    # Fingerprint - property
1678
 
    @dbus_annotations(
1679
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1680
1532
    @dbus_service_property(_interface, signature="s", access="read")
1681
1533
    def Fingerprint_dbus_property(self):
1682
1534
        return dbus.String(self.fingerprint)
1691
1543
        self.host = str(value)
1692
1544
    
1693
1545
    # Created - property
1694
 
    @dbus_annotations(
1695
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1696
1546
    @dbus_service_property(_interface, signature="s", access="read")
1697
1547
    def Created_dbus_property(self):
1698
1548
        return datetime_to_dbus(self.created)
1813
1663
            self.stop_checker()
1814
1664
    
1815
1665
    # ObjectPath - property
1816
 
    @dbus_annotations(
1817
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
1818
 
         "org.freedesktop.DBus.Deprecated": "true"})
1819
1666
    @dbus_service_property(_interface, signature="o", access="read")
1820
1667
    def ObjectPath_dbus_property(self):
1821
1668
        return self.dbus_object_path # is already a dbus.ObjectPath
1822
1669
    
1823
1670
    # Secret = property
1824
 
    @dbus_annotations(
1825
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
1826
 
         "invalidates"})
1827
1671
    @dbus_service_property(_interface,
1828
1672
                           signature="ay",
1829
1673
                           access="write",
2553
2397
                        "debug": "False",
2554
2398
                        "priority":
2555
2399
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2556
 
                        ":+SIGN-DSA-SHA256",
 
2400
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2557
2401
                        "servicename": "Mandos",
2558
2402
                        "use_dbus": "True",
2559
2403
                        "use_ipv6": "True",
2890
2734
        
2891
2735
        @alternate_dbus_interfaces(
2892
2736
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2893
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2737
        class MandosDBusService(DBusObjectWithProperties):
2894
2738
            """A D-Bus proxy object"""
2895
2739
            
2896
2740
            def __init__(self):
2898
2742
            
2899
2743
            _interface = "se.recompile.Mandos"
2900
2744
            
 
2745
            @dbus_interface_annotations(_interface)
 
2746
            def _foo(self):
 
2747
                return {
 
2748
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2749
                    "false" }
 
2750
            
2901
2751
            @dbus.service.signal(_interface, signature="o")
2902
2752
            def ClientAdded(self, objpath):
2903
2753
                "D-Bus signal"
2908
2758
                "D-Bus signal"
2909
2759
                pass
2910
2760
            
2911
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2912
 
                               "true"})
2913
2761
            @dbus.service.signal(_interface, signature="os")
2914
2762
            def ClientRemoved(self, objpath, name):
2915
2763
                "D-Bus signal"
2916
2764
                pass
2917
2765
            
2918
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2919
 
                               "true"})
2920
2766
            @dbus.service.method(_interface, out_signature="ao")
2921
2767
            def GetAllClients(self):
2922
2768
                "D-Bus method"
2923
2769
                return dbus.Array(c.dbus_object_path for c in
2924
2770
                                  tcp_server.clients.itervalues())
2925
2771
            
2926
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2927
 
                               "true"})
2928
2772
            @dbus.service.method(_interface,
2929
2773
                                 out_signature="a{oa{sv}}")
2930
2774
            def GetAllClientsWithProperties(self):
2931
2775
                "D-Bus method"
2932
2776
                return dbus.Dictionary(
2933
 
                    { c.dbus_object_path: c.GetAll(
2934
 
                        "se.recompile.Mandos.Client")
 
2777
                    { c.dbus_object_path: c.GetAll("")
2935
2778
                      for c in tcp_server.clients.itervalues() },
2936
2779
                    signature="oa{sv}")
2937
2780
            
2942
2785
                    if c.dbus_object_path == object_path:
2943
2786
                        del tcp_server.clients[c.name]
2944
2787
                        c.remove_from_connection()
2945
 
                        # Don't signal the disabling
 
2788
                        # Don't signal anything except ClientRemoved
2946
2789
                        c.disable(quiet=True)
2947
 
                        # Emit D-Bus signal for removal
2948
 
                        self.client_removed_signal(c)
 
2790
                        # Emit D-Bus signal
 
2791
                        self.ClientRemoved(object_path, c.name)
2949
2792
                        return
2950
2793
                raise KeyError(object_path)
2951
2794
            
2952
2795
            del _interface
2953
 
            
2954
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
2955
 
                                 out_signature = "a{oa{sa{sv}}}")
2956
 
            def GetManagedObjects(self):
2957
 
                """D-Bus method"""
2958
 
                return dbus.Dictionary(
2959
 
                    { client.dbus_object_path:
2960
 
                      dbus.Dictionary(
2961
 
                          { interface: client.GetAll(interface)
2962
 
                            for interface in
2963
 
                                 client._get_all_interface_names()})
2964
 
                      for client in tcp_server.clients.values()})
2965
 
            
2966
 
            def client_added_signal(self, client):
2967
 
                """Send the new standard signal and the old signal"""
2968
 
                if use_dbus:
2969
 
                    # New standard signal
2970
 
                    self.InterfacesAdded(
2971
 
                        client.dbus_object_path,
2972
 
                        dbus.Dictionary(
2973
 
                            { interface: client.GetAll(interface)
2974
 
                              for interface in
2975
 
                              client._get_all_interface_names()}))
2976
 
                    # Old signal
2977
 
                    self.ClientAdded(client.dbus_object_path)
2978
 
            
2979
 
            def client_removed_signal(self, client):
2980
 
                """Send the new standard signal and the old signal"""
2981
 
                if use_dbus:
2982
 
                    # New standard signal
2983
 
                    self.InterfacesRemoved(
2984
 
                        client.dbus_object_path,
2985
 
                        client._get_all_interface_names())
2986
 
                    # Old signal
2987
 
                    self.ClientRemoved(client.dbus_object_path,
2988
 
                                       client.name)
2989
2796
        
2990
2797
        mandos_dbus_service = MandosDBusService()
2991
2798
    
3056
2863
            name, client = tcp_server.clients.popitem()
3057
2864
            if use_dbus:
3058
2865
                client.remove_from_connection()
3059
 
            # Don't signal the disabling
 
2866
            # Don't signal anything except ClientRemoved
3060
2867
            client.disable(quiet=True)
3061
 
            # Emit D-Bus signal for removal
3062
 
            mandos_dbus_service.client_removed_signal(client)
 
2868
            if use_dbus:
 
2869
                # Emit D-Bus signal
 
2870
                mandos_dbus_service.ClientRemoved(
 
2871
                    client.dbus_object_path, client.name)
3063
2872
        client_settings.clear()
3064
2873
    
3065
2874
    atexit.register(cleanup)
3066
2875
    
3067
2876
    for client in tcp_server.clients.itervalues():
3068
2877
        if use_dbus:
3069
 
            # Emit D-Bus signal for adding
3070
 
            mandos_dbus_service.client_added_signal(client)
 
2878
            # Emit D-Bus signal
 
2879
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3071
2880
        # Need to initiate checking of clients
3072
2881
        if client.enabled:
3073
2882
            client.init_checker()