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
114
115
def initlogger(debug, level=logging.WARNING):
115
116
"""init logger and add loglevel"""
117
119
syslogger = (logging.handlers.SysLogHandler
119
121
logging.handlers.SysLogHandler.LOG_DAEMON,
120
address = str("/dev/log")))
122
address = "/dev/log"))
121
123
syslogger.setFormatter(logging.Formatter
122
124
('Mandos [%(process)d]: %(levelname)s:'
223
225
class AvahiError(Exception):
224
226
def __init__(self, value, *args, **kwargs):
225
227
self.value = value
226
super(AvahiError, self).__init__(value, *args, **kwargs)
227
def __unicode__(self):
228
return unicode(repr(self.value))
228
return super(AvahiError, self).__init__(value, *args,
230
231
class AvahiServiceError(AvahiError):
281
282
" after %i retries, exiting.",
282
283
self.rename_count)
283
284
raise AvahiServiceError("Too many renames")
284
self.name = unicode(self.server
285
.GetAlternativeServiceName(self.name))
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
286
287
logger.info("Changing Zeroconf service name to %r ...",
337
338
elif state == avahi.ENTRY_GROUP_FAILURE:
338
339
logger.critical("Avahi: Error in group state changed %s",
340
raise AvahiGroupError("State changed: {0!s}"
341
raise AvahiGroupError("State changed: {!s}"
343
344
def cleanup(self):
394
395
"""Add the new name to the syslog messages"""
395
396
ret = AvahiService.rename(self)
396
397
syslogger.setFormatter(logging.Formatter
397
('Mandos ({0}) [%(process)d]:'
398
('Mandos ({}) [%(process)d]:'
398
399
' %(levelname)s: %(message)s'
399
400
.format(self.name)))
403
def timedelta_to_milliseconds(td):
404
"Convert a datetime.timedelta() to milliseconds"
405
return ((td.days * 24 * 60 * 60 * 1000)
406
+ (td.seconds * 1000)
407
+ (td.microseconds // 1000))
410
404
class Client(object):
411
405
"""A representation of a client host served by this server.
467
461
"enabled": "True",
470
def timeout_milliseconds(self):
471
"Return the 'timeout' attribute in milliseconds"
472
return timedelta_to_milliseconds(self.timeout)
474
def extended_timeout_milliseconds(self):
475
"Return the 'extended_timeout' attribute in milliseconds"
476
return timedelta_to_milliseconds(self.extended_timeout)
478
def interval_milliseconds(self):
479
"Return the 'interval' attribute in milliseconds"
480
return timedelta_to_milliseconds(self.interval)
482
def approval_delay_milliseconds(self):
483
return timedelta_to_milliseconds(self.approval_delay)
486
465
def config_parser(config):
487
466
"""Construct a new dict of client settings of this form:
512
491
"rb") as secfile:
513
492
client["secret"] = secfile.read()
515
raise TypeError("No secret or secfile for section {0}"
494
raise TypeError("No secret or secfile for section {}"
516
495
.format(section))
517
496
client["timeout"] = string_to_delta(section["timeout"])
518
497
client["extended_timeout"] = string_to_delta(
535
514
server_settings = {}
536
515
self.server_settings = server_settings
537
516
# adding all client settings
538
for setting, value in settings.iteritems():
517
for setting, value in settings.items():
539
518
setattr(self, setting, value)
624
603
if self.checker_initiator_tag is not None:
625
604
gobject.source_remove(self.checker_initiator_tag)
626
605
self.checker_initiator_tag = (gobject.timeout_add
627
(self.interval_milliseconds(),
607
.total_seconds() * 1000),
628
608
self.start_checker))
629
609
# Schedule a disable() when 'timeout' has passed
630
610
if self.disable_initiator_tag is not None:
631
611
gobject.source_remove(self.disable_initiator_tag)
632
612
self.disable_initiator_tag = (gobject.timeout_add
633
(self.timeout_milliseconds(),
614
.total_seconds() * 1000),
635
616
# Also start a new checker *right now*.
636
617
self.start_checker()
668
649
self.disable_initiator_tag = None
669
650
if getattr(self, "enabled", False):
670
651
self.disable_initiator_tag = (gobject.timeout_add
671
(timedelta_to_milliseconds
672
(timeout), self.disable))
652
(int(timeout.total_seconds()
653
* 1000), self.disable))
673
654
self.expires = datetime.datetime.utcnow() + timeout
675
656
def need_approval(self):
706
687
# Start a new checker if needed
707
688
if self.checker is None:
708
689
# Escape attributes for the shell
709
escaped_attrs = dict(
710
(attr, re.escape(unicode(getattr(self, attr))))
712
self.runtime_expansions)
690
escaped_attrs = { attr:
691
re.escape(str(getattr(self, attr)))
692
for attr in self.runtime_expansions }
714
694
command = self.checker_command % escaped_attrs
715
695
except TypeError as error:
796
776
# "Set" method, so we fail early here:
797
777
if byte_arrays and signature != "ay":
798
778
raise ValueError("Byte arrays not supported for non-'ay'"
799
" signature {0!r}".format(signature))
779
" signature {!r}".format(signature))
800
780
def decorator(func):
801
781
func._dbus_is_property = True
802
782
func._dbus_interface = dbus_interface
833
813
"""Decorator to annotate D-Bus methods, signals or properties
816
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
817
"org.freedesktop.DBus.Property."
818
"EmitsChangedSignal": "false"})
836
819
@dbus_service_property("org.example.Interface", signature="b",
838
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
839
"org.freedesktop.DBus.Property."
840
"EmitsChangedSignal": "false"})
841
821
def Property_dbus_property(self):
842
822
return dbus.Boolean(False)
850
830
class DBusPropertyException(dbus.exceptions.DBusException):
851
831
"""A base class for D-Bus property-related exceptions
853
def __unicode__(self):
854
return unicode(str(self))
857
835
class DBusPropertyAccessException(DBusPropertyException):
858
836
"""A property's access permissions disallows an operation.
881
859
If called like _is_dbus_thing("method") it returns a function
882
860
suitable for use as predicate to inspect.getmembers().
884
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
862
return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
887
865
def _get_all_dbus_things(self, thing):
937
915
# signatures other than "ay".
938
916
if prop._dbus_signature != "ay":
939
917
raise ValueError("Byte arrays not supported for non-"
940
"'ay' signature {0!r}"
918
"'ay' signature {!r}"
941
919
.format(prop._dbus_signature))
942
920
value = dbus.ByteArray(b''.join(chr(byte)
943
921
for byte in value))
968
946
value.variant_level+1)
969
947
return dbus.Dictionary(properties, signature="sv")
949
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
950
def PropertiesChanged(self, interface_name, changed_properties,
951
invalidated_properties):
952
"""Standard D-Bus PropertiesChanged() signal, see D-Bus
971
957
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
972
958
out_signature="s",
973
959
path_keyword='object_path',
1009
995
"_dbus_annotations",
1011
for name, value in annots.iteritems():
997
for name, value in annots.items():
1012
998
ann_tag = document.createElement(
1014
1000
ann_tag.setAttribute("name", name)
1017
1003
# Add interface annotation tags
1018
1004
for annotation, value in dict(
1019
1005
itertools.chain.from_iterable(
1020
annotations().iteritems()
1006
annotations().items()
1021
1007
for name, annotations in
1022
1008
self._get_all_dbus_things("interface")
1023
1009
if name == if_tag.getAttribute("name")
1025
1011
ann_tag = document.createElement("annotation")
1026
1012
ann_tag.setAttribute("name", annotation)
1027
1013
ann_tag.setAttribute("value", value)
1084
1070
def wrapper(cls):
1085
1071
for orig_interface_name, alt_interface_name in (
1086
alt_interface_names.iteritems()):
1072
alt_interface_names.items()):
1088
1074
interface_names = set()
1089
1075
# Go though all attributes of the class
1206
1192
attribute.func_closure)))
1208
1194
# Deprecate all alternate interfaces
1209
iname="_AlternateDBusNames_interface_annotation{0}"
1195
iname="_AlternateDBusNames_interface_annotation{}"
1210
1196
for interface_name in interface_names:
1211
1197
@dbus_interface_annotations(interface_name)
1212
1198
def func(self):
1221
1207
if interface_names:
1222
1208
# Replace the class with a new subclass of it with
1223
1209
# methods, signals, etc. as created above.
1224
cls = type(b"{0}Alternate".format(cls.__name__),
1210
cls = type(b"{}Alternate".format(cls.__name__),
1240
1226
runtime_expansions = (Client.runtime_expansions
1241
1227
+ ("dbus_object_path",))
1229
_interface = "se.recompile.Mandos.Client"
1243
1231
# dbus.service.Object doesn't use super(), so we can't either.
1245
1233
def __init__(self, bus = None, *args, **kwargs):
1247
1235
Client.__init__(self, *args, **kwargs)
1248
1236
# Only now, when this client is initialized, can it show up on
1250
client_object_name = unicode(self.name).translate(
1238
client_object_name = str(self.name).translate(
1251
1239
{ord("."): ord("_"),
1252
1240
ord("-"): ord("_")})
1253
1241
self.dbus_object_path = (dbus.ObjectPath
1258
1246
def notifychangeproperty(transform_func,
1259
1247
dbus_name, type_func=lambda x: x,
1248
variant_level=1, invalidate_only=False,
1249
_interface=_interface):
1261
1250
""" Modify a variable so that it's a property which announces
1262
1251
its changes to DBus.
1268
1257
to the D-Bus. Default: no transform
1269
1258
variant_level: D-Bus variant level. Default: 1
1271
attrname = "_{0}".format(dbus_name)
1260
attrname = "_{}".format(dbus_name)
1272
1261
def setter(self, value):
1273
1262
if hasattr(self, "dbus_object_path"):
1274
1263
if (not hasattr(self, attrname) or
1275
1264
type_func(getattr(self, attrname, None))
1276
1265
!= type_func(value)):
1277
dbus_value = transform_func(type_func(value),
1280
self.PropertyChanged(dbus.String(dbus_name),
1267
self.PropertiesChanged(_interface,
1272
dbus_value = transform_func(type_func(value),
1275
self.PropertyChanged(dbus.String(dbus_name),
1277
self.PropertiesChanged(_interface,
1279
dbus.String(dbus_name):
1280
dbus_value }), dbus.Array())
1282
1281
setattr(self, attrname, value)
1284
1283
return property(lambda self: getattr(self, attrname), setter)
1304
1303
approval_delay = notifychangeproperty(dbus.UInt64,
1305
1304
"ApprovalDelay",
1307
timedelta_to_milliseconds)
1306
lambda td: td.total_seconds()
1308
1308
approval_duration = notifychangeproperty(
1309
1309
dbus.UInt64, "ApprovalDuration",
1310
type_func = timedelta_to_milliseconds)
1310
type_func = lambda td: td.total_seconds() * 1000)
1311
1311
host = notifychangeproperty(dbus.String, "Host")
1312
1312
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1314
timedelta_to_milliseconds)
1313
type_func = lambda td:
1314
td.total_seconds() * 1000)
1315
1315
extended_timeout = notifychangeproperty(
1316
1316
dbus.UInt64, "ExtendedTimeout",
1317
type_func = timedelta_to_milliseconds)
1317
type_func = lambda td: td.total_seconds() * 1000)
1318
1318
interval = notifychangeproperty(dbus.UInt64,
1321
timedelta_to_milliseconds)
1321
lambda td: td.total_seconds()
1322
1323
checker_command = notifychangeproperty(dbus.String, "Checker")
1324
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1325
invalidate_only=True)
1324
1327
del notifychangeproperty
1368
1371
def approve(self, value=True):
1369
1372
self.approved = value
1370
gobject.timeout_add(timedelta_to_milliseconds
1371
(self.approval_duration),
1372
self._reset_approved)
1373
gobject.timeout_add(int(self.approval_duration.total_seconds()
1374
* 1000), self._reset_approved)
1373
1375
self.send_changedstate()
1375
1377
## D-Bus methods, signals & properties
1376
_interface = "se.recompile.Mandos.Client"
1380
@dbus_interface_annotations(_interface)
1382
return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1387
1383
# CheckerCompleted - signal
1399
1395
# PropertyChanged - signal
1396
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1400
1397
@dbus.service.signal(_interface, signature="sv")
1401
1398
def PropertyChanged(self, property, value):
1478
1475
access="readwrite")
1479
1476
def ApprovalDelay_dbus_property(self, value=None):
1480
1477
if value is None: # get
1481
return dbus.UInt64(self.approval_delay_milliseconds())
1478
return dbus.UInt64(self.approval_delay.total_seconds()
1482
1480
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1484
1482
# ApprovalDuration - property
1486
1484
access="readwrite")
1487
1485
def ApprovalDuration_dbus_property(self, value=None):
1488
1486
if value is None: # get
1489
return dbus.UInt64(timedelta_to_milliseconds(
1490
self.approval_duration))
1487
return dbus.UInt64(self.approval_duration.total_seconds()
1491
1489
self.approval_duration = datetime.timedelta(0, 0, 0, value)
1493
1491
# Name - property
1506
1504
def Host_dbus_property(self, value=None):
1507
1505
if value is None: # get
1508
1506
return dbus.String(self.host)
1509
self.host = unicode(value)
1507
self.host = str(value)
1511
1509
# Created - property
1512
1510
@dbus_service_property(_interface, signature="s", access="read")
1559
1557
access="readwrite")
1560
1558
def Timeout_dbus_property(self, value=None):
1561
1559
if value is None: # get
1562
return dbus.UInt64(self.timeout_milliseconds())
1560
return dbus.UInt64(self.timeout.total_seconds() * 1000)
1563
1561
old_timeout = self.timeout
1564
1562
self.timeout = datetime.timedelta(0, 0, 0, value)
1565
1563
# Reschedule disabling
1576
1574
gobject.source_remove(self.disable_initiator_tag)
1577
1575
self.disable_initiator_tag = (
1578
1576
gobject.timeout_add(
1579
timedelta_to_milliseconds(self.expires - now),
1577
int((self.expires - now).total_seconds()
1578
* 1000), self.disable))
1582
1580
# ExtendedTimeout - property
1583
1581
@dbus_service_property(_interface, signature="t",
1584
1582
access="readwrite")
1585
1583
def ExtendedTimeout_dbus_property(self, value=None):
1586
1584
if value is None: # get
1587
return dbus.UInt64(self.extended_timeout_milliseconds())
1585
return dbus.UInt64(self.extended_timeout.total_seconds()
1588
1587
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1590
1589
# Interval - property
1592
1591
access="readwrite")
1593
1592
def Interval_dbus_property(self, value=None):
1594
1593
if value is None: # get
1595
return dbus.UInt64(self.interval_milliseconds())
1594
return dbus.UInt64(self.interval.total_seconds() * 1000)
1596
1595
self.interval = datetime.timedelta(0, 0, 0, value)
1597
1596
if getattr(self, "checker_initiator_tag", None) is None:
1609
1608
def Checker_dbus_property(self, value=None):
1610
1609
if value is None: # get
1611
1610
return dbus.String(self.checker_command)
1612
self.checker_command = unicode(value)
1611
self.checker_command = str(value)
1614
1613
# CheckerRunning - property
1615
1614
@dbus_service_property(_interface, signature="b",
1631
1630
@dbus_service_property(_interface, signature="ay",
1632
1631
access="write", byte_arrays=True)
1633
1632
def Secret_dbus_property(self, value):
1634
self.secret = str(value)
1633
self.secret = bytes(value)
1671
1670
def handle(self):
1672
1671
with contextlib.closing(self.server.child_pipe) as child_pipe:
1673
1672
logger.info("TCP connection from: %s",
1674
unicode(self.client_address))
1673
str(self.client_address))
1675
1674
logger.debug("Pipe FD: %d",
1676
1675
self.server.child_pipe.fileno())
1758
1757
if self.server.use_dbus:
1759
1758
# Emit D-Bus signal
1760
1759
client.NeedApproval(
1761
client.approval_delay_milliseconds(),
1762
client.approved_by_default)
1760
client.approval_delay.total_seconds()
1761
* 1000, client.approved_by_default)
1764
1763
logger.warning("Client %s was not approved",
1771
1770
#wait until timeout or approved
1772
1771
time = datetime.datetime.now()
1773
1772
client.changedstate.acquire()
1774
client.changedstate.wait(
1775
float(timedelta_to_milliseconds(delay)
1773
client.changedstate.wait(delay.total_seconds())
1777
1774
client.changedstate.release()
1778
1775
time2 = datetime.datetime.now()
1779
1776
if (time2 - time) >= delay:
1979
1976
self.socket.setsockopt(socket.SOL_SOCKET,
1980
1977
SO_BINDTODEVICE,
1981
str(self.interface + '\0'))
1978
(self.interface + "\0")
1982
1980
except socket.error as error:
1983
1981
if error.errno == errno.EPERM:
1984
1982
logger.error("No permission to bind to"
2187
2185
token_duration = Token(re.compile(r"P"), None,
2188
2186
frozenset((token_year, token_month,
2189
2187
token_day, token_time,
2191
2189
# Define starting values
2192
2190
value = datetime.timedelta() # Value so far
2193
2191
found_token = None
2194
followers = frozenset(token_duration,) # Following valid tokens
2192
followers = frozenset((token_duration,)) # Following valid tokens
2195
2193
s = duration # String left to parse
2196
2194
# Loop until end token is found
2197
2195
while found_token is not token_end:
2257
2255
elif suffix == "w":
2258
2256
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2260
raise ValueError("Unknown suffix {0!r}"
2258
raise ValueError("Unknown suffix {!r}"
2261
2259
.format(suffix))
2262
2260
except IndexError as e:
2263
2261
raise ValueError(*(e.args))
2280
2278
# Close all standard open file descriptors
2281
2279
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2282
2280
if not stat.S_ISCHR(os.fstat(null).st_mode):
2283
raise OSError(errno.ENODEV,
2284
"{0} not a character device"
2281
raise OSError(errno.ENODEV, "{} not a character device"
2285
2282
.format(os.devnull))
2286
2283
os.dup2(null, sys.stdin.fileno())
2287
2284
os.dup2(null, sys.stdout.fileno())
2298
2295
parser = argparse.ArgumentParser()
2299
2296
parser.add_argument("-v", "--version", action="version",
2300
version = "%(prog)s {0}".format(version),
2297
version = "%(prog)s {}".format(version),
2301
2298
help="show version number and exit")
2302
2299
parser.add_argument("-i", "--interface", metavar="IF",
2303
2300
help="Bind to interface IF")
2336
2333
help="Directory to save/restore state in")
2337
2334
parser.add_argument("--foreground", action="store_true",
2338
2335
help="Run in foreground", default=None)
2336
parser.add_argument("--no-zeroconf", action="store_false",
2337
dest="zeroconf", help="Do not use Zeroconf",
2340
2340
options = parser.parse_args()
2391
2392
for option in ("interface", "address", "port", "debug",
2392
2393
"priority", "servicename", "configdir",
2393
2394
"use_dbus", "use_ipv6", "debuglevel", "restore",
2394
"statedir", "socket", "foreground"):
2395
"statedir", "socket", "foreground", "zeroconf"):
2395
2396
value = getattr(options, option)
2396
2397
if value is not None:
2397
2398
server_settings[option] = value
2399
2400
# Force all strings to be unicode
2400
2401
for option in server_settings.keys():
2401
if type(server_settings[option]) is str:
2402
server_settings[option] = unicode(server_settings[option])
2402
if isinstance(server_settings[option], bytes):
2403
server_settings[option] = (server_settings[option]
2403
2405
# Force all boolean options to be boolean
2404
2406
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2407
"foreground", "zeroconf"):
2406
2408
server_settings[option] = bool(server_settings[option])
2407
2409
# Debug implies foreground
2408
2410
if server_settings["debug"]:
2412
2414
##################################################################
2416
if (not server_settings["zeroconf"] and
2417
not (server_settings["port"]
2418
or server_settings["socket"] != "")):
2419
parser.error("Needs port or socket to work without"
2414
2422
# For convenience
2415
2423
debug = server_settings["debug"]
2416
2424
debuglevel = server_settings["debuglevel"]
2419
2427
stored_state_path = os.path.join(server_settings["statedir"],
2420
2428
stored_state_file)
2421
2429
foreground = server_settings["foreground"]
2430
zeroconf = server_settings["zeroconf"]
2424
2433
initlogger(debug, logging.DEBUG)
2432
2441
if server_settings["servicename"] != "Mandos":
2433
2442
syslogger.setFormatter(logging.Formatter
2434
('Mandos ({0}) [%(process)d]:'
2443
('Mandos ({}) [%(process)d]:'
2435
2444
' %(levelname)s: %(message)s'
2436
2445
.format(server_settings
2437
2446
["servicename"])))
2445
2454
global mandos_dbus_service
2446
2455
mandos_dbus_service = None
2458
if server_settings["socket"] != "":
2459
socketfd = server_settings["socket"]
2448
2460
tcp_server = MandosServer((server_settings["address"],
2449
2461
server_settings["port"]),
2454
2466
gnutls_priority=
2455
2467
server_settings["priority"],
2456
2468
use_dbus=use_dbus,
2457
socketfd=(server_settings["socket"]
2459
2470
if not foreground:
2460
2471
pidfilename = "/run/mandos.pid"
2461
2472
if not os.path.isdir("/run/."):
2531
2542
use_dbus = False
2532
2543
server_settings["use_dbus"] = False
2533
2544
tcp_server.use_dbus = False
2534
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2535
service = AvahiServiceToSyslog(name =
2536
server_settings["servicename"],
2537
servicetype = "_mandos._tcp",
2538
protocol = protocol, bus = bus)
2539
if server_settings["interface"]:
2540
service.interface = (if_nametoindex
2541
(str(server_settings["interface"])))
2546
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2547
service = AvahiServiceToSyslog(name =
2548
server_settings["servicename"],
2549
servicetype = "_mandos._tcp",
2550
protocol = protocol, bus = bus)
2551
if server_settings["interface"]:
2552
service.interface = (if_nametoindex
2553
(server_settings["interface"]
2543
2556
global multiprocessing_manager
2544
2557
multiprocessing_manager = multiprocessing.Manager()
2568
2581
os.remove(stored_state_path)
2569
2582
except IOError as e:
2570
2583
if e.errno == errno.ENOENT:
2571
logger.warning("Could not load persistent state: {0}"
2584
logger.warning("Could not load persistent state: {}"
2572
2585
.format(os.strerror(e.errno)))
2574
2587
logger.critical("Could not load persistent state:",
2610
2623
if datetime.datetime.utcnow() >= client["expires"]:
2611
2624
if not client["last_checked_ok"]:
2612
2625
logger.warning(
2613
"disabling client {0} - Client never "
2626
"disabling client {} - Client never "
2614
2627
"performed a successful checker"
2615
2628
.format(client_name))
2616
2629
client["enabled"] = False
2617
2630
elif client["last_checker_status"] != 0:
2618
2631
logger.warning(
2619
"disabling client {0} - Client "
2620
"last checker failed with error code {1}"
2632
"disabling client {} - Client last"
2633
" checker failed with error code {}"
2621
2634
.format(client_name,
2622
2635
client["last_checker_status"]))
2623
2636
client["enabled"] = False
2636
2649
except PGPError:
2637
2650
# If decryption fails, we use secret from new settings
2638
logger.debug("Failed to decrypt {0} old secret"
2651
logger.debug("Failed to decrypt {} old secret"
2639
2652
.format(client_name))
2640
2653
client["secret"] = (
2641
2654
client_settings[client_name]["secret"])
2649
2662
clients_data[client_name] = client_settings[client_name]
2651
2664
# Create all client objects
2652
for client_name, client in clients_data.iteritems():
2665
for client_name, client in clients_data.items():
2653
2666
tcp_server.clients[client_name] = client_class(
2654
2667
name = client_name, settings = client,
2655
2668
server_settings = server_settings)
2714
2727
def GetAllClientsWithProperties(self):
2716
2729
return dbus.Dictionary(
2717
((c.dbus_object_path, c.GetAll(""))
2718
for c in tcp_server.clients.itervalues()),
2730
{ c.dbus_object_path: c.GetAll("")
2731
for c in tcp_server.clients.itervalues() },
2719
2732
signature="oa{sv}")
2721
2734
@dbus.service.method(_interface, in_signature="o")
2759
2773
# A list of attributes that can not be pickled
2761
exclude = set(("bus", "changedstate", "secret",
2762
"checker", "server_settings"))
2775
exclude = { "bus", "changedstate", "secret",
2776
"checker", "server_settings" }
2763
2777
for name, typ in (inspect.getmembers
2764
2778
(dbus.service.Object)):
2765
2779
exclude.add(name)
2788
2802
except NameError:
2790
2804
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2791
logger.warning("Could not save persistent state: {0}"
2805
logger.warning("Could not save persistent state: {}"
2792
2806
.format(os.strerror(e.errno)))
2794
2808
logger.warning("Could not save persistent state:",
2823
2837
tcp_server.server_activate()
2825
2839
# Find out what port we got
2826
service.port = tcp_server.socket.getsockname()[1]
2841
service.port = tcp_server.socket.getsockname()[1]
2828
2843
logger.info("Now listening on address %r, port %d,"
2829
2844
" flowinfo %d, scope_id %d",
2835
2850
#service.interface = tcp_server.socket.getsockname()[3]
2838
# From the Avahi example code
2841
except dbus.exceptions.DBusException as error:
2842
logger.critical("D-Bus Exception", exc_info=error)
2845
# End of Avahi example code
2854
# From the Avahi example code
2857
except dbus.exceptions.DBusException as error:
2858
logger.critical("D-Bus Exception", exc_info=error)
2861
# End of Avahi example code
2847
2863
gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2848
2864
lambda *args, **kwargs: