/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-05 01:05:25 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090905010525-7qeq05ztwc2ddhuv
* plugins.d/mandos-client.c (main): Do not handle ignored signals.
                                    Bug fix: remove signal handler
                                    before re-raising signal.

* plugins.d/password-prompt.c (main): Check return values from
                                      "sigaddset()".

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
398
395
        # is as it should be.
399
396
        
400
397
        # If a checker exists, make sure it is not a zombie
401
 
        try:
 
398
        if self.checker is not None:
402
399
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
403
 
        except (AttributeError, OSError), error:
404
 
            if (isinstance(error, OSError)
405
 
                and error.errno != errno.ECHILD):
406
 
                raise error
407
 
        else:
408
400
            if pid:
409
401
                logger.warning(u"Checker was a zombie")
410
402
                gobject.source_remove(self.checker_callback_tag)
485
477
            return now < (self.last_checked_ok + self.timeout)
486
478
 
487
479
 
488
 
def dbus_service_property(dbus_interface, signature=u"v",
489
 
                          access=u"readwrite", byte_arrays=False):
490
 
    """Decorators for marking methods of a DBusObjectWithProperties to
491
 
    become properties on the D-Bus.
492
 
    
493
 
    The decorated method will be called with no arguments by "Get"
494
 
    and with one argument by "Set".
495
 
    
496
 
    The parameters, where they are supported, are the same as
497
 
    dbus.service.method, except there is only "signature", since the
498
 
    type from Get() and the type sent to Set() is the same.
499
 
    """
500
 
    def decorator(func):
501
 
        func._dbus_is_property = True
502
 
        func._dbus_interface = dbus_interface
503
 
        func._dbus_signature = signature
504
 
        func._dbus_access = access
505
 
        func._dbus_name = func.__name__
506
 
        if func._dbus_name.endswith(u"_dbus_property"):
507
 
            func._dbus_name = func._dbus_name[:-14]
508
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
509
 
        return func
510
 
    return decorator
511
 
 
512
 
 
513
 
class DBusPropertyException(dbus.exceptions.DBusException):
514
 
    """A base class for D-Bus property-related exceptions
515
 
    """
516
 
    def __unicode__(self):
517
 
        return unicode(str(self))
518
 
 
519
 
 
520
 
class DBusPropertyAccessException(DBusPropertyException):
521
 
    """A property's access permissions disallows an operation.
522
 
    """
523
 
    pass
524
 
 
525
 
 
526
 
class DBusPropertyNotFound(DBusPropertyException):
527
 
    """An attempt was made to access a non-existing property.
528
 
    """
529
 
    pass
530
 
 
531
 
 
532
 
class DBusObjectWithProperties(dbus.service.Object):
533
 
    """A D-Bus object with properties.
534
 
 
535
 
    Classes inheriting from this can use the dbus_service_property
536
 
    decorator to expose methods as D-Bus properties.  It exposes the
537
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
538
 
    """
539
 
    
540
 
    @staticmethod
541
 
    def _is_dbus_property(obj):
542
 
        return getattr(obj, u"_dbus_is_property", False)
543
 
    
544
 
    def _get_all_dbus_properties(self):
545
 
        """Returns a generator of (name, attribute) pairs
546
 
        """
547
 
        return ((prop._dbus_name, prop)
548
 
                for name, prop in
549
 
                inspect.getmembers(self, self._is_dbus_property))
550
 
    
551
 
    def _get_dbus_property(self, interface_name, property_name):
552
 
        """Returns a bound method if one exists which is a D-Bus
553
 
        property with the specified name and interface.
554
 
        """
555
 
        for name in (property_name,
556
 
                     property_name + u"_dbus_property"):
557
 
            prop = getattr(self, name, None)
558
 
            if (prop is None
559
 
                or not self._is_dbus_property(prop)
560
 
                or prop._dbus_name != property_name
561
 
                or (interface_name and prop._dbus_interface
562
 
                    and interface_name != prop._dbus_interface)):
563
 
                continue
564
 
            return prop
565
 
        # No such property
566
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
567
 
                                   + interface_name + u"."
568
 
                                   + property_name)
569
 
    
570
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
571
 
                         out_signature=u"v")
572
 
    def Get(self, interface_name, property_name):
573
 
        """Standard D-Bus property Get() method, see D-Bus standard.
574
 
        """
575
 
        prop = self._get_dbus_property(interface_name, property_name)
576
 
        if prop._dbus_access == u"write":
577
 
            raise DBusPropertyAccessException(property_name)
578
 
        value = prop()
579
 
        if not hasattr(value, u"variant_level"):
580
 
            return value
581
 
        return type(value)(value, variant_level=value.variant_level+1)
582
 
    
583
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
584
 
    def Set(self, interface_name, property_name, value):
585
 
        """Standard D-Bus property Set() method, see D-Bus standard.
586
 
        """
587
 
        prop = self._get_dbus_property(interface_name, property_name)
588
 
        if prop._dbus_access == u"read":
589
 
            raise DBusPropertyAccessException(property_name)
590
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
591
 
            value = dbus.ByteArray(''.join(unichr(byte)
592
 
                                           for byte in value))
593
 
        prop(value)
594
 
    
595
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
596
 
                         out_signature=u"a{sv}")
597
 
    def GetAll(self, interface_name):
598
 
        """Standard D-Bus property GetAll() method, see D-Bus
599
 
        standard.
600
 
 
601
 
        Note: Will not include properties with access="write".
602
 
        """
603
 
        all = {}
604
 
        for name, prop in self._get_all_dbus_properties():
605
 
            if (interface_name
606
 
                and interface_name != prop._dbus_interface):
607
 
                # Interface non-empty but did not match
608
 
                continue
609
 
            # Ignore write-only properties
610
 
            if prop._dbus_access == u"write":
611
 
                continue
612
 
            value = prop()
613
 
            if not hasattr(value, u"variant_level"):
614
 
                all[name] = value
615
 
                continue
616
 
            all[name] = type(value)(value, variant_level=
617
 
                                    value.variant_level+1)
618
 
        return dbus.Dictionary(all, signature=u"sv")
619
 
    
620
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
621
 
                         out_signature=u"s",
622
 
                         path_keyword='object_path',
623
 
                         connection_keyword='connection')
624
 
    def Introspect(self, object_path, connection):
625
 
        """Standard D-Bus method, overloaded to insert property tags.
626
 
        """
627
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
628
 
                                           connection)
629
 
        document = xml.dom.minidom.parseString(xmlstring)
630
 
        del xmlstring
631
 
        def make_tag(document, name, prop):
632
 
            e = document.createElement(u"property")
633
 
            e.setAttribute(u"name", name)
634
 
            e.setAttribute(u"type", prop._dbus_signature)
635
 
            e.setAttribute(u"access", prop._dbus_access)
636
 
            return e
637
 
        for if_tag in document.getElementsByTagName(u"interface"):
638
 
            for tag in (make_tag(document, name, prop)
639
 
                        for name, prop
640
 
                        in self._get_all_dbus_properties()
641
 
                        if prop._dbus_interface
642
 
                        == if_tag.getAttribute(u"name")):
643
 
                if_tag.appendChild(tag)
644
 
        xmlstring = document.toxml(u"utf-8")
645
 
        document.unlink()
646
 
        return xmlstring
647
 
 
648
 
 
649
 
class ClientDBus(Client, DBusObjectWithProperties):
 
480
class ClientDBus(Client, dbus.service.Object):
650
481
    """A Client class using D-Bus
651
482
    
652
483
    Attributes:
663
494
        self.dbus_object_path = (dbus.ObjectPath
664
495
                                 (u"/clients/"
665
496
                                  + self.name.replace(u".", u"_")))
666
 
        DBusObjectWithProperties.__init__(self, self.bus,
667
 
                                          self.dbus_object_path)
 
497
        dbus.service.Object.__init__(self, self.bus,
 
498
                                     self.dbus_object_path)
668
499
    
669
500
    @staticmethod
670
501
    def _datetime_to_dbus(dt, variant_level=0):
699
530
            self.remove_from_connection()
700
531
        except LookupError:
701
532
            pass
702
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
703
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
533
        if hasattr(dbus.service.Object, u"__del__"):
 
534
            dbus.service.Object.__del__(self, *args, **kwargs)
704
535
        Client.__del__(self, *args, **kwargs)
705
536
    
706
537
    def checker_callback(self, pid, condition, command,
780
611
        "D-Bus signal"
781
612
        pass
782
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
    
783
662
    # PropertyChanged - signal
784
663
    @dbus.service.signal(_interface, signature=u"sv")
785
664
    def PropertyChanged(self, property, value):
798
677
        "D-Bus signal"
799
678
        pass
800
679
    
 
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
 
685
        # Emit D-Bus signal
 
686
        self.PropertyChanged(dbus.String(u"checker"),
 
687
                             dbus.String(self.checker_command,
 
688
                                         variant_level=1))
 
689
    
 
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
    
801
724
    # Enable - method
802
725
    @dbus.service.method(_interface)
803
726
    def Enable(self):
821
744
    def StopChecker(self):
822
745
        self.stop_checker()
823
746
    
824
 
    # name - property
825
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
826
 
    def name_dbus_property(self):
827
 
        return dbus.String(self.name)
828
 
    
829
 
    # fingerprint - property
830
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
831
 
    def fingerprint_dbus_property(self):
832
 
        return dbus.String(self.fingerprint)
833
 
    
834
 
    # host - property
835
 
    @dbus_service_property(_interface, signature=u"s",
836
 
                           access=u"readwrite")
837
 
    def host_dbus_property(self, value=None):
838
 
        if value is None:       # get
839
 
            return dbus.String(self.host)
840
 
        self.host = value
841
 
        # Emit D-Bus signal
842
 
        self.PropertyChanged(dbus.String(u"host"),
843
 
                             dbus.String(value, variant_level=1))
844
 
    
845
 
    # created - property
846
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
847
 
    def created_dbus_property(self):
848
 
        return dbus.String(self._datetime_to_dbus(self.created))
849
 
    
850
 
    # last_enabled - property
851
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
852
 
    def last_enabled_dbus_property(self):
853
 
        if self.last_enabled is None:
854
 
            return dbus.String(u"")
855
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
856
 
    
857
 
    # enabled - property
858
 
    @dbus_service_property(_interface, signature=u"b",
859
 
                           access=u"readwrite")
860
 
    def enabled_dbus_property(self, value=None):
861
 
        if value is None:       # get
862
 
            return dbus.Boolean(self.enabled)
863
 
        if value:
864
 
            self.enable()
865
 
        else:
866
 
            self.disable()
867
 
    
868
 
    # last_checked_ok - property
869
 
    @dbus_service_property(_interface, signature=u"s",
870
 
                           access=u"readwrite")
871
 
    def last_checked_ok_dbus_property(self, value=None):
872
 
        if value is not None:
873
 
            self.checked_ok()
874
 
            return
875
 
        if self.last_checked_ok is None:
876
 
            return dbus.String(u"")
877
 
        return dbus.String(self._datetime_to_dbus(self
878
 
                                                  .last_checked_ok))
879
 
    
880
 
    # timeout - property
881
 
    @dbus_service_property(_interface, signature=u"t",
882
 
                           access=u"readwrite")
883
 
    def timeout_dbus_property(self, value=None):
884
 
        if value is None:       # get
885
 
            return dbus.UInt64(self.timeout_milliseconds())
886
 
        self.timeout = datetime.timedelta(0, 0, 0, value)
887
 
        # Emit D-Bus signal
888
 
        self.PropertyChanged(dbus.String(u"timeout"),
889
 
                             dbus.UInt64(value, variant_level=1))
890
 
        if getattr(self, u"disable_initiator_tag", None) is None:
891
 
            return
892
 
        # Reschedule timeout
893
 
        gobject.source_remove(self.disable_initiator_tag)
894
 
        self.disable_initiator_tag = None
895
 
        time_to_die = (self.
896
 
                       _timedelta_to_milliseconds((self
897
 
                                                   .last_checked_ok
898
 
                                                   + self.timeout)
899
 
                                                  - datetime.datetime
900
 
                                                  .utcnow()))
901
 
        if time_to_die <= 0:
902
 
            # The timeout has passed
903
 
            self.disable()
904
 
        else:
905
 
            self.disable_initiator_tag = (gobject.timeout_add
906
 
                                          (time_to_die, self.disable))
907
 
    
908
 
    # interval - property
909
 
    @dbus_service_property(_interface, signature=u"t",
910
 
                           access=u"readwrite")
911
 
    def interval_dbus_property(self, value=None):
912
 
        if value is None:       # get
913
 
            return dbus.UInt64(self.interval_milliseconds())
914
 
        self.interval = datetime.timedelta(0, 0, 0, value)
915
 
        # Emit D-Bus signal
916
 
        self.PropertyChanged(dbus.String(u"interval"),
917
 
                             dbus.UInt64(value, variant_level=1))
918
 
        if getattr(self, u"checker_initiator_tag", None) is None:
919
 
            return
920
 
        # Reschedule checker run
921
 
        gobject.source_remove(self.checker_initiator_tag)
922
 
        self.checker_initiator_tag = (gobject.timeout_add
923
 
                                      (value, self.start_checker))
924
 
        self.start_checker()    # Start one now, too
925
 
 
926
 
    # checker - property
927
 
    @dbus_service_property(_interface, signature=u"s",
928
 
                           access=u"readwrite")
929
 
    def checker_dbus_property(self, value=None):
930
 
        if value is None:       # get
931
 
            return dbus.String(self.checker_command)
932
 
        self.checker_command = value
933
 
        # Emit D-Bus signal
934
 
        self.PropertyChanged(dbus.String(u"checker"),
935
 
                             dbus.String(self.checker_command,
936
 
                                         variant_level=1))
937
 
    
938
 
    # checker_running - property
939
 
    @dbus_service_property(_interface, signature=u"b",
940
 
                           access=u"readwrite")
941
 
    def checker_running_dbus_property(self, value=None):
942
 
        if value is None:       # get
943
 
            return dbus.Boolean(self.checker is not None)
944
 
        if value:
945
 
            self.start_checker()
946
 
        else:
947
 
            self.stop_checker()
948
 
    
949
 
    # object_path - property
950
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
951
 
    def object_path_dbus_property(self):
952
 
        return self.dbus_object_path # is already a dbus.ObjectPath
953
 
    
954
 
    # secret = property
955
 
    @dbus_service_property(_interface, signature=u"ay",
956
 
                           access=u"write", byte_arrays=True)
957
 
    def secret_dbus_property(self, value):
958
 
        self.secret = str(value)
959
 
    
960
747
    del _interface
961
748
 
962
749
 
1196
983
        clients:        set of Client objects
1197
984
        gnutls_priority GnuTLS priority string
1198
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
1199
989
    
1200
990
    Assumes a gobject.MainLoop event loop.
1201
991
    """
1382
1172
 
1383
1173
def main():
1384
1174
    
1385
 
    ##################################################################
 
1175
    ######################################################################
1386
1176
    # Parsing of options, both command line and config file
1387
1177
    
1388
1178
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1638
1428
            def GetAllClientsWithProperties(self):
1639
1429
                "D-Bus method"
1640
1430
                return dbus.Dictionary(
1641
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1431
                    ((c.dbus_object_path, c.GetAllProperties())
1642
1432
                     for c in tcp_server.clients),
1643
1433
                    signature=u"oa{sv}")
1644
1434
            
1664
1454
        if use_dbus:
1665
1455
            # Emit D-Bus signal
1666
1456
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
1667
 
                                            client.GetAll(u""))
 
1457
                                            client.GetAllProperties())
1668
1458
        client.enable()
1669
1459
    
1670
1460
    tcp_server.enable()