/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2015-05-23 12:07:07 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • Revision ID: teddy@recompile.se-20150523120707-t5fq0brh2kxkvw8g
mandos: Some more minor changes to prepare for Python 3.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
 
1
#!/usr/bin/python2.7
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2016 Teddy Hogeborn
15
 
# Copyright © 2008-2016 Björn Påhlsson
 
14
# Copyright © 2008-2015 Teddy Hogeborn
 
15
# Copyright © 2008-2015 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
34
34
from __future__ import (division, absolute_import, print_function,
35
35
                        unicode_literals)
36
36
 
37
 
try:
38
 
    from future_builtins import *
39
 
except ImportError:
40
 
    pass
 
37
from future_builtins import *
41
38
 
42
39
try:
43
40
    import SocketServer as socketserver
47
44
import argparse
48
45
import datetime
49
46
import errno
 
47
import gnutls.crypto
 
48
import gnutls.connection
 
49
import gnutls.errors
 
50
import gnutls.library.functions
 
51
import gnutls.library.constants
 
52
import gnutls.library.types
50
53
try:
51
54
    import ConfigParser as configparser
52
55
except ImportError:
75
78
import tempfile
76
79
import itertools
77
80
import collections
78
 
import codecs
79
81
 
80
82
import dbus
81
83
import dbus.service
82
 
from gi.repository import GLib
 
84
try:
 
85
    import gobject
 
86
except ImportError:
 
87
    from gi.repository import GObject as gobject
 
88
import avahi
83
89
from dbus.mainloop.glib import DBusGMainLoop
84
90
import ctypes
85
91
import ctypes.util
97
103
if sys.version_info.major == 2:
98
104
    str = unicode
99
105
 
100
 
version = "1.7.7"
 
106
version = "1.6.9"
101
107
stored_state_file = "clients.pickle"
102
108
 
103
109
logger = logging.getLogger()
118
124
        return interface_index
119
125
 
120
126
 
121
 
def copy_function(func):
122
 
    """Make a copy of a function"""
123
 
    if sys.version_info.major == 2:
124
 
        return types.FunctionType(func.func_code,
125
 
                                  func.func_globals,
126
 
                                  func.func_name,
127
 
                                  func.func_defaults,
128
 
                                  func.func_closure)
129
 
    else:
130
 
        return types.FunctionType(func.__code__,
131
 
                                  func.__globals__,
132
 
                                  func.__name__,
133
 
                                  func.__defaults__,
134
 
                                  func.__closure__)
135
 
 
136
 
 
137
127
def initlogger(debug, level=logging.WARNING):
138
128
    """init logger and add loglevel"""
139
129
    
166
156
    
167
157
    def __init__(self):
168
158
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
169
 
        self.gpg = "gpg"
170
 
        try:
171
 
            output = subprocess.check_output(["gpgconf"])
172
 
            for line in output.splitlines():
173
 
                name, text, path = line.split(b":")
174
 
                if name == "gpg":
175
 
                    self.gpg = path
176
 
                    break
177
 
        except OSError as e:
178
 
            if e.errno != errno.ENOENT:
179
 
                raise
180
159
        self.gnupgargs = ['--batch',
181
 
                          '--homedir', self.tempdir,
 
160
                          '--home', self.tempdir,
182
161
                          '--force-mdc',
183
 
                          '--quiet']
184
 
        # Only GPG version 1 has the --no-use-agent option.
185
 
        if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
186
 
            self.gnupgargs.append("--no-use-agent")
 
162
                          '--quiet',
 
163
                          '--no-use-agent']
187
164
    
188
165
    def __enter__(self):
189
166
        return self
225
202
                dir=self.tempdir) as passfile:
226
203
            passfile.write(passphrase)
227
204
            passfile.flush()
228
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
 
205
            proc = subprocess.Popen(['gpg', '--symmetric',
229
206
                                     '--passphrase-file',
230
207
                                     passfile.name]
231
208
                                    + self.gnupgargs,
243
220
                dir = self.tempdir) as passfile:
244
221
            passfile.write(passphrase)
245
222
            passfile.flush()
246
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
 
223
            proc = subprocess.Popen(['gpg', '--decrypt',
247
224
                                     '--passphrase-file',
248
225
                                     passfile.name]
249
226
                                    + self.gnupgargs,
255
232
            raise PGPError(err)
256
233
        return decrypted_plaintext
257
234
 
258
 
# Pretend that we have an Avahi module
259
 
class Avahi(object):
260
 
    """This isn't so much a class as it is a module-like namespace.
261
 
    It is instantiated once, and simulates having an Avahi module."""
262
 
    IF_UNSPEC = -1              # avahi-common/address.h
263
 
    PROTO_UNSPEC = -1           # avahi-common/address.h
264
 
    PROTO_INET = 0              # avahi-common/address.h
265
 
    PROTO_INET6 = 1             # avahi-common/address.h
266
 
    DBUS_NAME = "org.freedesktop.Avahi"
267
 
    DBUS_INTERFACE_ENTRY_GROUP = DBUS_NAME + ".EntryGroup"
268
 
    DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
269
 
    DBUS_PATH_SERVER = "/"
270
 
    def string_array_to_txt_array(self, t):
271
 
        return dbus.Array((dbus.ByteArray(s.encode("utf-8"))
272
 
                           for s in t), signature="ay")
273
 
    ENTRY_GROUP_ESTABLISHED = 2 # avahi-common/defs.h
274
 
    ENTRY_GROUP_COLLISION = 3   # avahi-common/defs.h
275
 
    ENTRY_GROUP_FAILURE = 4     # avahi-common/defs.h
276
 
    SERVER_INVALID = 0          # avahi-common/defs.h
277
 
    SERVER_REGISTERING = 1      # avahi-common/defs.h
278
 
    SERVER_RUNNING = 2          # avahi-common/defs.h
279
 
    SERVER_COLLISION = 3        # avahi-common/defs.h
280
 
    SERVER_FAILURE = 4          # avahi-common/defs.h
281
 
avahi = Avahi()
282
235
 
283
236
class AvahiError(Exception):
284
237
    def __init__(self, value, *args, **kwargs):
441
394
                    logger.error(bad_states[state] + ": %r", error)
442
395
            self.cleanup()
443
396
        elif state == avahi.SERVER_RUNNING:
444
 
            try:
445
 
                self.add()
446
 
            except dbus.exceptions.DBusException as error:
447
 
                if (error.get_dbus_name()
448
 
                    == "org.freedesktop.Avahi.CollisionError"):
449
 
                    logger.info("Local Zeroconf service name"
450
 
                                " collision.")
451
 
                    return self.rename(remove=False)
452
 
                else:
453
 
                    logger.critical("D-Bus Exception", exc_info=error)
454
 
                    self.cleanup()
455
 
                    os._exit(1)
 
397
            self.add()
456
398
        else:
457
399
            if error is None:
458
400
                logger.debug("Unknown state: %r", state)
481
423
            .format(self.name)))
482
424
        return ret
483
425
 
484
 
# Pretend that we have a GnuTLS module
485
 
class GnuTLS(object):
486
 
    """This isn't so much a class as it is a module-like namespace.
487
 
    It is instantiated once, and simulates having a GnuTLS module."""
488
 
    
489
 
    _library = ctypes.cdll.LoadLibrary(
490
 
        ctypes.util.find_library("gnutls"))
491
 
    _need_version = b"3.3.0"
492
 
    def __init__(self):
493
 
        # Need to use class name "GnuTLS" here, since this method is
494
 
        # called before the assignment to the "gnutls" global variable
495
 
        # happens.
496
 
        if GnuTLS.check_version(self._need_version) is None:
497
 
            raise GnuTLS.Error("Needs GnuTLS {} or later"
498
 
                               .format(self._need_version))
499
 
    
500
 
    # Unless otherwise indicated, the constants and types below are
501
 
    # all from the gnutls/gnutls.h C header file.
502
 
    
503
 
    # Constants
504
 
    E_SUCCESS = 0
505
 
    E_INTERRUPTED = -52
506
 
    E_AGAIN = -28
507
 
    CRT_OPENPGP = 2
508
 
    CLIENT = 2
509
 
    SHUT_RDWR = 0
510
 
    CRD_CERTIFICATE = 1
511
 
    E_NO_CERTIFICATE_FOUND = -49
512
 
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
513
 
    
514
 
    # Types
515
 
    class session_int(ctypes.Structure):
516
 
        _fields_ = []
517
 
    session_t = ctypes.POINTER(session_int)
518
 
    class certificate_credentials_st(ctypes.Structure):
519
 
        _fields_ = []
520
 
    certificate_credentials_t = ctypes.POINTER(
521
 
        certificate_credentials_st)
522
 
    certificate_type_t = ctypes.c_int
523
 
    class datum_t(ctypes.Structure):
524
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
525
 
                    ('size', ctypes.c_uint)]
526
 
    class openpgp_crt_int(ctypes.Structure):
527
 
        _fields_ = []
528
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
529
 
    openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
530
 
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
531
 
    credentials_type_t = ctypes.c_int
532
 
    transport_ptr_t = ctypes.c_void_p
533
 
    close_request_t = ctypes.c_int
534
 
    
535
 
    # Exceptions
536
 
    class Error(Exception):
537
 
        # We need to use the class name "GnuTLS" here, since this
538
 
        # exception might be raised from within GnuTLS.__init__,
539
 
        # which is called before the assignment to the "gnutls"
540
 
        # global variable has happened.
541
 
        def __init__(self, message = None, code = None, args=()):
542
 
            # Default usage is by a message string, but if a return
543
 
            # code is passed, convert it to a string with
544
 
            # gnutls.strerror()
545
 
            self.code = code
546
 
            if message is None and code is not None:
547
 
                message = GnuTLS.strerror(code)
548
 
            return super(GnuTLS.Error, self).__init__(
549
 
                message, *args)
550
 
    
551
 
    class CertificateSecurityError(Error):
552
 
        pass
553
 
    
554
 
    # Classes
555
 
    class Credentials(object):
556
 
        def __init__(self):
557
 
            self._c_object = gnutls.certificate_credentials_t()
558
 
            gnutls.certificate_allocate_credentials(
559
 
                ctypes.byref(self._c_object))
560
 
            self.type = gnutls.CRD_CERTIFICATE
561
 
        
562
 
        def __del__(self):
563
 
            gnutls.certificate_free_credentials(self._c_object)
564
 
    
565
 
    class ClientSession(object):
566
 
        def __init__(self, socket, credentials = None):
567
 
            self._c_object = gnutls.session_t()
568
 
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
569
 
            gnutls.set_default_priority(self._c_object)
570
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
571
 
            gnutls.handshake_set_private_extensions(self._c_object,
572
 
                                                    True)
573
 
            self.socket = socket
574
 
            if credentials is None:
575
 
                credentials = gnutls.Credentials()
576
 
            gnutls.credentials_set(self._c_object, credentials.type,
577
 
                                   ctypes.cast(credentials._c_object,
578
 
                                               ctypes.c_void_p))
579
 
            self.credentials = credentials
580
 
        
581
 
        def __del__(self):
582
 
            gnutls.deinit(self._c_object)
583
 
        
584
 
        def handshake(self):
585
 
            return gnutls.handshake(self._c_object)
586
 
        
587
 
        def send(self, data):
588
 
            data = bytes(data)
589
 
            data_len = len(data)
590
 
            while data_len > 0:
591
 
                data_len -= gnutls.record_send(self._c_object,
592
 
                                               data[-data_len:],
593
 
                                               data_len)
594
 
        
595
 
        def bye(self):
596
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
597
 
    
598
 
    # Error handling functions
599
 
    def _error_code(result):
600
 
        """A function to raise exceptions on errors, suitable
601
 
        for the 'restype' attribute on ctypes functions"""
602
 
        if result >= 0:
603
 
            return result
604
 
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
605
 
            raise gnutls.CertificateSecurityError(code = result)
606
 
        raise gnutls.Error(code = result)
607
 
    
608
 
    def _retry_on_error(result, func, arguments):
609
 
        """A function to retry on some errors, suitable
610
 
        for the 'errcheck' attribute on ctypes functions"""
611
 
        while result < 0:
612
 
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
613
 
                return _error_code(result)
614
 
            result = func(*arguments)
615
 
        return result
616
 
    
617
 
    # Unless otherwise indicated, the function declarations below are
618
 
    # all from the gnutls/gnutls.h C header file.
619
 
    
620
 
    # Functions
621
 
    priority_set_direct = _library.gnutls_priority_set_direct
622
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
623
 
                                    ctypes.POINTER(ctypes.c_char_p)]
624
 
    priority_set_direct.restype = _error_code
625
 
    
626
 
    init = _library.gnutls_init
627
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
628
 
    init.restype = _error_code
629
 
    
630
 
    set_default_priority = _library.gnutls_set_default_priority
631
 
    set_default_priority.argtypes = [session_t]
632
 
    set_default_priority.restype = _error_code
633
 
    
634
 
    record_send = _library.gnutls_record_send
635
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
636
 
                            ctypes.c_size_t]
637
 
    record_send.restype = ctypes.c_ssize_t
638
 
    record_send.errcheck = _retry_on_error
639
 
    
640
 
    certificate_allocate_credentials = (
641
 
        _library.gnutls_certificate_allocate_credentials)
642
 
    certificate_allocate_credentials.argtypes = [
643
 
        ctypes.POINTER(certificate_credentials_t)]
644
 
    certificate_allocate_credentials.restype = _error_code
645
 
    
646
 
    certificate_free_credentials = (
647
 
        _library.gnutls_certificate_free_credentials)
648
 
    certificate_free_credentials.argtypes = [certificate_credentials_t]
649
 
    certificate_free_credentials.restype = None
650
 
    
651
 
    handshake_set_private_extensions = (
652
 
        _library.gnutls_handshake_set_private_extensions)
653
 
    handshake_set_private_extensions.argtypes = [session_t,
654
 
                                                 ctypes.c_int]
655
 
    handshake_set_private_extensions.restype = None
656
 
    
657
 
    credentials_set = _library.gnutls_credentials_set
658
 
    credentials_set.argtypes = [session_t, credentials_type_t,
659
 
                                ctypes.c_void_p]
660
 
    credentials_set.restype = _error_code
661
 
    
662
 
    strerror = _library.gnutls_strerror
663
 
    strerror.argtypes = [ctypes.c_int]
664
 
    strerror.restype = ctypes.c_char_p
665
 
    
666
 
    certificate_type_get = _library.gnutls_certificate_type_get
667
 
    certificate_type_get.argtypes = [session_t]
668
 
    certificate_type_get.restype = _error_code
669
 
    
670
 
    certificate_get_peers = _library.gnutls_certificate_get_peers
671
 
    certificate_get_peers.argtypes = [session_t,
672
 
                                      ctypes.POINTER(ctypes.c_uint)]
673
 
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
674
 
    
675
 
    global_set_log_level = _library.gnutls_global_set_log_level
676
 
    global_set_log_level.argtypes = [ctypes.c_int]
677
 
    global_set_log_level.restype = None
678
 
    
679
 
    global_set_log_function = _library.gnutls_global_set_log_function
680
 
    global_set_log_function.argtypes = [log_func]
681
 
    global_set_log_function.restype = None
682
 
    
683
 
    deinit = _library.gnutls_deinit
684
 
    deinit.argtypes = [session_t]
685
 
    deinit.restype = None
686
 
    
687
 
    handshake = _library.gnutls_handshake
688
 
    handshake.argtypes = [session_t]
689
 
    handshake.restype = _error_code
690
 
    handshake.errcheck = _retry_on_error
691
 
    
692
 
    transport_set_ptr = _library.gnutls_transport_set_ptr
693
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
694
 
    transport_set_ptr.restype = None
695
 
    
696
 
    bye = _library.gnutls_bye
697
 
    bye.argtypes = [session_t, close_request_t]
698
 
    bye.restype = _error_code
699
 
    bye.errcheck = _retry_on_error
700
 
    
701
 
    check_version = _library.gnutls_check_version
702
 
    check_version.argtypes = [ctypes.c_char_p]
703
 
    check_version.restype = ctypes.c_char_p
704
 
    
705
 
    # All the function declarations below are from gnutls/openpgp.h
706
 
    
707
 
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
708
 
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
709
 
    openpgp_crt_init.restype = _error_code
710
 
    
711
 
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
712
 
    openpgp_crt_import.argtypes = [openpgp_crt_t,
713
 
                                   ctypes.POINTER(datum_t),
714
 
                                   openpgp_crt_fmt_t]
715
 
    openpgp_crt_import.restype = _error_code
716
 
    
717
 
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
718
 
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
719
 
                                        ctypes.POINTER(ctypes.c_uint)]
720
 
    openpgp_crt_verify_self.restype = _error_code
721
 
    
722
 
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
723
 
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
724
 
    openpgp_crt_deinit.restype = None
725
 
    
726
 
    openpgp_crt_get_fingerprint = (
727
 
        _library.gnutls_openpgp_crt_get_fingerprint)
728
 
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
729
 
                                            ctypes.c_void_p,
730
 
                                            ctypes.POINTER(
731
 
                                                ctypes.c_size_t)]
732
 
    openpgp_crt_get_fingerprint.restype = _error_code
733
 
    
734
 
    # Remove non-public functions
735
 
    del _error_code, _retry_on_error
736
 
# Create the global "gnutls" object, simulating a module
737
 
gnutls = GnuTLS()
738
 
 
739
 
def call_pipe(connection,       # : multiprocessing.Connection
740
 
              func, *args, **kwargs):
741
 
    """This function is meant to be called by multiprocessing.Process
742
 
    
743
 
    This function runs func(*args, **kwargs), and writes the resulting
744
 
    return value on the provided multiprocessing.Connection.
745
 
    """
746
 
    connection.send(func(*args, **kwargs))
747
 
    connection.close()
748
426
 
749
427
class Client(object):
750
428
    """A representation of a client host served by this server.
756
434
    checker:    subprocess.Popen(); a running checker process used
757
435
                                    to see if the client lives.
758
436
                                    'None' if no process is running.
759
 
    checker_callback_tag: a GLib event source tag, or None
 
437
    checker_callback_tag: a gobject event source tag, or None
760
438
    checker_command: string; External command which is run to check
761
439
                     if client lives.  %() expansions are done at
762
440
                     runtime with vars(self) as dict, so that for
763
441
                     instance %(name)s can be used in the command.
764
 
    checker_initiator_tag: a GLib event source tag, or None
 
442
    checker_initiator_tag: a gobject event source tag, or None
765
443
    created:    datetime.datetime(); (UTC) object creation
766
444
    client_structure: Object describing what attributes a client has
767
445
                      and is used for storing the client at exit
768
446
    current_checker_command: string; current running checker_command
769
 
    disable_initiator_tag: a GLib event source tag, or None
 
447
    disable_initiator_tag: a gobject event source tag, or None
770
448
    enabled:    bool()
771
449
    fingerprint: string (40 or 32 hexadecimal digits); used to
772
450
                 uniquely identify the client
777
455
    last_checker_status: integer between 0 and 255 reflecting exit
778
456
                         status of last checker. -1 reflects crashed
779
457
                         checker, -2 means no checker completed yet.
780
 
    last_checker_signal: The signal which killed the last checker, if
781
 
                         last_checker_status is -1
782
458
    last_enabled: datetime.datetime(); (UTC) or None
783
459
    name:       string; from the config file, used in log messages and
784
460
                        D-Bus identifiers
835
511
            client["fingerprint"] = (section["fingerprint"].upper()
836
512
                                     .replace(" ", ""))
837
513
            if "secret" in section:
838
 
                client["secret"] = codecs.decode(section["secret"]
839
 
                                                 .encode("utf-8"),
840
 
                                                 "base64")
 
514
                client["secret"] = section["secret"].decode("base64")
841
515
            elif "secfile" in section:
842
516
                with open(os.path.expanduser(os.path.expandvars
843
517
                                             (section["secfile"])),
896
570
        self.changedstate = multiprocessing_manager.Condition(
897
571
            multiprocessing_manager.Lock())
898
572
        self.client_structure = [attr
899
 
                                 for attr in self.__dict__.keys()
 
573
                                 for attr in self.__dict__.iterkeys()
900
574
                                 if not attr.startswith("_")]
901
575
        self.client_structure.append("client_structure")
902
576
        
928
602
        if not quiet:
929
603
            logger.info("Disabling client %s", self.name)
930
604
        if getattr(self, "disable_initiator_tag", None) is not None:
931
 
            GLib.source_remove(self.disable_initiator_tag)
 
605
            gobject.source_remove(self.disable_initiator_tag)
932
606
            self.disable_initiator_tag = None
933
607
        self.expires = None
934
608
        if getattr(self, "checker_initiator_tag", None) is not None:
935
 
            GLib.source_remove(self.checker_initiator_tag)
 
609
            gobject.source_remove(self.checker_initiator_tag)
936
610
            self.checker_initiator_tag = None
937
611
        self.stop_checker()
938
612
        self.enabled = False
939
613
        if not quiet:
940
614
            self.send_changedstate()
941
 
        # Do not run this again if called by a GLib.timeout_add
 
615
        # Do not run this again if called by a gobject.timeout_add
942
616
        return False
943
617
    
944
618
    def __del__(self):
948
622
        # Schedule a new checker to be started an 'interval' from now,
949
623
        # and every interval from then on.
950
624
        if self.checker_initiator_tag is not None:
951
 
            GLib.source_remove(self.checker_initiator_tag)
952
 
        self.checker_initiator_tag = GLib.timeout_add(
 
625
            gobject.source_remove(self.checker_initiator_tag)
 
626
        self.checker_initiator_tag = gobject.timeout_add(
953
627
            int(self.interval.total_seconds() * 1000),
954
628
            self.start_checker)
955
629
        # Schedule a disable() when 'timeout' has passed
956
630
        if self.disable_initiator_tag is not None:
957
 
            GLib.source_remove(self.disable_initiator_tag)
958
 
        self.disable_initiator_tag = GLib.timeout_add(
 
631
            gobject.source_remove(self.disable_initiator_tag)
 
632
        self.disable_initiator_tag = gobject.timeout_add(
959
633
            int(self.timeout.total_seconds() * 1000), self.disable)
960
634
        # Also start a new checker *right now*.
961
635
        self.start_checker()
962
636
    
963
 
    def checker_callback(self, source, condition, connection,
964
 
                         command):
 
637
    def checker_callback(self, pid, condition, command):
965
638
        """The checker has completed, so take appropriate actions."""
966
639
        self.checker_callback_tag = None
967
640
        self.checker = None
968
 
        # Read return code from connection (see call_pipe)
969
 
        returncode = connection.recv()
970
 
        connection.close()
971
 
        
972
 
        if returncode >= 0:
973
 
            self.last_checker_status = returncode
974
 
            self.last_checker_signal = None
 
641
        if os.WIFEXITED(condition):
 
642
            self.last_checker_status = os.WEXITSTATUS(condition)
975
643
            if self.last_checker_status == 0:
976
644
                logger.info("Checker for %(name)s succeeded",
977
645
                            vars(self))
980
648
                logger.info("Checker for %(name)s failed", vars(self))
981
649
        else:
982
650
            self.last_checker_status = -1
983
 
            self.last_checker_signal = -returncode
984
651
            logger.warning("Checker for %(name)s crashed?",
985
652
                           vars(self))
986
 
        return False
987
653
    
988
654
    def checked_ok(self):
989
655
        """Assert that the client has been seen, alive and well."""
990
656
        self.last_checked_ok = datetime.datetime.utcnow()
991
657
        self.last_checker_status = 0
992
 
        self.last_checker_signal = None
993
658
        self.bump_timeout()
994
659
    
995
660
    def bump_timeout(self, timeout=None):
997
662
        if timeout is None:
998
663
            timeout = self.timeout
999
664
        if self.disable_initiator_tag is not None:
1000
 
            GLib.source_remove(self.disable_initiator_tag)
 
665
            gobject.source_remove(self.disable_initiator_tag)
1001
666
            self.disable_initiator_tag = None
1002
667
        if getattr(self, "enabled", False):
1003
 
            self.disable_initiator_tag = GLib.timeout_add(
 
668
            self.disable_initiator_tag = gobject.timeout_add(
1004
669
                int(timeout.total_seconds() * 1000), self.disable)
1005
670
            self.expires = datetime.datetime.utcnow() + timeout
1006
671
    
1021
686
        # than 'timeout' for the client to be disabled, which is as it
1022
687
        # should be.
1023
688
        
1024
 
        if self.checker is not None and not self.checker.is_alive():
1025
 
            logger.warning("Checker was not alive; joining")
1026
 
            self.checker.join()
1027
 
            self.checker = None
 
689
        # If a checker exists, make sure it is not a zombie
 
690
        try:
 
691
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
692
        except AttributeError:
 
693
            pass
 
694
        except OSError as error:
 
695
            if error.errno != errno.ECHILD:
 
696
                raise
 
697
        else:
 
698
            if pid:
 
699
                logger.warning("Checker was a zombie")
 
700
                gobject.source_remove(self.checker_callback_tag)
 
701
                self.checker_callback(pid, status,
 
702
                                      self.current_checker_command)
1028
703
        # Start a new checker if needed
1029
704
        if self.checker is None:
1030
705
            # Escape attributes for the shell
1039
714
                             exc_info=error)
1040
715
                return True     # Try again later
1041
716
            self.current_checker_command = command
1042
 
            logger.info("Starting checker %r for %s", command,
1043
 
                        self.name)
1044
 
            # We don't need to redirect stdout and stderr, since
1045
 
            # in normal mode, that is already done by daemon(),
1046
 
            # and in debug mode we don't want to.  (Stdin is
1047
 
            # always replaced by /dev/null.)
1048
 
            # The exception is when not debugging but nevertheless
1049
 
            # running in the foreground; use the previously
1050
 
            # created wnull.
1051
 
            popen_args = { "close_fds": True,
1052
 
                           "shell": True,
1053
 
                           "cwd": "/" }
1054
 
            if (not self.server_settings["debug"]
1055
 
                and self.server_settings["foreground"]):
1056
 
                popen_args.update({"stdout": wnull,
1057
 
                                   "stderr": wnull })
1058
 
            pipe = multiprocessing.Pipe(duplex = False)
1059
 
            self.checker = multiprocessing.Process(
1060
 
                target = call_pipe,
1061
 
                args = (pipe[1], subprocess.call, command),
1062
 
                kwargs = popen_args)
1063
 
            self.checker.start()
1064
 
            self.checker_callback_tag = GLib.io_add_watch(
1065
 
                pipe[0].fileno(), GLib.IO_IN,
1066
 
                self.checker_callback, pipe[0], command)
1067
 
        # Re-run this periodically if run by GLib.timeout_add
 
717
            try:
 
718
                logger.info("Starting checker %r for %s", command,
 
719
                            self.name)
 
720
                # We don't need to redirect stdout and stderr, since
 
721
                # in normal mode, that is already done by daemon(),
 
722
                # and in debug mode we don't want to.  (Stdin is
 
723
                # always replaced by /dev/null.)
 
724
                # The exception is when not debugging but nevertheless
 
725
                # running in the foreground; use the previously
 
726
                # created wnull.
 
727
                popen_args = {}
 
728
                if (not self.server_settings["debug"]
 
729
                    and self.server_settings["foreground"]):
 
730
                    popen_args.update({"stdout": wnull,
 
731
                                       "stderr": wnull })
 
732
                self.checker = subprocess.Popen(command,
 
733
                                                close_fds=True,
 
734
                                                shell=True,
 
735
                                                cwd="/",
 
736
                                                **popen_args)
 
737
            except OSError as error:
 
738
                logger.error("Failed to start subprocess",
 
739
                             exc_info=error)
 
740
                return True
 
741
            self.checker_callback_tag = gobject.child_watch_add(
 
742
                self.checker.pid, self.checker_callback, data=command)
 
743
            # The checker may have completed before the gobject
 
744
            # watch was added.  Check for this.
 
745
            try:
 
746
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
747
            except OSError as error:
 
748
                if error.errno == errno.ECHILD:
 
749
                    # This should never happen
 
750
                    logger.error("Child process vanished",
 
751
                                 exc_info=error)
 
752
                    return True
 
753
                raise
 
754
            if pid:
 
755
                gobject.source_remove(self.checker_callback_tag)
 
756
                self.checker_callback(pid, status, command)
 
757
        # Re-run this periodically if run by gobject.timeout_add
1068
758
        return True
1069
759
    
1070
760
    def stop_checker(self):
1071
761
        """Force the checker process, if any, to stop."""
1072
762
        if self.checker_callback_tag:
1073
 
            GLib.source_remove(self.checker_callback_tag)
 
763
            gobject.source_remove(self.checker_callback_tag)
1074
764
            self.checker_callback_tag = None
1075
765
        if getattr(self, "checker", None) is None:
1076
766
            return
1077
767
        logger.debug("Stopping checker for %(name)s", vars(self))
1078
 
        self.checker.terminate()
 
768
        try:
 
769
            self.checker.terminate()
 
770
            #time.sleep(0.5)
 
771
            #if self.checker.poll() is None:
 
772
            #    self.checker.kill()
 
773
        except OSError as error:
 
774
            if error.errno != errno.ESRCH: # No such process
 
775
                raise
1079
776
        self.checker = None
1080
777
 
1081
778
 
1145
842
                           access="r")
1146
843
    def Property_dbus_property(self):
1147
844
        return dbus.Boolean(False)
1148
 
    
1149
 
    See also the DBusObjectWithAnnotations class.
1150
845
    """
1151
846
    
1152
847
    def decorator(func):
1174
869
    pass
1175
870
 
1176
871
 
1177
 
class DBusObjectWithAnnotations(dbus.service.Object):
1178
 
    """A D-Bus object with annotations.
 
872
class DBusObjectWithProperties(dbus.service.Object):
 
873
    """A D-Bus object with properties.
1179
874
    
1180
 
    Classes inheriting from this can use the dbus_annotations
1181
 
    decorator to add annotations to methods or signals.
 
875
    Classes inheriting from this can use the dbus_service_property
 
876
    decorator to expose methods as D-Bus properties.  It exposes the
 
877
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1182
878
    """
1183
879
    
1184
880
    @staticmethod
1200
896
                for name, athing in
1201
897
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
1202
898
    
1203
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1204
 
                         out_signature = "s",
1205
 
                         path_keyword = 'object_path',
1206
 
                         connection_keyword = 'connection')
1207
 
    def Introspect(self, object_path, connection):
1208
 
        """Overloading of standard D-Bus method.
1209
 
        
1210
 
        Inserts annotation tags on methods and signals.
1211
 
        """
1212
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
1213
 
                                                   connection)
1214
 
        try:
1215
 
            document = xml.dom.minidom.parseString(xmlstring)
1216
 
            
1217
 
            for if_tag in document.getElementsByTagName("interface"):
1218
 
                # Add annotation tags
1219
 
                for typ in ("method", "signal"):
1220
 
                    for tag in if_tag.getElementsByTagName(typ):
1221
 
                        annots = dict()
1222
 
                        for name, prop in (self.
1223
 
                                           _get_all_dbus_things(typ)):
1224
 
                            if (name == tag.getAttribute("name")
1225
 
                                and prop._dbus_interface
1226
 
                                == if_tag.getAttribute("name")):
1227
 
                                annots.update(getattr(
1228
 
                                    prop, "_dbus_annotations", {}))
1229
 
                        for name, value in annots.items():
1230
 
                            ann_tag = document.createElement(
1231
 
                                "annotation")
1232
 
                            ann_tag.setAttribute("name", name)
1233
 
                            ann_tag.setAttribute("value", value)
1234
 
                            tag.appendChild(ann_tag)
1235
 
                # Add interface annotation tags
1236
 
                for annotation, value in dict(
1237
 
                    itertools.chain.from_iterable(
1238
 
                        annotations().items()
1239
 
                        for name, annotations
1240
 
                        in self._get_all_dbus_things("interface")
1241
 
                        if name == if_tag.getAttribute("name")
1242
 
                        )).items():
1243
 
                    ann_tag = document.createElement("annotation")
1244
 
                    ann_tag.setAttribute("name", annotation)
1245
 
                    ann_tag.setAttribute("value", value)
1246
 
                    if_tag.appendChild(ann_tag)
1247
 
                # Fix argument name for the Introspect method itself
1248
 
                if (if_tag.getAttribute("name")
1249
 
                                == dbus.INTROSPECTABLE_IFACE):
1250
 
                    for cn in if_tag.getElementsByTagName("method"):
1251
 
                        if cn.getAttribute("name") == "Introspect":
1252
 
                            for arg in cn.getElementsByTagName("arg"):
1253
 
                                if (arg.getAttribute("direction")
1254
 
                                    == "out"):
1255
 
                                    arg.setAttribute("name",
1256
 
                                                     "xml_data")
1257
 
            xmlstring = document.toxml("utf-8")
1258
 
            document.unlink()
1259
 
        except (AttributeError, xml.dom.DOMException,
1260
 
                xml.parsers.expat.ExpatError) as error:
1261
 
            logger.error("Failed to override Introspection method",
1262
 
                         exc_info=error)
1263
 
        return xmlstring
1264
 
 
1265
 
 
1266
 
class DBusObjectWithProperties(DBusObjectWithAnnotations):
1267
 
    """A D-Bus object with properties.
1268
 
    
1269
 
    Classes inheriting from this can use the dbus_service_property
1270
 
    decorator to expose methods as D-Bus properties.  It exposes the
1271
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1272
 
    """
1273
 
    
1274
899
    def _get_dbus_property(self, interface_name, property_name):
1275
900
        """Returns a bound method if one exists which is a D-Bus
1276
901
        property with the specified name and interface.
1286
911
        raise DBusPropertyNotFound("{}:{}.{}".format(
1287
912
            self.dbus_object_path, interface_name, property_name))
1288
913
    
1289
 
    @classmethod
1290
 
    def _get_all_interface_names(cls):
1291
 
        """Get a sequence of all interfaces supported by an object"""
1292
 
        return (name for name in set(getattr(getattr(x, attr),
1293
 
                                             "_dbus_interface", None)
1294
 
                                     for x in (inspect.getmro(cls))
1295
 
                                     for attr in dir(x))
1296
 
                if name is not None)
1297
 
    
1298
914
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1299
915
                         in_signature="ss",
1300
916
                         out_signature="v")
1370
986
        
1371
987
        Inserts property tags and interface annotation tags.
1372
988
        """
1373
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1374
 
                                                         object_path,
1375
 
                                                         connection)
 
989
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
990
                                                   connection)
1376
991
        try:
1377
992
            document = xml.dom.minidom.parseString(xmlstring)
1378
993
            
1391
1006
                            if prop._dbus_interface
1392
1007
                            == if_tag.getAttribute("name")):
1393
1008
                    if_tag.appendChild(tag)
1394
 
                # Add annotation tags for properties
1395
 
                for tag in if_tag.getElementsByTagName("property"):
1396
 
                    annots = dict()
1397
 
                    for name, prop in self._get_all_dbus_things(
1398
 
                            "property"):
1399
 
                        if (name == tag.getAttribute("name")
1400
 
                            and prop._dbus_interface
1401
 
                            == if_tag.getAttribute("name")):
1402
 
                            annots.update(getattr(
1403
 
                                prop, "_dbus_annotations", {}))
1404
 
                    for name, value in annots.items():
1405
 
                        ann_tag = document.createElement(
1406
 
                            "annotation")
1407
 
                        ann_tag.setAttribute("name", name)
1408
 
                        ann_tag.setAttribute("value", value)
1409
 
                        tag.appendChild(ann_tag)
 
1009
                # Add annotation tags
 
1010
                for typ in ("method", "signal", "property"):
 
1011
                    for tag in if_tag.getElementsByTagName(typ):
 
1012
                        annots = dict()
 
1013
                        for name, prop in (self.
 
1014
                                           _get_all_dbus_things(typ)):
 
1015
                            if (name == tag.getAttribute("name")
 
1016
                                and prop._dbus_interface
 
1017
                                == if_tag.getAttribute("name")):
 
1018
                                annots.update(getattr(
 
1019
                                    prop, "_dbus_annotations", {}))
 
1020
                        for name, value in annots.items():
 
1021
                            ann_tag = document.createElement(
 
1022
                                "annotation")
 
1023
                            ann_tag.setAttribute("name", name)
 
1024
                            ann_tag.setAttribute("value", value)
 
1025
                            tag.appendChild(ann_tag)
 
1026
                # Add interface annotation tags
 
1027
                for annotation, value in dict(
 
1028
                    itertools.chain.from_iterable(
 
1029
                        annotations().items()
 
1030
                        for name, annotations
 
1031
                        in self._get_all_dbus_things("interface")
 
1032
                        if name == if_tag.getAttribute("name")
 
1033
                        )).items():
 
1034
                    ann_tag = document.createElement("annotation")
 
1035
                    ann_tag.setAttribute("name", annotation)
 
1036
                    ann_tag.setAttribute("value", value)
 
1037
                    if_tag.appendChild(ann_tag)
1410
1038
                # Add the names to the return values for the
1411
1039
                # "org.freedesktop.DBus.Properties" methods
1412
1040
                if (if_tag.getAttribute("name")
1430
1058
                         exc_info=error)
1431
1059
        return xmlstring
1432
1060
 
1433
 
try:
1434
 
    dbus.OBJECT_MANAGER_IFACE
1435
 
except AttributeError:
1436
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1437
 
 
1438
 
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1439
 
    """A D-Bus object with an ObjectManager.
1440
 
    
1441
 
    Classes inheriting from this exposes the standard
1442
 
    GetManagedObjects call and the InterfacesAdded and
1443
 
    InterfacesRemoved signals on the standard
1444
 
    "org.freedesktop.DBus.ObjectManager" interface.
1445
 
    
1446
 
    Note: No signals are sent automatically; they must be sent
1447
 
    manually.
1448
 
    """
1449
 
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1450
 
                         out_signature = "a{oa{sa{sv}}}")
1451
 
    def GetManagedObjects(self):
1452
 
        """This function must be overridden"""
1453
 
        raise NotImplementedError()
1454
 
    
1455
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1456
 
                         signature = "oa{sa{sv}}")
1457
 
    def InterfacesAdded(self, object_path, interfaces_and_properties):
1458
 
        pass
1459
 
    
1460
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1461
 
    def InterfacesRemoved(self, object_path, interfaces):
1462
 
        pass
1463
 
    
1464
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1465
 
                         out_signature = "s",
1466
 
                         path_keyword = 'object_path',
1467
 
                         connection_keyword = 'connection')
1468
 
    def Introspect(self, object_path, connection):
1469
 
        """Overloading of standard D-Bus method.
1470
 
        
1471
 
        Override return argument name of GetManagedObjects to be
1472
 
        "objpath_interfaces_and_properties"
1473
 
        """
1474
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1475
 
                                                         object_path,
1476
 
                                                         connection)
1477
 
        try:
1478
 
            document = xml.dom.minidom.parseString(xmlstring)
1479
 
            
1480
 
            for if_tag in document.getElementsByTagName("interface"):
1481
 
                # Fix argument name for the GetManagedObjects method
1482
 
                if (if_tag.getAttribute("name")
1483
 
                                == dbus.OBJECT_MANAGER_IFACE):
1484
 
                    for cn in if_tag.getElementsByTagName("method"):
1485
 
                        if (cn.getAttribute("name")
1486
 
                            == "GetManagedObjects"):
1487
 
                            for arg in cn.getElementsByTagName("arg"):
1488
 
                                if (arg.getAttribute("direction")
1489
 
                                    == "out"):
1490
 
                                    arg.setAttribute(
1491
 
                                        "name",
1492
 
                                        "objpath_interfaces"
1493
 
                                        "_and_properties")
1494
 
            xmlstring = document.toxml("utf-8")
1495
 
            document.unlink()
1496
 
        except (AttributeError, xml.dom.DOMException,
1497
 
                xml.parsers.expat.ExpatError) as error:
1498
 
            logger.error("Failed to override Introspection method",
1499
 
                         exc_info = error)
1500
 
        return xmlstring
1501
1061
 
1502
1062
def datetime_to_dbus(dt, variant_level=0):
1503
1063
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1552
1112
                if getattr(attribute, "_dbus_is_signal", False):
1553
1113
                    # Extract the original non-method undecorated
1554
1114
                    # function by black magic
1555
 
                    if sys.version_info.major == 2:
1556
 
                        nonmethod_func = (dict(
1557
 
                            zip(attribute.func_code.co_freevars,
1558
 
                                attribute.__closure__))
1559
 
                                          ["func"].cell_contents)
1560
 
                    else:
1561
 
                        nonmethod_func = (dict(
1562
 
                            zip(attribute.__code__.co_freevars,
1563
 
                                attribute.__closure__))
1564
 
                                          ["func"].cell_contents)
 
1115
                    nonmethod_func = (dict(
 
1116
                        zip(attribute.func_code.co_freevars,
 
1117
                            attribute.__closure__))
 
1118
                                      ["func"].cell_contents)
1565
1119
                    # Create a new, but exactly alike, function
1566
1120
                    # object, and decorate it to be a new D-Bus signal
1567
1121
                    # with the alternate D-Bus interface name
1568
 
                    new_function = copy_function(nonmethod_func)
1569
1122
                    new_function = (dbus.service.signal(
1570
 
                        alt_interface,
1571
 
                        attribute._dbus_signature)(new_function))
 
1123
                        alt_interface, attribute._dbus_signature)
 
1124
                                    (types.FunctionType(
 
1125
                                        nonmethod_func.func_code,
 
1126
                                        nonmethod_func.func_globals,
 
1127
                                        nonmethod_func.func_name,
 
1128
                                        nonmethod_func.func_defaults,
 
1129
                                        nonmethod_func.func_closure)))
1572
1130
                    # Copy annotations, if any
1573
1131
                    try:
1574
1132
                        new_function._dbus_annotations = dict(
1584
1142
                        func1 and func2 to the "call_both" function
1585
1143
                        outside of its arguments"""
1586
1144
                        
1587
 
                        @functools.wraps(func2)
1588
1145
                        def call_both(*args, **kwargs):
1589
1146
                            """This function will emit two D-Bus
1590
1147
                            signals by calling func1 and func2"""
1591
1148
                            func1(*args, **kwargs)
1592
1149
                            func2(*args, **kwargs)
1593
 
                        # Make wrapper function look like a D-Bus signal
1594
 
                        for name, attr in inspect.getmembers(func2):
1595
 
                            if name.startswith("_dbus_"):
1596
 
                                setattr(call_both, name, attr)
1597
1150
                        
1598
1151
                        return call_both
1599
1152
                    # Create the "call_both" function and add it to
1610
1163
                            alt_interface,
1611
1164
                            attribute._dbus_in_signature,
1612
1165
                            attribute._dbus_out_signature)
1613
 
                        (copy_function(attribute)))
 
1166
                        (types.FunctionType(attribute.func_code,
 
1167
                                            attribute.func_globals,
 
1168
                                            attribute.func_name,
 
1169
                                            attribute.func_defaults,
 
1170
                                            attribute.func_closure)))
1614
1171
                    # Copy annotations, if any
1615
1172
                    try:
1616
1173
                        attr[attrname]._dbus_annotations = dict(
1628
1185
                        attribute._dbus_access,
1629
1186
                        attribute._dbus_get_args_options
1630
1187
                        ["byte_arrays"])
1631
 
                                      (copy_function(attribute)))
 
1188
                                      (types.FunctionType(
 
1189
                                          attribute.func_code,
 
1190
                                          attribute.func_globals,
 
1191
                                          attribute.func_name,
 
1192
                                          attribute.func_defaults,
 
1193
                                          attribute.func_closure)))
1632
1194
                    # Copy annotations, if any
1633
1195
                    try:
1634
1196
                        attr[attrname]._dbus_annotations = dict(
1643
1205
                    # to the class.
1644
1206
                    attr[attrname] = (
1645
1207
                        dbus_interface_annotations(alt_interface)
1646
 
                        (copy_function(attribute)))
 
1208
                        (types.FunctionType(attribute.func_code,
 
1209
                                            attribute.func_globals,
 
1210
                                            attribute.func_name,
 
1211
                                            attribute.func_defaults,
 
1212
                                            attribute.func_closure)))
1647
1213
            if deprecate:
1648
1214
                # Deprecate all alternate interfaces
1649
1215
                iname="_AlternateDBusNames_interface_annotation{}"
1662
1228
            if interface_names:
1663
1229
                # Replace the class with a new subclass of it with
1664
1230
                # methods, signals, etc. as created above.
1665
 
                if sys.version_info.major == 2:
1666
 
                    cls = type(b"{}Alternate".format(cls.__name__),
1667
 
                               (cls, ), attr)
1668
 
                else:
1669
 
                    cls = type("{}Alternate".format(cls.__name__),
1670
 
                               (cls, ), attr)
 
1231
                cls = type(b"{}Alternate".format(cls.__name__),
 
1232
                           (cls, ), attr)
1671
1233
        return cls
1672
1234
    
1673
1235
    return wrapper
1793
1355
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1794
1356
        Client.__del__(self, *args, **kwargs)
1795
1357
    
1796
 
    def checker_callback(self, source, condition,
1797
 
                         connection, command, *args, **kwargs):
1798
 
        ret = Client.checker_callback(self, source, condition,
1799
 
                                      connection, command, *args,
1800
 
                                      **kwargs)
1801
 
        exitstatus = self.last_checker_status
1802
 
        if exitstatus >= 0:
 
1358
    def checker_callback(self, pid, condition, command,
 
1359
                         *args, **kwargs):
 
1360
        self.checker_callback_tag = None
 
1361
        self.checker = None
 
1362
        if os.WIFEXITED(condition):
 
1363
            exitstatus = os.WEXITSTATUS(condition)
1803
1364
            # Emit D-Bus signal
1804
1365
            self.CheckerCompleted(dbus.Int16(exitstatus),
1805
 
                                  # This is specific to GNU libC
1806
 
                                  dbus.Int64(exitstatus << 8),
 
1366
                                  dbus.Int64(condition),
1807
1367
                                  dbus.String(command))
1808
1368
        else:
1809
1369
            # Emit D-Bus signal
1810
1370
            self.CheckerCompleted(dbus.Int16(-1),
1811
 
                                  dbus.Int64(
1812
 
                                      # This is specific to GNU libC
1813
 
                                      (exitstatus << 8)
1814
 
                                      | self.last_checker_signal),
 
1371
                                  dbus.Int64(condition),
1815
1372
                                  dbus.String(command))
1816
 
        return ret
 
1373
        
 
1374
        return Client.checker_callback(self, pid, condition, command,
 
1375
                                       *args, **kwargs)
1817
1376
    
1818
1377
    def start_checker(self, *args, **kwargs):
1819
1378
        old_checker_pid = getattr(self.checker, "pid", None)
1831
1390
    
1832
1391
    def approve(self, value=True):
1833
1392
        self.approved = value
1834
 
        GLib.timeout_add(int(self.approval_duration.total_seconds()
1835
 
                             * 1000), self._reset_approved)
 
1393
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1394
                                * 1000), self._reset_approved)
1836
1395
        self.send_changedstate()
1837
1396
    
1838
1397
    ## D-Bus methods, signals & properties
1894
1453
        self.checked_ok()
1895
1454
    
1896
1455
    # Enable - method
1897
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1898
1456
    @dbus.service.method(_interface)
1899
1457
    def Enable(self):
1900
1458
        "D-Bus method"
1901
1459
        self.enable()
1902
1460
    
1903
1461
    # StartChecker - method
1904
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1905
1462
    @dbus.service.method(_interface)
1906
1463
    def StartChecker(self):
1907
1464
        "D-Bus method"
1908
1465
        self.start_checker()
1909
1466
    
1910
1467
    # Disable - method
1911
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1912
1468
    @dbus.service.method(_interface)
1913
1469
    def Disable(self):
1914
1470
        "D-Bus method"
1915
1471
        self.disable()
1916
1472
    
1917
1473
    # StopChecker - method
1918
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1919
1474
    @dbus.service.method(_interface)
1920
1475
    def StopChecker(self):
1921
1476
        self.stop_checker()
1957
1512
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1958
1513
    
1959
1514
    # Name - property
1960
 
    @dbus_annotations(
1961
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1962
1515
    @dbus_service_property(_interface, signature="s", access="read")
1963
1516
    def Name_dbus_property(self):
1964
1517
        return dbus.String(self.name)
1965
1518
    
1966
1519
    # Fingerprint - property
1967
 
    @dbus_annotations(
1968
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1969
1520
    @dbus_service_property(_interface, signature="s", access="read")
1970
1521
    def Fingerprint_dbus_property(self):
1971
1522
        return dbus.String(self.fingerprint)
1980
1531
        self.host = str(value)
1981
1532
    
1982
1533
    # Created - property
1983
 
    @dbus_annotations(
1984
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1985
1534
    @dbus_service_property(_interface, signature="s", access="read")
1986
1535
    def Created_dbus_property(self):
1987
1536
        return datetime_to_dbus(self.created)
2048
1597
                if (getattr(self, "disable_initiator_tag", None)
2049
1598
                    is None):
2050
1599
                    return
2051
 
                GLib.source_remove(self.disable_initiator_tag)
2052
 
                self.disable_initiator_tag = GLib.timeout_add(
 
1600
                gobject.source_remove(self.disable_initiator_tag)
 
1601
                self.disable_initiator_tag = gobject.timeout_add(
2053
1602
                    int((self.expires - now).total_seconds() * 1000),
2054
1603
                    self.disable)
2055
1604
    
2075
1624
            return
2076
1625
        if self.enabled:
2077
1626
            # Reschedule checker run
2078
 
            GLib.source_remove(self.checker_initiator_tag)
2079
 
            self.checker_initiator_tag = GLib.timeout_add(
 
1627
            gobject.source_remove(self.checker_initiator_tag)
 
1628
            self.checker_initiator_tag = gobject.timeout_add(
2080
1629
                value, self.start_checker)
2081
1630
            self.start_checker() # Start one now, too
2082
1631
    
2102
1651
            self.stop_checker()
2103
1652
    
2104
1653
    # ObjectPath - property
2105
 
    @dbus_annotations(
2106
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2107
 
         "org.freedesktop.DBus.Deprecated": "true"})
2108
1654
    @dbus_service_property(_interface, signature="o", access="read")
2109
1655
    def ObjectPath_dbus_property(self):
2110
1656
        return self.dbus_object_path # is already a dbus.ObjectPath
2111
1657
    
2112
1658
    # Secret = property
2113
 
    @dbus_annotations(
2114
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
2115
 
         "invalidates"})
2116
1659
    @dbus_service_property(_interface,
2117
1660
                           signature="ay",
2118
1661
                           access="write",
2128
1671
        self._pipe = child_pipe
2129
1672
        self._pipe.send(('init', fpr, address))
2130
1673
        if not self._pipe.recv():
2131
 
            raise KeyError(fpr)
 
1674
            raise KeyError()
2132
1675
    
2133
1676
    def __getattribute__(self, name):
2134
1677
        if name == '_pipe':
2164
1707
            logger.debug("Pipe FD: %d",
2165
1708
                         self.server.child_pipe.fileno())
2166
1709
            
2167
 
            session = gnutls.ClientSession(self.request)
 
1710
            session = gnutls.connection.ClientSession(
 
1711
                self.request, gnutls.connection .X509Credentials())
 
1712
            
 
1713
            # Note: gnutls.connection.X509Credentials is really a
 
1714
            # generic GnuTLS certificate credentials object so long as
 
1715
            # no X.509 keys are added to it.  Therefore, we can use it
 
1716
            # here despite using OpenPGP certificates.
2168
1717
            
2169
1718
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
2170
1719
            #                      "+AES-256-CBC", "+SHA1",
2174
1723
            priority = self.server.gnutls_priority
2175
1724
            if priority is None:
2176
1725
                priority = "NORMAL"
2177
 
            gnutls.priority_set_direct(session._c_object,
2178
 
                                       priority.encode("utf-8"),
2179
 
                                       None)
 
1726
            gnutls.library.functions.gnutls_priority_set_direct(
 
1727
                session._c_object, priority, None)
2180
1728
            
2181
1729
            # Start communication using the Mandos protocol
2182
1730
            # Get protocol number
2192
1740
            # Start GnuTLS connection
2193
1741
            try:
2194
1742
                session.handshake()
2195
 
            except gnutls.Error as error:
 
1743
            except gnutls.errors.GNUTLSError as error:
2196
1744
                logger.warning("Handshake failed: %s", error)
2197
1745
                # Do not run session.bye() here: the session is not
2198
1746
                # established.  Just abandon the request.
2204
1752
                try:
2205
1753
                    fpr = self.fingerprint(
2206
1754
                        self.peer_certificate(session))
2207
 
                except (TypeError, gnutls.Error) as error:
 
1755
                except (TypeError,
 
1756
                        gnutls.errors.GNUTLSError) as error:
2208
1757
                    logger.warning("Bad certificate: %s", error)
2209
1758
                    return
2210
1759
                logger.debug("Fingerprint: %s", fpr)
2268
1817
                    else:
2269
1818
                        delay -= time2 - time
2270
1819
                
2271
 
                try:
2272
 
                    session.send(client.secret)
2273
 
                except gnutls.Error as error:
2274
 
                    logger.warning("gnutls send failed",
2275
 
                                   exc_info = error)
2276
 
                    return
 
1820
                sent_size = 0
 
1821
                while sent_size < len(client.secret):
 
1822
                    try:
 
1823
                        sent = session.send(client.secret[sent_size:])
 
1824
                    except gnutls.errors.GNUTLSError as error:
 
1825
                        logger.warning("gnutls send failed",
 
1826
                                       exc_info=error)
 
1827
                        return
 
1828
                    logger.debug("Sent: %d, remaining: %d", sent,
 
1829
                                 len(client.secret) - (sent_size
 
1830
                                                       + sent))
 
1831
                    sent_size += sent
2277
1832
                
2278
1833
                logger.info("Sending secret to %s", client.name)
2279
1834
                # bump the timeout using extended_timeout
2287
1842
                    client.approvals_pending -= 1
2288
1843
                try:
2289
1844
                    session.bye()
2290
 
                except gnutls.Error as error:
 
1845
                except gnutls.errors.GNUTLSError as error:
2291
1846
                    logger.warning("GnuTLS bye failed",
2292
1847
                                   exc_info=error)
2293
1848
    
2295
1850
    def peer_certificate(session):
2296
1851
        "Return the peer's OpenPGP certificate as a bytestring"
2297
1852
        # If not an OpenPGP certificate...
2298
 
        if (gnutls.certificate_type_get(session._c_object)
2299
 
            != gnutls.CRT_OPENPGP):
2300
 
            # ...return invalid data
2301
 
            return b""
 
1853
        if (gnutls.library.functions.gnutls_certificate_type_get(
 
1854
                session._c_object)
 
1855
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
1856
            # ...do the normal thing
 
1857
            return session.peer_certificate
2302
1858
        list_size = ctypes.c_uint(1)
2303
 
        cert_list = (gnutls.certificate_get_peers
 
1859
        cert_list = (gnutls.library.functions
 
1860
                     .gnutls_certificate_get_peers
2304
1861
                     (session._c_object, ctypes.byref(list_size)))
2305
1862
        if not bool(cert_list) and list_size.value != 0:
2306
 
            raise gnutls.Error("error getting peer certificate")
 
1863
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1864
                                            " certificate")
2307
1865
        if list_size.value == 0:
2308
1866
            return None
2309
1867
        cert = cert_list[0]
2313
1871
    def fingerprint(openpgp):
2314
1872
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2315
1873
        # New GnuTLS "datum" with the OpenPGP public key
2316
 
        datum = gnutls.datum_t(
 
1874
        datum = gnutls.library.types.gnutls_datum_t(
2317
1875
            ctypes.cast(ctypes.c_char_p(openpgp),
2318
1876
                        ctypes.POINTER(ctypes.c_ubyte)),
2319
1877
            ctypes.c_uint(len(openpgp)))
2320
1878
        # New empty GnuTLS certificate
2321
 
        crt = gnutls.openpgp_crt_t()
2322
 
        gnutls.openpgp_crt_init(ctypes.byref(crt))
 
1879
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
1880
        gnutls.library.functions.gnutls_openpgp_crt_init(
 
1881
            ctypes.byref(crt))
2323
1882
        # Import the OpenPGP public key into the certificate
2324
 
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2325
 
                                  gnutls.OPENPGP_FMT_RAW)
 
1883
        gnutls.library.functions.gnutls_openpgp_crt_import(
 
1884
            crt, ctypes.byref(datum),
 
1885
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
2326
1886
        # Verify the self signature in the key
2327
1887
        crtverify = ctypes.c_uint()
2328
 
        gnutls.openpgp_crt_verify_self(crt, 0,
2329
 
                                       ctypes.byref(crtverify))
 
1888
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
 
1889
            crt, 0, ctypes.byref(crtverify))
2330
1890
        if crtverify.value != 0:
2331
 
            gnutls.openpgp_crt_deinit(crt)
2332
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
1891
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
1892
            raise gnutls.errors.CertificateSecurityError(
 
1893
                "Verify failed")
2333
1894
        # New buffer for the fingerprint
2334
1895
        buf = ctypes.create_string_buffer(20)
2335
1896
        buf_len = ctypes.c_size_t()
2336
1897
        # Get the fingerprint from the certificate into the buffer
2337
 
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2338
 
                                           ctypes.byref(buf_len))
 
1898
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
 
1899
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
2339
1900
        # Deinit the certificate
2340
 
        gnutls.openpgp_crt_deinit(crt)
 
1901
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2341
1902
        # Convert the buffer to a Python bytestring
2342
1903
        fpr = ctypes.string_at(buf, buf_len.value)
2343
1904
        # Convert the bytestring to hexadecimal notation
2487
2048
        gnutls_priority GnuTLS priority string
2488
2049
        use_dbus:       Boolean; to emit D-Bus signals or not
2489
2050
    
2490
 
    Assumes a GLib.MainLoop event loop.
 
2051
    Assumes a gobject.MainLoop event loop.
2491
2052
    """
2492
2053
    
2493
2054
    def __init__(self, server_address, RequestHandlerClass,
2518
2079
    
2519
2080
    def add_pipe(self, parent_pipe, proc):
2520
2081
        # Call "handle_ipc" for both data and EOF events
2521
 
        GLib.io_add_watch(
 
2082
        gobject.io_add_watch(
2522
2083
            parent_pipe.fileno(),
2523
 
            GLib.IO_IN | GLib.IO_HUP,
 
2084
            gobject.IO_IN | gobject.IO_HUP,
2524
2085
            functools.partial(self.handle_ipc,
2525
2086
                              parent_pipe = parent_pipe,
2526
2087
                              proc = proc))
2530
2091
                   proc = None,
2531
2092
                   client_object=None):
2532
2093
        # error, or the other end of multiprocessing.Pipe has closed
2533
 
        if condition & (GLib.IO_ERR | GLib.IO_HUP):
 
2094
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2534
2095
            # Wait for other process to exit
2535
2096
            proc.join()
2536
2097
            return False
2543
2104
            fpr = request[1]
2544
2105
            address = request[2]
2545
2106
            
2546
 
            for c in self.clients.values():
 
2107
            for c in self.clients.itervalues():
2547
2108
                if c.fingerprint == fpr:
2548
2109
                    client = c
2549
2110
                    break
2557
2118
                parent_pipe.send(False)
2558
2119
                return False
2559
2120
            
2560
 
            GLib.io_add_watch(
 
2121
            gobject.io_add_watch(
2561
2122
                parent_pipe.fileno(),
2562
 
                GLib.IO_IN | GLib.IO_HUP,
 
2123
                gobject.IO_IN | gobject.IO_HUP,
2563
2124
                functools.partial(self.handle_ipc,
2564
2125
                                  parent_pipe = parent_pipe,
2565
2126
                                  proc = proc,
2579
2140
        
2580
2141
        if command == 'getattr':
2581
2142
            attrname = request[1]
2582
 
            if isinstance(client_object.__getattribute__(attrname),
2583
 
                          collections.Callable):
 
2143
            if callable(client_object.__getattribute__(attrname)):
2584
2144
                parent_pipe.send(('function', ))
2585
2145
            else:
2586
2146
                parent_pipe.send((
2621
2181
    # avoid excessive use of external libraries.
2622
2182
    
2623
2183
    # New type for defining tokens, syntax, and semantics all-in-one
 
2184
    Token = collections.namedtuple("Token",
 
2185
                                   ("regexp", # To match token; if
 
2186
                                              # "value" is not None,
 
2187
                                              # must have a "group"
 
2188
                                              # containing digits
 
2189
                                    "value",  # datetime.timedelta or
 
2190
                                              # None
 
2191
                                    "followers")) # Tokens valid after
 
2192
                                                  # this token
2624
2193
    Token = collections.namedtuple("Token", (
2625
2194
        "regexp",  # To match token; if "value" is not None, must have
2626
2195
                   # a "group" containing digits
2661
2230
    # Define starting values
2662
2231
    value = datetime.timedelta() # Value so far
2663
2232
    found_token = None
2664
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2233
    followers = frozenset((token_duration,)) # Following valid tokens
2665
2234
    s = duration                # String left to parse
2666
2235
    # Loop until end token is found
2667
2236
    while found_token is not token_end:
2684
2253
                break
2685
2254
        else:
2686
2255
            # No currently valid tokens were found
2687
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2688
 
                             .format(duration))
 
2256
            raise ValueError("Invalid RFC 3339 duration")
2689
2257
    # End token found
2690
2258
    return value
2691
2259
 
2824
2392
                        "debug": "False",
2825
2393
                        "priority":
2826
2394
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2827
 
                        ":+SIGN-DSA-SHA256",
 
2395
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2828
2396
                        "servicename": "Mandos",
2829
2397
                        "use_dbus": "True",
2830
2398
                        "use_ipv6": "True",
2942
2510
            pidfilename = "/var/run/mandos.pid"
2943
2511
        pidfile = None
2944
2512
        try:
2945
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2513
            pidfile = open(pidfilename, "w")
2946
2514
        except IOError as e:
2947
2515
            logger.error("Could not open file %r", pidfilename,
2948
2516
                         exc_info=e)
2949
2517
    
2950
 
    for name, group in (("_mandos", "_mandos"),
2951
 
                        ("mandos", "mandos"),
2952
 
                        ("nobody", "nogroup")):
 
2518
    for name in ("_mandos", "mandos", "nobody"):
2953
2519
        try:
2954
2520
            uid = pwd.getpwnam(name).pw_uid
2955
 
            gid = pwd.getpwnam(group).pw_gid
 
2521
            gid = pwd.getpwnam(name).pw_gid
2956
2522
            break
2957
2523
        except KeyError:
2958
2524
            continue
2962
2528
    try:
2963
2529
        os.setgid(gid)
2964
2530
        os.setuid(uid)
2965
 
        if debug:
2966
 
            logger.debug("Did setuid/setgid to {}:{}".format(uid,
2967
 
                                                             gid))
2968
2531
    except OSError as error:
2969
 
        logger.warning("Failed to setuid/setgid to {}:{}: {}"
2970
 
                       .format(uid, gid, os.strerror(error.errno)))
2971
2532
        if error.errno != errno.EPERM:
2972
2533
            raise
2973
2534
    
2976
2537
        
2977
2538
        # "Use a log level over 10 to enable all debugging options."
2978
2539
        # - GnuTLS manual
2979
 
        gnutls.global_set_log_level(11)
 
2540
        gnutls.library.functions.gnutls_global_set_log_level(11)
2980
2541
        
2981
 
        @gnutls.log_func
 
2542
        @gnutls.library.types.gnutls_log_func
2982
2543
        def debug_gnutls(level, string):
2983
2544
            logger.debug("GnuTLS: %s", string[:-1])
2984
2545
        
2985
 
        gnutls.global_set_log_function(debug_gnutls)
 
2546
        gnutls.library.functions.gnutls_global_set_log_function(
 
2547
            debug_gnutls)
2986
2548
        
2987
2549
        # Redirect stdin so all checkers get /dev/null
2988
2550
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2995
2557
        # Close all input and output, do double fork, etc.
2996
2558
        daemon()
2997
2559
    
2998
 
    # multiprocessing will use threads, so before we use GLib we need
2999
 
    # to inform GLib that threads will be used.
3000
 
    GLib.threads_init()
 
2560
    # multiprocessing will use threads, so before we use gobject we
 
2561
    # need to inform gobject that threads will be used.
 
2562
    gobject.threads_init()
3001
2563
    
3002
2564
    global main_loop
3003
2565
    # From the Avahi example code
3004
2566
    DBusGMainLoop(set_as_default=True)
3005
 
    main_loop = GLib.MainLoop()
 
2567
    main_loop = gobject.MainLoop()
3006
2568
    bus = dbus.SystemBus()
3007
2569
    # End of Avahi example code
3008
2570
    if use_dbus:
3013
2575
            old_bus_name = dbus.service.BusName(
3014
2576
                "se.bsnet.fukt.Mandos", bus,
3015
2577
                do_not_queue=True)
3016
 
        except dbus.exceptions.DBusException as e:
 
2578
        except dbus.exceptions.NameExistsException as e:
3017
2579
            logger.error("Disabling D-Bus:", exc_info=e)
3018
2580
            use_dbus = False
3019
2581
            server_settings["use_dbus"] = False
3052
2614
    if server_settings["restore"]:
3053
2615
        try:
3054
2616
            with open(stored_state_path, "rb") as stored_state:
3055
 
                if sys.version_info.major == 2:                
3056
 
                    clients_data, old_client_settings = pickle.load(
3057
 
                        stored_state)
3058
 
                else:
3059
 
                    bytes_clients_data, bytes_old_client_settings = (
3060
 
                        pickle.load(stored_state, encoding = "bytes"))
3061
 
                    ### Fix bytes to strings
3062
 
                    ## clients_data
3063
 
                    # .keys()
3064
 
                    clients_data = { (key.decode("utf-8")
3065
 
                                      if isinstance(key, bytes)
3066
 
                                      else key): value
3067
 
                                     for key, value in
3068
 
                                     bytes_clients_data.items() }
3069
 
                    del bytes_clients_data
3070
 
                    for key in clients_data:
3071
 
                        value = { (k.decode("utf-8")
3072
 
                                   if isinstance(k, bytes) else k): v
3073
 
                                  for k, v in
3074
 
                                  clients_data[key].items() }
3075
 
                        clients_data[key] = value
3076
 
                        # .client_structure
3077
 
                        value["client_structure"] = [
3078
 
                            (s.decode("utf-8")
3079
 
                             if isinstance(s, bytes)
3080
 
                             else s) for s in
3081
 
                            value["client_structure"] ]
3082
 
                        # .name & .host
3083
 
                        for k in ("name", "host"):
3084
 
                            if isinstance(value[k], bytes):
3085
 
                                value[k] = value[k].decode("utf-8")
3086
 
                    ## old_client_settings
3087
 
                    # .keys()
3088
 
                    old_client_settings = {
3089
 
                        (key.decode("utf-8")
3090
 
                         if isinstance(key, bytes)
3091
 
                         else key): value
3092
 
                        for key, value in
3093
 
                        bytes_old_client_settings.items() }
3094
 
                    del bytes_old_client_settings
3095
 
                    # .host
3096
 
                    for value in old_client_settings.values():
3097
 
                        if isinstance(value["host"], bytes):
3098
 
                            value["host"] = (value["host"]
3099
 
                                             .decode("utf-8"))
 
2617
                clients_data, old_client_settings = pickle.load(
 
2618
                    stored_state)
3100
2619
            os.remove(stored_state_path)
3101
2620
        except IOError as e:
3102
2621
            if e.errno == errno.ENOENT:
3135
2654
                    pass
3136
2655
            
3137
2656
            # Clients who has passed its expire date can still be
3138
 
            # enabled if its last checker was successful.  A Client
 
2657
            # enabled if its last checker was successful.  Clients
3139
2658
            # whose checker succeeded before we stored its state is
3140
2659
            # assumed to have successfully run all checkers during
3141
2660
            # downtime.
3193
2712
    
3194
2713
    if not foreground:
3195
2714
        if pidfile is not None:
3196
 
            pid = os.getpid()
3197
2715
            try:
3198
2716
                with pidfile:
3199
 
                    print(pid, file=pidfile)
 
2717
                    pid = os.getpid()
 
2718
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
3200
2719
            except IOError:
3201
2720
                logger.error("Could not write to file %r with PID %d",
3202
2721
                             pidfilename, pid)
3203
2722
        del pidfile
3204
2723
        del pidfilename
3205
2724
    
3206
 
    for termsig in (signal.SIGHUP, signal.SIGTERM):
3207
 
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, termsig,
3208
 
                             lambda: main_loop.quit() and False)
 
2725
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
 
2726
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
3209
2727
    
3210
2728
    if use_dbus:
3211
2729
        
3212
2730
        @alternate_dbus_interfaces(
3213
2731
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
3214
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2732
        class MandosDBusService(DBusObjectWithProperties):
3215
2733
            """A D-Bus proxy object"""
3216
2734
            
3217
2735
            def __init__(self):
3219
2737
            
3220
2738
            _interface = "se.recompile.Mandos"
3221
2739
            
 
2740
            @dbus_interface_annotations(_interface)
 
2741
            def _foo(self):
 
2742
                return {
 
2743
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2744
                    "false" }
 
2745
            
3222
2746
            @dbus.service.signal(_interface, signature="o")
3223
2747
            def ClientAdded(self, objpath):
3224
2748
                "D-Bus signal"
3229
2753
                "D-Bus signal"
3230
2754
                pass
3231
2755
            
3232
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3233
 
                               "true"})
3234
2756
            @dbus.service.signal(_interface, signature="os")
3235
2757
            def ClientRemoved(self, objpath, name):
3236
2758
                "D-Bus signal"
3237
2759
                pass
3238
2760
            
3239
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3240
 
                               "true"})
3241
2761
            @dbus.service.method(_interface, out_signature="ao")
3242
2762
            def GetAllClients(self):
3243
2763
                "D-Bus method"
3244
2764
                return dbus.Array(c.dbus_object_path for c in
3245
 
                                  tcp_server.clients.values())
 
2765
                                  tcp_server.clients.itervalues())
3246
2766
            
3247
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3248
 
                               "true"})
3249
2767
            @dbus.service.method(_interface,
3250
2768
                                 out_signature="a{oa{sv}}")
3251
2769
            def GetAllClientsWithProperties(self):
3252
2770
                "D-Bus method"
3253
2771
                return dbus.Dictionary(
3254
 
                    { c.dbus_object_path: c.GetAll(
3255
 
                        "se.recompile.Mandos.Client")
3256
 
                      for c in tcp_server.clients.values() },
 
2772
                    { c.dbus_object_path: c.GetAll("")
 
2773
                      for c in tcp_server.clients.itervalues() },
3257
2774
                    signature="oa{sv}")
3258
2775
            
3259
2776
            @dbus.service.method(_interface, in_signature="o")
3260
2777
            def RemoveClient(self, object_path):
3261
2778
                "D-Bus method"
3262
 
                for c in tcp_server.clients.values():
 
2779
                for c in tcp_server.clients.itervalues():
3263
2780
                    if c.dbus_object_path == object_path:
3264
2781
                        del tcp_server.clients[c.name]
3265
2782
                        c.remove_from_connection()
3266
 
                        # Don't signal the disabling
 
2783
                        # Don't signal anything except ClientRemoved
3267
2784
                        c.disable(quiet=True)
3268
 
                        # Emit D-Bus signal for removal
3269
 
                        self.client_removed_signal(c)
 
2785
                        # Emit D-Bus signal
 
2786
                        self.ClientRemoved(object_path, c.name)
3270
2787
                        return
3271
2788
                raise KeyError(object_path)
3272
2789
            
3273
2790
            del _interface
3274
 
            
3275
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3276
 
                                 out_signature = "a{oa{sa{sv}}}")
3277
 
            def GetManagedObjects(self):
3278
 
                """D-Bus method"""
3279
 
                return dbus.Dictionary(
3280
 
                    { client.dbus_object_path:
3281
 
                      dbus.Dictionary(
3282
 
                          { interface: client.GetAll(interface)
3283
 
                            for interface in
3284
 
                                 client._get_all_interface_names()})
3285
 
                      for client in tcp_server.clients.values()})
3286
 
            
3287
 
            def client_added_signal(self, client):
3288
 
                """Send the new standard signal and the old signal"""
3289
 
                if use_dbus:
3290
 
                    # New standard signal
3291
 
                    self.InterfacesAdded(
3292
 
                        client.dbus_object_path,
3293
 
                        dbus.Dictionary(
3294
 
                            { interface: client.GetAll(interface)
3295
 
                              for interface in
3296
 
                              client._get_all_interface_names()}))
3297
 
                    # Old signal
3298
 
                    self.ClientAdded(client.dbus_object_path)
3299
 
            
3300
 
            def client_removed_signal(self, client):
3301
 
                """Send the new standard signal and the old signal"""
3302
 
                if use_dbus:
3303
 
                    # New standard signal
3304
 
                    self.InterfacesRemoved(
3305
 
                        client.dbus_object_path,
3306
 
                        client._get_all_interface_names())
3307
 
                    # Old signal
3308
 
                    self.ClientRemoved(client.dbus_object_path,
3309
 
                                       client.name)
3310
2791
        
3311
2792
        mandos_dbus_service = MandosDBusService()
3312
2793
    
3313
 
    # Save modules to variables to exempt the modules from being
3314
 
    # unloaded before the function registered with atexit() is run.
3315
 
    mp = multiprocessing
3316
 
    wn = wnull
3317
2794
    def cleanup():
3318
2795
        "Cleanup function; run on exit"
3319
2796
        if zeroconf:
3320
2797
            service.cleanup()
3321
2798
        
3322
 
        mp.active_children()
3323
 
        wn.close()
 
2799
        multiprocessing.active_children()
 
2800
        wnull.close()
3324
2801
        if not (tcp_server.clients or client_settings):
3325
2802
            return
3326
2803
        
3329
2806
        # removed/edited, old secret will thus be unrecovable.
3330
2807
        clients = {}
3331
2808
        with PGPEngine() as pgp:
3332
 
            for client in tcp_server.clients.values():
 
2809
            for client in tcp_server.clients.itervalues():
3333
2810
                key = client_settings[client.name]["secret"]
3334
2811
                client.encrypted_secret = pgp.encrypt(client.secret,
3335
2812
                                                      key)
3359
2836
                    prefix='clients-',
3360
2837
                    dir=os.path.dirname(stored_state_path),
3361
2838
                    delete=False) as stored_state:
3362
 
                pickle.dump((clients, client_settings), stored_state,
3363
 
                            protocol = 2)
 
2839
                pickle.dump((clients, client_settings), stored_state)
3364
2840
                tempname = stored_state.name
3365
2841
            os.rename(tempname, stored_state_path)
3366
2842
        except (IOError, OSError) as e:
3382
2858
            name, client = tcp_server.clients.popitem()
3383
2859
            if use_dbus:
3384
2860
                client.remove_from_connection()
3385
 
            # Don't signal the disabling
 
2861
            # Don't signal anything except ClientRemoved
3386
2862
            client.disable(quiet=True)
3387
 
            # Emit D-Bus signal for removal
3388
2863
            if use_dbus:
3389
 
                mandos_dbus_service.client_removed_signal(client)
 
2864
                # Emit D-Bus signal
 
2865
                mandos_dbus_service.ClientRemoved(
 
2866
                    client.dbus_object_path, client.name)
3390
2867
        client_settings.clear()
3391
2868
    
3392
2869
    atexit.register(cleanup)
3393
2870
    
3394
 
    for client in tcp_server.clients.values():
 
2871
    for client in tcp_server.clients.itervalues():
3395
2872
        if use_dbus:
3396
 
            # Emit D-Bus signal for adding
3397
 
            mandos_dbus_service.client_added_signal(client)
 
2873
            # Emit D-Bus signal
 
2874
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3398
2875
        # Need to initiate checking of clients
3399
2876
        if client.enabled:
3400
2877
            client.init_checker()
3426
2903
                sys.exit(1)
3427
2904
            # End of Avahi example code
3428
2905
        
3429
 
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
3430
 
                          lambda *args, **kwargs:
3431
 
                          (tcp_server.handle_request
3432
 
                           (*args[2:], **kwargs) or True))
 
2906
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
 
2907
                             lambda *args, **kwargs:
 
2908
                             (tcp_server.handle_request
 
2909
                              (*args[2:], **kwargs) or True))
3433
2910
        
3434
2911
        logger.debug("Starting main loop")
3435
2912
        main_loop.run()