/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2014-10-08 21:07:10 UTC
  • Revision ID: teddy@recompile.se-20141008210710-x0rg80z2aabdg05d
Handle local Zeroconf service name collisions.

Service name collisions from other servers have always been handled,
but not *local* name collisions from services on the same host.

* mandos (AvahiService/rename): Handle local Zeroconf service name
                                collision.
  (AvahiServiceToSyslog.rename): Pass on any extra arguments.

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