85
81
except ImportError:
86
82
SO_BINDTODEVICE = None
89
stored_state_file = "clients.pickle"
91
logger = logging.getLogger()
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
92
89
syslogger = (logging.handlers.SysLogHandler
93
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
91
address = str("/dev/log")))
97
if_nametoindex = (ctypes.cdll.LoadLibrary
98
(ctypes.util.find_library("c"))
100
except (OSError, AttributeError):
101
def if_nametoindex(interface):
102
"Get an interface index the hard way, i.e. using fcntl()"
103
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
104
with contextlib.closing(socket.socket()) as s:
105
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
106
struct.pack(str("16s16x"),
108
interface_index = struct.unpack(str("I"),
110
return interface_index
113
def initlogger(level=logging.WARNING):
114
"""init logger and add loglevel"""
116
syslogger.setFormatter(logging.Formatter
117
('Mandos [%(process)d]: %(levelname)s:'
119
logger.addHandler(syslogger)
121
console = logging.StreamHandler()
122
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
126
logger.addHandler(console)
127
logger.setLevel(level)
130
class PGPError(Exception):
131
"""Exception if encryption/decryption fails"""
135
class PGPEngine(object):
136
"""A simple class for OpenPGP symmetric encryption & decryption"""
138
self.gnupg = GnuPGInterface.GnuPG()
139
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
self.gnupg = GnuPGInterface.GnuPG()
141
self.gnupg.options.meta_interactive = False
142
self.gnupg.options.homedir = self.tempdir
143
self.gnupg.options.extra_args.extend(['--force-mdc',
149
def __exit__ (self, exc_type, exc_value, traceback):
157
if self.tempdir is not None:
158
# Delete contents of tempdir
159
for root, dirs, files in os.walk(self.tempdir,
161
for filename in files:
162
os.remove(os.path.join(root, filename))
164
os.rmdir(os.path.join(root, dirname))
166
os.rmdir(self.tempdir)
169
def password_encode(self, password):
170
# Passphrase can not be empty and can not contain newlines or
171
# NUL bytes. So we prefix it and hex encode it.
172
return b"mandos" + binascii.hexlify(password)
174
def encrypt(self, data, password):
175
self.gnupg.passphrase = self.password_encode(password)
176
with open(os.devnull) as devnull:
178
proc = self.gnupg.run(['--symmetric'],
179
create_fhs=['stdin', 'stdout'],
180
attach_fhs={'stderr': devnull})
181
with contextlib.closing(proc.handles['stdin']) as f:
183
with contextlib.closing(proc.handles['stdout']) as f:
184
ciphertext = f.read()
188
self.gnupg.passphrase = None
191
def decrypt(self, data, password):
192
self.gnupg.passphrase = self.password_encode(password)
193
with open(os.devnull) as devnull:
195
proc = self.gnupg.run(['--decrypt'],
196
create_fhs=['stdin', 'stdout'],
197
attach_fhs={'stderr': devnull})
198
with contextlib.closing(proc.handles['stdin'] ) as f:
200
with contextlib.closing(proc.handles['stdout']) as f:
201
decrypted_plaintext = f.read()
205
self.gnupg.passphrase = None
206
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)
210
103
class AvahiError(Exception):
211
104
def __init__(self, value, *args, **kwargs):
430
313
"created", "enabled", "fingerprint",
431
314
"host", "interval", "last_checked_ok",
432
315
"last_enabled", "name", "timeout")
433
client_defaults = { "timeout": "5m",
434
"extended_timeout": "15m",
436
"checker": "fping -q -- %%(host)s",
438
"approval_delay": "0s",
439
"approval_duration": "1s",
440
"approved_by_default": "True",
444
317
def timeout_milliseconds(self):
445
318
"Return the 'timeout' attribute in milliseconds"
446
return timedelta_to_milliseconds(self.timeout)
319
return _timedelta_to_milliseconds(self.timeout)
448
321
def extended_timeout_milliseconds(self):
449
322
"Return the 'extended_timeout' attribute in milliseconds"
450
return timedelta_to_milliseconds(self.extended_timeout)
323
return _timedelta_to_milliseconds(self.extended_timeout)
452
325
def interval_milliseconds(self):
453
326
"Return the 'interval' attribute in milliseconds"
454
return timedelta_to_milliseconds(self.interval)
327
return _timedelta_to_milliseconds(self.interval)
456
329
def approval_delay_milliseconds(self):
457
return timedelta_to_milliseconds(self.approval_delay)
460
def config_parser(config):
461
""" Construct a new dict of client settings of this form:
462
{ client_name: {setting_name: value, ...}, ...}
463
with exceptions for any special settings as defined above"""
465
for client_name in config.sections():
466
section = dict(config.items(client_name))
467
client = settings[client_name] = {}
469
client["host"] = section["host"]
470
# Reformat values from string types to Python types
471
client["approved_by_default"] = config.getboolean(
472
client_name, "approved_by_default")
473
client["enabled"] = config.getboolean(client_name, "enabled")
475
client["fingerprint"] = (section["fingerprint"].upper()
477
if "secret" in section:
478
client["secret"] = section["secret"].decode("base64")
479
elif "secfile" in section:
480
with open(os.path.expanduser(os.path.expandvars
481
(section["secfile"])),
483
client["secret"] = secfile.read()
485
raise TypeError("No secret or secfile for section %s"
487
client["timeout"] = string_to_delta(section["timeout"])
488
client["extended_timeout"] = string_to_delta(
489
section["extended_timeout"])
490
client["interval"] = string_to_delta(section["interval"])
491
client["approval_delay"] = string_to_delta(
492
section["approval_delay"])
493
client["approval_duration"] = string_to_delta(
494
section["approval_duration"])
495
client["checker_command"] = section["checker"]
496
client["last_approval_request"] = None
497
client["last_checked_ok"] = None
498
client["last_checker_status"] = None
499
if client["enabled"]:
500
client["last_enabled"] = datetime.datetime.utcnow()
501
client["expires"] = (datetime.datetime.utcnow()
504
client["last_enabled"] = None
505
client["expires"] = None
510
def __init__(self, settings, name = None):
330
return _timedelta_to_milliseconds(self.approval_delay)
332
def __init__(self, name = None, disable_hook=None, config=None):
511
333
"""Note: the 'checker' key in 'config' sets the
512
334
'checker_command' attribute and *not* the 'checker'
515
# adding all client settings
516
for setting, value in settings.iteritems():
517
setattr(self, setting, value)
519
339
logger.debug("Creating client %r", self.name)
520
340
# Uppercase and remove spaces from fingerprint for later
521
341
# comparison purposes with return value from the fingerprint()
343
self.fingerprint = (config["fingerprint"].upper()
523
345
logger.debug(" Fingerprint: %s", self.fingerprint)
524
self.created = settings.get("created", datetime.datetime.utcnow())
526
# attributes specific for this server instance
346
if "secret" in config:
347
self.secret = config["secret"].decode("base64")
348
elif "secfile" in config:
349
with open(os.path.expanduser(os.path.expandvars
350
(config["secfile"])),
352
self.secret = secfile.read()
354
raise TypeError("No secret or secfile for client %s"
356
self.host = config.get("host", "")
357
self.created = datetime.datetime.utcnow()
359
self.last_approval_request = None
360
self.last_enabled = None
361
self.last_checked_ok = None
362
self.timeout = string_to_delta(config["timeout"])
363
self.extended_timeout = string_to_delta(config["extended_timeout"])
364
self.interval = string_to_delta(config["interval"])
365
self.disable_hook = disable_hook
527
366
self.checker = None
528
367
self.checker_initiator_tag = None
529
368
self.disable_initiator_tag = None
530
370
self.checker_callback_tag = None
371
self.checker_command = config["checker"]
531
372
self.current_checker_command = None
373
self.last_connect = None
374
self._approved = None
375
self.approved_by_default = config.get("approved_by_default",
533
377
self.approvals_pending = 0
534
self.changedstate = (multiprocessing_manager
535
.Condition(multiprocessing_manager
537
self.client_structure = [attr for attr in
538
self.__dict__.iterkeys()
539
if not attr.startswith("_")]
540
self.client_structure.append("client_structure")
542
for name, t in inspect.getmembers(type(self),
546
if not name.startswith("_"):
547
self.client_structure.append(name)
378
self.approval_delay = string_to_delta(
379
config["approval_delay"])
380
self.approval_duration = string_to_delta(
381
config["approval_duration"])
382
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
549
# Send notice to process children that client state has changed
550
384
def send_changedstate(self):
551
with self.changedstate:
552
self.changedstate.notify_all()
385
self.changedstate.acquire()
386
self.changedstate.notify_all()
387
self.changedstate.release()
554
389
def enable(self):
555
390
"""Start this client's checker and timeout hooks"""
556
391
if getattr(self, "enabled", False):
557
392
# Already enabled
559
394
self.send_changedstate()
395
# Schedule a new checker to be started an 'interval' from now,
396
# and every interval from then on.
397
self.checker_initiator_tag = (gobject.timeout_add
398
(self.interval_milliseconds(),
400
# Schedule a disable() when 'timeout' has passed
560
401
self.expires = datetime.datetime.utcnow() + self.timeout
402
self.disable_initiator_tag = (gobject.timeout_add
403
(self.timeout_milliseconds(),
561
405
self.enabled = True
562
406
self.last_enabled = datetime.datetime.utcnow()
407
# Also start a new checker *right now*.
565
410
def disable(self, quiet=True):
566
411
"""Disable this client."""
794
625
def _get_all_dbus_properties(self):
795
626
"""Returns a generator of (name, attribute) pairs
797
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
798
for cls in self.__class__.__mro__
628
return ((prop._dbus_name, prop)
799
629
for name, prop in
800
inspect.getmembers(cls, self._is_dbus_property))
630
inspect.getmembers(self, self._is_dbus_property))
802
632
def _get_dbus_property(self, interface_name, property_name):
803
633
"""Returns a bound method if one exists which is a D-Bus
804
634
property with the specified name and interface.
806
for cls in self.__class__.__mro__:
807
for name, value in (inspect.getmembers
808
(cls, self._is_dbus_property)):
809
if (value._dbus_name == property_name
810
and value._dbus_interface == interface_name):
811
return value.__get__(self)
636
for name in (property_name,
637
property_name + "_dbus_property"):
638
prop = getattr(self, name, None)
640
or not self._is_dbus_property(prop)
641
or prop._dbus_name != property_name
642
or (interface_name and prop._dbus_interface
643
and interface_name != prop._dbus_interface)):
813
646
# No such property
814
647
raise DBusPropertyNotFound(self.dbus_object_path + ":"
815
648
+ interface_name + "."
924
757
return dbus.String(dt.isoformat(),
925
758
variant_level=variant_level)
928
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
930
"""Applied to an empty subclass of a D-Bus object, this metaclass
931
will add additional D-Bus attributes matching a certain pattern.
933
def __new__(mcs, name, bases, attr):
934
# Go through all the base classes which could have D-Bus
935
# methods, signals, or properties in them
936
for base in (b for b in bases
937
if issubclass(b, dbus.service.Object)):
938
# Go though all attributes of the base class
939
for attrname, attribute in inspect.getmembers(base):
940
# Ignore non-D-Bus attributes, and D-Bus attributes
941
# with the wrong interface name
942
if (not hasattr(attribute, "_dbus_interface")
943
or not attribute._dbus_interface
944
.startswith("se.recompile.Mandos")):
946
# Create an alternate D-Bus interface name based on
948
alt_interface = (attribute._dbus_interface
949
.replace("se.recompile.Mandos",
950
"se.bsnet.fukt.Mandos"))
951
# Is this a D-Bus signal?
952
if getattr(attribute, "_dbus_is_signal", False):
953
# Extract the original non-method function by
955
nonmethod_func = (dict(
956
zip(attribute.func_code.co_freevars,
957
attribute.__closure__))["func"]
959
# Create a new, but exactly alike, function
960
# object, and decorate it to be a new D-Bus signal
961
# with the alternate D-Bus interface name
962
new_function = (dbus.service.signal
964
attribute._dbus_signature)
966
nonmethod_func.func_code,
967
nonmethod_func.func_globals,
968
nonmethod_func.func_name,
969
nonmethod_func.func_defaults,
970
nonmethod_func.func_closure)))
971
# Define a creator of a function to call both the
972
# old and new functions, so both the old and new
973
# signals gets sent when the function is called
974
def fixscope(func1, func2):
975
"""This function is a scope container to pass
976
func1 and func2 to the "call_both" function
977
outside of its arguments"""
978
def call_both(*args, **kwargs):
979
"""This function will emit two D-Bus
980
signals by calling func1 and func2"""
981
func1(*args, **kwargs)
982
func2(*args, **kwargs)
984
# Create the "call_both" function and add it to
986
attr[attrname] = fixscope(attribute,
988
# Is this a D-Bus method?
989
elif getattr(attribute, "_dbus_is_method", False):
990
# Create a new, but exactly alike, function
991
# object. Decorate it to be a new D-Bus method
992
# with the alternate D-Bus interface name. Add it
994
attr[attrname] = (dbus.service.method
996
attribute._dbus_in_signature,
997
attribute._dbus_out_signature)
999
(attribute.func_code,
1000
attribute.func_globals,
1001
attribute.func_name,
1002
attribute.func_defaults,
1003
attribute.func_closure)))
1004
# Is this a D-Bus property?
1005
elif getattr(attribute, "_dbus_is_property", False):
1006
# Create a new, but exactly alike, function
1007
# object, and decorate it to be a new D-Bus
1008
# property with the alternate D-Bus interface
1009
# name. Add it to the class.
1010
attr[attrname] = (dbus_service_property
1012
attribute._dbus_signature,
1013
attribute._dbus_access,
1015
._dbus_get_args_options
1018
(attribute.func_code,
1019
attribute.func_globals,
1020
attribute.func_name,
1021
attribute.func_defaults,
1022
attribute.func_closure)))
1023
return type.__new__(mcs, name, bases, attr)
1026
760
class ClientDBus(Client, DBusObjectWithProperties):
1027
761
"""A Client class using D-Bus
1055
787
def notifychangeproperty(transform_func,
1056
788
dbus_name, type_func=lambda x: x,
1057
789
variant_level=1):
1058
""" Modify a variable so that it's a property which announces
1059
its changes to DBus.
1061
transform_fun: Function that takes a value and a variant_level
1062
and transforms it to a D-Bus type.
1063
dbus_name: D-Bus name of the variable
790
""" Modify a variable so that its a property that announce its
792
transform_fun: Function that takes a value and transform it to
794
dbus_name: DBus name of the variable
1064
795
type_func: Function that transform the value before sending it
1065
to the D-Bus. Default: no transform
1066
variant_level: D-Bus variant level. Default: 1
797
variant_level: DBus variant level. default: 1
1068
attrname = "_{0}".format(dbus_name)
1069
800
def setter(self, value):
801
old_value = real_value[0]
802
real_value[0] = value
1070
803
if hasattr(self, "dbus_object_path"):
1071
if (not hasattr(self, attrname) or
1072
type_func(getattr(self, attrname, None))
1073
!= type_func(value)):
1074
dbus_value = transform_func(type_func(value),
804
if type_func(old_value) != type_func(real_value[0]):
805
dbus_value = transform_func(type_func(real_value[0]),
1077
807
self.PropertyChanged(dbus.String(dbus_name),
1079
setattr(self, attrname, value)
1081
return property(lambda self: getattr(self, attrname), setter)
810
return property(lambda self: real_value[0], setter)
1084
813
expires = notifychangeproperty(datetime_to_dbus, "Expires")
1085
814
approvals_pending = notifychangeproperty(dbus.Boolean,
1086
815
"ApprovalPending",
1089
818
last_enabled = notifychangeproperty(datetime_to_dbus,
1091
820
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1092
type_func = lambda checker:
1093
checker is not None)
821
type_func = lambda checker: checker is not None)
1094
822
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1095
823
"LastCheckedOK")
1096
last_approval_request = notifychangeproperty(
1097
datetime_to_dbus, "LastApprovalRequest")
824
last_approval_request = notifychangeproperty(datetime_to_dbus,
825
"LastApprovalRequest")
1098
826
approved_by_default = notifychangeproperty(dbus.Boolean,
1099
827
"ApprovedByDefault")
1100
approval_delay = notifychangeproperty(dbus.UInt64,
1103
timedelta_to_milliseconds)
1104
approval_duration = notifychangeproperty(
1105
dbus.UInt64, "ApprovalDuration",
1106
type_func = timedelta_to_milliseconds)
828
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
829
type_func = _timedelta_to_milliseconds)
830
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
831
type_func = _timedelta_to_milliseconds)
1107
832
host = notifychangeproperty(dbus.String, "Host")
1108
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1110
timedelta_to_milliseconds)
1111
extended_timeout = notifychangeproperty(
1112
dbus.UInt64, "ExtendedTimeout",
1113
type_func = timedelta_to_milliseconds)
1114
interval = notifychangeproperty(dbus.UInt64,
1117
timedelta_to_milliseconds)
833
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
834
type_func = _timedelta_to_milliseconds)
835
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
836
type_func = _timedelta_to_milliseconds)
837
interval = notifychangeproperty(dbus.UInt16, "Interval",
838
type_func = _timedelta_to_milliseconds)
1118
839
checker_command = notifychangeproperty(dbus.String, "Checker")
1120
841
del notifychangeproperty
1866
1558
"dress: %s", fpr, address)
1867
1559
if self.use_dbus:
1868
1560
# Emit D-Bus signal
1869
mandos_dbus_service.ClientNotFound(fpr,
1561
mandos_dbus_service.ClientNotFound(fpr, address[0])
1871
1562
parent_pipe.send(False)
1874
1565
gobject.io_add_watch(parent_pipe.fileno(),
1875
1566
gobject.IO_IN | gobject.IO_HUP,
1876
1567
functools.partial(self.handle_ipc,
1568
parent_pipe = parent_pipe,
1569
client_object = client))
1882
1570
parent_pipe.send(True)
1883
# remove the old hook in favor of the new above hook on
1571
# remove the old hook in favor of the new above hook on same fileno
1886
1573
if command == 'funcall':
1887
1574
funcname = request[1]
1888
1575
args = request[2]
1889
1576
kwargs = request[3]
1891
parent_pipe.send(('data', getattr(client_object,
1578
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1895
1580
if command == 'getattr':
1896
1581
attrname = request[1]
1897
1582
if callable(client_object.__getattribute__(attrname)):
1898
1583
parent_pipe.send(('function',))
1900
parent_pipe.send(('data', client_object
1901
.__getattribute__(attrname)))
1585
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1903
1587
if command == 'setattr':
1904
1588
attrname = request[1]
1905
1589
value = request[2]
1906
1590
setattr(client_object, attrname, value)
2200
1898
client_class = Client
2202
client_class = functools.partial(ClientDBusTransitional,
2205
client_settings = Client.config_parser(client_config)
2206
old_client_settings = {}
2209
# Get client data and settings from last running state.
2210
if server_settings["restore"]:
2212
with open(stored_state_path, "rb") as stored_state:
2213
clients_data, old_client_settings = (pickle.load
2215
os.remove(stored_state_path)
2216
except IOError as e:
2217
logger.warning("Could not load persistent state: {0}"
2219
if e.errno != errno.ENOENT:
2221
except EOFError as e:
2222
logger.warning("Could not load persistent state: "
2223
"EOFError: {0}".format(e))
2225
with PGPEngine() as pgp:
2226
for client_name, client in clients_data.iteritems():
2227
# Decide which value to use after restoring saved state.
2228
# We have three different values: Old config file,
2229
# new config file, and saved state.
2230
# New config value takes precedence if it differs from old
2231
# config value, otherwise use saved state.
2232
for name, value in client_settings[client_name].items():
2234
# For each value in new config, check if it
2235
# differs from the old config value (Except for
2236
# the "secret" attribute)
2237
if (name != "secret" and
2238
value != old_client_settings[client_name]
2240
client[name] = value
2244
# Clients who has passed its expire date can still be
2245
# enabled if its last checker was successful. Clients
2246
# whose checker failed before we stored its state is
2247
# assumed to have failed all checkers during downtime.
2248
if client["enabled"]:
2249
if datetime.datetime.utcnow() >= client["expires"]:
2250
if not client["last_checked_ok"]:
2252
"disabling client {0} - Client never "
2253
"performed a successfull checker"
2254
.format(client["name"]))
2255
client["enabled"] = False
2256
elif client["last_checker_status"] != 0:
2258
"disabling client {0} - Client "
2259
"last checker failed with error code {1}"
2260
.format(client["name"],
2261
client["last_checker_status"]))
2262
client["enabled"] = False
2264
client["expires"] = (datetime.datetime
2266
+ client["timeout"])
1900
client_class = functools.partial(ClientDBus, bus = bus)
1901
def client_config_items(config, section):
1902
special_settings = {
1903
"approved_by_default":
1904
lambda: config.getboolean(section,
1905
"approved_by_default"),
1907
for name, value in config.items(section):
2269
client["secret"] = (
2270
pgp.decrypt(client["encrypted_secret"],
2271
client_settings[client_name]
2274
# If decryption fails, we use secret from new settings
2275
logger.debug("Failed to decrypt {0} old secret"
2276
.format(client_name))
2277
client["secret"] = (
2278
client_settings[client_name]["secret"])
2281
# Add/remove clients based on new changes made to config
2282
for client_name in set(old_client_settings) - set(client_settings):
2283
del clients_data[client_name]
2284
for client_name in set(client_settings) - set(old_client_settings):
2285
clients_data[client_name] = client_settings[client_name]
2287
# Create clients all clients
2288
for client_name, client in clients_data.iteritems():
2289
tcp_server.clients[client_name] = client_class(
2290
name = client_name, settings = client)
1909
yield (name, special_settings[name]())
1913
tcp_server.clients.update(set(
1914
client_class(name = section,
1915
config= dict(client_config_items(
1916
client_config, section)))
1917
for section in client_config.sections()))
2292
1918
if not tcp_server.clients:
2293
1919
logger.warning("No clients defined")
2367
class MandosDBusServiceTransitional(MandosDBusService):
2368
__metaclass__ = AlternateDBusNamesMetaclass
2369
mandos_dbus_service = MandosDBusServiceTransitional()
1993
mandos_dbus_service = MandosDBusService()
2372
1996
"Cleanup function; run on exit"
2373
1997
service.cleanup()
2375
multiprocessing.active_children()
2376
if not (tcp_server.clients or client_settings):
2379
# Store client before exiting. Secrets are encrypted with key
2380
# based on what config file has. If config file is
2381
# removed/edited, old secret will thus be unrecovable.
2383
with PGPEngine() as pgp:
2384
for client in tcp_server.clients.itervalues():
2385
key = client_settings[client.name]["secret"]
2386
client.encrypted_secret = pgp.encrypt(client.secret,
2390
# A list of attributes that can not be pickled
2392
exclude = set(("bus", "changedstate", "secret",
2394
for name, typ in (inspect.getmembers
2395
(dbus.service.Object)):
2398
client_dict["encrypted_secret"] = (client
2400
for attr in client.client_structure:
2401
if attr not in exclude:
2402
client_dict[attr] = getattr(client, attr)
2404
clients[client.name] = client_dict
2405
del client_settings[client.name]["secret"]
2408
with os.fdopen(os.open(stored_state_path,
2409
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2410
0600), "wb") as stored_state:
2411
pickle.dump((clients, client_settings), stored_state)
2412
except (IOError, OSError) as e:
2413
logger.warning("Could not save persistent state: {0}"
2415
if e.errno not in (errno.ENOENT, errno.EACCES):
2418
# Delete all clients, and settings from config
2419
1999
while tcp_server.clients:
2420
name, client = tcp_server.clients.popitem()
2000
client = tcp_server.clients.pop()
2422
2002
client.remove_from_connection()
2003
client.disable_hook = None
2423
2004
# Don't signal anything except ClientRemoved
2424
2005
client.disable(quiet=True)
2426
2007
# Emit D-Bus signal
2427
mandos_dbus_service.ClientRemoved(client
2008
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2430
client_settings.clear()
2432
2011
atexit.register(cleanup)
2434
for client in tcp_server.clients.itervalues():
2013
for client in tcp_server.clients:
2436
2015
# Emit D-Bus signal
2437
2016
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2438
# Need to initiate checking of clients
2440
client.init_checker()
2442
2019
tcp_server.enable()
2443
2020
tcp_server.server_activate()