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