11
11
# "AvahiService" class, and some lines in "main".
13
13
# Everything else is
14
# Copyright © 2008-2014 Teddy Hogeborn
15
# Copyright © 2008-2014 Björn Påhlsson
14
# Copyright © 2008-2015 Teddy Hogeborn
15
# Copyright © 2008-2015 Björn Påhlsson
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
88
88
except ImportError:
89
89
SO_BINDTODEVICE = None
91
if sys.version_info.major == 2:
92
95
stored_state_file = "clients.pickle"
94
97
logger = logging.getLogger()
98
if_nametoindex = (ctypes.cdll.LoadLibrary
99
(ctypes.util.find_library("c"))
101
if_nametoindex = ctypes.cdll.LoadLibrary(
102
ctypes.util.find_library("c")).if_nametoindex
101
103
except (OSError, AttributeError):
102
105
def if_nametoindex(interface):
103
106
"Get an interface index the hard way, i.e. using fcntl()"
104
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
105
108
with contextlib.closing(socket.socket()) as s:
106
109
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
struct.pack(str("16s16x"),
109
interface_index = struct.unpack(str("I"),
110
struct.pack(b"16s16x", interface))
111
interface_index = struct.unpack("I", ifreq[16:20])[0]
111
112
return interface_index
115
116
"""init logger and add loglevel"""
118
syslogger = (logging.handlers.SysLogHandler
120
logging.handlers.SysLogHandler.LOG_DAEMON,
121
address = str("/dev/log")))
119
syslogger = (logging.handlers.SysLogHandler(
120
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
121
address = "/dev/log"))
122
122
syslogger.setFormatter(logging.Formatter
123
123
('Mandos [%(process)d]: %(levelname)s:'
186
187
def encrypt(self, data, password):
187
188
passphrase = self.password_encode(password)
188
with tempfile.NamedTemporaryFile(dir=self.tempdir
189
with tempfile.NamedTemporaryFile(
190
dir=self.tempdir) as passfile:
190
191
passfile.write(passphrase)
192
193
proc = subprocess.Popen(['gpg', '--symmetric',
204
205
def decrypt(self, data, password):
205
206
passphrase = self.password_encode(password)
206
with tempfile.NamedTemporaryFile(dir = self.tempdir
207
with tempfile.NamedTemporaryFile(
208
dir = self.tempdir) as passfile:
208
209
passfile.write(passphrase)
210
211
proc = subprocess.Popen(['gpg', '--decrypt',
224
224
class AvahiError(Exception):
225
225
def __init__(self, value, *args, **kwargs):
226
226
self.value = value
227
super(AvahiError, self).__init__(value, *args, **kwargs)
228
def __unicode__(self):
229
return unicode(repr(self.value))
227
return super(AvahiError, self).__init__(value, *args,
231
231
class AvahiServiceError(AvahiError):
234
235
class AvahiGroupError(AvahiError):
256
257
bus: dbus.SystemBus()
259
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
260
servicetype = None, port = None, TXT = None,
261
domain = "", host = "", max_renames = 32768,
262
protocol = avahi.PROTO_UNSPEC, bus = None):
261
interface = avahi.IF_UNSPEC,
269
protocol = avahi.PROTO_UNSPEC,
263
271
self.interface = interface
265
273
self.type = servicetype
276
284
self.entry_group_state_changed_match = None
286
def rename(self, remove=True):
279
287
"""Derived from the Avahi example code"""
280
288
if self.rename_count >= self.max_renames:
281
289
logger.critical("No suitable Zeroconf service name found"
282
290
" after %i retries, exiting.",
283
291
self.rename_count)
284
292
raise AvahiServiceError("Too many renames")
285
self.name = unicode(self.server
286
.GetAlternativeServiceName(self.name))
294
self.server.GetAlternativeServiceName(self.name))
295
self.rename_count += 1
287
296
logger.info("Changing Zeroconf service name to %r ...",
292
302
except dbus.exceptions.DBusException as error:
293
logger.critical("D-Bus Exception", exc_info=error)
296
self.rename_count += 1
303
if (error.get_dbus_name()
304
== "org.freedesktop.Avahi.CollisionError"):
305
logger.info("Local Zeroconf service name collision.")
306
return self.rename(remove=False)
308
logger.critical("D-Bus Exception", exc_info=error)
298
312
def remove(self):
299
313
"""Derived from the Avahi example code"""
355
368
def server_state_changed(self, state, error=None):
356
369
"""Derived from the Avahi example code"""
357
370
logger.debug("Avahi server state change: %i", state)
358
bad_states = { avahi.SERVER_INVALID:
359
"Zeroconf server invalid",
360
avahi.SERVER_REGISTERING: None,
361
avahi.SERVER_COLLISION:
362
"Zeroconf server name collision",
363
avahi.SERVER_FAILURE:
364
"Zeroconf server failure" }
372
avahi.SERVER_INVALID: "Zeroconf server invalid",
373
avahi.SERVER_REGISTERING: None,
374
avahi.SERVER_COLLISION: "Zeroconf server name collision",
375
avahi.SERVER_FAILURE: "Zeroconf server failure",
365
377
if state in bad_states:
366
378
if bad_states[state] is not None:
367
379
if error is None:
386
398
follow_name_owner_changes=True),
387
399
avahi.DBUS_INTERFACE_SERVER)
388
400
self.server.connect_to_signal("StateChanged",
389
self.server_state_changed)
401
self.server_state_changed)
390
402
self.server_state_changed(self.server.GetState())
393
405
class AvahiServiceToSyslog(AvahiService):
406
def rename(self, *args, **kwargs):
395
407
"""Add the new name to the syslog messages"""
396
ret = AvahiService.rename(self)
397
syslogger.setFormatter(logging.Formatter
398
('Mandos ({}) [%(process)d]:'
399
' %(levelname)s: %(message)s'
408
ret = AvahiService.rename(self, *args, **kwargs)
409
syslogger.setFormatter(logging.Formatter(
410
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
450
461
"fingerprint", "host", "interval",
451
462
"last_approval_request", "last_checked_ok",
452
463
"last_enabled", "name", "timeout")
453
client_defaults = { "timeout": "PT5M",
454
"extended_timeout": "PT15M",
456
"checker": "fping -q -- %%(host)s",
458
"approval_delay": "PT0S",
459
"approval_duration": "PT1S",
460
"approved_by_default": "True",
466
"extended_timeout": "PT15M",
468
"checker": "fping -q -- %%(host)s",
470
"approval_delay": "PT0S",
471
"approval_duration": "PT1S",
472
"approved_by_default": "True",
465
477
def config_parser(config):
528
543
self.expires = None
530
545
logger.debug("Creating client %r", self.name)
531
# Uppercase and remove spaces from fingerprint for later
532
# comparison purposes with return value from the fingerprint()
534
546
logger.debug(" Fingerprint: %s", self.fingerprint)
535
547
self.created = settings.get("created",
536
548
datetime.datetime.utcnow())
543
555
self.current_checker_command = None
544
556
self.approved = None
545
557
self.approvals_pending = 0
546
self.changedstate = (multiprocessing_manager
547
.Condition(multiprocessing_manager
549
self.client_structure = [attr for attr in
550
self.__dict__.iterkeys()
558
self.changedstate = multiprocessing_manager.Condition(
559
multiprocessing_manager.Lock())
560
self.client_structure = [attr
561
for attr in self.__dict__.iterkeys()
551
562
if not attr.startswith("_")]
552
563
self.client_structure.append("client_structure")
554
for name, t in inspect.getmembers(type(self),
565
for name, t in inspect.getmembers(
566
type(self), lambda obj: isinstance(obj, property)):
558
567
if not name.startswith("_"):
559
568
self.client_structure.append(name)
602
611
# and every interval from then on.
603
612
if self.checker_initiator_tag is not None:
604
613
gobject.source_remove(self.checker_initiator_tag)
605
self.checker_initiator_tag = (gobject.timeout_add
607
.total_seconds() * 1000),
614
self.checker_initiator_tag = gobject.timeout_add(
615
int(self.interval.total_seconds() * 1000),
609
617
# Schedule a disable() when 'timeout' has passed
610
618
if self.disable_initiator_tag is not None:
611
619
gobject.source_remove(self.disable_initiator_tag)
612
self.disable_initiator_tag = (gobject.timeout_add
614
.total_seconds() * 1000),
620
self.disable_initiator_tag = gobject.timeout_add(
621
int(self.timeout.total_seconds() * 1000), self.disable)
616
622
# Also start a new checker *right now*.
617
623
self.start_checker()
648
653
gobject.source_remove(self.disable_initiator_tag)
649
654
self.disable_initiator_tag = None
650
655
if getattr(self, "enabled", False):
651
self.disable_initiator_tag = (gobject.timeout_add
652
(int(timeout.total_seconds()
653
* 1000), self.disable))
656
self.disable_initiator_tag = gobject.timeout_add(
657
int(timeout.total_seconds() * 1000), self.disable)
654
658
self.expires = datetime.datetime.utcnow() + timeout
656
660
def need_approval(self):
687
691
# Start a new checker if needed
688
692
if self.checker is None:
689
693
# Escape attributes for the shell
690
escaped_attrs = { attr:
691
re.escape(unicode(getattr(self,
693
for attr in self.runtime_expansions }
695
attr: re.escape(str(getattr(self, attr)))
696
for attr in self.runtime_expansions }
695
698
command = self.checker_command % escaped_attrs
696
699
except TypeError as error:
697
700
logger.error('Could not format string "%s"',
698
self.checker_command, exc_info=error)
699
return True # Try again later
701
self.checker_command,
703
return True # Try again later
700
704
self.current_checker_command = command
702
logger.info("Starting checker %r for %s",
706
logger.info("Starting checker %r for %s", command,
704
708
# We don't need to redirect stdout and stderr, since
705
709
# in normal mode, that is already done by daemon(),
706
710
# and in debug mode we don't want to. (Stdin is
715
719
"stderr": wnull })
716
720
self.checker = subprocess.Popen(command,
720
725
except OSError as error:
721
726
logger.error("Failed to start subprocess",
724
self.checker_callback_tag = (gobject.child_watch_add
726
self.checker_callback,
729
self.checker_callback_tag = gobject.child_watch_add(
730
self.checker.pid, self.checker_callback, data=command)
728
731
# The checker may have completed before the gobject
729
732
# watch was added. Check for this.
761
764
self.checker = None
764
def dbus_service_property(dbus_interface, signature="v",
765
access="readwrite", byte_arrays=False):
767
def dbus_service_property(dbus_interface,
766
771
"""Decorators for marking methods of a DBusObjectWithProperties to
767
772
become properties on the D-Bus.
814
823
"""Decorator to annotate D-Bus methods, signals or properties
826
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
827
"org.freedesktop.DBus.Property."
828
"EmitsChangedSignal": "false"})
817
829
@dbus_service_property("org.example.Interface", signature="b",
819
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
820
"org.freedesktop.DBus.Property."
821
"EmitsChangedSignal": "false"})
822
831
def Property_dbus_property(self):
823
832
return dbus.Boolean(False)
825
835
def decorator(func):
826
836
func._dbus_annotations = annotations
831
842
class DBusPropertyException(dbus.exceptions.DBusException):
832
843
"""A base class for D-Bus property-related exceptions
834
def __unicode__(self):
835
return unicode(str(self))
838
848
class DBusPropertyAccessException(DBusPropertyException):
868
878
def _get_all_dbus_things(self, thing):
869
879
"""Returns a generator of (name, attribute) pairs
871
return ((getattr(athing.__get__(self), "_dbus_name",
881
return ((getattr(athing.__get__(self), "_dbus_name", name),
873
882
athing.__get__(self))
874
883
for cls in self.__class__.__mro__
875
884
for name, athing in
876
inspect.getmembers(cls,
877
self._is_dbus_thing(thing)))
885
inspect.getmembers(cls, self._is_dbus_thing(thing)))
879
887
def _get_dbus_property(self, interface_name, property_name):
880
888
"""Returns a bound method if one exists which is a D-Bus
881
889
property with the specified name and interface.
883
for cls in self.__class__.__mro__:
884
for name, value in (inspect.getmembers
886
self._is_dbus_thing("property"))):
891
for cls in self.__class__.__mro__:
892
for name, value in inspect.getmembers(
893
cls, self._is_dbus_thing("property")):
887
894
if (value._dbus_name == property_name
888
895
and value._dbus_interface == interface_name):
889
896
return value.__get__(self)
891
898
# No such property
892
raise DBusPropertyNotFound(self.dbus_object_path + ":"
893
+ interface_name + "."
899
raise DBusPropertyNotFound("{}:{}.{}".format(
900
self.dbus_object_path, interface_name, property_name))
896
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
902
@dbus.service.method(dbus.PROPERTIES_IFACE,
897
904
out_signature="v")
898
905
def Get(self, interface_name, property_name):
899
906
"""Standard D-Bus property Get() method, see D-Bus standard.
945
953
if not hasattr(value, "variant_level"):
946
954
properties[name] = value
948
properties[name] = type(value)(value, variant_level=
949
value.variant_level+1)
956
properties[name] = type(value)(
957
value, variant_level = value.variant_level + 1)
950
958
return dbus.Dictionary(properties, signature="sv")
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
952
968
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
953
969
out_signature="s",
954
970
path_keyword='object_path',
964
980
document = xml.dom.minidom.parseString(xmlstring)
965
982
def make_tag(document, name, prop):
966
983
e = document.createElement("property")
967
984
e.setAttribute("name", name)
968
985
e.setAttribute("type", prop._dbus_signature)
969
986
e.setAttribute("access", prop._dbus_access)
971
989
for if_tag in document.getElementsByTagName("interface"):
972
990
# Add property tags
973
991
for tag in (make_tag(document, name, prop)
1035
1051
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1037
1053
return dbus.String("", variant_level = variant_level)
1038
return dbus.String(dt.isoformat(),
1039
variant_level=variant_level)
1054
return dbus.String(dt.isoformat(), variant_level=variant_level)
1042
1057
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1072
1088
# Ignore non-D-Bus attributes, and D-Bus attributes
1073
1089
# with the wrong interface name
1074
1090
if (not hasattr(attribute, "_dbus_interface")
1075
or not attribute._dbus_interface
1076
.startswith(orig_interface_name)):
1091
or not attribute._dbus_interface.startswith(
1092
orig_interface_name)):
1078
1094
# Create an alternate D-Bus interface name based on
1079
1095
# the current name
1080
alt_interface = (attribute._dbus_interface
1081
.replace(orig_interface_name,
1082
alt_interface_name))
1096
alt_interface = attribute._dbus_interface.replace(
1097
orig_interface_name, alt_interface_name)
1083
1098
interface_names.add(alt_interface)
1084
1099
# Is this a D-Bus signal?
1085
1100
if getattr(attribute, "_dbus_is_signal", False):
1086
1101
# Extract the original non-method undecorated
1087
1102
# function by black magic
1088
1103
nonmethod_func = (dict(
1089
zip(attribute.func_code.co_freevars,
1090
attribute.__closure__))["func"]
1104
zip(attribute.func_code.co_freevars,
1105
attribute.__closure__))
1106
["func"].cell_contents)
1092
1107
# Create a new, but exactly alike, function
1093
1108
# object, and decorate it to be a new D-Bus signal
1094
1109
# with the alternate D-Bus interface name
1095
new_function = (dbus.service.signal
1097
attribute._dbus_signature)
1110
new_function = (dbus.service.signal(
1111
alt_interface, attribute._dbus_signature)
1098
1112
(types.FunctionType(
1099
nonmethod_func.func_code,
1100
nonmethod_func.func_globals,
1101
nonmethod_func.func_name,
1102
nonmethod_func.func_defaults,
1103
nonmethod_func.func_closure)))
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)))
1104
1118
# Copy annotations, if any
1106
new_function._dbus_annotations = (
1107
dict(attribute._dbus_annotations))
1120
new_function._dbus_annotations = dict(
1121
attribute._dbus_annotations)
1108
1122
except AttributeError:
1110
1124
# Define a creator of a function to call both the
1115
1129
"""This function is a scope container to pass
1116
1130
func1 and func2 to the "call_both" function
1117
1131
outside of its arguments"""
1118
1133
def call_both(*args, **kwargs):
1119
1134
"""This function will emit two D-Bus
1120
1135
signals by calling func1 and func2"""
1121
1136
func1(*args, **kwargs)
1122
1137
func2(*args, **kwargs)
1123
1139
return call_both
1124
1140
# Create the "call_both" function and add it to
1130
1146
# object. Decorate it to be a new D-Bus method
1131
1147
# with the alternate D-Bus interface name. Add it
1132
1148
# to the class.
1133
attr[attrname] = (dbus.service.method
1135
attribute._dbus_in_signature,
1136
attribute._dbus_out_signature)
1138
(attribute.func_code,
1139
attribute.func_globals,
1140
attribute.func_name,
1141
attribute.func_defaults,
1142
attribute.func_closure)))
1150
dbus.service.method(
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)))
1143
1159
# Copy annotations, if any
1145
attr[attrname]._dbus_annotations = (
1146
dict(attribute._dbus_annotations))
1161
attr[attrname]._dbus_annotations = dict(
1162
attribute._dbus_annotations)
1147
1163
except AttributeError:
1149
1165
# Is this a D-Bus property?
1152
1168
# object, and decorate it to be a new D-Bus
1153
1169
# property with the alternate D-Bus interface
1154
1170
# name. Add it to the class.
1155
attr[attrname] = (dbus_service_property
1157
attribute._dbus_signature,
1158
attribute._dbus_access,
1160
._dbus_get_args_options
1163
(attribute.func_code,
1164
attribute.func_globals,
1165
attribute.func_name,
1166
attribute.func_defaults,
1167
attribute.func_closure)))
1171
attr[attrname] = (dbus_service_property(
1172
alt_interface, attribute._dbus_signature,
1173
attribute._dbus_access,
1174
attribute._dbus_get_args_options
1176
(types.FunctionType(
1177
attribute.func_code,
1178
attribute.func_globals,
1179
attribute.func_name,
1180
attribute.func_defaults,
1181
attribute.func_closure)))
1168
1182
# Copy annotations, if any
1170
attr[attrname]._dbus_annotations = (
1171
dict(attribute._dbus_annotations))
1184
attr[attrname]._dbus_annotations = dict(
1185
attribute._dbus_annotations)
1172
1186
except AttributeError:
1174
1188
# Is this a D-Bus interface?
1177
1191
# object. Decorate it to be a new D-Bus interface
1178
1192
# with the alternate D-Bus interface name. Add it
1179
1193
# to the class.
1180
attr[attrname] = (dbus_interface_annotations
1183
(attribute.func_code,
1184
attribute.func_globals,
1185
attribute.func_name,
1186
attribute.func_defaults,
1187
attribute.func_closure)))
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)))
1189
1202
# Deprecate all alternate interfaces
1190
1203
iname="_AlternateDBusNames_interface_annotation{}"
1191
1204
for interface_name in interface_names:
1192
1206
@dbus_interface_annotations(interface_name)
1193
1207
def func(self):
1194
1208
return { "org.freedesktop.DBus.Deprecated":
1196
1210
# Find an unused name
1197
1211
for aname in (iname.format(i)
1198
1212
for i in itertools.count()):
1203
1217
# Replace the class with a new subclass of it with
1204
1218
# methods, signals, etc. as created above.
1205
1219
cls = type(b"{}Alternate".format(cls.__name__),
1211
1226
@alternate_dbus_interfaces({"se.recompile.Mandos":
1212
"se.bsnet.fukt.Mandos"})
1227
"se.bsnet.fukt.Mandos"})
1213
1228
class ClientDBus(Client, DBusObjectWithProperties):
1214
1229
"""A Client class using D-Bus
1228
1245
Client.__init__(self, *args, **kwargs)
1229
1246
# Only now, when this client is initialized, can it show up on
1231
client_object_name = unicode(self.name).translate(
1248
client_object_name = str(self.name).translate(
1232
1249
{ord("."): ord("_"),
1233
1250
ord("-"): ord("_")})
1234
self.dbus_object_path = (dbus.ObjectPath
1235
("/clients/" + client_object_name))
1251
self.dbus_object_path = dbus.ObjectPath(
1252
"/clients/" + client_object_name)
1236
1253
DBusObjectWithProperties.__init__(self, self.bus,
1237
1254
self.dbus_object_path)
1239
def notifychangeproperty(transform_func,
1240
dbus_name, type_func=lambda x: x,
1256
def notifychangeproperty(transform_func, dbus_name,
1257
type_func=lambda x: x,
1259
invalidate_only=False,
1260
_interface=_interface):
1242
1261
""" Modify a variable so that it's a property which announces
1243
1262
its changes to DBus.
1250
1269
variant_level: D-Bus variant level. Default: 1
1252
1271
attrname = "_{}".format(dbus_name)
1253
1273
def setter(self, value):
1254
1274
if hasattr(self, "dbus_object_path"):
1255
1275
if (not hasattr(self, attrname) or
1256
1276
type_func(getattr(self, attrname, None))
1257
1277
!= type_func(value)):
1258
dbus_value = transform_func(type_func(value),
1261
self.PropertyChanged(dbus.String(dbus_name),
1279
self.PropertiesChanged(
1280
_interface, dbus.Dictionary(),
1281
dbus.Array((dbus_name, )))
1283
dbus_value = transform_func(
1285
variant_level = variant_level)
1286
self.PropertyChanged(dbus.String(dbus_name),
1288
self.PropertiesChanged(
1290
dbus.Dictionary({ dbus.String(dbus_name):
1263
1293
setattr(self, attrname, value)
1265
1295
return property(lambda self: getattr(self, attrname), setter)
1271
1301
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1272
1302
last_enabled = notifychangeproperty(datetime_to_dbus,
1274
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1275
type_func = lambda checker:
1276
checker is not None)
1304
checker = notifychangeproperty(
1305
dbus.Boolean, "CheckerRunning",
1306
type_func = lambda checker: checker is not None)
1277
1307
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1278
1308
"LastCheckedOK")
1279
1309
last_checker_status = notifychangeproperty(dbus.Int16,
1282
1312
datetime_to_dbus, "LastApprovalRequest")
1283
1313
approved_by_default = notifychangeproperty(dbus.Boolean,
1284
1314
"ApprovedByDefault")
1285
approval_delay = notifychangeproperty(dbus.UInt64,
1288
lambda td: td.total_seconds()
1315
approval_delay = notifychangeproperty(
1316
dbus.UInt64, "ApprovalDelay",
1317
type_func = lambda td: td.total_seconds() * 1000)
1290
1318
approval_duration = notifychangeproperty(
1291
1319
dbus.UInt64, "ApprovalDuration",
1292
1320
type_func = lambda td: td.total_seconds() * 1000)
1293
1321
host = notifychangeproperty(dbus.String, "Host")
1294
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1295
type_func = lambda td:
1296
td.total_seconds() * 1000)
1322
timeout = notifychangeproperty(
1323
dbus.UInt64, "Timeout",
1324
type_func = lambda td: td.total_seconds() * 1000)
1297
1325
extended_timeout = notifychangeproperty(
1298
1326
dbus.UInt64, "ExtendedTimeout",
1299
1327
type_func = lambda td: td.total_seconds() * 1000)
1300
interval = notifychangeproperty(dbus.UInt64,
1303
lambda td: td.total_seconds()
1328
interval = notifychangeproperty(
1329
dbus.UInt64, "Interval",
1330
type_func = lambda td: td.total_seconds() * 1000)
1305
1331
checker_command = notifychangeproperty(dbus.String, "Checker")
1332
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
invalidate_only=True)
1307
1335
del notifychangeproperty
1448
1471
return dbus.Boolean(bool(self.approvals_pending))
1450
1473
# ApprovedByDefault - property
1451
@dbus_service_property(_interface, signature="b",
1474
@dbus_service_property(_interface,
1452
1476
access="readwrite")
1453
1477
def ApprovedByDefault_dbus_property(self, value=None):
1454
1478
if value is None: # get
1456
1480
self.approved_by_default = bool(value)
1458
1482
# ApprovalDelay - property
1459
@dbus_service_property(_interface, signature="t",
1483
@dbus_service_property(_interface,
1460
1485
access="readwrite")
1461
1486
def ApprovalDelay_dbus_property(self, value=None):
1462
1487
if value is None: # get
1465
1490
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1467
1492
# ApprovalDuration - property
1468
@dbus_service_property(_interface, signature="t",
1493
@dbus_service_property(_interface,
1469
1495
access="readwrite")
1470
1496
def ApprovalDuration_dbus_property(self, value=None):
1471
1497
if value is None: # get
1484
1510
return dbus.String(self.fingerprint)
1486
1512
# Host - property
1487
@dbus_service_property(_interface, signature="s",
1513
@dbus_service_property(_interface,
1488
1515
access="readwrite")
1489
1516
def Host_dbus_property(self, value=None):
1490
1517
if value is None: # get
1491
1518
return dbus.String(self.host)
1492
self.host = unicode(value)
1519
self.host = str(value)
1494
1521
# Created - property
1495
1522
@dbus_service_property(_interface, signature="s", access="read")
1522
1551
return datetime_to_dbus(self.last_checked_ok)
1524
1553
# LastCheckerStatus - property
1525
@dbus_service_property(_interface, signature="n",
1554
@dbus_service_property(_interface, signature="n", access="read")
1527
1555
def LastCheckerStatus_dbus_property(self):
1528
1556
return dbus.Int16(self.last_checker_status)
1559
1588
gobject.source_remove(self.disable_initiator_tag)
1560
self.disable_initiator_tag = (
1561
gobject.timeout_add(
1562
int((self.expires - now).total_seconds()
1563
* 1000), self.disable))
1589
self.disable_initiator_tag = gobject.timeout_add(
1590
int((self.expires - now).total_seconds() * 1000),
1565
1593
# ExtendedTimeout - property
1566
@dbus_service_property(_interface, signature="t",
1594
@dbus_service_property(_interface,
1567
1596
access="readwrite")
1568
1597
def ExtendedTimeout_dbus_property(self, value=None):
1569
1598
if value is None: # get
1572
1601
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1574
1603
# Interval - property
1575
@dbus_service_property(_interface, signature="t",
1604
@dbus_service_property(_interface,
1576
1606
access="readwrite")
1577
1607
def Interval_dbus_property(self, value=None):
1578
1608
if value is None: # get
1583
1613
if self.enabled:
1584
1614
# Reschedule checker run
1585
1615
gobject.source_remove(self.checker_initiator_tag)
1586
self.checker_initiator_tag = (gobject.timeout_add
1587
(value, self.start_checker))
1588
self.start_checker() # Start one now, too
1616
self.checker_initiator_tag = gobject.timeout_add(
1617
value, self.start_checker)
1618
self.start_checker() # Start one now, too
1590
1620
# Checker - property
1591
@dbus_service_property(_interface, signature="s",
1621
@dbus_service_property(_interface,
1592
1623
access="readwrite")
1593
1624
def Checker_dbus_property(self, value=None):
1594
1625
if value is None: # get
1595
1626
return dbus.String(self.checker_command)
1596
self.checker_command = unicode(value)
1627
self.checker_command = str(value)
1598
1629
# CheckerRunning - property
1599
@dbus_service_property(_interface, signature="b",
1630
@dbus_service_property(_interface,
1600
1632
access="readwrite")
1601
1633
def CheckerRunning_dbus_property(self, value=None):
1602
1634
if value is None: # get
1612
1644
return self.dbus_object_path # is already a dbus.ObjectPath
1614
1646
# Secret = property
1615
@dbus_service_property(_interface, signature="ay",
1616
access="write", byte_arrays=True)
1647
@dbus_service_property(_interface,
1617
1651
def Secret_dbus_property(self, value):
1618
self.secret = str(value)
1652
self.secret = bytes(value)
1635
1669
if data[0] == 'data':
1637
1671
if data[0] == 'function':
1638
1673
def func(*args, **kwargs):
1639
1674
self._pipe.send(('funcall', name, args, kwargs))
1640
1675
return self._pipe.recv()[1]
1643
1679
def __setattr__(self, name, value):
1655
1691
def handle(self):
1656
1692
with contextlib.closing(self.server.child_pipe) as child_pipe:
1657
1693
logger.info("TCP connection from: %s",
1658
unicode(self.client_address))
1694
str(self.client_address))
1659
1695
logger.debug("Pipe FD: %d",
1660
1696
self.server.child_pipe.fileno())
1662
session = (gnutls.connection
1663
.ClientSession(self.request,
1665
.X509Credentials()))
1698
session = gnutls.connection.ClientSession(
1699
self.request, gnutls.connection .X509Credentials())
1667
1701
# Note: gnutls.connection.X509Credentials is really a
1668
1702
# generic GnuTLS certificate credentials object so long as
1677
1711
priority = self.server.gnutls_priority
1678
1712
if priority is None:
1679
1713
priority = "NORMAL"
1680
(gnutls.library.functions
1681
.gnutls_priority_set_direct(session._c_object,
1714
gnutls.library.functions.gnutls_priority_set_direct(
1715
session._c_object, priority, None)
1684
1717
# Start communication using the Mandos protocol
1685
1718
# Get protocol number
1780
1813
logger.warning("gnutls send failed",
1781
1814
exc_info=error)
1783
logger.debug("Sent: %d, remaining: %d",
1784
sent, len(client.secret)
1785
- (sent_size + sent))
1816
logger.debug("Sent: %d, remaining: %d", sent,
1817
len(client.secret) - (sent_size
1786
1819
sent_size += sent
1788
1821
logger.info("Sending secret to %s", client.name)
1805
1838
def peer_certificate(session):
1806
1839
"Return the peer's OpenPGP certificate as a bytestring"
1807
1840
# If not an OpenPGP certificate...
1808
if (gnutls.library.functions
1809
.gnutls_certificate_type_get(session._c_object)
1841
if (gnutls.library.functions.gnutls_certificate_type_get(
1810
1843
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1811
1844
# ...do the normal thing
1812
1845
return session.peer_certificate
1826
1859
def fingerprint(openpgp):
1827
1860
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1828
1861
# New GnuTLS "datum" with the OpenPGP public key
1829
datum = (gnutls.library.types
1830
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1833
ctypes.c_uint(len(openpgp))))
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)))
1834
1866
# New empty GnuTLS certificate
1835
1867
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1836
(gnutls.library.functions
1837
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1868
gnutls.library.functions.gnutls_openpgp_crt_init(
1838
1870
# Import the OpenPGP public key into the certificate
1839
(gnutls.library.functions
1840
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1841
gnutls.library.constants
1842
.GNUTLS_OPENPGP_FMT_RAW))
1871
gnutls.library.functions.gnutls_openpgp_crt_import(
1872
crt, ctypes.byref(datum),
1873
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1843
1874
# Verify the self signature in the key
1844
1875
crtverify = ctypes.c_uint()
1845
(gnutls.library.functions
1846
.gnutls_openpgp_crt_verify_self(crt, 0,
1847
ctypes.byref(crtverify)))
1876
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
crt, 0, ctypes.byref(crtverify))
1848
1878
if crtverify.value != 0:
1849
1879
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1850
raise (gnutls.errors.CertificateSecurityError
1880
raise gnutls.errors.CertificateSecurityError(
1852
1882
# New buffer for the fingerprint
1853
1883
buf = ctypes.create_string_buffer(20)
1854
1884
buf_len = ctypes.c_size_t()
1855
1885
# Get the fingerprint from the certificate into the buffer
1856
(gnutls.library.functions
1857
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1858
ctypes.byref(buf_len)))
1886
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1887
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1859
1888
# Deinit the certificate
1860
1889
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1861
1890
# Convert the buffer to a Python bytestring
1910
1941
interface: None or a network interface name (string)
1911
1942
use_ipv6: Boolean; to use IPv6 or not
1913
1945
def __init__(self, server_address, RequestHandlerClass,
1914
interface=None, use_ipv6=True, socketfd=None):
1915
1949
"""If socketfd is set, use that file descriptor instead of
1916
1950
creating a new one with socket.socket().
1958
1992
self.interface)
1961
self.socket.setsockopt(socket.SOL_SOCKET,
1963
str(self.interface + '\0'))
1995
self.socket.setsockopt(
1996
socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
(self.interface + "\0").encode("utf-8"))
1964
1998
except socket.error as error:
1965
1999
if error.errno == errno.EPERM:
1966
2000
logger.error("No permission to bind to"
1984
2018
self.server_address = (any_address,
1985
2019
self.server_address[1])
1986
2020
elif not self.server_address[1]:
1987
self.server_address = (self.server_address[0],
2021
self.server_address = (self.server_address[0], 0)
1989
2022
# if self.interface:
1990
2023
# self.server_address = (self.server_address[0],
2006
2039
Assumes a gobject.MainLoop event loop.
2008
2042
def __init__(self, server_address, RequestHandlerClass,
2009
interface=None, use_ipv6=True, clients=None,
2010
gnutls_priority=None, use_dbus=True, socketfd=None):
2046
gnutls_priority=None,
2011
2049
self.enabled = False
2012
2050
self.clients = clients
2013
2051
if self.clients is None:
2029
2068
def add_pipe(self, parent_pipe, proc):
2030
2069
# Call "handle_ipc" for both data and EOF events
2031
gobject.io_add_watch(parent_pipe.fileno(),
2032
gobject.IO_IN | gobject.IO_HUP,
2033
functools.partial(self.handle_ipc,
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,
2038
def handle_ipc(self, source, condition, parent_pipe=None,
2039
proc = None, client_object=None):
2077
def handle_ipc(self, source, condition,
2080
client_object=None):
2040
2081
# error, or the other end of multiprocessing.Pipe has closed
2041
2082
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2042
2083
# Wait for other process to exit
2065
2106
parent_pipe.send(False)
2068
gobject.io_add_watch(parent_pipe.fileno(),
2069
gobject.IO_IN | gobject.IO_HUP,
2070
functools.partial(self.handle_ipc,
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,
2115
client_object = client))
2076
2116
parent_pipe.send(True)
2077
2117
# remove the old hook in favor of the new above hook on
2085
2125
parent_pipe.send(('data', getattr(client_object,
2086
2126
funcname)(*args,
2089
2129
if command == 'getattr':
2090
2130
attrname = request[1]
2091
2131
if callable(client_object.__getattribute__(attrname)):
2092
parent_pipe.send(('function',))
2132
parent_pipe.send(('function', ))
2094
parent_pipe.send(('data', client_object
2095
.__getattribute__(attrname)))
2135
'data', client_object.__getattribute__(attrname)))
2097
2137
if command == 'setattr':
2098
2138
attrname = request[1]
2139
2179
"followers")) # Tokens valid after
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
2141
2186
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2142
2187
# the "duration" ABNF definition in RFC 3339, Appendix A.
2143
2188
token_end = Token(re.compile(r"$"), None, frozenset())
2144
2189
token_second = Token(re.compile(r"(\d+)S"),
2145
2190
datetime.timedelta(seconds=1),
2146
frozenset((token_end,)))
2191
frozenset((token_end, )))
2147
2192
token_minute = Token(re.compile(r"(\d+)M"),
2148
2193
datetime.timedelta(minutes=1),
2149
2194
frozenset((token_second, token_end)))
2165
2210
frozenset((token_month, token_end)))
2166
2211
token_week = Token(re.compile(r"(\d+)W"),
2167
2212
datetime.timedelta(weeks=1),
2168
frozenset((token_end,)))
2213
frozenset((token_end, )))
2169
2214
token_duration = Token(re.compile(r"P"), None,
2170
2215
frozenset((token_year, token_month,
2171
2216
token_day, token_time,
2262
2306
# Close all standard open file descriptors
2263
2307
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2264
2308
if not stat.S_ISCHR(os.fstat(null).st_mode):
2265
raise OSError(errno.ENODEV, "{} not a character device"
2309
raise OSError(errno.ENODEV,
2310
"{} not a character device"
2266
2311
.format(os.devnull))
2267
2312
os.dup2(null, sys.stdin.fileno())
2268
2313
os.dup2(null, sys.stdout.fileno())
2344
2390
"statedir": "/var/lib/mandos",
2345
2391
"foreground": "False",
2346
2392
"zeroconf": "True",
2349
2395
# Parse config file for server-global settings
2350
2396
server_config = configparser.SafeConfigParser(server_defaults)
2351
2397
del server_defaults
2352
server_config.read(os.path.join(options.configdir,
2398
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2354
2399
# Convert the SafeConfigParser object to a dict
2355
2400
server_settings = server_config.defaults()
2356
2401
# Use the appropriate methods on the non-string config options
2374
2419
# Override the settings from the config file with command line
2375
2420
# options, if set.
2376
2421
for option in ("interface", "address", "port", "debug",
2377
"priority", "servicename", "configdir",
2378
"use_dbus", "use_ipv6", "debuglevel", "restore",
2379
"statedir", "socket", "foreground", "zeroconf"):
2422
"priority", "servicename", "configdir", "use_dbus",
2423
"use_ipv6", "debuglevel", "restore", "statedir",
2424
"socket", "foreground", "zeroconf"):
2380
2425
value = getattr(options, option)
2381
2426
if value is not None:
2382
2427
server_settings[option] = value
2384
2429
# Force all strings to be unicode
2385
2430
for option in server_settings.keys():
2386
if type(server_settings[option]) is str:
2387
server_settings[option] = unicode(server_settings[option])
2431
if isinstance(server_settings[option], bytes):
2432
server_settings[option] = (server_settings[option]
2388
2434
# Force all boolean options to be boolean
2389
2435
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2390
2436
"foreground", "zeroconf"):
2397
2443
##################################################################
2399
if (not server_settings["zeroconf"] and
2400
not (server_settings["port"]
2401
or server_settings["socket"] != "")):
2402
parser.error("Needs port or socket to work without"
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")
2405
2450
# For convenience
2406
2451
debug = server_settings["debug"]
2422
2467
initlogger(debug, level)
2424
2469
if server_settings["servicename"] != "Mandos":
2425
syslogger.setFormatter(logging.Formatter
2426
('Mandos ({}) [%(process)d]:'
2427
' %(levelname)s: %(message)s'
2428
.format(server_settings
2470
syslogger.setFormatter(
2471
logging.Formatter('Mandos ({}) [%(process)d]:'
2472
' %(levelname)s: %(message)s'.format(
2473
server_settings["servicename"])))
2431
2475
# Parse config file with clients
2432
2476
client_config = configparser.SafeConfigParser(Client
2440
2484
socketfd = None
2441
2485
if server_settings["socket"] != "":
2442
2486
socketfd = server_settings["socket"]
2443
tcp_server = MandosServer((server_settings["address"],
2444
server_settings["port"]),
2446
interface=(server_settings["interface"]
2450
server_settings["priority"],
2487
tcp_server = MandosServer(
2488
(server_settings["address"], server_settings["port"]),
2490
interface=(server_settings["interface"] or None),
2492
gnutls_priority=server_settings["priority"],
2453
2495
if not foreground:
2454
2496
pidfilename = "/run/mandos.pid"
2455
2497
if not os.path.isdir("/run/."):
2489
2531
def debug_gnutls(level, string):
2490
2532
logger.debug("GnuTLS: %s", string[:-1])
2492
(gnutls.library.functions
2493
.gnutls_global_set_log_function(debug_gnutls))
2534
gnutls.library.functions.gnutls_global_set_log_function(
2495
2537
# Redirect stdin so all checkers get /dev/null
2496
2538
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2518
2560
bus_name = dbus.service.BusName("se.recompile.Mandos",
2519
bus, do_not_queue=True)
2520
old_bus_name = (dbus.service.BusName
2521
("se.bsnet.fukt.Mandos", bus,
2563
old_bus_name = dbus.service.BusName(
2564
"se.bsnet.fukt.Mandos", bus,
2523
2566
except dbus.exceptions.NameExistsException as e:
2524
2567
logger.error("Disabling D-Bus:", exc_info=e)
2525
2568
use_dbus = False
2527
2570
tcp_server.use_dbus = False
2529
2572
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2530
service = AvahiServiceToSyslog(name =
2531
server_settings["servicename"],
2532
servicetype = "_mandos._tcp",
2533
protocol = protocol, bus = bus)
2573
service = AvahiServiceToSyslog(
2574
name = server_settings["servicename"],
2575
servicetype = "_mandos._tcp",
2576
protocol = protocol,
2534
2578
if server_settings["interface"]:
2535
service.interface = (if_nametoindex
2536
(str(server_settings["interface"])))
2579
service.interface = if_nametoindex(
2580
server_settings["interface"].encode("utf-8"))
2538
2582
global multiprocessing_manager
2539
2583
multiprocessing_manager = multiprocessing.Manager()
2558
2602
if server_settings["restore"]:
2560
2604
with open(stored_state_path, "rb") as stored_state:
2561
clients_data, old_client_settings = (pickle.load
2605
clients_data, old_client_settings = pickle.load(
2563
2607
os.remove(stored_state_path)
2564
2608
except IOError as e:
2565
2609
if e.errno == errno.ENOENT:
2566
logger.warning("Could not load persistent state: {}"
2567
.format(os.strerror(e.errno)))
2610
logger.warning("Could not load persistent state:"
2611
" {}".format(os.strerror(e.errno)))
2569
2613
logger.critical("Could not load persistent state:",
2572
2616
except EOFError as e:
2573
2617
logger.warning("Could not load persistent state: "
2574
"EOFError:", exc_info=e)
2576
2621
with PGPEngine() as pgp:
2577
2622
for client_name, client in clients_data.items():
2606
2651
if not client["last_checked_ok"]:
2607
2652
logger.warning(
2608
2653
"disabling client {} - Client never "
2609
"performed a successful checker"
2610
.format(client_name))
2654
"performed a successful checker".format(
2611
2656
client["enabled"] = False
2612
2657
elif client["last_checker_status"] != 0:
2613
2658
logger.warning(
2614
2659
"disabling client {} - Client last"
2615
" checker failed with error code {}"
2616
.format(client_name,
2617
client["last_checker_status"]))
2660
" checker failed with error code"
2663
client["last_checker_status"]))
2618
2664
client["enabled"] = False
2620
client["expires"] = (datetime.datetime
2622
+ client["timeout"])
2666
client["expires"] = (
2667
datetime.datetime.utcnow()
2668
+ client["timeout"])
2623
2669
logger.debug("Last checker succeeded,"
2624
" keeping {} enabled"
2625
.format(client_name))
2670
" keeping {} enabled".format(
2627
client["secret"] = (
2628
pgp.decrypt(client["encrypted_secret"],
2629
client_settings[client_name]
2673
client["secret"] = pgp.decrypt(
2674
client["encrypted_secret"],
2675
client_settings[client_name]["secret"])
2631
2676
except PGPError:
2632
2677
# If decryption fails, we use secret from new settings
2633
logger.debug("Failed to decrypt {} old secret"
2634
.format(client_name))
2635
client["secret"] = (
2636
client_settings[client_name]["secret"])
2678
logger.debug("Failed to decrypt {} old secret".format(
2680
client["secret"] = (client_settings[client_name]
2638
2683
# Add/remove clients based on new changes made to config
2639
2684
for client_name in (set(old_client_settings)
2646
2691
# Create all client objects
2647
2692
for client_name, client in clients_data.items():
2648
2693
tcp_server.clients[client_name] = client_class(
2649
name = client_name, settings = client,
2650
2696
server_settings = server_settings)
2652
2698
if not tcp_server.clients:
2668
2714
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2671
@alternate_dbus_interfaces({"se.recompile.Mandos":
2672
"se.bsnet.fukt.Mandos"})
2718
@alternate_dbus_interfaces(
2719
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2673
2720
class MandosDBusService(DBusObjectWithProperties):
2674
2721
"""A D-Bus proxy object"""
2675
2723
def __init__(self):
2676
2724
dbus.service.Object.__init__(self, bus, "/")
2677
2726
_interface = "se.recompile.Mandos"
2679
2728
@dbus_interface_annotations(_interface)
2680
2729
def _foo(self):
2681
return { "org.freedesktop.DBus.Property"
2682
".EmitsChangedSignal":
2731
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2685
2734
@dbus.service.signal(_interface, signature="o")
2686
2735
def ClientAdded(self, objpath):
2709
2757
def GetAllClientsWithProperties(self):
2711
2759
return dbus.Dictionary(
2712
((c.dbus_object_path, c.GetAll(""))
2713
for c in tcp_server.clients.itervalues()),
2760
{ c.dbus_object_path: c.GetAll("")
2761
for c in tcp_server.clients.itervalues() },
2714
2762
signature="oa{sv}")
2716
2764
@dbus.service.method(_interface, in_signature="o")
2757
2805
exclude = { "bus", "changedstate", "secret",
2758
2806
"checker", "server_settings" }
2759
for name, typ in (inspect.getmembers
2760
(dbus.service.Object)):
2807
for name, typ in inspect.getmembers(dbus.service
2761
2809
exclude.add(name)
2763
2811
client_dict["encrypted_secret"] = (client
2770
2818
del client_settings[client.name]["secret"]
2773
with (tempfile.NamedTemporaryFile
2774
(mode='wb', suffix=".pickle", prefix='clients-',
2775
dir=os.path.dirname(stored_state_path),
2776
delete=False)) as stored_state:
2821
with tempfile.NamedTemporaryFile(
2825
dir=os.path.dirname(stored_state_path),
2826
delete=False) as stored_state:
2777
2827
pickle.dump((clients, client_settings), stored_state)
2778
tempname=stored_state.name
2828
tempname = stored_state.name
2779
2829
os.rename(tempname, stored_state_path)
2780
2830
except (IOError, OSError) as e: