/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: 2009-09-21 21:39:25 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090921213925-jbpt6tzu99otseng
Use D-Bus properties instead of our own methods.

* mandos (Client._datetime_to_milliseconds): Renamed to
                                             "_timedelta_to_milliseconds".
                                             All callers changed.
  (dbus_service_property): New decorator for D-Bus properties.
  (DBusPropertyException, DBusPropertyAccessException,
  DBusPropertyNotFound): New D-Bus exception classes.
  (DBusObjectWithProperties): New; extends "dbus.service.Object" with
                              support for properties.
  (ClientDBus): Inherit from, and call up to, "DBusObjectWithProperties".
  (ClientDBus.CheckedOK, ClientDBus.GetAllProperties,
  ClientDBus.SetChecker, ClientDBus.SetHost, ClientDBus.SetInterval,
  ClientDBus.SetSecret, ClientDBus.SetTimeout, ClientDBus.Enable,
  ClientDBus.StartChecker, ClientDBus.Disable,
  ClientDBus.StopChecker): Removed, replaced with properties.
  (ClientDBus.IsStillValid): Removed, superfluous.
  (ClientDBus.name_dbus_property,
  ClientDBus.fingerprint_dbus_property, ClientDBus.host_dbus_property,
  ClientDBus.created_dbus_property,
  ClientDBus.last_enabled_dbus_property,
  ClientDBus.enabled_dbus_property,
  ClientDBus.last_checked_ok_dbus_property,
  ClientDBus.timeout_dbus_property, ClientDBus.interval_dbus_property,
  ClientDBus.checker_dbus_property,
  ClientDBus.checker_running_dbus_property,
  ClientDBus.object_path_dbus_property,
  ClientDBus.secret_dbus_property): New D-Bus properties.

Show diffs side-by-side

added added

removed removed

Lines of Context:
67
67
from dbus.mainloop.glib import DBusGMainLoop
68
68
import ctypes
69
69
import ctypes.util
 
70
import xml.dom.minidom
 
71
import inspect
70
72
 
71
73
try:
72
74
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
247
249
                                    to see if the client lives.
248
250
                                    'None' if no process is running.
249
251
    checker_initiator_tag: a gobject event source tag, or None
250
 
    disable_initiator_tag:    - '' -
 
252
    disable_initiator_tag: - '' -
251
253
    checker_callback_tag:  - '' -
252
254
    checker_command: string; External command which is run to check if
253
255
                     client lives.  %() expansions are done at
257
259
    """
258
260
    
259
261
    @staticmethod
260
 
    def _datetime_to_milliseconds(dt):
261
 
        "Convert a datetime.datetime() to milliseconds"
262
 
        return ((dt.days * 24 * 60 * 60 * 1000)
263
 
                + (dt.seconds * 1000)
264
 
                + (dt.microseconds // 1000))
 
262
    def _timedelta_to_milliseconds(td):
 
263
        "Convert a datetime.timedelta() to milliseconds"
 
264
        return ((td.days * 24 * 60 * 60 * 1000)
 
265
                + (td.seconds * 1000)
 
266
                + (td.microseconds // 1000))
265
267
    
266
268
    def timeout_milliseconds(self):
267
269
        "Return the 'timeout' attribute in milliseconds"
268
 
        return self._datetime_to_milliseconds(self.timeout)
 
270
        return self._timedelta_to_milliseconds(self.timeout)
269
271
    
270
272
    def interval_milliseconds(self):
271
273
        "Return the 'interval' attribute in milliseconds"
272
 
        return self._datetime_to_milliseconds(self.interval)
 
274
        return self._timedelta_to_milliseconds(self.interval)
273
275
    
274
276
    def __init__(self, name = None, disable_hook=None, config=None):
275
277
        """Note: the 'checker' key in 'config' sets the
478
480
            return now < (self.last_checked_ok + self.timeout)
479
481
 
480
482
 
481
 
class ClientDBus(Client, dbus.service.Object):
 
483
def dbus_service_property(dbus_interface, signature=u"v",
 
484
                          access=u"readwrite", byte_arrays=False):
 
485
    """Decorators for marking methods of a DBusObjectWithProperties to
 
486
    become properties on the D-Bus.
 
487
    
 
488
    The decorated method will be called with no arguments by "Get"
 
489
    and with one argument by "Set".
 
490
    
 
491
    The parameters, where they are supported, are the same as
 
492
    dbus.service.method, except there is only "signature", since the
 
493
    type from Get() and the type sent to Set() is the same.
 
494
    """
 
495
    def decorator(func):
 
496
        func._dbus_is_property = True
 
497
        func._dbus_interface = dbus_interface
 
498
        func._dbus_signature = signature
 
499
        func._dbus_access = access
 
500
        func._dbus_name = func.__name__
 
501
        if func._dbus_name.endswith(u"_dbus_property"):
 
502
            func._dbus_name = func._dbus_name[:-14]
 
503
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
 
504
        return func
 
505
    return decorator
 
506
 
 
507
 
 
508
class DBusPropertyException(dbus.exceptions.DBusException):
 
509
    """A base class for D-Bus property-related exceptions
 
510
    """
 
511
    def __unicode__(self):
 
512
        return unicode(str(self))
 
513
 
 
514
 
 
515
class DBusPropertyAccessException(DBusPropertyException):
 
516
    """A property's access permissions disallows an operation.
 
517
    """
 
518
    pass
 
519
 
 
520
 
 
521
class DBusPropertyNotFound(DBusPropertyException):
 
522
    """An attempt was made to access a non-existing property.
 
523
    """
 
524
    pass
 
525
 
 
526
 
 
527
class DBusObjectWithProperties(dbus.service.Object):
 
528
    """A D-Bus object with properties.
 
529
 
 
530
    Classes inheriting from this can use the dbus_service_property
 
531
    decorator to expose methods as D-Bus properties.  It exposes the
 
532
    standard Get(), Set(), and GetAll() methods on the D-Bus.
 
533
    """
 
534
    
 
535
    @staticmethod
 
536
    def _is_dbus_property(obj):
 
537
        return getattr(obj, u"_dbus_is_property", False)
 
538
    
 
539
    def _get_all_dbus_properties(self):
 
540
        """Returns a generator of (name, attribute) pairs
 
541
        """
 
542
        return ((prop._dbus_name, prop)
 
543
                for name, prop in
 
544
                inspect.getmembers(self, self._is_dbus_property))
 
545
    
 
546
    def _get_dbus_property(self, interface_name, property_name):
 
547
        """Returns a bound method if one exists which is a D-Bus
 
548
        property with the specified name and interface.
 
549
        """
 
550
        for name in (property_name,
 
551
                     property_name + u"_dbus_property"):
 
552
            prop = getattr(self, name, None)
 
553
            if (prop is None
 
554
                or not self._is_dbus_property(prop)
 
555
                or prop._dbus_name != property_name
 
556
                or (interface_name and prop._dbus_interface
 
557
                    and interface_name != prop._dbus_interface)):
 
558
                continue
 
559
            return prop
 
560
        # No such property
 
561
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
 
562
                                   + interface_name + u"."
 
563
                                   + property_name)
 
564
    
 
565
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
 
566
                         out_signature=u"v")
 
567
    def Get(self, interface_name, property_name):
 
568
        """Standard D-Bus property Get() method, see D-Bus standard.
 
569
        """
 
570
        prop = self._get_dbus_property(interface_name, property_name)
 
571
        if prop._dbus_access == u"write":
 
572
            raise DBusPropertyAccessException(property_name)
 
573
        value = prop()
 
574
        if not hasattr(value, u"variant_level"):
 
575
            return value
 
576
        return type(value)(value, variant_level=value.variant_level+1)
 
577
    
 
578
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
 
579
    def Set(self, interface_name, property_name, value):
 
580
        """Standard D-Bus property Set() method, see D-Bus standard.
 
581
        """
 
582
        prop = self._get_dbus_property(interface_name, property_name)
 
583
        if prop._dbus_access == u"read":
 
584
            raise DBusPropertyAccessException(property_name)
 
585
        if prop._dbus_get_args_options[u"byte_arrays"]:
 
586
            value = dbus.ByteArray(''.join(unichr(byte)
 
587
                                           for byte in value))
 
588
        prop(value)
 
589
    
 
590
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
 
591
                         out_signature=u"a{sv}")
 
592
    def GetAll(self, interface_name):
 
593
        """Standard D-Bus property GetAll() method, see D-Bus
 
594
        standard.
 
595
 
 
596
        Note: Will not include properties with access="write".
 
597
        """
 
598
        all = {}
 
599
        for name, prop in self._get_all_dbus_properties():
 
600
            if (interface_name
 
601
                and interface_name != prop._dbus_interface):
 
602
                # Interface non-empty but did not match
 
603
                continue
 
604
            # Ignore write-only properties
 
605
            if prop._dbus_access == u"write":
 
606
                continue
 
607
            value = prop()
 
608
            if not hasattr(value, u"variant_level"):
 
609
                all[name] = value
 
610
                continue
 
611
            all[name] = type(value)(value, variant_level=
 
612
                                    value.variant_level+1)
 
613
        return dbus.Dictionary(all, signature=u"sv")
 
614
    
 
615
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
 
616
                         out_signature=u"s",
 
617
                         path_keyword='object_path',
 
618
                         connection_keyword='connection')
 
619
    def Introspect(self, object_path, connection):
 
620
        """Standard D-Bus method, overloaded to insert property tags.
 
621
        """
 
622
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
623
                                           connection)
 
624
        document = xml.dom.minidom.parseString(xmlstring)
 
625
        del xmlstring
 
626
        def make_tag(document, name, prop):
 
627
            e = document.createElement(u"property")
 
628
            e.setAttribute(u"name", name)
 
629
            e.setAttribute(u"type", prop._dbus_signature)
 
630
            e.setAttribute(u"access", prop._dbus_access)
 
631
            return e
 
632
        for if_tag in document.getElementsByTagName(u"interface"):
 
633
            for tag in (make_tag(document, name, prop)
 
634
                        for name, prop
 
635
                        in self._get_all_dbus_properties()
 
636
                        if prop._dbus_interface
 
637
                        == if_tag.getAttribute(u"name")):
 
638
                if_tag.appendChild(tag)
 
639
        xmlstring = document.toxml(u"utf-8")
 
640
        document.unlink()
 
641
        return xmlstring
 
642
 
 
643
 
 
644
class ClientDBus(Client, DBusObjectWithProperties):
482
645
    """A Client class using D-Bus
483
646
    
484
647
    Attributes:
495
658
        self.dbus_object_path = (dbus.ObjectPath
496
659
                                 (u"/clients/"
497
660
                                  + self.name.replace(u".", u"_")))
498
 
        dbus.service.Object.__init__(self, self.bus,
499
 
                                     self.dbus_object_path)
 
661
        DBusObjectWithProperties.__init__(self, self.bus,
 
662
                                          self.dbus_object_path)
500
663
    
501
664
    @staticmethod
502
665
    def _datetime_to_dbus(dt, variant_level=0):
531
694
            self.remove_from_connection()
532
695
        except LookupError:
533
696
            pass
534
 
        if hasattr(dbus.service.Object, u"__del__"):
535
 
            dbus.service.Object.__del__(self, *args, **kwargs)
 
697
        if hasattr(DBusObjectWithProperties, u"__del__"):
 
698
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
536
699
        Client.__del__(self, *args, **kwargs)
537
700
    
538
701
    def checker_callback(self, pid, condition, command,
595
758
    ## D-Bus methods & signals
596
759
    _interface = u"se.bsnet.fukt.Mandos.Client"
597
760
    
598
 
    # CheckedOK - method
599
 
    @dbus.service.method(_interface)
600
 
    def CheckedOK(self):
601
 
        return self.checked_ok()
602
 
    
603
761
    # CheckerCompleted - signal
604
762
    @dbus.service.signal(_interface, signature=u"nxs")
605
763
    def CheckerCompleted(self, exitcode, waitstatus, command):
612
770
        "D-Bus signal"
613
771
        pass
614
772
    
615
 
    # GetAllProperties - method
616
 
    @dbus.service.method(_interface, out_signature=u"a{sv}")
617
 
    def GetAllProperties(self):
618
 
        "D-Bus method"
619
 
        return dbus.Dictionary({
620
 
                dbus.String(u"name"):
621
 
                    dbus.String(self.name, variant_level=1),
622
 
                dbus.String(u"fingerprint"):
623
 
                    dbus.String(self.fingerprint, variant_level=1),
624
 
                dbus.String(u"host"):
625
 
                    dbus.String(self.host, variant_level=1),
626
 
                dbus.String(u"created"):
627
 
                    self._datetime_to_dbus(self.created,
628
 
                                           variant_level=1),
629
 
                dbus.String(u"last_enabled"):
630
 
                    (self._datetime_to_dbus(self.last_enabled,
631
 
                                            variant_level=1)
632
 
                     if self.last_enabled is not None
633
 
                     else dbus.Boolean(False, variant_level=1)),
634
 
                dbus.String(u"enabled"):
635
 
                    dbus.Boolean(self.enabled, variant_level=1),
636
 
                dbus.String(u"last_checked_ok"):
637
 
                    (self._datetime_to_dbus(self.last_checked_ok,
638
 
                                            variant_level=1)
639
 
                     if self.last_checked_ok is not None
640
 
                     else dbus.Boolean (False, variant_level=1)),
641
 
                dbus.String(u"timeout"):
642
 
                    dbus.UInt64(self.timeout_milliseconds(),
643
 
                                variant_level=1),
644
 
                dbus.String(u"interval"):
645
 
                    dbus.UInt64(self.interval_milliseconds(),
646
 
                                variant_level=1),
647
 
                dbus.String(u"checker"):
648
 
                    dbus.String(self.checker_command,
649
 
                                variant_level=1),
650
 
                dbus.String(u"checker_running"):
651
 
                    dbus.Boolean(self.checker is not None,
652
 
                                 variant_level=1),
653
 
                dbus.String(u"object_path"):
654
 
                    dbus.ObjectPath(self.dbus_object_path,
655
 
                                    variant_level=1)
656
 
                }, signature=u"sv")
657
 
    
658
 
    # IsStillValid - method
659
 
    @dbus.service.method(_interface, out_signature=u"b")
660
 
    def IsStillValid(self):
661
 
        return self.still_valid()
662
 
    
663
773
    # PropertyChanged - signal
664
774
    @dbus.service.signal(_interface, signature=u"sv")
665
775
    def PropertyChanged(self, property, value):
678
788
        "D-Bus signal"
679
789
        pass
680
790
    
681
 
    # SetChecker - method
682
 
    @dbus.service.method(_interface, in_signature=u"s")
683
 
    def SetChecker(self, checker):
684
 
        "D-Bus setter method"
685
 
        self.checker_command = checker
 
791
    # name - property
 
792
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
793
    def name_dbus_property(self):
 
794
        return dbus.String(self.name)
 
795
    
 
796
    # fingerprint - property
 
797
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
798
    def fingerprint_dbus_property(self):
 
799
        return dbus.String(self.fingerprint)
 
800
    
 
801
    # host - property
 
802
    @dbus_service_property(_interface, signature=u"s",
 
803
                           access=u"readwrite")
 
804
    def host_dbus_property(self, value=None):
 
805
        if value is None:       # get
 
806
            return dbus.String(self.host)
 
807
        self.host = value
 
808
        # Emit D-Bus signal
 
809
        self.PropertyChanged(dbus.String(u"host"),
 
810
                             dbus.String(value, variant_level=1))
 
811
    
 
812
    # created - property
 
813
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
814
    def created_dbus_property(self):
 
815
        return dbus.String(self._datetime_to_dbus(self.created))
 
816
    
 
817
    # last_enabled - property
 
818
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
819
    def last_enabled_dbus_property(self):
 
820
        if self.last_enabled is None:
 
821
            return dbus.String(u"")
 
822
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
 
823
    
 
824
    # enabled - property
 
825
    @dbus_service_property(_interface, signature=u"b",
 
826
                           access=u"readwrite")
 
827
    def enabled_dbus_property(self, value=None):
 
828
        if value is None:       # get
 
829
            return dbus.Boolean(self.enabled)
 
830
        if value:
 
831
            self.enable()
 
832
        else:
 
833
            self.disable()
 
834
    
 
835
    # last_checked_ok - property
 
836
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
837
    def last_checked_ok_dbus_property(self):
 
838
        if self.last_checked_ok is None:
 
839
            return dbus.String(u"")
 
840
        return dbus.String(self._datetime_to_dbus(self
 
841
                                                  .last_checked_ok))
 
842
    
 
843
    # timeout - property
 
844
    @dbus_service_property(_interface, signature=u"t",
 
845
                           access=u"readwrite")
 
846
    def timeout_dbus_property(self, value=None):
 
847
        if value is None:       # get
 
848
            return dbus.UInt64(self.timeout_milliseconds())
 
849
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
850
        # Emit D-Bus signal
 
851
        self.PropertyChanged(dbus.String(u"timeout"),
 
852
                             dbus.UInt64(value, variant_level=1))
 
853
        if getattr(self, u"disable_initiator_tag", None) is None:
 
854
            return
 
855
        # Reschedule timeout
 
856
        gobject.source_remove(self.disable_initiator_tag)
 
857
        self.disable_initiator_tag = None
 
858
        time_to_die = (self.
 
859
                       _timedelta_to_milliseconds((self
 
860
                                                   .last_checked_ok
 
861
                                                   + self.timeout)
 
862
                                                  - datetime.datetime
 
863
                                                  .utcnow()))
 
864
        if time_to_die <= 0:
 
865
            # The timeout has passed
 
866
            self.disable()
 
867
        else:
 
868
            self.disable_initiator_tag = (gobject.timeout_add
 
869
                                          (time_to_die, self.disable))
 
870
    
 
871
    # interval - property
 
872
    @dbus_service_property(_interface, signature=u"t",
 
873
                           access=u"readwrite")
 
874
    def interval_dbus_property(self, value=None):
 
875
        if value is None:       # get
 
876
            return dbus.UInt64(self.interval_milliseconds())
 
877
        self.interval = datetime.timedelta(0, 0, 0, value)
 
878
        # Emit D-Bus signal
 
879
        self.PropertyChanged(dbus.String(u"interval"),
 
880
                             dbus.UInt64(value, variant_level=1))
 
881
        if getattr(self, u"checker_initiator_tag", None) is None:
 
882
            return
 
883
        # Reschedule checker run
 
884
        gobject.source_remove(self.checker_initiator_tag)
 
885
        self.checker_initiator_tag = (gobject.timeout_add
 
886
                                      (value, self.start_checker))
 
887
        self.start_checker()    # Start one now, too
 
888
 
 
889
    # checker - property
 
890
    @dbus_service_property(_interface, signature=u"s",
 
891
                           access=u"readwrite")
 
892
    def checker_dbus_property(self, value=None):
 
893
        if value is None:       # get
 
894
            return dbus.String(self.checker_command)
 
895
        self.checker_command = value
686
896
        # Emit D-Bus signal
687
897
        self.PropertyChanged(dbus.String(u"checker"),
688
898
                             dbus.String(self.checker_command,
689
899
                                         variant_level=1))
690
900
    
691
 
    # SetHost - method
692
 
    @dbus.service.method(_interface, in_signature=u"s")
693
 
    def SetHost(self, host):
694
 
        "D-Bus setter method"
695
 
        self.host = host
696
 
        # Emit D-Bus signal
697
 
        self.PropertyChanged(dbus.String(u"host"),
698
 
                             dbus.String(self.host, variant_level=1))
699
 
    
700
 
    # SetInterval - method
701
 
    @dbus.service.method(_interface, in_signature=u"t")
702
 
    def SetInterval(self, milliseconds):
703
 
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
704
 
        # Emit D-Bus signal
705
 
        self.PropertyChanged(dbus.String(u"interval"),
706
 
                             (dbus.UInt64(self
707
 
                                          .interval_milliseconds(),
708
 
                                          variant_level=1)))
709
 
    
710
 
    # SetSecret - method
711
 
    @dbus.service.method(_interface, in_signature=u"ay",
712
 
                         byte_arrays=True)
713
 
    def SetSecret(self, secret):
714
 
        "D-Bus setter method"
715
 
        self.secret = str(secret)
716
 
    
717
 
    # SetTimeout - method
718
 
    @dbus.service.method(_interface, in_signature=u"t")
719
 
    def SetTimeout(self, milliseconds):
720
 
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
721
 
        # Emit D-Bus signal
722
 
        self.PropertyChanged(dbus.String(u"timeout"),
723
 
                             (dbus.UInt64(self.timeout_milliseconds(),
724
 
                                          variant_level=1)))
725
 
    
726
 
    # Enable - method
727
 
    @dbus.service.method(_interface)
728
 
    def Enable(self):
729
 
        "D-Bus method"
730
 
        self.enable()
731
 
    
732
 
    # StartChecker - method
733
 
    @dbus.service.method(_interface)
734
 
    def StartChecker(self):
735
 
        "D-Bus method"
736
 
        self.start_checker()
737
 
    
738
 
    # Disable - method
739
 
    @dbus.service.method(_interface)
740
 
    def Disable(self):
741
 
        "D-Bus method"
742
 
        self.disable()
743
 
    
744
 
    # StopChecker - method
745
 
    @dbus.service.method(_interface)
746
 
    def StopChecker(self):
747
 
        self.stop_checker()
 
901
    # checker_running - property
 
902
    @dbus_service_property(_interface, signature=u"b",
 
903
                           access=u"readwrite")
 
904
    def checker_running_dbus_property(self, value=None):
 
905
        if value is None:       # get
 
906
            return dbus.Boolean(self.checker is not None)
 
907
        if value:
 
908
            self.start_checker()
 
909
        else:
 
910
            self.stop_checker()
 
911
    
 
912
    # object_path - property
 
913
    @dbus_service_property(_interface, signature=u"o", access=u"read")
 
914
    def object_path_dbus_property(self):
 
915
        return self.dbus_object_path # is already a dbus.ObjectPath
 
916
    
 
917
    # secret = property xxx
 
918
    @dbus_service_property(_interface, signature=u"ay",
 
919
                           access=u"write", byte_arrays=True)
 
920
    def secret_dbus_property(self, value):
 
921
        self.secret = str(value)
748
922
    
749
923
    del _interface
750
924
 
1427
1601
            def GetAllClientsWithProperties(self):
1428
1602
                "D-Bus method"
1429
1603
                return dbus.Dictionary(
1430
 
                    ((c.dbus_object_path, c.GetAllProperties())
 
1604
                    ((c.dbus_object_path, c.GetAll(u""))
1431
1605
                     for c in tcp_server.clients),
1432
1606
                    signature=u"oa{sv}")
1433
1607
            
1453
1627
        if use_dbus:
1454
1628
            # Emit D-Bus signal
1455
1629
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
1456
 
                                            client.GetAllProperties())
 
1630
                                            client.GetAll(u""))
1457
1631
        client.enable()
1458
1632
    
1459
1633
    tcp_server.enable()