/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: 2012-05-12 15:45:57 UTC
  • Revision ID: teddy@recompile.se-20120512154557-r1yzcb8su8byp4us
* mandos (Client.enable, Client.disable, ClientDBus.approve): Call
                    self.send_changedstate() after change, not before.
  (Client.disable): Bug fix: Handle disable_initiator_tag and
                    checker_initiator_tag of 0.
  (Client.init_checker): Bug fix: Remove old checker_initiator_tag and
                         disable_initiator_tag, if any.
  (Client.bump_timeout): Bug fix: Remove old disable_initiator_tag, if
                         any.
  (ClientDBus.Timeout_dbus_property): Bug fix: Use self.expires.
  (ClientHandler.handle): Bug fix: timedelta_to_milliseconds is a
                          global function, not a class method.
* mandos-monitor (MandosClientWidget._update_timer_callback_lock):
  Removed.  All users changed.
  (MandosClientWidget.last_checked_ok): Removed (unused).
  (MandosClientWidget.__init__): Don't call self.using_timer().
  (MandosClientWidget.property_changed): Removed unused version.
  (MandosClientWidget.using_timer): Stop using the counter
                                    self._update_timer_callback_lock;
                                    be strictly boolean.
  (MandosClientWidget.need_approval): Don't call self.using_timer().
  (MandosClientWidget.update): Call self.using_timer() throughout.
                               Bug fix: Never show negative timers.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python2.7
 
1
#!/usr/bin/python
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-2015 Teddy Hogeborn
15
 
# Copyright © 2008-2015 Björn Påhlsson
 
14
# Copyright © 2008-2012 Teddy Hogeborn
 
15
# Copyright © 2008-2012 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
47
 
try:
48
 
    import ConfigParser as configparser
49
 
except ImportError:
50
 
    import configparser
 
44
import gnutls.crypto
 
45
import gnutls.connection
 
46
import gnutls.errors
 
47
import gnutls.library.functions
 
48
import gnutls.library.constants
 
49
import gnutls.library.types
 
50
import ConfigParser as configparser
51
51
import sys
52
52
import re
53
53
import os
62
62
import struct
63
63
import fcntl
64
64
import functools
65
 
try:
66
 
    import cPickle as pickle
67
 
except ImportError:
68
 
    import pickle
 
65
import cPickle as pickle
69
66
import multiprocessing
70
67
import types
71
68
import binascii
72
69
import tempfile
73
70
import itertools
74
 
import collections
75
 
import codecs
76
71
 
77
72
import dbus
78
73
import dbus.service
79
 
try:
80
 
    import gobject
81
 
except ImportError:
82
 
    from gi.repository import GObject as gobject
 
74
import gobject
83
75
import avahi
84
76
from dbus.mainloop.glib import DBusGMainLoop
85
77
import ctypes
86
78
import ctypes.util
87
79
import xml.dom.minidom
88
80
import inspect
 
81
import GnuPGInterface
89
82
 
90
83
try:
91
84
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
95
88
    except ImportError:
96
89
        SO_BINDTODEVICE = None
97
90
 
98
 
if sys.version_info.major == 2:
99
 
    str = unicode
100
 
 
101
 
version = "1.7.1"
 
91
version = "1.5.3"
102
92
stored_state_file = "clients.pickle"
103
93
 
104
94
logger = logging.getLogger()
105
 
syslogger = None
 
95
syslogger = (logging.handlers.SysLogHandler
 
96
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
              address = str("/dev/log")))
106
98
 
107
99
try:
108
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
109
 
        ctypes.util.find_library("c")).if_nametoindex
 
100
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
101
                      (ctypes.util.find_library("c"))
 
102
                      .if_nametoindex)
110
103
except (OSError, AttributeError):
111
 
    
112
104
    def if_nametoindex(interface):
113
105
        "Get an interface index the hard way, i.e. using fcntl()"
114
106
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
115
107
        with contextlib.closing(socket.socket()) as s:
116
108
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
117
 
                                struct.pack(b"16s16x", interface))
118
 
        interface_index = struct.unpack("I", ifreq[16:20])[0]
 
109
                                struct.pack(str("16s16x"),
 
110
                                            interface))
 
111
        interface_index = struct.unpack(str("I"),
 
112
                                        ifreq[16:20])[0]
119
113
        return interface_index
120
114
 
121
115
 
122
116
def initlogger(debug, level=logging.WARNING):
123
117
    """init logger and add loglevel"""
124
118
    
125
 
    global syslogger
126
 
    syslogger = (logging.handlers.SysLogHandler(
127
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
128
 
        address = "/dev/log"))
129
119
    syslogger.setFormatter(logging.Formatter
130
120
                           ('Mandos [%(process)d]: %(levelname)s:'
131
121
                            ' %(message)s'))
148
138
 
149
139
class PGPEngine(object):
150
140
    """A simple class for OpenPGP symmetric encryption & decryption"""
151
 
    
152
141
    def __init__(self):
 
142
        self.gnupg = GnuPGInterface.GnuPG()
153
143
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
154
 
        self.gnupgargs = ['--batch',
155
 
                          '--home', self.tempdir,
156
 
                          '--force-mdc',
157
 
                          '--quiet',
158
 
                          '--no-use-agent']
 
144
        self.gnupg = GnuPGInterface.GnuPG()
 
145
        self.gnupg.options.meta_interactive = False
 
146
        self.gnupg.options.homedir = self.tempdir
 
147
        self.gnupg.options.extra_args.extend(['--force-mdc',
 
148
                                              '--quiet',
 
149
                                              '--no-use-agent'])
159
150
    
160
151
    def __enter__(self):
161
152
        return self
162
153
    
163
 
    def __exit__(self, exc_type, exc_value, traceback):
 
154
    def __exit__ (self, exc_type, exc_value, traceback):
164
155
        self._cleanup()
165
156
        return False
166
157
    
183
174
    def password_encode(self, password):
184
175
        # Passphrase can not be empty and can not contain newlines or
185
176
        # NUL bytes.  So we prefix it and hex encode it.
186
 
        encoded = b"mandos" + binascii.hexlify(password)
187
 
        if len(encoded) > 2048:
188
 
            # GnuPG can't handle long passwords, so encode differently
189
 
            encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
190
 
                       .replace(b"\n", b"\\n")
191
 
                       .replace(b"\0", b"\\x00"))
192
 
        return encoded
 
177
        return b"mandos" + binascii.hexlify(password)
193
178
    
194
179
    def encrypt(self, data, password):
195
 
        passphrase = self.password_encode(password)
196
 
        with tempfile.NamedTemporaryFile(
197
 
                dir=self.tempdir) as passfile:
198
 
            passfile.write(passphrase)
199
 
            passfile.flush()
200
 
            proc = subprocess.Popen(['gpg', '--symmetric',
201
 
                                     '--passphrase-file',
202
 
                                     passfile.name]
203
 
                                    + self.gnupgargs,
204
 
                                    stdin = subprocess.PIPE,
205
 
                                    stdout = subprocess.PIPE,
206
 
                                    stderr = subprocess.PIPE)
207
 
            ciphertext, err = proc.communicate(input = data)
208
 
        if proc.returncode != 0:
209
 
            raise PGPError(err)
 
180
        self.gnupg.passphrase = self.password_encode(password)
 
181
        with open(os.devnull, "w") as devnull:
 
182
            try:
 
183
                proc = self.gnupg.run(['--symmetric'],
 
184
                                      create_fhs=['stdin', 'stdout'],
 
185
                                      attach_fhs={'stderr': devnull})
 
186
                with contextlib.closing(proc.handles['stdin']) as f:
 
187
                    f.write(data)
 
188
                with contextlib.closing(proc.handles['stdout']) as f:
 
189
                    ciphertext = f.read()
 
190
                proc.wait()
 
191
            except IOError as e:
 
192
                raise PGPError(e)
 
193
        self.gnupg.passphrase = None
210
194
        return ciphertext
211
195
    
212
196
    def decrypt(self, data, password):
213
 
        passphrase = self.password_encode(password)
214
 
        with tempfile.NamedTemporaryFile(
215
 
                dir = self.tempdir) as passfile:
216
 
            passfile.write(passphrase)
217
 
            passfile.flush()
218
 
            proc = subprocess.Popen(['gpg', '--decrypt',
219
 
                                     '--passphrase-file',
220
 
                                     passfile.name]
221
 
                                    + self.gnupgargs,
222
 
                                    stdin = subprocess.PIPE,
223
 
                                    stdout = subprocess.PIPE,
224
 
                                    stderr = subprocess.PIPE)
225
 
            decrypted_plaintext, err = proc.communicate(input = data)
226
 
        if proc.returncode != 0:
227
 
            raise PGPError(err)
 
197
        self.gnupg.passphrase = self.password_encode(password)
 
198
        with open(os.devnull, "w") as devnull:
 
199
            try:
 
200
                proc = self.gnupg.run(['--decrypt'],
 
201
                                      create_fhs=['stdin', 'stdout'],
 
202
                                      attach_fhs={'stderr': devnull})
 
203
                with contextlib.closing(proc.handles['stdin']) as f:
 
204
                    f.write(data)
 
205
                with contextlib.closing(proc.handles['stdout']) as f:
 
206
                    decrypted_plaintext = f.read()
 
207
                proc.wait()
 
208
            except IOError as e:
 
209
                raise PGPError(e)
 
210
        self.gnupg.passphrase = None
228
211
        return decrypted_plaintext
229
212
 
230
213
 
231
214
class AvahiError(Exception):
232
215
    def __init__(self, value, *args, **kwargs):
233
216
        self.value = value
234
 
        return super(AvahiError, self).__init__(value, *args,
235
 
                                                **kwargs)
236
 
 
 
217
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
218
    def __unicode__(self):
 
219
        return unicode(repr(self.value))
237
220
 
238
221
class AvahiServiceError(AvahiError):
239
222
    pass
240
223
 
241
 
 
242
224
class AvahiGroupError(AvahiError):
243
225
    pass
244
226
 
251
233
               Used to optionally bind to the specified interface.
252
234
    name: string; Example: 'Mandos'
253
235
    type: string; Example: '_mandos._tcp'.
254
 
     See <https://www.iana.org/assignments/service-names-port-numbers>
 
236
                  See <http://www.dns-sd.org/ServiceTypes.html>
255
237
    port: integer; what port to announce
256
238
    TXT: list of strings; TXT record for the service
257
239
    domain: string; Domain to publish on, default to .local if empty.
264
246
    bus: dbus.SystemBus()
265
247
    """
266
248
    
267
 
    def __init__(self,
268
 
                 interface = avahi.IF_UNSPEC,
269
 
                 name = None,
270
 
                 servicetype = None,
271
 
                 port = None,
272
 
                 TXT = None,
273
 
                 domain = "",
274
 
                 host = "",
275
 
                 max_renames = 32768,
276
 
                 protocol = avahi.PROTO_UNSPEC,
277
 
                 bus = None):
 
249
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
250
                 servicetype = None, port = None, TXT = None,
 
251
                 domain = "", host = "", max_renames = 32768,
 
252
                 protocol = avahi.PROTO_UNSPEC, bus = None):
278
253
        self.interface = interface
279
254
        self.name = name
280
255
        self.type = servicetype
290
265
        self.bus = bus
291
266
        self.entry_group_state_changed_match = None
292
267
    
293
 
    def rename(self, remove=True):
 
268
    def rename(self):
294
269
        """Derived from the Avahi example code"""
295
270
        if self.rename_count >= self.max_renames:
296
271
            logger.critical("No suitable Zeroconf service name found"
297
272
                            " after %i retries, exiting.",
298
273
                            self.rename_count)
299
274
            raise AvahiServiceError("Too many renames")
300
 
        self.name = str(
301
 
            self.server.GetAlternativeServiceName(self.name))
302
 
        self.rename_count += 1
 
275
        self.name = unicode(self.server
 
276
                            .GetAlternativeServiceName(self.name))
303
277
        logger.info("Changing Zeroconf service name to %r ...",
304
278
                    self.name)
305
 
        if remove:
306
 
            self.remove()
 
279
        self.remove()
307
280
        try:
308
281
            self.add()
309
282
        except dbus.exceptions.DBusException as error:
310
 
            if (error.get_dbus_name()
311
 
                == "org.freedesktop.Avahi.CollisionError"):
312
 
                logger.info("Local Zeroconf service name collision.")
313
 
                return self.rename(remove=False)
314
 
            else:
315
 
                logger.critical("D-Bus Exception", exc_info=error)
316
 
                self.cleanup()
317
 
                os._exit(1)
 
283
            logger.critical("D-Bus Exception", exc_info=error)
 
284
            self.cleanup()
 
285
            os._exit(1)
 
286
        self.rename_count += 1
318
287
    
319
288
    def remove(self):
320
289
        """Derived from the Avahi example code"""
358
327
            self.rename()
359
328
        elif state == avahi.ENTRY_GROUP_FAILURE:
360
329
            logger.critical("Avahi: Error in group state changed %s",
361
 
                            str(error))
362
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
330
                            unicode(error))
 
331
            raise AvahiGroupError("State changed: {0!s}"
 
332
                                  .format(error))
363
333
    
364
334
    def cleanup(self):
365
335
        """Derived from the Avahi example code"""
375
345
    def server_state_changed(self, state, error=None):
376
346
        """Derived from the Avahi example code"""
377
347
        logger.debug("Avahi server state change: %i", state)
378
 
        bad_states = {
379
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
380
 
            avahi.SERVER_REGISTERING: None,
381
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
382
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
383
 
        }
 
348
        bad_states = { avahi.SERVER_INVALID:
 
349
                           "Zeroconf server invalid",
 
350
                       avahi.SERVER_REGISTERING: None,
 
351
                       avahi.SERVER_COLLISION:
 
352
                           "Zeroconf server name collision",
 
353
                       avahi.SERVER_FAILURE:
 
354
                           "Zeroconf server failure" }
384
355
        if state in bad_states:
385
356
            if bad_states[state] is not None:
386
357
                if error is None:
389
360
                    logger.error(bad_states[state] + ": %r", error)
390
361
            self.cleanup()
391
362
        elif state == avahi.SERVER_RUNNING:
392
 
            try:
393
 
                self.add()
394
 
            except dbus.exceptions.DBusException as error:
395
 
                if (error.get_dbus_name()
396
 
                    == "org.freedesktop.Avahi.CollisionError"):
397
 
                    logger.info("Local Zeroconf service name"
398
 
                                " collision.")
399
 
                    return self.rename(remove=False)
400
 
                else:
401
 
                    logger.critical("D-Bus Exception", exc_info=error)
402
 
                    self.cleanup()
403
 
                    os._exit(1)
 
363
            self.add()
404
364
        else:
405
365
            if error is None:
406
366
                logger.debug("Unknown state: %r", state)
416
376
                                    follow_name_owner_changes=True),
417
377
                avahi.DBUS_INTERFACE_SERVER)
418
378
        self.server.connect_to_signal("StateChanged",
419
 
                                      self.server_state_changed)
 
379
                                 self.server_state_changed)
420
380
        self.server_state_changed(self.server.GetState())
421
381
 
422
 
 
423
382
class AvahiServiceToSyslog(AvahiService):
424
 
    def rename(self, *args, **kwargs):
 
383
    def rename(self):
425
384
        """Add the new name to the syslog messages"""
426
 
        ret = AvahiService.rename(self, *args, **kwargs)
427
 
        syslogger.setFormatter(logging.Formatter(
428
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
429
 
            .format(self.name)))
 
385
        ret = AvahiService.rename(self)
 
386
        syslogger.setFormatter(logging.Formatter
 
387
                               ('Mandos ({0}) [%(process)d]:'
 
388
                                ' %(levelname)s: %(message)s'
 
389
                                .format(self.name)))
430
390
        return ret
431
391
 
432
 
# Pretend that we have a GnuTLS module
433
 
class GnuTLS(object):
434
 
    """This isn't so much a class as it is a module-like namespace.
435
 
    It is instantiated once, and simulates having a GnuTLS module."""
436
 
    
437
 
    _library = ctypes.cdll.LoadLibrary(
438
 
        ctypes.util.find_library("gnutls"))
439
 
    _need_version = "3.3.0"
440
 
    def __init__(self):
441
 
        # Need to use class name "GnuTLS" here, since this method is
442
 
        # called before the assignment to the "gnutls" global variable
443
 
        # happens.
444
 
        if GnuTLS.check_version(self._need_version) is None:
445
 
            raise GnuTLS.Error("Needs GnuTLS {} or later"
446
 
                               .format(self._need_version))
447
 
    
448
 
    # Unless otherwise indicated, the constants and types below are
449
 
    # all from the gnutls/gnutls.h C header file.
450
 
    
451
 
    # Constants
452
 
    E_SUCCESS = 0
453
 
    CRT_OPENPGP = 2
454
 
    CLIENT = 2
455
 
    SHUT_RDWR = 0
456
 
    CRD_CERTIFICATE = 1
457
 
    E_NO_CERTIFICATE_FOUND = -49
458
 
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
459
 
    
460
 
    # Types
461
 
    class session_int(ctypes.Structure):
462
 
        _fields_ = []
463
 
    session_t = ctypes.POINTER(session_int)
464
 
    class certificate_credentials_st(ctypes.Structure):
465
 
        _fields_ = []
466
 
    certificate_credentials_t = ctypes.POINTER(
467
 
        certificate_credentials_st)
468
 
    certificate_type_t = ctypes.c_int
469
 
    class datum_t(ctypes.Structure):
470
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
471
 
                    ('size', ctypes.c_uint)]
472
 
    class openpgp_crt_int(ctypes.Structure):
473
 
        _fields_ = []
474
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
475
 
    openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
476
 
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
477
 
    credentials_type_t = ctypes.c_int # 
478
 
    transport_ptr_t = ctypes.c_void_p
479
 
    close_request_t = ctypes.c_int
480
 
    
481
 
    # Exceptions
482
 
    class Error(Exception):
483
 
        # We need to use the class name "GnuTLS" here, since this
484
 
        # exception might be raised from within GnuTLS.__init__,
485
 
        # which is called before the assignment to the "gnutls"
486
 
        # global variable happens.
487
 
        def __init__(self, message = None, code = None, args=()):
488
 
            # Default usage is by a message string, but if a return
489
 
            # code is passed, convert it to a string with
490
 
            # gnutls.strerror()
491
 
            if message is None and code is not None:
492
 
                message = GnuTLS.strerror(code)
493
 
            return super(GnuTLS.Error, self).__init__(
494
 
                message, *args)
495
 
    
496
 
    class CertificateSecurityError(Error):
497
 
        pass
498
 
    
499
 
    # Classes
500
 
    class Credentials(object):
501
 
        def __init__(self):
502
 
            self._c_object = gnutls.certificate_credentials_t()
503
 
            gnutls.certificate_allocate_credentials(
504
 
                ctypes.byref(self._c_object))
505
 
            self.type = gnutls.CRD_CERTIFICATE
506
 
        
507
 
        def __del__(self):
508
 
            gnutls.certificate_free_credentials(self._c_object)
509
 
    
510
 
    class ClientSession(object):
511
 
        def __init__(self, socket, credentials = None):
512
 
            self._c_object = gnutls.session_t()
513
 
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
514
 
            gnutls.set_default_priority(self._c_object)
515
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
516
 
            gnutls.handshake_set_private_extensions(self._c_object,
517
 
                                                    True)
518
 
            self.socket = socket
519
 
            if credentials is None:
520
 
                credentials = gnutls.Credentials()
521
 
            gnutls.credentials_set(self._c_object, credentials.type,
522
 
                                   ctypes.cast(credentials._c_object,
523
 
                                               ctypes.c_void_p))
524
 
            self.credentials = credentials
525
 
        
526
 
        def __del__(self):
527
 
            gnutls.deinit(self._c_object)
528
 
        
529
 
        def handshake(self):
530
 
            return gnutls.handshake(self._c_object)
531
 
        
532
 
        def send(self, data):
533
 
            data = bytes(data)
534
 
            if not data:
535
 
                return 0
536
 
            return gnutls.record_send(self._c_object, data, len(data))
537
 
        
538
 
        def bye(self):
539
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
540
 
    
541
 
    # Error handling function
542
 
    def _error_code(result):
543
 
        """A function to raise exceptions on errors, suitable
544
 
        for the 'restype' attribute on ctypes functions"""
545
 
        if result >= 0:
546
 
            return result
547
 
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
548
 
            raise gnutls.CertificateSecurityError(code = result)
549
 
        raise gnutls.Error(code = result)
550
 
    
551
 
    # Unless otherwise indicated, the function declarations below are
552
 
    # all from the gnutls/gnutls.h C header file.
553
 
    
554
 
    # Functions
555
 
    priority_set_direct = _library.gnutls_priority_set_direct
556
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
557
 
                                    ctypes.POINTER(ctypes.c_char_p)]
558
 
    priority_set_direct.restype = _error_code
559
 
    
560
 
    init = _library.gnutls_init
561
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
562
 
    init.restype = _error_code
563
 
    
564
 
    set_default_priority = _library.gnutls_set_default_priority
565
 
    set_default_priority.argtypes = [session_t]
566
 
    set_default_priority.restype = _error_code
567
 
    
568
 
    record_send = _library.gnutls_record_send
569
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
570
 
                            ctypes.c_size_t]
571
 
    record_send.restype = ctypes.c_ssize_t
572
 
    
573
 
    certificate_allocate_credentials = (
574
 
        _library.gnutls_certificate_allocate_credentials)
575
 
    certificate_allocate_credentials.argtypes = [
576
 
        ctypes.POINTER(certificate_credentials_t)]
577
 
    certificate_allocate_credentials.restype = _error_code
578
 
    
579
 
    certificate_free_credentials = (
580
 
        _library.gnutls_certificate_free_credentials)
581
 
    certificate_free_credentials.argtypes = [certificate_credentials_t]
582
 
    certificate_free_credentials.restype = None
583
 
    
584
 
    handshake_set_private_extensions = (
585
 
        _library.gnutls_handshake_set_private_extensions)
586
 
    handshake_set_private_extensions.argtypes = [session_t,
587
 
                                                 ctypes.c_int]
588
 
    handshake_set_private_extensions.restype = None
589
 
    
590
 
    credentials_set = _library.gnutls_credentials_set
591
 
    credentials_set.argtypes = [session_t, credentials_type_t,
592
 
                                ctypes.c_void_p]
593
 
    credentials_set.restype = _error_code
594
 
    
595
 
    strerror = _library.gnutls_strerror
596
 
    strerror.argtypes = [ctypes.c_int]
597
 
    strerror.restype = ctypes.c_char_p
598
 
    
599
 
    certificate_type_get = _library.gnutls_certificate_type_get
600
 
    certificate_type_get.argtypes = [session_t]
601
 
    certificate_type_get.restype = _error_code
602
 
    
603
 
    certificate_get_peers = _library.gnutls_certificate_get_peers
604
 
    certificate_get_peers.argtypes = [session_t,
605
 
                                      ctypes.POINTER(ctypes.c_uint)]
606
 
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
607
 
    
608
 
    global_set_log_level = _library.gnutls_global_set_log_level
609
 
    global_set_log_level.argtypes = [ctypes.c_int]
610
 
    global_set_log_level.restype = None
611
 
    
612
 
    global_set_log_function = _library.gnutls_global_set_log_function
613
 
    global_set_log_function.argtypes = [log_func]
614
 
    global_set_log_function.restype = None
615
 
    
616
 
    deinit = _library.gnutls_deinit
617
 
    deinit.argtypes = [session_t]
618
 
    deinit.restype = None
619
 
    
620
 
    handshake = _library.gnutls_handshake
621
 
    handshake.argtypes = [session_t]
622
 
    handshake.restype = _error_code
623
 
    
624
 
    transport_set_ptr = _library.gnutls_transport_set_ptr
625
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
626
 
    transport_set_ptr.restype = None
627
 
    
628
 
    bye = _library.gnutls_bye
629
 
    bye.argtypes = [session_t, close_request_t]
630
 
    bye.restype = _error_code
631
 
    
632
 
    check_version = _library.gnutls_check_version
633
 
    check_version.argtypes = [ctypes.c_char_p]
634
 
    check_version.restype = ctypes.c_char_p
635
 
    
636
 
    # All the function declarations below are from gnutls/openpgp.h
637
 
    
638
 
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
639
 
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
640
 
    openpgp_crt_init.restype = _error_code
641
 
    
642
 
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
643
 
    openpgp_crt_import.argtypes = [openpgp_crt_t,
644
 
                                   ctypes.POINTER(datum_t),
645
 
                                   openpgp_crt_fmt_t]
646
 
    openpgp_crt_import.restype = _error_code
647
 
    
648
 
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
649
 
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
650
 
                                        ctypes.POINTER(ctypes.c_uint)]
651
 
    openpgp_crt_verify_self.restype = _error_code
652
 
    
653
 
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
654
 
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
655
 
    openpgp_crt_deinit.restype = None
656
 
    
657
 
    openpgp_crt_get_fingerprint = (
658
 
        _library.gnutls_openpgp_crt_get_fingerprint)
659
 
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
660
 
                                            ctypes.c_void_p,
661
 
                                            ctypes.POINTER(
662
 
                                                ctypes.c_size_t)]
663
 
    openpgp_crt_get_fingerprint.restype = _error_code
664
 
    
665
 
    # Remove non-public function
666
 
    del _error_code
667
 
# Create the global "gnutls" object, simulating a module
668
 
gnutls = GnuTLS()
669
 
 
670
 
def call_pipe(connection,       # : multiprocessing.Connection
671
 
              func, *args, **kwargs):
672
 
    """This function is meant to be called by multiprocessing.Process
673
 
    
674
 
    This function runs func(*args, **kwargs), and writes the resulting
675
 
    return value on the provided multiprocessing.Connection.
676
 
    """
677
 
    connection.send(func(*args, **kwargs))
678
 
    connection.close()
 
392
def timedelta_to_milliseconds(td):
 
393
    "Convert a datetime.timedelta() to milliseconds"
 
394
    return ((td.days * 24 * 60 * 60 * 1000)
 
395
            + (td.seconds * 1000)
 
396
            + (td.microseconds // 1000))
679
397
 
680
398
class Client(object):
681
399
    """A representation of a client host served by this server.
708
426
    last_checker_status: integer between 0 and 255 reflecting exit
709
427
                         status of last checker. -1 reflects crashed
710
428
                         checker, -2 means no checker completed yet.
711
 
    last_checker_signal: The signal which killed the last checker, if
712
 
                         last_checker_status is -1
713
429
    last_enabled: datetime.datetime(); (UTC) or None
714
430
    name:       string; from the config file, used in log messages and
715
431
                        D-Bus identifiers
720
436
    runtime_expansions: Allowed attributes for runtime expansion.
721
437
    expires:    datetime.datetime(); time (UTC) when a client will be
722
438
                disabled, or None
723
 
    server_settings: The server_settings dict from main()
724
439
    """
725
440
    
726
441
    runtime_expansions = ("approval_delay", "approval_duration",
727
 
                          "created", "enabled", "expires",
728
 
                          "fingerprint", "host", "interval",
729
 
                          "last_approval_request", "last_checked_ok",
 
442
                          "created", "enabled", "fingerprint",
 
443
                          "host", "interval", "last_checked_ok",
730
444
                          "last_enabled", "name", "timeout")
731
 
    client_defaults = {
732
 
        "timeout": "PT5M",
733
 
        "extended_timeout": "PT15M",
734
 
        "interval": "PT2M",
735
 
        "checker": "fping -q -- %%(host)s",
736
 
        "host": "",
737
 
        "approval_delay": "PT0S",
738
 
        "approval_duration": "PT1S",
739
 
        "approved_by_default": "True",
740
 
        "enabled": "True",
741
 
    }
 
445
    client_defaults = { "timeout": "5m",
 
446
                        "extended_timeout": "15m",
 
447
                        "interval": "2m",
 
448
                        "checker": "fping -q -- %%(host)s",
 
449
                        "host": "",
 
450
                        "approval_delay": "0s",
 
451
                        "approval_duration": "1s",
 
452
                        "approved_by_default": "True",
 
453
                        "enabled": "True",
 
454
                        }
 
455
    
 
456
    def timeout_milliseconds(self):
 
457
        "Return the 'timeout' attribute in milliseconds"
 
458
        return timedelta_to_milliseconds(self.timeout)
 
459
    
 
460
    def extended_timeout_milliseconds(self):
 
461
        "Return the 'extended_timeout' attribute in milliseconds"
 
462
        return timedelta_to_milliseconds(self.extended_timeout)
 
463
    
 
464
    def interval_milliseconds(self):
 
465
        "Return the 'interval' attribute in milliseconds"
 
466
        return timedelta_to_milliseconds(self.interval)
 
467
    
 
468
    def approval_delay_milliseconds(self):
 
469
        return timedelta_to_milliseconds(self.approval_delay)
742
470
    
743
471
    @staticmethod
744
472
    def config_parser(config):
760
488
            client["enabled"] = config.getboolean(client_name,
761
489
                                                  "enabled")
762
490
            
763
 
            # Uppercase and remove spaces from fingerprint for later
764
 
            # comparison purposes with return value from the
765
 
            # fingerprint() function
766
491
            client["fingerprint"] = (section["fingerprint"].upper()
767
492
                                     .replace(" ", ""))
768
493
            if "secret" in section:
773
498
                          "rb") as secfile:
774
499
                    client["secret"] = secfile.read()
775
500
            else:
776
 
                raise TypeError("No secret or secfile for section {}"
 
501
                raise TypeError("No secret or secfile for section {0}"
777
502
                                .format(section))
778
503
            client["timeout"] = string_to_delta(section["timeout"])
779
504
            client["extended_timeout"] = string_to_delta(
790
515
        
791
516
        return settings
792
517
    
793
 
    def __init__(self, settings, name = None, server_settings=None):
 
518
    def __init__(self, settings, name = None):
794
519
        self.name = name
795
 
        if server_settings is None:
796
 
            server_settings = {}
797
 
        self.server_settings = server_settings
798
520
        # adding all client settings
799
 
        for setting, value in settings.items():
 
521
        for setting, value in settings.iteritems():
800
522
            setattr(self, setting, value)
801
523
        
802
524
        if self.enabled:
810
532
            self.expires = None
811
533
        
812
534
        logger.debug("Creating client %r", self.name)
 
535
        # Uppercase and remove spaces from fingerprint for later
 
536
        # comparison purposes with return value from the fingerprint()
 
537
        # function
813
538
        logger.debug("  Fingerprint: %s", self.fingerprint)
814
539
        self.created = settings.get("created",
815
540
                                    datetime.datetime.utcnow())
822
547
        self.current_checker_command = None
823
548
        self.approved = None
824
549
        self.approvals_pending = 0
825
 
        self.changedstate = multiprocessing_manager.Condition(
826
 
            multiprocessing_manager.Lock())
827
 
        self.client_structure = [attr
828
 
                                 for attr in self.__dict__.iterkeys()
 
550
        self.changedstate = (multiprocessing_manager
 
551
                             .Condition(multiprocessing_manager
 
552
                                        .Lock()))
 
553
        self.client_structure = [attr for attr in
 
554
                                 self.__dict__.iterkeys()
829
555
                                 if not attr.startswith("_")]
830
556
        self.client_structure.append("client_structure")
831
557
        
832
 
        for name, t in inspect.getmembers(
833
 
                type(self), lambda obj: isinstance(obj, property)):
 
558
        for name, t in inspect.getmembers(type(self),
 
559
                                          lambda obj:
 
560
                                              isinstance(obj,
 
561
                                                         property)):
834
562
            if not name.startswith("_"):
835
563
                self.client_structure.append(name)
836
564
    
878
606
        # and every interval from then on.
879
607
        if self.checker_initiator_tag is not None:
880
608
            gobject.source_remove(self.checker_initiator_tag)
881
 
        self.checker_initiator_tag = gobject.timeout_add(
882
 
            int(self.interval.total_seconds() * 1000),
883
 
            self.start_checker)
 
609
        self.checker_initiator_tag = (gobject.timeout_add
 
610
                                      (self.interval_milliseconds(),
 
611
                                       self.start_checker))
884
612
        # Schedule a disable() when 'timeout' has passed
885
613
        if self.disable_initiator_tag is not None:
886
614
            gobject.source_remove(self.disable_initiator_tag)
887
 
        self.disable_initiator_tag = gobject.timeout_add(
888
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
615
        self.disable_initiator_tag = (gobject.timeout_add
 
616
                                   (self.timeout_milliseconds(),
 
617
                                    self.disable))
889
618
        # Also start a new checker *right now*.
890
619
        self.start_checker()
891
620
    
892
 
    def checker_callback(self, source, condition, connection,
893
 
                         command):
 
621
    def checker_callback(self, pid, condition, command):
894
622
        """The checker has completed, so take appropriate actions."""
895
623
        self.checker_callback_tag = None
896
624
        self.checker = None
897
 
        # Read return code from connection (see call_pipe)
898
 
        returncode = connection.recv()
899
 
        connection.close()
900
 
        
901
 
        if returncode >= 0:
902
 
            self.last_checker_status = returncode
903
 
            self.last_checker_signal = None
 
625
        if os.WIFEXITED(condition):
 
626
            self.last_checker_status = os.WEXITSTATUS(condition)
904
627
            if self.last_checker_status == 0:
905
628
                logger.info("Checker for %(name)s succeeded",
906
629
                            vars(self))
907
630
                self.checked_ok()
908
631
            else:
909
 
                logger.info("Checker for %(name)s failed", vars(self))
 
632
                logger.info("Checker for %(name)s failed",
 
633
                            vars(self))
910
634
        else:
911
635
            self.last_checker_status = -1
912
 
            self.last_checker_signal = -returncode
913
636
            logger.warning("Checker for %(name)s crashed?",
914
637
                           vars(self))
915
 
        return False
916
638
    
917
639
    def checked_ok(self):
918
640
        """Assert that the client has been seen, alive and well."""
919
641
        self.last_checked_ok = datetime.datetime.utcnow()
920
642
        self.last_checker_status = 0
921
 
        self.last_checker_signal = None
922
643
        self.bump_timeout()
923
644
    
924
645
    def bump_timeout(self, timeout=None):
929
650
            gobject.source_remove(self.disable_initiator_tag)
930
651
            self.disable_initiator_tag = None
931
652
        if getattr(self, "enabled", False):
932
 
            self.disable_initiator_tag = gobject.timeout_add(
933
 
                int(timeout.total_seconds() * 1000), self.disable)
 
653
            self.disable_initiator_tag = (gobject.timeout_add
 
654
                                          (timedelta_to_milliseconds
 
655
                                           (timeout), self.disable))
934
656
            self.expires = datetime.datetime.utcnow() + timeout
935
657
    
936
658
    def need_approval(self):
950
672
        # than 'timeout' for the client to be disabled, which is as it
951
673
        # should be.
952
674
        
953
 
        if self.checker is not None and not self.checker.is_alive():
954
 
            logger.warning("Checker was not alive; joining")
955
 
            self.checker.join()
956
 
            self.checker = None
 
675
        # If a checker exists, make sure it is not a zombie
 
676
        try:
 
677
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
678
        except (AttributeError, OSError) as error:
 
679
            if (isinstance(error, OSError)
 
680
                and error.errno != errno.ECHILD):
 
681
                raise error
 
682
        else:
 
683
            if pid:
 
684
                logger.warning("Checker was a zombie")
 
685
                gobject.source_remove(self.checker_callback_tag)
 
686
                self.checker_callback(pid, status,
 
687
                                      self.current_checker_command)
957
688
        # Start a new checker if needed
958
689
        if self.checker is None:
959
 
            # Escape attributes for the shell
960
 
            escaped_attrs = {
961
 
                attr: re.escape(str(getattr(self, attr)))
962
 
                for attr in self.runtime_expansions }
963
 
            try:
964
 
                command = self.checker_command % escaped_attrs
965
 
            except TypeError as error:
966
 
                logger.error('Could not format string "%s"',
967
 
                             self.checker_command,
 
690
            try:
 
691
                # In case checker_command has exactly one % operator
 
692
                command = self.checker_command % self.host
 
693
            except TypeError:
 
694
                # Escape attributes for the shell
 
695
                escaped_attrs = dict(
 
696
                    (attr,
 
697
                     re.escape(unicode(str(getattr(self, attr, "")),
 
698
                                       errors=
 
699
                                       'replace')))
 
700
                    for attr in
 
701
                    self.runtime_expansions)
 
702
                
 
703
                try:
 
704
                    command = self.checker_command % escaped_attrs
 
705
                except TypeError as error:
 
706
                    logger.error('Could not format string "%s"',
 
707
                                 self.checker_command, exc_info=error)
 
708
                    return True # Try again later
 
709
            self.current_checker_command = command
 
710
            try:
 
711
                logger.info("Starting checker %r for %s",
 
712
                            command, self.name)
 
713
                # We don't need to redirect stdout and stderr, since
 
714
                # in normal mode, that is already done by daemon(),
 
715
                # and in debug mode we don't want to.  (Stdin is
 
716
                # always replaced by /dev/null.)
 
717
                self.checker = subprocess.Popen(command,
 
718
                                                close_fds=True,
 
719
                                                shell=True, cwd="/")
 
720
                self.checker_callback_tag = (gobject.child_watch_add
 
721
                                             (self.checker.pid,
 
722
                                              self.checker_callback,
 
723
                                              data=command))
 
724
                # The checker may have completed before the gobject
 
725
                # watch was added.  Check for this.
 
726
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
727
                if pid:
 
728
                    gobject.source_remove(self.checker_callback_tag)
 
729
                    self.checker_callback(pid, status, command)
 
730
            except OSError as error:
 
731
                logger.error("Failed to start subprocess",
968
732
                             exc_info=error)
969
 
                return True     # Try again later
970
 
            self.current_checker_command = command
971
 
            logger.info("Starting checker %r for %s", command,
972
 
                        self.name)
973
 
            # We don't need to redirect stdout and stderr, since
974
 
            # in normal mode, that is already done by daemon(),
975
 
            # and in debug mode we don't want to.  (Stdin is
976
 
            # always replaced by /dev/null.)
977
 
            # The exception is when not debugging but nevertheless
978
 
            # running in the foreground; use the previously
979
 
            # created wnull.
980
 
            popen_args = { "close_fds": True,
981
 
                           "shell": True,
982
 
                           "cwd": "/" }
983
 
            if (not self.server_settings["debug"]
984
 
                and self.server_settings["foreground"]):
985
 
                popen_args.update({"stdout": wnull,
986
 
                                   "stderr": wnull })
987
 
            pipe = multiprocessing.Pipe(duplex = False)
988
 
            self.checker = multiprocessing.Process(
989
 
                target = call_pipe,
990
 
                args = (pipe[1], subprocess.call, command),
991
 
                kwargs = popen_args)
992
 
            self.checker.start()
993
 
            self.checker_callback_tag = gobject.io_add_watch(
994
 
                pipe[0].fileno(), gobject.IO_IN,
995
 
                self.checker_callback, pipe[0], command)
996
733
        # Re-run this periodically if run by gobject.timeout_add
997
734
        return True
998
735
    
1004
741
        if getattr(self, "checker", None) is None:
1005
742
            return
1006
743
        logger.debug("Stopping checker for %(name)s", vars(self))
1007
 
        self.checker.terminate()
 
744
        try:
 
745
            self.checker.terminate()
 
746
            #time.sleep(0.5)
 
747
            #if self.checker.poll() is None:
 
748
            #    self.checker.kill()
 
749
        except OSError as error:
 
750
            if error.errno != errno.ESRCH: # No such process
 
751
                raise
1008
752
        self.checker = None
1009
753
 
1010
754
 
1011
 
def dbus_service_property(dbus_interface,
1012
 
                          signature="v",
1013
 
                          access="readwrite",
1014
 
                          byte_arrays=False):
 
755
def dbus_service_property(dbus_interface, signature="v",
 
756
                          access="readwrite", byte_arrays=False):
1015
757
    """Decorators for marking methods of a DBusObjectWithProperties to
1016
758
    become properties on the D-Bus.
1017
759
    
1026
768
    # "Set" method, so we fail early here:
1027
769
    if byte_arrays and signature != "ay":
1028
770
        raise ValueError("Byte arrays not supported for non-'ay'"
1029
 
                         " signature {!r}".format(signature))
1030
 
    
 
771
                         " signature {0!r}".format(signature))
1031
772
    def decorator(func):
1032
773
        func._dbus_is_property = True
1033
774
        func._dbus_interface = dbus_interface
1038
779
            func._dbus_name = func._dbus_name[:-14]
1039
780
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
1040
781
        return func
1041
 
    
1042
782
    return decorator
1043
783
 
1044
784
 
1053
793
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
1054
794
                    "false"}
1055
795
    """
1056
 
    
1057
796
    def decorator(func):
1058
797
        func._dbus_is_interface = True
1059
798
        func._dbus_interface = dbus_interface
1060
799
        func._dbus_name = dbus_interface
1061
800
        return func
1062
 
    
1063
801
    return decorator
1064
802
 
1065
803
 
1067
805
    """Decorator to annotate D-Bus methods, signals or properties
1068
806
    Usage:
1069
807
    
1070
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
1071
 
                       "org.freedesktop.DBus.Property."
1072
 
                       "EmitsChangedSignal": "false"})
1073
808
    @dbus_service_property("org.example.Interface", signature="b",
1074
809
                           access="r")
 
810
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
811
                        "org.freedesktop.DBus.Property."
 
812
                        "EmitsChangedSignal": "false"})
1075
813
    def Property_dbus_property(self):
1076
814
        return dbus.Boolean(False)
1077
 
    
1078
 
    See also the DBusObjectWithAnnotations class.
1079
815
    """
1080
 
    
1081
816
    def decorator(func):
1082
817
        func._dbus_annotations = annotations
1083
818
        return func
1084
 
    
1085
819
    return decorator
1086
820
 
1087
821
 
1088
822
class DBusPropertyException(dbus.exceptions.DBusException):
1089
823
    """A base class for D-Bus property-related exceptions
1090
824
    """
1091
 
    pass
 
825
    def __unicode__(self):
 
826
        return unicode(str(self))
1092
827
 
1093
828
 
1094
829
class DBusPropertyAccessException(DBusPropertyException):
1103
838
    pass
1104
839
 
1105
840
 
1106
 
class DBusObjectWithAnnotations(dbus.service.Object):
1107
 
    """A D-Bus object with annotations.
 
841
class DBusObjectWithProperties(dbus.service.Object):
 
842
    """A D-Bus object with properties.
1108
843
    
1109
 
    Classes inheriting from this can use the dbus_annotations
1110
 
    decorator to add annotations to methods or signals.
 
844
    Classes inheriting from this can use the dbus_service_property
 
845
    decorator to expose methods as D-Bus properties.  It exposes the
 
846
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1111
847
    """
1112
848
    
1113
849
    @staticmethod
1117
853
        If called like _is_dbus_thing("method") it returns a function
1118
854
        suitable for use as predicate to inspect.getmembers().
1119
855
        """
1120
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
856
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
1121
857
                                   False)
1122
858
    
1123
859
    def _get_all_dbus_things(self, thing):
1124
860
        """Returns a generator of (name, attribute) pairs
1125
861
        """
1126
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
862
        return ((getattr(athing.__get__(self), "_dbus_name",
 
863
                         name),
1127
864
                 athing.__get__(self))
1128
865
                for cls in self.__class__.__mro__
1129
866
                for name, athing in
1130
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
1131
 
    
1132
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1133
 
                         out_signature = "s",
1134
 
                         path_keyword = 'object_path',
1135
 
                         connection_keyword = 'connection')
1136
 
    def Introspect(self, object_path, connection):
1137
 
        """Overloading of standard D-Bus method.
1138
 
        
1139
 
        Inserts annotation tags on methods and signals.
1140
 
        """
1141
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
1142
 
                                                   connection)
1143
 
        try:
1144
 
            document = xml.dom.minidom.parseString(xmlstring)
1145
 
            
1146
 
            for if_tag in document.getElementsByTagName("interface"):
1147
 
                # Add annotation tags
1148
 
                for typ in ("method", "signal"):
1149
 
                    for tag in if_tag.getElementsByTagName(typ):
1150
 
                        annots = dict()
1151
 
                        for name, prop in (self.
1152
 
                                           _get_all_dbus_things(typ)):
1153
 
                            if (name == tag.getAttribute("name")
1154
 
                                and prop._dbus_interface
1155
 
                                == if_tag.getAttribute("name")):
1156
 
                                annots.update(getattr(
1157
 
                                    prop, "_dbus_annotations", {}))
1158
 
                        for name, value in annots.items():
1159
 
                            ann_tag = document.createElement(
1160
 
                                "annotation")
1161
 
                            ann_tag.setAttribute("name", name)
1162
 
                            ann_tag.setAttribute("value", value)
1163
 
                            tag.appendChild(ann_tag)
1164
 
                # Add interface annotation tags
1165
 
                for annotation, value in dict(
1166
 
                    itertools.chain.from_iterable(
1167
 
                        annotations().items()
1168
 
                        for name, annotations
1169
 
                        in self._get_all_dbus_things("interface")
1170
 
                        if name == if_tag.getAttribute("name")
1171
 
                        )).items():
1172
 
                    ann_tag = document.createElement("annotation")
1173
 
                    ann_tag.setAttribute("name", annotation)
1174
 
                    ann_tag.setAttribute("value", value)
1175
 
                    if_tag.appendChild(ann_tag)
1176
 
                # Fix argument name for the Introspect method itself
1177
 
                if (if_tag.getAttribute("name")
1178
 
                                == dbus.INTROSPECTABLE_IFACE):
1179
 
                    for cn in if_tag.getElementsByTagName("method"):
1180
 
                        if cn.getAttribute("name") == "Introspect":
1181
 
                            for arg in cn.getElementsByTagName("arg"):
1182
 
                                if (arg.getAttribute("direction")
1183
 
                                    == "out"):
1184
 
                                    arg.setAttribute("name",
1185
 
                                                     "xml_data")
1186
 
            xmlstring = document.toxml("utf-8")
1187
 
            document.unlink()
1188
 
        except (AttributeError, xml.dom.DOMException,
1189
 
                xml.parsers.expat.ExpatError) as error:
1190
 
            logger.error("Failed to override Introspection method",
1191
 
                         exc_info=error)
1192
 
        return xmlstring
1193
 
 
1194
 
 
1195
 
class DBusObjectWithProperties(DBusObjectWithAnnotations):
1196
 
    """A D-Bus object with properties.
1197
 
    
1198
 
    Classes inheriting from this can use the dbus_service_property
1199
 
    decorator to expose methods as D-Bus properties.  It exposes the
1200
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1201
 
    """
 
867
                inspect.getmembers(cls,
 
868
                                   self._is_dbus_thing(thing)))
1202
869
    
1203
870
    def _get_dbus_property(self, interface_name, property_name):
1204
871
        """Returns a bound method if one exists which is a D-Bus
1205
872
        property with the specified name and interface.
1206
873
        """
1207
 
        for cls in self.__class__.__mro__:
1208
 
            for name, value in inspect.getmembers(
1209
 
                    cls, self._is_dbus_thing("property")):
 
874
        for cls in  self.__class__.__mro__:
 
875
            for name, value in (inspect.getmembers
 
876
                                (cls,
 
877
                                 self._is_dbus_thing("property"))):
1210
878
                if (value._dbus_name == property_name
1211
879
                    and value._dbus_interface == interface_name):
1212
880
                    return value.__get__(self)
1213
881
        
1214
882
        # No such property
1215
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
1216
 
            self.dbus_object_path, interface_name, property_name))
1217
 
    
1218
 
    @classmethod
1219
 
    def _get_all_interface_names(cls):
1220
 
        """Get a sequence of all interfaces supported by an object"""
1221
 
        return (name for name in set(getattr(getattr(x, attr),
1222
 
                                             "_dbus_interface", None)
1223
 
                                     for x in (inspect.getmro(cls))
1224
 
                                     for attr in dir(x))
1225
 
                if name is not None)
1226
 
    
1227
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1228
 
                         in_signature="ss",
 
883
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
884
                                   + interface_name + "."
 
885
                                   + property_name)
 
886
    
 
887
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
1229
888
                         out_signature="v")
1230
889
    def Get(self, interface_name, property_name):
1231
890
        """Standard D-Bus property Get() method, see D-Bus standard.
1249
908
            # The byte_arrays option is not supported yet on
1250
909
            # signatures other than "ay".
1251
910
            if prop._dbus_signature != "ay":
1252
 
                raise ValueError("Byte arrays not supported for non-"
1253
 
                                 "'ay' signature {!r}"
1254
 
                                 .format(prop._dbus_signature))
 
911
                raise ValueError
1255
912
            value = dbus.ByteArray(b''.join(chr(byte)
1256
913
                                            for byte in value))
1257
914
        prop(value)
1258
915
    
1259
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1260
 
                         in_signature="s",
 
916
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
1261
917
                         out_signature="a{sv}")
1262
918
    def GetAll(self, interface_name):
1263
919
        """Standard D-Bus property GetAll() method, see D-Bus
1278
934
            if not hasattr(value, "variant_level"):
1279
935
                properties[name] = value
1280
936
                continue
1281
 
            properties[name] = type(value)(
1282
 
                value, variant_level = value.variant_level + 1)
 
937
            properties[name] = type(value)(value, variant_level=
 
938
                                           value.variant_level+1)
1283
939
        return dbus.Dictionary(properties, signature="sv")
1284
940
    
1285
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
1286
 
    def PropertiesChanged(self, interface_name, changed_properties,
1287
 
                          invalidated_properties):
1288
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
1289
 
        standard.
1290
 
        """
1291
 
        pass
1292
 
    
1293
941
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1294
942
                         out_signature="s",
1295
943
                         path_keyword='object_path',
1299
947
        
1300
948
        Inserts property tags and interface annotation tags.
1301
949
        """
1302
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1303
 
                                                         object_path,
1304
 
                                                         connection)
 
950
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
951
                                                   connection)
1305
952
        try:
1306
953
            document = xml.dom.minidom.parseString(xmlstring)
1307
 
            
1308
954
            def make_tag(document, name, prop):
1309
955
                e = document.createElement("property")
1310
956
                e.setAttribute("name", name)
1311
957
                e.setAttribute("type", prop._dbus_signature)
1312
958
                e.setAttribute("access", prop._dbus_access)
1313
959
                return e
1314
 
            
1315
960
            for if_tag in document.getElementsByTagName("interface"):
1316
961
                # Add property tags
1317
962
                for tag in (make_tag(document, name, prop)
1320
965
                            if prop._dbus_interface
1321
966
                            == if_tag.getAttribute("name")):
1322
967
                    if_tag.appendChild(tag)
1323
 
                # Add annotation tags for properties
1324
 
                for tag in if_tag.getElementsByTagName("property"):
1325
 
                    annots = dict()
1326
 
                    for name, prop in self._get_all_dbus_things(
1327
 
                            "property"):
1328
 
                        if (name == tag.getAttribute("name")
1329
 
                            and prop._dbus_interface
1330
 
                            == if_tag.getAttribute("name")):
1331
 
                            annots.update(getattr(
1332
 
                                prop, "_dbus_annotations", {}))
1333
 
                    for name, value in annots.items():
1334
 
                        ann_tag = document.createElement(
1335
 
                            "annotation")
1336
 
                        ann_tag.setAttribute("name", name)
1337
 
                        ann_tag.setAttribute("value", value)
1338
 
                        tag.appendChild(ann_tag)
 
968
                # Add annotation tags
 
969
                for typ in ("method", "signal", "property"):
 
970
                    for tag in if_tag.getElementsByTagName(typ):
 
971
                        annots = dict()
 
972
                        for name, prop in (self.
 
973
                                           _get_all_dbus_things(typ)):
 
974
                            if (name == tag.getAttribute("name")
 
975
                                and prop._dbus_interface
 
976
                                == if_tag.getAttribute("name")):
 
977
                                annots.update(getattr
 
978
                                              (prop,
 
979
                                               "_dbus_annotations",
 
980
                                               {}))
 
981
                        for name, value in annots.iteritems():
 
982
                            ann_tag = document.createElement(
 
983
                                "annotation")
 
984
                            ann_tag.setAttribute("name", name)
 
985
                            ann_tag.setAttribute("value", value)
 
986
                            tag.appendChild(ann_tag)
 
987
                # Add interface annotation tags
 
988
                for annotation, value in dict(
 
989
                    itertools.chain.from_iterable(
 
990
                        annotations().iteritems()
 
991
                        for name, annotations in
 
992
                        self._get_all_dbus_things("interface")
 
993
                        if name == if_tag.getAttribute("name")
 
994
                        )).iteritems():
 
995
                    ann_tag = document.createElement("annotation")
 
996
                    ann_tag.setAttribute("name", annotation)
 
997
                    ann_tag.setAttribute("value", value)
 
998
                    if_tag.appendChild(ann_tag)
1339
999
                # Add the names to the return values for the
1340
1000
                # "org.freedesktop.DBus.Properties" methods
1341
1001
                if (if_tag.getAttribute("name")
1359
1019
                         exc_info=error)
1360
1020
        return xmlstring
1361
1021
 
1362
 
try:
1363
 
    dbus.OBJECT_MANAGER_IFACE
1364
 
except AttributeError:
1365
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1366
 
 
1367
 
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1368
 
    """A D-Bus object with an ObjectManager.
1369
 
    
1370
 
    Classes inheriting from this exposes the standard
1371
 
    GetManagedObjects call and the InterfacesAdded and
1372
 
    InterfacesRemoved signals on the standard
1373
 
    "org.freedesktop.DBus.ObjectManager" interface.
1374
 
    
1375
 
    Note: No signals are sent automatically; they must be sent
1376
 
    manually.
1377
 
    """
1378
 
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1379
 
                         out_signature = "a{oa{sa{sv}}}")
1380
 
    def GetManagedObjects(self):
1381
 
        """This function must be overridden"""
1382
 
        raise NotImplementedError()
1383
 
    
1384
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1385
 
                         signature = "oa{sa{sv}}")
1386
 
    def InterfacesAdded(self, object_path, interfaces_and_properties):
1387
 
        pass
1388
 
    
1389
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1390
 
    def InterfacesRemoved(self, object_path, interfaces):
1391
 
        pass
1392
 
    
1393
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1394
 
                         out_signature = "s",
1395
 
                         path_keyword = 'object_path',
1396
 
                         connection_keyword = 'connection')
1397
 
    def Introspect(self, object_path, connection):
1398
 
        """Overloading of standard D-Bus method.
1399
 
        
1400
 
        Override return argument name of GetManagedObjects to be
1401
 
        "objpath_interfaces_and_properties"
1402
 
        """
1403
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1404
 
                                                         object_path,
1405
 
                                                         connection)
1406
 
        try:
1407
 
            document = xml.dom.minidom.parseString(xmlstring)
1408
 
            
1409
 
            for if_tag in document.getElementsByTagName("interface"):
1410
 
                # Fix argument name for the GetManagedObjects method
1411
 
                if (if_tag.getAttribute("name")
1412
 
                                == dbus.OBJECT_MANAGER_IFACE):
1413
 
                    for cn in if_tag.getElementsByTagName("method"):
1414
 
                        if (cn.getAttribute("name")
1415
 
                            == "GetManagedObjects"):
1416
 
                            for arg in cn.getElementsByTagName("arg"):
1417
 
                                if (arg.getAttribute("direction")
1418
 
                                    == "out"):
1419
 
                                    arg.setAttribute(
1420
 
                                        "name",
1421
 
                                        "objpath_interfaces"
1422
 
                                        "_and_properties")
1423
 
            xmlstring = document.toxml("utf-8")
1424
 
            document.unlink()
1425
 
        except (AttributeError, xml.dom.DOMException,
1426
 
                xml.parsers.expat.ExpatError) as error:
1427
 
            logger.error("Failed to override Introspection method",
1428
 
                         exc_info = error)
1429
 
        return xmlstring
1430
 
 
1431
 
def datetime_to_dbus(dt, variant_level=0):
 
1022
 
 
1023
def datetime_to_dbus (dt, variant_level=0):
1432
1024
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1433
1025
    if dt is None:
1434
1026
        return dbus.String("", variant_level = variant_level)
1435
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1027
    return dbus.String(dt.isoformat(),
 
1028
                       variant_level=variant_level)
1436
1029
 
1437
1030
 
1438
1031
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1441
1034
    interface names according to the "alt_interface_names" mapping.
1442
1035
    Usage:
1443
1036
    
1444
 
    @alternate_dbus_interfaces({"org.example.Interface":
1445
 
                                    "net.example.AlternateInterface"})
 
1037
    @alternate_dbus_names({"org.example.Interface":
 
1038
                               "net.example.AlternateInterface"})
1446
1039
    class SampleDBusObject(dbus.service.Object):
1447
1040
        @dbus.service.method("org.example.Interface")
1448
1041
        def SampleDBusMethod():
1458
1051
    (from DBusObjectWithProperties) and interfaces (from the
1459
1052
    dbus_interface_annotations decorator).
1460
1053
    """
1461
 
    
1462
1054
    def wrapper(cls):
1463
1055
        for orig_interface_name, alt_interface_name in (
1464
 
                alt_interface_names.items()):
 
1056
            alt_interface_names.iteritems()):
1465
1057
            attr = {}
1466
1058
            interface_names = set()
1467
1059
            # Go though all attributes of the class
1469
1061
                # Ignore non-D-Bus attributes, and D-Bus attributes
1470
1062
                # with the wrong interface name
1471
1063
                if (not hasattr(attribute, "_dbus_interface")
1472
 
                    or not attribute._dbus_interface.startswith(
1473
 
                        orig_interface_name)):
 
1064
                    or not attribute._dbus_interface
 
1065
                    .startswith(orig_interface_name)):
1474
1066
                    continue
1475
1067
                # Create an alternate D-Bus interface name based on
1476
1068
                # the current name
1477
 
                alt_interface = attribute._dbus_interface.replace(
1478
 
                    orig_interface_name, alt_interface_name)
 
1069
                alt_interface = (attribute._dbus_interface
 
1070
                                 .replace(orig_interface_name,
 
1071
                                          alt_interface_name))
1479
1072
                interface_names.add(alt_interface)
1480
1073
                # Is this a D-Bus signal?
1481
1074
                if getattr(attribute, "_dbus_is_signal", False):
1482
 
                    if sys.version_info.major == 2:
1483
 
                        # Extract the original non-method undecorated
1484
 
                        # function by black magic
1485
 
                        nonmethod_func = (dict(
 
1075
                    # Extract the original non-method function by
 
1076
                    # black magic
 
1077
                    nonmethod_func = (dict(
1486
1078
                            zip(attribute.func_code.co_freevars,
1487
 
                                attribute.__closure__))
1488
 
                                          ["func"].cell_contents)
1489
 
                    else:
1490
 
                        nonmethod_func = attribute
 
1079
                                attribute.__closure__))["func"]
 
1080
                                      .cell_contents)
1491
1081
                    # Create a new, but exactly alike, function
1492
1082
                    # object, and decorate it to be a new D-Bus signal
1493
1083
                    # with the alternate D-Bus interface name
1494
 
                    if sys.version_info.major == 2:
1495
 
                        new_function = types.FunctionType(
1496
 
                            nonmethod_func.func_code,
1497
 
                            nonmethod_func.func_globals,
1498
 
                            nonmethod_func.func_name,
1499
 
                            nonmethod_func.func_defaults,
1500
 
                            nonmethod_func.func_closure)
1501
 
                    else:
1502
 
                        new_function = types.FunctionType(
1503
 
                            nonmethod_func.__code__,
1504
 
                            nonmethod_func.__globals__,
1505
 
                            nonmethod_func.__name__,
1506
 
                            nonmethod_func.__defaults__,
1507
 
                            nonmethod_func.__closure__)
1508
 
                    new_function = (dbus.service.signal(
1509
 
                        alt_interface,
1510
 
                        attribute._dbus_signature)(new_function))
 
1084
                    new_function = (dbus.service.signal
 
1085
                                    (alt_interface,
 
1086
                                     attribute._dbus_signature)
 
1087
                                    (types.FunctionType(
 
1088
                                nonmethod_func.func_code,
 
1089
                                nonmethod_func.func_globals,
 
1090
                                nonmethod_func.func_name,
 
1091
                                nonmethod_func.func_defaults,
 
1092
                                nonmethod_func.func_closure)))
1511
1093
                    # Copy annotations, if any
1512
1094
                    try:
1513
 
                        new_function._dbus_annotations = dict(
1514
 
                            attribute._dbus_annotations)
 
1095
                        new_function._dbus_annotations = (
 
1096
                            dict(attribute._dbus_annotations))
1515
1097
                    except AttributeError:
1516
1098
                        pass
1517
1099
                    # Define a creator of a function to call both the
1522
1104
                        """This function is a scope container to pass
1523
1105
                        func1 and func2 to the "call_both" function
1524
1106
                        outside of its arguments"""
1525
 
                        
1526
 
                        @functools.wraps(func2)
1527
1107
                        def call_both(*args, **kwargs):
1528
1108
                            """This function will emit two D-Bus
1529
1109
                            signals by calling func1 and func2"""
1530
1110
                            func1(*args, **kwargs)
1531
1111
                            func2(*args, **kwargs)
1532
 
                        # Make wrapper function look like a D-Bus signal
1533
 
                        for name, attr in inspect.getmembers(func2):
1534
 
                            if name.startswith("_dbus_"):
1535
 
                                setattr(call_both, name, attr)
1536
 
                        
1537
1112
                        return call_both
1538
1113
                    # Create the "call_both" function and add it to
1539
1114
                    # the class
1544
1119
                    # object.  Decorate it to be a new D-Bus method
1545
1120
                    # with the alternate D-Bus interface name.  Add it
1546
1121
                    # to the class.
1547
 
                    attr[attrname] = (
1548
 
                        dbus.service.method(
1549
 
                            alt_interface,
1550
 
                            attribute._dbus_in_signature,
1551
 
                            attribute._dbus_out_signature)
1552
 
                        (types.FunctionType(attribute.func_code,
1553
 
                                            attribute.func_globals,
1554
 
                                            attribute.func_name,
1555
 
                                            attribute.func_defaults,
1556
 
                                            attribute.func_closure)))
 
1122
                    attr[attrname] = (dbus.service.method
 
1123
                                      (alt_interface,
 
1124
                                       attribute._dbus_in_signature,
 
1125
                                       attribute._dbus_out_signature)
 
1126
                                      (types.FunctionType
 
1127
                                       (attribute.func_code,
 
1128
                                        attribute.func_globals,
 
1129
                                        attribute.func_name,
 
1130
                                        attribute.func_defaults,
 
1131
                                        attribute.func_closure)))
1557
1132
                    # Copy annotations, if any
1558
1133
                    try:
1559
 
                        attr[attrname]._dbus_annotations = dict(
1560
 
                            attribute._dbus_annotations)
 
1134
                        attr[attrname]._dbus_annotations = (
 
1135
                            dict(attribute._dbus_annotations))
1561
1136
                    except AttributeError:
1562
1137
                        pass
1563
1138
                # Is this a D-Bus property?
1566
1141
                    # object, and decorate it to be a new D-Bus
1567
1142
                    # property with the alternate D-Bus interface
1568
1143
                    # name.  Add it to the class.
1569
 
                    attr[attrname] = (dbus_service_property(
1570
 
                        alt_interface, attribute._dbus_signature,
1571
 
                        attribute._dbus_access,
1572
 
                        attribute._dbus_get_args_options
1573
 
                        ["byte_arrays"])
1574
 
                                      (types.FunctionType(
1575
 
                                          attribute.func_code,
1576
 
                                          attribute.func_globals,
1577
 
                                          attribute.func_name,
1578
 
                                          attribute.func_defaults,
1579
 
                                          attribute.func_closure)))
 
1144
                    attr[attrname] = (dbus_service_property
 
1145
                                      (alt_interface,
 
1146
                                       attribute._dbus_signature,
 
1147
                                       attribute._dbus_access,
 
1148
                                       attribute
 
1149
                                       ._dbus_get_args_options
 
1150
                                       ["byte_arrays"])
 
1151
                                      (types.FunctionType
 
1152
                                       (attribute.func_code,
 
1153
                                        attribute.func_globals,
 
1154
                                        attribute.func_name,
 
1155
                                        attribute.func_defaults,
 
1156
                                        attribute.func_closure)))
1580
1157
                    # Copy annotations, if any
1581
1158
                    try:
1582
 
                        attr[attrname]._dbus_annotations = dict(
1583
 
                            attribute._dbus_annotations)
 
1159
                        attr[attrname]._dbus_annotations = (
 
1160
                            dict(attribute._dbus_annotations))
1584
1161
                    except AttributeError:
1585
1162
                        pass
1586
1163
                # Is this a D-Bus interface?
1589
1166
                    # object.  Decorate it to be a new D-Bus interface
1590
1167
                    # with the alternate D-Bus interface name.  Add it
1591
1168
                    # to the class.
1592
 
                    attr[attrname] = (
1593
 
                        dbus_interface_annotations(alt_interface)
1594
 
                        (types.FunctionType(attribute.func_code,
1595
 
                                            attribute.func_globals,
1596
 
                                            attribute.func_name,
1597
 
                                            attribute.func_defaults,
1598
 
                                            attribute.func_closure)))
 
1169
                    attr[attrname] = (dbus_interface_annotations
 
1170
                                      (alt_interface)
 
1171
                                      (types.FunctionType
 
1172
                                       (attribute.func_code,
 
1173
                                        attribute.func_globals,
 
1174
                                        attribute.func_name,
 
1175
                                        attribute.func_defaults,
 
1176
                                        attribute.func_closure)))
1599
1177
            if deprecate:
1600
1178
                # Deprecate all alternate interfaces
1601
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1179
                iname="_AlternateDBusNames_interface_annotation{0}"
1602
1180
                for interface_name in interface_names:
1603
 
                    
1604
1181
                    @dbus_interface_annotations(interface_name)
1605
1182
                    def func(self):
1606
1183
                        return { "org.freedesktop.DBus.Deprecated":
1607
 
                                 "true" }
 
1184
                                     "true" }
1608
1185
                    # Find an unused name
1609
1186
                    for aname in (iname.format(i)
1610
1187
                                  for i in itertools.count()):
1614
1191
            if interface_names:
1615
1192
                # Replace the class with a new subclass of it with
1616
1193
                # methods, signals, etc. as created above.
1617
 
                cls = type(b"{}Alternate".format(cls.__name__),
1618
 
                           (cls, ), attr)
 
1194
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1195
                           (cls,), attr)
1619
1196
        return cls
1620
 
    
1621
1197
    return wrapper
1622
1198
 
1623
1199
 
1624
1200
@alternate_dbus_interfaces({"se.recompile.Mandos":
1625
 
                            "se.bsnet.fukt.Mandos"})
 
1201
                                "se.bsnet.fukt.Mandos"})
1626
1202
class ClientDBus(Client, DBusObjectWithProperties):
1627
1203
    """A Client class using D-Bus
1628
1204
    
1632
1208
    """
1633
1209
    
1634
1210
    runtime_expansions = (Client.runtime_expansions
1635
 
                          + ("dbus_object_path", ))
1636
 
    
1637
 
    _interface = "se.recompile.Mandos.Client"
 
1211
                          + ("dbus_object_path",))
1638
1212
    
1639
1213
    # dbus.service.Object doesn't use super(), so we can't either.
1640
1214
    
1643
1217
        Client.__init__(self, *args, **kwargs)
1644
1218
        # Only now, when this client is initialized, can it show up on
1645
1219
        # the D-Bus
1646
 
        client_object_name = str(self.name).translate(
 
1220
        client_object_name = unicode(self.name).translate(
1647
1221
            {ord("."): ord("_"),
1648
1222
             ord("-"): ord("_")})
1649
 
        self.dbus_object_path = dbus.ObjectPath(
1650
 
            "/clients/" + client_object_name)
 
1223
        self.dbus_object_path = (dbus.ObjectPath
 
1224
                                 ("/clients/" + client_object_name))
1651
1225
        DBusObjectWithProperties.__init__(self, self.bus,
1652
1226
                                          self.dbus_object_path)
1653
1227
    
1654
 
    def notifychangeproperty(transform_func, dbus_name,
1655
 
                             type_func=lambda x: x,
1656
 
                             variant_level=1,
1657
 
                             invalidate_only=False,
1658
 
                             _interface=_interface):
 
1228
    def notifychangeproperty(transform_func,
 
1229
                             dbus_name, type_func=lambda x: x,
 
1230
                             variant_level=1):
1659
1231
        """ Modify a variable so that it's a property which announces
1660
1232
        its changes to DBus.
1661
1233
        
1666
1238
                   to the D-Bus.  Default: no transform
1667
1239
        variant_level: D-Bus variant level.  Default: 1
1668
1240
        """
1669
 
        attrname = "_{}".format(dbus_name)
1670
 
        
 
1241
        attrname = "_{0}".format(dbus_name)
1671
1242
        def setter(self, value):
1672
1243
            if hasattr(self, "dbus_object_path"):
1673
1244
                if (not hasattr(self, attrname) or
1674
1245
                    type_func(getattr(self, attrname, None))
1675
1246
                    != type_func(value)):
1676
 
                    if invalidate_only:
1677
 
                        self.PropertiesChanged(
1678
 
                            _interface, dbus.Dictionary(),
1679
 
                            dbus.Array((dbus_name, )))
1680
 
                    else:
1681
 
                        dbus_value = transform_func(
1682
 
                            type_func(value),
1683
 
                            variant_level = variant_level)
1684
 
                        self.PropertyChanged(dbus.String(dbus_name),
1685
 
                                             dbus_value)
1686
 
                        self.PropertiesChanged(
1687
 
                            _interface,
1688
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1689
 
                                              dbus_value }),
1690
 
                            dbus.Array())
 
1247
                    dbus_value = transform_func(type_func(value),
 
1248
                                                variant_level
 
1249
                                                =variant_level)
 
1250
                    self.PropertyChanged(dbus.String(dbus_name),
 
1251
                                         dbus_value)
1691
1252
            setattr(self, attrname, value)
1692
1253
        
1693
1254
        return property(lambda self: getattr(self, attrname), setter)
1699
1260
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1700
1261
    last_enabled = notifychangeproperty(datetime_to_dbus,
1701
1262
                                        "LastEnabled")
1702
 
    checker = notifychangeproperty(
1703
 
        dbus.Boolean, "CheckerRunning",
1704
 
        type_func = lambda checker: checker is not None)
 
1263
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1264
                                   type_func = lambda checker:
 
1265
                                       checker is not None)
1705
1266
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1706
1267
                                           "LastCheckedOK")
1707
1268
    last_checker_status = notifychangeproperty(dbus.Int16,
1710
1271
        datetime_to_dbus, "LastApprovalRequest")
1711
1272
    approved_by_default = notifychangeproperty(dbus.Boolean,
1712
1273
                                               "ApprovedByDefault")
1713
 
    approval_delay = notifychangeproperty(
1714
 
        dbus.UInt64, "ApprovalDelay",
1715
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1274
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1275
                                          "ApprovalDelay",
 
1276
                                          type_func =
 
1277
                                          timedelta_to_milliseconds)
1716
1278
    approval_duration = notifychangeproperty(
1717
1279
        dbus.UInt64, "ApprovalDuration",
1718
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1280
        type_func = timedelta_to_milliseconds)
1719
1281
    host = notifychangeproperty(dbus.String, "Host")
1720
 
    timeout = notifychangeproperty(
1721
 
        dbus.UInt64, "Timeout",
1722
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1282
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1283
                                   type_func =
 
1284
                                   timedelta_to_milliseconds)
1723
1285
    extended_timeout = notifychangeproperty(
1724
1286
        dbus.UInt64, "ExtendedTimeout",
1725
 
        type_func = lambda td: td.total_seconds() * 1000)
1726
 
    interval = notifychangeproperty(
1727
 
        dbus.UInt64, "Interval",
1728
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1287
        type_func = timedelta_to_milliseconds)
 
1288
    interval = notifychangeproperty(dbus.UInt64,
 
1289
                                    "Interval",
 
1290
                                    type_func =
 
1291
                                    timedelta_to_milliseconds)
1729
1292
    checker_command = notifychangeproperty(dbus.String, "Checker")
1730
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1731
 
                                  invalidate_only=True)
1732
1293
    
1733
1294
    del notifychangeproperty
1734
1295
    
1741
1302
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1742
1303
        Client.__del__(self, *args, **kwargs)
1743
1304
    
1744
 
    def checker_callback(self, source, condition,
1745
 
                         connection, command, *args, **kwargs):
1746
 
        ret = Client.checker_callback(self, source, condition,
1747
 
                                      connection, command, *args,
1748
 
                                      **kwargs)
1749
 
        exitstatus = self.last_checker_status
1750
 
        if exitstatus >= 0:
 
1305
    def checker_callback(self, pid, condition, command,
 
1306
                         *args, **kwargs):
 
1307
        self.checker_callback_tag = None
 
1308
        self.checker = None
 
1309
        if os.WIFEXITED(condition):
 
1310
            exitstatus = os.WEXITSTATUS(condition)
1751
1311
            # Emit D-Bus signal
1752
1312
            self.CheckerCompleted(dbus.Int16(exitstatus),
1753
 
                                  # This is specific to GNU libC
1754
 
                                  dbus.Int64(exitstatus << 8),
 
1313
                                  dbus.Int64(condition),
1755
1314
                                  dbus.String(command))
1756
1315
        else:
1757
1316
            # Emit D-Bus signal
1758
1317
            self.CheckerCompleted(dbus.Int16(-1),
1759
 
                                  dbus.Int64(
1760
 
                                      # This is specific to GNU libC
1761
 
                                      (exitstatus << 8)
1762
 
                                      | self.last_checker_signal),
 
1318
                                  dbus.Int64(condition),
1763
1319
                                  dbus.String(command))
1764
 
        return ret
 
1320
        
 
1321
        return Client.checker_callback(self, pid, condition, command,
 
1322
                                       *args, **kwargs)
1765
1323
    
1766
1324
    def start_checker(self, *args, **kwargs):
1767
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1325
        old_checker = self.checker
 
1326
        if self.checker is not None:
 
1327
            old_checker_pid = self.checker.pid
 
1328
        else:
 
1329
            old_checker_pid = None
1768
1330
        r = Client.start_checker(self, *args, **kwargs)
1769
1331
        # Only if new checker process was started
1770
1332
        if (self.checker is not None
1779
1341
    
1780
1342
    def approve(self, value=True):
1781
1343
        self.approved = value
1782
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1783
 
                                * 1000), self._reset_approved)
 
1344
        gobject.timeout_add(timedelta_to_milliseconds
 
1345
                            (self.approval_duration),
 
1346
                            self._reset_approved)
1784
1347
        self.send_changedstate()
1785
1348
    
1786
1349
    ## D-Bus methods, signals & properties
 
1350
    _interface = "se.recompile.Mandos.Client"
1787
1351
    
1788
1352
    ## Interfaces
1789
1353
    
 
1354
    @dbus_interface_annotations(_interface)
 
1355
    def _foo(self):
 
1356
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1357
                     "false"}
 
1358
    
1790
1359
    ## Signals
1791
1360
    
1792
1361
    # CheckerCompleted - signal
1802
1371
        pass
1803
1372
    
1804
1373
    # PropertyChanged - signal
1805
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1806
1374
    @dbus.service.signal(_interface, signature="sv")
1807
1375
    def PropertyChanged(self, property, value):
1808
1376
        "D-Bus signal"
1842
1410
        self.checked_ok()
1843
1411
    
1844
1412
    # Enable - method
1845
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1846
1413
    @dbus.service.method(_interface)
1847
1414
    def Enable(self):
1848
1415
        "D-Bus method"
1849
1416
        self.enable()
1850
1417
    
1851
1418
    # StartChecker - method
1852
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1853
1419
    @dbus.service.method(_interface)
1854
1420
    def StartChecker(self):
1855
1421
        "D-Bus method"
1856
1422
        self.start_checker()
1857
1423
    
1858
1424
    # Disable - method
1859
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1860
1425
    @dbus.service.method(_interface)
1861
1426
    def Disable(self):
1862
1427
        "D-Bus method"
1863
1428
        self.disable()
1864
1429
    
1865
1430
    # StopChecker - method
1866
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1867
1431
    @dbus.service.method(_interface)
1868
1432
    def StopChecker(self):
1869
1433
        self.stop_checker()
1876
1440
        return dbus.Boolean(bool(self.approvals_pending))
1877
1441
    
1878
1442
    # ApprovedByDefault - property
1879
 
    @dbus_service_property(_interface,
1880
 
                           signature="b",
 
1443
    @dbus_service_property(_interface, signature="b",
1881
1444
                           access="readwrite")
1882
1445
    def ApprovedByDefault_dbus_property(self, value=None):
1883
1446
        if value is None:       # get
1885
1448
        self.approved_by_default = bool(value)
1886
1449
    
1887
1450
    # ApprovalDelay - property
1888
 
    @dbus_service_property(_interface,
1889
 
                           signature="t",
 
1451
    @dbus_service_property(_interface, signature="t",
1890
1452
                           access="readwrite")
1891
1453
    def ApprovalDelay_dbus_property(self, value=None):
1892
1454
        if value is None:       # get
1893
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1894
 
                               * 1000)
 
1455
            return dbus.UInt64(self.approval_delay_milliseconds())
1895
1456
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1896
1457
    
1897
1458
    # ApprovalDuration - property
1898
 
    @dbus_service_property(_interface,
1899
 
                           signature="t",
 
1459
    @dbus_service_property(_interface, signature="t",
1900
1460
                           access="readwrite")
1901
1461
    def ApprovalDuration_dbus_property(self, value=None):
1902
1462
        if value is None:       # get
1903
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1904
 
                               * 1000)
 
1463
            return dbus.UInt64(timedelta_to_milliseconds(
 
1464
                    self.approval_duration))
1905
1465
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1906
1466
    
1907
1467
    # Name - property
1908
 
    @dbus_annotations(
1909
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1910
1468
    @dbus_service_property(_interface, signature="s", access="read")
1911
1469
    def Name_dbus_property(self):
1912
1470
        return dbus.String(self.name)
1913
1471
    
1914
1472
    # Fingerprint - property
1915
 
    @dbus_annotations(
1916
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1917
1473
    @dbus_service_property(_interface, signature="s", access="read")
1918
1474
    def Fingerprint_dbus_property(self):
1919
1475
        return dbus.String(self.fingerprint)
1920
1476
    
1921
1477
    # Host - property
1922
 
    @dbus_service_property(_interface,
1923
 
                           signature="s",
 
1478
    @dbus_service_property(_interface, signature="s",
1924
1479
                           access="readwrite")
1925
1480
    def Host_dbus_property(self, value=None):
1926
1481
        if value is None:       # get
1927
1482
            return dbus.String(self.host)
1928
 
        self.host = str(value)
 
1483
        self.host = unicode(value)
1929
1484
    
1930
1485
    # Created - property
1931
 
    @dbus_annotations(
1932
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1933
1486
    @dbus_service_property(_interface, signature="s", access="read")
1934
1487
    def Created_dbus_property(self):
1935
1488
        return datetime_to_dbus(self.created)
1940
1493
        return datetime_to_dbus(self.last_enabled)
1941
1494
    
1942
1495
    # Enabled - property
1943
 
    @dbus_service_property(_interface,
1944
 
                           signature="b",
 
1496
    @dbus_service_property(_interface, signature="b",
1945
1497
                           access="readwrite")
1946
1498
    def Enabled_dbus_property(self, value=None):
1947
1499
        if value is None:       # get
1952
1504
            self.disable()
1953
1505
    
1954
1506
    # LastCheckedOK - property
1955
 
    @dbus_service_property(_interface,
1956
 
                           signature="s",
 
1507
    @dbus_service_property(_interface, signature="s",
1957
1508
                           access="readwrite")
1958
1509
    def LastCheckedOK_dbus_property(self, value=None):
1959
1510
        if value is not None:
1962
1513
        return datetime_to_dbus(self.last_checked_ok)
1963
1514
    
1964
1515
    # LastCheckerStatus - property
1965
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1516
    @dbus_service_property(_interface, signature="n",
 
1517
                           access="read")
1966
1518
    def LastCheckerStatus_dbus_property(self):
1967
1519
        return dbus.Int16(self.last_checker_status)
1968
1520
    
1977
1529
        return datetime_to_dbus(self.last_approval_request)
1978
1530
    
1979
1531
    # Timeout - property
1980
 
    @dbus_service_property(_interface,
1981
 
                           signature="t",
 
1532
    @dbus_service_property(_interface, signature="t",
1982
1533
                           access="readwrite")
1983
1534
    def Timeout_dbus_property(self, value=None):
1984
1535
        if value is None:       # get
1985
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1536
            return dbus.UInt64(self.timeout_milliseconds())
1986
1537
        old_timeout = self.timeout
1987
1538
        self.timeout = datetime.timedelta(0, 0, 0, value)
1988
1539
        # Reschedule disabling
1997
1548
                    is None):
1998
1549
                    return
1999
1550
                gobject.source_remove(self.disable_initiator_tag)
2000
 
                self.disable_initiator_tag = gobject.timeout_add(
2001
 
                    int((self.expires - now).total_seconds() * 1000),
2002
 
                    self.disable)
 
1551
                self.disable_initiator_tag = (
 
1552
                    gobject.timeout_add(
 
1553
                        timedelta_to_milliseconds(self.expires - now),
 
1554
                        self.disable))
2003
1555
    
2004
1556
    # ExtendedTimeout - property
2005
 
    @dbus_service_property(_interface,
2006
 
                           signature="t",
 
1557
    @dbus_service_property(_interface, signature="t",
2007
1558
                           access="readwrite")
2008
1559
    def ExtendedTimeout_dbus_property(self, value=None):
2009
1560
        if value is None:       # get
2010
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
2011
 
                               * 1000)
 
1561
            return dbus.UInt64(self.extended_timeout_milliseconds())
2012
1562
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
2013
1563
    
2014
1564
    # Interval - property
2015
 
    @dbus_service_property(_interface,
2016
 
                           signature="t",
 
1565
    @dbus_service_property(_interface, signature="t",
2017
1566
                           access="readwrite")
2018
1567
    def Interval_dbus_property(self, value=None):
2019
1568
        if value is None:       # get
2020
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1569
            return dbus.UInt64(self.interval_milliseconds())
2021
1570
        self.interval = datetime.timedelta(0, 0, 0, value)
2022
1571
        if getattr(self, "checker_initiator_tag", None) is None:
2023
1572
            return
2024
1573
        if self.enabled:
2025
1574
            # Reschedule checker run
2026
1575
            gobject.source_remove(self.checker_initiator_tag)
2027
 
            self.checker_initiator_tag = gobject.timeout_add(
2028
 
                value, self.start_checker)
2029
 
            self.start_checker() # Start one now, too
 
1576
            self.checker_initiator_tag = (gobject.timeout_add
 
1577
                                          (value, self.start_checker))
 
1578
            self.start_checker()    # Start one now, too
2030
1579
    
2031
1580
    # Checker - property
2032
 
    @dbus_service_property(_interface,
2033
 
                           signature="s",
 
1581
    @dbus_service_property(_interface, signature="s",
2034
1582
                           access="readwrite")
2035
1583
    def Checker_dbus_property(self, value=None):
2036
1584
        if value is None:       # get
2037
1585
            return dbus.String(self.checker_command)
2038
 
        self.checker_command = str(value)
 
1586
        self.checker_command = unicode(value)
2039
1587
    
2040
1588
    # CheckerRunning - property
2041
 
    @dbus_service_property(_interface,
2042
 
                           signature="b",
 
1589
    @dbus_service_property(_interface, signature="b",
2043
1590
                           access="readwrite")
2044
1591
    def CheckerRunning_dbus_property(self, value=None):
2045
1592
        if value is None:       # get
2050
1597
            self.stop_checker()
2051
1598
    
2052
1599
    # ObjectPath - property
2053
 
    @dbus_annotations(
2054
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2055
 
         "org.freedesktop.DBus.Deprecated": "true"})
2056
1600
    @dbus_service_property(_interface, signature="o", access="read")
2057
1601
    def ObjectPath_dbus_property(self):
2058
1602
        return self.dbus_object_path # is already a dbus.ObjectPath
2059
1603
    
2060
1604
    # Secret = property
2061
 
    @dbus_annotations(
2062
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
2063
 
         "invalidates"})
2064
 
    @dbus_service_property(_interface,
2065
 
                           signature="ay",
2066
 
                           access="write",
2067
 
                           byte_arrays=True)
 
1605
    @dbus_service_property(_interface, signature="ay",
 
1606
                           access="write", byte_arrays=True)
2068
1607
    def Secret_dbus_property(self, value):
2069
 
        self.secret = bytes(value)
 
1608
        self.secret = str(value)
2070
1609
    
2071
1610
    del _interface
2072
1611
 
2076
1615
        self._pipe = child_pipe
2077
1616
        self._pipe.send(('init', fpr, address))
2078
1617
        if not self._pipe.recv():
2079
 
            raise KeyError(fpr)
 
1618
            raise KeyError()
2080
1619
    
2081
1620
    def __getattribute__(self, name):
2082
1621
        if name == '_pipe':
2086
1625
        if data[0] == 'data':
2087
1626
            return data[1]
2088
1627
        if data[0] == 'function':
2089
 
            
2090
1628
            def func(*args, **kwargs):
2091
1629
                self._pipe.send(('funcall', name, args, kwargs))
2092
1630
                return self._pipe.recv()[1]
2093
 
            
2094
1631
            return func
2095
1632
    
2096
1633
    def __setattr__(self, name, value):
2108
1645
    def handle(self):
2109
1646
        with contextlib.closing(self.server.child_pipe) as child_pipe:
2110
1647
            logger.info("TCP connection from: %s",
2111
 
                        str(self.client_address))
 
1648
                        unicode(self.client_address))
2112
1649
            logger.debug("Pipe FD: %d",
2113
1650
                         self.server.child_pipe.fileno())
2114
1651
            
2115
 
            session = gnutls.ClientSession(self.request)
 
1652
            session = (gnutls.connection
 
1653
                       .ClientSession(self.request,
 
1654
                                      gnutls.connection
 
1655
                                      .X509Credentials()))
 
1656
            
 
1657
            # Note: gnutls.connection.X509Credentials is really a
 
1658
            # generic GnuTLS certificate credentials object so long as
 
1659
            # no X.509 keys are added to it.  Therefore, we can use it
 
1660
            # here despite using OpenPGP certificates.
2116
1661
            
2117
1662
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
2118
1663
            #                      "+AES-256-CBC", "+SHA1",
2122
1667
            priority = self.server.gnutls_priority
2123
1668
            if priority is None:
2124
1669
                priority = "NORMAL"
2125
 
            gnutls.priority_set_direct(session._c_object, priority,
2126
 
                                       None)
 
1670
            (gnutls.library.functions
 
1671
             .gnutls_priority_set_direct(session._c_object,
 
1672
                                         priority, None))
2127
1673
            
2128
1674
            # Start communication using the Mandos protocol
2129
1675
            # Get protocol number
2131
1677
            logger.debug("Protocol version: %r", line)
2132
1678
            try:
2133
1679
                if int(line.strip().split()[0]) > 1:
2134
 
                    raise RuntimeError(line)
 
1680
                    raise RuntimeError
2135
1681
            except (ValueError, IndexError, RuntimeError) as error:
2136
1682
                logger.error("Unknown protocol version: %s", error)
2137
1683
                return
2139
1685
            # Start GnuTLS connection
2140
1686
            try:
2141
1687
                session.handshake()
2142
 
            except gnutls.Error as error:
 
1688
            except gnutls.errors.GNUTLSError as error:
2143
1689
                logger.warning("Handshake failed: %s", error)
2144
1690
                # Do not run session.bye() here: the session is not
2145
1691
                # established.  Just abandon the request.
2149
1695
            approval_required = False
2150
1696
            try:
2151
1697
                try:
2152
 
                    fpr = self.fingerprint(
2153
 
                        self.peer_certificate(session))
2154
 
                except (TypeError, gnutls.Error) as error:
 
1698
                    fpr = self.fingerprint(self.peer_certificate
 
1699
                                           (session))
 
1700
                except (TypeError,
 
1701
                        gnutls.errors.GNUTLSError) as error:
2155
1702
                    logger.warning("Bad certificate: %s", error)
2156
1703
                    return
2157
1704
                logger.debug("Fingerprint: %s", fpr)
2170
1717
                while True:
2171
1718
                    if not client.enabled:
2172
1719
                        logger.info("Client %s is disabled",
2173
 
                                    client.name)
 
1720
                                       client.name)
2174
1721
                        if self.server.use_dbus:
2175
1722
                            # Emit D-Bus signal
2176
1723
                            client.Rejected("Disabled")
2185
1732
                        if self.server.use_dbus:
2186
1733
                            # Emit D-Bus signal
2187
1734
                            client.NeedApproval(
2188
 
                                client.approval_delay.total_seconds()
2189
 
                                * 1000, client.approved_by_default)
 
1735
                                client.approval_delay_milliseconds(),
 
1736
                                client.approved_by_default)
2190
1737
                    else:
2191
1738
                        logger.warning("Client %s was not approved",
2192
1739
                                       client.name)
2198
1745
                    #wait until timeout or approved
2199
1746
                    time = datetime.datetime.now()
2200
1747
                    client.changedstate.acquire()
2201
 
                    client.changedstate.wait(delay.total_seconds())
 
1748
                    client.changedstate.wait(
 
1749
                        float(timedelta_to_milliseconds(delay)
 
1750
                              / 1000))
2202
1751
                    client.changedstate.release()
2203
1752
                    time2 = datetime.datetime.now()
2204
1753
                    if (time2 - time) >= delay:
2219
1768
                while sent_size < len(client.secret):
2220
1769
                    try:
2221
1770
                        sent = session.send(client.secret[sent_size:])
2222
 
                    except gnutls.Error as error:
 
1771
                    except gnutls.errors.GNUTLSError as error:
2223
1772
                        logger.warning("gnutls send failed",
2224
1773
                                       exc_info=error)
2225
1774
                        return
2226
 
                    logger.debug("Sent: %d, remaining: %d", sent,
2227
 
                                 len(client.secret) - (sent_size
2228
 
                                                       + sent))
 
1775
                    logger.debug("Sent: %d, remaining: %d",
 
1776
                                 sent, len(client.secret)
 
1777
                                 - (sent_size + sent))
2229
1778
                    sent_size += sent
2230
1779
                
2231
1780
                logger.info("Sending secret to %s", client.name)
2240
1789
                    client.approvals_pending -= 1
2241
1790
                try:
2242
1791
                    session.bye()
2243
 
                except gnutls.Error as error:
 
1792
                except gnutls.errors.GNUTLSError as error:
2244
1793
                    logger.warning("GnuTLS bye failed",
2245
1794
                                   exc_info=error)
2246
1795
    
2248
1797
    def peer_certificate(session):
2249
1798
        "Return the peer's OpenPGP certificate as a bytestring"
2250
1799
        # If not an OpenPGP certificate...
2251
 
        if (gnutls.certificate_type_get(session._c_object)
2252
 
            != gnutls.CRT_OPENPGP):
2253
 
            # ...return invalid data
2254
 
            return b""
 
1800
        if (gnutls.library.functions
 
1801
            .gnutls_certificate_type_get(session._c_object)
 
1802
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
1803
            # ...do the normal thing
 
1804
            return session.peer_certificate
2255
1805
        list_size = ctypes.c_uint(1)
2256
 
        cert_list = (gnutls.certificate_get_peers
 
1806
        cert_list = (gnutls.library.functions
 
1807
                     .gnutls_certificate_get_peers
2257
1808
                     (session._c_object, ctypes.byref(list_size)))
2258
1809
        if not bool(cert_list) and list_size.value != 0:
2259
 
            raise gnutls.Error("error getting peer certificate")
 
1810
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1811
                                            " certificate")
2260
1812
        if list_size.value == 0:
2261
1813
            return None
2262
1814
        cert = cert_list[0]
2266
1818
    def fingerprint(openpgp):
2267
1819
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2268
1820
        # New GnuTLS "datum" with the OpenPGP public key
2269
 
        datum = gnutls.datum_t(
2270
 
            ctypes.cast(ctypes.c_char_p(openpgp),
2271
 
                        ctypes.POINTER(ctypes.c_ubyte)),
2272
 
            ctypes.c_uint(len(openpgp)))
 
1821
        datum = (gnutls.library.types
 
1822
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1823
                                             ctypes.POINTER
 
1824
                                             (ctypes.c_ubyte)),
 
1825
                                 ctypes.c_uint(len(openpgp))))
2273
1826
        # New empty GnuTLS certificate
2274
 
        crt = gnutls.openpgp_crt_t()
2275
 
        gnutls.openpgp_crt_init(ctypes.byref(crt))
 
1827
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
1828
        (gnutls.library.functions
 
1829
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
2276
1830
        # Import the OpenPGP public key into the certificate
2277
 
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2278
 
                                  gnutls.OPENPGP_FMT_RAW)
 
1831
        (gnutls.library.functions
 
1832
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1833
                                    gnutls.library.constants
 
1834
                                    .GNUTLS_OPENPGP_FMT_RAW))
2279
1835
        # Verify the self signature in the key
2280
1836
        crtverify = ctypes.c_uint()
2281
 
        gnutls.openpgp_crt_verify_self(crt, 0,
2282
 
                                       ctypes.byref(crtverify))
 
1837
        (gnutls.library.functions
 
1838
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1839
                                         ctypes.byref(crtverify)))
2283
1840
        if crtverify.value != 0:
2284
 
            gnutls.openpgp_crt_deinit(crt)
2285
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
1841
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
1842
            raise (gnutls.errors.CertificateSecurityError
 
1843
                   ("Verify failed"))
2286
1844
        # New buffer for the fingerprint
2287
1845
        buf = ctypes.create_string_buffer(20)
2288
1846
        buf_len = ctypes.c_size_t()
2289
1847
        # Get the fingerprint from the certificate into the buffer
2290
 
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2291
 
                                           ctypes.byref(buf_len))
 
1848
        (gnutls.library.functions
 
1849
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1850
                                             ctypes.byref(buf_len)))
2292
1851
        # Deinit the certificate
2293
 
        gnutls.openpgp_crt_deinit(crt)
 
1852
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2294
1853
        # Convert the buffer to a Python bytestring
2295
1854
        fpr = ctypes.string_at(buf, buf_len.value)
2296
1855
        # Convert the bytestring to hexadecimal notation
2300
1859
 
2301
1860
class MultiprocessingMixIn(object):
2302
1861
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2303
 
    
2304
1862
    def sub_process_main(self, request, address):
2305
1863
        try:
2306
1864
            self.finish_request(request, address)
2318
1876
 
2319
1877
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
2320
1878
    """ adds a pipe to the MixIn """
2321
 
    
2322
1879
    def process_request(self, request, client_address):
2323
1880
        """Overrides and wraps the original process_request().
2324
1881
        
2333
1890
    
2334
1891
    def add_pipe(self, parent_pipe, proc):
2335
1892
        """Dummy function; override as necessary"""
2336
 
        raise NotImplementedError()
 
1893
        raise NotImplementedError
2337
1894
 
2338
1895
 
2339
1896
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2345
1902
        interface:      None or a network interface name (string)
2346
1903
        use_ipv6:       Boolean; to use IPv6 or not
2347
1904
    """
2348
 
    
2349
1905
    def __init__(self, server_address, RequestHandlerClass,
2350
 
                 interface=None,
2351
 
                 use_ipv6=True,
2352
 
                 socketfd=None):
2353
 
        """If socketfd is set, use that file descriptor instead of
2354
 
        creating a new one with socket.socket().
2355
 
        """
 
1906
                 interface=None, use_ipv6=True):
2356
1907
        self.interface = interface
2357
1908
        if use_ipv6:
2358
1909
            self.address_family = socket.AF_INET6
2359
 
        if socketfd is not None:
2360
 
            # Save the file descriptor
2361
 
            self.socketfd = socketfd
2362
 
            # Save the original socket.socket() function
2363
 
            self.socket_socket = socket.socket
2364
 
            # To implement --socket, we monkey patch socket.socket.
2365
 
            # 
2366
 
            # (When socketserver.TCPServer is a new-style class, we
2367
 
            # could make self.socket into a property instead of monkey
2368
 
            # patching socket.socket.)
2369
 
            # 
2370
 
            # Create a one-time-only replacement for socket.socket()
2371
 
            @functools.wraps(socket.socket)
2372
 
            def socket_wrapper(*args, **kwargs):
2373
 
                # Restore original function so subsequent calls are
2374
 
                # not affected.
2375
 
                socket.socket = self.socket_socket
2376
 
                del self.socket_socket
2377
 
                # This time only, return a new socket object from the
2378
 
                # saved file descriptor.
2379
 
                return socket.fromfd(self.socketfd, *args, **kwargs)
2380
 
            # Replace socket.socket() function with wrapper
2381
 
            socket.socket = socket_wrapper
2382
 
        # The socketserver.TCPServer.__init__ will call
2383
 
        # socket.socket(), which might be our replacement,
2384
 
        # socket_wrapper(), if socketfd was set.
2385
1910
        socketserver.TCPServer.__init__(self, server_address,
2386
1911
                                        RequestHandlerClass)
2387
 
    
2388
1912
    def server_bind(self):
2389
1913
        """This overrides the normal server_bind() function
2390
1914
        to bind to an interface if one was specified, and also NOT to
2396
1920
                             self.interface)
2397
1921
            else:
2398
1922
                try:
2399
 
                    self.socket.setsockopt(
2400
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
2401
 
                        (self.interface + "\0").encode("utf-8"))
 
1923
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1924
                                           SO_BINDTODEVICE,
 
1925
                                           str(self.interface
 
1926
                                               + '\0'))
2402
1927
                except socket.error as error:
2403
 
                    if error.errno == errno.EPERM:
2404
 
                        logger.error("No permission to bind to"
2405
 
                                     " interface %s", self.interface)
2406
 
                    elif error.errno == errno.ENOPROTOOPT:
 
1928
                    if error[0] == errno.EPERM:
 
1929
                        logger.error("No permission to"
 
1930
                                     " bind to interface %s",
 
1931
                                     self.interface)
 
1932
                    elif error[0] == errno.ENOPROTOOPT:
2407
1933
                        logger.error("SO_BINDTODEVICE not available;"
2408
1934
                                     " cannot bind to interface %s",
2409
1935
                                     self.interface)
2410
 
                    elif error.errno == errno.ENODEV:
2411
 
                        logger.error("Interface %s does not exist,"
2412
 
                                     " cannot bind", self.interface)
2413
1936
                    else:
2414
1937
                        raise
2415
1938
        # Only bind(2) the socket if we really need to.
2418
1941
                if self.address_family == socket.AF_INET6:
2419
1942
                    any_address = "::" # in6addr_any
2420
1943
                else:
2421
 
                    any_address = "0.0.0.0" # INADDR_ANY
 
1944
                    any_address = socket.INADDR_ANY
2422
1945
                self.server_address = (any_address,
2423
1946
                                       self.server_address[1])
2424
1947
            elif not self.server_address[1]:
2425
 
                self.server_address = (self.server_address[0], 0)
 
1948
                self.server_address = (self.server_address[0],
 
1949
                                       0)
2426
1950
#                 if self.interface:
2427
1951
#                     self.server_address = (self.server_address[0],
2428
1952
#                                            0, # port
2442
1966
    
2443
1967
    Assumes a gobject.MainLoop event loop.
2444
1968
    """
2445
 
    
2446
1969
    def __init__(self, server_address, RequestHandlerClass,
2447
 
                 interface=None,
2448
 
                 use_ipv6=True,
2449
 
                 clients=None,
2450
 
                 gnutls_priority=None,
2451
 
                 use_dbus=True,
2452
 
                 socketfd=None):
 
1970
                 interface=None, use_ipv6=True, clients=None,
 
1971
                 gnutls_priority=None, use_dbus=True):
2453
1972
        self.enabled = False
2454
1973
        self.clients = clients
2455
1974
        if self.clients is None:
2459
1978
        IPv6_TCPServer.__init__(self, server_address,
2460
1979
                                RequestHandlerClass,
2461
1980
                                interface = interface,
2462
 
                                use_ipv6 = use_ipv6,
2463
 
                                socketfd = socketfd)
2464
 
    
 
1981
                                use_ipv6 = use_ipv6)
2465
1982
    def server_activate(self):
2466
1983
        if self.enabled:
2467
1984
            return socketserver.TCPServer.server_activate(self)
2471
1988
    
2472
1989
    def add_pipe(self, parent_pipe, proc):
2473
1990
        # Call "handle_ipc" for both data and EOF events
2474
 
        gobject.io_add_watch(
2475
 
            parent_pipe.fileno(),
2476
 
            gobject.IO_IN | gobject.IO_HUP,
2477
 
            functools.partial(self.handle_ipc,
2478
 
                              parent_pipe = parent_pipe,
2479
 
                              proc = proc))
 
1991
        gobject.io_add_watch(parent_pipe.fileno(),
 
1992
                             gobject.IO_IN | gobject.IO_HUP,
 
1993
                             functools.partial(self.handle_ipc,
 
1994
                                               parent_pipe =
 
1995
                                               parent_pipe,
 
1996
                                               proc = proc))
2480
1997
    
2481
 
    def handle_ipc(self, source, condition,
2482
 
                   parent_pipe=None,
2483
 
                   proc = None,
2484
 
                   client_object=None):
 
1998
    def handle_ipc(self, source, condition, parent_pipe=None,
 
1999
                   proc = None, client_object=None):
2485
2000
        # error, or the other end of multiprocessing.Pipe has closed
2486
2001
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2487
2002
            # Wait for other process to exit
2510
2025
                parent_pipe.send(False)
2511
2026
                return False
2512
2027
            
2513
 
            gobject.io_add_watch(
2514
 
                parent_pipe.fileno(),
2515
 
                gobject.IO_IN | gobject.IO_HUP,
2516
 
                functools.partial(self.handle_ipc,
2517
 
                                  parent_pipe = parent_pipe,
2518
 
                                  proc = proc,
2519
 
                                  client_object = client))
 
2028
            gobject.io_add_watch(parent_pipe.fileno(),
 
2029
                                 gobject.IO_IN | gobject.IO_HUP,
 
2030
                                 functools.partial(self.handle_ipc,
 
2031
                                                   parent_pipe =
 
2032
                                                   parent_pipe,
 
2033
                                                   proc = proc,
 
2034
                                                   client_object =
 
2035
                                                   client))
2520
2036
            parent_pipe.send(True)
2521
2037
            # remove the old hook in favor of the new above hook on
2522
2038
            # same fileno
2528
2044
            
2529
2045
            parent_pipe.send(('data', getattr(client_object,
2530
2046
                                              funcname)(*args,
2531
 
                                                        **kwargs)))
 
2047
                                                         **kwargs)))
2532
2048
        
2533
2049
        if command == 'getattr':
2534
2050
            attrname = request[1]
2535
 
            if isinstance(client_object.__getattribute__(attrname),
2536
 
                          collections.Callable):
2537
 
                parent_pipe.send(('function', ))
 
2051
            if callable(client_object.__getattribute__(attrname)):
 
2052
                parent_pipe.send(('function',))
2538
2053
            else:
2539
 
                parent_pipe.send((
2540
 
                    'data', client_object.__getattribute__(attrname)))
 
2054
                parent_pipe.send(('data', client_object
 
2055
                                  .__getattribute__(attrname)))
2541
2056
        
2542
2057
        if command == 'setattr':
2543
2058
            attrname = request[1]
2547
2062
        return True
2548
2063
 
2549
2064
 
2550
 
def rfc3339_duration_to_delta(duration):
2551
 
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2552
 
    
2553
 
    >>> rfc3339_duration_to_delta("P7D")
2554
 
    datetime.timedelta(7)
2555
 
    >>> rfc3339_duration_to_delta("PT60S")
2556
 
    datetime.timedelta(0, 60)
2557
 
    >>> rfc3339_duration_to_delta("PT60M")
2558
 
    datetime.timedelta(0, 3600)
2559
 
    >>> rfc3339_duration_to_delta("PT24H")
2560
 
    datetime.timedelta(1)
2561
 
    >>> rfc3339_duration_to_delta("P1W")
2562
 
    datetime.timedelta(7)
2563
 
    >>> rfc3339_duration_to_delta("PT5M30S")
2564
 
    datetime.timedelta(0, 330)
2565
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
2566
 
    datetime.timedelta(1, 200)
2567
 
    """
2568
 
    
2569
 
    # Parsing an RFC 3339 duration with regular expressions is not
2570
 
    # possible - there would have to be multiple places for the same
2571
 
    # values, like seconds.  The current code, while more esoteric, is
2572
 
    # cleaner without depending on a parsing library.  If Python had a
2573
 
    # built-in library for parsing we would use it, but we'd like to
2574
 
    # avoid excessive use of external libraries.
2575
 
    
2576
 
    # New type for defining tokens, syntax, and semantics all-in-one
2577
 
    Token = collections.namedtuple("Token", (
2578
 
        "regexp",  # To match token; if "value" is not None, must have
2579
 
                   # a "group" containing digits
2580
 
        "value",   # datetime.timedelta or None
2581
 
        "followers"))           # Tokens valid after this token
2582
 
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2583
 
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2584
 
    token_end = Token(re.compile(r"$"), None, frozenset())
2585
 
    token_second = Token(re.compile(r"(\d+)S"),
2586
 
                         datetime.timedelta(seconds=1),
2587
 
                         frozenset((token_end, )))
2588
 
    token_minute = Token(re.compile(r"(\d+)M"),
2589
 
                         datetime.timedelta(minutes=1),
2590
 
                         frozenset((token_second, token_end)))
2591
 
    token_hour = Token(re.compile(r"(\d+)H"),
2592
 
                       datetime.timedelta(hours=1),
2593
 
                       frozenset((token_minute, token_end)))
2594
 
    token_time = Token(re.compile(r"T"),
2595
 
                       None,
2596
 
                       frozenset((token_hour, token_minute,
2597
 
                                  token_second)))
2598
 
    token_day = Token(re.compile(r"(\d+)D"),
2599
 
                      datetime.timedelta(days=1),
2600
 
                      frozenset((token_time, token_end)))
2601
 
    token_month = Token(re.compile(r"(\d+)M"),
2602
 
                        datetime.timedelta(weeks=4),
2603
 
                        frozenset((token_day, token_end)))
2604
 
    token_year = Token(re.compile(r"(\d+)Y"),
2605
 
                       datetime.timedelta(weeks=52),
2606
 
                       frozenset((token_month, token_end)))
2607
 
    token_week = Token(re.compile(r"(\d+)W"),
2608
 
                       datetime.timedelta(weeks=1),
2609
 
                       frozenset((token_end, )))
2610
 
    token_duration = Token(re.compile(r"P"), None,
2611
 
                           frozenset((token_year, token_month,
2612
 
                                      token_day, token_time,
2613
 
                                      token_week)))
2614
 
    # Define starting values
2615
 
    value = datetime.timedelta() # Value so far
2616
 
    found_token = None
2617
 
    followers = frozenset((token_duration, )) # Following valid tokens
2618
 
    s = duration                # String left to parse
2619
 
    # Loop until end token is found
2620
 
    while found_token is not token_end:
2621
 
        # Search for any currently valid tokens
2622
 
        for token in followers:
2623
 
            match = token.regexp.match(s)
2624
 
            if match is not None:
2625
 
                # Token found
2626
 
                if token.value is not None:
2627
 
                    # Value found, parse digits
2628
 
                    factor = int(match.group(1), 10)
2629
 
                    # Add to value so far
2630
 
                    value += factor * token.value
2631
 
                # Strip token from string
2632
 
                s = token.regexp.sub("", s, 1)
2633
 
                # Go to found token
2634
 
                found_token = token
2635
 
                # Set valid next tokens
2636
 
                followers = found_token.followers
2637
 
                break
2638
 
        else:
2639
 
            # No currently valid tokens were found
2640
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2641
 
                             .format(duration))
2642
 
    # End token found
2643
 
    return value
2644
 
 
2645
 
 
2646
2065
def string_to_delta(interval):
2647
2066
    """Parse a string and return a datetime.timedelta
2648
2067
    
2659
2078
    >>> string_to_delta('5m 30s')
2660
2079
    datetime.timedelta(0, 330)
2661
2080
    """
2662
 
    
2663
 
    try:
2664
 
        return rfc3339_duration_to_delta(interval)
2665
 
    except ValueError:
2666
 
        pass
2667
 
    
2668
2081
    timevalue = datetime.timedelta(0)
2669
2082
    for s in interval.split():
2670
2083
        try:
2671
 
            suffix = s[-1]
 
2084
            suffix = unicode(s[-1])
2672
2085
            value = int(s[:-1])
2673
2086
            if suffix == "d":
2674
2087
                delta = datetime.timedelta(value)
2681
2094
            elif suffix == "w":
2682
2095
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2683
2096
            else:
2684
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
2685
 
        except IndexError as e:
 
2097
                raise ValueError("Unknown suffix {0!r}"
 
2098
                                 .format(suffix))
 
2099
        except (ValueError, IndexError) as e:
2686
2100
            raise ValueError(*(e.args))
2687
2101
        timevalue += delta
2688
2102
    return timevalue
2704
2118
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2705
2119
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2706
2120
            raise OSError(errno.ENODEV,
2707
 
                          "{} not a character device"
 
2121
                          "{0} not a character device"
2708
2122
                          .format(os.devnull))
2709
2123
        os.dup2(null, sys.stdin.fileno())
2710
2124
        os.dup2(null, sys.stdout.fileno())
2720
2134
    
2721
2135
    parser = argparse.ArgumentParser()
2722
2136
    parser.add_argument("-v", "--version", action="version",
2723
 
                        version = "%(prog)s {}".format(version),
 
2137
                        version = "%(prog)s {0}".format(version),
2724
2138
                        help="show version number and exit")
2725
2139
    parser.add_argument("-i", "--interface", metavar="IF",
2726
2140
                        help="Bind to interface IF")
2732
2146
                        help="Run self-test")
2733
2147
    parser.add_argument("--debug", action="store_true",
2734
2148
                        help="Debug mode; run in foreground and log"
2735
 
                        " to terminal", default=None)
 
2149
                        " to terminal")
2736
2150
    parser.add_argument("--debuglevel", metavar="LEVEL",
2737
2151
                        help="Debug level for stdout output")
2738
2152
    parser.add_argument("--priority", help="GnuTLS"
2745
2159
                        " files")
2746
2160
    parser.add_argument("--no-dbus", action="store_false",
2747
2161
                        dest="use_dbus", help="Do not provide D-Bus"
2748
 
                        " system bus interface", default=None)
 
2162
                        " system bus interface")
2749
2163
    parser.add_argument("--no-ipv6", action="store_false",
2750
 
                        dest="use_ipv6", help="Do not use IPv6",
2751
 
                        default=None)
 
2164
                        dest="use_ipv6", help="Do not use IPv6")
2752
2165
    parser.add_argument("--no-restore", action="store_false",
2753
2166
                        dest="restore", help="Do not restore stored"
2754
 
                        " state", default=None)
2755
 
    parser.add_argument("--socket", type=int,
2756
 
                        help="Specify a file descriptor to a network"
2757
 
                        " socket to use instead of creating one")
 
2167
                        " state")
2758
2168
    parser.add_argument("--statedir", metavar="DIR",
2759
2169
                        help="Directory to save/restore state in")
2760
 
    parser.add_argument("--foreground", action="store_true",
2761
 
                        help="Run in foreground", default=None)
2762
 
    parser.add_argument("--no-zeroconf", action="store_false",
2763
 
                        dest="zeroconf", help="Do not use Zeroconf",
2764
 
                        default=None)
2765
2170
    
2766
2171
    options = parser.parse_args()
2767
2172
    
2768
2173
    if options.check:
2769
2174
        import doctest
2770
 
        fail_count, test_count = doctest.testmod()
2771
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2175
        doctest.testmod()
 
2176
        sys.exit()
2772
2177
    
2773
2178
    # Default values for config file for server-global settings
2774
2179
    server_defaults = { "interface": "",
2776
2181
                        "port": "",
2777
2182
                        "debug": "False",
2778
2183
                        "priority":
2779
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2780
 
                        ":+SIGN-DSA-SHA256",
 
2184
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
2781
2185
                        "servicename": "Mandos",
2782
2186
                        "use_dbus": "True",
2783
2187
                        "use_ipv6": "True",
2784
2188
                        "debuglevel": "",
2785
2189
                        "restore": "True",
2786
 
                        "socket": "",
2787
 
                        "statedir": "/var/lib/mandos",
2788
 
                        "foreground": "False",
2789
 
                        "zeroconf": "True",
2790
 
                    }
 
2190
                        "statedir": "/var/lib/mandos"
 
2191
                        }
2791
2192
    
2792
2193
    # Parse config file for server-global settings
2793
2194
    server_config = configparser.SafeConfigParser(server_defaults)
2794
2195
    del server_defaults
2795
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2196
    server_config.read(os.path.join(options.configdir,
 
2197
                                    "mandos.conf"))
2796
2198
    # Convert the SafeConfigParser object to a dict
2797
2199
    server_settings = server_config.defaults()
2798
2200
    # Use the appropriate methods on the non-string config options
2799
 
    for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
 
2201
    for option in ("debug", "use_dbus", "use_ipv6"):
2800
2202
        server_settings[option] = server_config.getboolean("DEFAULT",
2801
2203
                                                           option)
2802
2204
    if server_settings["port"]:
2803
2205
        server_settings["port"] = server_config.getint("DEFAULT",
2804
2206
                                                       "port")
2805
 
    if server_settings["socket"]:
2806
 
        server_settings["socket"] = server_config.getint("DEFAULT",
2807
 
                                                         "socket")
2808
 
        # Later, stdin will, and stdout and stderr might, be dup'ed
2809
 
        # over with an opened os.devnull.  But we don't want this to
2810
 
        # happen with a supplied network socket.
2811
 
        if 0 <= server_settings["socket"] <= 2:
2812
 
            server_settings["socket"] = os.dup(server_settings
2813
 
                                               ["socket"])
2814
2207
    del server_config
2815
2208
    
2816
2209
    # Override the settings from the config file with command line
2817
2210
    # options, if set.
2818
2211
    for option in ("interface", "address", "port", "debug",
2819
 
                   "priority", "servicename", "configdir", "use_dbus",
2820
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2821
 
                   "socket", "foreground", "zeroconf"):
 
2212
                   "priority", "servicename", "configdir",
 
2213
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2214
                   "statedir"):
2822
2215
        value = getattr(options, option)
2823
2216
        if value is not None:
2824
2217
            server_settings[option] = value
2825
2218
    del options
2826
2219
    # Force all strings to be unicode
2827
2220
    for option in server_settings.keys():
2828
 
        if isinstance(server_settings[option], bytes):
2829
 
            server_settings[option] = (server_settings[option]
2830
 
                                       .decode("utf-8"))
2831
 
    # Force all boolean options to be boolean
2832
 
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2833
 
                   "foreground", "zeroconf"):
2834
 
        server_settings[option] = bool(server_settings[option])
2835
 
    # Debug implies foreground
2836
 
    if server_settings["debug"]:
2837
 
        server_settings["foreground"] = True
 
2221
        if type(server_settings[option]) is str:
 
2222
            server_settings[option] = unicode(server_settings[option])
2838
2223
    # Now we have our good server settings in "server_settings"
2839
2224
    
2840
2225
    ##################################################################
2841
2226
    
2842
 
    if (not server_settings["zeroconf"]
2843
 
        and not (server_settings["port"]
2844
 
                 or server_settings["socket"] != "")):
2845
 
        parser.error("Needs port or socket to work without Zeroconf")
2846
 
    
2847
2227
    # For convenience
2848
2228
    debug = server_settings["debug"]
2849
2229
    debuglevel = server_settings["debuglevel"]
2851
2231
    use_ipv6 = server_settings["use_ipv6"]
2852
2232
    stored_state_path = os.path.join(server_settings["statedir"],
2853
2233
                                     stored_state_file)
2854
 
    foreground = server_settings["foreground"]
2855
 
    zeroconf = server_settings["zeroconf"]
2856
2234
    
2857
2235
    if debug:
2858
2236
        initlogger(debug, logging.DEBUG)
2864
2242
            initlogger(debug, level)
2865
2243
    
2866
2244
    if server_settings["servicename"] != "Mandos":
2867
 
        syslogger.setFormatter(
2868
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2869
 
                              ' %(levelname)s: %(message)s'.format(
2870
 
                                  server_settings["servicename"])))
 
2245
        syslogger.setFormatter(logging.Formatter
 
2246
                               ('Mandos ({0}) [%(process)d]:'
 
2247
                                ' %(levelname)s: %(message)s'
 
2248
                                .format(server_settings
 
2249
                                        ["servicename"])))
2871
2250
    
2872
2251
    # Parse config file with clients
2873
2252
    client_config = configparser.SafeConfigParser(Client
2878
2257
    global mandos_dbus_service
2879
2258
    mandos_dbus_service = None
2880
2259
    
2881
 
    socketfd = None
2882
 
    if server_settings["socket"] != "":
2883
 
        socketfd = server_settings["socket"]
2884
 
    tcp_server = MandosServer(
2885
 
        (server_settings["address"], server_settings["port"]),
2886
 
        ClientHandler,
2887
 
        interface=(server_settings["interface"] or None),
2888
 
        use_ipv6=use_ipv6,
2889
 
        gnutls_priority=server_settings["priority"],
2890
 
        use_dbus=use_dbus,
2891
 
        socketfd=socketfd)
2892
 
    if not foreground:
2893
 
        pidfilename = "/run/mandos.pid"
2894
 
        if not os.path.isdir("/run/."):
2895
 
            pidfilename = "/var/run/mandos.pid"
2896
 
        pidfile = None
 
2260
    tcp_server = MandosServer((server_settings["address"],
 
2261
                               server_settings["port"]),
 
2262
                              ClientHandler,
 
2263
                              interface=(server_settings["interface"]
 
2264
                                         or None),
 
2265
                              use_ipv6=use_ipv6,
 
2266
                              gnutls_priority=
 
2267
                              server_settings["priority"],
 
2268
                              use_dbus=use_dbus)
 
2269
    if not debug:
 
2270
        pidfilename = "/var/run/mandos.pid"
2897
2271
        try:
2898
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2272
            pidfile = open(pidfilename, "w")
2899
2273
        except IOError as e:
2900
2274
            logger.error("Could not open file %r", pidfilename,
2901
2275
                         exc_info=e)
2914
2288
        os.setgid(gid)
2915
2289
        os.setuid(uid)
2916
2290
    except OSError as error:
2917
 
        if error.errno != errno.EPERM:
2918
 
            raise
 
2291
        if error[0] != errno.EPERM:
 
2292
            raise error
2919
2293
    
2920
2294
    if debug:
2921
2295
        # Enable all possible GnuTLS debugging
2922
2296
        
2923
2297
        # "Use a log level over 10 to enable all debugging options."
2924
2298
        # - GnuTLS manual
2925
 
        gnutls.global_set_log_level(11)
 
2299
        gnutls.library.functions.gnutls_global_set_log_level(11)
2926
2300
        
2927
 
        @gnutls.log_func
 
2301
        @gnutls.library.types.gnutls_log_func
2928
2302
        def debug_gnutls(level, string):
2929
2303
            logger.debug("GnuTLS: %s", string[:-1])
2930
2304
        
2931
 
        gnutls.global_set_log_function(debug_gnutls)
 
2305
        (gnutls.library.functions
 
2306
         .gnutls_global_set_log_function(debug_gnutls))
2932
2307
        
2933
2308
        # Redirect stdin so all checkers get /dev/null
2934
2309
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2937
2312
            os.close(null)
2938
2313
    
2939
2314
    # Need to fork before connecting to D-Bus
2940
 
    if not foreground:
 
2315
    if not debug:
2941
2316
        # Close all input and output, do double fork, etc.
2942
2317
        daemon()
2943
2318
    
2944
 
    # multiprocessing will use threads, so before we use gobject we
2945
 
    # need to inform gobject that threads will be used.
2946
2319
    gobject.threads_init()
2947
2320
    
2948
2321
    global main_loop
2954
2327
    if use_dbus:
2955
2328
        try:
2956
2329
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2957
 
                                            bus,
2958
 
                                            do_not_queue=True)
2959
 
            old_bus_name = dbus.service.BusName(
2960
 
                "se.bsnet.fukt.Mandos", bus,
2961
 
                do_not_queue=True)
2962
 
        except dbus.exceptions.DBusException as e:
 
2330
                                            bus, do_not_queue=True)
 
2331
            old_bus_name = (dbus.service.BusName
 
2332
                            ("se.bsnet.fukt.Mandos", bus,
 
2333
                             do_not_queue=True))
 
2334
        except dbus.exceptions.NameExistsException as e:
2963
2335
            logger.error("Disabling D-Bus:", exc_info=e)
2964
2336
            use_dbus = False
2965
2337
            server_settings["use_dbus"] = False
2966
2338
            tcp_server.use_dbus = False
2967
 
    if zeroconf:
2968
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2969
 
        service = AvahiServiceToSyslog(
2970
 
            name = server_settings["servicename"],
2971
 
            servicetype = "_mandos._tcp",
2972
 
            protocol = protocol,
2973
 
            bus = bus)
2974
 
        if server_settings["interface"]:
2975
 
            service.interface = if_nametoindex(
2976
 
                server_settings["interface"].encode("utf-8"))
 
2339
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2340
    service = AvahiServiceToSyslog(name =
 
2341
                                   server_settings["servicename"],
 
2342
                                   servicetype = "_mandos._tcp",
 
2343
                                   protocol = protocol, bus = bus)
 
2344
    if server_settings["interface"]:
 
2345
        service.interface = (if_nametoindex
 
2346
                             (str(server_settings["interface"])))
2977
2347
    
2978
2348
    global multiprocessing_manager
2979
2349
    multiprocessing_manager = multiprocessing.Manager()
2986
2356
    old_client_settings = {}
2987
2357
    clients_data = {}
2988
2358
    
2989
 
    # This is used to redirect stdout and stderr for checker processes
2990
 
    global wnull
2991
 
    wnull = open(os.devnull, "w") # A writable /dev/null
2992
 
    # Only used if server is running in foreground but not in debug
2993
 
    # mode
2994
 
    if debug or not foreground:
2995
 
        wnull.close()
2996
 
    
2997
2359
    # Get client data and settings from last running state.
2998
2360
    if server_settings["restore"]:
2999
2361
        try:
3000
2362
            with open(stored_state_path, "rb") as stored_state:
3001
 
                clients_data, old_client_settings = pickle.load(
3002
 
                    stored_state)
 
2363
                clients_data, old_client_settings = (pickle.load
 
2364
                                                     (stored_state))
3003
2365
            os.remove(stored_state_path)
3004
2366
        except IOError as e:
3005
2367
            if e.errno == errno.ENOENT:
3006
 
                logger.warning("Could not load persistent state:"
3007
 
                               " {}".format(os.strerror(e.errno)))
 
2368
                logger.warning("Could not load persistent state: {0}"
 
2369
                                .format(os.strerror(e.errno)))
3008
2370
            else:
3009
2371
                logger.critical("Could not load persistent state:",
3010
2372
                                exc_info=e)
3011
2373
                raise
3012
2374
        except EOFError as e:
3013
2375
            logger.warning("Could not load persistent state: "
3014
 
                           "EOFError:",
3015
 
                           exc_info=e)
 
2376
                           "EOFError:", exc_info=e)
3016
2377
    
3017
2378
    with PGPEngine() as pgp:
3018
 
        for client_name, client in clients_data.items():
3019
 
            # Skip removed clients
3020
 
            if client_name not in client_settings:
3021
 
                continue
3022
 
            
 
2379
        for client_name, client in clients_data.iteritems():
3023
2380
            # Decide which value to use after restoring saved state.
3024
2381
            # We have three different values: Old config file,
3025
2382
            # new config file, and saved state.
3030
2387
                    # For each value in new config, check if it
3031
2388
                    # differs from the old config value (Except for
3032
2389
                    # the "secret" attribute)
3033
 
                    if (name != "secret"
3034
 
                        and (value !=
3035
 
                             old_client_settings[client_name][name])):
 
2390
                    if (name != "secret" and
 
2391
                        value != old_client_settings[client_name]
 
2392
                        [name]):
3036
2393
                        client[name] = value
3037
2394
                except KeyError:
3038
2395
                    pass
3039
2396
            
3040
2397
            # Clients who has passed its expire date can still be
3041
 
            # enabled if its last checker was successful.  A Client
 
2398
            # enabled if its last checker was successful.  Clients
3042
2399
            # whose checker succeeded before we stored its state is
3043
2400
            # assumed to have successfully run all checkers during
3044
2401
            # downtime.
3046
2403
                if datetime.datetime.utcnow() >= client["expires"]:
3047
2404
                    if not client["last_checked_ok"]:
3048
2405
                        logger.warning(
3049
 
                            "disabling client {} - Client never "
3050
 
                            "performed a successful checker".format(
3051
 
                                client_name))
 
2406
                            "disabling client {0} - Client never "
 
2407
                            "performed a successful checker"
 
2408
                            .format(client_name))
3052
2409
                        client["enabled"] = False
3053
2410
                    elif client["last_checker_status"] != 0:
3054
2411
                        logger.warning(
3055
 
                            "disabling client {} - Client last"
3056
 
                            " checker failed with error code"
3057
 
                            " {}".format(
3058
 
                                client_name,
3059
 
                                client["last_checker_status"]))
 
2412
                            "disabling client {0} - Client "
 
2413
                            "last checker failed with error code {1}"
 
2414
                            .format(client_name,
 
2415
                                    client["last_checker_status"]))
3060
2416
                        client["enabled"] = False
3061
2417
                    else:
3062
 
                        client["expires"] = (
3063
 
                            datetime.datetime.utcnow()
3064
 
                            + client["timeout"])
 
2418
                        client["expires"] = (datetime.datetime
 
2419
                                             .utcnow()
 
2420
                                             + client["timeout"])
3065
2421
                        logger.debug("Last checker succeeded,"
3066
 
                                     " keeping {} enabled".format(
3067
 
                                         client_name))
 
2422
                                     " keeping {0} enabled"
 
2423
                                     .format(client_name))
3068
2424
            try:
3069
 
                client["secret"] = pgp.decrypt(
3070
 
                    client["encrypted_secret"],
3071
 
                    client_settings[client_name]["secret"])
 
2425
                client["secret"] = (
 
2426
                    pgp.decrypt(client["encrypted_secret"],
 
2427
                                client_settings[client_name]
 
2428
                                ["secret"]))
3072
2429
            except PGPError:
3073
2430
                # If decryption fails, we use secret from new settings
3074
 
                logger.debug("Failed to decrypt {} old secret".format(
3075
 
                    client_name))
3076
 
                client["secret"] = (client_settings[client_name]
3077
 
                                    ["secret"])
 
2431
                logger.debug("Failed to decrypt {0} old secret"
 
2432
                             .format(client_name))
 
2433
                client["secret"] = (
 
2434
                    client_settings[client_name]["secret"])
3078
2435
    
3079
2436
    # Add/remove clients based on new changes made to config
3080
2437
    for client_name in (set(old_client_settings)
3085
2442
        clients_data[client_name] = client_settings[client_name]
3086
2443
    
3087
2444
    # Create all client objects
3088
 
    for client_name, client in clients_data.items():
 
2445
    for client_name, client in clients_data.iteritems():
3089
2446
        tcp_server.clients[client_name] = client_class(
3090
 
            name = client_name,
3091
 
            settings = client,
3092
 
            server_settings = server_settings)
 
2447
            name = client_name, settings = client)
3093
2448
    
3094
2449
    if not tcp_server.clients:
3095
2450
        logger.warning("No clients defined")
3096
2451
    
3097
 
    if not foreground:
3098
 
        if pidfile is not None:
3099
 
            pid = os.getpid()
3100
 
            try:
3101
 
                with pidfile:
3102
 
                    print(pid, file=pidfile)
3103
 
            except IOError:
3104
 
                logger.error("Could not write to file %r with PID %d",
3105
 
                             pidfilename, pid)
3106
 
        del pidfile
 
2452
    if not debug:
 
2453
        try:
 
2454
            with pidfile:
 
2455
                pid = os.getpid()
 
2456
                pidfile.write(str(pid) + "\n".encode("utf-8"))
 
2457
            del pidfile
 
2458
        except IOError:
 
2459
            logger.error("Could not write to file %r with PID %d",
 
2460
                         pidfilename, pid)
 
2461
        except NameError:
 
2462
            # "pidfile" was never created
 
2463
            pass
3107
2464
        del pidfilename
 
2465
        signal.signal(signal.SIGINT, signal.SIG_IGN)
3108
2466
    
3109
2467
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
3110
2468
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
3111
2469
    
3112
2470
    if use_dbus:
3113
 
        
3114
 
        @alternate_dbus_interfaces(
3115
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
3116
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2471
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2472
                                        "se.bsnet.fukt.Mandos"})
 
2473
        class MandosDBusService(DBusObjectWithProperties):
3117
2474
            """A D-Bus proxy object"""
3118
 
            
3119
2475
            def __init__(self):
3120
2476
                dbus.service.Object.__init__(self, bus, "/")
3121
 
            
3122
2477
            _interface = "se.recompile.Mandos"
3123
2478
            
 
2479
            @dbus_interface_annotations(_interface)
 
2480
            def _foo(self):
 
2481
                return { "org.freedesktop.DBus.Property"
 
2482
                         ".EmitsChangedSignal":
 
2483
                             "false"}
 
2484
            
3124
2485
            @dbus.service.signal(_interface, signature="o")
3125
2486
            def ClientAdded(self, objpath):
3126
2487
                "D-Bus signal"
3131
2492
                "D-Bus signal"
3132
2493
                pass
3133
2494
            
3134
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3135
 
                               "true"})
3136
2495
            @dbus.service.signal(_interface, signature="os")
3137
2496
            def ClientRemoved(self, objpath, name):
3138
2497
                "D-Bus signal"
3139
2498
                pass
3140
2499
            
3141
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3142
 
                               "true"})
3143
2500
            @dbus.service.method(_interface, out_signature="ao")
3144
2501
            def GetAllClients(self):
3145
2502
                "D-Bus method"
3146
 
                return dbus.Array(c.dbus_object_path for c in
 
2503
                return dbus.Array(c.dbus_object_path
 
2504
                                  for c in
3147
2505
                                  tcp_server.clients.itervalues())
3148
2506
            
3149
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3150
 
                               "true"})
3151
2507
            @dbus.service.method(_interface,
3152
2508
                                 out_signature="a{oa{sv}}")
3153
2509
            def GetAllClientsWithProperties(self):
3154
2510
                "D-Bus method"
3155
2511
                return dbus.Dictionary(
3156
 
                    { c.dbus_object_path: c.GetAll(
3157
 
                        "se.recompile.Mandos.Client")
3158
 
                      for c in tcp_server.clients.itervalues() },
 
2512
                    ((c.dbus_object_path, c.GetAll(""))
 
2513
                     for c in tcp_server.clients.itervalues()),
3159
2514
                    signature="oa{sv}")
3160
2515
            
3161
2516
            @dbus.service.method(_interface, in_signature="o")
3165
2520
                    if c.dbus_object_path == object_path:
3166
2521
                        del tcp_server.clients[c.name]
3167
2522
                        c.remove_from_connection()
3168
 
                        # Don't signal the disabling
 
2523
                        # Don't signal anything except ClientRemoved
3169
2524
                        c.disable(quiet=True)
3170
 
                        # Emit D-Bus signal for removal
3171
 
                        self.client_removed_signal(c)
 
2525
                        # Emit D-Bus signal
 
2526
                        self.ClientRemoved(object_path, c.name)
3172
2527
                        return
3173
2528
                raise KeyError(object_path)
3174
2529
            
3175
2530
            del _interface
3176
 
            
3177
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3178
 
                                 out_signature = "a{oa{sa{sv}}}")
3179
 
            def GetManagedObjects(self):
3180
 
                """D-Bus method"""
3181
 
                return dbus.Dictionary(
3182
 
                    { client.dbus_object_path:
3183
 
                      dbus.Dictionary(
3184
 
                          { interface: client.GetAll(interface)
3185
 
                            for interface in
3186
 
                                 client._get_all_interface_names()})
3187
 
                      for client in tcp_server.clients.values()})
3188
 
            
3189
 
            def client_added_signal(self, client):
3190
 
                """Send the new standard signal and the old signal"""
3191
 
                if use_dbus:
3192
 
                    # New standard signal
3193
 
                    self.InterfacesAdded(
3194
 
                        client.dbus_object_path,
3195
 
                        dbus.Dictionary(
3196
 
                            { interface: client.GetAll(interface)
3197
 
                              for interface in
3198
 
                              client._get_all_interface_names()}))
3199
 
                    # Old signal
3200
 
                    self.ClientAdded(client.dbus_object_path)
3201
 
            
3202
 
            def client_removed_signal(self, client):
3203
 
                """Send the new standard signal and the old signal"""
3204
 
                if use_dbus:
3205
 
                    # New standard signal
3206
 
                    self.InterfacesRemoved(
3207
 
                        client.dbus_object_path,
3208
 
                        client._get_all_interface_names())
3209
 
                    # Old signal
3210
 
                    self.ClientRemoved(client.dbus_object_path,
3211
 
                                       client.name)
3212
2531
        
3213
2532
        mandos_dbus_service = MandosDBusService()
3214
2533
    
3215
2534
    def cleanup():
3216
2535
        "Cleanup function; run on exit"
3217
 
        if zeroconf:
3218
 
            service.cleanup()
 
2536
        service.cleanup()
3219
2537
        
3220
2538
        multiprocessing.active_children()
3221
 
        wnull.close()
3222
2539
        if not (tcp_server.clients or client_settings):
3223
2540
            return
3224
2541
        
3235
2552
                
3236
2553
                # A list of attributes that can not be pickled
3237
2554
                # + secret.
3238
 
                exclude = { "bus", "changedstate", "secret",
3239
 
                            "checker", "server_settings" }
3240
 
                for name, typ in inspect.getmembers(dbus.service
3241
 
                                                    .Object):
 
2555
                exclude = set(("bus", "changedstate", "secret",
 
2556
                               "checker"))
 
2557
                for name, typ in (inspect.getmembers
 
2558
                                  (dbus.service.Object)):
3242
2559
                    exclude.add(name)
3243
2560
                
3244
2561
                client_dict["encrypted_secret"] = (client
3251
2568
                del client_settings[client.name]["secret"]
3252
2569
        
3253
2570
        try:
3254
 
            with tempfile.NamedTemporaryFile(
3255
 
                    mode='wb',
3256
 
                    suffix=".pickle",
3257
 
                    prefix='clients-',
3258
 
                    dir=os.path.dirname(stored_state_path),
3259
 
                    delete=False) as stored_state:
 
2571
            with (tempfile.NamedTemporaryFile
 
2572
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2573
                   dir=os.path.dirname(stored_state_path),
 
2574
                   delete=False)) as stored_state:
3260
2575
                pickle.dump((clients, client_settings), stored_state)
3261
 
                tempname = stored_state.name
 
2576
                tempname=stored_state.name
3262
2577
            os.rename(tempname, stored_state_path)
3263
2578
        except (IOError, OSError) as e:
3264
2579
            if not debug:
3267
2582
                except NameError:
3268
2583
                    pass
3269
2584
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
3270
 
                logger.warning("Could not save persistent state: {}"
 
2585
                logger.warning("Could not save persistent state: {0}"
3271
2586
                               .format(os.strerror(e.errno)))
3272
2587
            else:
3273
2588
                logger.warning("Could not save persistent state:",
3274
2589
                               exc_info=e)
3275
 
                raise
 
2590
                raise e
3276
2591
        
3277
2592
        # Delete all clients, and settings from config
3278
2593
        while tcp_server.clients:
3279
2594
            name, client = tcp_server.clients.popitem()
3280
2595
            if use_dbus:
3281
2596
                client.remove_from_connection()
3282
 
            # Don't signal the disabling
 
2597
            # Don't signal anything except ClientRemoved
3283
2598
            client.disable(quiet=True)
3284
 
            # Emit D-Bus signal for removal
3285
2599
            if use_dbus:
3286
 
                mandos_dbus_service.client_removed_signal(client)
 
2600
                # Emit D-Bus signal
 
2601
                mandos_dbus_service.ClientRemoved(client
 
2602
                                                  .dbus_object_path,
 
2603
                                                  client.name)
3287
2604
        client_settings.clear()
3288
2605
    
3289
2606
    atexit.register(cleanup)
3290
2607
    
3291
2608
    for client in tcp_server.clients.itervalues():
3292
2609
        if use_dbus:
3293
 
            # Emit D-Bus signal for adding
3294
 
            mandos_dbus_service.client_added_signal(client)
 
2610
            # Emit D-Bus signal
 
2611
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3295
2612
        # Need to initiate checking of clients
3296
2613
        if client.enabled:
3297
2614
            client.init_checker()
3300
2617
    tcp_server.server_activate()
3301
2618
    
3302
2619
    # Find out what port we got
3303
 
    if zeroconf:
3304
 
        service.port = tcp_server.socket.getsockname()[1]
 
2620
    service.port = tcp_server.socket.getsockname()[1]
3305
2621
    if use_ipv6:
3306
2622
        logger.info("Now listening on address %r, port %d,"
3307
2623
                    " flowinfo %d, scope_id %d",
3313
2629
    #service.interface = tcp_server.socket.getsockname()[3]
3314
2630
    
3315
2631
    try:
3316
 
        if zeroconf:
3317
 
            # From the Avahi example code
3318
 
            try:
3319
 
                service.activate()
3320
 
            except dbus.exceptions.DBusException as error:
3321
 
                logger.critical("D-Bus Exception", exc_info=error)
3322
 
                cleanup()
3323
 
                sys.exit(1)
3324
 
            # End of Avahi example code
 
2632
        # From the Avahi example code
 
2633
        try:
 
2634
            service.activate()
 
2635
        except dbus.exceptions.DBusException as error:
 
2636
            logger.critical("D-Bus Exception", exc_info=error)
 
2637
            cleanup()
 
2638
            sys.exit(1)
 
2639
        # End of Avahi example code
3325
2640
        
3326
2641
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
3327
2642
                             lambda *args, **kwargs:
3342
2657
    # Must run before the D-Bus bus name gets deregistered
3343
2658
    cleanup()
3344
2659
 
3345
 
 
3346
2660
if __name__ == '__main__':
3347
2661
    main()