/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-08-10 09:00:23 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • Revision ID: teddy@recompile.se-20150810090023-fz6vjqr7zf33e2tf
Support the standard org.freedesktop.DBus.ObjectManager interface.

Now that the D-Bus standard has an interface to keep track of new and
removed objects, use that instead of our own methods.  This deprecates
our D-Bus methods "GetAllClients" and "GetAllClientsWithProperties"
and the signals "ClientAdded" and "ClientRemoved", all on the server
interface "se.recompile.Mandos".

* DBUS-API: Removed references to deprecated methods and signals;
  insert reference to the org.freedesktop.DBus.ObjectManager
  interface.
* mandos (DBusObjectWithProperties._get_all_interface_names): New.
  (dbus.OBJECT_MANAGER_IFACE): If not present, monkey patch.
  (DBusObjectWithObjectManager): New.
  (main/MandosDBusService): Inherit from DBusObjectWithObjectManager.
  (main/MandosDBusService.ClientRemoved): Annotate as deprecated.
  (main/MandosDBusService.GetAllClients): - '' -
  (main/MandosDBusService.GetAllClientsWithProperties): Annotate as
                                                        deprecated.
                                                        Also only
                                                        return
                                                        properties on
                                                        client
                                                        interface.
  (main/MandosDBusService.RemoveClient): Call client_removed_signal
                                         instead of ClientRemoved.
  (main/MandosDBusService.GetManagedObjects): New.
  (main/MandosDBusService.client_added_signal): New.
  (main/MandosDBusService.client_removed_signal): - '' -
  (main/cleanup): Call "client_removed_signal" instead of sending
                  "ClientRemoved" signal directly.
  (main): Call "client_added_signal" instead of sending "ClientAdded"
          signal directly.
* mandos-ctl: Use GetManagedObjects instead of
              GetAllClientsWithProperties.  Also, show better error
              message in case of failure to connect to the D-Bus

* mandos-monitor (MandosClientPropertyCache.properties_changed):
  Bug fix; only update properties on client interface.
  (UserInterface.find_and_remove_client): Change to accept arguments
                                          from InterfacesRemoved
                                          signal.  Also, bug fix:
                                          working error message when
                                          removing unknown client.
  (UserInterface.add_new_client): Change to accept arguments from
                                  InterfacesRemoved signal.  Pass
                                  properties to MandosClientWidget
                                  constructor.
  (UserInterface.run): Connect find_and_remove_client method to
                       InterfacesRemoved signal and the add_new_client
                       method to the InterfacesAdded signal.

Show diffs side-by-side

added added

removed removed

Lines of Context:
78
78
import tempfile
79
79
import itertools
80
80
import collections
 
81
import codecs
81
82
 
82
83
import dbus
83
84
import dbus.service
394
395
                    logger.error(bad_states[state] + ": %r", error)
395
396
            self.cleanup()
396
397
        elif state == avahi.SERVER_RUNNING:
397
 
            self.add()
 
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
410
        else:
399
411
            if error is None:
400
412
                logger.debug("Unknown state: %r", state)
645
657
        # Also start a new checker *right now*.
646
658
        self.start_checker()
647
659
    
648
 
    def checker_callback(self, source, condition,
649
 
                         (connection, command)):
 
660
    def checker_callback(self, source, condition, connection,
 
661
                         command):
650
662
        """The checker has completed, so take appropriate actions."""
651
663
        self.checker_callback_tag = None
652
664
        self.checker = None
740
752
                and self.server_settings["foreground"]):
741
753
                popen_args.update({"stdout": wnull,
742
754
                                   "stderr": wnull })
743
 
            pipe = multiprocessing.Pipe(duplex=False)
 
755
            pipe = multiprocessing.Pipe(duplex = False)
744
756
            self.checker = multiprocessing.Process(
745
757
                target = call_pipe,
746
 
                args = (subprocess.call, pipe[1], command),
 
758
                args = (pipe[1], subprocess.call, command),
747
759
                kwargs = popen_args)
748
760
            self.checker.start()
749
761
            self.checker_callback_tag = gobject.io_add_watch(
750
762
                pipe[0].fileno(), gobject.IO_IN,
751
 
                self.checker_callback, (pipe[0], command))
 
763
                self.checker_callback, pipe[0], command)
752
764
        # Re-run this periodically if run by gobject.timeout_add
753
765
        return True
754
766
    
830
842
                           access="r")
831
843
    def Property_dbus_property(self):
832
844
        return dbus.Boolean(False)
 
845
    
 
846
    See also the DBusObjectWithAnnotations class.
833
847
    """
834
848
    
835
849
    def decorator(func):
857
871
    pass
858
872
 
859
873
 
860
 
class DBusObjectWithProperties(dbus.service.Object):
861
 
    """A D-Bus object with properties.
 
874
class DBusObjectWithAnnotations(dbus.service.Object):
 
875
    """A D-Bus object with annotations.
862
876
    
863
 
    Classes inheriting from this can use the dbus_service_property
864
 
    decorator to expose methods as D-Bus properties.  It exposes the
865
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
 
877
    Classes inheriting from this can use the dbus_annotations
 
878
    decorator to add annotations to methods or signals.
866
879
    """
867
880
    
868
881
    @staticmethod
884
897
                for name, athing in
885
898
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
886
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
    
887
971
    def _get_dbus_property(self, interface_name, property_name):
888
972
        """Returns a bound method if one exists which is a D-Bus
889
973
        property with the specified name and interface.
899
983
        raise DBusPropertyNotFound("{}:{}.{}".format(
900
984
            self.dbus_object_path, interface_name, property_name))
901
985
    
 
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
    
902
995
    @dbus.service.method(dbus.PROPERTIES_IFACE,
903
996
                         in_signature="ss",
904
997
                         out_signature="v")
974
1067
        
975
1068
        Inserts property tags and interface annotation tags.
976
1069
        """
977
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
978
 
                                                   connection)
 
1070
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
 
1071
                                                         object_path,
 
1072
                                                         connection)
979
1073
        try:
980
1074
            document = xml.dom.minidom.parseString(xmlstring)
981
1075
            
994
1088
                            if prop._dbus_interface
995
1089
                            == if_tag.getAttribute("name")):
996
1090
                    if_tag.appendChild(tag)
997
 
                # Add annotation tags
998
 
                for typ in ("method", "signal", "property"):
999
 
                    for tag in if_tag.getElementsByTagName(typ):
1000
 
                        annots = dict()
1001
 
                        for name, prop in (self.
1002
 
                                           _get_all_dbus_things(typ)):
1003
 
                            if (name == tag.getAttribute("name")
1004
 
                                and prop._dbus_interface
1005
 
                                == if_tag.getAttribute("name")):
1006
 
                                annots.update(getattr(
1007
 
                                    prop, "_dbus_annotations", {}))
1008
 
                        for name, value in annots.items():
1009
 
                            ann_tag = document.createElement(
1010
 
                                "annotation")
1011
 
                            ann_tag.setAttribute("name", name)
1012
 
                            ann_tag.setAttribute("value", value)
1013
 
                            tag.appendChild(ann_tag)
1014
 
                # Add interface annotation tags
1015
 
                for annotation, value in dict(
1016
 
                    itertools.chain.from_iterable(
1017
 
                        annotations().items()
1018
 
                        for name, annotations
1019
 
                        in self._get_all_dbus_things("interface")
1020
 
                        if name == if_tag.getAttribute("name")
1021
 
                        )).items():
1022
 
                    ann_tag = document.createElement("annotation")
1023
 
                    ann_tag.setAttribute("name", annotation)
1024
 
                    ann_tag.setAttribute("value", value)
1025
 
                    if_tag.appendChild(ann_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)
1026
1107
                # Add the names to the return values for the
1027
1108
                # "org.freedesktop.DBus.Properties" methods
1028
1109
                if (if_tag.getAttribute("name")
1046
1127
                         exc_info=error)
1047
1128
        return xmlstring
1048
1129
 
 
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
1049
1198
 
1050
1199
def datetime_to_dbus(dt, variant_level=0):
1051
1200
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1098
1247
                interface_names.add(alt_interface)
1099
1248
                # Is this a D-Bus signal?
1100
1249
                if getattr(attribute, "_dbus_is_signal", False):
1101
 
                    # Extract the original non-method undecorated
1102
 
                    # function by black magic
1103
 
                    nonmethod_func = (dict(
1104
 
                        zip(attribute.func_code.co_freevars,
1105
 
                            attribute.__closure__))
1106
 
                                      ["func"].cell_contents)
 
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
1107
1259
                    # Create a new, but exactly alike, function
1108
1260
                    # object, and decorate it to be a new D-Bus signal
1109
1261
                    # 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__)
1110
1276
                    new_function = (dbus.service.signal(
1111
 
                        alt_interface, attribute._dbus_signature)
1112
 
                                    (types.FunctionType(
1113
 
                                        nonmethod_func.func_code,
1114
 
                                        nonmethod_func.func_globals,
1115
 
                                        nonmethod_func.func_name,
1116
 
                                        nonmethod_func.func_defaults,
1117
 
                                        nonmethod_func.func_closure)))
 
1277
                        alt_interface,
 
1278
                        attribute._dbus_signature)(new_function))
1118
1279
                    # Copy annotations, if any
1119
1280
                    try:
1120
1281
                        new_function._dbus_annotations = dict(
1344
1505
        Client.__del__(self, *args, **kwargs)
1345
1506
    
1346
1507
    def checker_callback(self, source, condition,
1347
 
                         (connection, command), *args, **kwargs):
 
1508
                         connection, command, *args, **kwargs):
1348
1509
        ret = Client.checker_callback(self, source, condition,
1349
 
                                      (connection, command), *args,
 
1510
                                      connection, command, *args,
1350
1511
                                      **kwargs)
1351
1512
        exitstatus = self.last_checker_status
1352
1513
        if exitstatus >= 0:
1353
1514
            # Emit D-Bus signal
1354
1515
            self.CheckerCompleted(dbus.Int16(exitstatus),
1355
 
                                  dbus.Int64(0),
 
1516
                                  # This is specific to GNU libC
 
1517
                                  dbus.Int64(exitstatus << 8),
1356
1518
                                  dbus.String(command))
1357
1519
        else:
1358
1520
            # Emit D-Bus signal
1359
1521
            self.CheckerCompleted(dbus.Int16(-1),
1360
1522
                                  dbus.Int64(
1361
 
                                      self.last_checker_signal),
 
1523
                                      # This is specific to GNU libC
 
1524
                                      (exitstatus << 8)
 
1525
                                      | self.last_checker_signal),
1362
1526
                                  dbus.String(command))
1363
1527
        return ret
1364
1528
    
1441
1605
        self.checked_ok()
1442
1606
    
1443
1607
    # Enable - method
 
1608
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1444
1609
    @dbus.service.method(_interface)
1445
1610
    def Enable(self):
1446
1611
        "D-Bus method"
1447
1612
        self.enable()
1448
1613
    
1449
1614
    # StartChecker - method
 
1615
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1450
1616
    @dbus.service.method(_interface)
1451
1617
    def StartChecker(self):
1452
1618
        "D-Bus method"
1453
1619
        self.start_checker()
1454
1620
    
1455
1621
    # Disable - method
 
1622
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1456
1623
    @dbus.service.method(_interface)
1457
1624
    def Disable(self):
1458
1625
        "D-Bus method"
1459
1626
        self.disable()
1460
1627
    
1461
1628
    # StopChecker - method
 
1629
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1462
1630
    @dbus.service.method(_interface)
1463
1631
    def StopChecker(self):
1464
1632
        self.stop_checker()
1500
1668
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1501
1669
    
1502
1670
    # Name - property
 
1671
    @dbus_annotations(
 
1672
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1503
1673
    @dbus_service_property(_interface, signature="s", access="read")
1504
1674
    def Name_dbus_property(self):
1505
1675
        return dbus.String(self.name)
1506
1676
    
1507
1677
    # Fingerprint - property
 
1678
    @dbus_annotations(
 
1679
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1508
1680
    @dbus_service_property(_interface, signature="s", access="read")
1509
1681
    def Fingerprint_dbus_property(self):
1510
1682
        return dbus.String(self.fingerprint)
1519
1691
        self.host = str(value)
1520
1692
    
1521
1693
    # Created - property
 
1694
    @dbus_annotations(
 
1695
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1522
1696
    @dbus_service_property(_interface, signature="s", access="read")
1523
1697
    def Created_dbus_property(self):
1524
1698
        return datetime_to_dbus(self.created)
1639
1813
            self.stop_checker()
1640
1814
    
1641
1815
    # ObjectPath - property
 
1816
    @dbus_annotations(
 
1817
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
 
1818
         "org.freedesktop.DBus.Deprecated": "true"})
1642
1819
    @dbus_service_property(_interface, signature="o", access="read")
1643
1820
    def ObjectPath_dbus_property(self):
1644
1821
        return self.dbus_object_path # is already a dbus.ObjectPath
1645
1822
    
1646
1823
    # Secret = property
 
1824
    @dbus_annotations(
 
1825
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1826
         "invalidates"})
1647
1827
    @dbus_service_property(_interface,
1648
1828
                           signature="ay",
1649
1829
                           access="write",
1659
1839
        self._pipe = child_pipe
1660
1840
        self._pipe.send(('init', fpr, address))
1661
1841
        if not self._pipe.recv():
1662
 
            raise KeyError()
 
1842
            raise KeyError(fpr)
1663
1843
    
1664
1844
    def __getattribute__(self, name):
1665
1845
        if name == '_pipe':
2128
2308
        
2129
2309
        if command == 'getattr':
2130
2310
            attrname = request[1]
2131
 
            if callable(client_object.__getattribute__(attrname)):
 
2311
            if isinstance(client_object.__getattribute__(attrname),
 
2312
                          collections.Callable):
2132
2313
                parent_pipe.send(('function', ))
2133
2314
            else:
2134
2315
                parent_pipe.send((
2169
2350
    # avoid excessive use of external libraries.
2170
2351
    
2171
2352
    # New type for defining tokens, syntax, and semantics all-in-one
2172
 
    Token = collections.namedtuple("Token",
2173
 
                                   ("regexp", # To match token; if
2174
 
                                              # "value" is not None,
2175
 
                                              # must have a "group"
2176
 
                                              # containing digits
2177
 
                                    "value",  # datetime.timedelta or
2178
 
                                              # None
2179
 
                                    "followers")) # Tokens valid after
2180
 
                                                  # this token
2181
2353
    Token = collections.namedtuple("Token", (
2182
2354
        "regexp",  # To match token; if "value" is not None, must have
2183
2355
                   # a "group" containing digits
2218
2390
    # Define starting values
2219
2391
    value = datetime.timedelta() # Value so far
2220
2392
    found_token = None
2221
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2393
    followers = frozenset((token_duration, )) # Following valid tokens
2222
2394
    s = duration                # String left to parse
2223
2395
    # Loop until end token is found
2224
2396
    while found_token is not token_end:
2241
2413
                break
2242
2414
        else:
2243
2415
            # No currently valid tokens were found
2244
 
            raise ValueError("Invalid RFC 3339 duration")
 
2416
            raise ValueError("Invalid RFC 3339 duration: {!r}"
 
2417
                             .format(duration))
2245
2418
    # End token found
2246
2419
    return value
2247
2420
 
2380
2553
                        "debug": "False",
2381
2554
                        "priority":
2382
2555
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2383
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2556
                        ":+SIGN-DSA-SHA256",
2384
2557
                        "servicename": "Mandos",
2385
2558
                        "use_dbus": "True",
2386
2559
                        "use_ipv6": "True",
2498
2671
            pidfilename = "/var/run/mandos.pid"
2499
2672
        pidfile = None
2500
2673
        try:
2501
 
            pidfile = open(pidfilename, "w")
 
2674
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2502
2675
        except IOError as e:
2503
2676
            logger.error("Could not open file %r", pidfilename,
2504
2677
                         exc_info=e)
2563
2736
            old_bus_name = dbus.service.BusName(
2564
2737
                "se.bsnet.fukt.Mandos", bus,
2565
2738
                do_not_queue=True)
2566
 
        except dbus.exceptions.NameExistsException as e:
 
2739
        except dbus.exceptions.DBusException as e:
2567
2740
            logger.error("Disabling D-Bus:", exc_info=e)
2568
2741
            use_dbus = False
2569
2742
            server_settings["use_dbus"] = False
2700
2873
    
2701
2874
    if not foreground:
2702
2875
        if pidfile is not None:
 
2876
            pid = os.getpid()
2703
2877
            try:
2704
2878
                with pidfile:
2705
 
                    pid = os.getpid()
2706
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2879
                    print(pid, file=pidfile)
2707
2880
            except IOError:
2708
2881
                logger.error("Could not write to file %r with PID %d",
2709
2882
                             pidfilename, pid)
2717
2890
        
2718
2891
        @alternate_dbus_interfaces(
2719
2892
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2720
 
        class MandosDBusService(DBusObjectWithProperties):
 
2893
        class MandosDBusService(DBusObjectWithObjectManager):
2721
2894
            """A D-Bus proxy object"""
2722
2895
            
2723
2896
            def __init__(self):
2725
2898
            
2726
2899
            _interface = "se.recompile.Mandos"
2727
2900
            
2728
 
            @dbus_interface_annotations(_interface)
2729
 
            def _foo(self):
2730
 
                return {
2731
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2732
 
                    "false" }
2733
 
            
2734
2901
            @dbus.service.signal(_interface, signature="o")
2735
2902
            def ClientAdded(self, objpath):
2736
2903
                "D-Bus signal"
2741
2908
                "D-Bus signal"
2742
2909
                pass
2743
2910
            
 
2911
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
2912
                               "true"})
2744
2913
            @dbus.service.signal(_interface, signature="os")
2745
2914
            def ClientRemoved(self, objpath, name):
2746
2915
                "D-Bus signal"
2747
2916
                pass
2748
2917
            
 
2918
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
2919
                               "true"})
2749
2920
            @dbus.service.method(_interface, out_signature="ao")
2750
2921
            def GetAllClients(self):
2751
2922
                "D-Bus method"
2752
2923
                return dbus.Array(c.dbus_object_path for c in
2753
2924
                                  tcp_server.clients.itervalues())
2754
2925
            
 
2926
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
2927
                               "true"})
2755
2928
            @dbus.service.method(_interface,
2756
2929
                                 out_signature="a{oa{sv}}")
2757
2930
            def GetAllClientsWithProperties(self):
2758
2931
                "D-Bus method"
2759
2932
                return dbus.Dictionary(
2760
 
                    { c.dbus_object_path: c.GetAll("")
 
2933
                    { c.dbus_object_path: c.GetAll(
 
2934
                        "se.recompile.Mandos.Client")
2761
2935
                      for c in tcp_server.clients.itervalues() },
2762
2936
                    signature="oa{sv}")
2763
2937
            
2768
2942
                    if c.dbus_object_path == object_path:
2769
2943
                        del tcp_server.clients[c.name]
2770
2944
                        c.remove_from_connection()
2771
 
                        # Don't signal anything except ClientRemoved
 
2945
                        # Don't signal the disabling
2772
2946
                        c.disable(quiet=True)
2773
 
                        # Emit D-Bus signal
2774
 
                        self.ClientRemoved(object_path, c.name)
 
2947
                        # Emit D-Bus signal for removal
 
2948
                        self.client_removed_signal(c)
2775
2949
                        return
2776
2950
                raise KeyError(object_path)
2777
2951
            
2778
2952
            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)
2779
2989
        
2780
2990
        mandos_dbus_service = MandosDBusService()
2781
2991
    
2846
3056
            name, client = tcp_server.clients.popitem()
2847
3057
            if use_dbus:
2848
3058
                client.remove_from_connection()
2849
 
            # Don't signal anything except ClientRemoved
 
3059
            # Don't signal the disabling
2850
3060
            client.disable(quiet=True)
2851
 
            if use_dbus:
2852
 
                # Emit D-Bus signal
2853
 
                mandos_dbus_service.ClientRemoved(
2854
 
                    client.dbus_object_path, client.name)
 
3061
            # Emit D-Bus signal for removal
 
3062
            mandos_dbus_service.client_removed_signal(client)
2855
3063
        client_settings.clear()
2856
3064
    
2857
3065
    atexit.register(cleanup)
2858
3066
    
2859
3067
    for client in tcp_server.clients.itervalues():
2860
3068
        if use_dbus:
2861
 
            # Emit D-Bus signal
2862
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
3069
            # Emit D-Bus signal for adding
 
3070
            mandos_dbus_service.client_added_signal(client)
2863
3071
        # Need to initiate checking of clients
2864
3072
        if client.enabled:
2865
3073
            client.init_checker()