/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2014-08-09 13:18:46 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 323.
  • Revision ID: teddy@recompile.se-20140809131846-2emd272mf9c9wihe
mandos: Replace unicode() with str().

This is in preparation for the coming Python 3 conversion.

* mandos: Replace "str" with "unicode".  All callers changed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
 
1
#!/usr/bin/python2.7
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
88
88
    except ImportError:
89
89
        SO_BINDTODEVICE = None
90
90
 
91
 
version = "1.6.6"
 
91
if sys.version_info.major == 2:
 
92
    str = unicode
 
93
 
 
94
version = "1.6.8"
92
95
stored_state_file = "clients.pickle"
93
96
 
94
97
logger = logging.getLogger()
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"),
108
 
                                            interface))
109
 
        interface_index = struct.unpack(str("I"),
110
 
                                        ifreq[16:20])[0]
 
110
                                struct.pack(b"16s16x", interface))
 
111
        interface_index = struct.unpack("I", ifreq[16:20])[0]
111
112
        return interface_index
112
113
 
113
114
 
118
119
    syslogger = (logging.handlers.SysLogHandler
119
120
                 (facility =
120
121
                  logging.handlers.SysLogHandler.LOG_DAEMON,
121
 
                  address = str("/dev/log")))
 
122
                  address = "/dev/log"))
122
123
    syslogger.setFormatter(logging.Formatter
123
124
                           ('Mandos [%(process)d]: %(levelname)s:'
124
125
                            ' %(message)s'))
224
225
class AvahiError(Exception):
225
226
    def __init__(self, value, *args, **kwargs):
226
227
        self.value = value
227
 
        super(AvahiError, self).__init__(value, *args, **kwargs)
228
 
    def __unicode__(self):
229
 
        return unicode(repr(self.value))
 
228
        return super(AvahiError, self).__init__(value, *args,
 
229
                                                **kwargs)
230
230
 
231
231
class AvahiServiceError(AvahiError):
232
232
    pass
282
282
                            " after %i retries, exiting.",
283
283
                            self.rename_count)
284
284
            raise AvahiServiceError("Too many renames")
285
 
        self.name = unicode(self.server
286
 
                            .GetAlternativeServiceName(self.name))
 
285
        self.name = str(self.server
 
286
                        .GetAlternativeServiceName(self.name))
287
287
        logger.info("Changing Zeroconf service name to %r ...",
288
288
                    self.name)
289
289
        self.remove()
337
337
            self.rename()
338
338
        elif state == avahi.ENTRY_GROUP_FAILURE:
339
339
            logger.critical("Avahi: Error in group state changed %s",
340
 
                            unicode(error))
341
 
            raise AvahiGroupError("State changed: {0!s}"
 
340
                            str(error))
 
341
            raise AvahiGroupError("State changed: {!s}"
342
342
                                  .format(error))
343
343
    
344
344
    def cleanup(self):
395
395
        """Add the new name to the syslog messages"""
396
396
        ret = AvahiService.rename(self)
397
397
        syslogger.setFormatter(logging.Formatter
398
 
                               ('Mandos ({0}) [%(process)d]:'
 
398
                               ('Mandos ({}) [%(process)d]:'
399
399
                                ' %(levelname)s: %(message)s'
400
400
                                .format(self.name)))
401
401
        return ret
402
402
 
403
403
 
404
 
def timedelta_to_milliseconds(td):
405
 
    "Convert a datetime.timedelta() to milliseconds"
406
 
    return ((td.days * 24 * 60 * 60 * 1000)
407
 
            + (td.seconds * 1000)
408
 
            + (td.microseconds // 1000))
409
 
 
410
 
 
411
404
class Client(object):
412
405
    """A representation of a client host served by this server.
413
406
    
468
461
                        "enabled": "True",
469
462
                        }
470
463
    
471
 
    def timeout_milliseconds(self):
472
 
        "Return the 'timeout' attribute in milliseconds"
473
 
        return timedelta_to_milliseconds(self.timeout)
474
 
    
475
 
    def extended_timeout_milliseconds(self):
476
 
        "Return the 'extended_timeout' attribute in milliseconds"
477
 
        return timedelta_to_milliseconds(self.extended_timeout)
478
 
    
479
 
    def interval_milliseconds(self):
480
 
        "Return the 'interval' attribute in milliseconds"
481
 
        return timedelta_to_milliseconds(self.interval)
482
 
    
483
 
    def approval_delay_milliseconds(self):
484
 
        return timedelta_to_milliseconds(self.approval_delay)
485
 
    
486
464
    @staticmethod
487
465
    def config_parser(config):
488
466
        """Construct a new dict of client settings of this form:
513
491
                          "rb") as secfile:
514
492
                    client["secret"] = secfile.read()
515
493
            else:
516
 
                raise TypeError("No secret or secfile for section {0}"
 
494
                raise TypeError("No secret or secfile for section {}"
517
495
                                .format(section))
518
496
            client["timeout"] = string_to_delta(section["timeout"])
519
497
            client["extended_timeout"] = string_to_delta(
536
514
            server_settings = {}
537
515
        self.server_settings = server_settings
538
516
        # adding all client settings
539
 
        for setting, value in settings.iteritems():
 
517
        for setting, value in settings.items():
540
518
            setattr(self, setting, value)
541
519
        
542
520
        if self.enabled:
625
603
        if self.checker_initiator_tag is not None:
626
604
            gobject.source_remove(self.checker_initiator_tag)
627
605
        self.checker_initiator_tag = (gobject.timeout_add
628
 
                                      (self.interval_milliseconds(),
 
606
                                      (int(self.interval
 
607
                                           .total_seconds() * 1000),
629
608
                                       self.start_checker))
630
609
        # Schedule a disable() when 'timeout' has passed
631
610
        if self.disable_initiator_tag is not None:
632
611
            gobject.source_remove(self.disable_initiator_tag)
633
612
        self.disable_initiator_tag = (gobject.timeout_add
634
 
                                   (self.timeout_milliseconds(),
635
 
                                    self.disable))
 
613
                                      (int(self.timeout
 
614
                                           .total_seconds() * 1000),
 
615
                                       self.disable))
636
616
        # Also start a new checker *right now*.
637
617
        self.start_checker()
638
618
    
669
649
            self.disable_initiator_tag = None
670
650
        if getattr(self, "enabled", False):
671
651
            self.disable_initiator_tag = (gobject.timeout_add
672
 
                                          (timedelta_to_milliseconds
673
 
                                           (timeout), self.disable))
 
652
                                          (int(timeout.total_seconds()
 
653
                                               * 1000), self.disable))
674
654
            self.expires = datetime.datetime.utcnow() + timeout
675
655
    
676
656
    def need_approval(self):
707
687
        # Start a new checker if needed
708
688
        if self.checker is None:
709
689
            # Escape attributes for the shell
710
 
            escaped_attrs = dict(
711
 
                (attr, re.escape(unicode(getattr(self, attr))))
712
 
                for attr in
713
 
                self.runtime_expansions)
 
690
            escaped_attrs = { attr:
 
691
                                  re.escape(str(getattr(self, attr)))
 
692
                              for attr in self.runtime_expansions }
714
693
            try:
715
694
                command = self.checker_command % escaped_attrs
716
695
            except TypeError as error:
797
776
    # "Set" method, so we fail early here:
798
777
    if byte_arrays and signature != "ay":
799
778
        raise ValueError("Byte arrays not supported for non-'ay'"
800
 
                         " signature {0!r}".format(signature))
 
779
                         " signature {!r}".format(signature))
801
780
    def decorator(func):
802
781
        func._dbus_is_property = True
803
782
        func._dbus_interface = dbus_interface
851
830
class DBusPropertyException(dbus.exceptions.DBusException):
852
831
    """A base class for D-Bus property-related exceptions
853
832
    """
854
 
    def __unicode__(self):
855
 
        return unicode(str(self))
856
 
 
 
833
    pass
857
834
 
858
835
class DBusPropertyAccessException(DBusPropertyException):
859
836
    """A property's access permissions disallows an operation.
882
859
        If called like _is_dbus_thing("method") it returns a function
883
860
        suitable for use as predicate to inspect.getmembers().
884
861
        """
885
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
 
862
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
886
863
                                   False)
887
864
    
888
865
    def _get_all_dbus_things(self, thing):
938
915
            # signatures other than "ay".
939
916
            if prop._dbus_signature != "ay":
940
917
                raise ValueError("Byte arrays not supported for non-"
941
 
                                 "'ay' signature {0!r}"
 
918
                                 "'ay' signature {!r}"
942
919
                                 .format(prop._dbus_signature))
943
920
            value = dbus.ByteArray(b''.join(chr(byte)
944
921
                                            for byte in value))
1009
986
                                              (prop,
1010
987
                                               "_dbus_annotations",
1011
988
                                               {}))
1012
 
                        for name, value in annots.iteritems():
 
989
                        for name, value in annots.items():
1013
990
                            ann_tag = document.createElement(
1014
991
                                "annotation")
1015
992
                            ann_tag.setAttribute("name", name)
1018
995
                # Add interface annotation tags
1019
996
                for annotation, value in dict(
1020
997
                    itertools.chain.from_iterable(
1021
 
                        annotations().iteritems()
 
998
                        annotations().items()
1022
999
                        for name, annotations in
1023
1000
                        self._get_all_dbus_things("interface")
1024
1001
                        if name == if_tag.getAttribute("name")
1025
 
                        )).iteritems():
 
1002
                        )).items():
1026
1003
                    ann_tag = document.createElement("annotation")
1027
1004
                    ann_tag.setAttribute("name", annotation)
1028
1005
                    ann_tag.setAttribute("value", value)
1084
1061
    """
1085
1062
    def wrapper(cls):
1086
1063
        for orig_interface_name, alt_interface_name in (
1087
 
            alt_interface_names.iteritems()):
 
1064
            alt_interface_names.items()):
1088
1065
            attr = {}
1089
1066
            interface_names = set()
1090
1067
            # Go though all attributes of the class
1207
1184
                                        attribute.func_closure)))
1208
1185
            if deprecate:
1209
1186
                # Deprecate all alternate interfaces
1210
 
                iname="_AlternateDBusNames_interface_annotation{0}"
 
1187
                iname="_AlternateDBusNames_interface_annotation{}"
1211
1188
                for interface_name in interface_names:
1212
1189
                    @dbus_interface_annotations(interface_name)
1213
1190
                    def func(self):
1222
1199
            if interface_names:
1223
1200
                # Replace the class with a new subclass of it with
1224
1201
                # methods, signals, etc. as created above.
1225
 
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1202
                cls = type(b"{}Alternate".format(cls.__name__),
1226
1203
                           (cls,), attr)
1227
1204
        return cls
1228
1205
    return wrapper
1248
1225
        Client.__init__(self, *args, **kwargs)
1249
1226
        # Only now, when this client is initialized, can it show up on
1250
1227
        # the D-Bus
1251
 
        client_object_name = unicode(self.name).translate(
 
1228
        client_object_name = str(self.name).translate(
1252
1229
            {ord("."): ord("_"),
1253
1230
             ord("-"): ord("_")})
1254
1231
        self.dbus_object_path = (dbus.ObjectPath
1269
1246
                   to the D-Bus.  Default: no transform
1270
1247
        variant_level: D-Bus variant level.  Default: 1
1271
1248
        """
1272
 
        attrname = "_{0}".format(dbus_name)
 
1249
        attrname = "_{}".format(dbus_name)
1273
1250
        def setter(self, value):
1274
1251
            if hasattr(self, "dbus_object_path"):
1275
1252
                if (not hasattr(self, attrname) or
1305
1282
    approval_delay = notifychangeproperty(dbus.UInt64,
1306
1283
                                          "ApprovalDelay",
1307
1284
                                          type_func =
1308
 
                                          timedelta_to_milliseconds)
 
1285
                                          lambda td: td.total_seconds()
 
1286
                                          * 1000)
1309
1287
    approval_duration = notifychangeproperty(
1310
1288
        dbus.UInt64, "ApprovalDuration",
1311
 
        type_func = timedelta_to_milliseconds)
 
1289
        type_func = lambda td: td.total_seconds() * 1000)
1312
1290
    host = notifychangeproperty(dbus.String, "Host")
1313
1291
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1314
 
                                   type_func =
1315
 
                                   timedelta_to_milliseconds)
 
1292
                                   type_func = lambda td:
 
1293
                                       td.total_seconds() * 1000)
1316
1294
    extended_timeout = notifychangeproperty(
1317
1295
        dbus.UInt64, "ExtendedTimeout",
1318
 
        type_func = timedelta_to_milliseconds)
 
1296
        type_func = lambda td: td.total_seconds() * 1000)
1319
1297
    interval = notifychangeproperty(dbus.UInt64,
1320
1298
                                    "Interval",
1321
1299
                                    type_func =
1322
 
                                    timedelta_to_milliseconds)
 
1300
                                    lambda td: td.total_seconds()
 
1301
                                    * 1000)
1323
1302
    checker_command = notifychangeproperty(dbus.String, "Checker")
1324
1303
    
1325
1304
    del notifychangeproperty
1368
1347
    
1369
1348
    def approve(self, value=True):
1370
1349
        self.approved = value
1371
 
        gobject.timeout_add(timedelta_to_milliseconds
1372
 
                            (self.approval_duration),
1373
 
                            self._reset_approved)
 
1350
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1351
                                * 1000), self._reset_approved)
1374
1352
        self.send_changedstate()
1375
1353
    
1376
1354
    ## D-Bus methods, signals & properties
1479
1457
                           access="readwrite")
1480
1458
    def ApprovalDelay_dbus_property(self, value=None):
1481
1459
        if value is None:       # get
1482
 
            return dbus.UInt64(self.approval_delay_milliseconds())
 
1460
            return dbus.UInt64(self.approval_delay.total_seconds()
 
1461
                               * 1000)
1483
1462
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1484
1463
    
1485
1464
    # ApprovalDuration - property
1487
1466
                           access="readwrite")
1488
1467
    def ApprovalDuration_dbus_property(self, value=None):
1489
1468
        if value is None:       # get
1490
 
            return dbus.UInt64(timedelta_to_milliseconds(
1491
 
                    self.approval_duration))
 
1469
            return dbus.UInt64(self.approval_duration.total_seconds()
 
1470
                               * 1000)
1492
1471
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1493
1472
    
1494
1473
    # Name - property
1507
1486
    def Host_dbus_property(self, value=None):
1508
1487
        if value is None:       # get
1509
1488
            return dbus.String(self.host)
1510
 
        self.host = unicode(value)
 
1489
        self.host = str(value)
1511
1490
    
1512
1491
    # Created - property
1513
1492
    @dbus_service_property(_interface, signature="s", access="read")
1560
1539
                           access="readwrite")
1561
1540
    def Timeout_dbus_property(self, value=None):
1562
1541
        if value is None:       # get
1563
 
            return dbus.UInt64(self.timeout_milliseconds())
 
1542
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
1564
1543
        old_timeout = self.timeout
1565
1544
        self.timeout = datetime.timedelta(0, 0, 0, value)
1566
1545
        # Reschedule disabling
1577
1556
                gobject.source_remove(self.disable_initiator_tag)
1578
1557
                self.disable_initiator_tag = (
1579
1558
                    gobject.timeout_add(
1580
 
                        timedelta_to_milliseconds(self.expires - now),
1581
 
                        self.disable))
 
1559
                        int((self.expires - now).total_seconds()
 
1560
                            * 1000), self.disable))
1582
1561
    
1583
1562
    # ExtendedTimeout - property
1584
1563
    @dbus_service_property(_interface, signature="t",
1585
1564
                           access="readwrite")
1586
1565
    def ExtendedTimeout_dbus_property(self, value=None):
1587
1566
        if value is None:       # get
1588
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1567
            return dbus.UInt64(self.extended_timeout.total_seconds()
 
1568
                               * 1000)
1589
1569
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1590
1570
    
1591
1571
    # Interval - property
1593
1573
                           access="readwrite")
1594
1574
    def Interval_dbus_property(self, value=None):
1595
1575
        if value is None:       # get
1596
 
            return dbus.UInt64(self.interval_milliseconds())
 
1576
            return dbus.UInt64(self.interval.total_seconds() * 1000)
1597
1577
        self.interval = datetime.timedelta(0, 0, 0, value)
1598
1578
        if getattr(self, "checker_initiator_tag", None) is None:
1599
1579
            return
1610
1590
    def Checker_dbus_property(self, value=None):
1611
1591
        if value is None:       # get
1612
1592
            return dbus.String(self.checker_command)
1613
 
        self.checker_command = unicode(value)
 
1593
        self.checker_command = str(value)
1614
1594
    
1615
1595
    # CheckerRunning - property
1616
1596
    @dbus_service_property(_interface, signature="b",
1632
1612
    @dbus_service_property(_interface, signature="ay",
1633
1613
                           access="write", byte_arrays=True)
1634
1614
    def Secret_dbus_property(self, value):
1635
 
        self.secret = str(value)
 
1615
        self.secret = bytes(value)
1636
1616
    
1637
1617
    del _interface
1638
1618
 
1672
1652
    def handle(self):
1673
1653
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1674
1654
            logger.info("TCP connection from: %s",
1675
 
                        unicode(self.client_address))
 
1655
                        str(self.client_address))
1676
1656
            logger.debug("Pipe FD: %d",
1677
1657
                         self.server.child_pipe.fileno())
1678
1658
            
1759
1739
                        if self.server.use_dbus:
1760
1740
                            # Emit D-Bus signal
1761
1741
                            client.NeedApproval(
1762
 
                                client.approval_delay_milliseconds(),
1763
 
                                client.approved_by_default)
 
1742
                                client.approval_delay.total_seconds()
 
1743
                                * 1000, client.approved_by_default)
1764
1744
                    else:
1765
1745
                        logger.warning("Client %s was not approved",
1766
1746
                                       client.name)
1772
1752
                    #wait until timeout or approved
1773
1753
                    time = datetime.datetime.now()
1774
1754
                    client.changedstate.acquire()
1775
 
                    client.changedstate.wait(
1776
 
                        float(timedelta_to_milliseconds(delay)
1777
 
                              / 1000))
 
1755
                    client.changedstate.wait(delay.total_seconds())
1778
1756
                    client.changedstate.release()
1779
1757
                    time2 = datetime.datetime.now()
1780
1758
                    if (time2 - time) >= delay:
1979
1957
                try:
1980
1958
                    self.socket.setsockopt(socket.SOL_SOCKET,
1981
1959
                                           SO_BINDTODEVICE,
1982
 
                                           str(self.interface + '\0'))
 
1960
                                           (self.interface + "\0")
 
1961
                                           .encode("utf-8"))
1983
1962
                except socket.error as error:
1984
1963
                    if error.errno == errno.EPERM:
1985
1964
                        logger.error("No permission to bind to"
2188
2167
    token_duration = Token(re.compile(r"P"), None,
2189
2168
                           frozenset((token_year, token_month,
2190
2169
                                      token_day, token_time,
2191
 
                                      token_week))),
 
2170
                                      token_week)))
2192
2171
    # Define starting values
2193
2172
    value = datetime.timedelta() # Value so far
2194
2173
    found_token = None
2195
 
    followers = frozenset(token_duration,) # Following valid tokens
 
2174
    followers = frozenset((token_duration,)) # Following valid tokens
2196
2175
    s = duration                # String left to parse
2197
2176
    # Loop until end token is found
2198
2177
    while found_token is not token_end:
2245
2224
    timevalue = datetime.timedelta(0)
2246
2225
    for s in interval.split():
2247
2226
        try:
2248
 
            suffix = unicode(s[-1])
 
2227
            suffix = s[-1]
2249
2228
            value = int(s[:-1])
2250
2229
            if suffix == "d":
2251
2230
                delta = datetime.timedelta(value)
2258
2237
            elif suffix == "w":
2259
2238
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2260
2239
            else:
2261
 
                raise ValueError("Unknown suffix {0!r}"
 
2240
                raise ValueError("Unknown suffix {!r}"
2262
2241
                                 .format(suffix))
2263
2242
        except IndexError as e:
2264
2243
            raise ValueError(*(e.args))
2281
2260
        # Close all standard open file descriptors
2282
2261
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2283
2262
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2284
 
            raise OSError(errno.ENODEV,
2285
 
                          "{0} not a character device"
 
2263
            raise OSError(errno.ENODEV, "{} not a character device"
2286
2264
                          .format(os.devnull))
2287
2265
        os.dup2(null, sys.stdin.fileno())
2288
2266
        os.dup2(null, sys.stdout.fileno())
2298
2276
    
2299
2277
    parser = argparse.ArgumentParser()
2300
2278
    parser.add_argument("-v", "--version", action="version",
2301
 
                        version = "%(prog)s {0}".format(version),
 
2279
                        version = "%(prog)s {}".format(version),
2302
2280
                        help="show version number and exit")
2303
2281
    parser.add_argument("-i", "--interface", metavar="IF",
2304
2282
                        help="Bind to interface IF")
2403
2381
    del options
2404
2382
    # Force all strings to be unicode
2405
2383
    for option in server_settings.keys():
2406
 
        if type(server_settings[option]) is str:
2407
 
            server_settings[option] = unicode(server_settings[option])
 
2384
        if isinstance(server_settings[option], bytes):
 
2385
            server_settings[option] = (server_settings[option]
 
2386
                                       .decode("utf-8"))
2408
2387
    # Force all boolean options to be boolean
2409
2388
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2410
2389
                   "foreground", "zeroconf"):
2443
2422
    
2444
2423
    if server_settings["servicename"] != "Mandos":
2445
2424
        syslogger.setFormatter(logging.Formatter
2446
 
                               ('Mandos ({0}) [%(process)d]:'
 
2425
                               ('Mandos ({}) [%(process)d]:'
2447
2426
                                ' %(levelname)s: %(message)s'
2448
2427
                                .format(server_settings
2449
2428
                                        ["servicename"])))
2553
2532
                                       protocol = protocol, bus = bus)
2554
2533
        if server_settings["interface"]:
2555
2534
            service.interface = (if_nametoindex
2556
 
                                 (str(server_settings["interface"])))
 
2535
                                 (server_settings["interface"]
 
2536
                                  .encode("utf-8")))
2557
2537
    
2558
2538
    global multiprocessing_manager
2559
2539
    multiprocessing_manager = multiprocessing.Manager()
2583
2563
            os.remove(stored_state_path)
2584
2564
        except IOError as e:
2585
2565
            if e.errno == errno.ENOENT:
2586
 
                logger.warning("Could not load persistent state: {0}"
 
2566
                logger.warning("Could not load persistent state: {}"
2587
2567
                                .format(os.strerror(e.errno)))
2588
2568
            else:
2589
2569
                logger.critical("Could not load persistent state:",
2594
2574
                           "EOFError:", exc_info=e)
2595
2575
    
2596
2576
    with PGPEngine() as pgp:
2597
 
        for client_name, client in clients_data.iteritems():
 
2577
        for client_name, client in clients_data.items():
2598
2578
            # Skip removed clients
2599
2579
            if client_name not in client_settings:
2600
2580
                continue
2625
2605
                if datetime.datetime.utcnow() >= client["expires"]:
2626
2606
                    if not client["last_checked_ok"]:
2627
2607
                        logger.warning(
2628
 
                            "disabling client {0} - Client never "
 
2608
                            "disabling client {} - Client never "
2629
2609
                            "performed a successful checker"
2630
2610
                            .format(client_name))
2631
2611
                        client["enabled"] = False
2632
2612
                    elif client["last_checker_status"] != 0:
2633
2613
                        logger.warning(
2634
 
                            "disabling client {0} - Client "
2635
 
                            "last checker failed with error code {1}"
 
2614
                            "disabling client {} - Client last"
 
2615
                            " checker failed with error code {}"
2636
2616
                            .format(client_name,
2637
2617
                                    client["last_checker_status"]))
2638
2618
                        client["enabled"] = False
2641
2621
                                             .utcnow()
2642
2622
                                             + client["timeout"])
2643
2623
                        logger.debug("Last checker succeeded,"
2644
 
                                     " keeping {0} enabled"
 
2624
                                     " keeping {} enabled"
2645
2625
                                     .format(client_name))
2646
2626
            try:
2647
2627
                client["secret"] = (
2650
2630
                                ["secret"]))
2651
2631
            except PGPError:
2652
2632
                # If decryption fails, we use secret from new settings
2653
 
                logger.debug("Failed to decrypt {0} old secret"
 
2633
                logger.debug("Failed to decrypt {} old secret"
2654
2634
                             .format(client_name))
2655
2635
                client["secret"] = (
2656
2636
                    client_settings[client_name]["secret"])
2664
2644
        clients_data[client_name] = client_settings[client_name]
2665
2645
    
2666
2646
    # Create all client objects
2667
 
    for client_name, client in clients_data.iteritems():
 
2647
    for client_name, client in clients_data.items():
2668
2648
        tcp_server.clients[client_name] = client_class(
2669
2649
            name = client_name, settings = client,
2670
2650
            server_settings = server_settings)
2677
2657
            try:
2678
2658
                with pidfile:
2679
2659
                    pid = os.getpid()
2680
 
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
 
2660
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2681
2661
            except IOError:
2682
2662
                logger.error("Could not write to file %r with PID %d",
2683
2663
                             pidfilename, pid)
2774
2754
                
2775
2755
                # A list of attributes that can not be pickled
2776
2756
                # + secret.
2777
 
                exclude = set(("bus", "changedstate", "secret",
2778
 
                               "checker", "server_settings"))
 
2757
                exclude = { "bus", "changedstate", "secret",
 
2758
                            "checker", "server_settings" }
2779
2759
                for name, typ in (inspect.getmembers
2780
2760
                                  (dbus.service.Object)):
2781
2761
                    exclude.add(name)
2804
2784
                except NameError:
2805
2785
                    pass
2806
2786
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2807
 
                logger.warning("Could not save persistent state: {0}"
 
2787
                logger.warning("Could not save persistent state: {}"
2808
2788
                               .format(os.strerror(e.errno)))
2809
2789
            else:
2810
2790
                logger.warning("Could not save persistent state:",