/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2013-12-31 16:02:18 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 307.
  • Revision ID: teddy@recompile.se-20131231160218-plmmb0o0iifkd5l2
Specify BusName in systemd service file.

* mandos.service (BusName): Uncommented.

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-2013 Teddy Hogeborn
 
15
# Copyright © 2008-2013 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
36
36
 
37
37
from future_builtins import *
38
38
 
39
 
try:
40
 
    import SocketServer as socketserver
41
 
except ImportError:
42
 
    import socketserver
 
39
import SocketServer as socketserver
43
40
import socket
44
41
import argparse
45
42
import datetime
50
47
import gnutls.library.functions
51
48
import gnutls.library.constants
52
49
import gnutls.library.types
53
 
try:
54
 
    import ConfigParser as configparser
55
 
except ImportError:
56
 
    import configparser
 
50
import ConfigParser as configparser
57
51
import sys
58
52
import re
59
53
import os
68
62
import struct
69
63
import fcntl
70
64
import functools
71
 
try:
72
 
    import cPickle as pickle
73
 
except ImportError:
74
 
    import pickle
 
65
import cPickle as pickle
75
66
import multiprocessing
76
67
import types
77
68
import binascii
81
72
 
82
73
import dbus
83
74
import dbus.service
84
 
try:
85
 
    import gobject
86
 
except ImportError:
87
 
    from gi.repository import GObject as gobject
 
75
import gobject
88
76
import avahi
89
77
from dbus.mainloop.glib import DBusGMainLoop
90
78
import ctypes
100
88
    except ImportError:
101
89
        SO_BINDTODEVICE = None
102
90
 
103
 
if sys.version_info.major == 2:
104
 
    str = unicode
105
 
 
106
 
version = "1.6.9"
 
91
version = "1.6.2"
107
92
stored_state_file = "clients.pickle"
108
93
 
109
94
logger = logging.getLogger()
110
 
syslogger = None
 
95
syslogger = (logging.handlers.SysLogHandler
 
96
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
              address = str("/dev/log")))
111
98
 
112
99
try:
113
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
114
 
        ctypes.util.find_library("c")).if_nametoindex
 
100
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
101
                      (ctypes.util.find_library("c"))
 
102
                      .if_nametoindex)
115
103
except (OSError, AttributeError):
116
 
    
117
104
    def if_nametoindex(interface):
118
105
        "Get an interface index the hard way, i.e. using fcntl()"
119
106
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
120
107
        with contextlib.closing(socket.socket()) as s:
121
108
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
122
 
                                struct.pack(b"16s16x", interface))
123
 
        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]
124
113
        return interface_index
125
114
 
126
115
 
127
116
def initlogger(debug, level=logging.WARNING):
128
117
    """init logger and add loglevel"""
129
118
    
130
 
    global syslogger
131
 
    syslogger = (logging.handlers.SysLogHandler(
132
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
133
 
        address = "/dev/log"))
134
119
    syslogger.setFormatter(logging.Formatter
135
120
                           ('Mandos [%(process)d]: %(levelname)s:'
136
121
                            ' %(message)s'))
153
138
 
154
139
class PGPEngine(object):
155
140
    """A simple class for OpenPGP symmetric encryption & decryption"""
156
 
    
157
141
    def __init__(self):
158
142
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
159
143
        self.gnupgargs = ['--batch',
198
182
    
199
183
    def encrypt(self, data, password):
200
184
        passphrase = self.password_encode(password)
201
 
        with tempfile.NamedTemporaryFile(
202
 
                dir=self.tempdir) as passfile:
 
185
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
186
                                         ) as passfile:
203
187
            passfile.write(passphrase)
204
188
            passfile.flush()
205
189
            proc = subprocess.Popen(['gpg', '--symmetric',
216
200
    
217
201
    def decrypt(self, data, password):
218
202
        passphrase = self.password_encode(password)
219
 
        with tempfile.NamedTemporaryFile(
220
 
                dir = self.tempdir) as passfile:
 
203
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
204
                                         ) as passfile:
221
205
            passfile.write(passphrase)
222
206
            passfile.flush()
223
207
            proc = subprocess.Popen(['gpg', '--decrypt',
227
211
                                    stdin = subprocess.PIPE,
228
212
                                    stdout = subprocess.PIPE,
229
213
                                    stderr = subprocess.PIPE)
230
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
214
            decrypted_plaintext, err = proc.communicate(input
 
215
                                                        = data)
231
216
        if proc.returncode != 0:
232
217
            raise PGPError(err)
233
218
        return decrypted_plaintext
236
221
class AvahiError(Exception):
237
222
    def __init__(self, value, *args, **kwargs):
238
223
        self.value = value
239
 
        return super(AvahiError, self).__init__(value, *args,
240
 
                                                **kwargs)
241
 
 
 
224
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
225
    def __unicode__(self):
 
226
        return unicode(repr(self.value))
242
227
 
243
228
class AvahiServiceError(AvahiError):
244
229
    pass
245
230
 
246
 
 
247
231
class AvahiGroupError(AvahiError):
248
232
    pass
249
233
 
269
253
    bus: dbus.SystemBus()
270
254
    """
271
255
    
272
 
    def __init__(self,
273
 
                 interface = avahi.IF_UNSPEC,
274
 
                 name = None,
275
 
                 servicetype = None,
276
 
                 port = None,
277
 
                 TXT = None,
278
 
                 domain = "",
279
 
                 host = "",
280
 
                 max_renames = 32768,
281
 
                 protocol = avahi.PROTO_UNSPEC,
282
 
                 bus = None):
 
256
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
257
                 servicetype = None, port = None, TXT = None,
 
258
                 domain = "", host = "", max_renames = 32768,
 
259
                 protocol = avahi.PROTO_UNSPEC, bus = None):
283
260
        self.interface = interface
284
261
        self.name = name
285
262
        self.type = servicetype
295
272
        self.bus = bus
296
273
        self.entry_group_state_changed_match = None
297
274
    
298
 
    def rename(self, remove=True):
 
275
    def rename(self):
299
276
        """Derived from the Avahi example code"""
300
277
        if self.rename_count >= self.max_renames:
301
278
            logger.critical("No suitable Zeroconf service name found"
302
279
                            " after %i retries, exiting.",
303
280
                            self.rename_count)
304
281
            raise AvahiServiceError("Too many renames")
305
 
        self.name = str(
306
 
            self.server.GetAlternativeServiceName(self.name))
307
 
        self.rename_count += 1
 
282
        self.name = unicode(self.server
 
283
                            .GetAlternativeServiceName(self.name))
308
284
        logger.info("Changing Zeroconf service name to %r ...",
309
285
                    self.name)
310
 
        if remove:
311
 
            self.remove()
 
286
        self.remove()
312
287
        try:
313
288
            self.add()
314
289
        except dbus.exceptions.DBusException as error:
315
 
            if (error.get_dbus_name()
316
 
                == "org.freedesktop.Avahi.CollisionError"):
317
 
                logger.info("Local Zeroconf service name collision.")
318
 
                return self.rename(remove=False)
319
 
            else:
320
 
                logger.critical("D-Bus Exception", exc_info=error)
321
 
                self.cleanup()
322
 
                os._exit(1)
 
290
            logger.critical("D-Bus Exception", exc_info=error)
 
291
            self.cleanup()
 
292
            os._exit(1)
 
293
        self.rename_count += 1
323
294
    
324
295
    def remove(self):
325
296
        """Derived from the Avahi example code"""
363
334
            self.rename()
364
335
        elif state == avahi.ENTRY_GROUP_FAILURE:
365
336
            logger.critical("Avahi: Error in group state changed %s",
366
 
                            str(error))
367
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
337
                            unicode(error))
 
338
            raise AvahiGroupError("State changed: {0!s}"
 
339
                                  .format(error))
368
340
    
369
341
    def cleanup(self):
370
342
        """Derived from the Avahi example code"""
380
352
    def server_state_changed(self, state, error=None):
381
353
        """Derived from the Avahi example code"""
382
354
        logger.debug("Avahi server state change: %i", state)
383
 
        bad_states = {
384
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
385
 
            avahi.SERVER_REGISTERING: None,
386
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
387
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
388
 
        }
 
355
        bad_states = { avahi.SERVER_INVALID:
 
356
                           "Zeroconf server invalid",
 
357
                       avahi.SERVER_REGISTERING: None,
 
358
                       avahi.SERVER_COLLISION:
 
359
                           "Zeroconf server name collision",
 
360
                       avahi.SERVER_FAILURE:
 
361
                           "Zeroconf server failure" }
389
362
        if state in bad_states:
390
363
            if bad_states[state] is not None:
391
364
                if error is None:
410
383
                                    follow_name_owner_changes=True),
411
384
                avahi.DBUS_INTERFACE_SERVER)
412
385
        self.server.connect_to_signal("StateChanged",
413
 
                                      self.server_state_changed)
 
386
                                 self.server_state_changed)
414
387
        self.server_state_changed(self.server.GetState())
415
388
 
416
389
 
417
390
class AvahiServiceToSyslog(AvahiService):
418
 
    def rename(self, *args, **kwargs):
 
391
    def rename(self):
419
392
        """Add the new name to the syslog messages"""
420
 
        ret = AvahiService.rename(self, *args, **kwargs)
421
 
        syslogger.setFormatter(logging.Formatter(
422
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
423
 
            .format(self.name)))
 
393
        ret = AvahiService.rename(self)
 
394
        syslogger.setFormatter(logging.Formatter
 
395
                               ('Mandos ({0}) [%(process)d]:'
 
396
                                ' %(levelname)s: %(message)s'
 
397
                                .format(self.name)))
424
398
        return ret
425
399
 
426
 
def call_pipe(connection,       # : multiprocessing.Connection
427
 
              func, *args, **kwargs):
428
 
    """This function is meant to be called by multiprocessing.Process
429
 
    
430
 
    This function runs func(*args, **kwargs), and writes the resulting
431
 
    return value on the provided multiprocessing.Connection.
432
 
    """
433
 
    connection.send(func(*args, **kwargs))
434
 
    connection.close()
 
400
 
 
401
def timedelta_to_milliseconds(td):
 
402
    "Convert a datetime.timedelta() to milliseconds"
 
403
    return ((td.days * 24 * 60 * 60 * 1000)
 
404
            + (td.seconds * 1000)
 
405
            + (td.microseconds // 1000))
 
406
 
435
407
 
436
408
class Client(object):
437
409
    """A representation of a client host served by this server.
464
436
    last_checker_status: integer between 0 and 255 reflecting exit
465
437
                         status of last checker. -1 reflects crashed
466
438
                         checker, -2 means no checker completed yet.
467
 
    last_checker_signal: The signal which killed the last checker, if
468
 
                         last_checker_status is -1
469
439
    last_enabled: datetime.datetime(); (UTC) or None
470
440
    name:       string; from the config file, used in log messages and
471
441
                        D-Bus identifiers
484
454
                          "fingerprint", "host", "interval",
485
455
                          "last_approval_request", "last_checked_ok",
486
456
                          "last_enabled", "name", "timeout")
487
 
    client_defaults = {
488
 
        "timeout": "PT5M",
489
 
        "extended_timeout": "PT15M",
490
 
        "interval": "PT2M",
491
 
        "checker": "fping -q -- %%(host)s",
492
 
        "host": "",
493
 
        "approval_delay": "PT0S",
494
 
        "approval_duration": "PT1S",
495
 
        "approved_by_default": "True",
496
 
        "enabled": "True",
497
 
    }
 
457
    client_defaults = { "timeout": "PT5M",
 
458
                        "extended_timeout": "PT15M",
 
459
                        "interval": "PT2M",
 
460
                        "checker": "fping -q -- %%(host)s",
 
461
                        "host": "",
 
462
                        "approval_delay": "PT0S",
 
463
                        "approval_duration": "PT1S",
 
464
                        "approved_by_default": "True",
 
465
                        "enabled": "True",
 
466
                        }
 
467
    
 
468
    def timeout_milliseconds(self):
 
469
        "Return the 'timeout' attribute in milliseconds"
 
470
        return timedelta_to_milliseconds(self.timeout)
 
471
    
 
472
    def extended_timeout_milliseconds(self):
 
473
        "Return the 'extended_timeout' attribute in milliseconds"
 
474
        return timedelta_to_milliseconds(self.extended_timeout)
 
475
    
 
476
    def interval_milliseconds(self):
 
477
        "Return the 'interval' attribute in milliseconds"
 
478
        return timedelta_to_milliseconds(self.interval)
 
479
    
 
480
    def approval_delay_milliseconds(self):
 
481
        return timedelta_to_milliseconds(self.approval_delay)
498
482
    
499
483
    @staticmethod
500
484
    def config_parser(config):
516
500
            client["enabled"] = config.getboolean(client_name,
517
501
                                                  "enabled")
518
502
            
519
 
            # Uppercase and remove spaces from fingerprint for later
520
 
            # comparison purposes with return value from the
521
 
            # fingerprint() function
522
503
            client["fingerprint"] = (section["fingerprint"].upper()
523
504
                                     .replace(" ", ""))
524
505
            if "secret" in section:
529
510
                          "rb") as secfile:
530
511
                    client["secret"] = secfile.read()
531
512
            else:
532
 
                raise TypeError("No secret or secfile for section {}"
 
513
                raise TypeError("No secret or secfile for section {0}"
533
514
                                .format(section))
534
515
            client["timeout"] = string_to_delta(section["timeout"])
535
516
            client["extended_timeout"] = string_to_delta(
552
533
            server_settings = {}
553
534
        self.server_settings = server_settings
554
535
        # adding all client settings
555
 
        for setting, value in settings.items():
 
536
        for setting, value in settings.iteritems():
556
537
            setattr(self, setting, value)
557
538
        
558
539
        if self.enabled:
566
547
            self.expires = None
567
548
        
568
549
        logger.debug("Creating client %r", self.name)
 
550
        # Uppercase and remove spaces from fingerprint for later
 
551
        # comparison purposes with return value from the fingerprint()
 
552
        # function
569
553
        logger.debug("  Fingerprint: %s", self.fingerprint)
570
554
        self.created = settings.get("created",
571
555
                                    datetime.datetime.utcnow())
578
562
        self.current_checker_command = None
579
563
        self.approved = None
580
564
        self.approvals_pending = 0
581
 
        self.changedstate = multiprocessing_manager.Condition(
582
 
            multiprocessing_manager.Lock())
583
 
        self.client_structure = [attr
584
 
                                 for attr in self.__dict__.iterkeys()
 
565
        self.changedstate = (multiprocessing_manager
 
566
                             .Condition(multiprocessing_manager
 
567
                                        .Lock()))
 
568
        self.client_structure = [attr for attr in
 
569
                                 self.__dict__.iterkeys()
585
570
                                 if not attr.startswith("_")]
586
571
        self.client_structure.append("client_structure")
587
572
        
588
 
        for name, t in inspect.getmembers(
589
 
                type(self), lambda obj: isinstance(obj, property)):
 
573
        for name, t in inspect.getmembers(type(self),
 
574
                                          lambda obj:
 
575
                                              isinstance(obj,
 
576
                                                         property)):
590
577
            if not name.startswith("_"):
591
578
                self.client_structure.append(name)
592
579
    
634
621
        # and every interval from then on.
635
622
        if self.checker_initiator_tag is not None:
636
623
            gobject.source_remove(self.checker_initiator_tag)
637
 
        self.checker_initiator_tag = gobject.timeout_add(
638
 
            int(self.interval.total_seconds() * 1000),
639
 
            self.start_checker)
 
624
        self.checker_initiator_tag = (gobject.timeout_add
 
625
                                      (self.interval_milliseconds(),
 
626
                                       self.start_checker))
640
627
        # Schedule a disable() when 'timeout' has passed
641
628
        if self.disable_initiator_tag is not None:
642
629
            gobject.source_remove(self.disable_initiator_tag)
643
 
        self.disable_initiator_tag = gobject.timeout_add(
644
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
630
        self.disable_initiator_tag = (gobject.timeout_add
 
631
                                   (self.timeout_milliseconds(),
 
632
                                    self.disable))
645
633
        # Also start a new checker *right now*.
646
634
        self.start_checker()
647
635
    
648
 
    def checker_callback(self, source, condition,
649
 
                         (connection, command)):
 
636
    def checker_callback(self, pid, condition, command):
650
637
        """The checker has completed, so take appropriate actions."""
651
638
        self.checker_callback_tag = None
652
639
        self.checker = None
653
 
        # Read return code from connection (see call_pipe)
654
 
        returncode = connection.recv()
655
 
        connection.close()
656
 
        
657
 
        if returncode >= 0:
658
 
            self.last_checker_status = returncode
659
 
            self.last_checker_signal = None
 
640
        if os.WIFEXITED(condition):
 
641
            self.last_checker_status = os.WEXITSTATUS(condition)
660
642
            if self.last_checker_status == 0:
661
643
                logger.info("Checker for %(name)s succeeded",
662
644
                            vars(self))
663
645
                self.checked_ok()
664
646
            else:
665
 
                logger.info("Checker for %(name)s failed", vars(self))
 
647
                logger.info("Checker for %(name)s failed",
 
648
                            vars(self))
666
649
        else:
667
650
            self.last_checker_status = -1
668
 
            self.last_checker_signal = -returncode
669
651
            logger.warning("Checker for %(name)s crashed?",
670
652
                           vars(self))
671
 
        return False
672
653
    
673
654
    def checked_ok(self):
674
655
        """Assert that the client has been seen, alive and well."""
675
656
        self.last_checked_ok = datetime.datetime.utcnow()
676
657
        self.last_checker_status = 0
677
 
        self.last_checker_signal = None
678
658
        self.bump_timeout()
679
659
    
680
660
    def bump_timeout(self, timeout=None):
685
665
            gobject.source_remove(self.disable_initiator_tag)
686
666
            self.disable_initiator_tag = None
687
667
        if getattr(self, "enabled", False):
688
 
            self.disable_initiator_tag = gobject.timeout_add(
689
 
                int(timeout.total_seconds() * 1000), self.disable)
 
668
            self.disable_initiator_tag = (gobject.timeout_add
 
669
                                          (timedelta_to_milliseconds
 
670
                                           (timeout), self.disable))
690
671
            self.expires = datetime.datetime.utcnow() + timeout
691
672
    
692
673
    def need_approval(self):
706
687
        # than 'timeout' for the client to be disabled, which is as it
707
688
        # should be.
708
689
        
709
 
        if self.checker is not None and not self.checker.is_alive():
710
 
            logger.warning("Checker was not alive; joining")
711
 
            self.checker.join()
712
 
            self.checker = None
 
690
        # If a checker exists, make sure it is not a zombie
 
691
        try:
 
692
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
693
        except AttributeError:
 
694
            pass
 
695
        except OSError as error:
 
696
            if error.errno != errno.ECHILD:
 
697
                raise
 
698
        else:
 
699
            if pid:
 
700
                logger.warning("Checker was a zombie")
 
701
                gobject.source_remove(self.checker_callback_tag)
 
702
                self.checker_callback(pid, status,
 
703
                                      self.current_checker_command)
713
704
        # Start a new checker if needed
714
705
        if self.checker is None:
715
706
            # Escape attributes for the shell
716
 
            escaped_attrs = {
717
 
                attr: re.escape(str(getattr(self, attr)))
718
 
                for attr in self.runtime_expansions }
 
707
            escaped_attrs = dict(
 
708
                (attr, re.escape(unicode(getattr(self, attr))))
 
709
                for attr in
 
710
                self.runtime_expansions)
719
711
            try:
720
712
                command = self.checker_command % escaped_attrs
721
713
            except TypeError as error:
722
714
                logger.error('Could not format string "%s"',
723
 
                             self.checker_command,
 
715
                             self.checker_command, exc_info=error)
 
716
                return True # Try again later
 
717
            self.current_checker_command = command
 
718
            try:
 
719
                logger.info("Starting checker %r for %s",
 
720
                            command, self.name)
 
721
                # We don't need to redirect stdout and stderr, since
 
722
                # in normal mode, that is already done by daemon(),
 
723
                # and in debug mode we don't want to.  (Stdin is
 
724
                # always replaced by /dev/null.)
 
725
                # The exception is when not debugging but nevertheless
 
726
                # running in the foreground; use the previously
 
727
                # created wnull.
 
728
                popen_args = {}
 
729
                if (not self.server_settings["debug"]
 
730
                    and self.server_settings["foreground"]):
 
731
                    popen_args.update({"stdout": wnull,
 
732
                                       "stderr": wnull })
 
733
                self.checker = subprocess.Popen(command,
 
734
                                                close_fds=True,
 
735
                                                shell=True, cwd="/",
 
736
                                                **popen_args)
 
737
            except OSError as error:
 
738
                logger.error("Failed to start subprocess",
724
739
                             exc_info=error)
725
 
                return True     # Try again later
726
 
            self.current_checker_command = command
727
 
            logger.info("Starting checker %r for %s", command,
728
 
                        self.name)
729
 
            # We don't need to redirect stdout and stderr, since
730
 
            # in normal mode, that is already done by daemon(),
731
 
            # and in debug mode we don't want to.  (Stdin is
732
 
            # always replaced by /dev/null.)
733
 
            # The exception is when not debugging but nevertheless
734
 
            # running in the foreground; use the previously
735
 
            # created wnull.
736
 
            popen_args = { "close_fds": True,
737
 
                           "shell": True,
738
 
                           "cwd": "/" }
739
 
            if (not self.server_settings["debug"]
740
 
                and self.server_settings["foreground"]):
741
 
                popen_args.update({"stdout": wnull,
742
 
                                   "stderr": wnull })
743
 
            pipe = multiprocessing.Pipe(duplex=False)
744
 
            self.checker = multiprocessing.Process(
745
 
                target = call_pipe,
746
 
                args = (subprocess.call, pipe[1], command),
747
 
                kwargs = popen_args)
748
 
            self.checker.start()
749
 
            self.checker_callback_tag = gobject.io_add_watch(
750
 
                pipe[0].fileno(), gobject.IO_IN,
751
 
                self.checker_callback, (pipe[0], command))
 
740
                return True
 
741
            self.checker_callback_tag = (gobject.child_watch_add
 
742
                                         (self.checker.pid,
 
743
                                          self.checker_callback,
 
744
                                          data=command))
 
745
            # The checker may have completed before the gobject
 
746
            # watch was added.  Check for this.
 
747
            try:
 
748
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
749
            except OSError as error:
 
750
                if error.errno == errno.ECHILD:
 
751
                    # This should never happen
 
752
                    logger.error("Child process vanished",
 
753
                                 exc_info=error)
 
754
                    return True
 
755
                raise
 
756
            if pid:
 
757
                gobject.source_remove(self.checker_callback_tag)
 
758
                self.checker_callback(pid, status, command)
752
759
        # Re-run this periodically if run by gobject.timeout_add
753
760
        return True
754
761
    
760
767
        if getattr(self, "checker", None) is None:
761
768
            return
762
769
        logger.debug("Stopping checker for %(name)s", vars(self))
763
 
        self.checker.terminate()
 
770
        try:
 
771
            self.checker.terminate()
 
772
            #time.sleep(0.5)
 
773
            #if self.checker.poll() is None:
 
774
            #    self.checker.kill()
 
775
        except OSError as error:
 
776
            if error.errno != errno.ESRCH: # No such process
 
777
                raise
764
778
        self.checker = None
765
779
 
766
780
 
767
 
def dbus_service_property(dbus_interface,
768
 
                          signature="v",
769
 
                          access="readwrite",
770
 
                          byte_arrays=False):
 
781
def dbus_service_property(dbus_interface, signature="v",
 
782
                          access="readwrite", byte_arrays=False):
771
783
    """Decorators for marking methods of a DBusObjectWithProperties to
772
784
    become properties on the D-Bus.
773
785
    
782
794
    # "Set" method, so we fail early here:
783
795
    if byte_arrays and signature != "ay":
784
796
        raise ValueError("Byte arrays not supported for non-'ay'"
785
 
                         " signature {!r}".format(signature))
786
 
    
 
797
                         " signature {0!r}".format(signature))
787
798
    def decorator(func):
788
799
        func._dbus_is_property = True
789
800
        func._dbus_interface = dbus_interface
794
805
            func._dbus_name = func._dbus_name[:-14]
795
806
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
796
807
        return func
797
 
    
798
808
    return decorator
799
809
 
800
810
 
809
819
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
810
820
                    "false"}
811
821
    """
812
 
    
813
822
    def decorator(func):
814
823
        func._dbus_is_interface = True
815
824
        func._dbus_interface = dbus_interface
816
825
        func._dbus_name = dbus_interface
817
826
        return func
818
 
    
819
827
    return decorator
820
828
 
821
829
 
823
831
    """Decorator to annotate D-Bus methods, signals or properties
824
832
    Usage:
825
833
    
826
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
827
 
                       "org.freedesktop.DBus.Property."
828
 
                       "EmitsChangedSignal": "false"})
829
834
    @dbus_service_property("org.example.Interface", signature="b",
830
835
                           access="r")
 
836
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
837
                        "org.freedesktop.DBus.Property."
 
838
                        "EmitsChangedSignal": "false"})
831
839
    def Property_dbus_property(self):
832
840
        return dbus.Boolean(False)
833
841
    """
834
 
    
835
842
    def decorator(func):
836
843
        func._dbus_annotations = annotations
837
844
        return func
838
 
    
839
845
    return decorator
840
846
 
841
847
 
842
848
class DBusPropertyException(dbus.exceptions.DBusException):
843
849
    """A base class for D-Bus property-related exceptions
844
850
    """
845
 
    pass
 
851
    def __unicode__(self):
 
852
        return unicode(str(self))
846
853
 
847
854
 
848
855
class DBusPropertyAccessException(DBusPropertyException):
872
879
        If called like _is_dbus_thing("method") it returns a function
873
880
        suitable for use as predicate to inspect.getmembers().
874
881
        """
875
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
882
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
876
883
                                   False)
877
884
    
878
885
    def _get_all_dbus_things(self, thing):
879
886
        """Returns a generator of (name, attribute) pairs
880
887
        """
881
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
888
        return ((getattr(athing.__get__(self), "_dbus_name",
 
889
                         name),
882
890
                 athing.__get__(self))
883
891
                for cls in self.__class__.__mro__
884
892
                for name, athing in
885
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
 
893
                inspect.getmembers(cls,
 
894
                                   self._is_dbus_thing(thing)))
886
895
    
887
896
    def _get_dbus_property(self, interface_name, property_name):
888
897
        """Returns a bound method if one exists which is a D-Bus
889
898
        property with the specified name and interface.
890
899
        """
891
 
        for cls in self.__class__.__mro__:
892
 
            for name, value in inspect.getmembers(
893
 
                    cls, self._is_dbus_thing("property")):
 
900
        for cls in  self.__class__.__mro__:
 
901
            for name, value in (inspect.getmembers
 
902
                                (cls,
 
903
                                 self._is_dbus_thing("property"))):
894
904
                if (value._dbus_name == property_name
895
905
                    and value._dbus_interface == interface_name):
896
906
                    return value.__get__(self)
897
907
        
898
908
        # No such property
899
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
900
 
            self.dbus_object_path, interface_name, property_name))
 
909
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
910
                                   + interface_name + "."
 
911
                                   + property_name)
901
912
    
902
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
903
 
                         in_signature="ss",
 
913
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
904
914
                         out_signature="v")
905
915
    def Get(self, interface_name, property_name):
906
916
        """Standard D-Bus property Get() method, see D-Bus standard.
924
934
            # The byte_arrays option is not supported yet on
925
935
            # signatures other than "ay".
926
936
            if prop._dbus_signature != "ay":
927
 
                raise ValueError("Byte arrays not supported for non-"
928
 
                                 "'ay' signature {!r}"
929
 
                                 .format(prop._dbus_signature))
 
937
                raise ValueError
930
938
            value = dbus.ByteArray(b''.join(chr(byte)
931
939
                                            for byte in value))
932
940
        prop(value)
933
941
    
934
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
935
 
                         in_signature="s",
 
942
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
936
943
                         out_signature="a{sv}")
937
944
    def GetAll(self, interface_name):
938
945
        """Standard D-Bus property GetAll() method, see D-Bus
953
960
            if not hasattr(value, "variant_level"):
954
961
                properties[name] = value
955
962
                continue
956
 
            properties[name] = type(value)(
957
 
                value, variant_level = value.variant_level + 1)
 
963
            properties[name] = type(value)(value, variant_level=
 
964
                                           value.variant_level+1)
958
965
        return dbus.Dictionary(properties, signature="sv")
959
966
    
960
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
961
 
    def PropertiesChanged(self, interface_name, changed_properties,
962
 
                          invalidated_properties):
963
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
964
 
        standard.
965
 
        """
966
 
        pass
967
 
    
968
967
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
969
968
                         out_signature="s",
970
969
                         path_keyword='object_path',
978
977
                                                   connection)
979
978
        try:
980
979
            document = xml.dom.minidom.parseString(xmlstring)
981
 
            
982
980
            def make_tag(document, name, prop):
983
981
                e = document.createElement("property")
984
982
                e.setAttribute("name", name)
985
983
                e.setAttribute("type", prop._dbus_signature)
986
984
                e.setAttribute("access", prop._dbus_access)
987
985
                return e
988
 
            
989
986
            for if_tag in document.getElementsByTagName("interface"):
990
987
                # Add property tags
991
988
                for tag in (make_tag(document, name, prop)
1003
1000
                            if (name == tag.getAttribute("name")
1004
1001
                                and prop._dbus_interface
1005
1002
                                == if_tag.getAttribute("name")):
1006
 
                                annots.update(getattr(
1007
 
                                    prop, "_dbus_annotations", {}))
1008
 
                        for name, value in annots.items():
 
1003
                                annots.update(getattr
 
1004
                                              (prop,
 
1005
                                               "_dbus_annotations",
 
1006
                                               {}))
 
1007
                        for name, value in annots.iteritems():
1009
1008
                            ann_tag = document.createElement(
1010
1009
                                "annotation")
1011
1010
                            ann_tag.setAttribute("name", name)
1014
1013
                # Add interface annotation tags
1015
1014
                for annotation, value in dict(
1016
1015
                    itertools.chain.from_iterable(
1017
 
                        annotations().items()
1018
 
                        for name, annotations
1019
 
                        in self._get_all_dbus_things("interface")
 
1016
                        annotations().iteritems()
 
1017
                        for name, annotations in
 
1018
                        self._get_all_dbus_things("interface")
1020
1019
                        if name == if_tag.getAttribute("name")
1021
 
                        )).items():
 
1020
                        )).iteritems():
1022
1021
                    ann_tag = document.createElement("annotation")
1023
1022
                    ann_tag.setAttribute("name", annotation)
1024
1023
                    ann_tag.setAttribute("value", value)
1051
1050
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1052
1051
    if dt is None:
1053
1052
        return dbus.String("", variant_level = variant_level)
1054
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1053
    return dbus.String(dt.isoformat(),
 
1054
                       variant_level=variant_level)
1055
1055
 
1056
1056
 
1057
1057
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1077
1077
    (from DBusObjectWithProperties) and interfaces (from the
1078
1078
    dbus_interface_annotations decorator).
1079
1079
    """
1080
 
    
1081
1080
    def wrapper(cls):
1082
1081
        for orig_interface_name, alt_interface_name in (
1083
 
                alt_interface_names.items()):
 
1082
            alt_interface_names.iteritems()):
1084
1083
            attr = {}
1085
1084
            interface_names = set()
1086
1085
            # Go though all attributes of the class
1088
1087
                # Ignore non-D-Bus attributes, and D-Bus attributes
1089
1088
                # with the wrong interface name
1090
1089
                if (not hasattr(attribute, "_dbus_interface")
1091
 
                    or not attribute._dbus_interface.startswith(
1092
 
                        orig_interface_name)):
 
1090
                    or not attribute._dbus_interface
 
1091
                    .startswith(orig_interface_name)):
1093
1092
                    continue
1094
1093
                # Create an alternate D-Bus interface name based on
1095
1094
                # the current name
1096
 
                alt_interface = attribute._dbus_interface.replace(
1097
 
                    orig_interface_name, alt_interface_name)
 
1095
                alt_interface = (attribute._dbus_interface
 
1096
                                 .replace(orig_interface_name,
 
1097
                                          alt_interface_name))
1098
1098
                interface_names.add(alt_interface)
1099
1099
                # Is this a D-Bus signal?
1100
1100
                if getattr(attribute, "_dbus_is_signal", False):
1101
1101
                    # Extract the original non-method undecorated
1102
1102
                    # function by black magic
1103
1103
                    nonmethod_func = (dict(
1104
 
                        zip(attribute.func_code.co_freevars,
1105
 
                            attribute.__closure__))
1106
 
                                      ["func"].cell_contents)
 
1104
                            zip(attribute.func_code.co_freevars,
 
1105
                                attribute.__closure__))["func"]
 
1106
                                      .cell_contents)
1107
1107
                    # Create a new, but exactly alike, function
1108
1108
                    # object, and decorate it to be a new D-Bus signal
1109
1109
                    # with the alternate D-Bus interface name
1110
 
                    new_function = (dbus.service.signal(
1111
 
                        alt_interface, attribute._dbus_signature)
 
1110
                    new_function = (dbus.service.signal
 
1111
                                    (alt_interface,
 
1112
                                     attribute._dbus_signature)
1112
1113
                                    (types.FunctionType(
1113
 
                                        nonmethod_func.func_code,
1114
 
                                        nonmethod_func.func_globals,
1115
 
                                        nonmethod_func.func_name,
1116
 
                                        nonmethod_func.func_defaults,
1117
 
                                        nonmethod_func.func_closure)))
 
1114
                                nonmethod_func.func_code,
 
1115
                                nonmethod_func.func_globals,
 
1116
                                nonmethod_func.func_name,
 
1117
                                nonmethod_func.func_defaults,
 
1118
                                nonmethod_func.func_closure)))
1118
1119
                    # Copy annotations, if any
1119
1120
                    try:
1120
 
                        new_function._dbus_annotations = dict(
1121
 
                            attribute._dbus_annotations)
 
1121
                        new_function._dbus_annotations = (
 
1122
                            dict(attribute._dbus_annotations))
1122
1123
                    except AttributeError:
1123
1124
                        pass
1124
1125
                    # Define a creator of a function to call both the
1129
1130
                        """This function is a scope container to pass
1130
1131
                        func1 and func2 to the "call_both" function
1131
1132
                        outside of its arguments"""
1132
 
                        
1133
1133
                        def call_both(*args, **kwargs):
1134
1134
                            """This function will emit two D-Bus
1135
1135
                            signals by calling func1 and func2"""
1136
1136
                            func1(*args, **kwargs)
1137
1137
                            func2(*args, **kwargs)
1138
 
                        
1139
1138
                        return call_both
1140
1139
                    # Create the "call_both" function and add it to
1141
1140
                    # the class
1146
1145
                    # object.  Decorate it to be a new D-Bus method
1147
1146
                    # with the alternate D-Bus interface name.  Add it
1148
1147
                    # to the class.
1149
 
                    attr[attrname] = (
1150
 
                        dbus.service.method(
1151
 
                            alt_interface,
1152
 
                            attribute._dbus_in_signature,
1153
 
                            attribute._dbus_out_signature)
1154
 
                        (types.FunctionType(attribute.func_code,
1155
 
                                            attribute.func_globals,
1156
 
                                            attribute.func_name,
1157
 
                                            attribute.func_defaults,
1158
 
                                            attribute.func_closure)))
 
1148
                    attr[attrname] = (dbus.service.method
 
1149
                                      (alt_interface,
 
1150
                                       attribute._dbus_in_signature,
 
1151
                                       attribute._dbus_out_signature)
 
1152
                                      (types.FunctionType
 
1153
                                       (attribute.func_code,
 
1154
                                        attribute.func_globals,
 
1155
                                        attribute.func_name,
 
1156
                                        attribute.func_defaults,
 
1157
                                        attribute.func_closure)))
1159
1158
                    # Copy annotations, if any
1160
1159
                    try:
1161
 
                        attr[attrname]._dbus_annotations = dict(
1162
 
                            attribute._dbus_annotations)
 
1160
                        attr[attrname]._dbus_annotations = (
 
1161
                            dict(attribute._dbus_annotations))
1163
1162
                    except AttributeError:
1164
1163
                        pass
1165
1164
                # Is this a D-Bus property?
1168
1167
                    # object, and decorate it to be a new D-Bus
1169
1168
                    # property with the alternate D-Bus interface
1170
1169
                    # name.  Add it to the class.
1171
 
                    attr[attrname] = (dbus_service_property(
1172
 
                        alt_interface, attribute._dbus_signature,
1173
 
                        attribute._dbus_access,
1174
 
                        attribute._dbus_get_args_options
1175
 
                        ["byte_arrays"])
1176
 
                                      (types.FunctionType(
1177
 
                                          attribute.func_code,
1178
 
                                          attribute.func_globals,
1179
 
                                          attribute.func_name,
1180
 
                                          attribute.func_defaults,
1181
 
                                          attribute.func_closure)))
 
1170
                    attr[attrname] = (dbus_service_property
 
1171
                                      (alt_interface,
 
1172
                                       attribute._dbus_signature,
 
1173
                                       attribute._dbus_access,
 
1174
                                       attribute
 
1175
                                       ._dbus_get_args_options
 
1176
                                       ["byte_arrays"])
 
1177
                                      (types.FunctionType
 
1178
                                       (attribute.func_code,
 
1179
                                        attribute.func_globals,
 
1180
                                        attribute.func_name,
 
1181
                                        attribute.func_defaults,
 
1182
                                        attribute.func_closure)))
1182
1183
                    # Copy annotations, if any
1183
1184
                    try:
1184
 
                        attr[attrname]._dbus_annotations = dict(
1185
 
                            attribute._dbus_annotations)
 
1185
                        attr[attrname]._dbus_annotations = (
 
1186
                            dict(attribute._dbus_annotations))
1186
1187
                    except AttributeError:
1187
1188
                        pass
1188
1189
                # Is this a D-Bus interface?
1191
1192
                    # object.  Decorate it to be a new D-Bus interface
1192
1193
                    # with the alternate D-Bus interface name.  Add it
1193
1194
                    # to the class.
1194
 
                    attr[attrname] = (
1195
 
                        dbus_interface_annotations(alt_interface)
1196
 
                        (types.FunctionType(attribute.func_code,
1197
 
                                            attribute.func_globals,
1198
 
                                            attribute.func_name,
1199
 
                                            attribute.func_defaults,
1200
 
                                            attribute.func_closure)))
 
1195
                    attr[attrname] = (dbus_interface_annotations
 
1196
                                      (alt_interface)
 
1197
                                      (types.FunctionType
 
1198
                                       (attribute.func_code,
 
1199
                                        attribute.func_globals,
 
1200
                                        attribute.func_name,
 
1201
                                        attribute.func_defaults,
 
1202
                                        attribute.func_closure)))
1201
1203
            if deprecate:
1202
1204
                # Deprecate all alternate interfaces
1203
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1205
                iname="_AlternateDBusNames_interface_annotation{0}"
1204
1206
                for interface_name in interface_names:
1205
 
                    
1206
1207
                    @dbus_interface_annotations(interface_name)
1207
1208
                    def func(self):
1208
1209
                        return { "org.freedesktop.DBus.Deprecated":
1209
 
                                 "true" }
 
1210
                                     "true" }
1210
1211
                    # Find an unused name
1211
1212
                    for aname in (iname.format(i)
1212
1213
                                  for i in itertools.count()):
1216
1217
            if interface_names:
1217
1218
                # Replace the class with a new subclass of it with
1218
1219
                # methods, signals, etc. as created above.
1219
 
                cls = type(b"{}Alternate".format(cls.__name__),
1220
 
                           (cls, ), attr)
 
1220
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1221
                           (cls,), attr)
1221
1222
        return cls
1222
 
    
1223
1223
    return wrapper
1224
1224
 
1225
1225
 
1226
1226
@alternate_dbus_interfaces({"se.recompile.Mandos":
1227
 
                            "se.bsnet.fukt.Mandos"})
 
1227
                                "se.bsnet.fukt.Mandos"})
1228
1228
class ClientDBus(Client, DBusObjectWithProperties):
1229
1229
    """A Client class using D-Bus
1230
1230
    
1234
1234
    """
1235
1235
    
1236
1236
    runtime_expansions = (Client.runtime_expansions
1237
 
                          + ("dbus_object_path", ))
1238
 
    
1239
 
    _interface = "se.recompile.Mandos.Client"
 
1237
                          + ("dbus_object_path",))
1240
1238
    
1241
1239
    # dbus.service.Object doesn't use super(), so we can't either.
1242
1240
    
1245
1243
        Client.__init__(self, *args, **kwargs)
1246
1244
        # Only now, when this client is initialized, can it show up on
1247
1245
        # the D-Bus
1248
 
        client_object_name = str(self.name).translate(
 
1246
        client_object_name = unicode(self.name).translate(
1249
1247
            {ord("."): ord("_"),
1250
1248
             ord("-"): ord("_")})
1251
 
        self.dbus_object_path = dbus.ObjectPath(
1252
 
            "/clients/" + client_object_name)
 
1249
        self.dbus_object_path = (dbus.ObjectPath
 
1250
                                 ("/clients/" + client_object_name))
1253
1251
        DBusObjectWithProperties.__init__(self, self.bus,
1254
1252
                                          self.dbus_object_path)
1255
1253
    
1256
 
    def notifychangeproperty(transform_func, dbus_name,
1257
 
                             type_func=lambda x: x,
1258
 
                             variant_level=1,
1259
 
                             invalidate_only=False,
1260
 
                             _interface=_interface):
 
1254
    def notifychangeproperty(transform_func,
 
1255
                             dbus_name, type_func=lambda x: x,
 
1256
                             variant_level=1):
1261
1257
        """ Modify a variable so that it's a property which announces
1262
1258
        its changes to DBus.
1263
1259
        
1268
1264
                   to the D-Bus.  Default: no transform
1269
1265
        variant_level: D-Bus variant level.  Default: 1
1270
1266
        """
1271
 
        attrname = "_{}".format(dbus_name)
1272
 
        
 
1267
        attrname = "_{0}".format(dbus_name)
1273
1268
        def setter(self, value):
1274
1269
            if hasattr(self, "dbus_object_path"):
1275
1270
                if (not hasattr(self, attrname) or
1276
1271
                    type_func(getattr(self, attrname, None))
1277
1272
                    != type_func(value)):
1278
 
                    if invalidate_only:
1279
 
                        self.PropertiesChanged(
1280
 
                            _interface, dbus.Dictionary(),
1281
 
                            dbus.Array((dbus_name, )))
1282
 
                    else:
1283
 
                        dbus_value = transform_func(
1284
 
                            type_func(value),
1285
 
                            variant_level = variant_level)
1286
 
                        self.PropertyChanged(dbus.String(dbus_name),
1287
 
                                             dbus_value)
1288
 
                        self.PropertiesChanged(
1289
 
                            _interface,
1290
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1291
 
                                              dbus_value }),
1292
 
                            dbus.Array())
 
1273
                    dbus_value = transform_func(type_func(value),
 
1274
                                                variant_level
 
1275
                                                =variant_level)
 
1276
                    self.PropertyChanged(dbus.String(dbus_name),
 
1277
                                         dbus_value)
1293
1278
            setattr(self, attrname, value)
1294
1279
        
1295
1280
        return property(lambda self: getattr(self, attrname), setter)
1301
1286
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1302
1287
    last_enabled = notifychangeproperty(datetime_to_dbus,
1303
1288
                                        "LastEnabled")
1304
 
    checker = notifychangeproperty(
1305
 
        dbus.Boolean, "CheckerRunning",
1306
 
        type_func = lambda checker: checker is not None)
 
1289
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1290
                                   type_func = lambda checker:
 
1291
                                       checker is not None)
1307
1292
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1308
1293
                                           "LastCheckedOK")
1309
1294
    last_checker_status = notifychangeproperty(dbus.Int16,
1312
1297
        datetime_to_dbus, "LastApprovalRequest")
1313
1298
    approved_by_default = notifychangeproperty(dbus.Boolean,
1314
1299
                                               "ApprovedByDefault")
1315
 
    approval_delay = notifychangeproperty(
1316
 
        dbus.UInt64, "ApprovalDelay",
1317
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1300
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1301
                                          "ApprovalDelay",
 
1302
                                          type_func =
 
1303
                                          timedelta_to_milliseconds)
1318
1304
    approval_duration = notifychangeproperty(
1319
1305
        dbus.UInt64, "ApprovalDuration",
1320
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1306
        type_func = timedelta_to_milliseconds)
1321
1307
    host = notifychangeproperty(dbus.String, "Host")
1322
 
    timeout = notifychangeproperty(
1323
 
        dbus.UInt64, "Timeout",
1324
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1308
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1309
                                   type_func =
 
1310
                                   timedelta_to_milliseconds)
1325
1311
    extended_timeout = notifychangeproperty(
1326
1312
        dbus.UInt64, "ExtendedTimeout",
1327
 
        type_func = lambda td: td.total_seconds() * 1000)
1328
 
    interval = notifychangeproperty(
1329
 
        dbus.UInt64, "Interval",
1330
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1313
        type_func = timedelta_to_milliseconds)
 
1314
    interval = notifychangeproperty(dbus.UInt64,
 
1315
                                    "Interval",
 
1316
                                    type_func =
 
1317
                                    timedelta_to_milliseconds)
1331
1318
    checker_command = notifychangeproperty(dbus.String, "Checker")
1332
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
 
                                  invalidate_only=True)
1334
1319
    
1335
1320
    del notifychangeproperty
1336
1321
    
1343
1328
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1344
1329
        Client.__del__(self, *args, **kwargs)
1345
1330
    
1346
 
    def checker_callback(self, source, condition,
1347
 
                         (connection, command), *args, **kwargs):
1348
 
        ret = Client.checker_callback(self, source, condition,
1349
 
                                      (connection, command), *args,
1350
 
                                      **kwargs)
1351
 
        exitstatus = self.last_checker_status
1352
 
        if exitstatus >= 0:
 
1331
    def checker_callback(self, pid, condition, command,
 
1332
                         *args, **kwargs):
 
1333
        self.checker_callback_tag = None
 
1334
        self.checker = None
 
1335
        if os.WIFEXITED(condition):
 
1336
            exitstatus = os.WEXITSTATUS(condition)
1353
1337
            # Emit D-Bus signal
1354
1338
            self.CheckerCompleted(dbus.Int16(exitstatus),
1355
 
                                  dbus.Int64(0),
 
1339
                                  dbus.Int64(condition),
1356
1340
                                  dbus.String(command))
1357
1341
        else:
1358
1342
            # Emit D-Bus signal
1359
1343
            self.CheckerCompleted(dbus.Int16(-1),
1360
 
                                  dbus.Int64(
1361
 
                                      self.last_checker_signal),
 
1344
                                  dbus.Int64(condition),
1362
1345
                                  dbus.String(command))
1363
 
        return ret
 
1346
        
 
1347
        return Client.checker_callback(self, pid, condition, command,
 
1348
                                       *args, **kwargs)
1364
1349
    
1365
1350
    def start_checker(self, *args, **kwargs):
1366
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1351
        old_checker = self.checker
 
1352
        if self.checker is not None:
 
1353
            old_checker_pid = self.checker.pid
 
1354
        else:
 
1355
            old_checker_pid = None
1367
1356
        r = Client.start_checker(self, *args, **kwargs)
1368
1357
        # Only if new checker process was started
1369
1358
        if (self.checker is not None
1378
1367
    
1379
1368
    def approve(self, value=True):
1380
1369
        self.approved = value
1381
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1382
 
                                * 1000), self._reset_approved)
 
1370
        gobject.timeout_add(timedelta_to_milliseconds
 
1371
                            (self.approval_duration),
 
1372
                            self._reset_approved)
1383
1373
        self.send_changedstate()
1384
1374
    
1385
1375
    ## D-Bus methods, signals & properties
 
1376
    _interface = "se.recompile.Mandos.Client"
1386
1377
    
1387
1378
    ## Interfaces
1388
1379
    
 
1380
    @dbus_interface_annotations(_interface)
 
1381
    def _foo(self):
 
1382
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1383
                     "false"}
 
1384
    
1389
1385
    ## Signals
1390
1386
    
1391
1387
    # CheckerCompleted - signal
1401
1397
        pass
1402
1398
    
1403
1399
    # PropertyChanged - signal
1404
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1405
1400
    @dbus.service.signal(_interface, signature="sv")
1406
1401
    def PropertyChanged(self, property, value):
1407
1402
        "D-Bus signal"
1471
1466
        return dbus.Boolean(bool(self.approvals_pending))
1472
1467
    
1473
1468
    # ApprovedByDefault - property
1474
 
    @dbus_service_property(_interface,
1475
 
                           signature="b",
 
1469
    @dbus_service_property(_interface, signature="b",
1476
1470
                           access="readwrite")
1477
1471
    def ApprovedByDefault_dbus_property(self, value=None):
1478
1472
        if value is None:       # get
1480
1474
        self.approved_by_default = bool(value)
1481
1475
    
1482
1476
    # ApprovalDelay - property
1483
 
    @dbus_service_property(_interface,
1484
 
                           signature="t",
 
1477
    @dbus_service_property(_interface, signature="t",
1485
1478
                           access="readwrite")
1486
1479
    def ApprovalDelay_dbus_property(self, value=None):
1487
1480
        if value is None:       # get
1488
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1489
 
                               * 1000)
 
1481
            return dbus.UInt64(self.approval_delay_milliseconds())
1490
1482
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1491
1483
    
1492
1484
    # ApprovalDuration - property
1493
 
    @dbus_service_property(_interface,
1494
 
                           signature="t",
 
1485
    @dbus_service_property(_interface, signature="t",
1495
1486
                           access="readwrite")
1496
1487
    def ApprovalDuration_dbus_property(self, value=None):
1497
1488
        if value is None:       # get
1498
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1499
 
                               * 1000)
 
1489
            return dbus.UInt64(timedelta_to_milliseconds(
 
1490
                    self.approval_duration))
1500
1491
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1501
1492
    
1502
1493
    # Name - property
1510
1501
        return dbus.String(self.fingerprint)
1511
1502
    
1512
1503
    # Host - property
1513
 
    @dbus_service_property(_interface,
1514
 
                           signature="s",
 
1504
    @dbus_service_property(_interface, signature="s",
1515
1505
                           access="readwrite")
1516
1506
    def Host_dbus_property(self, value=None):
1517
1507
        if value is None:       # get
1518
1508
            return dbus.String(self.host)
1519
 
        self.host = str(value)
 
1509
        self.host = unicode(value)
1520
1510
    
1521
1511
    # Created - property
1522
1512
    @dbus_service_property(_interface, signature="s", access="read")
1529
1519
        return datetime_to_dbus(self.last_enabled)
1530
1520
    
1531
1521
    # Enabled - property
1532
 
    @dbus_service_property(_interface,
1533
 
                           signature="b",
 
1522
    @dbus_service_property(_interface, signature="b",
1534
1523
                           access="readwrite")
1535
1524
    def Enabled_dbus_property(self, value=None):
1536
1525
        if value is None:       # get
1541
1530
            self.disable()
1542
1531
    
1543
1532
    # LastCheckedOK - property
1544
 
    @dbus_service_property(_interface,
1545
 
                           signature="s",
 
1533
    @dbus_service_property(_interface, signature="s",
1546
1534
                           access="readwrite")
1547
1535
    def LastCheckedOK_dbus_property(self, value=None):
1548
1536
        if value is not None:
1551
1539
        return datetime_to_dbus(self.last_checked_ok)
1552
1540
    
1553
1541
    # LastCheckerStatus - property
1554
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1542
    @dbus_service_property(_interface, signature="n",
 
1543
                           access="read")
1555
1544
    def LastCheckerStatus_dbus_property(self):
1556
1545
        return dbus.Int16(self.last_checker_status)
1557
1546
    
1566
1555
        return datetime_to_dbus(self.last_approval_request)
1567
1556
    
1568
1557
    # Timeout - property
1569
 
    @dbus_service_property(_interface,
1570
 
                           signature="t",
 
1558
    @dbus_service_property(_interface, signature="t",
1571
1559
                           access="readwrite")
1572
1560
    def Timeout_dbus_property(self, value=None):
1573
1561
        if value is None:       # get
1574
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1562
            return dbus.UInt64(self.timeout_milliseconds())
1575
1563
        old_timeout = self.timeout
1576
1564
        self.timeout = datetime.timedelta(0, 0, 0, value)
1577
1565
        # Reschedule disabling
1586
1574
                    is None):
1587
1575
                    return
1588
1576
                gobject.source_remove(self.disable_initiator_tag)
1589
 
                self.disable_initiator_tag = gobject.timeout_add(
1590
 
                    int((self.expires - now).total_seconds() * 1000),
1591
 
                    self.disable)
 
1577
                self.disable_initiator_tag = (
 
1578
                    gobject.timeout_add(
 
1579
                        timedelta_to_milliseconds(self.expires - now),
 
1580
                        self.disable))
1592
1581
    
1593
1582
    # ExtendedTimeout - property
1594
 
    @dbus_service_property(_interface,
1595
 
                           signature="t",
 
1583
    @dbus_service_property(_interface, signature="t",
1596
1584
                           access="readwrite")
1597
1585
    def ExtendedTimeout_dbus_property(self, value=None):
1598
1586
        if value is None:       # get
1599
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
1600
 
                               * 1000)
 
1587
            return dbus.UInt64(self.extended_timeout_milliseconds())
1601
1588
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1602
1589
    
1603
1590
    # Interval - property
1604
 
    @dbus_service_property(_interface,
1605
 
                           signature="t",
 
1591
    @dbus_service_property(_interface, signature="t",
1606
1592
                           access="readwrite")
1607
1593
    def Interval_dbus_property(self, value=None):
1608
1594
        if value is None:       # get
1609
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1595
            return dbus.UInt64(self.interval_milliseconds())
1610
1596
        self.interval = datetime.timedelta(0, 0, 0, value)
1611
1597
        if getattr(self, "checker_initiator_tag", None) is None:
1612
1598
            return
1613
1599
        if self.enabled:
1614
1600
            # Reschedule checker run
1615
1601
            gobject.source_remove(self.checker_initiator_tag)
1616
 
            self.checker_initiator_tag = gobject.timeout_add(
1617
 
                value, self.start_checker)
1618
 
            self.start_checker() # Start one now, too
 
1602
            self.checker_initiator_tag = (gobject.timeout_add
 
1603
                                          (value, self.start_checker))
 
1604
            self.start_checker()    # Start one now, too
1619
1605
    
1620
1606
    # Checker - property
1621
 
    @dbus_service_property(_interface,
1622
 
                           signature="s",
 
1607
    @dbus_service_property(_interface, signature="s",
1623
1608
                           access="readwrite")
1624
1609
    def Checker_dbus_property(self, value=None):
1625
1610
        if value is None:       # get
1626
1611
            return dbus.String(self.checker_command)
1627
 
        self.checker_command = str(value)
 
1612
        self.checker_command = unicode(value)
1628
1613
    
1629
1614
    # CheckerRunning - property
1630
 
    @dbus_service_property(_interface,
1631
 
                           signature="b",
 
1615
    @dbus_service_property(_interface, signature="b",
1632
1616
                           access="readwrite")
1633
1617
    def CheckerRunning_dbus_property(self, value=None):
1634
1618
        if value is None:       # get
1644
1628
        return self.dbus_object_path # is already a dbus.ObjectPath
1645
1629
    
1646
1630
    # Secret = property
1647
 
    @dbus_service_property(_interface,
1648
 
                           signature="ay",
1649
 
                           access="write",
1650
 
                           byte_arrays=True)
 
1631
    @dbus_service_property(_interface, signature="ay",
 
1632
                           access="write", byte_arrays=True)
1651
1633
    def Secret_dbus_property(self, value):
1652
 
        self.secret = bytes(value)
 
1634
        self.secret = str(value)
1653
1635
    
1654
1636
    del _interface
1655
1637
 
1669
1651
        if data[0] == 'data':
1670
1652
            return data[1]
1671
1653
        if data[0] == 'function':
1672
 
            
1673
1654
            def func(*args, **kwargs):
1674
1655
                self._pipe.send(('funcall', name, args, kwargs))
1675
1656
                return self._pipe.recv()[1]
1676
 
            
1677
1657
            return func
1678
1658
    
1679
1659
    def __setattr__(self, name, value):
1691
1671
    def handle(self):
1692
1672
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1693
1673
            logger.info("TCP connection from: %s",
1694
 
                        str(self.client_address))
 
1674
                        unicode(self.client_address))
1695
1675
            logger.debug("Pipe FD: %d",
1696
1676
                         self.server.child_pipe.fileno())
1697
1677
            
1698
 
            session = gnutls.connection.ClientSession(
1699
 
                self.request, gnutls.connection .X509Credentials())
 
1678
            session = (gnutls.connection
 
1679
                       .ClientSession(self.request,
 
1680
                                      gnutls.connection
 
1681
                                      .X509Credentials()))
1700
1682
            
1701
1683
            # Note: gnutls.connection.X509Credentials is really a
1702
1684
            # generic GnuTLS certificate credentials object so long as
1711
1693
            priority = self.server.gnutls_priority
1712
1694
            if priority is None:
1713
1695
                priority = "NORMAL"
1714
 
            gnutls.library.functions.gnutls_priority_set_direct(
1715
 
                session._c_object, priority, None)
 
1696
            (gnutls.library.functions
 
1697
             .gnutls_priority_set_direct(session._c_object,
 
1698
                                         priority, None))
1716
1699
            
1717
1700
            # Start communication using the Mandos protocol
1718
1701
            # Get protocol number
1738
1721
            approval_required = False
1739
1722
            try:
1740
1723
                try:
1741
 
                    fpr = self.fingerprint(
1742
 
                        self.peer_certificate(session))
 
1724
                    fpr = self.fingerprint(self.peer_certificate
 
1725
                                           (session))
1743
1726
                except (TypeError,
1744
1727
                        gnutls.errors.GNUTLSError) as error:
1745
1728
                    logger.warning("Bad certificate: %s", error)
1760
1743
                while True:
1761
1744
                    if not client.enabled:
1762
1745
                        logger.info("Client %s is disabled",
1763
 
                                    client.name)
 
1746
                                       client.name)
1764
1747
                        if self.server.use_dbus:
1765
1748
                            # Emit D-Bus signal
1766
1749
                            client.Rejected("Disabled")
1775
1758
                        if self.server.use_dbus:
1776
1759
                            # Emit D-Bus signal
1777
1760
                            client.NeedApproval(
1778
 
                                client.approval_delay.total_seconds()
1779
 
                                * 1000, client.approved_by_default)
 
1761
                                client.approval_delay_milliseconds(),
 
1762
                                client.approved_by_default)
1780
1763
                    else:
1781
1764
                        logger.warning("Client %s was not approved",
1782
1765
                                       client.name)
1788
1771
                    #wait until timeout or approved
1789
1772
                    time = datetime.datetime.now()
1790
1773
                    client.changedstate.acquire()
1791
 
                    client.changedstate.wait(delay.total_seconds())
 
1774
                    client.changedstate.wait(
 
1775
                        float(timedelta_to_milliseconds(delay)
 
1776
                              / 1000))
1792
1777
                    client.changedstate.release()
1793
1778
                    time2 = datetime.datetime.now()
1794
1779
                    if (time2 - time) >= delay:
1813
1798
                        logger.warning("gnutls send failed",
1814
1799
                                       exc_info=error)
1815
1800
                        return
1816
 
                    logger.debug("Sent: %d, remaining: %d", sent,
1817
 
                                 len(client.secret) - (sent_size
1818
 
                                                       + sent))
 
1801
                    logger.debug("Sent: %d, remaining: %d",
 
1802
                                 sent, len(client.secret)
 
1803
                                 - (sent_size + sent))
1819
1804
                    sent_size += sent
1820
1805
                
1821
1806
                logger.info("Sending secret to %s", client.name)
1838
1823
    def peer_certificate(session):
1839
1824
        "Return the peer's OpenPGP certificate as a bytestring"
1840
1825
        # If not an OpenPGP certificate...
1841
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
1842
 
                session._c_object)
 
1826
        if (gnutls.library.functions
 
1827
            .gnutls_certificate_type_get(session._c_object)
1843
1828
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1844
1829
            # ...do the normal thing
1845
1830
            return session.peer_certificate
1859
1844
    def fingerprint(openpgp):
1860
1845
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1861
1846
        # New GnuTLS "datum" with the OpenPGP public key
1862
 
        datum = gnutls.library.types.gnutls_datum_t(
1863
 
            ctypes.cast(ctypes.c_char_p(openpgp),
1864
 
                        ctypes.POINTER(ctypes.c_ubyte)),
1865
 
            ctypes.c_uint(len(openpgp)))
 
1847
        datum = (gnutls.library.types
 
1848
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1849
                                             ctypes.POINTER
 
1850
                                             (ctypes.c_ubyte)),
 
1851
                                 ctypes.c_uint(len(openpgp))))
1866
1852
        # New empty GnuTLS certificate
1867
1853
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1868
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1869
 
            ctypes.byref(crt))
 
1854
        (gnutls.library.functions
 
1855
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1870
1856
        # Import the OpenPGP public key into the certificate
1871
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1872
 
            crt, ctypes.byref(datum),
1873
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
1857
        (gnutls.library.functions
 
1858
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1859
                                    gnutls.library.constants
 
1860
                                    .GNUTLS_OPENPGP_FMT_RAW))
1874
1861
        # Verify the self signature in the key
1875
1862
        crtverify = ctypes.c_uint()
1876
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
 
            crt, 0, ctypes.byref(crtverify))
 
1863
        (gnutls.library.functions
 
1864
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1865
                                         ctypes.byref(crtverify)))
1878
1866
        if crtverify.value != 0:
1879
1867
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1880
 
            raise gnutls.errors.CertificateSecurityError(
1881
 
                "Verify failed")
 
1868
            raise (gnutls.errors.CertificateSecurityError
 
1869
                   ("Verify failed"))
1882
1870
        # New buffer for the fingerprint
1883
1871
        buf = ctypes.create_string_buffer(20)
1884
1872
        buf_len = ctypes.c_size_t()
1885
1873
        # Get the fingerprint from the certificate into the buffer
1886
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1887
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
1874
        (gnutls.library.functions
 
1875
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1876
                                             ctypes.byref(buf_len)))
1888
1877
        # Deinit the certificate
1889
1878
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1890
1879
        # Convert the buffer to a Python bytestring
1896
1885
 
1897
1886
class MultiprocessingMixIn(object):
1898
1887
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1899
 
    
1900
1888
    def sub_process_main(self, request, address):
1901
1889
        try:
1902
1890
            self.finish_request(request, address)
1914
1902
 
1915
1903
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1916
1904
    """ adds a pipe to the MixIn """
1917
 
    
1918
1905
    def process_request(self, request, client_address):
1919
1906
        """Overrides and wraps the original process_request().
1920
1907
        
1941
1928
        interface:      None or a network interface name (string)
1942
1929
        use_ipv6:       Boolean; to use IPv6 or not
1943
1930
    """
1944
 
    
1945
1931
    def __init__(self, server_address, RequestHandlerClass,
1946
 
                 interface=None,
1947
 
                 use_ipv6=True,
1948
 
                 socketfd=None):
 
1932
                 interface=None, use_ipv6=True, socketfd=None):
1949
1933
        """If socketfd is set, use that file descriptor instead of
1950
1934
        creating a new one with socket.socket().
1951
1935
        """
1992
1976
                             self.interface)
1993
1977
            else:
1994
1978
                try:
1995
 
                    self.socket.setsockopt(
1996
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
 
                        (self.interface + "\0").encode("utf-8"))
 
1979
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1980
                                           SO_BINDTODEVICE,
 
1981
                                           str(self.interface + '\0'))
1998
1982
                except socket.error as error:
1999
1983
                    if error.errno == errno.EPERM:
2000
1984
                        logger.error("No permission to bind to"
2018
2002
                self.server_address = (any_address,
2019
2003
                                       self.server_address[1])
2020
2004
            elif not self.server_address[1]:
2021
 
                self.server_address = (self.server_address[0], 0)
 
2005
                self.server_address = (self.server_address[0],
 
2006
                                       0)
2022
2007
#                 if self.interface:
2023
2008
#                     self.server_address = (self.server_address[0],
2024
2009
#                                            0, # port
2038
2023
    
2039
2024
    Assumes a gobject.MainLoop event loop.
2040
2025
    """
2041
 
    
2042
2026
    def __init__(self, server_address, RequestHandlerClass,
2043
 
                 interface=None,
2044
 
                 use_ipv6=True,
2045
 
                 clients=None,
2046
 
                 gnutls_priority=None,
2047
 
                 use_dbus=True,
2048
 
                 socketfd=None):
 
2027
                 interface=None, use_ipv6=True, clients=None,
 
2028
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2049
2029
        self.enabled = False
2050
2030
        self.clients = clients
2051
2031
        if self.clients is None:
2057
2037
                                interface = interface,
2058
2038
                                use_ipv6 = use_ipv6,
2059
2039
                                socketfd = socketfd)
2060
 
    
2061
2040
    def server_activate(self):
2062
2041
        if self.enabled:
2063
2042
            return socketserver.TCPServer.server_activate(self)
2067
2046
    
2068
2047
    def add_pipe(self, parent_pipe, proc):
2069
2048
        # Call "handle_ipc" for both data and EOF events
2070
 
        gobject.io_add_watch(
2071
 
            parent_pipe.fileno(),
2072
 
            gobject.IO_IN | gobject.IO_HUP,
2073
 
            functools.partial(self.handle_ipc,
2074
 
                              parent_pipe = parent_pipe,
2075
 
                              proc = proc))
 
2049
        gobject.io_add_watch(parent_pipe.fileno(),
 
2050
                             gobject.IO_IN | gobject.IO_HUP,
 
2051
                             functools.partial(self.handle_ipc,
 
2052
                                               parent_pipe =
 
2053
                                               parent_pipe,
 
2054
                                               proc = proc))
2076
2055
    
2077
 
    def handle_ipc(self, source, condition,
2078
 
                   parent_pipe=None,
2079
 
                   proc = None,
2080
 
                   client_object=None):
 
2056
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2057
                   proc = None, client_object=None):
2081
2058
        # error, or the other end of multiprocessing.Pipe has closed
2082
2059
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2083
2060
            # Wait for other process to exit
2106
2083
                parent_pipe.send(False)
2107
2084
                return False
2108
2085
            
2109
 
            gobject.io_add_watch(
2110
 
                parent_pipe.fileno(),
2111
 
                gobject.IO_IN | gobject.IO_HUP,
2112
 
                functools.partial(self.handle_ipc,
2113
 
                                  parent_pipe = parent_pipe,
2114
 
                                  proc = proc,
2115
 
                                  client_object = client))
 
2086
            gobject.io_add_watch(parent_pipe.fileno(),
 
2087
                                 gobject.IO_IN | gobject.IO_HUP,
 
2088
                                 functools.partial(self.handle_ipc,
 
2089
                                                   parent_pipe =
 
2090
                                                   parent_pipe,
 
2091
                                                   proc = proc,
 
2092
                                                   client_object =
 
2093
                                                   client))
2116
2094
            parent_pipe.send(True)
2117
2095
            # remove the old hook in favor of the new above hook on
2118
2096
            # same fileno
2124
2102
            
2125
2103
            parent_pipe.send(('data', getattr(client_object,
2126
2104
                                              funcname)(*args,
2127
 
                                                        **kwargs)))
 
2105
                                                         **kwargs)))
2128
2106
        
2129
2107
        if command == 'getattr':
2130
2108
            attrname = request[1]
2131
2109
            if callable(client_object.__getattribute__(attrname)):
2132
 
                parent_pipe.send(('function', ))
 
2110
                parent_pipe.send(('function',))
2133
2111
            else:
2134
 
                parent_pipe.send((
2135
 
                    'data', client_object.__getattribute__(attrname)))
 
2112
                parent_pipe.send(('data', client_object
 
2113
                                  .__getattribute__(attrname)))
2136
2114
        
2137
2115
        if command == 'setattr':
2138
2116
            attrname = request[1]
2178
2156
                                              # None
2179
2157
                                    "followers")) # Tokens valid after
2180
2158
                                                  # this token
2181
 
    Token = collections.namedtuple("Token", (
2182
 
        "regexp",  # To match token; if "value" is not None, must have
2183
 
                   # a "group" containing digits
2184
 
        "value",   # datetime.timedelta or None
2185
 
        "followers"))           # Tokens valid after this token
2186
2159
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2187
2160
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2188
2161
    token_end = Token(re.compile(r"$"), None, frozenset())
2189
2162
    token_second = Token(re.compile(r"(\d+)S"),
2190
2163
                         datetime.timedelta(seconds=1),
2191
 
                         frozenset((token_end, )))
 
2164
                         frozenset((token_end,)))
2192
2165
    token_minute = Token(re.compile(r"(\d+)M"),
2193
2166
                         datetime.timedelta(minutes=1),
2194
2167
                         frozenset((token_second, token_end)))
2210
2183
                       frozenset((token_month, token_end)))
2211
2184
    token_week = Token(re.compile(r"(\d+)W"),
2212
2185
                       datetime.timedelta(weeks=1),
2213
 
                       frozenset((token_end, )))
 
2186
                       frozenset((token_end,)))
2214
2187
    token_duration = Token(re.compile(r"P"), None,
2215
2188
                           frozenset((token_year, token_month,
2216
2189
                                      token_day, token_time,
2217
 
                                      token_week)))
 
2190
                                      token_week))),
2218
2191
    # Define starting values
2219
2192
    value = datetime.timedelta() # Value so far
2220
2193
    found_token = None
2221
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2194
    followers = frozenset(token_duration,) # Following valid tokens
2222
2195
    s = duration                # String left to parse
2223
2196
    # Loop until end token is found
2224
2197
    while found_token is not token_end:
2271
2244
    timevalue = datetime.timedelta(0)
2272
2245
    for s in interval.split():
2273
2246
        try:
2274
 
            suffix = s[-1]
 
2247
            suffix = unicode(s[-1])
2275
2248
            value = int(s[:-1])
2276
2249
            if suffix == "d":
2277
2250
                delta = datetime.timedelta(value)
2284
2257
            elif suffix == "w":
2285
2258
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2286
2259
            else:
2287
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2260
                raise ValueError("Unknown suffix {0!r}"
 
2261
                                 .format(suffix))
2288
2262
        except IndexError as e:
2289
2263
            raise ValueError(*(e.args))
2290
2264
        timevalue += delta
2307
2281
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2308
2282
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2309
2283
            raise OSError(errno.ENODEV,
2310
 
                          "{} not a character device"
 
2284
                          "{0} not a character device"
2311
2285
                          .format(os.devnull))
2312
2286
        os.dup2(null, sys.stdin.fileno())
2313
2287
        os.dup2(null, sys.stdout.fileno())
2323
2297
    
2324
2298
    parser = argparse.ArgumentParser()
2325
2299
    parser.add_argument("-v", "--version", action="version",
2326
 
                        version = "%(prog)s {}".format(version),
 
2300
                        version = "%(prog)s {0}".format(version),
2327
2301
                        help="show version number and exit")
2328
2302
    parser.add_argument("-i", "--interface", metavar="IF",
2329
2303
                        help="Bind to interface IF")
2362
2336
                        help="Directory to save/restore state in")
2363
2337
    parser.add_argument("--foreground", action="store_true",
2364
2338
                        help="Run in foreground", default=None)
2365
 
    parser.add_argument("--no-zeroconf", action="store_false",
2366
 
                        dest="zeroconf", help="Do not use Zeroconf",
2367
 
                        default=None)
2368
2339
    
2369
2340
    options = parser.parse_args()
2370
2341
    
2371
2342
    if options.check:
2372
2343
        import doctest
2373
 
        fail_count, test_count = doctest.testmod()
2374
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2344
        doctest.testmod()
 
2345
        sys.exit()
2375
2346
    
2376
2347
    # Default values for config file for server-global settings
2377
2348
    server_defaults = { "interface": "",
2379
2350
                        "port": "",
2380
2351
                        "debug": "False",
2381
2352
                        "priority":
2382
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2383
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2353
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2384
2354
                        "servicename": "Mandos",
2385
2355
                        "use_dbus": "True",
2386
2356
                        "use_ipv6": "True",
2389
2359
                        "socket": "",
2390
2360
                        "statedir": "/var/lib/mandos",
2391
2361
                        "foreground": "False",
2392
 
                        "zeroconf": "True",
2393
 
                    }
 
2362
                        }
2394
2363
    
2395
2364
    # Parse config file for server-global settings
2396
2365
    server_config = configparser.SafeConfigParser(server_defaults)
2397
2366
    del server_defaults
2398
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2367
    server_config.read(os.path.join(options.configdir,
 
2368
                                    "mandos.conf"))
2399
2369
    # Convert the SafeConfigParser object to a dict
2400
2370
    server_settings = server_config.defaults()
2401
2371
    # Use the appropriate methods on the non-string config options
2419
2389
    # Override the settings from the config file with command line
2420
2390
    # options, if set.
2421
2391
    for option in ("interface", "address", "port", "debug",
2422
 
                   "priority", "servicename", "configdir", "use_dbus",
2423
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2424
 
                   "socket", "foreground", "zeroconf"):
 
2392
                   "priority", "servicename", "configdir",
 
2393
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2394
                   "statedir", "socket", "foreground"):
2425
2395
        value = getattr(options, option)
2426
2396
        if value is not None:
2427
2397
            server_settings[option] = value
2428
2398
    del options
2429
2399
    # Force all strings to be unicode
2430
2400
    for option in server_settings.keys():
2431
 
        if isinstance(server_settings[option], bytes):
2432
 
            server_settings[option] = (server_settings[option]
2433
 
                                       .decode("utf-8"))
 
2401
        if type(server_settings[option]) is str:
 
2402
            server_settings[option] = unicode(server_settings[option])
2434
2403
    # Force all boolean options to be boolean
2435
2404
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2436
 
                   "foreground", "zeroconf"):
 
2405
                   "foreground"):
2437
2406
        server_settings[option] = bool(server_settings[option])
2438
2407
    # Debug implies foreground
2439
2408
    if server_settings["debug"]:
2442
2411
    
2443
2412
    ##################################################################
2444
2413
    
2445
 
    if (not server_settings["zeroconf"]
2446
 
        and not (server_settings["port"]
2447
 
                 or server_settings["socket"] != "")):
2448
 
        parser.error("Needs port or socket to work without Zeroconf")
2449
 
    
2450
2414
    # For convenience
2451
2415
    debug = server_settings["debug"]
2452
2416
    debuglevel = server_settings["debuglevel"]
2455
2419
    stored_state_path = os.path.join(server_settings["statedir"],
2456
2420
                                     stored_state_file)
2457
2421
    foreground = server_settings["foreground"]
2458
 
    zeroconf = server_settings["zeroconf"]
2459
2422
    
2460
2423
    if debug:
2461
2424
        initlogger(debug, logging.DEBUG)
2467
2430
            initlogger(debug, level)
2468
2431
    
2469
2432
    if server_settings["servicename"] != "Mandos":
2470
 
        syslogger.setFormatter(
2471
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2472
 
                              ' %(levelname)s: %(message)s'.format(
2473
 
                                  server_settings["servicename"])))
 
2433
        syslogger.setFormatter(logging.Formatter
 
2434
                               ('Mandos ({0}) [%(process)d]:'
 
2435
                                ' %(levelname)s: %(message)s'
 
2436
                                .format(server_settings
 
2437
                                        ["servicename"])))
2474
2438
    
2475
2439
    # Parse config file with clients
2476
2440
    client_config = configparser.SafeConfigParser(Client
2481
2445
    global mandos_dbus_service
2482
2446
    mandos_dbus_service = None
2483
2447
    
2484
 
    socketfd = None
2485
 
    if server_settings["socket"] != "":
2486
 
        socketfd = server_settings["socket"]
2487
 
    tcp_server = MandosServer(
2488
 
        (server_settings["address"], server_settings["port"]),
2489
 
        ClientHandler,
2490
 
        interface=(server_settings["interface"] or None),
2491
 
        use_ipv6=use_ipv6,
2492
 
        gnutls_priority=server_settings["priority"],
2493
 
        use_dbus=use_dbus,
2494
 
        socketfd=socketfd)
 
2448
    tcp_server = MandosServer((server_settings["address"],
 
2449
                               server_settings["port"]),
 
2450
                              ClientHandler,
 
2451
                              interface=(server_settings["interface"]
 
2452
                                         or None),
 
2453
                              use_ipv6=use_ipv6,
 
2454
                              gnutls_priority=
 
2455
                              server_settings["priority"],
 
2456
                              use_dbus=use_dbus,
 
2457
                              socketfd=(server_settings["socket"]
 
2458
                                        or None))
2495
2459
    if not foreground:
2496
2460
        pidfilename = "/run/mandos.pid"
2497
2461
        if not os.path.isdir("/run/."):
2531
2495
        def debug_gnutls(level, string):
2532
2496
            logger.debug("GnuTLS: %s", string[:-1])
2533
2497
        
2534
 
        gnutls.library.functions.gnutls_global_set_log_function(
2535
 
            debug_gnutls)
 
2498
        (gnutls.library.functions
 
2499
         .gnutls_global_set_log_function(debug_gnutls))
2536
2500
        
2537
2501
        # Redirect stdin so all checkers get /dev/null
2538
2502
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2558
2522
    if use_dbus:
2559
2523
        try:
2560
2524
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2561
 
                                            bus,
2562
 
                                            do_not_queue=True)
2563
 
            old_bus_name = dbus.service.BusName(
2564
 
                "se.bsnet.fukt.Mandos", bus,
2565
 
                do_not_queue=True)
 
2525
                                            bus, do_not_queue=True)
 
2526
            old_bus_name = (dbus.service.BusName
 
2527
                            ("se.bsnet.fukt.Mandos", bus,
 
2528
                             do_not_queue=True))
2566
2529
        except dbus.exceptions.NameExistsException as e:
2567
2530
            logger.error("Disabling D-Bus:", exc_info=e)
2568
2531
            use_dbus = False
2569
2532
            server_settings["use_dbus"] = False
2570
2533
            tcp_server.use_dbus = False
2571
 
    if zeroconf:
2572
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2573
 
        service = AvahiServiceToSyslog(
2574
 
            name = server_settings["servicename"],
2575
 
            servicetype = "_mandos._tcp",
2576
 
            protocol = protocol,
2577
 
            bus = bus)
2578
 
        if server_settings["interface"]:
2579
 
            service.interface = if_nametoindex(
2580
 
                server_settings["interface"].encode("utf-8"))
 
2534
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2535
    service = AvahiServiceToSyslog(name =
 
2536
                                   server_settings["servicename"],
 
2537
                                   servicetype = "_mandos._tcp",
 
2538
                                   protocol = protocol, bus = bus)
 
2539
    if server_settings["interface"]:
 
2540
        service.interface = (if_nametoindex
 
2541
                             (str(server_settings["interface"])))
2581
2542
    
2582
2543
    global multiprocessing_manager
2583
2544
    multiprocessing_manager = multiprocessing.Manager()
2602
2563
    if server_settings["restore"]:
2603
2564
        try:
2604
2565
            with open(stored_state_path, "rb") as stored_state:
2605
 
                clients_data, old_client_settings = pickle.load(
2606
 
                    stored_state)
 
2566
                clients_data, old_client_settings = (pickle.load
 
2567
                                                     (stored_state))
2607
2568
            os.remove(stored_state_path)
2608
2569
        except IOError as e:
2609
2570
            if e.errno == errno.ENOENT:
2610
 
                logger.warning("Could not load persistent state:"
2611
 
                               " {}".format(os.strerror(e.errno)))
 
2571
                logger.warning("Could not load persistent state: {0}"
 
2572
                                .format(os.strerror(e.errno)))
2612
2573
            else:
2613
2574
                logger.critical("Could not load persistent state:",
2614
2575
                                exc_info=e)
2615
2576
                raise
2616
2577
        except EOFError as e:
2617
2578
            logger.warning("Could not load persistent state: "
2618
 
                           "EOFError:",
2619
 
                           exc_info=e)
 
2579
                           "EOFError:", exc_info=e)
2620
2580
    
2621
2581
    with PGPEngine() as pgp:
2622
 
        for client_name, client in clients_data.items():
 
2582
        for client_name, client in clients_data.iteritems():
2623
2583
            # Skip removed clients
2624
2584
            if client_name not in client_settings:
2625
2585
                continue
2634
2594
                    # For each value in new config, check if it
2635
2595
                    # differs from the old config value (Except for
2636
2596
                    # the "secret" attribute)
2637
 
                    if (name != "secret"
2638
 
                        and (value !=
2639
 
                             old_client_settings[client_name][name])):
 
2597
                    if (name != "secret" and
 
2598
                        value != old_client_settings[client_name]
 
2599
                        [name]):
2640
2600
                        client[name] = value
2641
2601
                except KeyError:
2642
2602
                    pass
2643
2603
            
2644
2604
            # Clients who has passed its expire date can still be
2645
 
            # enabled if its last checker was successful.  A Client
 
2605
            # enabled if its last checker was successful.  Clients
2646
2606
            # whose checker succeeded before we stored its state is
2647
2607
            # assumed to have successfully run all checkers during
2648
2608
            # downtime.
2650
2610
                if datetime.datetime.utcnow() >= client["expires"]:
2651
2611
                    if not client["last_checked_ok"]:
2652
2612
                        logger.warning(
2653
 
                            "disabling client {} - Client never "
2654
 
                            "performed a successful checker".format(
2655
 
                                client_name))
 
2613
                            "disabling client {0} - Client never "
 
2614
                            "performed a successful checker"
 
2615
                            .format(client_name))
2656
2616
                        client["enabled"] = False
2657
2617
                    elif client["last_checker_status"] != 0:
2658
2618
                        logger.warning(
2659
 
                            "disabling client {} - Client last"
2660
 
                            " checker failed with error code"
2661
 
                            " {}".format(
2662
 
                                client_name,
2663
 
                                client["last_checker_status"]))
 
2619
                            "disabling client {0} - Client "
 
2620
                            "last checker failed with error code {1}"
 
2621
                            .format(client_name,
 
2622
                                    client["last_checker_status"]))
2664
2623
                        client["enabled"] = False
2665
2624
                    else:
2666
 
                        client["expires"] = (
2667
 
                            datetime.datetime.utcnow()
2668
 
                            + client["timeout"])
 
2625
                        client["expires"] = (datetime.datetime
 
2626
                                             .utcnow()
 
2627
                                             + client["timeout"])
2669
2628
                        logger.debug("Last checker succeeded,"
2670
 
                                     " keeping {} enabled".format(
2671
 
                                         client_name))
 
2629
                                     " keeping {0} enabled"
 
2630
                                     .format(client_name))
2672
2631
            try:
2673
 
                client["secret"] = pgp.decrypt(
2674
 
                    client["encrypted_secret"],
2675
 
                    client_settings[client_name]["secret"])
 
2632
                client["secret"] = (
 
2633
                    pgp.decrypt(client["encrypted_secret"],
 
2634
                                client_settings[client_name]
 
2635
                                ["secret"]))
2676
2636
            except PGPError:
2677
2637
                # If decryption fails, we use secret from new settings
2678
 
                logger.debug("Failed to decrypt {} old secret".format(
2679
 
                    client_name))
2680
 
                client["secret"] = (client_settings[client_name]
2681
 
                                    ["secret"])
 
2638
                logger.debug("Failed to decrypt {0} old secret"
 
2639
                             .format(client_name))
 
2640
                client["secret"] = (
 
2641
                    client_settings[client_name]["secret"])
2682
2642
    
2683
2643
    # Add/remove clients based on new changes made to config
2684
2644
    for client_name in (set(old_client_settings)
2689
2649
        clients_data[client_name] = client_settings[client_name]
2690
2650
    
2691
2651
    # Create all client objects
2692
 
    for client_name, client in clients_data.items():
 
2652
    for client_name, client in clients_data.iteritems():
2693
2653
        tcp_server.clients[client_name] = client_class(
2694
 
            name = client_name,
2695
 
            settings = client,
 
2654
            name = client_name, settings = client,
2696
2655
            server_settings = server_settings)
2697
2656
    
2698
2657
    if not tcp_server.clients:
2703
2662
            try:
2704
2663
                with pidfile:
2705
2664
                    pid = os.getpid()
2706
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2665
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
2707
2666
            except IOError:
2708
2667
                logger.error("Could not write to file %r with PID %d",
2709
2668
                             pidfilename, pid)
2714
2673
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2715
2674
    
2716
2675
    if use_dbus:
2717
 
        
2718
 
        @alternate_dbus_interfaces(
2719
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2676
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2677
                                        "se.bsnet.fukt.Mandos"})
2720
2678
        class MandosDBusService(DBusObjectWithProperties):
2721
2679
            """A D-Bus proxy object"""
2722
 
            
2723
2680
            def __init__(self):
2724
2681
                dbus.service.Object.__init__(self, bus, "/")
2725
 
            
2726
2682
            _interface = "se.recompile.Mandos"
2727
2683
            
2728
2684
            @dbus_interface_annotations(_interface)
2729
2685
            def _foo(self):
2730
 
                return {
2731
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2732
 
                    "false" }
 
2686
                return { "org.freedesktop.DBus.Property"
 
2687
                         ".EmitsChangedSignal":
 
2688
                             "false"}
2733
2689
            
2734
2690
            @dbus.service.signal(_interface, signature="o")
2735
2691
            def ClientAdded(self, objpath):
2749
2705
            @dbus.service.method(_interface, out_signature="ao")
2750
2706
            def GetAllClients(self):
2751
2707
                "D-Bus method"
2752
 
                return dbus.Array(c.dbus_object_path for c in
 
2708
                return dbus.Array(c.dbus_object_path
 
2709
                                  for c in
2753
2710
                                  tcp_server.clients.itervalues())
2754
2711
            
2755
2712
            @dbus.service.method(_interface,
2757
2714
            def GetAllClientsWithProperties(self):
2758
2715
                "D-Bus method"
2759
2716
                return dbus.Dictionary(
2760
 
                    { c.dbus_object_path: c.GetAll("")
2761
 
                      for c in tcp_server.clients.itervalues() },
 
2717
                    ((c.dbus_object_path, c.GetAll(""))
 
2718
                     for c in tcp_server.clients.itervalues()),
2762
2719
                    signature="oa{sv}")
2763
2720
            
2764
2721
            @dbus.service.method(_interface, in_signature="o")
2781
2738
    
2782
2739
    def cleanup():
2783
2740
        "Cleanup function; run on exit"
2784
 
        if zeroconf:
2785
 
            service.cleanup()
 
2741
        service.cleanup()
2786
2742
        
2787
2743
        multiprocessing.active_children()
2788
2744
        wnull.close()
2802
2758
                
2803
2759
                # A list of attributes that can not be pickled
2804
2760
                # + secret.
2805
 
                exclude = { "bus", "changedstate", "secret",
2806
 
                            "checker", "server_settings" }
2807
 
                for name, typ in inspect.getmembers(dbus.service
2808
 
                                                    .Object):
 
2761
                exclude = set(("bus", "changedstate", "secret",
 
2762
                               "checker", "server_settings"))
 
2763
                for name, typ in (inspect.getmembers
 
2764
                                  (dbus.service.Object)):
2809
2765
                    exclude.add(name)
2810
2766
                
2811
2767
                client_dict["encrypted_secret"] = (client
2818
2774
                del client_settings[client.name]["secret"]
2819
2775
        
2820
2776
        try:
2821
 
            with tempfile.NamedTemporaryFile(
2822
 
                    mode='wb',
2823
 
                    suffix=".pickle",
2824
 
                    prefix='clients-',
2825
 
                    dir=os.path.dirname(stored_state_path),
2826
 
                    delete=False) as stored_state:
 
2777
            with (tempfile.NamedTemporaryFile
 
2778
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2779
                   dir=os.path.dirname(stored_state_path),
 
2780
                   delete=False)) as stored_state:
2827
2781
                pickle.dump((clients, client_settings), stored_state)
2828
 
                tempname = stored_state.name
 
2782
                tempname=stored_state.name
2829
2783
            os.rename(tempname, stored_state_path)
2830
2784
        except (IOError, OSError) as e:
2831
2785
            if not debug:
2834
2788
                except NameError:
2835
2789
                    pass
2836
2790
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2837
 
                logger.warning("Could not save persistent state: {}"
 
2791
                logger.warning("Could not save persistent state: {0}"
2838
2792
                               .format(os.strerror(e.errno)))
2839
2793
            else:
2840
2794
                logger.warning("Could not save persistent state:",
2850
2804
            client.disable(quiet=True)
2851
2805
            if use_dbus:
2852
2806
                # Emit D-Bus signal
2853
 
                mandos_dbus_service.ClientRemoved(
2854
 
                    client.dbus_object_path, client.name)
 
2807
                mandos_dbus_service.ClientRemoved(client
 
2808
                                                  .dbus_object_path,
 
2809
                                                  client.name)
2855
2810
        client_settings.clear()
2856
2811
    
2857
2812
    atexit.register(cleanup)
2868
2823
    tcp_server.server_activate()
2869
2824
    
2870
2825
    # Find out what port we got
2871
 
    if zeroconf:
2872
 
        service.port = tcp_server.socket.getsockname()[1]
 
2826
    service.port = tcp_server.socket.getsockname()[1]
2873
2827
    if use_ipv6:
2874
2828
        logger.info("Now listening on address %r, port %d,"
2875
2829
                    " flowinfo %d, scope_id %d",
2881
2835
    #service.interface = tcp_server.socket.getsockname()[3]
2882
2836
    
2883
2837
    try:
2884
 
        if zeroconf:
2885
 
            # From the Avahi example code
2886
 
            try:
2887
 
                service.activate()
2888
 
            except dbus.exceptions.DBusException as error:
2889
 
                logger.critical("D-Bus Exception", exc_info=error)
2890
 
                cleanup()
2891
 
                sys.exit(1)
2892
 
            # End of Avahi example code
 
2838
        # From the Avahi example code
 
2839
        try:
 
2840
            service.activate()
 
2841
        except dbus.exceptions.DBusException as error:
 
2842
            logger.critical("D-Bus Exception", exc_info=error)
 
2843
            cleanup()
 
2844
            sys.exit(1)
 
2845
        # End of Avahi example code
2893
2846
        
2894
2847
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2895
2848
                             lambda *args, **kwargs:
2910
2863
    # Must run before the D-Bus bus name gets deregistered
2911
2864
    cleanup()
2912
2865
 
2913
 
 
2914
2866
if __name__ == '__main__':
2915
2867
    main()