/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

fixed incorrect include comments

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
72
70
 
73
71
try:
74
72
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
79
77
        SO_BINDTODEVICE = None
80
78
 
81
79
 
82
 
version = "1.0.12"
 
80
version = "1.0.11"
83
81
 
84
82
logger = logging.Logger(u'mandos')
85
83
syslogger = (logging.handlers.SysLogHandler
176
174
                                    self.server.EntryGroupNew()),
177
175
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
178
176
            self.group.connect_to_signal('StateChanged',
179
 
                                         self
180
 
                                         .entry_group_state_changed)
 
177
                                         self.entry_group_state_changed)
181
178
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
182
179
                     self.name, self.type)
183
180
        self.group.AddService(
249
246
                                    to see if the client lives.
250
247
                                    'None' if no process is running.
251
248
    checker_initiator_tag: a gobject event source tag, or None
252
 
    disable_initiator_tag: - '' -
 
249
    disable_initiator_tag:    - '' -
253
250
    checker_callback_tag:  - '' -
254
251
    checker_command: string; External command which is run to check if
255
252
                     client lives.  %() expansions are done at
259
256
    """
260
257
    
261
258
    @staticmethod
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))
 
259
    def _datetime_to_milliseconds(dt):
 
260
        "Convert a datetime.datetime() to milliseconds"
 
261
        return ((dt.days * 24 * 60 * 60 * 1000)
 
262
                + (dt.seconds * 1000)
 
263
                + (dt.microseconds // 1000))
267
264
    
268
265
    def timeout_milliseconds(self):
269
266
        "Return the 'timeout' attribute in milliseconds"
270
 
        return self._timedelta_to_milliseconds(self.timeout)
 
267
        return self._datetime_to_milliseconds(self.timeout)
271
268
    
272
269
    def interval_milliseconds(self):
273
270
        "Return the 'interval' attribute in milliseconds"
274
 
        return self._timedelta_to_milliseconds(self.interval)
 
271
        return self._datetime_to_milliseconds(self.interval)
275
272
    
276
273
    def __init__(self, name = None, disable_hook=None, config=None):
277
274
        """Note: the 'checker' key in 'config' sets the
480
477
            return now < (self.last_checked_ok + self.timeout)
481
478
 
482
479
 
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):
 
480
class ClientDBus(Client, dbus.service.Object):
645
481
    """A Client class using D-Bus
646
482
    
647
483
    Attributes:
658
494
        self.dbus_object_path = (dbus.ObjectPath
659
495
                                 (u"/clients/"
660
496
                                  + self.name.replace(u".", u"_")))
661
 
        DBusObjectWithProperties.__init__(self, self.bus,
662
 
                                          self.dbus_object_path)
 
497
        dbus.service.Object.__init__(self, self.bus,
 
498
                                     self.dbus_object_path)
663
499
    
664
500
    @staticmethod
665
501
    def _datetime_to_dbus(dt, variant_level=0):
694
530
            self.remove_from_connection()
695
531
        except LookupError:
696
532
            pass
697
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
698
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
533
        if hasattr(dbus.service.Object, u"__del__"):
 
534
            dbus.service.Object.__del__(self, *args, **kwargs)
699
535
        Client.__del__(self, *args, **kwargs)
700
536
    
701
537
    def checker_callback(self, pid, condition, command,
758
594
    ## D-Bus methods & signals
759
595
    _interface = u"se.bsnet.fukt.Mandos.Client"
760
596
    
 
597
    # CheckedOK - method
 
598
    @dbus.service.method(_interface)
 
599
    def CheckedOK(self):
 
600
        return self.checked_ok()
 
601
    
761
602
    # CheckerCompleted - signal
762
603
    @dbus.service.signal(_interface, signature=u"nxs")
763
604
    def CheckerCompleted(self, exitcode, waitstatus, command):
770
611
        "D-Bus signal"
771
612
        pass
772
613
    
 
614
    # GetAllProperties - method
 
615
    @dbus.service.method(_interface, out_signature=u"a{sv}")
 
616
    def GetAllProperties(self):
 
617
        "D-Bus method"
 
618
        return dbus.Dictionary({
 
619
                dbus.String(u"name"):
 
620
                    dbus.String(self.name, variant_level=1),
 
621
                dbus.String(u"fingerprint"):
 
622
                    dbus.String(self.fingerprint, variant_level=1),
 
623
                dbus.String(u"host"):
 
624
                    dbus.String(self.host, variant_level=1),
 
625
                dbus.String(u"created"):
 
626
                    self._datetime_to_dbus(self.created,
 
627
                                           variant_level=1),
 
628
                dbus.String(u"last_enabled"):
 
629
                    (self._datetime_to_dbus(self.last_enabled,
 
630
                                            variant_level=1)
 
631
                     if self.last_enabled is not None
 
632
                     else dbus.Boolean(False, variant_level=1)),
 
633
                dbus.String(u"enabled"):
 
634
                    dbus.Boolean(self.enabled, variant_level=1),
 
635
                dbus.String(u"last_checked_ok"):
 
636
                    (self._datetime_to_dbus(self.last_checked_ok,
 
637
                                            variant_level=1)
 
638
                     if self.last_checked_ok is not None
 
639
                     else dbus.Boolean (False, variant_level=1)),
 
640
                dbus.String(u"timeout"):
 
641
                    dbus.UInt64(self.timeout_milliseconds(),
 
642
                                variant_level=1),
 
643
                dbus.String(u"interval"):
 
644
                    dbus.UInt64(self.interval_milliseconds(),
 
645
                                variant_level=1),
 
646
                dbus.String(u"checker"):
 
647
                    dbus.String(self.checker_command,
 
648
                                variant_level=1),
 
649
                dbus.String(u"checker_running"):
 
650
                    dbus.Boolean(self.checker is not None,
 
651
                                 variant_level=1),
 
652
                dbus.String(u"object_path"):
 
653
                    dbus.ObjectPath(self.dbus_object_path,
 
654
                                    variant_level=1)
 
655
                }, signature=u"sv")
 
656
    
 
657
    # IsStillValid - method
 
658
    @dbus.service.method(_interface, out_signature=u"b")
 
659
    def IsStillValid(self):
 
660
        return self.still_valid()
 
661
    
773
662
    # PropertyChanged - signal
774
663
    @dbus.service.signal(_interface, signature=u"sv")
775
664
    def PropertyChanged(self, property, value):
788
677
        "D-Bus signal"
789
678
        pass
790
679
    
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
 
680
    # SetChecker - method
 
681
    @dbus.service.method(_interface, in_signature=u"s")
 
682
    def SetChecker(self, checker):
 
683
        "D-Bus setter method"
 
684
        self.checker_command = checker
896
685
        # Emit D-Bus signal
897
686
        self.PropertyChanged(dbus.String(u"checker"),
898
687
                             dbus.String(self.checker_command,
899
688
                                         variant_level=1))
900
689
    
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)
 
690
    # SetHost - method
 
691
    @dbus.service.method(_interface, in_signature=u"s")
 
692
    def SetHost(self, host):
 
693
        "D-Bus setter method"
 
694
        self.host = host
 
695
        # Emit D-Bus signal
 
696
        self.PropertyChanged(dbus.String(u"host"),
 
697
                             dbus.String(self.host, variant_level=1))
 
698
    
 
699
    # SetInterval - method
 
700
    @dbus.service.method(_interface, in_signature=u"t")
 
701
    def SetInterval(self, milliseconds):
 
702
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
703
        # Emit D-Bus signal
 
704
        self.PropertyChanged(dbus.String(u"interval"),
 
705
                             (dbus.UInt64(self.interval_milliseconds(),
 
706
                                          variant_level=1)))
 
707
    
 
708
    # SetSecret - method
 
709
    @dbus.service.method(_interface, in_signature=u"ay",
 
710
                         byte_arrays=True)
 
711
    def SetSecret(self, secret):
 
712
        "D-Bus setter method"
 
713
        self.secret = str(secret)
 
714
    
 
715
    # SetTimeout - method
 
716
    @dbus.service.method(_interface, in_signature=u"t")
 
717
    def SetTimeout(self, milliseconds):
 
718
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
719
        # Emit D-Bus signal
 
720
        self.PropertyChanged(dbus.String(u"timeout"),
 
721
                             (dbus.UInt64(self.timeout_milliseconds(),
 
722
                                          variant_level=1)))
 
723
    
 
724
    # Enable - method
 
725
    @dbus.service.method(_interface)
 
726
    def Enable(self):
 
727
        "D-Bus method"
 
728
        self.enable()
 
729
    
 
730
    # StartChecker - method
 
731
    @dbus.service.method(_interface)
 
732
    def StartChecker(self):
 
733
        "D-Bus method"
 
734
        self.start_checker()
 
735
    
 
736
    # Disable - method
 
737
    @dbus.service.method(_interface)
 
738
    def Disable(self):
 
739
        "D-Bus method"
 
740
        self.disable()
 
741
    
 
742
    # StopChecker - method
 
743
    @dbus.service.method(_interface)
 
744
    def StopChecker(self):
 
745
        self.stop_checker()
922
746
    
923
747
    del _interface
924
748
 
1159
983
        clients:        set of Client objects
1160
984
        gnutls_priority GnuTLS priority string
1161
985
        use_dbus:       Boolean; to emit D-Bus signals or not
 
986
        clients:        set of Client objects
 
987
        gnutls_priority GnuTLS priority string
 
988
        use_dbus:       Boolean; to emit D-Bus signals or not
1162
989
    
1163
990
    Assumes a gobject.MainLoop event loop.
1164
991
    """
1345
1172
 
1346
1173
def main():
1347
1174
    
1348
 
    ##################################################################
 
1175
    ######################################################################
1349
1176
    # Parsing of options, both command line and config file
1350
1177
    
1351
1178
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1601
1428
            def GetAllClientsWithProperties(self):
1602
1429
                "D-Bus method"
1603
1430
                return dbus.Dictionary(
1604
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1431
                    ((c.dbus_object_path, c.GetAllProperties())
1605
1432
                     for c in tcp_server.clients),
1606
1433
                    signature=u"oa{sv}")
1607
1434
            
1627
1454
        if use_dbus:
1628
1455
            # Emit D-Bus signal
1629
1456
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
1630
 
                                            client.GetAll(u""))
 
1457
                                            client.GetAllProperties())
1631
1458
        client.enable()
1632
1459
    
1633
1460
    tcp_server.enable()