/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.4"
 
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
 
114
115
def initlogger(debug, level=logging.WARNING):
115
116
    """init logger and add loglevel"""
116
117
    
 
118
    global syslogger
117
119
    syslogger = (logging.handlers.SysLogHandler
118
120
                 (facility =
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:'
123
125
                            ' %(message)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,
 
229
                                                **kwargs)
229
230
 
230
231
class AvahiServiceError(AvahiError):
231
232
    pass
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 ...",
287
288
                    self.name)
288
289
        self.remove()
336
337
            self.rename()
337
338
        elif state == avahi.ENTRY_GROUP_FAILURE:
338
339
            logger.critical("Avahi: Error in group state changed %s",
339
 
                            unicode(error))
340
 
            raise AvahiGroupError("State changed: {0!s}"
 
340
                            str(error))
 
341
            raise AvahiGroupError("State changed: {!s}"
341
342
                                  .format(error))
342
343
    
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)))
400
401
        return ret
401
402
 
402
403
 
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))
408
 
 
409
 
 
410
404
class Client(object):
411
405
    """A representation of a client host served by this server.
412
406
    
467
461
                        "enabled": "True",
468
462
                        }
469
463
    
470
 
    def timeout_milliseconds(self):
471
 
        "Return the 'timeout' attribute in milliseconds"
472
 
        return timedelta_to_milliseconds(self.timeout)
473
 
    
474
 
    def extended_timeout_milliseconds(self):
475
 
        "Return the 'extended_timeout' attribute in milliseconds"
476
 
        return timedelta_to_milliseconds(self.extended_timeout)
477
 
    
478
 
    def interval_milliseconds(self):
479
 
        "Return the 'interval' attribute in milliseconds"
480
 
        return timedelta_to_milliseconds(self.interval)
481
 
    
482
 
    def approval_delay_milliseconds(self):
483
 
        return timedelta_to_milliseconds(self.approval_delay)
484
 
    
485
464
    @staticmethod
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()
514
493
            else:
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)
540
519
        
541
520
        if self.enabled:
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(),
 
606
                                      (int(self.interval
 
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(),
634
 
                                    self.disable))
 
613
                                      (int(self.timeout
 
614
                                           .total_seconds() * 1000),
 
615
                                       self.disable))
635
616
        # Also start a new checker *right now*.
636
617
        self.start_checker()
637
618
    
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
674
655
    
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))))
711
 
                for attr in
712
 
                self.runtime_expansions)
 
690
            escaped_attrs = { attr:
 
691
                                  re.escape(str(getattr(self, attr)))
 
692
                              for attr in self.runtime_expansions }
713
693
            try:
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
850
830
class DBusPropertyException(dbus.exceptions.DBusException):
851
831
    """A base class for D-Bus property-related exceptions
852
832
    """
853
 
    def __unicode__(self):
854
 
        return unicode(str(self))
855
 
 
 
833
    pass
856
834
 
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().
883
861
        """
884
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
 
862
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
885
863
                                   False)
886
864
    
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))
1008
986
                                              (prop,
1009
987
                                               "_dbus_annotations",
1010
988
                                               {}))
1011
 
                        for name, value in annots.iteritems():
 
989
                        for name, value in annots.items():
1012
990
                            ann_tag = document.createElement(
1013
991
                                "annotation")
1014
992
                            ann_tag.setAttribute("name", name)
1017
995
                # Add interface annotation tags
1018
996
                for annotation, value in dict(
1019
997
                    itertools.chain.from_iterable(
1020
 
                        annotations().iteritems()
 
998
                        annotations().items()
1021
999
                        for name, annotations in
1022
1000
                        self._get_all_dbus_things("interface")
1023
1001
                        if name == if_tag.getAttribute("name")
1024
 
                        )).iteritems():
 
1002
                        )).items():
1025
1003
                    ann_tag = document.createElement("annotation")
1026
1004
                    ann_tag.setAttribute("name", annotation)
1027
1005
                    ann_tag.setAttribute("value", value)
1083
1061
    """
1084
1062
    def wrapper(cls):
1085
1063
        for orig_interface_name, alt_interface_name in (
1086
 
            alt_interface_names.iteritems()):
 
1064
            alt_interface_names.items()):
1087
1065
            attr = {}
1088
1066
            interface_names = set()
1089
1067
            # Go though all attributes of the class
1206
1184
                                        attribute.func_closure)))
1207
1185
            if deprecate:
1208
1186
                # Deprecate all alternate interfaces
1209
 
                iname="_AlternateDBusNames_interface_annotation{0}"
 
1187
                iname="_AlternateDBusNames_interface_annotation{}"
1210
1188
                for interface_name in interface_names:
1211
1189
                    @dbus_interface_annotations(interface_name)
1212
1190
                    def func(self):
1221
1199
            if interface_names:
1222
1200
                # Replace the class with a new subclass of it with
1223
1201
                # methods, signals, etc. as created above.
1224
 
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1202
                cls = type(b"{}Alternate".format(cls.__name__),
1225
1203
                           (cls,), attr)
1226
1204
        return cls
1227
1205
    return wrapper
1247
1225
        Client.__init__(self, *args, **kwargs)
1248
1226
        # Only now, when this client is initialized, can it show up on
1249
1227
        # the D-Bus
1250
 
        client_object_name = unicode(self.name).translate(
 
1228
        client_object_name = str(self.name).translate(
1251
1229
            {ord("."): ord("_"),
1252
1230
             ord("-"): ord("_")})
1253
1231
        self.dbus_object_path = (dbus.ObjectPath
1268
1246
                   to the D-Bus.  Default: no transform
1269
1247
        variant_level: D-Bus variant level.  Default: 1
1270
1248
        """
1271
 
        attrname = "_{0}".format(dbus_name)
 
1249
        attrname = "_{}".format(dbus_name)
1272
1250
        def setter(self, value):
1273
1251
            if hasattr(self, "dbus_object_path"):
1274
1252
                if (not hasattr(self, attrname) or
1304
1282
    approval_delay = notifychangeproperty(dbus.UInt64,
1305
1283
                                          "ApprovalDelay",
1306
1284
                                          type_func =
1307
 
                                          timedelta_to_milliseconds)
 
1285
                                          lambda td: td.total_seconds()
 
1286
                                          * 1000)
1308
1287
    approval_duration = notifychangeproperty(
1309
1288
        dbus.UInt64, "ApprovalDuration",
1310
 
        type_func = timedelta_to_milliseconds)
 
1289
        type_func = lambda td: td.total_seconds() * 1000)
1311
1290
    host = notifychangeproperty(dbus.String, "Host")
1312
1291
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1313
 
                                   type_func =
1314
 
                                   timedelta_to_milliseconds)
 
1292
                                   type_func = lambda td:
 
1293
                                       td.total_seconds() * 1000)
1315
1294
    extended_timeout = notifychangeproperty(
1316
1295
        dbus.UInt64, "ExtendedTimeout",
1317
 
        type_func = timedelta_to_milliseconds)
 
1296
        type_func = lambda td: td.total_seconds() * 1000)
1318
1297
    interval = notifychangeproperty(dbus.UInt64,
1319
1298
                                    "Interval",
1320
1299
                                    type_func =
1321
 
                                    timedelta_to_milliseconds)
 
1300
                                    lambda td: td.total_seconds()
 
1301
                                    * 1000)
1322
1302
    checker_command = notifychangeproperty(dbus.String, "Checker")
1323
1303
    
1324
1304
    del notifychangeproperty
1367
1347
    
1368
1348
    def approve(self, value=True):
1369
1349
        self.approved = value
1370
 
        gobject.timeout_add(timedelta_to_milliseconds
1371
 
                            (self.approval_duration),
1372
 
                            self._reset_approved)
 
1350
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1351
                                * 1000), self._reset_approved)
1373
1352
        self.send_changedstate()
1374
1353
    
1375
1354
    ## D-Bus methods, signals & properties
1478
1457
                           access="readwrite")
1479
1458
    def ApprovalDelay_dbus_property(self, value=None):
1480
1459
        if value is None:       # get
1481
 
            return dbus.UInt64(self.approval_delay_milliseconds())
 
1460
            return dbus.UInt64(self.approval_delay.total_seconds()
 
1461
                               * 1000)
1482
1462
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1483
1463
    
1484
1464
    # ApprovalDuration - property
1486
1466
                           access="readwrite")
1487
1467
    def ApprovalDuration_dbus_property(self, value=None):
1488
1468
        if value is None:       # get
1489
 
            return dbus.UInt64(timedelta_to_milliseconds(
1490
 
                    self.approval_duration))
 
1469
            return dbus.UInt64(self.approval_duration.total_seconds()
 
1470
                               * 1000)
1491
1471
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1492
1472
    
1493
1473
    # Name - property
1506
1486
    def Host_dbus_property(self, value=None):
1507
1487
        if value is None:       # get
1508
1488
            return dbus.String(self.host)
1509
 
        self.host = unicode(value)
 
1489
        self.host = str(value)
1510
1490
    
1511
1491
    # Created - property
1512
1492
    @dbus_service_property(_interface, signature="s", access="read")
1559
1539
                           access="readwrite")
1560
1540
    def Timeout_dbus_property(self, value=None):
1561
1541
        if value is None:       # get
1562
 
            return dbus.UInt64(self.timeout_milliseconds())
 
1542
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
1563
1543
        old_timeout = self.timeout
1564
1544
        self.timeout = datetime.timedelta(0, 0, 0, value)
1565
1545
        # Reschedule disabling
1576
1556
                gobject.source_remove(self.disable_initiator_tag)
1577
1557
                self.disable_initiator_tag = (
1578
1558
                    gobject.timeout_add(
1579
 
                        timedelta_to_milliseconds(self.expires - now),
1580
 
                        self.disable))
 
1559
                        int((self.expires - now).total_seconds()
 
1560
                            * 1000), self.disable))
1581
1561
    
1582
1562
    # ExtendedTimeout - property
1583
1563
    @dbus_service_property(_interface, signature="t",
1584
1564
                           access="readwrite")
1585
1565
    def ExtendedTimeout_dbus_property(self, value=None):
1586
1566
        if value is None:       # get
1587
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1567
            return dbus.UInt64(self.extended_timeout.total_seconds()
 
1568
                               * 1000)
1588
1569
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1589
1570
    
1590
1571
    # Interval - property
1592
1573
                           access="readwrite")
1593
1574
    def Interval_dbus_property(self, value=None):
1594
1575
        if value is None:       # get
1595
 
            return dbus.UInt64(self.interval_milliseconds())
 
1576
            return dbus.UInt64(self.interval.total_seconds() * 1000)
1596
1577
        self.interval = datetime.timedelta(0, 0, 0, value)
1597
1578
        if getattr(self, "checker_initiator_tag", None) is None:
1598
1579
            return
1609
1590
    def Checker_dbus_property(self, value=None):
1610
1591
        if value is None:       # get
1611
1592
            return dbus.String(self.checker_command)
1612
 
        self.checker_command = unicode(value)
 
1593
        self.checker_command = str(value)
1613
1594
    
1614
1595
    # CheckerRunning - property
1615
1596
    @dbus_service_property(_interface, signature="b",
1631
1612
    @dbus_service_property(_interface, signature="ay",
1632
1613
                           access="write", byte_arrays=True)
1633
1614
    def Secret_dbus_property(self, value):
1634
 
        self.secret = str(value)
 
1615
        self.secret = bytes(value)
1635
1616
    
1636
1617
    del _interface
1637
1618
 
1671
1652
    def handle(self):
1672
1653
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1673
1654
            logger.info("TCP connection from: %s",
1674
 
                        unicode(self.client_address))
 
1655
                        str(self.client_address))
1675
1656
            logger.debug("Pipe FD: %d",
1676
1657
                         self.server.child_pipe.fileno())
1677
1658
            
1758
1739
                        if self.server.use_dbus:
1759
1740
                            # Emit D-Bus signal
1760
1741
                            client.NeedApproval(
1761
 
                                client.approval_delay_milliseconds(),
1762
 
                                client.approved_by_default)
 
1742
                                client.approval_delay.total_seconds()
 
1743
                                * 1000, client.approved_by_default)
1763
1744
                    else:
1764
1745
                        logger.warning("Client %s was not approved",
1765
1746
                                       client.name)
1771
1752
                    #wait until timeout or approved
1772
1753
                    time = datetime.datetime.now()
1773
1754
                    client.changedstate.acquire()
1774
 
                    client.changedstate.wait(
1775
 
                        float(timedelta_to_milliseconds(delay)
1776
 
                              / 1000))
 
1755
                    client.changedstate.wait(delay.total_seconds())
1777
1756
                    client.changedstate.release()
1778
1757
                    time2 = datetime.datetime.now()
1779
1758
                    if (time2 - time) >= delay:
1978
1957
                try:
1979
1958
                    self.socket.setsockopt(socket.SOL_SOCKET,
1980
1959
                                           SO_BINDTODEVICE,
1981
 
                                           str(self.interface + '\0'))
 
1960
                                           (self.interface + "\0")
 
1961
                                           .encode("utf-8"))
1982
1962
                except socket.error as error:
1983
1963
                    if error.errno == errno.EPERM:
1984
1964
                        logger.error("No permission to bind to"
2187
2167
    token_duration = Token(re.compile(r"P"), None,
2188
2168
                           frozenset((token_year, token_month,
2189
2169
                                      token_day, token_time,
2190
 
                                      token_week))),
 
2170
                                      token_week)))
2191
2171
    # Define starting values
2192
2172
    value = datetime.timedelta() # Value so far
2193
2173
    found_token = None
2194
 
    followers = frozenset(token_duration,) # Following valid tokens
 
2174
    followers = frozenset((token_duration,)) # Following valid tokens
2195
2175
    s = duration                # String left to parse
2196
2176
    # Loop until end token is found
2197
2177
    while found_token is not token_end:
2244
2224
    timevalue = datetime.timedelta(0)
2245
2225
    for s in interval.split():
2246
2226
        try:
2247
 
            suffix = unicode(s[-1])
 
2227
            suffix = s[-1]
2248
2228
            value = int(s[:-1])
2249
2229
            if suffix == "d":
2250
2230
                delta = datetime.timedelta(value)
2257
2237
            elif suffix == "w":
2258
2238
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2259
2239
            else:
2260
 
                raise ValueError("Unknown suffix {0!r}"
 
2240
                raise ValueError("Unknown suffix {!r}"
2261
2241
                                 .format(suffix))
2262
2242
        except IndexError as e:
2263
2243
            raise ValueError(*(e.args))
2280
2260
        # Close all standard open file descriptors
2281
2261
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2282
2262
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2283
 
            raise OSError(errno.ENODEV,
2284
 
                          "{0} not a character device"
 
2263
            raise OSError(errno.ENODEV, "{} not a character device"
2285
2264
                          .format(os.devnull))
2286
2265
        os.dup2(null, sys.stdin.fileno())
2287
2266
        os.dup2(null, sys.stdout.fileno())
2297
2276
    
2298
2277
    parser = argparse.ArgumentParser()
2299
2278
    parser.add_argument("-v", "--version", action="version",
2300
 
                        version = "%(prog)s {0}".format(version),
 
2279
                        version = "%(prog)s {}".format(version),
2301
2280
                        help="show version number and exit")
2302
2281
    parser.add_argument("-i", "--interface", metavar="IF",
2303
2282
                        help="Bind to interface IF")
2336
2315
                        help="Directory to save/restore state in")
2337
2316
    parser.add_argument("--foreground", action="store_true",
2338
2317
                        help="Run in foreground", default=None)
 
2318
    parser.add_argument("--no-zeroconf", action="store_false",
 
2319
                        dest="zeroconf", help="Do not use Zeroconf",
 
2320
                        default=None)
2339
2321
    
2340
2322
    options = parser.parse_args()
2341
2323
    
2359
2341
                        "socket": "",
2360
2342
                        "statedir": "/var/lib/mandos",
2361
2343
                        "foreground": "False",
 
2344
                        "zeroconf": "True",
2362
2345
                        }
2363
2346
    
2364
2347
    # Parse config file for server-global settings
2391
2374
    for option in ("interface", "address", "port", "debug",
2392
2375
                   "priority", "servicename", "configdir",
2393
2376
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2394
 
                   "statedir", "socket", "foreground"):
 
2377
                   "statedir", "socket", "foreground", "zeroconf"):
2395
2378
        value = getattr(options, option)
2396
2379
        if value is not None:
2397
2380
            server_settings[option] = value
2398
2381
    del options
2399
2382
    # Force all strings to be unicode
2400
2383
    for option in server_settings.keys():
2401
 
        if type(server_settings[option]) is str:
2402
 
            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"))
2403
2387
    # Force all boolean options to be boolean
2404
2388
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2405
 
                   "foreground"):
 
2389
                   "foreground", "zeroconf"):
2406
2390
        server_settings[option] = bool(server_settings[option])
2407
2391
    # Debug implies foreground
2408
2392
    if server_settings["debug"]:
2411
2395
    
2412
2396
    ##################################################################
2413
2397
    
 
2398
    if (not server_settings["zeroconf"] and
 
2399
        not (server_settings["port"]
 
2400
             or server_settings["socket"] != "")):
 
2401
            parser.error("Needs port or socket to work without"
 
2402
                         " Zeroconf")
 
2403
    
2414
2404
    # For convenience
2415
2405
    debug = server_settings["debug"]
2416
2406
    debuglevel = server_settings["debuglevel"]
2419
2409
    stored_state_path = os.path.join(server_settings["statedir"],
2420
2410
                                     stored_state_file)
2421
2411
    foreground = server_settings["foreground"]
 
2412
    zeroconf = server_settings["zeroconf"]
2422
2413
    
2423
2414
    if debug:
2424
2415
        initlogger(debug, logging.DEBUG)
2431
2422
    
2432
2423
    if server_settings["servicename"] != "Mandos":
2433
2424
        syslogger.setFormatter(logging.Formatter
2434
 
                               ('Mandos ({0}) [%(process)d]:'
 
2425
                               ('Mandos ({}) [%(process)d]:'
2435
2426
                                ' %(levelname)s: %(message)s'
2436
2427
                                .format(server_settings
2437
2428
                                        ["servicename"])))
2445
2436
    global mandos_dbus_service
2446
2437
    mandos_dbus_service = None
2447
2438
    
 
2439
    socketfd = None
 
2440
    if server_settings["socket"] != "":
 
2441
        socketfd = server_settings["socket"]
2448
2442
    tcp_server = MandosServer((server_settings["address"],
2449
2443
                               server_settings["port"]),
2450
2444
                              ClientHandler,
2454
2448
                              gnutls_priority=
2455
2449
                              server_settings["priority"],
2456
2450
                              use_dbus=use_dbus,
2457
 
                              socketfd=(server_settings["socket"]
2458
 
                                        or None))
 
2451
                              socketfd=socketfd)
2459
2452
    if not foreground:
2460
2453
        pidfilename = "/run/mandos.pid"
2461
2454
        if not os.path.isdir("/run/."):
2531
2524
            use_dbus = False
2532
2525
            server_settings["use_dbus"] = False
2533
2526
            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"])))
 
2527
    if zeroconf:
 
2528
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2529
        service = AvahiServiceToSyslog(name =
 
2530
                                       server_settings["servicename"],
 
2531
                                       servicetype = "_mandos._tcp",
 
2532
                                       protocol = protocol, bus = bus)
 
2533
        if server_settings["interface"]:
 
2534
            service.interface = (if_nametoindex
 
2535
                                 (server_settings["interface"]
 
2536
                                  .encode("utf-8")))
2542
2537
    
2543
2538
    global multiprocessing_manager
2544
2539
    multiprocessing_manager = multiprocessing.Manager()
2568
2563
            os.remove(stored_state_path)
2569
2564
        except IOError as e:
2570
2565
            if e.errno == errno.ENOENT:
2571
 
                logger.warning("Could not load persistent state: {0}"
 
2566
                logger.warning("Could not load persistent state: {}"
2572
2567
                                .format(os.strerror(e.errno)))
2573
2568
            else:
2574
2569
                logger.critical("Could not load persistent state:",
2579
2574
                           "EOFError:", exc_info=e)
2580
2575
    
2581
2576
    with PGPEngine() as pgp:
2582
 
        for client_name, client in clients_data.iteritems():
 
2577
        for client_name, client in clients_data.items():
2583
2578
            # Skip removed clients
2584
2579
            if client_name not in client_settings:
2585
2580
                continue
2610
2605
                if datetime.datetime.utcnow() >= client["expires"]:
2611
2606
                    if not client["last_checked_ok"]:
2612
2607
                        logger.warning(
2613
 
                            "disabling client {0} - Client never "
 
2608
                            "disabling client {} - Client never "
2614
2609
                            "performed a successful checker"
2615
2610
                            .format(client_name))
2616
2611
                        client["enabled"] = False
2617
2612
                    elif client["last_checker_status"] != 0:
2618
2613
                        logger.warning(
2619
 
                            "disabling client {0} - Client "
2620
 
                            "last checker failed with error code {1}"
 
2614
                            "disabling client {} - Client last"
 
2615
                            " checker failed with error code {}"
2621
2616
                            .format(client_name,
2622
2617
                                    client["last_checker_status"]))
2623
2618
                        client["enabled"] = False
2626
2621
                                             .utcnow()
2627
2622
                                             + client["timeout"])
2628
2623
                        logger.debug("Last checker succeeded,"
2629
 
                                     " keeping {0} enabled"
 
2624
                                     " keeping {} enabled"
2630
2625
                                     .format(client_name))
2631
2626
            try:
2632
2627
                client["secret"] = (
2635
2630
                                ["secret"]))
2636
2631
            except PGPError:
2637
2632
                # If decryption fails, we use secret from new settings
2638
 
                logger.debug("Failed to decrypt {0} old secret"
 
2633
                logger.debug("Failed to decrypt {} old secret"
2639
2634
                             .format(client_name))
2640
2635
                client["secret"] = (
2641
2636
                    client_settings[client_name]["secret"])
2649
2644
        clients_data[client_name] = client_settings[client_name]
2650
2645
    
2651
2646
    # Create all client objects
2652
 
    for client_name, client in clients_data.iteritems():
 
2647
    for client_name, client in clients_data.items():
2653
2648
        tcp_server.clients[client_name] = client_class(
2654
2649
            name = client_name, settings = client,
2655
2650
            server_settings = server_settings)
2662
2657
            try:
2663
2658
                with pidfile:
2664
2659
                    pid = os.getpid()
2665
 
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
 
2660
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2666
2661
            except IOError:
2667
2662
                logger.error("Could not write to file %r with PID %d",
2668
2663
                             pidfilename, pid)
2738
2733
    
2739
2734
    def cleanup():
2740
2735
        "Cleanup function; run on exit"
2741
 
        service.cleanup()
 
2736
        if zeroconf:
 
2737
            service.cleanup()
2742
2738
        
2743
2739
        multiprocessing.active_children()
2744
2740
        wnull.close()
2758
2754
                
2759
2755
                # A list of attributes that can not be pickled
2760
2756
                # + secret.
2761
 
                exclude = set(("bus", "changedstate", "secret",
2762
 
                               "checker", "server_settings"))
 
2757
                exclude = { "bus", "changedstate", "secret",
 
2758
                            "checker", "server_settings" }
2763
2759
                for name, typ in (inspect.getmembers
2764
2760
                                  (dbus.service.Object)):
2765
2761
                    exclude.add(name)
2788
2784
                except NameError:
2789
2785
                    pass
2790
2786
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2791
 
                logger.warning("Could not save persistent state: {0}"
 
2787
                logger.warning("Could not save persistent state: {}"
2792
2788
                               .format(os.strerror(e.errno)))
2793
2789
            else:
2794
2790
                logger.warning("Could not save persistent state:",
2823
2819
    tcp_server.server_activate()
2824
2820
    
2825
2821
    # Find out what port we got
2826
 
    service.port = tcp_server.socket.getsockname()[1]
 
2822
    if zeroconf:
 
2823
        service.port = tcp_server.socket.getsockname()[1]
2827
2824
    if use_ipv6:
2828
2825
        logger.info("Now listening on address %r, port %d,"
2829
2826
                    " flowinfo %d, scope_id %d",
2835
2832
    #service.interface = tcp_server.socket.getsockname()[3]
2836
2833
    
2837
2834
    try:
2838
 
        # From the Avahi example code
2839
 
        try:
2840
 
            service.activate()
2841
 
        except dbus.exceptions.DBusException as error:
2842
 
            logger.critical("D-Bus Exception", exc_info=error)
2843
 
            cleanup()
2844
 
            sys.exit(1)
2845
 
        # End of Avahi example code
 
2835
        if zeroconf:
 
2836
            # From the Avahi example code
 
2837
            try:
 
2838
                service.activate()
 
2839
            except dbus.exceptions.DBusException as error:
 
2840
                logger.critical("D-Bus Exception", exc_info=error)
 
2841
                cleanup()
 
2842
                sys.exit(1)
 
2843
            # End of Avahi example code
2846
2844
        
2847
2845
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2848
2846
                             lambda *args, **kwargs: