/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-04-02 18:59:29 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • Revision ID: teddy@recompile.se-20150402185929-1q1rf1zelbpzzn74
Add "!RSA" also to examples/documentation.

* mandos.conf (priority): Add "!RSA" to default commented-out value.
* mandos.conf.xml (EXAMPLE): Add "!RSA" to example priority setting.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2015 Teddy Hogeborn
15
 
# Copyright © 2008-2015 Björn Påhlsson
 
14
# Copyright © 2008-2014 Teddy Hogeborn
 
15
# Copyright © 2008-2014 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
36
36
 
37
37
from future_builtins import *
38
38
 
39
 
try:
40
 
    import SocketServer as socketserver
41
 
except ImportError:
42
 
    import socketserver
 
39
import SocketServer as socketserver
43
40
import socket
44
41
import argparse
45
42
import datetime
50
47
import gnutls.library.functions
51
48
import gnutls.library.constants
52
49
import gnutls.library.types
53
 
try:
54
 
    import ConfigParser as configparser
55
 
except ImportError:
56
 
    import configparser
 
50
import ConfigParser as configparser
57
51
import sys
58
52
import re
59
53
import os
68
62
import struct
69
63
import fcntl
70
64
import functools
71
 
try:
72
 
    import cPickle as pickle
73
 
except ImportError:
74
 
    import pickle
 
65
import cPickle as pickle
75
66
import multiprocessing
76
67
import types
77
68
import binascii
78
69
import tempfile
79
70
import itertools
80
71
import collections
81
 
import codecs
82
72
 
83
73
import dbus
84
74
import dbus.service
85
 
try:
86
 
    import gobject
87
 
except ImportError:
88
 
    from gi.repository import GObject as gobject
 
75
import gobject
89
76
import avahi
90
77
from dbus.mainloop.glib import DBusGMainLoop
91
78
import ctypes
104
91
if sys.version_info.major == 2:
105
92
    str = unicode
106
93
 
107
 
version = "1.7.0"
 
94
version = "1.6.9"
108
95
stored_state_file = "clients.pickle"
109
96
 
110
97
logger = logging.getLogger()
111
98
syslogger = None
112
99
 
113
100
try:
114
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
115
 
        ctypes.util.find_library("c")).if_nametoindex
 
101
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
102
                      (ctypes.util.find_library("c"))
 
103
                      .if_nametoindex)
116
104
except (OSError, AttributeError):
117
 
    
118
105
    def if_nametoindex(interface):
119
106
        "Get an interface index the hard way, i.e. using fcntl()"
120
107
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
129
116
    """init logger and add loglevel"""
130
117
    
131
118
    global syslogger
132
 
    syslogger = (logging.handlers.SysLogHandler(
133
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
134
 
        address = "/dev/log"))
 
119
    syslogger = (logging.handlers.SysLogHandler
 
120
                 (facility =
 
121
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
122
                  address = "/dev/log"))
135
123
    syslogger.setFormatter(logging.Formatter
136
124
                           ('Mandos [%(process)d]: %(levelname)s:'
137
125
                            ' %(message)s'))
154
142
 
155
143
class PGPEngine(object):
156
144
    """A simple class for OpenPGP symmetric encryption & decryption"""
157
 
    
158
145
    def __init__(self):
159
146
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
160
147
        self.gnupgargs = ['--batch',
199
186
    
200
187
    def encrypt(self, data, password):
201
188
        passphrase = self.password_encode(password)
202
 
        with tempfile.NamedTemporaryFile(
203
 
                dir=self.tempdir) as passfile:
 
189
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
190
                                         ) as passfile:
204
191
            passfile.write(passphrase)
205
192
            passfile.flush()
206
193
            proc = subprocess.Popen(['gpg', '--symmetric',
217
204
    
218
205
    def decrypt(self, data, password):
219
206
        passphrase = self.password_encode(password)
220
 
        with tempfile.NamedTemporaryFile(
221
 
                dir = self.tempdir) as passfile:
 
207
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
208
                                         ) as passfile:
222
209
            passfile.write(passphrase)
223
210
            passfile.flush()
224
211
            proc = subprocess.Popen(['gpg', '--decrypt',
228
215
                                    stdin = subprocess.PIPE,
229
216
                                    stdout = subprocess.PIPE,
230
217
                                    stderr = subprocess.PIPE)
231
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
218
            decrypted_plaintext, err = proc.communicate(input
 
219
                                                        = data)
232
220
        if proc.returncode != 0:
233
221
            raise PGPError(err)
234
222
        return decrypted_plaintext
240
228
        return super(AvahiError, self).__init__(value, *args,
241
229
                                                **kwargs)
242
230
 
243
 
 
244
231
class AvahiServiceError(AvahiError):
245
232
    pass
246
233
 
247
 
 
248
234
class AvahiGroupError(AvahiError):
249
235
    pass
250
236
 
270
256
    bus: dbus.SystemBus()
271
257
    """
272
258
    
273
 
    def __init__(self,
274
 
                 interface = avahi.IF_UNSPEC,
275
 
                 name = None,
276
 
                 servicetype = None,
277
 
                 port = None,
278
 
                 TXT = None,
279
 
                 domain = "",
280
 
                 host = "",
281
 
                 max_renames = 32768,
282
 
                 protocol = avahi.PROTO_UNSPEC,
283
 
                 bus = None):
 
259
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
260
                 servicetype = None, port = None, TXT = None,
 
261
                 domain = "", host = "", max_renames = 32768,
 
262
                 protocol = avahi.PROTO_UNSPEC, bus = None):
284
263
        self.interface = interface
285
264
        self.name = name
286
265
        self.type = servicetype
303
282
                            " after %i retries, exiting.",
304
283
                            self.rename_count)
305
284
            raise AvahiServiceError("Too many renames")
306
 
        self.name = str(
307
 
            self.server.GetAlternativeServiceName(self.name))
 
285
        self.name = str(self.server
 
286
                        .GetAlternativeServiceName(self.name))
308
287
        self.rename_count += 1
309
288
        logger.info("Changing Zeroconf service name to %r ...",
310
289
                    self.name)
365
344
        elif state == avahi.ENTRY_GROUP_FAILURE:
366
345
            logger.critical("Avahi: Error in group state changed %s",
367
346
                            str(error))
368
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
347
            raise AvahiGroupError("State changed: {!s}"
 
348
                                  .format(error))
369
349
    
370
350
    def cleanup(self):
371
351
        """Derived from the Avahi example code"""
381
361
    def server_state_changed(self, state, error=None):
382
362
        """Derived from the Avahi example code"""
383
363
        logger.debug("Avahi server state change: %i", state)
384
 
        bad_states = {
385
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
386
 
            avahi.SERVER_REGISTERING: None,
387
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
388
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
389
 
        }
 
364
        bad_states = { avahi.SERVER_INVALID:
 
365
                           "Zeroconf server invalid",
 
366
                       avahi.SERVER_REGISTERING: None,
 
367
                       avahi.SERVER_COLLISION:
 
368
                           "Zeroconf server name collision",
 
369
                       avahi.SERVER_FAILURE:
 
370
                           "Zeroconf server failure" }
390
371
        if state in bad_states:
391
372
            if bad_states[state] is not None:
392
373
                if error is None:
395
376
                    logger.error(bad_states[state] + ": %r", error)
396
377
            self.cleanup()
397
378
        elif state == avahi.SERVER_RUNNING:
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)
 
379
            self.add()
410
380
        else:
411
381
            if error is None:
412
382
                logger.debug("Unknown state: %r", state)
422
392
                                    follow_name_owner_changes=True),
423
393
                avahi.DBUS_INTERFACE_SERVER)
424
394
        self.server.connect_to_signal("StateChanged",
425
 
                                      self.server_state_changed)
 
395
                                 self.server_state_changed)
426
396
        self.server_state_changed(self.server.GetState())
427
397
 
428
398
 
430
400
    def rename(self, *args, **kwargs):
431
401
        """Add the new name to the syslog messages"""
432
402
        ret = AvahiService.rename(self, *args, **kwargs)
433
 
        syslogger.setFormatter(logging.Formatter(
434
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
435
 
            .format(self.name)))
 
403
        syslogger.setFormatter(logging.Formatter
 
404
                               ('Mandos ({}) [%(process)d]:'
 
405
                                ' %(levelname)s: %(message)s'
 
406
                                .format(self.name)))
436
407
        return ret
437
408
 
438
 
def call_pipe(connection,       # : multiprocessing.Connection
439
 
              func, *args, **kwargs):
440
 
    """This function is meant to be called by multiprocessing.Process
441
 
    
442
 
    This function runs func(*args, **kwargs), and writes the resulting
443
 
    return value on the provided multiprocessing.Connection.
444
 
    """
445
 
    connection.send(func(*args, **kwargs))
446
 
    connection.close()
447
409
 
448
410
class Client(object):
449
411
    """A representation of a client host served by this server.
476
438
    last_checker_status: integer between 0 and 255 reflecting exit
477
439
                         status of last checker. -1 reflects crashed
478
440
                         checker, -2 means no checker completed yet.
479
 
    last_checker_signal: The signal which killed the last checker, if
480
 
                         last_checker_status is -1
481
441
    last_enabled: datetime.datetime(); (UTC) or None
482
442
    name:       string; from the config file, used in log messages and
483
443
                        D-Bus identifiers
496
456
                          "fingerprint", "host", "interval",
497
457
                          "last_approval_request", "last_checked_ok",
498
458
                          "last_enabled", "name", "timeout")
499
 
    client_defaults = {
500
 
        "timeout": "PT5M",
501
 
        "extended_timeout": "PT15M",
502
 
        "interval": "PT2M",
503
 
        "checker": "fping -q -- %%(host)s",
504
 
        "host": "",
505
 
        "approval_delay": "PT0S",
506
 
        "approval_duration": "PT1S",
507
 
        "approved_by_default": "True",
508
 
        "enabled": "True",
509
 
    }
 
459
    client_defaults = { "timeout": "PT5M",
 
460
                        "extended_timeout": "PT15M",
 
461
                        "interval": "PT2M",
 
462
                        "checker": "fping -q -- %%(host)s",
 
463
                        "host": "",
 
464
                        "approval_delay": "PT0S",
 
465
                        "approval_duration": "PT1S",
 
466
                        "approved_by_default": "True",
 
467
                        "enabled": "True",
 
468
                        }
510
469
    
511
470
    @staticmethod
512
471
    def config_parser(config):
590
549
        self.current_checker_command = None
591
550
        self.approved = None
592
551
        self.approvals_pending = 0
593
 
        self.changedstate = multiprocessing_manager.Condition(
594
 
            multiprocessing_manager.Lock())
595
 
        self.client_structure = [attr
596
 
                                 for attr in self.__dict__.iterkeys()
 
552
        self.changedstate = (multiprocessing_manager
 
553
                             .Condition(multiprocessing_manager
 
554
                                        .Lock()))
 
555
        self.client_structure = [attr for attr in
 
556
                                 self.__dict__.iterkeys()
597
557
                                 if not attr.startswith("_")]
598
558
        self.client_structure.append("client_structure")
599
559
        
600
 
        for name, t in inspect.getmembers(
601
 
                type(self), lambda obj: isinstance(obj, property)):
 
560
        for name, t in inspect.getmembers(type(self),
 
561
                                          lambda obj:
 
562
                                              isinstance(obj,
 
563
                                                         property)):
602
564
            if not name.startswith("_"):
603
565
                self.client_structure.append(name)
604
566
    
646
608
        # and every interval from then on.
647
609
        if self.checker_initiator_tag is not None:
648
610
            gobject.source_remove(self.checker_initiator_tag)
649
 
        self.checker_initiator_tag = gobject.timeout_add(
650
 
            int(self.interval.total_seconds() * 1000),
651
 
            self.start_checker)
 
611
        self.checker_initiator_tag = (gobject.timeout_add
 
612
                                      (int(self.interval
 
613
                                           .total_seconds() * 1000),
 
614
                                       self.start_checker))
652
615
        # Schedule a disable() when 'timeout' has passed
653
616
        if self.disable_initiator_tag is not None:
654
617
            gobject.source_remove(self.disable_initiator_tag)
655
 
        self.disable_initiator_tag = gobject.timeout_add(
656
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
618
        self.disable_initiator_tag = (gobject.timeout_add
 
619
                                      (int(self.timeout
 
620
                                           .total_seconds() * 1000),
 
621
                                       self.disable))
657
622
        # Also start a new checker *right now*.
658
623
        self.start_checker()
659
624
    
660
 
    def checker_callback(self, source, condition, connection,
661
 
                         command):
 
625
    def checker_callback(self, pid, condition, command):
662
626
        """The checker has completed, so take appropriate actions."""
663
627
        self.checker_callback_tag = None
664
628
        self.checker = None
665
 
        # Read return code from connection (see call_pipe)
666
 
        returncode = connection.recv()
667
 
        connection.close()
668
 
        
669
 
        if returncode >= 0:
670
 
            self.last_checker_status = returncode
671
 
            self.last_checker_signal = None
 
629
        if os.WIFEXITED(condition):
 
630
            self.last_checker_status = os.WEXITSTATUS(condition)
672
631
            if self.last_checker_status == 0:
673
632
                logger.info("Checker for %(name)s succeeded",
674
633
                            vars(self))
675
634
                self.checked_ok()
676
635
            else:
677
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
678
638
        else:
679
639
            self.last_checker_status = -1
680
 
            self.last_checker_signal = -returncode
681
640
            logger.warning("Checker for %(name)s crashed?",
682
641
                           vars(self))
683
 
        return False
684
642
    
685
643
    def checked_ok(self):
686
644
        """Assert that the client has been seen, alive and well."""
687
645
        self.last_checked_ok = datetime.datetime.utcnow()
688
646
        self.last_checker_status = 0
689
 
        self.last_checker_signal = None
690
647
        self.bump_timeout()
691
648
    
692
649
    def bump_timeout(self, timeout=None):
697
654
            gobject.source_remove(self.disable_initiator_tag)
698
655
            self.disable_initiator_tag = None
699
656
        if getattr(self, "enabled", False):
700
 
            self.disable_initiator_tag = gobject.timeout_add(
701
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (int(timeout.total_seconds()
 
659
                                               * 1000), self.disable))
702
660
            self.expires = datetime.datetime.utcnow() + timeout
703
661
    
704
662
    def need_approval(self):
718
676
        # than 'timeout' for the client to be disabled, which is as it
719
677
        # should be.
720
678
        
721
 
        if self.checker is not None and not self.checker.is_alive():
722
 
            logger.warning("Checker was not alive; joining")
723
 
            self.checker.join()
724
 
            self.checker = None
 
679
        # If a checker exists, make sure it is not a zombie
 
680
        try:
 
681
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
682
        except AttributeError:
 
683
            pass
 
684
        except OSError as error:
 
685
            if error.errno != errno.ECHILD:
 
686
                raise
 
687
        else:
 
688
            if pid:
 
689
                logger.warning("Checker was a zombie")
 
690
                gobject.source_remove(self.checker_callback_tag)
 
691
                self.checker_callback(pid, status,
 
692
                                      self.current_checker_command)
725
693
        # Start a new checker if needed
726
694
        if self.checker is None:
727
695
            # Escape attributes for the shell
728
 
            escaped_attrs = {
729
 
                attr: re.escape(str(getattr(self, attr)))
730
 
                for attr in self.runtime_expansions }
 
696
            escaped_attrs = { attr:
 
697
                                  re.escape(str(getattr(self, attr)))
 
698
                              for attr in self.runtime_expansions }
731
699
            try:
732
700
                command = self.checker_command % escaped_attrs
733
701
            except TypeError as error:
734
702
                logger.error('Could not format string "%s"',
735
 
                             self.checker_command,
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
 
705
            self.current_checker_command = command
 
706
            try:
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
 
709
                # We don't need to redirect stdout and stderr, since
 
710
                # in normal mode, that is already done by daemon(),
 
711
                # and in debug mode we don't want to.  (Stdin is
 
712
                # always replaced by /dev/null.)
 
713
                # The exception is when not debugging but nevertheless
 
714
                # running in the foreground; use the previously
 
715
                # created wnull.
 
716
                popen_args = {}
 
717
                if (not self.server_settings["debug"]
 
718
                    and self.server_settings["foreground"]):
 
719
                    popen_args.update({"stdout": wnull,
 
720
                                       "stderr": wnull })
 
721
                self.checker = subprocess.Popen(command,
 
722
                                                close_fds=True,
 
723
                                                shell=True, cwd="/",
 
724
                                                **popen_args)
 
725
            except OSError as error:
 
726
                logger.error("Failed to start subprocess",
736
727
                             exc_info=error)
737
 
                return True     # Try again later
738
 
            self.current_checker_command = command
739
 
            logger.info("Starting checker %r for %s", command,
740
 
                        self.name)
741
 
            # We don't need to redirect stdout and stderr, since
742
 
            # in normal mode, that is already done by daemon(),
743
 
            # and in debug mode we don't want to.  (Stdin is
744
 
            # always replaced by /dev/null.)
745
 
            # The exception is when not debugging but nevertheless
746
 
            # running in the foreground; use the previously
747
 
            # created wnull.
748
 
            popen_args = { "close_fds": True,
749
 
                           "shell": True,
750
 
                           "cwd": "/" }
751
 
            if (not self.server_settings["debug"]
752
 
                and self.server_settings["foreground"]):
753
 
                popen_args.update({"stdout": wnull,
754
 
                                   "stderr": wnull })
755
 
            pipe = multiprocessing.Pipe(duplex = False)
756
 
            self.checker = multiprocessing.Process(
757
 
                target = call_pipe,
758
 
                args = (pipe[1], subprocess.call, command),
759
 
                kwargs = popen_args)
760
 
            self.checker.start()
761
 
            self.checker_callback_tag = gobject.io_add_watch(
762
 
                pipe[0].fileno(), gobject.IO_IN,
763
 
                self.checker_callback, pipe[0], command)
 
728
                return True
 
729
            self.checker_callback_tag = (gobject.child_watch_add
 
730
                                         (self.checker.pid,
 
731
                                          self.checker_callback,
 
732
                                          data=command))
 
733
            # The checker may have completed before the gobject
 
734
            # watch was added.  Check for this.
 
735
            try:
 
736
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
737
            except OSError as error:
 
738
                if error.errno == errno.ECHILD:
 
739
                    # This should never happen
 
740
                    logger.error("Child process vanished",
 
741
                                 exc_info=error)
 
742
                    return True
 
743
                raise
 
744
            if pid:
 
745
                gobject.source_remove(self.checker_callback_tag)
 
746
                self.checker_callback(pid, status, command)
764
747
        # Re-run this periodically if run by gobject.timeout_add
765
748
        return True
766
749
    
772
755
        if getattr(self, "checker", None) is None:
773
756
            return
774
757
        logger.debug("Stopping checker for %(name)s", vars(self))
775
 
        self.checker.terminate()
 
758
        try:
 
759
            self.checker.terminate()
 
760
            #time.sleep(0.5)
 
761
            #if self.checker.poll() is None:
 
762
            #    self.checker.kill()
 
763
        except OSError as error:
 
764
            if error.errno != errno.ESRCH: # No such process
 
765
                raise
776
766
        self.checker = None
777
767
 
778
768
 
779
 
def dbus_service_property(dbus_interface,
780
 
                          signature="v",
781
 
                          access="readwrite",
782
 
                          byte_arrays=False):
 
769
def dbus_service_property(dbus_interface, signature="v",
 
770
                          access="readwrite", byte_arrays=False):
783
771
    """Decorators for marking methods of a DBusObjectWithProperties to
784
772
    become properties on the D-Bus.
785
773
    
795
783
    if byte_arrays and signature != "ay":
796
784
        raise ValueError("Byte arrays not supported for non-'ay'"
797
785
                         " signature {!r}".format(signature))
798
 
    
799
786
    def decorator(func):
800
787
        func._dbus_is_property = True
801
788
        func._dbus_interface = dbus_interface
806
793
            func._dbus_name = func._dbus_name[:-14]
807
794
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
808
795
        return func
809
 
    
810
796
    return decorator
811
797
 
812
798
 
821
807
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
822
808
                    "false"}
823
809
    """
824
 
    
825
810
    def decorator(func):
826
811
        func._dbus_is_interface = True
827
812
        func._dbus_interface = dbus_interface
828
813
        func._dbus_name = dbus_interface
829
814
        return func
830
 
    
831
815
    return decorator
832
816
 
833
817
 
842
826
                           access="r")
843
827
    def Property_dbus_property(self):
844
828
        return dbus.Boolean(False)
845
 
    
846
 
    See also the DBusObjectWithAnnotations class.
847
829
    """
848
 
    
849
830
    def decorator(func):
850
831
        func._dbus_annotations = annotations
851
832
        return func
852
 
    
853
833
    return decorator
854
834
 
855
835
 
858
838
    """
859
839
    pass
860
840
 
861
 
 
862
841
class DBusPropertyAccessException(DBusPropertyException):
863
842
    """A property's access permissions disallows an operation.
864
843
    """
871
850
    pass
872
851
 
873
852
 
874
 
class DBusObjectWithAnnotations(dbus.service.Object):
875
 
    """A D-Bus object with annotations.
 
853
class DBusObjectWithProperties(dbus.service.Object):
 
854
    """A D-Bus object with properties.
876
855
    
877
 
    Classes inheriting from this can use the dbus_annotations
878
 
    decorator to add annotations to methods or signals.
 
856
    Classes inheriting from this can use the dbus_service_property
 
857
    decorator to expose methods as D-Bus properties.  It exposes the
 
858
    standard Get(), Set(), and GetAll() methods on the D-Bus.
879
859
    """
880
860
    
881
861
    @staticmethod
891
871
    def _get_all_dbus_things(self, thing):
892
872
        """Returns a generator of (name, attribute) pairs
893
873
        """
894
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
874
        return ((getattr(athing.__get__(self), "_dbus_name",
 
875
                         name),
895
876
                 athing.__get__(self))
896
877
                for cls in self.__class__.__mro__
897
878
                for name, athing in
898
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
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
 
    """
 
879
                inspect.getmembers(cls,
 
880
                                   self._is_dbus_thing(thing)))
970
881
    
971
882
    def _get_dbus_property(self, interface_name, property_name):
972
883
        """Returns a bound method if one exists which is a D-Bus
973
884
        property with the specified name and interface.
974
885
        """
975
 
        for cls in self.__class__.__mro__:
976
 
            for name, value in inspect.getmembers(
977
 
                    cls, self._is_dbus_thing("property")):
 
886
        for cls in  self.__class__.__mro__:
 
887
            for name, value in (inspect.getmembers
 
888
                                (cls,
 
889
                                 self._is_dbus_thing("property"))):
978
890
                if (value._dbus_name == property_name
979
891
                    and value._dbus_interface == interface_name):
980
892
                    return value.__get__(self)
981
893
        
982
894
        # No such property
983
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
984
 
            self.dbus_object_path, interface_name, property_name))
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
 
    
995
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
996
 
                         in_signature="ss",
 
895
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
896
                                   + interface_name + "."
 
897
                                   + property_name)
 
898
    
 
899
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
997
900
                         out_signature="v")
998
901
    def Get(self, interface_name, property_name):
999
902
        """Standard D-Bus property Get() method, see D-Bus standard.
1024
927
                                            for byte in value))
1025
928
        prop(value)
1026
929
    
1027
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1028
 
                         in_signature="s",
 
930
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
1029
931
                         out_signature="a{sv}")
1030
932
    def GetAll(self, interface_name):
1031
933
        """Standard D-Bus property GetAll() method, see D-Bus
1046
948
            if not hasattr(value, "variant_level"):
1047
949
                properties[name] = value
1048
950
                continue
1049
 
            properties[name] = type(value)(
1050
 
                value, variant_level = value.variant_level + 1)
 
951
            properties[name] = type(value)(value, variant_level=
 
952
                                           value.variant_level+1)
1051
953
        return dbus.Dictionary(properties, signature="sv")
1052
954
    
1053
955
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
1067
969
        
1068
970
        Inserts property tags and interface annotation tags.
1069
971
        """
1070
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1071
 
                                                         object_path,
1072
 
                                                         connection)
 
972
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
973
                                                   connection)
1073
974
        try:
1074
975
            document = xml.dom.minidom.parseString(xmlstring)
1075
 
            
1076
976
            def make_tag(document, name, prop):
1077
977
                e = document.createElement("property")
1078
978
                e.setAttribute("name", name)
1079
979
                e.setAttribute("type", prop._dbus_signature)
1080
980
                e.setAttribute("access", prop._dbus_access)
1081
981
                return e
1082
 
            
1083
982
            for if_tag in document.getElementsByTagName("interface"):
1084
983
                # Add property tags
1085
984
                for tag in (make_tag(document, name, prop)
1088
987
                            if prop._dbus_interface
1089
988
                            == if_tag.getAttribute("name")):
1090
989
                    if_tag.appendChild(tag)
1091
 
                # Add annotation tags for properties
1092
 
                for tag in if_tag.getElementsByTagName("property"):
1093
 
                    annots = dict()
1094
 
                    for name, prop in self._get_all_dbus_things(
1095
 
                            "property"):
1096
 
                        if (name == tag.getAttribute("name")
1097
 
                            and prop._dbus_interface
1098
 
                            == if_tag.getAttribute("name")):
1099
 
                            annots.update(getattr(
1100
 
                                prop, "_dbus_annotations", {}))
1101
 
                    for name, value in annots.items():
1102
 
                        ann_tag = document.createElement(
1103
 
                            "annotation")
1104
 
                        ann_tag.setAttribute("name", name)
1105
 
                        ann_tag.setAttribute("value", value)
1106
 
                        tag.appendChild(ann_tag)
 
990
                # Add annotation tags
 
991
                for typ in ("method", "signal", "property"):
 
992
                    for tag in if_tag.getElementsByTagName(typ):
 
993
                        annots = dict()
 
994
                        for name, prop in (self.
 
995
                                           _get_all_dbus_things(typ)):
 
996
                            if (name == tag.getAttribute("name")
 
997
                                and prop._dbus_interface
 
998
                                == if_tag.getAttribute("name")):
 
999
                                annots.update(getattr
 
1000
                                              (prop,
 
1001
                                               "_dbus_annotations",
 
1002
                                               {}))
 
1003
                        for name, value in annots.items():
 
1004
                            ann_tag = document.createElement(
 
1005
                                "annotation")
 
1006
                            ann_tag.setAttribute("name", name)
 
1007
                            ann_tag.setAttribute("value", value)
 
1008
                            tag.appendChild(ann_tag)
 
1009
                # Add interface annotation tags
 
1010
                for annotation, value in dict(
 
1011
                    itertools.chain.from_iterable(
 
1012
                        annotations().items()
 
1013
                        for name, annotations in
 
1014
                        self._get_all_dbus_things("interface")
 
1015
                        if name == if_tag.getAttribute("name")
 
1016
                        )).items():
 
1017
                    ann_tag = document.createElement("annotation")
 
1018
                    ann_tag.setAttribute("name", annotation)
 
1019
                    ann_tag.setAttribute("value", value)
 
1020
                    if_tag.appendChild(ann_tag)
1107
1021
                # Add the names to the return values for the
1108
1022
                # "org.freedesktop.DBus.Properties" methods
1109
1023
                if (if_tag.getAttribute("name")
1127
1041
                         exc_info=error)
1128
1042
        return xmlstring
1129
1043
 
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, signature = "oas")
1158
 
    def InterfacesRemoved(self, object_path, interfaces):
1159
 
        pass
1160
 
    
1161
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1162
 
                         out_signature = "s",
1163
 
                         path_keyword = 'object_path',
1164
 
                         connection_keyword = 'connection')
1165
 
    def Introspect(self, object_path, connection):
1166
 
        """Overloading of standard D-Bus method.
1167
 
        
1168
 
        Override return argument name of GetManagedObjects to be
1169
 
        "objpath_interfaces_and_properties"
1170
 
        """
1171
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1172
 
                                                         object_path,
1173
 
                                                         connection)
1174
 
        try:
1175
 
            document = xml.dom.minidom.parseString(xmlstring)
1176
 
            
1177
 
            for if_tag in document.getElementsByTagName("interface"):
1178
 
                # Fix argument name for the GetManagedObjects method
1179
 
                if (if_tag.getAttribute("name")
1180
 
                                == dbus.OBJECT_MANAGER_IFACE):
1181
 
                    for cn in if_tag.getElementsByTagName("method"):
1182
 
                        if (cn.getAttribute("name")
1183
 
                            == "GetManagedObjects"):
1184
 
                            for arg in cn.getElementsByTagName("arg"):
1185
 
                                if (arg.getAttribute("direction")
1186
 
                                    == "out"):
1187
 
                                    arg.setAttribute(
1188
 
                                        "name",
1189
 
                                        "objpath_interfaces"
1190
 
                                        "_and_properties")
1191
 
            xmlstring = document.toxml("utf-8")
1192
 
            document.unlink()
1193
 
        except (AttributeError, xml.dom.DOMException,
1194
 
                xml.parsers.expat.ExpatError) as error:
1195
 
            logger.error("Failed to override Introspection method",
1196
 
                         exc_info = error)
1197
 
        return xmlstring
1198
1044
 
1199
1045
def datetime_to_dbus(dt, variant_level=0):
1200
1046
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1201
1047
    if dt is None:
1202
1048
        return dbus.String("", variant_level = variant_level)
1203
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1049
    return dbus.String(dt.isoformat(),
 
1050
                       variant_level=variant_level)
1204
1051
 
1205
1052
 
1206
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1226
1073
    (from DBusObjectWithProperties) and interfaces (from the
1227
1074
    dbus_interface_annotations decorator).
1228
1075
    """
1229
 
    
1230
1076
    def wrapper(cls):
1231
1077
        for orig_interface_name, alt_interface_name in (
1232
 
                alt_interface_names.items()):
 
1078
            alt_interface_names.items()):
1233
1079
            attr = {}
1234
1080
            interface_names = set()
1235
1081
            # Go though all attributes of the class
1237
1083
                # Ignore non-D-Bus attributes, and D-Bus attributes
1238
1084
                # with the wrong interface name
1239
1085
                if (not hasattr(attribute, "_dbus_interface")
1240
 
                    or not attribute._dbus_interface.startswith(
1241
 
                        orig_interface_name)):
 
1086
                    or not attribute._dbus_interface
 
1087
                    .startswith(orig_interface_name)):
1242
1088
                    continue
1243
1089
                # Create an alternate D-Bus interface name based on
1244
1090
                # the current name
1245
 
                alt_interface = attribute._dbus_interface.replace(
1246
 
                    orig_interface_name, alt_interface_name)
 
1091
                alt_interface = (attribute._dbus_interface
 
1092
                                 .replace(orig_interface_name,
 
1093
                                          alt_interface_name))
1247
1094
                interface_names.add(alt_interface)
1248
1095
                # Is this a D-Bus signal?
1249
1096
                if getattr(attribute, "_dbus_is_signal", False):
1250
 
                    if sys.version_info.major == 2:
1251
 
                        # Extract the original non-method undecorated
1252
 
                        # function by black magic
1253
 
                        nonmethod_func = (dict(
 
1097
                    # Extract the original non-method undecorated
 
1098
                    # function by black magic
 
1099
                    nonmethod_func = (dict(
1254
1100
                            zip(attribute.func_code.co_freevars,
1255
 
                                attribute.__closure__))
1256
 
                                          ["func"].cell_contents)
1257
 
                    else:
1258
 
                        nonmethod_func = attribute
 
1101
                                attribute.__closure__))["func"]
 
1102
                                      .cell_contents)
1259
1103
                    # Create a new, but exactly alike, function
1260
1104
                    # object, and decorate it to be a new D-Bus signal
1261
1105
                    # 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__)
1276
 
                    new_function = (dbus.service.signal(
1277
 
                        alt_interface,
1278
 
                        attribute._dbus_signature)(new_function))
 
1106
                    new_function = (dbus.service.signal
 
1107
                                    (alt_interface,
 
1108
                                     attribute._dbus_signature)
 
1109
                                    (types.FunctionType(
 
1110
                                nonmethod_func.func_code,
 
1111
                                nonmethod_func.func_globals,
 
1112
                                nonmethod_func.func_name,
 
1113
                                nonmethod_func.func_defaults,
 
1114
                                nonmethod_func.func_closure)))
1279
1115
                    # Copy annotations, if any
1280
1116
                    try:
1281
 
                        new_function._dbus_annotations = dict(
1282
 
                            attribute._dbus_annotations)
 
1117
                        new_function._dbus_annotations = (
 
1118
                            dict(attribute._dbus_annotations))
1283
1119
                    except AttributeError:
1284
1120
                        pass
1285
1121
                    # Define a creator of a function to call both the
1290
1126
                        """This function is a scope container to pass
1291
1127
                        func1 and func2 to the "call_both" function
1292
1128
                        outside of its arguments"""
1293
 
                        
1294
 
                        @functools.wraps(func2)
1295
1129
                        def call_both(*args, **kwargs):
1296
1130
                            """This function will emit two D-Bus
1297
1131
                            signals by calling func1 and func2"""
1298
1132
                            func1(*args, **kwargs)
1299
1133
                            func2(*args, **kwargs)
1300
 
                        # Make wrapper function look like a D-Bus signal
1301
 
                        for name, attr in inspect.getmembers(func2):
1302
 
                            if name.startswith("_dbus_"):
1303
 
                                setattr(call_both, name, attr)
1304
 
                        
1305
1134
                        return call_both
1306
1135
                    # Create the "call_both" function and add it to
1307
1136
                    # the class
1312
1141
                    # object.  Decorate it to be a new D-Bus method
1313
1142
                    # with the alternate D-Bus interface name.  Add it
1314
1143
                    # to the class.
1315
 
                    attr[attrname] = (
1316
 
                        dbus.service.method(
1317
 
                            alt_interface,
1318
 
                            attribute._dbus_in_signature,
1319
 
                            attribute._dbus_out_signature)
1320
 
                        (types.FunctionType(attribute.func_code,
1321
 
                                            attribute.func_globals,
1322
 
                                            attribute.func_name,
1323
 
                                            attribute.func_defaults,
1324
 
                                            attribute.func_closure)))
 
1144
                    attr[attrname] = (dbus.service.method
 
1145
                                      (alt_interface,
 
1146
                                       attribute._dbus_in_signature,
 
1147
                                       attribute._dbus_out_signature)
 
1148
                                      (types.FunctionType
 
1149
                                       (attribute.func_code,
 
1150
                                        attribute.func_globals,
 
1151
                                        attribute.func_name,
 
1152
                                        attribute.func_defaults,
 
1153
                                        attribute.func_closure)))
1325
1154
                    # Copy annotations, if any
1326
1155
                    try:
1327
 
                        attr[attrname]._dbus_annotations = dict(
1328
 
                            attribute._dbus_annotations)
 
1156
                        attr[attrname]._dbus_annotations = (
 
1157
                            dict(attribute._dbus_annotations))
1329
1158
                    except AttributeError:
1330
1159
                        pass
1331
1160
                # Is this a D-Bus property?
1334
1163
                    # object, and decorate it to be a new D-Bus
1335
1164
                    # property with the alternate D-Bus interface
1336
1165
                    # name.  Add it to the class.
1337
 
                    attr[attrname] = (dbus_service_property(
1338
 
                        alt_interface, attribute._dbus_signature,
1339
 
                        attribute._dbus_access,
1340
 
                        attribute._dbus_get_args_options
1341
 
                        ["byte_arrays"])
1342
 
                                      (types.FunctionType(
1343
 
                                          attribute.func_code,
1344
 
                                          attribute.func_globals,
1345
 
                                          attribute.func_name,
1346
 
                                          attribute.func_defaults,
1347
 
                                          attribute.func_closure)))
 
1166
                    attr[attrname] = (dbus_service_property
 
1167
                                      (alt_interface,
 
1168
                                       attribute._dbus_signature,
 
1169
                                       attribute._dbus_access,
 
1170
                                       attribute
 
1171
                                       ._dbus_get_args_options
 
1172
                                       ["byte_arrays"])
 
1173
                                      (types.FunctionType
 
1174
                                       (attribute.func_code,
 
1175
                                        attribute.func_globals,
 
1176
                                        attribute.func_name,
 
1177
                                        attribute.func_defaults,
 
1178
                                        attribute.func_closure)))
1348
1179
                    # Copy annotations, if any
1349
1180
                    try:
1350
 
                        attr[attrname]._dbus_annotations = dict(
1351
 
                            attribute._dbus_annotations)
 
1181
                        attr[attrname]._dbus_annotations = (
 
1182
                            dict(attribute._dbus_annotations))
1352
1183
                    except AttributeError:
1353
1184
                        pass
1354
1185
                # Is this a D-Bus interface?
1357
1188
                    # object.  Decorate it to be a new D-Bus interface
1358
1189
                    # with the alternate D-Bus interface name.  Add it
1359
1190
                    # to the class.
1360
 
                    attr[attrname] = (
1361
 
                        dbus_interface_annotations(alt_interface)
1362
 
                        (types.FunctionType(attribute.func_code,
1363
 
                                            attribute.func_globals,
1364
 
                                            attribute.func_name,
1365
 
                                            attribute.func_defaults,
1366
 
                                            attribute.func_closure)))
 
1191
                    attr[attrname] = (dbus_interface_annotations
 
1192
                                      (alt_interface)
 
1193
                                      (types.FunctionType
 
1194
                                       (attribute.func_code,
 
1195
                                        attribute.func_globals,
 
1196
                                        attribute.func_name,
 
1197
                                        attribute.func_defaults,
 
1198
                                        attribute.func_closure)))
1367
1199
            if deprecate:
1368
1200
                # Deprecate all alternate interfaces
1369
1201
                iname="_AlternateDBusNames_interface_annotation{}"
1370
1202
                for interface_name in interface_names:
1371
 
                    
1372
1203
                    @dbus_interface_annotations(interface_name)
1373
1204
                    def func(self):
1374
1205
                        return { "org.freedesktop.DBus.Deprecated":
1375
 
                                 "true" }
 
1206
                                     "true" }
1376
1207
                    # Find an unused name
1377
1208
                    for aname in (iname.format(i)
1378
1209
                                  for i in itertools.count()):
1383
1214
                # Replace the class with a new subclass of it with
1384
1215
                # methods, signals, etc. as created above.
1385
1216
                cls = type(b"{}Alternate".format(cls.__name__),
1386
 
                           (cls, ), attr)
 
1217
                           (cls,), attr)
1387
1218
        return cls
1388
 
    
1389
1219
    return wrapper
1390
1220
 
1391
1221
 
1392
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1393
 
                            "se.bsnet.fukt.Mandos"})
 
1223
                                "se.bsnet.fukt.Mandos"})
1394
1224
class ClientDBus(Client, DBusObjectWithProperties):
1395
1225
    """A Client class using D-Bus
1396
1226
    
1400
1230
    """
1401
1231
    
1402
1232
    runtime_expansions = (Client.runtime_expansions
1403
 
                          + ("dbus_object_path", ))
 
1233
                          + ("dbus_object_path",))
1404
1234
    
1405
1235
    _interface = "se.recompile.Mandos.Client"
1406
1236
    
1414
1244
        client_object_name = str(self.name).translate(
1415
1245
            {ord("."): ord("_"),
1416
1246
             ord("-"): ord("_")})
1417
 
        self.dbus_object_path = dbus.ObjectPath(
1418
 
            "/clients/" + client_object_name)
 
1247
        self.dbus_object_path = (dbus.ObjectPath
 
1248
                                 ("/clients/" + client_object_name))
1419
1249
        DBusObjectWithProperties.__init__(self, self.bus,
1420
1250
                                          self.dbus_object_path)
1421
1251
    
1422
 
    def notifychangeproperty(transform_func, dbus_name,
1423
 
                             type_func=lambda x: x,
1424
 
                             variant_level=1,
1425
 
                             invalidate_only=False,
 
1252
    def notifychangeproperty(transform_func,
 
1253
                             dbus_name, type_func=lambda x: x,
 
1254
                             variant_level=1, invalidate_only=False,
1426
1255
                             _interface=_interface):
1427
1256
        """ Modify a variable so that it's a property which announces
1428
1257
        its changes to DBus.
1435
1264
        variant_level: D-Bus variant level.  Default: 1
1436
1265
        """
1437
1266
        attrname = "_{}".format(dbus_name)
1438
 
        
1439
1267
        def setter(self, value):
1440
1268
            if hasattr(self, "dbus_object_path"):
1441
1269
                if (not hasattr(self, attrname) or
1442
1270
                    type_func(getattr(self, attrname, None))
1443
1271
                    != type_func(value)):
1444
1272
                    if invalidate_only:
1445
 
                        self.PropertiesChanged(
1446
 
                            _interface, dbus.Dictionary(),
1447
 
                            dbus.Array((dbus_name, )))
 
1273
                        self.PropertiesChanged(_interface,
 
1274
                                               dbus.Dictionary(),
 
1275
                                               dbus.Array
 
1276
                                               ((dbus_name,)))
1448
1277
                    else:
1449
 
                        dbus_value = transform_func(
1450
 
                            type_func(value),
1451
 
                            variant_level = variant_level)
 
1278
                        dbus_value = transform_func(type_func(value),
 
1279
                                                    variant_level
 
1280
                                                    =variant_level)
1452
1281
                        self.PropertyChanged(dbus.String(dbus_name),
1453
1282
                                             dbus_value)
1454
 
                        self.PropertiesChanged(
1455
 
                            _interface,
1456
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1457
 
                                              dbus_value }),
1458
 
                            dbus.Array())
 
1283
                        self.PropertiesChanged(_interface,
 
1284
                                               dbus.Dictionary({
 
1285
                                    dbus.String(dbus_name):
 
1286
                                        dbus_value }), dbus.Array())
1459
1287
            setattr(self, attrname, value)
1460
1288
        
1461
1289
        return property(lambda self: getattr(self, attrname), setter)
1467
1295
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1468
1296
    last_enabled = notifychangeproperty(datetime_to_dbus,
1469
1297
                                        "LastEnabled")
1470
 
    checker = notifychangeproperty(
1471
 
        dbus.Boolean, "CheckerRunning",
1472
 
        type_func = lambda checker: checker is not None)
 
1298
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1299
                                   type_func = lambda checker:
 
1300
                                       checker is not None)
1473
1301
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1474
1302
                                           "LastCheckedOK")
1475
1303
    last_checker_status = notifychangeproperty(dbus.Int16,
1478
1306
        datetime_to_dbus, "LastApprovalRequest")
1479
1307
    approved_by_default = notifychangeproperty(dbus.Boolean,
1480
1308
                                               "ApprovedByDefault")
1481
 
    approval_delay = notifychangeproperty(
1482
 
        dbus.UInt64, "ApprovalDelay",
1483
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1309
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1310
                                          "ApprovalDelay",
 
1311
                                          type_func =
 
1312
                                          lambda td: td.total_seconds()
 
1313
                                          * 1000)
1484
1314
    approval_duration = notifychangeproperty(
1485
1315
        dbus.UInt64, "ApprovalDuration",
1486
1316
        type_func = lambda td: td.total_seconds() * 1000)
1487
1317
    host = notifychangeproperty(dbus.String, "Host")
1488
 
    timeout = notifychangeproperty(
1489
 
        dbus.UInt64, "Timeout",
1490
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1318
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1319
                                   type_func = lambda td:
 
1320
                                       td.total_seconds() * 1000)
1491
1321
    extended_timeout = notifychangeproperty(
1492
1322
        dbus.UInt64, "ExtendedTimeout",
1493
1323
        type_func = lambda td: td.total_seconds() * 1000)
1494
 
    interval = notifychangeproperty(
1495
 
        dbus.UInt64, "Interval",
1496
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1324
    interval = notifychangeproperty(dbus.UInt64,
 
1325
                                    "Interval",
 
1326
                                    type_func =
 
1327
                                    lambda td: td.total_seconds()
 
1328
                                    * 1000)
1497
1329
    checker_command = notifychangeproperty(dbus.String, "Checker")
1498
1330
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1499
1331
                                  invalidate_only=True)
1509
1341
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1510
1342
        Client.__del__(self, *args, **kwargs)
1511
1343
    
1512
 
    def checker_callback(self, source, condition,
1513
 
                         connection, command, *args, **kwargs):
1514
 
        ret = Client.checker_callback(self, source, condition,
1515
 
                                      connection, command, *args,
1516
 
                                      **kwargs)
1517
 
        exitstatus = self.last_checker_status
1518
 
        if exitstatus >= 0:
 
1344
    def checker_callback(self, pid, condition, command,
 
1345
                         *args, **kwargs):
 
1346
        self.checker_callback_tag = None
 
1347
        self.checker = None
 
1348
        if os.WIFEXITED(condition):
 
1349
            exitstatus = os.WEXITSTATUS(condition)
1519
1350
            # Emit D-Bus signal
1520
1351
            self.CheckerCompleted(dbus.Int16(exitstatus),
1521
 
                                  # This is specific to GNU libC
1522
 
                                  dbus.Int64(exitstatus << 8),
 
1352
                                  dbus.Int64(condition),
1523
1353
                                  dbus.String(command))
1524
1354
        else:
1525
1355
            # Emit D-Bus signal
1526
1356
            self.CheckerCompleted(dbus.Int16(-1),
1527
 
                                  dbus.Int64(
1528
 
                                      # This is specific to GNU libC
1529
 
                                      (exitstatus << 8)
1530
 
                                      | self.last_checker_signal),
 
1357
                                  dbus.Int64(condition),
1531
1358
                                  dbus.String(command))
1532
 
        return ret
 
1359
        
 
1360
        return Client.checker_callback(self, pid, condition, command,
 
1361
                                       *args, **kwargs)
1533
1362
    
1534
1363
    def start_checker(self, *args, **kwargs):
1535
1364
        old_checker_pid = getattr(self.checker, "pid", None)
1610
1439
        self.checked_ok()
1611
1440
    
1612
1441
    # Enable - method
1613
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1614
1442
    @dbus.service.method(_interface)
1615
1443
    def Enable(self):
1616
1444
        "D-Bus method"
1617
1445
        self.enable()
1618
1446
    
1619
1447
    # StartChecker - method
1620
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1621
1448
    @dbus.service.method(_interface)
1622
1449
    def StartChecker(self):
1623
1450
        "D-Bus method"
1624
1451
        self.start_checker()
1625
1452
    
1626
1453
    # Disable - method
1627
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1628
1454
    @dbus.service.method(_interface)
1629
1455
    def Disable(self):
1630
1456
        "D-Bus method"
1631
1457
        self.disable()
1632
1458
    
1633
1459
    # StopChecker - method
1634
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1635
1460
    @dbus.service.method(_interface)
1636
1461
    def StopChecker(self):
1637
1462
        self.stop_checker()
1644
1469
        return dbus.Boolean(bool(self.approvals_pending))
1645
1470
    
1646
1471
    # ApprovedByDefault - property
1647
 
    @dbus_service_property(_interface,
1648
 
                           signature="b",
 
1472
    @dbus_service_property(_interface, signature="b",
1649
1473
                           access="readwrite")
1650
1474
    def ApprovedByDefault_dbus_property(self, value=None):
1651
1475
        if value is None:       # get
1653
1477
        self.approved_by_default = bool(value)
1654
1478
    
1655
1479
    # ApprovalDelay - property
1656
 
    @dbus_service_property(_interface,
1657
 
                           signature="t",
 
1480
    @dbus_service_property(_interface, signature="t",
1658
1481
                           access="readwrite")
1659
1482
    def ApprovalDelay_dbus_property(self, value=None):
1660
1483
        if value is None:       # get
1663
1486
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1664
1487
    
1665
1488
    # ApprovalDuration - property
1666
 
    @dbus_service_property(_interface,
1667
 
                           signature="t",
 
1489
    @dbus_service_property(_interface, signature="t",
1668
1490
                           access="readwrite")
1669
1491
    def ApprovalDuration_dbus_property(self, value=None):
1670
1492
        if value is None:       # get
1673
1495
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1674
1496
    
1675
1497
    # Name - property
1676
 
    @dbus_annotations(
1677
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1678
1498
    @dbus_service_property(_interface, signature="s", access="read")
1679
1499
    def Name_dbus_property(self):
1680
1500
        return dbus.String(self.name)
1681
1501
    
1682
1502
    # Fingerprint - property
1683
 
    @dbus_annotations(
1684
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1685
1503
    @dbus_service_property(_interface, signature="s", access="read")
1686
1504
    def Fingerprint_dbus_property(self):
1687
1505
        return dbus.String(self.fingerprint)
1688
1506
    
1689
1507
    # Host - property
1690
 
    @dbus_service_property(_interface,
1691
 
                           signature="s",
 
1508
    @dbus_service_property(_interface, signature="s",
1692
1509
                           access="readwrite")
1693
1510
    def Host_dbus_property(self, value=None):
1694
1511
        if value is None:       # get
1696
1513
        self.host = str(value)
1697
1514
    
1698
1515
    # Created - property
1699
 
    @dbus_annotations(
1700
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1701
1516
    @dbus_service_property(_interface, signature="s", access="read")
1702
1517
    def Created_dbus_property(self):
1703
1518
        return datetime_to_dbus(self.created)
1708
1523
        return datetime_to_dbus(self.last_enabled)
1709
1524
    
1710
1525
    # Enabled - property
1711
 
    @dbus_service_property(_interface,
1712
 
                           signature="b",
 
1526
    @dbus_service_property(_interface, signature="b",
1713
1527
                           access="readwrite")
1714
1528
    def Enabled_dbus_property(self, value=None):
1715
1529
        if value is None:       # get
1720
1534
            self.disable()
1721
1535
    
1722
1536
    # LastCheckedOK - property
1723
 
    @dbus_service_property(_interface,
1724
 
                           signature="s",
 
1537
    @dbus_service_property(_interface, signature="s",
1725
1538
                           access="readwrite")
1726
1539
    def LastCheckedOK_dbus_property(self, value=None):
1727
1540
        if value is not None:
1730
1543
        return datetime_to_dbus(self.last_checked_ok)
1731
1544
    
1732
1545
    # LastCheckerStatus - property
1733
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1546
    @dbus_service_property(_interface, signature="n",
 
1547
                           access="read")
1734
1548
    def LastCheckerStatus_dbus_property(self):
1735
1549
        return dbus.Int16(self.last_checker_status)
1736
1550
    
1745
1559
        return datetime_to_dbus(self.last_approval_request)
1746
1560
    
1747
1561
    # Timeout - property
1748
 
    @dbus_service_property(_interface,
1749
 
                           signature="t",
 
1562
    @dbus_service_property(_interface, signature="t",
1750
1563
                           access="readwrite")
1751
1564
    def Timeout_dbus_property(self, value=None):
1752
1565
        if value is None:       # get
1765
1578
                    is None):
1766
1579
                    return
1767
1580
                gobject.source_remove(self.disable_initiator_tag)
1768
 
                self.disable_initiator_tag = gobject.timeout_add(
1769
 
                    int((self.expires - now).total_seconds() * 1000),
1770
 
                    self.disable)
 
1581
                self.disable_initiator_tag = (
 
1582
                    gobject.timeout_add(
 
1583
                        int((self.expires - now).total_seconds()
 
1584
                            * 1000), self.disable))
1771
1585
    
1772
1586
    # ExtendedTimeout - property
1773
 
    @dbus_service_property(_interface,
1774
 
                           signature="t",
 
1587
    @dbus_service_property(_interface, signature="t",
1775
1588
                           access="readwrite")
1776
1589
    def ExtendedTimeout_dbus_property(self, value=None):
1777
1590
        if value is None:       # get
1780
1593
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1781
1594
    
1782
1595
    # Interval - property
1783
 
    @dbus_service_property(_interface,
1784
 
                           signature="t",
 
1596
    @dbus_service_property(_interface, signature="t",
1785
1597
                           access="readwrite")
1786
1598
    def Interval_dbus_property(self, value=None):
1787
1599
        if value is None:       # get
1792
1604
        if self.enabled:
1793
1605
            # Reschedule checker run
1794
1606
            gobject.source_remove(self.checker_initiator_tag)
1795
 
            self.checker_initiator_tag = gobject.timeout_add(
1796
 
                value, self.start_checker)
1797
 
            self.start_checker() # Start one now, too
 
1607
            self.checker_initiator_tag = (gobject.timeout_add
 
1608
                                          (value, self.start_checker))
 
1609
            self.start_checker()    # Start one now, too
1798
1610
    
1799
1611
    # Checker - property
1800
 
    @dbus_service_property(_interface,
1801
 
                           signature="s",
 
1612
    @dbus_service_property(_interface, signature="s",
1802
1613
                           access="readwrite")
1803
1614
    def Checker_dbus_property(self, value=None):
1804
1615
        if value is None:       # get
1806
1617
        self.checker_command = str(value)
1807
1618
    
1808
1619
    # CheckerRunning - property
1809
 
    @dbus_service_property(_interface,
1810
 
                           signature="b",
 
1620
    @dbus_service_property(_interface, signature="b",
1811
1621
                           access="readwrite")
1812
1622
    def CheckerRunning_dbus_property(self, value=None):
1813
1623
        if value is None:       # get
1818
1628
            self.stop_checker()
1819
1629
    
1820
1630
    # ObjectPath - property
1821
 
    @dbus_annotations(
1822
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
1823
 
         "org.freedesktop.DBus.Deprecated": "true"})
1824
1631
    @dbus_service_property(_interface, signature="o", access="read")
1825
1632
    def ObjectPath_dbus_property(self):
1826
1633
        return self.dbus_object_path # is already a dbus.ObjectPath
1827
1634
    
1828
1635
    # Secret = property
1829
 
    @dbus_annotations(
1830
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
1831
 
         "invalidates"})
1832
 
    @dbus_service_property(_interface,
1833
 
                           signature="ay",
1834
 
                           access="write",
1835
 
                           byte_arrays=True)
 
1636
    @dbus_service_property(_interface, signature="ay",
 
1637
                           access="write", byte_arrays=True)
1836
1638
    def Secret_dbus_property(self, value):
1837
1639
        self.secret = bytes(value)
1838
1640
    
1844
1646
        self._pipe = child_pipe
1845
1647
        self._pipe.send(('init', fpr, address))
1846
1648
        if not self._pipe.recv():
1847
 
            raise KeyError(fpr)
 
1649
            raise KeyError()
1848
1650
    
1849
1651
    def __getattribute__(self, name):
1850
1652
        if name == '_pipe':
1854
1656
        if data[0] == 'data':
1855
1657
            return data[1]
1856
1658
        if data[0] == 'function':
1857
 
            
1858
1659
            def func(*args, **kwargs):
1859
1660
                self._pipe.send(('funcall', name, args, kwargs))
1860
1661
                return self._pipe.recv()[1]
1861
 
            
1862
1662
            return func
1863
1663
    
1864
1664
    def __setattr__(self, name, value):
1880
1680
            logger.debug("Pipe FD: %d",
1881
1681
                         self.server.child_pipe.fileno())
1882
1682
            
1883
 
            session = gnutls.connection.ClientSession(
1884
 
                self.request, gnutls.connection .X509Credentials())
 
1683
            session = (gnutls.connection
 
1684
                       .ClientSession(self.request,
 
1685
                                      gnutls.connection
 
1686
                                      .X509Credentials()))
1885
1687
            
1886
1688
            # Note: gnutls.connection.X509Credentials is really a
1887
1689
            # generic GnuTLS certificate credentials object so long as
1896
1698
            priority = self.server.gnutls_priority
1897
1699
            if priority is None:
1898
1700
                priority = "NORMAL"
1899
 
            gnutls.library.functions.gnutls_priority_set_direct(
1900
 
                session._c_object, priority, None)
 
1701
            (gnutls.library.functions
 
1702
             .gnutls_priority_set_direct(session._c_object,
 
1703
                                         priority, None))
1901
1704
            
1902
1705
            # Start communication using the Mandos protocol
1903
1706
            # Get protocol number
1923
1726
            approval_required = False
1924
1727
            try:
1925
1728
                try:
1926
 
                    fpr = self.fingerprint(
1927
 
                        self.peer_certificate(session))
 
1729
                    fpr = self.fingerprint(self.peer_certificate
 
1730
                                           (session))
1928
1731
                except (TypeError,
1929
1732
                        gnutls.errors.GNUTLSError) as error:
1930
1733
                    logger.warning("Bad certificate: %s", error)
1945
1748
                while True:
1946
1749
                    if not client.enabled:
1947
1750
                        logger.info("Client %s is disabled",
1948
 
                                    client.name)
 
1751
                                       client.name)
1949
1752
                        if self.server.use_dbus:
1950
1753
                            # Emit D-Bus signal
1951
1754
                            client.Rejected("Disabled")
1998
1801
                        logger.warning("gnutls send failed",
1999
1802
                                       exc_info=error)
2000
1803
                        return
2001
 
                    logger.debug("Sent: %d, remaining: %d", sent,
2002
 
                                 len(client.secret) - (sent_size
2003
 
                                                       + sent))
 
1804
                    logger.debug("Sent: %d, remaining: %d",
 
1805
                                 sent, len(client.secret)
 
1806
                                 - (sent_size + sent))
2004
1807
                    sent_size += sent
2005
1808
                
2006
1809
                logger.info("Sending secret to %s", client.name)
2023
1826
    def peer_certificate(session):
2024
1827
        "Return the peer's OpenPGP certificate as a bytestring"
2025
1828
        # If not an OpenPGP certificate...
2026
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
2027
 
                session._c_object)
 
1829
        if (gnutls.library.functions
 
1830
            .gnutls_certificate_type_get(session._c_object)
2028
1831
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
2029
1832
            # ...do the normal thing
2030
1833
            return session.peer_certificate
2044
1847
    def fingerprint(openpgp):
2045
1848
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2046
1849
        # New GnuTLS "datum" with the OpenPGP public key
2047
 
        datum = gnutls.library.types.gnutls_datum_t(
2048
 
            ctypes.cast(ctypes.c_char_p(openpgp),
2049
 
                        ctypes.POINTER(ctypes.c_ubyte)),
2050
 
            ctypes.c_uint(len(openpgp)))
 
1850
        datum = (gnutls.library.types
 
1851
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1852
                                             ctypes.POINTER
 
1853
                                             (ctypes.c_ubyte)),
 
1854
                                 ctypes.c_uint(len(openpgp))))
2051
1855
        # New empty GnuTLS certificate
2052
1856
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
2053
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
2054
 
            ctypes.byref(crt))
 
1857
        (gnutls.library.functions
 
1858
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
2055
1859
        # Import the OpenPGP public key into the certificate
2056
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
2057
 
            crt, ctypes.byref(datum),
2058
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
1860
        (gnutls.library.functions
 
1861
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1862
                                    gnutls.library.constants
 
1863
                                    .GNUTLS_OPENPGP_FMT_RAW))
2059
1864
        # Verify the self signature in the key
2060
1865
        crtverify = ctypes.c_uint()
2061
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
2062
 
            crt, 0, ctypes.byref(crtverify))
 
1866
        (gnutls.library.functions
 
1867
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1868
                                         ctypes.byref(crtverify)))
2063
1869
        if crtverify.value != 0:
2064
1870
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2065
 
            raise gnutls.errors.CertificateSecurityError(
2066
 
                "Verify failed")
 
1871
            raise (gnutls.errors.CertificateSecurityError
 
1872
                   ("Verify failed"))
2067
1873
        # New buffer for the fingerprint
2068
1874
        buf = ctypes.create_string_buffer(20)
2069
1875
        buf_len = ctypes.c_size_t()
2070
1876
        # Get the fingerprint from the certificate into the buffer
2071
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
2072
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
1877
        (gnutls.library.functions
 
1878
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1879
                                             ctypes.byref(buf_len)))
2073
1880
        # Deinit the certificate
2074
1881
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2075
1882
        # Convert the buffer to a Python bytestring
2081
1888
 
2082
1889
class MultiprocessingMixIn(object):
2083
1890
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2084
 
    
2085
1891
    def sub_process_main(self, request, address):
2086
1892
        try:
2087
1893
            self.finish_request(request, address)
2099
1905
 
2100
1906
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
2101
1907
    """ adds a pipe to the MixIn """
2102
 
    
2103
1908
    def process_request(self, request, client_address):
2104
1909
        """Overrides and wraps the original process_request().
2105
1910
        
2126
1931
        interface:      None or a network interface name (string)
2127
1932
        use_ipv6:       Boolean; to use IPv6 or not
2128
1933
    """
2129
 
    
2130
1934
    def __init__(self, server_address, RequestHandlerClass,
2131
 
                 interface=None,
2132
 
                 use_ipv6=True,
2133
 
                 socketfd=None):
 
1935
                 interface=None, use_ipv6=True, socketfd=None):
2134
1936
        """If socketfd is set, use that file descriptor instead of
2135
1937
        creating a new one with socket.socket().
2136
1938
        """
2177
1979
                             self.interface)
2178
1980
            else:
2179
1981
                try:
2180
 
                    self.socket.setsockopt(
2181
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
2182
 
                        (self.interface + "\0").encode("utf-8"))
 
1982
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1983
                                           SO_BINDTODEVICE,
 
1984
                                           (self.interface + "\0")
 
1985
                                           .encode("utf-8"))
2183
1986
                except socket.error as error:
2184
1987
                    if error.errno == errno.EPERM:
2185
1988
                        logger.error("No permission to bind to"
2203
2006
                self.server_address = (any_address,
2204
2007
                                       self.server_address[1])
2205
2008
            elif not self.server_address[1]:
2206
 
                self.server_address = (self.server_address[0], 0)
 
2009
                self.server_address = (self.server_address[0],
 
2010
                                       0)
2207
2011
#                 if self.interface:
2208
2012
#                     self.server_address = (self.server_address[0],
2209
2013
#                                            0, # port
2223
2027
    
2224
2028
    Assumes a gobject.MainLoop event loop.
2225
2029
    """
2226
 
    
2227
2030
    def __init__(self, server_address, RequestHandlerClass,
2228
 
                 interface=None,
2229
 
                 use_ipv6=True,
2230
 
                 clients=None,
2231
 
                 gnutls_priority=None,
2232
 
                 use_dbus=True,
2233
 
                 socketfd=None):
 
2031
                 interface=None, use_ipv6=True, clients=None,
 
2032
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2234
2033
        self.enabled = False
2235
2034
        self.clients = clients
2236
2035
        if self.clients is None:
2242
2041
                                interface = interface,
2243
2042
                                use_ipv6 = use_ipv6,
2244
2043
                                socketfd = socketfd)
2245
 
    
2246
2044
    def server_activate(self):
2247
2045
        if self.enabled:
2248
2046
            return socketserver.TCPServer.server_activate(self)
2252
2050
    
2253
2051
    def add_pipe(self, parent_pipe, proc):
2254
2052
        # Call "handle_ipc" for both data and EOF events
2255
 
        gobject.io_add_watch(
2256
 
            parent_pipe.fileno(),
2257
 
            gobject.IO_IN | gobject.IO_HUP,
2258
 
            functools.partial(self.handle_ipc,
2259
 
                              parent_pipe = parent_pipe,
2260
 
                              proc = proc))
 
2053
        gobject.io_add_watch(parent_pipe.fileno(),
 
2054
                             gobject.IO_IN | gobject.IO_HUP,
 
2055
                             functools.partial(self.handle_ipc,
 
2056
                                               parent_pipe =
 
2057
                                               parent_pipe,
 
2058
                                               proc = proc))
2261
2059
    
2262
 
    def handle_ipc(self, source, condition,
2263
 
                   parent_pipe=None,
2264
 
                   proc = None,
2265
 
                   client_object=None):
 
2060
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2061
                   proc = None, client_object=None):
2266
2062
        # error, or the other end of multiprocessing.Pipe has closed
2267
2063
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2268
2064
            # Wait for other process to exit
2291
2087
                parent_pipe.send(False)
2292
2088
                return False
2293
2089
            
2294
 
            gobject.io_add_watch(
2295
 
                parent_pipe.fileno(),
2296
 
                gobject.IO_IN | gobject.IO_HUP,
2297
 
                functools.partial(self.handle_ipc,
2298
 
                                  parent_pipe = parent_pipe,
2299
 
                                  proc = proc,
2300
 
                                  client_object = client))
 
2090
            gobject.io_add_watch(parent_pipe.fileno(),
 
2091
                                 gobject.IO_IN | gobject.IO_HUP,
 
2092
                                 functools.partial(self.handle_ipc,
 
2093
                                                   parent_pipe =
 
2094
                                                   parent_pipe,
 
2095
                                                   proc = proc,
 
2096
                                                   client_object =
 
2097
                                                   client))
2301
2098
            parent_pipe.send(True)
2302
2099
            # remove the old hook in favor of the new above hook on
2303
2100
            # same fileno
2309
2106
            
2310
2107
            parent_pipe.send(('data', getattr(client_object,
2311
2108
                                              funcname)(*args,
2312
 
                                                        **kwargs)))
 
2109
                                                         **kwargs)))
2313
2110
        
2314
2111
        if command == 'getattr':
2315
2112
            attrname = request[1]
2316
 
            if isinstance(client_object.__getattribute__(attrname),
2317
 
                          collections.Callable):
2318
 
                parent_pipe.send(('function', ))
 
2113
            if callable(client_object.__getattribute__(attrname)):
 
2114
                parent_pipe.send(('function',))
2319
2115
            else:
2320
 
                parent_pipe.send((
2321
 
                    'data', client_object.__getattribute__(attrname)))
 
2116
                parent_pipe.send(('data', client_object
 
2117
                                  .__getattribute__(attrname)))
2322
2118
        
2323
2119
        if command == 'setattr':
2324
2120
            attrname = request[1]
2355
2151
    # avoid excessive use of external libraries.
2356
2152
    
2357
2153
    # New type for defining tokens, syntax, and semantics all-in-one
2358
 
    Token = collections.namedtuple("Token", (
2359
 
        "regexp",  # To match token; if "value" is not None, must have
2360
 
                   # a "group" containing digits
2361
 
        "value",   # datetime.timedelta or None
2362
 
        "followers"))           # Tokens valid after this token
 
2154
    Token = collections.namedtuple("Token",
 
2155
                                   ("regexp", # To match token; if
 
2156
                                              # "value" is not None,
 
2157
                                              # must have a "group"
 
2158
                                              # containing digits
 
2159
                                    "value",  # datetime.timedelta or
 
2160
                                              # None
 
2161
                                    "followers")) # Tokens valid after
 
2162
                                                  # this token
2363
2163
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2364
2164
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2365
2165
    token_end = Token(re.compile(r"$"), None, frozenset())
2366
2166
    token_second = Token(re.compile(r"(\d+)S"),
2367
2167
                         datetime.timedelta(seconds=1),
2368
 
                         frozenset((token_end, )))
 
2168
                         frozenset((token_end,)))
2369
2169
    token_minute = Token(re.compile(r"(\d+)M"),
2370
2170
                         datetime.timedelta(minutes=1),
2371
2171
                         frozenset((token_second, token_end)))
2387
2187
                       frozenset((token_month, token_end)))
2388
2188
    token_week = Token(re.compile(r"(\d+)W"),
2389
2189
                       datetime.timedelta(weeks=1),
2390
 
                       frozenset((token_end, )))
 
2190
                       frozenset((token_end,)))
2391
2191
    token_duration = Token(re.compile(r"P"), None,
2392
2192
                           frozenset((token_year, token_month,
2393
2193
                                      token_day, token_time,
2395
2195
    # Define starting values
2396
2196
    value = datetime.timedelta() # Value so far
2397
2197
    found_token = None
2398
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2198
    followers = frozenset((token_duration,)) # Following valid tokens
2399
2199
    s = duration                # String left to parse
2400
2200
    # Loop until end token is found
2401
2201
    while found_token is not token_end:
2418
2218
                break
2419
2219
        else:
2420
2220
            # No currently valid tokens were found
2421
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2422
 
                             .format(duration))
 
2221
            raise ValueError("Invalid RFC 3339 duration")
2423
2222
    # End token found
2424
2223
    return value
2425
2224
 
2462
2261
            elif suffix == "w":
2463
2262
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2464
2263
            else:
2465
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2264
                raise ValueError("Unknown suffix {!r}"
 
2265
                                 .format(suffix))
2466
2266
        except IndexError as e:
2467
2267
            raise ValueError(*(e.args))
2468
2268
        timevalue += delta
2484
2284
        # Close all standard open file descriptors
2485
2285
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2486
2286
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2487
 
            raise OSError(errno.ENODEV,
2488
 
                          "{} not a character device"
 
2287
            raise OSError(errno.ENODEV, "{} not a character device"
2489
2288
                          .format(os.devnull))
2490
2289
        os.dup2(null, sys.stdin.fileno())
2491
2290
        os.dup2(null, sys.stdout.fileno())
2558
2357
                        "debug": "False",
2559
2358
                        "priority":
2560
2359
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2561
 
                        ":+SIGN-DSA-SHA256",
 
2360
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2562
2361
                        "servicename": "Mandos",
2563
2362
                        "use_dbus": "True",
2564
2363
                        "use_ipv6": "True",
2568
2367
                        "statedir": "/var/lib/mandos",
2569
2368
                        "foreground": "False",
2570
2369
                        "zeroconf": "True",
2571
 
                    }
 
2370
                        }
2572
2371
    
2573
2372
    # Parse config file for server-global settings
2574
2373
    server_config = configparser.SafeConfigParser(server_defaults)
2575
2374
    del server_defaults
2576
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2375
    server_config.read(os.path.join(options.configdir,
 
2376
                                    "mandos.conf"))
2577
2377
    # Convert the SafeConfigParser object to a dict
2578
2378
    server_settings = server_config.defaults()
2579
2379
    # Use the appropriate methods on the non-string config options
2597
2397
    # Override the settings from the config file with command line
2598
2398
    # options, if set.
2599
2399
    for option in ("interface", "address", "port", "debug",
2600
 
                   "priority", "servicename", "configdir", "use_dbus",
2601
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2602
 
                   "socket", "foreground", "zeroconf"):
 
2400
                   "priority", "servicename", "configdir",
 
2401
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2402
                   "statedir", "socket", "foreground", "zeroconf"):
2603
2403
        value = getattr(options, option)
2604
2404
        if value is not None:
2605
2405
            server_settings[option] = value
2620
2420
    
2621
2421
    ##################################################################
2622
2422
    
2623
 
    if (not server_settings["zeroconf"]
2624
 
        and not (server_settings["port"]
2625
 
                 or server_settings["socket"] != "")):
2626
 
        parser.error("Needs port or socket to work without Zeroconf")
 
2423
    if (not server_settings["zeroconf"] and
 
2424
        not (server_settings["port"]
 
2425
             or server_settings["socket"] != "")):
 
2426
            parser.error("Needs port or socket to work without"
 
2427
                         " Zeroconf")
2627
2428
    
2628
2429
    # For convenience
2629
2430
    debug = server_settings["debug"]
2645
2446
            initlogger(debug, level)
2646
2447
    
2647
2448
    if server_settings["servicename"] != "Mandos":
2648
 
        syslogger.setFormatter(
2649
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2650
 
                              ' %(levelname)s: %(message)s'.format(
2651
 
                                  server_settings["servicename"])))
 
2449
        syslogger.setFormatter(logging.Formatter
 
2450
                               ('Mandos ({}) [%(process)d]:'
 
2451
                                ' %(levelname)s: %(message)s'
 
2452
                                .format(server_settings
 
2453
                                        ["servicename"])))
2652
2454
    
2653
2455
    # Parse config file with clients
2654
2456
    client_config = configparser.SafeConfigParser(Client
2662
2464
    socketfd = None
2663
2465
    if server_settings["socket"] != "":
2664
2466
        socketfd = server_settings["socket"]
2665
 
    tcp_server = MandosServer(
2666
 
        (server_settings["address"], server_settings["port"]),
2667
 
        ClientHandler,
2668
 
        interface=(server_settings["interface"] or None),
2669
 
        use_ipv6=use_ipv6,
2670
 
        gnutls_priority=server_settings["priority"],
2671
 
        use_dbus=use_dbus,
2672
 
        socketfd=socketfd)
 
2467
    tcp_server = MandosServer((server_settings["address"],
 
2468
                               server_settings["port"]),
 
2469
                              ClientHandler,
 
2470
                              interface=(server_settings["interface"]
 
2471
                                         or None),
 
2472
                              use_ipv6=use_ipv6,
 
2473
                              gnutls_priority=
 
2474
                              server_settings["priority"],
 
2475
                              use_dbus=use_dbus,
 
2476
                              socketfd=socketfd)
2673
2477
    if not foreground:
2674
2478
        pidfilename = "/run/mandos.pid"
2675
2479
        if not os.path.isdir("/run/."):
2676
2480
            pidfilename = "/var/run/mandos.pid"
2677
2481
        pidfile = None
2678
2482
        try:
2679
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2483
            pidfile = open(pidfilename, "w")
2680
2484
        except IOError as e:
2681
2485
            logger.error("Could not open file %r", pidfilename,
2682
2486
                         exc_info=e)
2709
2513
        def debug_gnutls(level, string):
2710
2514
            logger.debug("GnuTLS: %s", string[:-1])
2711
2515
        
2712
 
        gnutls.library.functions.gnutls_global_set_log_function(
2713
 
            debug_gnutls)
 
2516
        (gnutls.library.functions
 
2517
         .gnutls_global_set_log_function(debug_gnutls))
2714
2518
        
2715
2519
        # Redirect stdin so all checkers get /dev/null
2716
2520
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2736
2540
    if use_dbus:
2737
2541
        try:
2738
2542
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2739
 
                                            bus,
2740
 
                                            do_not_queue=True)
2741
 
            old_bus_name = dbus.service.BusName(
2742
 
                "se.bsnet.fukt.Mandos", bus,
2743
 
                do_not_queue=True)
2744
 
        except dbus.exceptions.DBusException as e:
 
2543
                                            bus, do_not_queue=True)
 
2544
            old_bus_name = (dbus.service.BusName
 
2545
                            ("se.bsnet.fukt.Mandos", bus,
 
2546
                             do_not_queue=True))
 
2547
        except dbus.exceptions.NameExistsException as e:
2745
2548
            logger.error("Disabling D-Bus:", exc_info=e)
2746
2549
            use_dbus = False
2747
2550
            server_settings["use_dbus"] = False
2748
2551
            tcp_server.use_dbus = False
2749
2552
    if zeroconf:
2750
2553
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2751
 
        service = AvahiServiceToSyslog(
2752
 
            name = server_settings["servicename"],
2753
 
            servicetype = "_mandos._tcp",
2754
 
            protocol = protocol,
2755
 
            bus = bus)
 
2554
        service = AvahiServiceToSyslog(name =
 
2555
                                       server_settings["servicename"],
 
2556
                                       servicetype = "_mandos._tcp",
 
2557
                                       protocol = protocol, bus = bus)
2756
2558
        if server_settings["interface"]:
2757
 
            service.interface = if_nametoindex(
2758
 
                server_settings["interface"].encode("utf-8"))
 
2559
            service.interface = (if_nametoindex
 
2560
                                 (server_settings["interface"]
 
2561
                                  .encode("utf-8")))
2759
2562
    
2760
2563
    global multiprocessing_manager
2761
2564
    multiprocessing_manager = multiprocessing.Manager()
2780
2583
    if server_settings["restore"]:
2781
2584
        try:
2782
2585
            with open(stored_state_path, "rb") as stored_state:
2783
 
                clients_data, old_client_settings = pickle.load(
2784
 
                    stored_state)
 
2586
                clients_data, old_client_settings = (pickle.load
 
2587
                                                     (stored_state))
2785
2588
            os.remove(stored_state_path)
2786
2589
        except IOError as e:
2787
2590
            if e.errno == errno.ENOENT:
2788
 
                logger.warning("Could not load persistent state:"
2789
 
                               " {}".format(os.strerror(e.errno)))
 
2591
                logger.warning("Could not load persistent state: {}"
 
2592
                                .format(os.strerror(e.errno)))
2790
2593
            else:
2791
2594
                logger.critical("Could not load persistent state:",
2792
2595
                                exc_info=e)
2793
2596
                raise
2794
2597
        except EOFError as e:
2795
2598
            logger.warning("Could not load persistent state: "
2796
 
                           "EOFError:",
2797
 
                           exc_info=e)
 
2599
                           "EOFError:", exc_info=e)
2798
2600
    
2799
2601
    with PGPEngine() as pgp:
2800
2602
        for client_name, client in clients_data.items():
2812
2614
                    # For each value in new config, check if it
2813
2615
                    # differs from the old config value (Except for
2814
2616
                    # the "secret" attribute)
2815
 
                    if (name != "secret"
2816
 
                        and (value !=
2817
 
                             old_client_settings[client_name][name])):
 
2617
                    if (name != "secret" and
 
2618
                        value != old_client_settings[client_name]
 
2619
                        [name]):
2818
2620
                        client[name] = value
2819
2621
                except KeyError:
2820
2622
                    pass
2821
2623
            
2822
2624
            # Clients who has passed its expire date can still be
2823
 
            # enabled if its last checker was successful.  A Client
 
2625
            # enabled if its last checker was successful.  Clients
2824
2626
            # whose checker succeeded before we stored its state is
2825
2627
            # assumed to have successfully run all checkers during
2826
2628
            # downtime.
2829
2631
                    if not client["last_checked_ok"]:
2830
2632
                        logger.warning(
2831
2633
                            "disabling client {} - Client never "
2832
 
                            "performed a successful checker".format(
2833
 
                                client_name))
 
2634
                            "performed a successful checker"
 
2635
                            .format(client_name))
2834
2636
                        client["enabled"] = False
2835
2637
                    elif client["last_checker_status"] != 0:
2836
2638
                        logger.warning(
2837
2639
                            "disabling client {} - Client last"
2838
 
                            " checker failed with error code"
2839
 
                            " {}".format(
2840
 
                                client_name,
2841
 
                                client["last_checker_status"]))
 
2640
                            " checker failed with error code {}"
 
2641
                            .format(client_name,
 
2642
                                    client["last_checker_status"]))
2842
2643
                        client["enabled"] = False
2843
2644
                    else:
2844
 
                        client["expires"] = (
2845
 
                            datetime.datetime.utcnow()
2846
 
                            + client["timeout"])
 
2645
                        client["expires"] = (datetime.datetime
 
2646
                                             .utcnow()
 
2647
                                             + client["timeout"])
2847
2648
                        logger.debug("Last checker succeeded,"
2848
 
                                     " keeping {} enabled".format(
2849
 
                                         client_name))
 
2649
                                     " keeping {} enabled"
 
2650
                                     .format(client_name))
2850
2651
            try:
2851
 
                client["secret"] = pgp.decrypt(
2852
 
                    client["encrypted_secret"],
2853
 
                    client_settings[client_name]["secret"])
 
2652
                client["secret"] = (
 
2653
                    pgp.decrypt(client["encrypted_secret"],
 
2654
                                client_settings[client_name]
 
2655
                                ["secret"]))
2854
2656
            except PGPError:
2855
2657
                # If decryption fails, we use secret from new settings
2856
 
                logger.debug("Failed to decrypt {} old secret".format(
2857
 
                    client_name))
2858
 
                client["secret"] = (client_settings[client_name]
2859
 
                                    ["secret"])
 
2658
                logger.debug("Failed to decrypt {} old secret"
 
2659
                             .format(client_name))
 
2660
                client["secret"] = (
 
2661
                    client_settings[client_name]["secret"])
2860
2662
    
2861
2663
    # Add/remove clients based on new changes made to config
2862
2664
    for client_name in (set(old_client_settings)
2869
2671
    # Create all client objects
2870
2672
    for client_name, client in clients_data.items():
2871
2673
        tcp_server.clients[client_name] = client_class(
2872
 
            name = client_name,
2873
 
            settings = client,
 
2674
            name = client_name, settings = client,
2874
2675
            server_settings = server_settings)
2875
2676
    
2876
2677
    if not tcp_server.clients:
2878
2679
    
2879
2680
    if not foreground:
2880
2681
        if pidfile is not None:
2881
 
            pid = os.getpid()
2882
2682
            try:
2883
2683
                with pidfile:
2884
 
                    print(pid, file=pidfile)
 
2684
                    pid = os.getpid()
 
2685
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2885
2686
            except IOError:
2886
2687
                logger.error("Could not write to file %r with PID %d",
2887
2688
                             pidfilename, pid)
2892
2693
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2893
2694
    
2894
2695
    if use_dbus:
2895
 
        
2896
 
        @alternate_dbus_interfaces(
2897
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2898
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2696
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2697
                                        "se.bsnet.fukt.Mandos"})
 
2698
        class MandosDBusService(DBusObjectWithProperties):
2899
2699
            """A D-Bus proxy object"""
2900
 
            
2901
2700
            def __init__(self):
2902
2701
                dbus.service.Object.__init__(self, bus, "/")
2903
 
            
2904
2702
            _interface = "se.recompile.Mandos"
2905
2703
            
 
2704
            @dbus_interface_annotations(_interface)
 
2705
            def _foo(self):
 
2706
                return { "org.freedesktop.DBus.Property"
 
2707
                         ".EmitsChangedSignal":
 
2708
                             "false"}
 
2709
            
2906
2710
            @dbus.service.signal(_interface, signature="o")
2907
2711
            def ClientAdded(self, objpath):
2908
2712
                "D-Bus signal"
2913
2717
                "D-Bus signal"
2914
2718
                pass
2915
2719
            
2916
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2917
 
                               "true"})
2918
2720
            @dbus.service.signal(_interface, signature="os")
2919
2721
            def ClientRemoved(self, objpath, name):
2920
2722
                "D-Bus signal"
2921
2723
                pass
2922
2724
            
2923
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2924
 
                               "true"})
2925
2725
            @dbus.service.method(_interface, out_signature="ao")
2926
2726
            def GetAllClients(self):
2927
2727
                "D-Bus method"
2928
 
                return dbus.Array(c.dbus_object_path for c in
 
2728
                return dbus.Array(c.dbus_object_path
 
2729
                                  for c in
2929
2730
                                  tcp_server.clients.itervalues())
2930
2731
            
2931
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
2932
 
                               "true"})
2933
2732
            @dbus.service.method(_interface,
2934
2733
                                 out_signature="a{oa{sv}}")
2935
2734
            def GetAllClientsWithProperties(self):
2936
2735
                "D-Bus method"
2937
2736
                return dbus.Dictionary(
2938
 
                    { c.dbus_object_path: c.GetAll(
2939
 
                        "se.recompile.Mandos.Client")
 
2737
                    { c.dbus_object_path: c.GetAll("")
2940
2738
                      for c in tcp_server.clients.itervalues() },
2941
2739
                    signature="oa{sv}")
2942
2740
            
2947
2745
                    if c.dbus_object_path == object_path:
2948
2746
                        del tcp_server.clients[c.name]
2949
2747
                        c.remove_from_connection()
2950
 
                        # Don't signal the disabling
 
2748
                        # Don't signal anything except ClientRemoved
2951
2749
                        c.disable(quiet=True)
2952
 
                        # Emit D-Bus signal for removal
2953
 
                        self.client_removed_signal(c)
 
2750
                        # Emit D-Bus signal
 
2751
                        self.ClientRemoved(object_path, c.name)
2954
2752
                        return
2955
2753
                raise KeyError(object_path)
2956
2754
            
2957
2755
            del _interface
2958
 
            
2959
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
2960
 
                                 out_signature = "a{oa{sa{sv}}}")
2961
 
            def GetManagedObjects(self):
2962
 
                """D-Bus method"""
2963
 
                return dbus.Dictionary(
2964
 
                    { client.dbus_object_path:
2965
 
                      dbus.Dictionary(
2966
 
                          { interface: client.GetAll(interface)
2967
 
                            for interface in
2968
 
                                 client._get_all_interface_names()})
2969
 
                      for client in tcp_server.clients.values()})
2970
 
            
2971
 
            def client_added_signal(self, client):
2972
 
                """Send the new standard signal and the old signal"""
2973
 
                if use_dbus:
2974
 
                    # New standard signal
2975
 
                    self.InterfacesAdded(
2976
 
                        client.dbus_object_path,
2977
 
                        dbus.Dictionary(
2978
 
                            { interface: client.GetAll(interface)
2979
 
                              for interface in
2980
 
                              client._get_all_interface_names()}))
2981
 
                    # Old signal
2982
 
                    self.ClientAdded(client.dbus_object_path)
2983
 
            
2984
 
            def client_removed_signal(self, client):
2985
 
                """Send the new standard signal and the old signal"""
2986
 
                if use_dbus:
2987
 
                    # New standard signal
2988
 
                    self.InterfacesRemoved(
2989
 
                        client.dbus_object_path,
2990
 
                        client._get_all_interface_names())
2991
 
                    # Old signal
2992
 
                    self.ClientRemoved(client.dbus_object_path,
2993
 
                                       client.name)
2994
2756
        
2995
2757
        mandos_dbus_service = MandosDBusService()
2996
2758
    
3019
2781
                # + secret.
3020
2782
                exclude = { "bus", "changedstate", "secret",
3021
2783
                            "checker", "server_settings" }
3022
 
                for name, typ in inspect.getmembers(dbus.service
3023
 
                                                    .Object):
 
2784
                for name, typ in (inspect.getmembers
 
2785
                                  (dbus.service.Object)):
3024
2786
                    exclude.add(name)
3025
2787
                
3026
2788
                client_dict["encrypted_secret"] = (client
3033
2795
                del client_settings[client.name]["secret"]
3034
2796
        
3035
2797
        try:
3036
 
            with tempfile.NamedTemporaryFile(
3037
 
                    mode='wb',
3038
 
                    suffix=".pickle",
3039
 
                    prefix='clients-',
3040
 
                    dir=os.path.dirname(stored_state_path),
3041
 
                    delete=False) as stored_state:
 
2798
            with (tempfile.NamedTemporaryFile
 
2799
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2800
                   dir=os.path.dirname(stored_state_path),
 
2801
                   delete=False)) as stored_state:
3042
2802
                pickle.dump((clients, client_settings), stored_state)
3043
 
                tempname = stored_state.name
 
2803
                tempname=stored_state.name
3044
2804
            os.rename(tempname, stored_state_path)
3045
2805
        except (IOError, OSError) as e:
3046
2806
            if not debug:
3061
2821
            name, client = tcp_server.clients.popitem()
3062
2822
            if use_dbus:
3063
2823
                client.remove_from_connection()
3064
 
            # Don't signal the disabling
 
2824
            # Don't signal anything except ClientRemoved
3065
2825
            client.disable(quiet=True)
3066
 
            # Emit D-Bus signal for removal
3067
 
            mandos_dbus_service.client_removed_signal(client)
 
2826
            if use_dbus:
 
2827
                # Emit D-Bus signal
 
2828
                mandos_dbus_service.ClientRemoved(client
 
2829
                                                  .dbus_object_path,
 
2830
                                                  client.name)
3068
2831
        client_settings.clear()
3069
2832
    
3070
2833
    atexit.register(cleanup)
3071
2834
    
3072
2835
    for client in tcp_server.clients.itervalues():
3073
2836
        if use_dbus:
3074
 
            # Emit D-Bus signal for adding
3075
 
            mandos_dbus_service.client_added_signal(client)
 
2837
            # Emit D-Bus signal
 
2838
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3076
2839
        # Need to initiate checking of clients
3077
2840
        if client.enabled:
3078
2841
            client.init_checker()
3123
2886
    # Must run before the D-Bus bus name gets deregistered
3124
2887
    cleanup()
3125
2888
 
3126
 
 
3127
2889
if __name__ == '__main__':
3128
2890
    main()