88
81
    except ImportError:
 
89
82
        SO_BINDTODEVICE = None
 
92
 
stored_state_file = "clients.pickle"
 
94
 
logger = logging.getLogger()
 
 
87
#logger = logging.getLogger('mandos')
 
 
88
logger = logging.Logger('mandos')
 
95
89
syslogger = (logging.handlers.SysLogHandler
 
96
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
91
              address = str("/dev/log")))
 
100
 
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
101
 
                      (ctypes.util.find_library("c"))
 
103
 
except (OSError, AttributeError):
 
104
 
    def if_nametoindex(interface):
 
105
 
        "Get an interface index the hard way, i.e. using fcntl()"
 
106
 
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
 
107
 
        with contextlib.closing(socket.socket()) as s:
 
108
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
109
 
                                struct.pack(str("16s16x"),
 
111
 
        interface_index = struct.unpack(str("I"),
 
113
 
        return interface_index
 
116
 
def initlogger(debug, level=logging.WARNING):
 
117
 
    """init logger and add loglevel"""
 
119
 
    syslogger.setFormatter(logging.Formatter
 
120
 
                           ('Mandos [%(process)d]: %(levelname)s:'
 
122
 
    logger.addHandler(syslogger)
 
125
 
        console = logging.StreamHandler()
 
126
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
 
130
 
        logger.addHandler(console)
 
131
 
    logger.setLevel(level)
 
134
 
class PGPError(Exception):
 
135
 
    """Exception if encryption/decryption fails"""
 
139
 
class PGPEngine(object):
 
140
 
    """A simple class for OpenPGP symmetric encryption & decryption"""
 
142
 
        self.gnupg = GnuPGInterface.GnuPG()
 
143
 
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
 
144
 
        self.gnupg = GnuPGInterface.GnuPG()
 
145
 
        self.gnupg.options.meta_interactive = False
 
146
 
        self.gnupg.options.homedir = self.tempdir
 
147
 
        self.gnupg.options.extra_args.extend(['--force-mdc',
 
154
 
    def __exit__(self, exc_type, exc_value, traceback):
 
162
 
        if self.tempdir is not None:
 
163
 
            # Delete contents of tempdir
 
164
 
            for root, dirs, files in os.walk(self.tempdir,
 
166
 
                for filename in files:
 
167
 
                    os.remove(os.path.join(root, filename))
 
169
 
                    os.rmdir(os.path.join(root, dirname))
 
171
 
            os.rmdir(self.tempdir)
 
174
 
    def password_encode(self, password):
 
175
 
        # Passphrase can not be empty and can not contain newlines or
 
176
 
        # NUL bytes.  So we prefix it and hex encode it.
 
177
 
        return b"mandos" + binascii.hexlify(password)
 
179
 
    def encrypt(self, data, password):
 
180
 
        self.gnupg.passphrase = self.password_encode(password)
 
181
 
        with open(os.devnull, "w") as devnull:
 
183
 
                proc = self.gnupg.run(['--symmetric'],
 
184
 
                                      create_fhs=['stdin', 'stdout'],
 
185
 
                                      attach_fhs={'stderr': devnull})
 
186
 
                with contextlib.closing(proc.handles['stdin']) as f:
 
188
 
                with contextlib.closing(proc.handles['stdout']) as f:
 
189
 
                    ciphertext = f.read()
 
193
 
        self.gnupg.passphrase = None
 
196
 
    def decrypt(self, data, password):
 
197
 
        self.gnupg.passphrase = self.password_encode(password)
 
198
 
        with open(os.devnull, "w") as devnull:
 
200
 
                proc = self.gnupg.run(['--decrypt'],
 
201
 
                                      create_fhs=['stdin', 'stdout'],
 
202
 
                                      attach_fhs={'stderr': devnull})
 
203
 
                with contextlib.closing(proc.handles['stdin']) as f:
 
205
 
                with contextlib.closing(proc.handles['stdout']) as f:
 
206
 
                    decrypted_plaintext = f.read()
 
210
 
        self.gnupg.passphrase = None
 
211
 
        return decrypted_plaintext
 
 
92
syslogger.setFormatter(logging.Formatter
 
 
93
                       ('Mandos [%(process)d]: %(levelname)s:'
 
 
95
logger.addHandler(syslogger)
 
 
97
console = logging.StreamHandler()
 
 
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
 
101
logger.addHandler(console)
 
214
103
class AvahiError(Exception):
 
215
104
    def __init__(self, value, *args, **kwargs):
 
 
328
210
        elif state == avahi.ENTRY_GROUP_FAILURE:
 
329
211
            logger.critical("Avahi: Error in group state changed %s",
 
331
 
            raise AvahiGroupError("State changed: {0!s}"
 
 
213
            raise AvahiGroupError("State changed: %s"
 
334
215
    def cleanup(self):
 
335
216
        """Derived from the Avahi example code"""
 
336
217
        if self.group is not None:
 
339
 
            except (dbus.exceptions.UnknownMethodException,
 
340
 
                    dbus.exceptions.DBusException):
 
342
219
            self.group = None
 
345
 
    def server_state_changed(self, state, error=None):
 
 
220
    def server_state_changed(self, state):
 
346
221
        """Derived from the Avahi example code"""
 
347
222
        logger.debug("Avahi server state change: %i", state)
 
348
 
        bad_states = { avahi.SERVER_INVALID:
 
349
 
                           "Zeroconf server invalid",
 
350
 
                       avahi.SERVER_REGISTERING: None,
 
351
 
                       avahi.SERVER_COLLISION:
 
352
 
                           "Zeroconf server name collision",
 
353
 
                       avahi.SERVER_FAILURE:
 
354
 
                           "Zeroconf server failure" }
 
355
 
        if state in bad_states:
 
356
 
            if bad_states[state] is not None:
 
358
 
                    logger.error(bad_states[state])
 
360
 
                    logger.error(bad_states[state] + ": %r", error)
 
 
223
        if state == avahi.SERVER_COLLISION:
 
 
224
            logger.error("Zeroconf server name collision")
 
362
226
        elif state == avahi.SERVER_RUNNING:
 
366
 
                logger.debug("Unknown state: %r", state)
 
368
 
                logger.debug("Unknown state: %r: %r", state, error)
 
370
228
    def activate(self):
 
371
229
        """Derived from the Avahi example code"""
 
372
230
        if self.server is None:
 
373
231
            self.server = dbus.Interface(
 
374
232
                self.bus.get_object(avahi.DBUS_NAME,
 
375
 
                                    avahi.DBUS_PATH_SERVER,
 
376
 
                                    follow_name_owner_changes=True),
 
 
233
                                    avahi.DBUS_PATH_SERVER),
 
377
234
                avahi.DBUS_INTERFACE_SERVER)
 
378
235
        self.server.connect_to_signal("StateChanged",
 
379
236
                                 self.server_state_changed)
 
380
237
        self.server_state_changed(self.server.GetState())
 
383
 
class AvahiServiceToSyslog(AvahiService):
 
385
 
        """Add the new name to the syslog messages"""
 
386
 
        ret = AvahiService.rename(self)
 
387
 
        syslogger.setFormatter(logging.Formatter
 
388
 
                               ('Mandos ({0}) [%(process)d]:'
 
389
 
                                ' %(levelname)s: %(message)s'
 
394
 
def timedelta_to_milliseconds(td):
 
395
 
    "Convert a datetime.timedelta() to milliseconds"
 
396
 
    return ((td.days * 24 * 60 * 60 * 1000)
 
397
 
            + (td.seconds * 1000)
 
398
 
            + (td.microseconds // 1000))
 
401
240
class Client(object):
 
402
241
    """A representation of a client host served by this server.
 
405
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
 
244
    _approved:   bool(); 'None' if not yet approved/disapproved
 
406
245
    approval_delay: datetime.timedelta(); Time to wait for approval
 
407
246
    approval_duration: datetime.timedelta(); Duration of one approval
 
408
247
    checker:    subprocess.Popen(); a running checker process used
 
 
426
264
    interval:   datetime.timedelta(); How often to start a new checker
 
427
265
    last_approval_request: datetime.datetime(); (UTC) or None
 
428
266
    last_checked_ok: datetime.datetime(); (UTC) or None
 
429
 
    last_checker_status: integer between 0 and 255 reflecting exit
 
430
 
                         status of last checker. -1 reflects crashed
 
431
 
                         checker, -2 means no checker completed yet.
 
432
 
    last_enabled: datetime.datetime(); (UTC) or None
 
 
267
    last_enabled: datetime.datetime(); (UTC)
 
433
268
    name:       string; from the config file, used in log messages and
 
434
269
                        D-Bus identifiers
 
435
270
    secret:     bytestring; sent verbatim (over TLS) to client
 
436
271
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
437
272
                                      until this client is disabled
 
438
 
    extended_timeout:   extra long timeout when secret has been sent
 
439
273
    runtime_expansions: Allowed attributes for runtime expansion.
 
440
 
    expires:    datetime.datetime(); time (UTC) when a client will be
 
444
276
    runtime_expansions = ("approval_delay", "approval_duration",
 
445
 
                          "created", "enabled", "expires",
 
446
 
                          "fingerprint", "host", "interval",
 
447
 
                          "last_approval_request", "last_checked_ok",
 
 
277
                          "created", "enabled", "fingerprint",
 
 
278
                          "host", "interval", "last_checked_ok",
 
448
279
                          "last_enabled", "name", "timeout")
 
449
 
    client_defaults = { "timeout": "5m",
 
450
 
                        "extended_timeout": "15m",
 
452
 
                        "checker": "fping -q -- %%(host)s",
 
454
 
                        "approval_delay": "0s",
 
455
 
                        "approval_duration": "1s",
 
456
 
                        "approved_by_default": "True",
 
 
282
    def _timedelta_to_milliseconds(td):
 
 
283
        "Convert a datetime.timedelta() to milliseconds"
 
 
284
        return ((td.days * 24 * 60 * 60 * 1000)
 
 
285
                + (td.seconds * 1000)
 
 
286
                + (td.microseconds // 1000))
 
460
288
    def timeout_milliseconds(self):
 
461
289
        "Return the 'timeout' attribute in milliseconds"
 
462
 
        return timedelta_to_milliseconds(self.timeout)
 
464
 
    def extended_timeout_milliseconds(self):
 
465
 
        "Return the 'extended_timeout' attribute in milliseconds"
 
466
 
        return timedelta_to_milliseconds(self.extended_timeout)
 
 
290
        return self._timedelta_to_milliseconds(self.timeout)
 
468
292
    def interval_milliseconds(self):
 
469
293
        "Return the 'interval' attribute in milliseconds"
 
470
 
        return timedelta_to_milliseconds(self.interval)
 
 
294
        return self._timedelta_to_milliseconds(self.interval)
 
472
296
    def approval_delay_milliseconds(self):
 
473
 
        return timedelta_to_milliseconds(self.approval_delay)
 
476
 
    def config_parser(config):
 
477
 
        """Construct a new dict of client settings of this form:
 
478
 
        { client_name: {setting_name: value, ...}, ...}
 
479
 
        with exceptions for any special settings as defined above.
 
480
 
        NOTE: Must be a pure function. Must return the same result
 
481
 
        value given the same arguments.
 
484
 
        for client_name in config.sections():
 
485
 
            section = dict(config.items(client_name))
 
486
 
            client = settings[client_name] = {}
 
488
 
            client["host"] = section["host"]
 
489
 
            # Reformat values from string types to Python types
 
490
 
            client["approved_by_default"] = config.getboolean(
 
491
 
                client_name, "approved_by_default")
 
492
 
            client["enabled"] = config.getboolean(client_name,
 
495
 
            client["fingerprint"] = (section["fingerprint"].upper()
 
497
 
            if "secret" in section:
 
498
 
                client["secret"] = section["secret"].decode("base64")
 
499
 
            elif "secfile" in section:
 
500
 
                with open(os.path.expanduser(os.path.expandvars
 
501
 
                                             (section["secfile"])),
 
503
 
                    client["secret"] = secfile.read()
 
505
 
                raise TypeError("No secret or secfile for section {0}"
 
507
 
            client["timeout"] = string_to_delta(section["timeout"])
 
508
 
            client["extended_timeout"] = string_to_delta(
 
509
 
                section["extended_timeout"])
 
510
 
            client["interval"] = string_to_delta(section["interval"])
 
511
 
            client["approval_delay"] = string_to_delta(
 
512
 
                section["approval_delay"])
 
513
 
            client["approval_duration"] = string_to_delta(
 
514
 
                section["approval_duration"])
 
515
 
            client["checker_command"] = section["checker"]
 
516
 
            client["last_approval_request"] = None
 
517
 
            client["last_checked_ok"] = None
 
518
 
            client["last_checker_status"] = -2
 
522
 
    def __init__(self, settings, name = None):
 
 
297
        return self._timedelta_to_milliseconds(self.approval_delay)
 
 
299
    def __init__(self, name = None, disable_hook=None, config=None):
 
 
300
        """Note: the 'checker' key in 'config' sets the
 
 
301
        'checker_command' attribute and *not* the 'checker'
 
524
 
        # adding all client settings
 
525
 
        for setting, value in settings.iteritems():
 
526
 
            setattr(self, setting, value)
 
529
 
            if not hasattr(self, "last_enabled"):
 
530
 
                self.last_enabled = datetime.datetime.utcnow()
 
531
 
            if not hasattr(self, "expires"):
 
532
 
                self.expires = (datetime.datetime.utcnow()
 
535
 
            self.last_enabled = None
 
538
306
        logger.debug("Creating client %r", self.name)
 
539
307
        # Uppercase and remove spaces from fingerprint for later
 
540
308
        # comparison purposes with return value from the fingerprint()
 
 
310
        self.fingerprint = (config["fingerprint"].upper()
 
542
312
        logger.debug("  Fingerprint: %s", self.fingerprint)
 
543
 
        self.created = settings.get("created",
 
544
 
                                    datetime.datetime.utcnow())
 
546
 
        # attributes specific for this server instance
 
 
313
        if "secret" in config:
 
 
314
            self.secret = config["secret"].decode("base64")
 
 
315
        elif "secfile" in config:
 
 
316
            with open(os.path.expanduser(os.path.expandvars
 
 
317
                                         (config["secfile"])),
 
 
319
                self.secret = secfile.read()
 
 
321
            raise TypeError("No secret or secfile for client %s"
 
 
323
        self.host = config.get("host", "")
 
 
324
        self.created = datetime.datetime.utcnow()
 
 
326
        self.last_approval_request = None
 
 
327
        self.last_enabled = None
 
 
328
        self.last_checked_ok = None
 
 
329
        self.timeout = string_to_delta(config["timeout"])
 
 
330
        self.interval = string_to_delta(config["interval"])
 
 
331
        self.disable_hook = disable_hook
 
547
332
        self.checker = None
 
548
333
        self.checker_initiator_tag = None
 
549
334
        self.disable_initiator_tag = None
 
550
335
        self.checker_callback_tag = None
 
 
336
        self.checker_command = config["checker"]
 
551
337
        self.current_checker_command = None
 
 
338
        self.last_connect = None
 
 
339
        self._approved = None
 
 
340
        self.approved_by_default = config.get("approved_by_default",
 
553
342
        self.approvals_pending = 0
 
554
 
        self.changedstate = (multiprocessing_manager
 
555
 
                             .Condition(multiprocessing_manager
 
557
 
        self.client_structure = [attr for attr in
 
558
 
                                 self.__dict__.iterkeys()
 
559
 
                                 if not attr.startswith("_")]
 
560
 
        self.client_structure.append("client_structure")
 
562
 
        for name, t in inspect.getmembers(type(self),
 
566
 
            if not name.startswith("_"):
 
567
 
                self.client_structure.append(name)
 
 
343
        self.approval_delay = string_to_delta(
 
 
344
            config["approval_delay"])
 
 
345
        self.approval_duration = string_to_delta(
 
 
346
            config["approval_duration"])
 
 
347
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
 
569
 
    # Send notice to process children that client state has changed
 
570
349
    def send_changedstate(self):
 
571
 
        with self.changedstate:
 
572
 
            self.changedstate.notify_all()
 
 
350
        self.changedstate.acquire()
 
 
351
        self.changedstate.notify_all()
 
 
352
        self.changedstate.release()
 
574
354
    def enable(self):
 
575
355
        """Start this client's checker and timeout hooks"""
 
576
356
        if getattr(self, "enabled", False):
 
577
357
            # Already enabled
 
579
 
        self.expires = datetime.datetime.utcnow() + self.timeout
 
 
359
        self.send_changedstate()
 
581
360
        self.last_enabled = datetime.datetime.utcnow()
 
583
 
        self.send_changedstate()
 
585
 
    def disable(self, quiet=True):
 
586
 
        """Disable this client."""
 
587
 
        if not getattr(self, "enabled", False):
 
590
 
            logger.info("Disabling client %s", self.name)
 
591
 
        if getattr(self, "disable_initiator_tag", None) is not None:
 
592
 
            gobject.source_remove(self.disable_initiator_tag)
 
593
 
            self.disable_initiator_tag = None
 
595
 
        if getattr(self, "checker_initiator_tag", None) is not None:
 
596
 
            gobject.source_remove(self.checker_initiator_tag)
 
597
 
            self.checker_initiator_tag = None
 
601
 
            self.send_changedstate()
 
602
 
        # Do not run this again if called by a gobject.timeout_add
 
608
 
    def init_checker(self):
 
609
361
        # Schedule a new checker to be started an 'interval' from now,
 
610
362
        # and every interval from then on.
 
611
 
        if self.checker_initiator_tag is not None:
 
612
 
            gobject.source_remove(self.checker_initiator_tag)
 
613
363
        self.checker_initiator_tag = (gobject.timeout_add
 
614
364
                                      (self.interval_milliseconds(),
 
615
365
                                       self.start_checker))
 
616
366
        # Schedule a disable() when 'timeout' has passed
 
617
 
        if self.disable_initiator_tag is not None:
 
618
 
            gobject.source_remove(self.disable_initiator_tag)
 
619
367
        self.disable_initiator_tag = (gobject.timeout_add
 
620
368
                                   (self.timeout_milliseconds(),
 
622
371
        # Also start a new checker *right now*.
 
623
372
        self.start_checker()
 
 
374
    def disable(self, quiet=True):
 
 
375
        """Disable this client."""
 
 
376
        if not getattr(self, "enabled", False):
 
 
379
            self.send_changedstate()
 
 
381
            logger.info("Disabling client %s", self.name)
 
 
382
        if getattr(self, "disable_initiator_tag", False):
 
 
383
            gobject.source_remove(self.disable_initiator_tag)
 
 
384
            self.disable_initiator_tag = None
 
 
385
        if getattr(self, "checker_initiator_tag", False):
 
 
386
            gobject.source_remove(self.checker_initiator_tag)
 
 
387
            self.checker_initiator_tag = None
 
 
389
        if self.disable_hook:
 
 
390
            self.disable_hook(self)
 
 
392
        # Do not run this again if called by a gobject.timeout_add
 
 
396
        self.disable_hook = None
 
625
399
    def checker_callback(self, pid, condition, command):
 
626
400
        """The checker has completed, so take appropriate actions."""
 
627
401
        self.checker_callback_tag = None
 
628
402
        self.checker = None
 
629
403
        if os.WIFEXITED(condition):
 
630
 
            self.last_checker_status = os.WEXITSTATUS(condition)
 
631
 
            if self.last_checker_status == 0:
 
 
404
            exitstatus = os.WEXITSTATUS(condition)
 
632
406
                logger.info("Checker for %(name)s succeeded",
 
634
408
                self.checked_ok()
 
 
837
573
class DBusObjectWithProperties(dbus.service.Object):
 
838
574
    """A D-Bus object with properties.
 
840
576
    Classes inheriting from this can use the dbus_service_property
 
841
577
    decorator to expose methods as D-Bus properties.  It exposes the
 
842
578
    standard Get(), Set(), and GetAll() methods on the D-Bus.
 
846
 
    def _is_dbus_thing(thing):
 
847
 
        """Returns a function testing if an attribute is a D-Bus thing
 
849
 
        If called like _is_dbus_thing("method") it returns a function
 
850
 
        suitable for use as predicate to inspect.getmembers().
 
852
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
 
 
582
    def _is_dbus_property(obj):
 
 
583
        return getattr(obj, "_dbus_is_property", False)
 
855
 
    def _get_all_dbus_things(self, thing):
 
 
585
    def _get_all_dbus_properties(self):
 
856
586
        """Returns a generator of (name, attribute) pairs
 
858
 
        return ((getattr(athing.__get__(self), "_dbus_name",
 
860
 
                 athing.__get__(self))
 
861
 
                for cls in self.__class__.__mro__
 
863
 
                inspect.getmembers(cls,
 
864
 
                                   self._is_dbus_thing(thing)))
 
 
588
        return ((prop._dbus_name, prop)
 
 
590
                inspect.getmembers(self, self._is_dbus_property))
 
866
592
    def _get_dbus_property(self, interface_name, property_name):
 
867
593
        """Returns a bound method if one exists which is a D-Bus
 
868
594
        property with the specified name and interface.
 
870
 
        for cls in  self.__class__.__mro__:
 
871
 
            for name, value in (inspect.getmembers
 
873
 
                                 self._is_dbus_thing("property"))):
 
874
 
                if (value._dbus_name == property_name
 
875
 
                    and value._dbus_interface == interface_name):
 
876
 
                    return value.__get__(self)
 
 
596
        for name in (property_name,
 
 
597
                     property_name + "_dbus_property"):
 
 
598
            prop = getattr(self, name, None)
 
 
600
                or not self._is_dbus_property(prop)
 
 
601
                or prop._dbus_name != property_name
 
 
602
                or (interface_name and prop._dbus_interface
 
 
603
                    and interface_name != prop._dbus_interface)):
 
878
606
        # No such property
 
879
607
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
880
608
                                   + interface_name + "."
 
 
1010
704
            xmlstring = document.toxml("utf-8")
 
1011
705
            document.unlink()
 
1012
706
        except (AttributeError, xml.dom.DOMException,
 
1013
 
                xml.parsers.expat.ExpatError) as error:
 
 
707
                xml.parsers.expat.ExpatError), error:
 
1014
708
            logger.error("Failed to override Introspection method",
 
1016
710
        return xmlstring
 
1019
 
def datetime_to_dbus(dt, variant_level=0):
 
1020
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
1022
 
        return dbus.String("", variant_level = variant_level)
 
1023
 
    return dbus.String(dt.isoformat(),
 
1024
 
                       variant_level=variant_level)
 
1027
 
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
 
1028
 
    """A class decorator; applied to a subclass of
 
1029
 
    dbus.service.Object, it will add alternate D-Bus attributes with
 
1030
 
    interface names according to the "alt_interface_names" mapping.
 
1033
 
    @alternate_dbus_interfaces({"org.example.Interface":
 
1034
 
                                    "net.example.AlternateInterface"})
 
1035
 
    class SampleDBusObject(dbus.service.Object):
 
1036
 
        @dbus.service.method("org.example.Interface")
 
1037
 
        def SampleDBusMethod():
 
1040
 
    The above "SampleDBusMethod" on "SampleDBusObject" will be
 
1041
 
    reachable via two interfaces: "org.example.Interface" and
 
1042
 
    "net.example.AlternateInterface", the latter of which will have
 
1043
 
    its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
 
1044
 
    "true", unless "deprecate" is passed with a False value.
 
1046
 
    This works for methods and signals, and also for D-Bus properties
 
1047
 
    (from DBusObjectWithProperties) and interfaces (from the
 
1048
 
    dbus_interface_annotations decorator).
 
1051
 
        for orig_interface_name, alt_interface_name in (
 
1052
 
            alt_interface_names.iteritems()):
 
1054
 
            interface_names = set()
 
1055
 
            # Go though all attributes of the class
 
1056
 
            for attrname, attribute in inspect.getmembers(cls):
 
1057
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
 
1058
 
                # with the wrong interface name
 
1059
 
                if (not hasattr(attribute, "_dbus_interface")
 
1060
 
                    or not attribute._dbus_interface
 
1061
 
                    .startswith(orig_interface_name)):
 
1063
 
                # Create an alternate D-Bus interface name based on
 
1065
 
                alt_interface = (attribute._dbus_interface
 
1066
 
                                 .replace(orig_interface_name,
 
1067
 
                                          alt_interface_name))
 
1068
 
                interface_names.add(alt_interface)
 
1069
 
                # Is this a D-Bus signal?
 
1070
 
                if getattr(attribute, "_dbus_is_signal", False):
 
1071
 
                    # Extract the original non-method function by
 
1073
 
                    nonmethod_func = (dict(
 
1074
 
                            zip(attribute.func_code.co_freevars,
 
1075
 
                                attribute.__closure__))["func"]
 
1077
 
                    # Create a new, but exactly alike, function
 
1078
 
                    # object, and decorate it to be a new D-Bus signal
 
1079
 
                    # with the alternate D-Bus interface name
 
1080
 
                    new_function = (dbus.service.signal
 
1082
 
                                     attribute._dbus_signature)
 
1083
 
                                    (types.FunctionType(
 
1084
 
                                nonmethod_func.func_code,
 
1085
 
                                nonmethod_func.func_globals,
 
1086
 
                                nonmethod_func.func_name,
 
1087
 
                                nonmethod_func.func_defaults,
 
1088
 
                                nonmethod_func.func_closure)))
 
1089
 
                    # Copy annotations, if any
 
1091
 
                        new_function._dbus_annotations = (
 
1092
 
                            dict(attribute._dbus_annotations))
 
1093
 
                    except AttributeError:
 
1095
 
                    # Define a creator of a function to call both the
 
1096
 
                    # original and alternate functions, so both the
 
1097
 
                    # original and alternate signals gets sent when
 
1098
 
                    # the function is called
 
1099
 
                    def fixscope(func1, func2):
 
1100
 
                        """This function is a scope container to pass
 
1101
 
                        func1 and func2 to the "call_both" function
 
1102
 
                        outside of its arguments"""
 
1103
 
                        def call_both(*args, **kwargs):
 
1104
 
                            """This function will emit two D-Bus
 
1105
 
                            signals by calling func1 and func2"""
 
1106
 
                            func1(*args, **kwargs)
 
1107
 
                            func2(*args, **kwargs)
 
1109
 
                    # Create the "call_both" function and add it to
 
1111
 
                    attr[attrname] = fixscope(attribute, new_function)
 
1112
 
                # Is this a D-Bus method?
 
1113
 
                elif getattr(attribute, "_dbus_is_method", False):
 
1114
 
                    # Create a new, but exactly alike, function
 
1115
 
                    # object.  Decorate it to be a new D-Bus method
 
1116
 
                    # with the alternate D-Bus interface name.  Add it
 
1118
 
                    attr[attrname] = (dbus.service.method
 
1120
 
                                       attribute._dbus_in_signature,
 
1121
 
                                       attribute._dbus_out_signature)
 
1123
 
                                       (attribute.func_code,
 
1124
 
                                        attribute.func_globals,
 
1125
 
                                        attribute.func_name,
 
1126
 
                                        attribute.func_defaults,
 
1127
 
                                        attribute.func_closure)))
 
1128
 
                    # Copy annotations, if any
 
1130
 
                        attr[attrname]._dbus_annotations = (
 
1131
 
                            dict(attribute._dbus_annotations))
 
1132
 
                    except AttributeError:
 
1134
 
                # Is this a D-Bus property?
 
1135
 
                elif getattr(attribute, "_dbus_is_property", False):
 
1136
 
                    # Create a new, but exactly alike, function
 
1137
 
                    # object, and decorate it to be a new D-Bus
 
1138
 
                    # property with the alternate D-Bus interface
 
1139
 
                    # name.  Add it to the class.
 
1140
 
                    attr[attrname] = (dbus_service_property
 
1142
 
                                       attribute._dbus_signature,
 
1143
 
                                       attribute._dbus_access,
 
1145
 
                                       ._dbus_get_args_options
 
1148
 
                                       (attribute.func_code,
 
1149
 
                                        attribute.func_globals,
 
1150
 
                                        attribute.func_name,
 
1151
 
                                        attribute.func_defaults,
 
1152
 
                                        attribute.func_closure)))
 
1153
 
                    # Copy annotations, if any
 
1155
 
                        attr[attrname]._dbus_annotations = (
 
1156
 
                            dict(attribute._dbus_annotations))
 
1157
 
                    except AttributeError:
 
1159
 
                # Is this a D-Bus interface?
 
1160
 
                elif getattr(attribute, "_dbus_is_interface", False):
 
1161
 
                    # Create a new, but exactly alike, function
 
1162
 
                    # object.  Decorate it to be a new D-Bus interface
 
1163
 
                    # with the alternate D-Bus interface name.  Add it
 
1165
 
                    attr[attrname] = (dbus_interface_annotations
 
1168
 
                                       (attribute.func_code,
 
1169
 
                                        attribute.func_globals,
 
1170
 
                                        attribute.func_name,
 
1171
 
                                        attribute.func_defaults,
 
1172
 
                                        attribute.func_closure)))
 
1174
 
                # Deprecate all alternate interfaces
 
1175
 
                iname="_AlternateDBusNames_interface_annotation{0}"
 
1176
 
                for interface_name in interface_names:
 
1177
 
                    @dbus_interface_annotations(interface_name)
 
1179
 
                        return { "org.freedesktop.DBus.Deprecated":
 
1181
 
                    # Find an unused name
 
1182
 
                    for aname in (iname.format(i)
 
1183
 
                                  for i in itertools.count()):
 
1184
 
                        if aname not in attr:
 
1188
 
                # Replace the class with a new subclass of it with
 
1189
 
                # methods, signals, etc. as created above.
 
1190
 
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1196
 
@alternate_dbus_interfaces({"se.recompile.Mandos":
 
1197
 
                                "se.bsnet.fukt.Mandos"})
 
1198
713
class ClientDBus(Client, DBusObjectWithProperties):
 
1199
714
    """A Client class using D-Bus
 
 
1220
736
                                 ("/clients/" + client_object_name))
 
1221
737
        DBusObjectWithProperties.__init__(self, self.bus,
 
1222
738
                                          self.dbus_object_path)
 
1224
 
    def notifychangeproperty(transform_func,
 
1225
 
                             dbus_name, type_func=lambda x: x,
 
1227
 
        """ Modify a variable so that it's a property which announces
 
1228
 
        its changes to DBus.
 
1230
 
        transform_fun: Function that takes a value and a variant_level
 
1231
 
                       and transforms it to a D-Bus type.
 
1232
 
        dbus_name: D-Bus name of the variable
 
1233
 
        type_func: Function that transform the value before sending it
 
1234
 
                   to the D-Bus.  Default: no transform
 
1235
 
        variant_level: D-Bus variant level.  Default: 1
 
1237
 
        attrname = "_{0}".format(dbus_name)
 
1238
 
        def setter(self, value):
 
1239
 
            if hasattr(self, "dbus_object_path"):
 
1240
 
                if (not hasattr(self, attrname) or
 
1241
 
                    type_func(getattr(self, attrname, None))
 
1242
 
                    != type_func(value)):
 
1243
 
                    dbus_value = transform_func(type_func(value),
 
1246
 
                    self.PropertyChanged(dbus.String(dbus_name),
 
1248
 
            setattr(self, attrname, value)
 
1250
 
        return property(lambda self: getattr(self, attrname), setter)
 
1252
 
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
 
1253
 
    approvals_pending = notifychangeproperty(dbus.Boolean,
 
1256
 
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
 
1257
 
    last_enabled = notifychangeproperty(datetime_to_dbus,
 
1259
 
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1260
 
                                   type_func = lambda checker:
 
1261
 
                                       checker is not None)
 
1262
 
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
 
1264
 
    last_checker_status = notifychangeproperty(dbus.Int16,
 
1265
 
                                               "LastCheckerStatus")
 
1266
 
    last_approval_request = notifychangeproperty(
 
1267
 
        datetime_to_dbus, "LastApprovalRequest")
 
1268
 
    approved_by_default = notifychangeproperty(dbus.Boolean,
 
1269
 
                                               "ApprovedByDefault")
 
1270
 
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1273
 
                                          timedelta_to_milliseconds)
 
1274
 
    approval_duration = notifychangeproperty(
 
1275
 
        dbus.UInt64, "ApprovalDuration",
 
1276
 
        type_func = timedelta_to_milliseconds)
 
1277
 
    host = notifychangeproperty(dbus.String, "Host")
 
1278
 
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1280
 
                                   timedelta_to_milliseconds)
 
1281
 
    extended_timeout = notifychangeproperty(
 
1282
 
        dbus.UInt64, "ExtendedTimeout",
 
1283
 
        type_func = timedelta_to_milliseconds)
 
1284
 
    interval = notifychangeproperty(dbus.UInt64,
 
1287
 
                                    timedelta_to_milliseconds)
 
1288
 
    checker_command = notifychangeproperty(dbus.String, "Checker")
 
1290
 
    del notifychangeproperty
 
 
740
    def _get_approvals_pending(self):
 
 
741
        return self._approvals_pending
 
 
742
    def _set_approvals_pending(self, value):
 
 
743
        old_value = self._approvals_pending
 
 
744
        self._approvals_pending = value
 
 
746
        if (hasattr(self, "dbus_object_path")
 
 
747
            and bval is not bool(old_value)):
 
 
748
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
 
749
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
 
752
    approvals_pending = property(_get_approvals_pending,
 
 
753
                                 _set_approvals_pending)
 
 
754
    del _get_approvals_pending, _set_approvals_pending
 
 
757
    def _datetime_to_dbus(dt, variant_level=0):
 
 
758
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
 
759
        return dbus.String(dt.isoformat(),
 
 
760
                           variant_level=variant_level)
 
 
763
        oldstate = getattr(self, "enabled", False)
 
 
764
        r = Client.enable(self)
 
 
765
        if oldstate != self.enabled:
 
 
767
            self.PropertyChanged(dbus.String("Enabled"),
 
 
768
                                 dbus.Boolean(True, variant_level=1))
 
 
769
            self.PropertyChanged(
 
 
770
                dbus.String("LastEnabled"),
 
 
771
                self._datetime_to_dbus(self.last_enabled,
 
 
775
    def disable(self, quiet = False):
 
 
776
        oldstate = getattr(self, "enabled", False)
 
 
777
        r = Client.disable(self, quiet=quiet)
 
 
778
        if not quiet and oldstate != self.enabled:
 
 
780
            self.PropertyChanged(dbus.String("Enabled"),
 
 
781
                                 dbus.Boolean(False, variant_level=1))
 
1292
784
    def __del__(self, *args, **kwargs):
 
 
1996
1487
    def __init__(self, server_address, RequestHandlerClass,
 
1997
1488
                 interface=None, use_ipv6=True, clients=None,
 
1998
 
                 gnutls_priority=None, use_dbus=True, socketfd=None):
 
 
1489
                 gnutls_priority=None, use_dbus=True):
 
1999
1490
        self.enabled = False
 
2000
1491
        self.clients = clients
 
2001
1492
        if self.clients is None:
 
 
1493
            self.clients = set()
 
2003
1494
        self.use_dbus = use_dbus
 
2004
1495
        self.gnutls_priority = gnutls_priority
 
2005
1496
        IPv6_TCPServer.__init__(self, server_address,
 
2006
1497
                                RequestHandlerClass,
 
2007
1498
                                interface = interface,
 
2008
 
                                use_ipv6 = use_ipv6,
 
2009
 
                                socketfd = socketfd)
 
 
1499
                                use_ipv6 = use_ipv6)
 
2010
1500
    def server_activate(self):
 
2011
1501
        if self.enabled:
 
2012
1502
            return socketserver.TCPServer.server_activate(self)
 
2014
1503
    def enable(self):
 
2015
1504
        self.enabled = True
 
2017
 
    def add_pipe(self, parent_pipe, proc):
 
 
1505
    def add_pipe(self, parent_pipe):
 
2018
1506
        # Call "handle_ipc" for both data and EOF events
 
2019
1507
        gobject.io_add_watch(parent_pipe.fileno(),
 
2020
1508
                             gobject.IO_IN | gobject.IO_HUP,
 
2021
1509
                             functools.partial(self.handle_ipc,
 
 
1510
                                               parent_pipe = parent_pipe))
 
2026
1512
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2027
 
                   proc = None, client_object=None):
 
2028
 
        # error, or the other end of multiprocessing.Pipe has closed
 
2029
 
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
 
2030
 
            # Wait for other process to exit
 
 
1513
                   client_object=None):
 
 
1515
            gobject.IO_IN: "IN",   # There is data to read.
 
 
1516
            gobject.IO_OUT: "OUT", # Data can be written (without
 
 
1518
            gobject.IO_PRI: "PRI", # There is urgent data to read.
 
 
1519
            gobject.IO_ERR: "ERR", # Error condition.
 
 
1520
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
 
 
1521
                                    # broken, usually for pipes and
 
 
1524
        conditions_string = ' | '.join(name
 
 
1526
                                       condition_names.iteritems()
 
 
1527
                                       if cond & condition)
 
 
1528
        # error or the other end of multiprocessing.Pipe has closed
 
 
1529
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
 
2034
1532
        # Read a request from the child
 
 
2357
1843
         .gnutls_global_set_log_function(debug_gnutls))
 
2359
1845
        # Redirect stdin so all checkers get /dev/null
 
2360
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
 
1846
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
2361
1847
        os.dup2(null, sys.stdin.fileno())
 
 
1851
        # No console logging
 
 
1852
        logger.removeHandler(console)
 
2365
1854
    # Need to fork before connecting to D-Bus
 
2367
1856
        # Close all input and output, do double fork, etc.
 
2370
 
    # multiprocessing will use threads, so before we use gobject we
 
2371
 
    # need to inform gobject that threads will be used.
 
2372
 
    gobject.threads_init()
 
2374
1859
    global main_loop
 
2375
1860
    # From the Avahi example code
 
2376
 
    DBusGMainLoop(set_as_default=True)
 
 
1861
    DBusGMainLoop(set_as_default=True )
 
2377
1862
    main_loop = gobject.MainLoop()
 
2378
1863
    bus = dbus.SystemBus()
 
2379
1864
    # End of Avahi example code
 
2382
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
 
1867
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
 
2383
1868
                                            bus, do_not_queue=True)
 
2384
 
            old_bus_name = (dbus.service.BusName
 
2385
 
                            ("se.bsnet.fukt.Mandos", bus,
 
2387
 
        except dbus.exceptions.NameExistsException as e:
 
2388
 
            logger.error("Disabling D-Bus:", exc_info=e)
 
 
1869
        except dbus.exceptions.NameExistsException, e:
 
 
1870
            logger.error(unicode(e) + ", disabling D-Bus")
 
2389
1871
            use_dbus = False
 
2390
1872
            server_settings["use_dbus"] = False
 
2391
1873
            tcp_server.use_dbus = False
 
2392
1874
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2393
 
    service = AvahiServiceToSyslog(name =
 
2394
 
                                   server_settings["servicename"],
 
2395
 
                                   servicetype = "_mandos._tcp",
 
2396
 
                                   protocol = protocol, bus = bus)
 
 
1875
    service = AvahiService(name = server_settings["servicename"],
 
 
1876
                           servicetype = "_mandos._tcp",
 
 
1877
                           protocol = protocol, bus = bus)
 
2397
1878
    if server_settings["interface"]:
 
2398
1879
        service.interface = (if_nametoindex
 
2399
1880
                             (str(server_settings["interface"])))
 
 
2404
1885
    client_class = Client
 
2406
1887
        client_class = functools.partial(ClientDBus, bus = bus)
 
2408
 
    client_settings = Client.config_parser(client_config)
 
2409
 
    old_client_settings = {}
 
2412
 
    # Get client data and settings from last running state.
 
2413
 
    if server_settings["restore"]:
 
2415
 
            with open(stored_state_path, "rb") as stored_state:
 
2416
 
                clients_data, old_client_settings = (pickle.load
 
2418
 
            os.remove(stored_state_path)
 
2419
 
        except IOError as e:
 
2420
 
            if e.errno == errno.ENOENT:
 
2421
 
                logger.warning("Could not load persistent state: {0}"
 
2422
 
                                .format(os.strerror(e.errno)))
 
2424
 
                logger.critical("Could not load persistent state:",
 
2427
 
        except EOFError as e:
 
2428
 
            logger.warning("Could not load persistent state: "
 
2429
 
                           "EOFError:", exc_info=e)
 
2431
 
    with PGPEngine() as pgp:
 
2432
 
        for client_name, client in clients_data.iteritems():
 
2433
 
            # Decide which value to use after restoring saved state.
 
2434
 
            # We have three different values: Old config file,
 
2435
 
            # new config file, and saved state.
 
2436
 
            # New config value takes precedence if it differs from old
 
2437
 
            # config value, otherwise use saved state.
 
2438
 
            for name, value in client_settings[client_name].items():
 
2440
 
                    # For each value in new config, check if it
 
2441
 
                    # differs from the old config value (Except for
 
2442
 
                    # the "secret" attribute)
 
2443
 
                    if (name != "secret" and
 
2444
 
                        value != old_client_settings[client_name]
 
2446
 
                        client[name] = value
 
2450
 
            # Clients who has passed its expire date can still be
 
2451
 
            # enabled if its last checker was successful.  Clients
 
2452
 
            # whose checker succeeded before we stored its state is
 
2453
 
            # assumed to have successfully run all checkers during
 
2455
 
            if client["enabled"]:
 
2456
 
                if datetime.datetime.utcnow() >= client["expires"]:
 
2457
 
                    if not client["last_checked_ok"]:
 
2459
 
                            "disabling client {0} - Client never "
 
2460
 
                            "performed a successful checker"
 
2461
 
                            .format(client_name))
 
2462
 
                        client["enabled"] = False
 
2463
 
                    elif client["last_checker_status"] != 0:
 
2465
 
                            "disabling client {0} - Client "
 
2466
 
                            "last checker failed with error code {1}"
 
2467
 
                            .format(client_name,
 
2468
 
                                    client["last_checker_status"]))
 
2469
 
                        client["enabled"] = False
 
2471
 
                        client["expires"] = (datetime.datetime
 
2473
 
                                             + client["timeout"])
 
2474
 
                        logger.debug("Last checker succeeded,"
 
2475
 
                                     " keeping {0} enabled"
 
2476
 
                                     .format(client_name))
 
 
1888
    def client_config_items(config, section):
 
 
1889
        special_settings = {
 
 
1890
            "approved_by_default":
 
 
1891
                lambda: config.getboolean(section,
 
 
1892
                                          "approved_by_default"),
 
 
1894
        for name, value in config.items(section):
 
2478
 
                client["secret"] = (
 
2479
 
                    pgp.decrypt(client["encrypted_secret"],
 
2480
 
                                client_settings[client_name]
 
2483
 
                # If decryption fails, we use secret from new settings
 
2484
 
                logger.debug("Failed to decrypt {0} old secret"
 
2485
 
                             .format(client_name))
 
2486
 
                client["secret"] = (
 
2487
 
                    client_settings[client_name]["secret"])
 
2489
 
    # Add/remove clients based on new changes made to config
 
2490
 
    for client_name in (set(old_client_settings)
 
2491
 
                        - set(client_settings)):
 
2492
 
        del clients_data[client_name]
 
2493
 
    for client_name in (set(client_settings)
 
2494
 
                        - set(old_client_settings)):
 
2495
 
        clients_data[client_name] = client_settings[client_name]
 
2497
 
    # Create all client objects
 
2498
 
    for client_name, client in clients_data.iteritems():
 
2499
 
        tcp_server.clients[client_name] = client_class(
 
2500
 
            name = client_name, settings = client)
 
 
1896
                yield (name, special_settings[name]())
 
 
1900
    tcp_server.clients.update(set(
 
 
1901
            client_class(name = section,
 
 
1902
                         config= dict(client_config_items(
 
 
1903
                        client_config, section)))
 
 
1904
            for section in client_config.sections()))
 
2502
1905
    if not tcp_server.clients:
 
2503
1906
        logger.warning("No clients defined")
 
2506
 
        if pidfile is not None:
 
2510
 
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
 
2512
 
                logger.error("Could not write to file %r with PID %d",
 
 
1912
                pidfile.write(str(pid) + "\n".encode("utf-8"))
 
 
1915
            logger.error("Could not write to file %r with PID %d",
 
 
1918
            # "pidfile" was never created
 
2515
1920
        del pidfilename
 
 
1922
        signal.signal(signal.SIGINT, signal.SIG_IGN)
 
2517
1924
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
 
2518
1925
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
 
2521
 
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2522
 
                                        "se.bsnet.fukt.Mandos"})
 
2523
 
        class MandosDBusService(DBusObjectWithProperties):
 
 
1928
        class MandosDBusService(dbus.service.Object):
 
2524
1929
            """A D-Bus proxy object"""
 
2525
1930
            def __init__(self):
 
2526
1931
                dbus.service.Object.__init__(self, bus, "/")
 
2527
 
            _interface = "se.recompile.Mandos"
 
2529
 
            @dbus_interface_annotations(_interface)
 
2531
 
                return { "org.freedesktop.DBus.Property"
 
2532
 
                         ".EmitsChangedSignal":
 
 
1932
            _interface = "se.bsnet.fukt.Mandos"
 
2535
1934
            @dbus.service.signal(_interface, signature="o")
 
2536
1935
            def ClientAdded(self, objpath):
 
 
2585
1983
        "Cleanup function; run on exit"
 
2586
1984
        service.cleanup()
 
2588
 
        multiprocessing.active_children()
 
2589
 
        if not (tcp_server.clients or client_settings):
 
2592
 
        # Store client before exiting. Secrets are encrypted with key
 
2593
 
        # based on what config file has. If config file is
 
2594
 
        # removed/edited, old secret will thus be unrecovable.
 
2596
 
        with PGPEngine() as pgp:
 
2597
 
            for client in tcp_server.clients.itervalues():
 
2598
 
                key = client_settings[client.name]["secret"]
 
2599
 
                client.encrypted_secret = pgp.encrypt(client.secret,
 
2603
 
                # A list of attributes that can not be pickled
 
2605
 
                exclude = set(("bus", "changedstate", "secret",
 
2607
 
                for name, typ in (inspect.getmembers
 
2608
 
                                  (dbus.service.Object)):
 
2611
 
                client_dict["encrypted_secret"] = (client
 
2613
 
                for attr in client.client_structure:
 
2614
 
                    if attr not in exclude:
 
2615
 
                        client_dict[attr] = getattr(client, attr)
 
2617
 
                clients[client.name] = client_dict
 
2618
 
                del client_settings[client.name]["secret"]
 
2621
 
            with (tempfile.NamedTemporaryFile
 
2622
 
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2623
 
                   dir=os.path.dirname(stored_state_path),
 
2624
 
                   delete=False)) as stored_state:
 
2625
 
                pickle.dump((clients, client_settings), stored_state)
 
2626
 
                tempname=stored_state.name
 
2627
 
            os.rename(tempname, stored_state_path)
 
2628
 
        except (IOError, OSError) as e:
 
2634
 
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
 
2635
 
                logger.warning("Could not save persistent state: {0}"
 
2636
 
                               .format(os.strerror(e.errno)))
 
2638
 
                logger.warning("Could not save persistent state:",
 
2642
 
        # Delete all clients, and settings from config
 
2643
1986
        while tcp_server.clients:
 
2644
 
            name, client = tcp_server.clients.popitem()
 
 
1987
            client = tcp_server.clients.pop()
 
2646
1989
                client.remove_from_connection()
 
 
1990
            client.disable_hook = None
 
2647
1991
            # Don't signal anything except ClientRemoved
 
2648
1992
            client.disable(quiet=True)
 
2650
1994
                # Emit D-Bus signal
 
2651
 
                mandos_dbus_service.ClientRemoved(client
 
 
1995
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
 
2654
 
        client_settings.clear()
 
2656
1998
    atexit.register(cleanup)
 
2658
 
    for client in tcp_server.clients.itervalues():
 
 
2000
    for client in tcp_server.clients:
 
2660
2002
            # Emit D-Bus signal
 
2661
2003
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
2662
 
        # Need to initiate checking of clients
 
2664
 
            client.init_checker()
 
2666
2006
    tcp_server.enable()
 
2667
2007
    tcp_server.server_activate()