/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: 2023-02-08 00:05:18 UTC
  • mto: This revision was merged to the branch mainline in revision 1272.
  • Revision ID: teddy@recompile.se-20230208000518-8p1ajaga9szbln3o
Tags: version-1.8.16-1
Version 1.8.16-1

* Makefile (version): Change to "1.8.16".
* NEWS (Version 1.8.16): Add new entry.
* debian/changelog (1.8.16-1): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
# -*- mode: python; coding: utf-8 -*-
 
1
#!/usr/bin/python3 -bI
 
2
# -*- coding: utf-8; lexical-binding: t -*-
3
3
#
4
4
# Mandos server - give out binary blobs to connecting clients.
5
5
#
11
11
# "AvahiService" class, and some lines in "main".
12
12
#
13
13
# Everything else is
14
 
# Copyright © 2008-2019 Teddy Hogeborn
15
 
# Copyright © 2008-2019 Björn Påhlsson
 
14
# Copyright © 2008-2022 Teddy Hogeborn
 
15
# Copyright © 2008-2022 Björn Påhlsson
16
16
#
17
17
# This file is part of Mandos.
18
18
#
31
31
#
32
32
# Contact the authors at <mandos@recompile.se>.
33
33
#
34
 
 
35
34
from __future__ import (division, absolute_import, print_function,
36
35
                        unicode_literals)
37
36
 
40
39
except ImportError:
41
40
    pass
42
41
 
 
42
import sys
 
43
import unittest
 
44
import argparse
 
45
import logging
 
46
import os
43
47
try:
44
48
    import SocketServer as socketserver
45
49
except ImportError:
46
50
    import socketserver
47
51
import socket
48
 
import argparse
49
52
import datetime
50
53
import errno
51
54
try:
52
55
    import ConfigParser as configparser
53
56
except ImportError:
54
57
    import configparser
55
 
import sys
56
58
import re
57
 
import os
58
59
import signal
59
60
import subprocess
60
61
import atexit
61
62
import stat
62
 
import logging
63
63
import logging.handlers
64
64
import pwd
65
65
import contextlib
77
77
import itertools
78
78
import collections
79
79
import codecs
 
80
import random
 
81
import shlex
80
82
 
81
83
import dbus
82
84
import dbus.service
 
85
import gi
83
86
from gi.repository import GLib
84
87
from dbus.mainloop.glib import DBusGMainLoop
85
88
import ctypes
87
90
import xml.dom.minidom
88
91
import inspect
89
92
 
 
93
if sys.version_info.major == 2:
 
94
    __metaclass__ = type
 
95
    str = unicode
 
96
    input = raw_input
 
97
 
 
98
# Add collections.abc.Callable if it does not exist
 
99
try:
 
100
    collections.abc.Callable
 
101
except AttributeError:
 
102
    class abc:
 
103
        Callable = collections.Callable
 
104
    collections.abc = abc
 
105
    del abc
 
106
 
 
107
# Add shlex.quote if it does not exist
 
108
try:
 
109
    shlex.quote
 
110
except AttributeError:
 
111
    shlex.quote = re.escape
 
112
 
 
113
# Show warnings by default
 
114
if not sys.warnoptions:
 
115
    import warnings
 
116
    warnings.simplefilter("default")
 
117
 
90
118
# Try to find the value of SO_BINDTODEVICE:
91
119
try:
92
120
    # This is where SO_BINDTODEVICE is in Python 3.3 (or 3.4?) and
112
140
            # No value found
113
141
            SO_BINDTODEVICE = None
114
142
 
115
 
if sys.version_info.major == 2:
116
 
    str = unicode
 
143
if sys.version_info < (3, 2):
 
144
    configparser.Configparser = configparser.SafeConfigParser
117
145
 
118
 
version = "1.8.4"
 
146
version = "1.8.16"
119
147
stored_state_file = "clients.pickle"
120
148
 
121
 
logger = logging.getLogger()
 
149
log = logging.getLogger(os.path.basename(sys.argv[0]))
 
150
logging.captureWarnings(True)   # Show warnings via the logging system
122
151
syslogger = None
123
152
 
124
153
try:
160
189
        facility=logging.handlers.SysLogHandler.LOG_DAEMON,
161
190
        address="/dev/log"))
162
191
    syslogger.setFormatter(logging.Formatter
163
 
                           ('Mandos [%(process)d]: %(levelname)s:'
164
 
                            ' %(message)s'))
165
 
    logger.addHandler(syslogger)
 
192
                           ("Mandos [%(process)d]: %(levelname)s:"
 
193
                            " %(message)s"))
 
194
    log.addHandler(syslogger)
166
195
 
167
196
    if debug:
168
197
        console = logging.StreamHandler()
169
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
170
 
                                               ' [%(process)d]:'
171
 
                                               ' %(levelname)s:'
172
 
                                               ' %(message)s'))
173
 
        logger.addHandler(console)
174
 
    logger.setLevel(level)
 
198
        console.setFormatter(logging.Formatter("%(asctime)s %(name)s"
 
199
                                               " [%(process)d]:"
 
200
                                               " %(levelname)s:"
 
201
                                               " %(message)s"))
 
202
        log.addHandler(console)
 
203
    log.setLevel(level)
175
204
 
176
205
 
177
206
class PGPError(Exception):
179
208
    pass
180
209
 
181
210
 
182
 
class PGPEngine(object):
 
211
class PGPEngine:
183
212
    """A simple class for OpenPGP symmetric encryption & decryption"""
184
213
 
185
214
    def __init__(self):
189
218
            output = subprocess.check_output(["gpgconf"])
190
219
            for line in output.splitlines():
191
220
                name, text, path = line.split(b":")
192
 
                if name == "gpg":
 
221
                if name == b"gpg":
193
222
                    self.gpg = path
194
223
                    break
195
224
        except OSError as e:
196
225
            if e.errno != errno.ENOENT:
197
226
                raise
198
 
        self.gnupgargs = ['--batch',
199
 
                          '--homedir', self.tempdir,
200
 
                          '--force-mdc',
201
 
                          '--quiet']
 
227
        self.gnupgargs = ["--batch",
 
228
                          "--homedir", self.tempdir,
 
229
                          "--force-mdc",
 
230
                          "--quiet"]
202
231
        # Only GPG version 1 has the --no-use-agent option.
203
 
        if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
 
232
        if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
204
233
            self.gnupgargs.append("--no-use-agent")
205
234
 
206
235
    def __enter__(self):
243
272
                dir=self.tempdir) as passfile:
244
273
            passfile.write(passphrase)
245
274
            passfile.flush()
246
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
247
 
                                     '--passphrase-file',
 
275
            proc = subprocess.Popen([self.gpg, "--symmetric",
 
276
                                     "--passphrase-file",
248
277
                                     passfile.name]
249
278
                                    + self.gnupgargs,
250
279
                                    stdin=subprocess.PIPE,
261
290
                dir=self.tempdir) as passfile:
262
291
            passfile.write(passphrase)
263
292
            passfile.flush()
264
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
265
 
                                     '--passphrase-file',
 
293
            proc = subprocess.Popen([self.gpg, "--decrypt",
 
294
                                     "--passphrase-file",
266
295
                                     passfile.name]
267
296
                                    + self.gnupgargs,
268
297
                                    stdin=subprocess.PIPE,
275
304
 
276
305
 
277
306
# Pretend that we have an Avahi module
278
 
class avahi(object):
 
307
class avahi:
279
308
    """This isn't so much a class as it is a module-like namespace."""
280
309
    IF_UNSPEC = -1               # avahi-common/address.h
281
310
    PROTO_UNSPEC = -1            # avahi-common/address.h
315
344
    pass
316
345
 
317
346
 
318
 
class AvahiService(object):
 
347
class AvahiService:
319
348
    """An Avahi (Zeroconf) service.
320
349
 
321
350
    Attributes:
322
351
    interface: integer; avahi.IF_UNSPEC or an interface index.
323
352
               Used to optionally bind to the specified interface.
324
 
    name: string; Example: 'Mandos'
325
 
    type: string; Example: '_mandos._tcp'.
 
353
    name: string; Example: "Mandos"
 
354
    type: string; Example: "_mandos._tcp".
326
355
     See <https://www.iana.org/assignments/service-names-port-numbers>
327
356
    port: integer; what port to announce
328
357
    TXT: list of strings; TXT record for the service
365
394
    def rename(self, remove=True):
366
395
        """Derived from the Avahi example code"""
367
396
        if self.rename_count >= self.max_renames:
368
 
            logger.critical("No suitable Zeroconf service name found"
369
 
                            " after %i retries, exiting.",
370
 
                            self.rename_count)
 
397
            log.critical("No suitable Zeroconf service name found"
 
398
                         " after %i retries, exiting.",
 
399
                         self.rename_count)
371
400
            raise AvahiServiceError("Too many renames")
372
401
        self.name = str(
373
402
            self.server.GetAlternativeServiceName(self.name))
374
403
        self.rename_count += 1
375
 
        logger.info("Changing Zeroconf service name to %r ...",
376
 
                    self.name)
 
404
        log.info("Changing Zeroconf service name to %r ...",
 
405
                 self.name)
377
406
        if remove:
378
407
            self.remove()
379
408
        try:
381
410
        except dbus.exceptions.DBusException as error:
382
411
            if (error.get_dbus_name()
383
412
                == "org.freedesktop.Avahi.CollisionError"):
384
 
                logger.info("Local Zeroconf service name collision.")
 
413
                log.info("Local Zeroconf service name collision.")
385
414
                return self.rename(remove=False)
386
415
            else:
387
 
                logger.critical("D-Bus Exception", exc_info=error)
 
416
                log.critical("D-Bus Exception", exc_info=error)
388
417
                self.cleanup()
389
418
                os._exit(1)
390
419
 
406
435
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
407
436
        self.entry_group_state_changed_match = (
408
437
            self.group.connect_to_signal(
409
 
                'StateChanged', self.entry_group_state_changed))
410
 
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
411
 
                     self.name, self.type)
 
438
                "StateChanged", self.entry_group_state_changed))
 
439
        log.debug("Adding Zeroconf service '%s' of type '%s' ...",
 
440
                  self.name, self.type)
412
441
        self.group.AddService(
413
442
            self.interface,
414
443
            self.protocol,
421
450
 
422
451
    def entry_group_state_changed(self, state, error):
423
452
        """Derived from the Avahi example code"""
424
 
        logger.debug("Avahi entry group state change: %i", state)
 
453
        log.debug("Avahi entry group state change: %i", state)
425
454
 
426
455
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
427
 
            logger.debug("Zeroconf service established.")
 
456
            log.debug("Zeroconf service established.")
428
457
        elif state == avahi.ENTRY_GROUP_COLLISION:
429
 
            logger.info("Zeroconf service name collision.")
 
458
            log.info("Zeroconf service name collision.")
430
459
            self.rename()
431
460
        elif state == avahi.ENTRY_GROUP_FAILURE:
432
 
            logger.critical("Avahi: Error in group state changed %s",
433
 
                            str(error))
 
461
            log.critical("Avahi: Error in group state changed %s",
 
462
                         str(error))
434
463
            raise AvahiGroupError("State changed: {!s}".format(error))
435
464
 
436
465
    def cleanup(self):
446
475
 
447
476
    def server_state_changed(self, state, error=None):
448
477
        """Derived from the Avahi example code"""
449
 
        logger.debug("Avahi server state change: %i", state)
 
478
        log.debug("Avahi server state change: %i", state)
450
479
        bad_states = {
451
480
            avahi.SERVER_INVALID: "Zeroconf server invalid",
452
481
            avahi.SERVER_REGISTERING: None,
456
485
        if state in bad_states:
457
486
            if bad_states[state] is not None:
458
487
                if error is None:
459
 
                    logger.error(bad_states[state])
 
488
                    log.error(bad_states[state])
460
489
                else:
461
 
                    logger.error(bad_states[state] + ": %r", error)
 
490
                    log.error(bad_states[state] + ": %r", error)
462
491
            self.cleanup()
463
492
        elif state == avahi.SERVER_RUNNING:
464
493
            try:
466
495
            except dbus.exceptions.DBusException as error:
467
496
                if (error.get_dbus_name()
468
497
                    == "org.freedesktop.Avahi.CollisionError"):
469
 
                    logger.info("Local Zeroconf service name"
470
 
                                " collision.")
 
498
                    log.info("Local Zeroconf service name collision.")
471
499
                    return self.rename(remove=False)
472
500
                else:
473
 
                    logger.critical("D-Bus Exception", exc_info=error)
 
501
                    log.critical("D-Bus Exception", exc_info=error)
474
502
                    self.cleanup()
475
503
                    os._exit(1)
476
504
        else:
477
505
            if error is None:
478
 
                logger.debug("Unknown state: %r", state)
 
506
                log.debug("Unknown state: %r", state)
479
507
            else:
480
 
                logger.debug("Unknown state: %r: %r", state, error)
 
508
                log.debug("Unknown state: %r: %r", state, error)
481
509
 
482
510
    def activate(self):
483
511
        """Derived from the Avahi example code"""
495
523
class AvahiServiceToSyslog(AvahiService):
496
524
    def rename(self, *args, **kwargs):
497
525
        """Add the new name to the syslog messages"""
498
 
        ret = super(AvahiServiceToSyslog, self).rename(*args, **kwargs)
 
526
        ret = super(AvahiServiceToSyslog, self).rename(*args,
 
527
                                                       **kwargs)
499
528
        syslogger.setFormatter(logging.Formatter(
500
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
 
529
            "Mandos ({}) [%(process)d]: %(levelname)s: %(message)s"
501
530
            .format(self.name)))
502
531
        return ret
503
532
 
504
533
 
505
534
# Pretend that we have a GnuTLS module
506
 
class gnutls(object):
 
535
class gnutls:
507
536
    """This isn't so much a class as it is a module-like namespace."""
508
537
 
509
538
    library = ctypes.util.find_library("gnutls")
533
562
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
534
563
 
535
564
    # Types
536
 
    class session_int(ctypes.Structure):
 
565
    class _session_int(ctypes.Structure):
537
566
        _fields_ = []
538
 
    session_t = ctypes.POINTER(session_int)
 
567
    session_t = ctypes.POINTER(_session_int)
539
568
 
540
569
    class certificate_credentials_st(ctypes.Structure):
541
570
        _fields_ = []
544
573
    certificate_type_t = ctypes.c_int
545
574
 
546
575
    class datum_t(ctypes.Structure):
547
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
548
 
                    ('size', ctypes.c_uint)]
 
576
        _fields_ = [("data", ctypes.POINTER(ctypes.c_ubyte)),
 
577
                    ("size", ctypes.c_uint)]
549
578
 
550
 
    class openpgp_crt_int(ctypes.Structure):
 
579
    class _openpgp_crt_int(ctypes.Structure):
551
580
        _fields_ = []
552
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
 
581
    openpgp_crt_t = ctypes.POINTER(_openpgp_crt_int)
553
582
    openpgp_crt_fmt_t = ctypes.c_int  # gnutls/openpgp.h
554
583
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
555
584
    credentials_type_t = ctypes.c_int
564
593
            # gnutls.strerror()
565
594
            self.code = code
566
595
            if message is None and code is not None:
567
 
                message = gnutls.strerror(code)
 
596
                message = gnutls.strerror(code).decode(
 
597
                    "utf-8", errors="replace")
568
598
            return super(gnutls.Error, self).__init__(
569
599
                message, *args)
570
600
 
571
601
    class CertificateSecurityError(Error):
572
602
        pass
573
603
 
 
604
    class PointerTo:
 
605
        def __init__(self, cls):
 
606
            self.cls = cls
 
607
 
 
608
        def from_param(self, obj):
 
609
            if not isinstance(obj, self.cls):
 
610
                raise TypeError("Not of type {}: {!r}"
 
611
                                .format(self.cls.__name__, obj))
 
612
            return ctypes.byref(obj.from_param(obj))
 
613
 
 
614
    class CastToVoidPointer:
 
615
        def __init__(self, cls):
 
616
            self.cls = cls
 
617
 
 
618
        def from_param(self, obj):
 
619
            if not isinstance(obj, self.cls):
 
620
                raise TypeError("Not of type {}: {!r}"
 
621
                                .format(self.cls.__name__, obj))
 
622
            return ctypes.cast(obj.from_param(obj), ctypes.c_void_p)
 
623
 
 
624
    class With_from_param:
 
625
        @classmethod
 
626
        def from_param(cls, obj):
 
627
            return obj._as_parameter_
 
628
 
574
629
    # Classes
575
 
    class Credentials(object):
 
630
    class Credentials(With_from_param):
576
631
        def __init__(self):
577
 
            self._c_object = gnutls.certificate_credentials_t()
578
 
            gnutls.certificate_allocate_credentials(
579
 
                ctypes.byref(self._c_object))
 
632
            self._as_parameter_ = gnutls.certificate_credentials_t()
 
633
            gnutls.certificate_allocate_credentials(self)
580
634
            self.type = gnutls.CRD_CERTIFICATE
581
635
 
582
636
        def __del__(self):
583
 
            gnutls.certificate_free_credentials(self._c_object)
 
637
            gnutls.certificate_free_credentials(self)
584
638
 
585
 
    class ClientSession(object):
 
639
    class ClientSession(With_from_param):
586
640
        def __init__(self, socket, credentials=None):
587
 
            self._c_object = gnutls.session_t()
 
641
            self._as_parameter_ = gnutls.session_t()
588
642
            gnutls_flags = gnutls.CLIENT
589
643
            if gnutls.check_version(b"3.5.6"):
590
644
                gnutls_flags |= gnutls.NO_TICKETS
591
645
            if gnutls.has_rawpk:
592
646
                gnutls_flags |= gnutls.ENABLE_RAWPK
593
 
            gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
 
647
            gnutls.init(self, gnutls_flags)
594
648
            del gnutls_flags
595
 
            gnutls.set_default_priority(self._c_object)
596
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
597
 
            gnutls.handshake_set_private_extensions(self._c_object,
598
 
                                                    True)
 
649
            gnutls.set_default_priority(self)
 
650
            gnutls.transport_set_ptr(self, socket.fileno())
 
651
            gnutls.handshake_set_private_extensions(self, True)
599
652
            self.socket = socket
600
653
            if credentials is None:
601
654
                credentials = gnutls.Credentials()
602
 
            gnutls.credentials_set(self._c_object, credentials.type,
603
 
                                   ctypes.cast(credentials._c_object,
604
 
                                               ctypes.c_void_p))
 
655
            gnutls.credentials_set(self, credentials.type,
 
656
                                   credentials)
605
657
            self.credentials = credentials
606
658
 
607
659
        def __del__(self):
608
 
            gnutls.deinit(self._c_object)
 
660
            gnutls.deinit(self)
609
661
 
610
662
        def handshake(self):
611
 
            return gnutls.handshake(self._c_object)
 
663
            return gnutls.handshake(self)
612
664
 
613
665
        def send(self, data):
614
666
            data = bytes(data)
615
667
            data_len = len(data)
616
668
            while data_len > 0:
617
 
                data_len -= gnutls.record_send(self._c_object,
618
 
                                               data[-data_len:],
 
669
                data_len -= gnutls.record_send(self, data[-data_len:],
619
670
                                               data_len)
620
671
 
621
672
        def bye(self):
622
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
 
673
            return gnutls.bye(self, gnutls.SHUT_RDWR)
623
674
 
624
675
    # Error handling functions
625
676
    def _error_code(result):
626
677
        """A function to raise exceptions on errors, suitable
627
 
        for the 'restype' attribute on ctypes functions"""
628
 
        if result >= 0:
 
678
        for the "restype" attribute on ctypes functions"""
 
679
        if result >= gnutls.E_SUCCESS:
629
680
            return result
630
681
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
631
682
            raise gnutls.CertificateSecurityError(code=result)
632
683
        raise gnutls.Error(code=result)
633
684
 
634
 
    def _retry_on_error(result, func, arguments):
 
685
    def _retry_on_error(result, func, arguments,
 
686
                        _error_code=_error_code):
635
687
        """A function to retry on some errors, suitable
636
 
        for the 'errcheck' attribute on ctypes functions"""
637
 
        while result < 0:
 
688
        for the "errcheck" attribute on ctypes functions"""
 
689
        while result < gnutls.E_SUCCESS:
638
690
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
639
691
                return _error_code(result)
640
692
            result = func(*arguments)
645
697
 
646
698
    # Functions
647
699
    priority_set_direct = _library.gnutls_priority_set_direct
648
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
 
700
    priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
649
701
                                    ctypes.POINTER(ctypes.c_char_p)]
650
702
    priority_set_direct.restype = _error_code
651
703
 
652
704
    init = _library.gnutls_init
653
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
 
705
    init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
654
706
    init.restype = _error_code
655
707
 
656
708
    set_default_priority = _library.gnutls_set_default_priority
657
 
    set_default_priority.argtypes = [session_t]
 
709
    set_default_priority.argtypes = [ClientSession]
658
710
    set_default_priority.restype = _error_code
659
711
 
660
712
    record_send = _library.gnutls_record_send
661
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
 
713
    record_send.argtypes = [ClientSession, ctypes.c_void_p,
662
714
                            ctypes.c_size_t]
663
715
    record_send.restype = ctypes.c_ssize_t
664
716
    record_send.errcheck = _retry_on_error
666
718
    certificate_allocate_credentials = (
667
719
        _library.gnutls_certificate_allocate_credentials)
668
720
    certificate_allocate_credentials.argtypes = [
669
 
        ctypes.POINTER(certificate_credentials_t)]
 
721
        PointerTo(Credentials)]
670
722
    certificate_allocate_credentials.restype = _error_code
671
723
 
672
724
    certificate_free_credentials = (
673
725
        _library.gnutls_certificate_free_credentials)
674
 
    certificate_free_credentials.argtypes = [
675
 
        certificate_credentials_t]
 
726
    certificate_free_credentials.argtypes = [Credentials]
676
727
    certificate_free_credentials.restype = None
677
728
 
678
729
    handshake_set_private_extensions = (
679
730
        _library.gnutls_handshake_set_private_extensions)
680
 
    handshake_set_private_extensions.argtypes = [session_t,
 
731
    handshake_set_private_extensions.argtypes = [ClientSession,
681
732
                                                 ctypes.c_int]
682
733
    handshake_set_private_extensions.restype = None
683
734
 
684
735
    credentials_set = _library.gnutls_credentials_set
685
 
    credentials_set.argtypes = [session_t, credentials_type_t,
686
 
                                ctypes.c_void_p]
 
736
    credentials_set.argtypes = [ClientSession, credentials_type_t,
 
737
                                CastToVoidPointer(Credentials)]
687
738
    credentials_set.restype = _error_code
688
739
 
689
740
    strerror = _library.gnutls_strerror
691
742
    strerror.restype = ctypes.c_char_p
692
743
 
693
744
    certificate_type_get = _library.gnutls_certificate_type_get
694
 
    certificate_type_get.argtypes = [session_t]
 
745
    certificate_type_get.argtypes = [ClientSession]
695
746
    certificate_type_get.restype = _error_code
696
747
 
697
748
    certificate_get_peers = _library.gnutls_certificate_get_peers
698
 
    certificate_get_peers.argtypes = [session_t,
 
749
    certificate_get_peers.argtypes = [ClientSession,
699
750
                                      ctypes.POINTER(ctypes.c_uint)]
700
751
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
701
752
 
708
759
    global_set_log_function.restype = None
709
760
 
710
761
    deinit = _library.gnutls_deinit
711
 
    deinit.argtypes = [session_t]
 
762
    deinit.argtypes = [ClientSession]
712
763
    deinit.restype = None
713
764
 
714
765
    handshake = _library.gnutls_handshake
715
 
    handshake.argtypes = [session_t]
716
 
    handshake.restype = _error_code
 
766
    handshake.argtypes = [ClientSession]
 
767
    handshake.restype = ctypes.c_int
717
768
    handshake.errcheck = _retry_on_error
718
769
 
719
770
    transport_set_ptr = _library.gnutls_transport_set_ptr
720
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
 
771
    transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
721
772
    transport_set_ptr.restype = None
722
773
 
723
774
    bye = _library.gnutls_bye
724
 
    bye.argtypes = [session_t, close_request_t]
725
 
    bye.restype = _error_code
 
775
    bye.argtypes = [ClientSession, close_request_t]
 
776
    bye.restype = ctypes.c_int
726
777
    bye.errcheck = _retry_on_error
727
778
 
728
779
    check_version = _library.gnutls_check_version
745
796
 
746
797
        x509_crt_fmt_t = ctypes.c_int
747
798
 
748
 
        # All the function declarations below are from gnutls/abstract.h
 
799
        # All the function declarations below are from
 
800
        # gnutls/abstract.h
749
801
        pubkey_init = _library.gnutls_pubkey_init
750
802
        pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
751
803
        pubkey_init.restype = _error_code
765
817
        pubkey_deinit.argtypes = [pubkey_t]
766
818
        pubkey_deinit.restype = None
767
819
    else:
768
 
        # All the function declarations below are from gnutls/openpgp.h
 
820
        # All the function declarations below are from
 
821
        # gnutls/openpgp.h
769
822
 
770
823
        openpgp_crt_init = _library.gnutls_openpgp_crt_init
771
824
        openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
777
830
                                       openpgp_crt_fmt_t]
778
831
        openpgp_crt_import.restype = _error_code
779
832
 
780
 
        openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
781
 
        openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
782
 
                                            ctypes.POINTER(ctypes.c_uint)]
 
833
        openpgp_crt_verify_self = \
 
834
            _library.gnutls_openpgp_crt_verify_self
 
835
        openpgp_crt_verify_self.argtypes = [
 
836
            openpgp_crt_t,
 
837
            ctypes.c_uint,
 
838
            ctypes.POINTER(ctypes.c_uint),
 
839
        ]
783
840
        openpgp_crt_verify_self.restype = _error_code
784
841
 
785
842
        openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
796
853
 
797
854
    if check_version(b"3.6.4"):
798
855
        certificate_type_get2 = _library.gnutls_certificate_type_get2
799
 
        certificate_type_get2.argtypes = [session_t, ctypes.c_int]
 
856
        certificate_type_get2.argtypes = [ClientSession, ctypes.c_int]
800
857
        certificate_type_get2.restype = _error_code
801
858
 
802
859
    # Remove non-public functions
814
871
    connection.close()
815
872
 
816
873
 
817
 
class Client(object):
 
874
class Client:
818
875
    """A representation of a client host served by this server.
819
876
 
820
877
    Attributes:
821
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
878
    approved:   bool(); None if not yet approved/disapproved
822
879
    approval_delay: datetime.timedelta(); Time to wait for approval
823
880
    approval_duration: datetime.timedelta(); Duration of one approval
824
881
    checker: multiprocessing.Process(); a running checker process used
825
 
             to see if the client lives. 'None' if no process is
 
882
             to see if the client lives. None if no process is
826
883
             running.
827
884
    checker_callback_tag: a GLib event source tag, or None
828
885
    checker_command: string; External command which is run to check
952
1009
            self.last_enabled = None
953
1010
            self.expires = None
954
1011
 
955
 
        logger.debug("Creating client %r", self.name)
956
 
        logger.debug("  Key ID: %s", self.key_id)
957
 
        logger.debug("  Fingerprint: %s", self.fingerprint)
 
1012
        log.debug("Creating client %r", self.name)
 
1013
        log.debug("  Key ID: %s", self.key_id)
 
1014
        log.debug("  Fingerprint: %s", self.fingerprint)
958
1015
        self.created = settings.get("created",
959
1016
                                    datetime.datetime.utcnow())
960
1017
 
988
1045
        if getattr(self, "enabled", False):
989
1046
            # Already enabled
990
1047
            return
991
 
        self.expires = datetime.datetime.utcnow() + self.timeout
992
1048
        self.enabled = True
993
1049
        self.last_enabled = datetime.datetime.utcnow()
994
1050
        self.init_checker()
999
1055
        if not getattr(self, "enabled", False):
1000
1056
            return False
1001
1057
        if not quiet:
1002
 
            logger.info("Disabling client %s", self.name)
 
1058
            log.info("Disabling client %s", self.name)
1003
1059
        if getattr(self, "disable_initiator_tag", None) is not None:
1004
1060
            GLib.source_remove(self.disable_initiator_tag)
1005
1061
            self.disable_initiator_tag = None
1017
1073
    def __del__(self):
1018
1074
        self.disable()
1019
1075
 
1020
 
    def init_checker(self):
1021
 
        # Schedule a new checker to be started an 'interval' from now,
1022
 
        # and every interval from then on.
 
1076
    def init_checker(self, randomize_start=False):
 
1077
        # Schedule a new checker to be started a randomly selected
 
1078
        # time (a fraction of 'interval') from now.  This spreads out
 
1079
        # the startup of checkers over time when the server is
 
1080
        # started.
1023
1081
        if self.checker_initiator_tag is not None:
1024
1082
            GLib.source_remove(self.checker_initiator_tag)
 
1083
        interval_milliseconds = int(self.interval.total_seconds()
 
1084
                                    * 1000)
 
1085
        if randomize_start:
 
1086
            delay_milliseconds = random.randrange(
 
1087
                interval_milliseconds + 1)
 
1088
        else:
 
1089
            delay_milliseconds = interval_milliseconds
1025
1090
        self.checker_initiator_tag = GLib.timeout_add(
1026
 
            int(self.interval.total_seconds() * 1000),
1027
 
            self.start_checker)
1028
 
        # Schedule a disable() when 'timeout' has passed
 
1091
            delay_milliseconds, self.start_checker, randomize_start)
 
1092
        delay = datetime.timedelta(0, 0, 0, delay_milliseconds)
 
1093
        # A checker might take up to an 'interval' of time, so we can
 
1094
        # expire at the soonest one interval after a checker was
 
1095
        # started.  Since the initial checker is delayed, the expire
 
1096
        # time might have to be extended.
 
1097
        now = datetime.datetime.utcnow()
 
1098
        self.expires = now + delay + self.interval
 
1099
        # Schedule a disable() at expire time
1029
1100
        if self.disable_initiator_tag is not None:
1030
1101
            GLib.source_remove(self.disable_initiator_tag)
1031
1102
        self.disable_initiator_tag = GLib.timeout_add(
1032
 
            int(self.timeout.total_seconds() * 1000), self.disable)
1033
 
        # Also start a new checker *right now*.
1034
 
        self.start_checker()
 
1103
            int((self.expires - now).total_seconds() * 1000),
 
1104
            self.disable)
1035
1105
 
1036
1106
    def checker_callback(self, source, condition, connection,
1037
1107
                         command):
1039
1109
        # Read return code from connection (see call_pipe)
1040
1110
        returncode = connection.recv()
1041
1111
        connection.close()
1042
 
        self.checker.join()
 
1112
        if self.checker is not None:
 
1113
            self.checker.join()
1043
1114
        self.checker_callback_tag = None
1044
1115
        self.checker = None
1045
1116
 
1047
1118
            self.last_checker_status = returncode
1048
1119
            self.last_checker_signal = None
1049
1120
            if self.last_checker_status == 0:
1050
 
                logger.info("Checker for %(name)s succeeded",
1051
 
                            vars(self))
 
1121
                log.info("Checker for %(name)s succeeded", vars(self))
1052
1122
                self.checked_ok()
1053
1123
            else:
1054
 
                logger.info("Checker for %(name)s failed", vars(self))
 
1124
                log.info("Checker for %(name)s failed", vars(self))
1055
1125
        else:
1056
1126
            self.last_checker_status = -1
1057
1127
            self.last_checker_signal = -returncode
1058
 
            logger.warning("Checker for %(name)s crashed?",
1059
 
                           vars(self))
 
1128
            log.warning("Checker for %(name)s crashed?", vars(self))
1060
1129
        return False
1061
1130
 
1062
1131
    def checked_ok(self):
1081
1150
    def need_approval(self):
1082
1151
        self.last_approval_request = datetime.datetime.utcnow()
1083
1152
 
1084
 
    def start_checker(self):
 
1153
    def start_checker(self, start_was_randomized=False):
1085
1154
        """Start a new checker subprocess if one is not running.
1086
1155
 
1087
1156
        If a checker already exists, leave it running and do
1096
1165
        # should be.
1097
1166
 
1098
1167
        if self.checker is not None and not self.checker.is_alive():
1099
 
            logger.warning("Checker was not alive; joining")
 
1168
            log.warning("Checker was not alive; joining")
1100
1169
            self.checker.join()
1101
1170
            self.checker = None
1102
1171
        # Start a new checker if needed
1103
1172
        if self.checker is None:
1104
1173
            # Escape attributes for the shell
1105
1174
            escaped_attrs = {
1106
 
                attr: re.escape(str(getattr(self, attr)))
 
1175
                attr: shlex.quote(str(getattr(self, attr)))
1107
1176
                for attr in self.runtime_expansions}
1108
1177
            try:
1109
1178
                command = self.checker_command % escaped_attrs
1110
1179
            except TypeError as error:
1111
 
                logger.error('Could not format string "%s"',
1112
 
                             self.checker_command,
1113
 
                             exc_info=error)
 
1180
                log.error('Could not format string "%s"',
 
1181
                          self.checker_command, exc_info=error)
1114
1182
                return True     # Try again later
1115
1183
            self.current_checker_command = command
1116
 
            logger.info("Starting checker %r for %s", command,
1117
 
                        self.name)
 
1184
            log.info("Starting checker %r for %s", command, self.name)
1118
1185
            # We don't need to redirect stdout and stderr, since
1119
1186
            # in normal mode, that is already done by daemon(),
1120
1187
            # and in debug mode we don't want to.  (Stdin is
1136
1203
                kwargs=popen_args)
1137
1204
            self.checker.start()
1138
1205
            self.checker_callback_tag = GLib.io_add_watch(
1139
 
                pipe[0].fileno(), GLib.IO_IN,
 
1206
                GLib.IOChannel.unix_new(pipe[0].fileno()),
 
1207
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
1140
1208
                self.checker_callback, pipe[0], command)
 
1209
        if start_was_randomized:
 
1210
            # We were started after a random delay; Schedule a new
 
1211
            # checker to be started an 'interval' from now, and every
 
1212
            # interval from then on.
 
1213
            now = datetime.datetime.utcnow()
 
1214
            self.checker_initiator_tag = GLib.timeout_add(
 
1215
                int(self.interval.total_seconds() * 1000),
 
1216
                self.start_checker)
 
1217
            self.expires = max(self.expires, now + self.interval)
 
1218
            # Don't start a new checker again after same random delay
 
1219
            return False
1141
1220
        # Re-run this periodically if run by GLib.timeout_add
1142
1221
        return True
1143
1222
 
1148
1227
            self.checker_callback_tag = None
1149
1228
        if getattr(self, "checker", None) is None:
1150
1229
            return
1151
 
        logger.debug("Stopping checker for %(name)s", vars(self))
 
1230
        log.debug("Stopping checker for %(name)s", vars(self))
1152
1231
        self.checker.terminate()
1153
1232
        self.checker = None
1154
1233
 
1181
1260
        func._dbus_name = func.__name__
1182
1261
        if func._dbus_name.endswith("_dbus_property"):
1183
1262
            func._dbus_name = func._dbus_name[:-14]
1184
 
        func._dbus_get_args_options = {'byte_arrays': byte_arrays}
 
1263
        func._dbus_get_args_options = {"byte_arrays": byte_arrays}
1185
1264
        return func
1186
1265
 
1187
1266
    return decorator
1276
1355
 
1277
1356
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1278
1357
                         out_signature="s",
1279
 
                         path_keyword='object_path',
1280
 
                         connection_keyword='connection')
 
1358
                         path_keyword="object_path",
 
1359
                         connection_keyword="connection")
1281
1360
    def Introspect(self, object_path, connection):
1282
1361
        """Overloading of standard D-Bus method.
1283
1362
 
1332
1411
            document.unlink()
1333
1412
        except (AttributeError, xml.dom.DOMException,
1334
1413
                xml.parsers.expat.ExpatError) as error:
1335
 
            logger.error("Failed to override Introspection method",
1336
 
                         exc_info=error)
 
1414
            log.error("Failed to override Introspection method",
 
1415
                      exc_info=error)
1337
1416
        return xmlstring
1338
1417
 
1339
1418
 
1397
1476
                raise ValueError("Byte arrays not supported for non-"
1398
1477
                                 "'ay' signature {!r}"
1399
1478
                                 .format(prop._dbus_signature))
1400
 
            value = dbus.ByteArray(b''.join(chr(byte)
1401
 
                                            for byte in value))
 
1479
            value = dbus.ByteArray(bytes(value))
1402
1480
        prop(value)
1403
1481
 
1404
1482
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1437
1515
 
1438
1516
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1439
1517
                         out_signature="s",
1440
 
                         path_keyword='object_path',
1441
 
                         connection_keyword='connection')
 
1518
                         path_keyword="object_path",
 
1519
                         connection_keyword="connection")
1442
1520
    def Introspect(self, object_path, connection):
1443
1521
        """Overloading of standard D-Bus method.
1444
1522
 
1500
1578
            document.unlink()
1501
1579
        except (AttributeError, xml.dom.DOMException,
1502
1580
                xml.parsers.expat.ExpatError) as error:
1503
 
            logger.error("Failed to override Introspection method",
1504
 
                         exc_info=error)
 
1581
            log.error("Failed to override Introspection method",
 
1582
                      exc_info=error)
1505
1583
        return xmlstring
1506
1584
 
1507
1585
 
1539
1617
 
1540
1618
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1541
1619
                         out_signature="s",
1542
 
                         path_keyword='object_path',
1543
 
                         connection_keyword='connection')
 
1620
                         path_keyword="object_path",
 
1621
                         connection_keyword="connection")
1544
1622
    def Introspect(self, object_path, connection):
1545
1623
        """Overloading of standard D-Bus method.
1546
1624
 
1571
1649
            document.unlink()
1572
1650
        except (AttributeError, xml.dom.DOMException,
1573
1651
                xml.parsers.expat.ExpatError) as error:
1574
 
            logger.error("Failed to override Introspection method",
1575
 
                         exc_info=error)
 
1652
            log.error("Failed to override Introspection method",
 
1653
                      exc_info=error)
1576
1654
        return xmlstring
1577
1655
 
1578
1656
 
2209
2287
    del _interface
2210
2288
 
2211
2289
 
2212
 
class ProxyClient(object):
 
2290
class ProxyClient:
2213
2291
    def __init__(self, child_pipe, key_id, fpr, address):
2214
2292
        self._pipe = child_pipe
2215
 
        self._pipe.send(('init', key_id, fpr, address))
 
2293
        self._pipe.send(("init", key_id, fpr, address))
2216
2294
        if not self._pipe.recv():
2217
2295
            raise KeyError(key_id or fpr)
2218
2296
 
2219
2297
    def __getattribute__(self, name):
2220
 
        if name == '_pipe':
 
2298
        if name == "_pipe":
2221
2299
            return super(ProxyClient, self).__getattribute__(name)
2222
 
        self._pipe.send(('getattr', name))
 
2300
        self._pipe.send(("getattr", name))
2223
2301
        data = self._pipe.recv()
2224
 
        if data[0] == 'data':
 
2302
        if data[0] == "data":
2225
2303
            return data[1]
2226
 
        if data[0] == 'function':
 
2304
        if data[0] == "function":
2227
2305
 
2228
2306
            def func(*args, **kwargs):
2229
 
                self._pipe.send(('funcall', name, args, kwargs))
 
2307
                self._pipe.send(("funcall", name, args, kwargs))
2230
2308
                return self._pipe.recv()[1]
2231
2309
 
2232
2310
            return func
2233
2311
 
2234
2312
    def __setattr__(self, name, value):
2235
 
        if name == '_pipe':
 
2313
        if name == "_pipe":
2236
2314
            return super(ProxyClient, self).__setattr__(name, value)
2237
 
        self._pipe.send(('setattr', name, value))
 
2315
        self._pipe.send(("setattr", name, value))
2238
2316
 
2239
2317
 
2240
2318
class ClientHandler(socketserver.BaseRequestHandler, object):
2245
2323
 
2246
2324
    def handle(self):
2247
2325
        with contextlib.closing(self.server.child_pipe) as child_pipe:
2248
 
            logger.info("TCP connection from: %s",
2249
 
                        str(self.client_address))
2250
 
            logger.debug("Pipe FD: %d",
2251
 
                         self.server.child_pipe.fileno())
 
2326
            log.info("TCP connection from: %s",
 
2327
                     str(self.client_address))
 
2328
            log.debug("Pipe FD: %d", self.server.child_pipe.fileno())
2252
2329
 
2253
2330
            session = gnutls.ClientSession(self.request)
2254
2331
 
2255
 
            # priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
2332
            # priority = ":".join(("NONE", "+VERS-TLS1.1",
2256
2333
            #                       "+AES-256-CBC", "+SHA1",
2257
2334
            #                       "+COMP-NULL", "+CTYPE-OPENPGP",
2258
2335
            #                       "+DHE-DSS"))
2260
2337
            priority = self.server.gnutls_priority
2261
2338
            if priority is None:
2262
2339
                priority = "NORMAL"
2263
 
            gnutls.priority_set_direct(session._c_object,
2264
 
                                       priority.encode("utf-8"),
2265
 
                                       None)
 
2340
            gnutls.priority_set_direct(session,
 
2341
                                       priority.encode("utf-8"), None)
2266
2342
 
2267
2343
            # Start communication using the Mandos protocol
2268
2344
            # Get protocol number
2269
2345
            line = self.request.makefile().readline()
2270
 
            logger.debug("Protocol version: %r", line)
 
2346
            log.debug("Protocol version: %r", line)
2271
2347
            try:
2272
2348
                if int(line.strip().split()[0]) > 1:
2273
2349
                    raise RuntimeError(line)
2274
2350
            except (ValueError, IndexError, RuntimeError) as error:
2275
 
                logger.error("Unknown protocol version: %s", error)
 
2351
                log.error("Unknown protocol version: %s", error)
2276
2352
                return
2277
2353
 
2278
2354
            # Start GnuTLS connection
2279
2355
            try:
2280
2356
                session.handshake()
2281
2357
            except gnutls.Error as error:
2282
 
                logger.warning("Handshake failed: %s", error)
 
2358
                log.warning("Handshake failed: %s", error)
2283
2359
                # Do not run session.bye() here: the session is not
2284
2360
                # established.  Just abandon the request.
2285
2361
                return
2286
 
            logger.debug("Handshake succeeded")
 
2362
            log.debug("Handshake succeeded")
2287
2363
 
2288
2364
            approval_required = False
2289
2365
            try:
2293
2369
                        key_id = self.key_id(
2294
2370
                            self.peer_certificate(session))
2295
2371
                    except (TypeError, gnutls.Error) as error:
2296
 
                        logger.warning("Bad certificate: %s", error)
 
2372
                        log.warning("Bad certificate: %s", error)
2297
2373
                        return
2298
 
                    logger.debug("Key ID: %s", key_id)
 
2374
                    log.debug("Key ID: %s",
 
2375
                              key_id.decode("utf-8",
 
2376
                                            errors="replace"))
2299
2377
 
2300
2378
                else:
2301
2379
                    key_id = b""
2303
2381
                        fpr = self.fingerprint(
2304
2382
                            self.peer_certificate(session))
2305
2383
                    except (TypeError, gnutls.Error) as error:
2306
 
                        logger.warning("Bad certificate: %s", error)
 
2384
                        log.warning("Bad certificate: %s", error)
2307
2385
                        return
2308
 
                    logger.debug("Fingerprint: %s", fpr)
 
2386
                    log.debug("Fingerprint: %s", fpr)
2309
2387
 
2310
2388
                try:
2311
2389
                    client = ProxyClient(child_pipe, key_id, fpr,
2320
2398
 
2321
2399
                while True:
2322
2400
                    if not client.enabled:
2323
 
                        logger.info("Client %s is disabled",
2324
 
                                    client.name)
 
2401
                        log.info("Client %s is disabled", client.name)
2325
2402
                        if self.server.use_dbus:
2326
2403
                            # Emit D-Bus signal
2327
2404
                            client.Rejected("Disabled")
2331
2408
                        # We are approved or approval is disabled
2332
2409
                        break
2333
2410
                    elif client.approved is None:
2334
 
                        logger.info("Client %s needs approval",
2335
 
                                    client.name)
 
2411
                        log.info("Client %s needs approval",
 
2412
                                 client.name)
2336
2413
                        if self.server.use_dbus:
2337
2414
                            # Emit D-Bus signal
2338
2415
                            client.NeedApproval(
2339
2416
                                client.approval_delay.total_seconds()
2340
2417
                                * 1000, client.approved_by_default)
2341
2418
                    else:
2342
 
                        logger.warning("Client %s was not approved",
2343
 
                                       client.name)
 
2419
                        log.warning("Client %s was not approved",
 
2420
                                    client.name)
2344
2421
                        if self.server.use_dbus:
2345
2422
                            # Emit D-Bus signal
2346
2423
                            client.Rejected("Denied")
2354
2431
                    time2 = datetime.datetime.now()
2355
2432
                    if (time2 - time) >= delay:
2356
2433
                        if not client.approved_by_default:
2357
 
                            logger.warning("Client %s timed out while"
2358
 
                                           " waiting for approval",
2359
 
                                           client.name)
 
2434
                            log.warning("Client %s timed out while"
 
2435
                                        " waiting for approval",
 
2436
                                        client.name)
2360
2437
                            if self.server.use_dbus:
2361
2438
                                # Emit D-Bus signal
2362
2439
                                client.Rejected("Approval timed out")
2369
2446
                try:
2370
2447
                    session.send(client.secret)
2371
2448
                except gnutls.Error as error:
2372
 
                    logger.warning("gnutls send failed",
2373
 
                                   exc_info=error)
 
2449
                    log.warning("gnutls send failed", exc_info=error)
2374
2450
                    return
2375
2451
 
2376
 
                logger.info("Sending secret to %s", client.name)
 
2452
                log.info("Sending secret to %s", client.name)
2377
2453
                # bump the timeout using extended_timeout
2378
2454
                client.bump_timeout(client.extended_timeout)
2379
2455
                if self.server.use_dbus:
2386
2462
                try:
2387
2463
                    session.bye()
2388
2464
                except gnutls.Error as error:
2389
 
                    logger.warning("GnuTLS bye failed",
2390
 
                                   exc_info=error)
 
2465
                    log.warning("GnuTLS bye failed", exc_info=error)
2391
2466
 
2392
2467
    @staticmethod
2393
2468
    def peer_certificate(session):
2394
2469
        "Return the peer's certificate as a bytestring"
2395
2470
        try:
2396
 
            cert_type = gnutls.certificate_type_get2(session._c_object,
2397
 
                                                     gnutls.CTYPE_PEERS)
 
2471
            cert_type = gnutls.certificate_type_get2(
 
2472
                session, gnutls.CTYPE_PEERS)
2398
2473
        except AttributeError:
2399
 
            cert_type = gnutls.certificate_type_get(session._c_object)
 
2474
            cert_type = gnutls.certificate_type_get(session)
2400
2475
        if gnutls.has_rawpk:
2401
2476
            valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
2402
2477
        else:
2403
2478
            valid_cert_types = frozenset((gnutls.CRT_OPENPGP,))
2404
2479
        # If not a valid certificate type...
2405
2480
        if cert_type not in valid_cert_types:
2406
 
            logger.info("Cert type %r not in %r", cert_type,
2407
 
                        valid_cert_types)
 
2481
            log.info("Cert type %r not in %r", cert_type,
 
2482
                     valid_cert_types)
2408
2483
            # ...return invalid data
2409
2484
            return b""
2410
2485
        list_size = ctypes.c_uint(1)
2411
2486
        cert_list = (gnutls.certificate_get_peers
2412
 
                     (session._c_object, ctypes.byref(list_size)))
 
2487
                     (session, ctypes.byref(list_size)))
2413
2488
        if not bool(cert_list) and list_size.value != 0:
2414
2489
            raise gnutls.Error("error getting peer certificate")
2415
2490
        if list_size.value == 0:
2437
2512
        buf = ctypes.create_string_buffer(32)
2438
2513
        buf_len = ctypes.c_size_t(len(buf))
2439
2514
        # Get the key ID from the raw public key into the buffer
2440
 
        gnutls.pubkey_get_key_id(pubkey,
2441
 
                                 gnutls.KEYID_USE_SHA256,
2442
 
                                 ctypes.cast(ctypes.byref(buf),
2443
 
                                             ctypes.POINTER(ctypes.c_ubyte)),
2444
 
                                 ctypes.byref(buf_len))
 
2515
        gnutls.pubkey_get_key_id(
 
2516
            pubkey,
 
2517
            gnutls.KEYID_USE_SHA256,
 
2518
            ctypes.cast(ctypes.byref(buf),
 
2519
                        ctypes.POINTER(ctypes.c_ubyte)),
 
2520
            ctypes.byref(buf_len))
2445
2521
        # Deinit the certificate
2446
2522
        gnutls.pubkey_deinit(pubkey)
2447
2523
 
2488
2564
        return hex_fpr
2489
2565
 
2490
2566
 
2491
 
class MultiprocessingMixIn(object):
 
2567
class MultiprocessingMixIn:
2492
2568
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2493
2569
 
2494
2570
    def sub_process_main(self, request, address):
2506
2582
        return proc
2507
2583
 
2508
2584
 
2509
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
 
2585
class MultiprocessingMixInWithPipe(MultiprocessingMixIn):
2510
2586
    """ adds a pipe to the MixIn """
2511
2587
 
2512
2588
    def process_request(self, request, client_address):
2527
2603
 
2528
2604
 
2529
2605
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2530
 
                     socketserver.TCPServer, object):
2531
 
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
 
2606
                     socketserver.TCPServer):
 
2607
    """IPv6-capable TCP server.  Accepts None as address and/or port
2532
2608
 
2533
2609
    Attributes:
2534
2610
        enabled:        Boolean; whether this server is activated yet
2585
2661
            if SO_BINDTODEVICE is None:
2586
2662
                # Fall back to a hard-coded value which seems to be
2587
2663
                # common enough.
2588
 
                logger.warning("SO_BINDTODEVICE not found, trying 25")
 
2664
                log.warning("SO_BINDTODEVICE not found, trying 25")
2589
2665
                SO_BINDTODEVICE = 25
2590
2666
            try:
2591
2667
                self.socket.setsockopt(
2593
2669
                    (self.interface + "\0").encode("utf-8"))
2594
2670
            except socket.error as error:
2595
2671
                if error.errno == errno.EPERM:
2596
 
                    logger.error("No permission to bind to"
2597
 
                                 " interface %s", self.interface)
 
2672
                    log.error("No permission to bind to interface %s",
 
2673
                              self.interface)
2598
2674
                elif error.errno == errno.ENOPROTOOPT:
2599
 
                    logger.error("SO_BINDTODEVICE not available;"
2600
 
                                 " cannot bind to interface %s",
2601
 
                                 self.interface)
 
2675
                    log.error("SO_BINDTODEVICE not available; cannot"
 
2676
                              " bind to interface %s", self.interface)
2602
2677
                elif error.errno == errno.ENODEV:
2603
 
                    logger.error("Interface %s does not exist,"
2604
 
                                 " cannot bind", self.interface)
 
2678
                    log.error("Interface %s does not exist, cannot"
 
2679
                              " bind", self.interface)
2605
2680
                else:
2606
2681
                    raise
2607
2682
        # Only bind(2) the socket if we really need to.
2666
2741
    def add_pipe(self, parent_pipe, proc):
2667
2742
        # Call "handle_ipc" for both data and EOF events
2668
2743
        GLib.io_add_watch(
2669
 
            parent_pipe.fileno(),
2670
 
            GLib.IO_IN | GLib.IO_HUP,
 
2744
            GLib.IOChannel.unix_new(parent_pipe.fileno()),
 
2745
            GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2671
2746
            functools.partial(self.handle_ipc,
2672
2747
                              parent_pipe=parent_pipe,
2673
2748
                              proc=proc))
2686
2761
        request = parent_pipe.recv()
2687
2762
        command = request[0]
2688
2763
 
2689
 
        if command == 'init':
 
2764
        if command == "init":
2690
2765
            key_id = request[1].decode("ascii")
2691
2766
            fpr = request[2].decode("ascii")
2692
2767
            address = request[3]
2693
2768
 
2694
2769
            for c in self.clients.values():
2695
 
                if key_id == "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855":
 
2770
                if key_id == ("E3B0C44298FC1C149AFBF4C8996FB924"
 
2771
                              "27AE41E4649B934CA495991B7852B855"):
2696
2772
                    continue
2697
2773
                if key_id and c.key_id == key_id:
2698
2774
                    client = c
2701
2777
                    client = c
2702
2778
                    break
2703
2779
            else:
2704
 
                logger.info("Client not found for key ID: %s, address"
2705
 
                            ": %s", key_id or fpr, address)
 
2780
                log.info("Client not found for key ID: %s, address:"
 
2781
                         " %s", key_id or fpr, address)
2706
2782
                if self.use_dbus:
2707
2783
                    # Emit D-Bus signal
2708
2784
                    mandos_dbus_service.ClientNotFound(key_id or fpr,
2711
2787
                return False
2712
2788
 
2713
2789
            GLib.io_add_watch(
2714
 
                parent_pipe.fileno(),
2715
 
                GLib.IO_IN | GLib.IO_HUP,
 
2790
                GLib.IOChannel.unix_new(parent_pipe.fileno()),
 
2791
                GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2716
2792
                functools.partial(self.handle_ipc,
2717
2793
                                  parent_pipe=parent_pipe,
2718
2794
                                  proc=proc,
2721
2797
            # remove the old hook in favor of the new above hook on
2722
2798
            # same fileno
2723
2799
            return False
2724
 
        if command == 'funcall':
 
2800
        if command == "funcall":
2725
2801
            funcname = request[1]
2726
2802
            args = request[2]
2727
2803
            kwargs = request[3]
2728
2804
 
2729
 
            parent_pipe.send(('data', getattr(client_object,
 
2805
            parent_pipe.send(("data", getattr(client_object,
2730
2806
                                              funcname)(*args,
2731
2807
                                                        **kwargs)))
2732
2808
 
2733
 
        if command == 'getattr':
 
2809
        if command == "getattr":
2734
2810
            attrname = request[1]
2735
2811
            if isinstance(client_object.__getattribute__(attrname),
2736
 
                          collections.Callable):
2737
 
                parent_pipe.send(('function', ))
 
2812
                          collections.abc.Callable):
 
2813
                parent_pipe.send(("function", ))
2738
2814
            else:
2739
2815
                parent_pipe.send((
2740
 
                    'data', client_object.__getattribute__(attrname)))
 
2816
                    "data", client_object.__getattribute__(attrname)))
2741
2817
 
2742
 
        if command == 'setattr':
 
2818
        if command == "setattr":
2743
2819
            attrname = request[1]
2744
2820
            value = request[2]
2745
2821
            setattr(client_object, attrname, value)
2750
2826
def rfc3339_duration_to_delta(duration):
2751
2827
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2752
2828
 
2753
 
    >>> rfc3339_duration_to_delta("P7D")
2754
 
    datetime.timedelta(7)
2755
 
    >>> rfc3339_duration_to_delta("PT60S")
2756
 
    datetime.timedelta(0, 60)
2757
 
    >>> rfc3339_duration_to_delta("PT60M")
2758
 
    datetime.timedelta(0, 3600)
2759
 
    >>> rfc3339_duration_to_delta("PT24H")
2760
 
    datetime.timedelta(1)
2761
 
    >>> rfc3339_duration_to_delta("P1W")
2762
 
    datetime.timedelta(7)
2763
 
    >>> rfc3339_duration_to_delta("PT5M30S")
2764
 
    datetime.timedelta(0, 330)
2765
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
2766
 
    datetime.timedelta(1, 200)
 
2829
    >>> timedelta = datetime.timedelta
 
2830
    >>> rfc3339_duration_to_delta("P7D") == timedelta(7)
 
2831
    True
 
2832
    >>> rfc3339_duration_to_delta("PT60S") == timedelta(0, 60)
 
2833
    True
 
2834
    >>> rfc3339_duration_to_delta("PT60M") == timedelta(0, 3600)
 
2835
    True
 
2836
    >>> rfc3339_duration_to_delta("PT24H") == timedelta(1)
 
2837
    True
 
2838
    >>> rfc3339_duration_to_delta("P1W") == timedelta(7)
 
2839
    True
 
2840
    >>> rfc3339_duration_to_delta("PT5M30S") == timedelta(0, 330)
 
2841
    True
 
2842
    >>> rfc3339_duration_to_delta("P1DT3M20S") == timedelta(1, 200)
 
2843
    True
 
2844
    >>> del timedelta
2767
2845
    """
2768
2846
 
2769
2847
    # Parsing an RFC 3339 duration with regular expressions is not
2849
2927
def string_to_delta(interval):
2850
2928
    """Parse a string and return a datetime.timedelta
2851
2929
 
2852
 
    >>> string_to_delta('7d')
2853
 
    datetime.timedelta(7)
2854
 
    >>> string_to_delta('60s')
2855
 
    datetime.timedelta(0, 60)
2856
 
    >>> string_to_delta('60m')
2857
 
    datetime.timedelta(0, 3600)
2858
 
    >>> string_to_delta('24h')
2859
 
    datetime.timedelta(1)
2860
 
    >>> string_to_delta('1w')
2861
 
    datetime.timedelta(7)
2862
 
    >>> string_to_delta('5m 30s')
2863
 
    datetime.timedelta(0, 330)
 
2930
    >>> string_to_delta("7d") == datetime.timedelta(7)
 
2931
    True
 
2932
    >>> string_to_delta("60s") == datetime.timedelta(0, 60)
 
2933
    True
 
2934
    >>> string_to_delta("60m") == datetime.timedelta(0, 3600)
 
2935
    True
 
2936
    >>> string_to_delta("24h") == datetime.timedelta(1)
 
2937
    True
 
2938
    >>> string_to_delta("1w") == datetime.timedelta(7)
 
2939
    True
 
2940
    >>> string_to_delta("5m 30s") == datetime.timedelta(0, 330)
 
2941
    True
2864
2942
    """
2865
2943
 
2866
2944
    try:
2968
3046
 
2969
3047
    options = parser.parse_args()
2970
3048
 
2971
 
    if options.check:
2972
 
        import doctest
2973
 
        fail_count, test_count = doctest.testmod()
2974
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2975
 
 
2976
3049
    # Default values for config file for server-global settings
2977
3050
    if gnutls.has_rawpk:
2978
3051
        priority = ("SECURE128:!CTYPE-X.509:+CTYPE-RAWPK:!RSA"
2998
3071
    del priority
2999
3072
 
3000
3073
    # Parse config file for server-global settings
3001
 
    server_config = configparser.SafeConfigParser(server_defaults)
 
3074
    server_config = configparser.ConfigParser(server_defaults)
3002
3075
    del server_defaults
3003
3076
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
3004
 
    # Convert the SafeConfigParser object to a dict
 
3077
    # Convert the ConfigParser object to a dict
3005
3078
    server_settings = server_config.defaults()
3006
3079
    # Use the appropriate methods on the non-string config options
3007
3080
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
3074
3147
 
3075
3148
    if server_settings["servicename"] != "Mandos":
3076
3149
        syslogger.setFormatter(
3077
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
3078
 
                              ' %(levelname)s: %(message)s'.format(
 
3150
            logging.Formatter("Mandos ({}) [%(process)d]:"
 
3151
                              " %(levelname)s: %(message)s".format(
3079
3152
                                  server_settings["servicename"])))
3080
3153
 
3081
3154
    # Parse config file with clients
3082
 
    client_config = configparser.SafeConfigParser(Client
3083
 
                                                  .client_defaults)
 
3155
    client_config = configparser.ConfigParser(Client.client_defaults)
3084
3156
    client_config.read(os.path.join(server_settings["configdir"],
3085
3157
                                    "clients.conf"))
3086
3158
 
3106
3178
        try:
3107
3179
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
3108
3180
        except IOError as e:
3109
 
            logger.error("Could not open file %r", pidfilename,
3110
 
                         exc_info=e)
 
3181
            log.error("Could not open file %r", pidfilename,
 
3182
                      exc_info=e)
3111
3183
 
3112
3184
    for name, group in (("_mandos", "_mandos"),
3113
3185
                        ("mandos", "mandos"),
3124
3196
    try:
3125
3197
        os.setgid(gid)
3126
3198
        os.setuid(uid)
3127
 
        if debug:
3128
 
            logger.debug("Did setuid/setgid to {}:{}".format(uid,
3129
 
                                                             gid))
 
3199
        log.debug("Did setuid/setgid to %s:%s", uid, gid)
3130
3200
    except OSError as error:
3131
 
        logger.warning("Failed to setuid/setgid to {}:{}: {}"
3132
 
                       .format(uid, gid, os.strerror(error.errno)))
 
3201
        log.warning("Failed to setuid/setgid to %s:%s: %s", uid, gid,
 
3202
                    os.strerror(error.errno))
3133
3203
        if error.errno != errno.EPERM:
3134
3204
            raise
3135
3205
 
3142
3212
 
3143
3213
        @gnutls.log_func
3144
3214
        def debug_gnutls(level, string):
3145
 
            logger.debug("GnuTLS: %s", string[:-1])
 
3215
            log.debug("GnuTLS: %s",
 
3216
                      string[:-1].decode("utf-8", errors="replace"))
3146
3217
 
3147
3218
        gnutls.global_set_log_function(debug_gnutls)
3148
3219
 
3157
3228
        # Close all input and output, do double fork, etc.
3158
3229
        daemon()
3159
3230
 
3160
 
    # multiprocessing will use threads, so before we use GLib we need
3161
 
    # to inform GLib that threads will be used.
3162
 
    GLib.threads_init()
 
3231
    if gi.version_info < (3, 10, 2):
 
3232
        # multiprocessing will use threads, so before we use GLib we
 
3233
        # need to inform GLib that threads will be used.
 
3234
        GLib.threads_init()
3163
3235
 
3164
3236
    global main_loop
3165
3237
    # From the Avahi example code
3176
3248
                "se.bsnet.fukt.Mandos", bus,
3177
3249
                do_not_queue=True)
3178
3250
        except dbus.exceptions.DBusException as e:
3179
 
            logger.error("Disabling D-Bus:", exc_info=e)
 
3251
            log.error("Disabling D-Bus:", exc_info=e)
3180
3252
            use_dbus = False
3181
3253
            server_settings["use_dbus"] = False
3182
3254
            tcp_server.use_dbus = False
3241
3313
                             if isinstance(s, bytes)
3242
3314
                             else s) for s in
3243
3315
                            value["client_structure"]]
3244
 
                        # .name & .host
3245
 
                        for k in ("name", "host"):
 
3316
                        # .name, .host, and .checker_command
 
3317
                        for k in ("name", "host", "checker_command"):
3246
3318
                            if isinstance(value[k], bytes):
3247
3319
                                value[k] = value[k].decode("utf-8")
3248
3320
                        if "key_id" not in value:
3258
3330
                        for key, value in
3259
3331
                        bytes_old_client_settings.items()}
3260
3332
                    del bytes_old_client_settings
3261
 
                    # .host
 
3333
                    # .host and .checker_command
3262
3334
                    for value in old_client_settings.values():
3263
 
                        if isinstance(value["host"], bytes):
3264
 
                            value["host"] = (value["host"]
3265
 
                                             .decode("utf-8"))
 
3335
                        for attribute in ("host", "checker_command"):
 
3336
                            if isinstance(value[attribute], bytes):
 
3337
                                value[attribute] = (value[attribute]
 
3338
                                                    .decode("utf-8"))
3266
3339
            os.remove(stored_state_path)
3267
3340
        except IOError as e:
3268
3341
            if e.errno == errno.ENOENT:
3269
 
                logger.warning("Could not load persistent state:"
3270
 
                               " {}".format(os.strerror(e.errno)))
 
3342
                log.warning("Could not load persistent state:"
 
3343
                            " %s", os.strerror(e.errno))
3271
3344
            else:
3272
 
                logger.critical("Could not load persistent state:",
3273
 
                                exc_info=e)
 
3345
                log.critical("Could not load persistent state:",
 
3346
                             exc_info=e)
3274
3347
                raise
3275
3348
        except EOFError as e:
3276
 
            logger.warning("Could not load persistent state: "
3277
 
                           "EOFError:",
3278
 
                           exc_info=e)
 
3349
            log.warning("Could not load persistent state: EOFError:",
 
3350
                        exc_info=e)
3279
3351
 
3280
3352
    with PGPEngine() as pgp:
3281
3353
        for client_name, client in clients_data.items():
3308
3380
            if client["enabled"]:
3309
3381
                if datetime.datetime.utcnow() >= client["expires"]:
3310
3382
                    if not client["last_checked_ok"]:
3311
 
                        logger.warning(
3312
 
                            "disabling client {} - Client never "
3313
 
                            "performed a successful checker".format(
3314
 
                                client_name))
 
3383
                        log.warning("disabling client %s - Client"
 
3384
                                    " never performed a successful"
 
3385
                                    " checker", client_name)
3315
3386
                        client["enabled"] = False
3316
3387
                    elif client["last_checker_status"] != 0:
3317
 
                        logger.warning(
3318
 
                            "disabling client {} - Client last"
3319
 
                            " checker failed with error code"
3320
 
                            " {}".format(
3321
 
                                client_name,
3322
 
                                client["last_checker_status"]))
 
3388
                        log.warning("disabling client %s - Client"
 
3389
                                    " last checker failed with error"
 
3390
                                    " code %s", client_name,
 
3391
                                    client["last_checker_status"])
3323
3392
                        client["enabled"] = False
3324
3393
                    else:
3325
3394
                        client["expires"] = (
3326
3395
                            datetime.datetime.utcnow()
3327
3396
                            + client["timeout"])
3328
 
                        logger.debug("Last checker succeeded,"
3329
 
                                     " keeping {} enabled".format(
3330
 
                                         client_name))
 
3397
                        log.debug("Last checker succeeded, keeping %s"
 
3398
                                  " enabled", client_name)
3331
3399
            try:
3332
3400
                client["secret"] = pgp.decrypt(
3333
3401
                    client["encrypted_secret"],
3334
3402
                    client_settings[client_name]["secret"])
3335
3403
            except PGPError:
3336
3404
                # If decryption fails, we use secret from new settings
3337
 
                logger.debug("Failed to decrypt {} old secret".format(
3338
 
                    client_name))
 
3405
                log.debug("Failed to decrypt %s old secret",
 
3406
                          client_name)
3339
3407
                client["secret"] = (client_settings[client_name]
3340
3408
                                    ["secret"])
3341
3409
 
3355
3423
            server_settings=server_settings)
3356
3424
 
3357
3425
    if not tcp_server.clients:
3358
 
        logger.warning("No clients defined")
 
3426
        log.warning("No clients defined")
3359
3427
 
3360
3428
    if not foreground:
3361
3429
        if pidfile is not None:
3364
3432
                with pidfile:
3365
3433
                    print(pid, file=pidfile)
3366
3434
            except IOError:
3367
 
                logger.error("Could not write to file %r with PID %d",
3368
 
                             pidfilename, pid)
 
3435
                log.error("Could not write to file %r with PID %d",
 
3436
                          pidfilename, pid)
3369
3437
        del pidfile
3370
3438
        del pidfilename
3371
3439
 
3521
3589
 
3522
3590
        try:
3523
3591
            with tempfile.NamedTemporaryFile(
3524
 
                    mode='wb',
 
3592
                    mode="wb",
3525
3593
                    suffix=".pickle",
3526
 
                    prefix='clients-',
 
3594
                    prefix="clients-",
3527
3595
                    dir=os.path.dirname(stored_state_path),
3528
3596
                    delete=False) as stored_state:
3529
3597
                pickle.dump((clients, client_settings), stored_state,
3537
3605
                except NameError:
3538
3606
                    pass
3539
3607
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
3540
 
                logger.warning("Could not save persistent state: {}"
3541
 
                               .format(os.strerror(e.errno)))
 
3608
                log.warning("Could not save persistent state: %s",
 
3609
                            os.strerror(e.errno))
3542
3610
            else:
3543
 
                logger.warning("Could not save persistent state:",
3544
 
                               exc_info=e)
 
3611
                log.warning("Could not save persistent state:",
 
3612
                            exc_info=e)
3545
3613
                raise
3546
3614
 
3547
3615
        # Delete all clients, and settings from config
3564
3632
            mandos_dbus_service.client_added_signal(client)
3565
3633
        # Need to initiate checking of clients
3566
3634
        if client.enabled:
3567
 
            client.init_checker()
 
3635
            client.init_checker(randomize_start=True)
3568
3636
 
3569
3637
    tcp_server.enable()
3570
3638
    tcp_server.server_activate()
3573
3641
    if zeroconf:
3574
3642
        service.port = tcp_server.socket.getsockname()[1]
3575
3643
    if use_ipv6:
3576
 
        logger.info("Now listening on address %r, port %d,"
3577
 
                    " flowinfo %d, scope_id %d",
3578
 
                    *tcp_server.socket.getsockname())
 
3644
        log.info("Now listening on address %r, port %d, flowinfo %d,"
 
3645
                 " scope_id %d", *tcp_server.socket.getsockname())
3579
3646
    else:                       # IPv4
3580
 
        logger.info("Now listening on address %r, port %d",
3581
 
                    *tcp_server.socket.getsockname())
 
3647
        log.info("Now listening on address %r, port %d",
 
3648
                 *tcp_server.socket.getsockname())
3582
3649
 
3583
3650
    # service.interface = tcp_server.socket.getsockname()[3]
3584
3651
 
3588
3655
            try:
3589
3656
                service.activate()
3590
3657
            except dbus.exceptions.DBusException as error:
3591
 
                logger.critical("D-Bus Exception", exc_info=error)
 
3658
                log.critical("D-Bus Exception", exc_info=error)
3592
3659
                cleanup()
3593
3660
                sys.exit(1)
3594
3661
            # End of Avahi example code
3595
3662
 
3596
 
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
3597
 
                          lambda *args, **kwargs:
3598
 
                          (tcp_server.handle_request
3599
 
                           (*args[2:], **kwargs) or True))
 
3663
        GLib.io_add_watch(
 
3664
            GLib.IOChannel.unix_new(tcp_server.fileno()),
 
3665
            GLib.PRIORITY_DEFAULT, GLib.IO_IN,
 
3666
            lambda *args, **kwargs: (tcp_server.handle_request
 
3667
                                     (*args[2:], **kwargs) or True))
3600
3668
 
3601
 
        logger.debug("Starting main loop")
 
3669
        log.debug("Starting main loop")
3602
3670
        main_loop.run()
3603
3671
    except AvahiError as error:
3604
 
        logger.critical("Avahi Error", exc_info=error)
 
3672
        log.critical("Avahi Error", exc_info=error)
3605
3673
        cleanup()
3606
3674
        sys.exit(1)
3607
3675
    except KeyboardInterrupt:
3608
3676
        if debug:
3609
3677
            print("", file=sys.stderr)
3610
 
        logger.debug("Server received KeyboardInterrupt")
3611
 
    logger.debug("Server exiting")
 
3678
        log.debug("Server received KeyboardInterrupt")
 
3679
    log.debug("Server exiting")
3612
3680
    # Must run before the D-Bus bus name gets deregistered
3613
3681
    cleanup()
3614
3682
 
3615
 
 
3616
 
if __name__ == '__main__':
3617
 
    main()
 
3683
 
 
3684
def parse_test_args():
 
3685
    # type: () -> argparse.Namespace
 
3686
    parser = argparse.ArgumentParser(add_help=False)
 
3687
    parser.add_argument("--check", action="store_true")
 
3688
    parser.add_argument("--prefix", )
 
3689
    args, unknown_args = parser.parse_known_args()
 
3690
    if args.check:
 
3691
        # Remove test options from sys.argv
 
3692
        sys.argv[1:] = unknown_args
 
3693
    return args
 
3694
 
 
3695
# Add all tests from doctest strings
 
3696
def load_tests(loader, tests, none):
 
3697
    import doctest
 
3698
    tests.addTests(doctest.DocTestSuite())
 
3699
    return tests
 
3700
 
 
3701
if __name__ == "__main__":
 
3702
    options = parse_test_args()
 
3703
    try:
 
3704
        if options.check:
 
3705
            extra_test_prefix = options.prefix
 
3706
            if extra_test_prefix is not None:
 
3707
                if not (unittest.main(argv=[""], exit=False)
 
3708
                        .result.wasSuccessful()):
 
3709
                    sys.exit(1)
 
3710
                class ExtraTestLoader(unittest.TestLoader):
 
3711
                    testMethodPrefix = extra_test_prefix
 
3712
                # Call using ./scriptname --test [--verbose]
 
3713
                unittest.main(argv=[""], testLoader=ExtraTestLoader())
 
3714
            else:
 
3715
                unittest.main(argv=[""])
 
3716
        else:
 
3717
            main()
 
3718
    finally:
 
3719
        logging.shutdown()
 
3720
 
 
3721
# Local Variables:
 
3722
# run-tests:
 
3723
# (lambda (&optional extra)
 
3724
#   (if (not (funcall run-tests-in-test-buffer default-directory
 
3725
#             extra))
 
3726
#       (funcall show-test-buffer-in-test-window)
 
3727
#     (funcall remove-test-window)
 
3728
#     (if extra (message "Extra tests run successfully!"))))
 
3729
# run-tests-in-test-buffer:
 
3730
# (lambda (dir &optional extra)
 
3731
#   (with-current-buffer (get-buffer-create "*Test*")
 
3732
#     (setq buffer-read-only nil
 
3733
#           default-directory dir)
 
3734
#     (erase-buffer)
 
3735
#     (compilation-mode))
 
3736
#   (let ((process-result
 
3737
#          (let ((inhibit-read-only t))
 
3738
#            (process-file-shell-command
 
3739
#             (funcall get-command-line extra) nil "*Test*"))))
 
3740
#     (and (numberp process-result)
 
3741
#          (= process-result 0))))
 
3742
# get-command-line:
 
3743
# (lambda (&optional extra)
 
3744
#   (let ((quoted-script
 
3745
#          (shell-quote-argument (funcall get-script-name))))
 
3746
#     (format
 
3747
#      (concat "%s --check" (if extra " --prefix=atest" ""))
 
3748
#      quoted-script)))
 
3749
# get-script-name:
 
3750
# (lambda ()
 
3751
#   (if (fboundp 'file-local-name)
 
3752
#       (file-local-name (buffer-file-name))
 
3753
#     (or (file-remote-p (buffer-file-name) 'localname)
 
3754
#         (buffer-file-name))))
 
3755
# remove-test-window:
 
3756
# (lambda ()
 
3757
#   (let ((test-window (get-buffer-window "*Test*")))
 
3758
#     (if test-window (delete-window test-window))))
 
3759
# show-test-buffer-in-test-window:
 
3760
# (lambda ()
 
3761
#   (when (not (get-buffer-window-list "*Test*"))
 
3762
#     (setq next-error-last-buffer (get-buffer "*Test*"))
 
3763
#     (let* ((side (if (>= (window-width) 146) 'right 'bottom))
 
3764
#            (display-buffer-overriding-action
 
3765
#             `((display-buffer-in-side-window) (side . ,side)
 
3766
#               (window-height . fit-window-to-buffer)
 
3767
#               (window-width . fit-window-to-buffer))))
 
3768
#       (display-buffer "*Test*"))))
 
3769
# eval:
 
3770
# (progn
 
3771
#   (let* ((run-extra-tests (lambda () (interactive)
 
3772
#                             (funcall run-tests t)))
 
3773
#          (inner-keymap `(keymap (116 . ,run-extra-tests))) ; t
 
3774
#          (outer-keymap `(keymap (3 . ,inner-keymap))))     ; C-c
 
3775
#     (setq minor-mode-overriding-map-alist
 
3776
#           (cons `(run-tests . ,outer-keymap)
 
3777
#                 minor-mode-overriding-map-alist)))
 
3778
#   (add-hook 'after-save-hook run-tests 90 t))
 
3779
# End: