/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: 2012-06-24 03:45:55 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 303.
  • Revision ID: teddy@recompile.se-20120624034555-7p0dtbpsz0dgsn4d
* mandos (Client.start_checker): Add comment.  Break long line.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python2.7
 
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2014 Teddy Hogeborn
15
 
# Copyright © 2008-2014 Björn Påhlsson
 
14
# Copyright © 2008-2012 Teddy Hogeborn
 
15
# Copyright © 2008-2012 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
79
79
import ctypes.util
80
80
import xml.dom.minidom
81
81
import inspect
 
82
import GnuPGInterface
82
83
 
83
84
try:
84
85
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
88
89
    except ImportError:
89
90
        SO_BINDTODEVICE = None
90
91
 
91
 
if sys.version_info.major == 2:
92
 
    str = unicode
93
 
 
94
 
version = "1.6.9"
 
92
version = "1.6.0"
95
93
stored_state_file = "clients.pickle"
96
94
 
97
95
logger = logging.getLogger()
98
 
syslogger = None
 
96
syslogger = (logging.handlers.SysLogHandler
 
97
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
98
              address = str("/dev/log")))
99
99
 
100
100
try:
101
101
    if_nametoindex = (ctypes.cdll.LoadLibrary
107
107
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
108
108
        with contextlib.closing(socket.socket()) as s:
109
109
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
 
                                struct.pack(b"16s16x", interface))
111
 
        interface_index = struct.unpack("I", ifreq[16:20])[0]
 
110
                                struct.pack(str("16s16x"),
 
111
                                            interface))
 
112
        interface_index = struct.unpack(str("I"),
 
113
                                        ifreq[16:20])[0]
112
114
        return interface_index
113
115
 
114
116
 
115
117
def initlogger(debug, level=logging.WARNING):
116
118
    """init logger and add loglevel"""
117
119
    
118
 
    global syslogger
119
 
    syslogger = (logging.handlers.SysLogHandler
120
 
                 (facility =
121
 
                  logging.handlers.SysLogHandler.LOG_DAEMON,
122
 
                  address = "/dev/log"))
123
120
    syslogger.setFormatter(logging.Formatter
124
121
                           ('Mandos [%(process)d]: %(levelname)s:'
125
122
                            ' %(message)s'))
143
140
class PGPEngine(object):
144
141
    """A simple class for OpenPGP symmetric encryption & decryption"""
145
142
    def __init__(self):
 
143
        self.gnupg = GnuPGInterface.GnuPG()
146
144
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
147
 
        self.gnupgargs = ['--batch',
148
 
                          '--home', self.tempdir,
149
 
                          '--force-mdc',
150
 
                          '--quiet',
151
 
                          '--no-use-agent']
 
145
        self.gnupg = GnuPGInterface.GnuPG()
 
146
        self.gnupg.options.meta_interactive = False
 
147
        self.gnupg.options.homedir = self.tempdir
 
148
        self.gnupg.options.extra_args.extend(['--force-mdc',
 
149
                                              '--quiet',
 
150
                                              '--no-use-agent'])
152
151
    
153
152
    def __enter__(self):
154
153
        return self
176
175
    def password_encode(self, password):
177
176
        # Passphrase can not be empty and can not contain newlines or
178
177
        # NUL bytes.  So we prefix it and hex encode it.
179
 
        encoded = b"mandos" + binascii.hexlify(password)
180
 
        if len(encoded) > 2048:
181
 
            # GnuPG can't handle long passwords, so encode differently
182
 
            encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
183
 
                       .replace(b"\n", b"\\n")
184
 
                       .replace(b"\0", b"\\x00"))
185
 
        return encoded
 
178
        return b"mandos" + binascii.hexlify(password)
186
179
    
187
180
    def encrypt(self, data, password):
188
 
        passphrase = self.password_encode(password)
189
 
        with tempfile.NamedTemporaryFile(dir=self.tempdir
190
 
                                         ) as passfile:
191
 
            passfile.write(passphrase)
192
 
            passfile.flush()
193
 
            proc = subprocess.Popen(['gpg', '--symmetric',
194
 
                                     '--passphrase-file',
195
 
                                     passfile.name]
196
 
                                    + self.gnupgargs,
197
 
                                    stdin = subprocess.PIPE,
198
 
                                    stdout = subprocess.PIPE,
199
 
                                    stderr = subprocess.PIPE)
200
 
            ciphertext, err = proc.communicate(input = data)
201
 
        if proc.returncode != 0:
202
 
            raise PGPError(err)
 
181
        self.gnupg.passphrase = self.password_encode(password)
 
182
        with open(os.devnull, "w") as devnull:
 
183
            try:
 
184
                proc = self.gnupg.run(['--symmetric'],
 
185
                                      create_fhs=['stdin', 'stdout'],
 
186
                                      attach_fhs={'stderr': devnull})
 
187
                with contextlib.closing(proc.handles['stdin']) as f:
 
188
                    f.write(data)
 
189
                with contextlib.closing(proc.handles['stdout']) as f:
 
190
                    ciphertext = f.read()
 
191
                proc.wait()
 
192
            except IOError as e:
 
193
                raise PGPError(e)
 
194
        self.gnupg.passphrase = None
203
195
        return ciphertext
204
196
    
205
197
    def decrypt(self, data, password):
206
 
        passphrase = self.password_encode(password)
207
 
        with tempfile.NamedTemporaryFile(dir = self.tempdir
208
 
                                         ) as passfile:
209
 
            passfile.write(passphrase)
210
 
            passfile.flush()
211
 
            proc = subprocess.Popen(['gpg', '--decrypt',
212
 
                                     '--passphrase-file',
213
 
                                     passfile.name]
214
 
                                    + self.gnupgargs,
215
 
                                    stdin = subprocess.PIPE,
216
 
                                    stdout = subprocess.PIPE,
217
 
                                    stderr = subprocess.PIPE)
218
 
            decrypted_plaintext, err = proc.communicate(input
219
 
                                                        = data)
220
 
        if proc.returncode != 0:
221
 
            raise PGPError(err)
 
198
        self.gnupg.passphrase = self.password_encode(password)
 
199
        with open(os.devnull, "w") as devnull:
 
200
            try:
 
201
                proc = self.gnupg.run(['--decrypt'],
 
202
                                      create_fhs=['stdin', 'stdout'],
 
203
                                      attach_fhs={'stderr': devnull})
 
204
                with contextlib.closing(proc.handles['stdin']) as f:
 
205
                    f.write(data)
 
206
                with contextlib.closing(proc.handles['stdout']) as f:
 
207
                    decrypted_plaintext = f.read()
 
208
                proc.wait()
 
209
            except IOError as e:
 
210
                raise PGPError(e)
 
211
        self.gnupg.passphrase = None
222
212
        return decrypted_plaintext
223
213
 
224
214
 
225
215
class AvahiError(Exception):
226
216
    def __init__(self, value, *args, **kwargs):
227
217
        self.value = value
228
 
        return super(AvahiError, self).__init__(value, *args,
229
 
                                                **kwargs)
 
218
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
219
    def __unicode__(self):
 
220
        return unicode(repr(self.value))
230
221
 
231
222
class AvahiServiceError(AvahiError):
232
223
    pass
243
234
               Used to optionally bind to the specified interface.
244
235
    name: string; Example: 'Mandos'
245
236
    type: string; Example: '_mandos._tcp'.
246
 
     See <https://www.iana.org/assignments/service-names-port-numbers>
 
237
                  See <http://www.dns-sd.org/ServiceTypes.html>
247
238
    port: integer; what port to announce
248
239
    TXT: list of strings; TXT record for the service
249
240
    domain: string; Domain to publish on, default to .local if empty.
275
266
        self.bus = bus
276
267
        self.entry_group_state_changed_match = None
277
268
    
278
 
    def rename(self, remove=True):
 
269
    def rename(self):
279
270
        """Derived from the Avahi example code"""
280
271
        if self.rename_count >= self.max_renames:
281
272
            logger.critical("No suitable Zeroconf service name found"
282
273
                            " after %i retries, exiting.",
283
274
                            self.rename_count)
284
275
            raise AvahiServiceError("Too many renames")
285
 
        self.name = str(self.server
286
 
                        .GetAlternativeServiceName(self.name))
287
 
        self.rename_count += 1
 
276
        self.name = unicode(self.server
 
277
                            .GetAlternativeServiceName(self.name))
288
278
        logger.info("Changing Zeroconf service name to %r ...",
289
279
                    self.name)
290
 
        if remove:
291
 
            self.remove()
 
280
        self.remove()
292
281
        try:
293
282
            self.add()
294
283
        except dbus.exceptions.DBusException as error:
295
 
            if (error.get_dbus_name()
296
 
                == "org.freedesktop.Avahi.CollisionError"):
297
 
                logger.info("Local Zeroconf service name collision.")
298
 
                return self.rename(remove=False)
299
 
            else:
300
 
                logger.critical("D-Bus Exception", exc_info=error)
301
 
                self.cleanup()
302
 
                os._exit(1)
 
284
            logger.critical("D-Bus Exception", exc_info=error)
 
285
            self.cleanup()
 
286
            os._exit(1)
 
287
        self.rename_count += 1
303
288
    
304
289
    def remove(self):
305
290
        """Derived from the Avahi example code"""
343
328
            self.rename()
344
329
        elif state == avahi.ENTRY_GROUP_FAILURE:
345
330
            logger.critical("Avahi: Error in group state changed %s",
346
 
                            str(error))
347
 
            raise AvahiGroupError("State changed: {!s}"
 
331
                            unicode(error))
 
332
            raise AvahiGroupError("State changed: {0!s}"
348
333
                                  .format(error))
349
334
    
350
335
    def cleanup(self):
397
382
 
398
383
 
399
384
class AvahiServiceToSyslog(AvahiService):
400
 
    def rename(self, *args, **kwargs):
 
385
    def rename(self):
401
386
        """Add the new name to the syslog messages"""
402
 
        ret = AvahiService.rename(self, *args, **kwargs)
 
387
        ret = AvahiService.rename(self)
403
388
        syslogger.setFormatter(logging.Formatter
404
 
                               ('Mandos ({}) [%(process)d]:'
 
389
                               ('Mandos ({0}) [%(process)d]:'
405
390
                                ' %(levelname)s: %(message)s'
406
391
                                .format(self.name)))
407
392
        return ret
408
393
 
409
394
 
 
395
def timedelta_to_milliseconds(td):
 
396
    "Convert a datetime.timedelta() to milliseconds"
 
397
    return ((td.days * 24 * 60 * 60 * 1000)
 
398
            + (td.seconds * 1000)
 
399
            + (td.microseconds // 1000))
 
400
 
 
401
 
410
402
class Client(object):
411
403
    """A representation of a client host served by this server.
412
404
    
448
440
    runtime_expansions: Allowed attributes for runtime expansion.
449
441
    expires:    datetime.datetime(); time (UTC) when a client will be
450
442
                disabled, or None
451
 
    server_settings: The server_settings dict from main()
452
443
    """
453
444
    
454
445
    runtime_expansions = ("approval_delay", "approval_duration",
467
458
                        "enabled": "True",
468
459
                        }
469
460
    
 
461
    def timeout_milliseconds(self):
 
462
        "Return the 'timeout' attribute in milliseconds"
 
463
        return timedelta_to_milliseconds(self.timeout)
 
464
    
 
465
    def extended_timeout_milliseconds(self):
 
466
        "Return the 'extended_timeout' attribute in milliseconds"
 
467
        return timedelta_to_milliseconds(self.extended_timeout)
 
468
    
 
469
    def interval_milliseconds(self):
 
470
        "Return the 'interval' attribute in milliseconds"
 
471
        return timedelta_to_milliseconds(self.interval)
 
472
    
 
473
    def approval_delay_milliseconds(self):
 
474
        return timedelta_to_milliseconds(self.approval_delay)
 
475
    
470
476
    @staticmethod
471
477
    def config_parser(config):
472
478
        """Construct a new dict of client settings of this form:
497
503
                          "rb") as secfile:
498
504
                    client["secret"] = secfile.read()
499
505
            else:
500
 
                raise TypeError("No secret or secfile for section {}"
 
506
                raise TypeError("No secret or secfile for section {0}"
501
507
                                .format(section))
502
508
            client["timeout"] = string_to_delta(section["timeout"])
503
509
            client["extended_timeout"] = string_to_delta(
514
520
        
515
521
        return settings
516
522
    
517
 
    def __init__(self, settings, name = None, server_settings=None):
 
523
    def __init__(self, settings, name = None):
518
524
        self.name = name
519
 
        if server_settings is None:
520
 
            server_settings = {}
521
 
        self.server_settings = server_settings
522
525
        # adding all client settings
523
 
        for setting, value in settings.items():
 
526
        for setting, value in settings.iteritems():
524
527
            setattr(self, setting, value)
525
528
        
526
529
        if self.enabled:
609
612
        if self.checker_initiator_tag is not None:
610
613
            gobject.source_remove(self.checker_initiator_tag)
611
614
        self.checker_initiator_tag = (gobject.timeout_add
612
 
                                      (int(self.interval
613
 
                                           .total_seconds() * 1000),
 
615
                                      (self.interval_milliseconds(),
614
616
                                       self.start_checker))
615
617
        # Schedule a disable() when 'timeout' has passed
616
618
        if self.disable_initiator_tag is not None:
617
619
            gobject.source_remove(self.disable_initiator_tag)
618
620
        self.disable_initiator_tag = (gobject.timeout_add
619
 
                                      (int(self.timeout
620
 
                                           .total_seconds() * 1000),
621
 
                                       self.disable))
 
621
                                   (self.timeout_milliseconds(),
 
622
                                    self.disable))
622
623
        # Also start a new checker *right now*.
623
624
        self.start_checker()
624
625
    
655
656
            self.disable_initiator_tag = None
656
657
        if getattr(self, "enabled", False):
657
658
            self.disable_initiator_tag = (gobject.timeout_add
658
 
                                          (int(timeout.total_seconds()
659
 
                                               * 1000), self.disable))
 
659
                                          (timedelta_to_milliseconds
 
660
                                           (timeout), self.disable))
660
661
            self.expires = datetime.datetime.utcnow() + timeout
661
662
    
662
663
    def need_approval(self):
679
680
        # If a checker exists, make sure it is not a zombie
680
681
        try:
681
682
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
682
 
        except AttributeError:
683
 
            pass
684
 
        except OSError as error:
685
 
            if error.errno != errno.ECHILD:
686
 
                raise
 
683
        except (AttributeError, OSError) as error:
 
684
            if (isinstance(error, OSError)
 
685
                and error.errno != errno.ECHILD):
 
686
                raise error
687
687
        else:
688
688
            if pid:
689
689
                logger.warning("Checker was a zombie")
693
693
        # Start a new checker if needed
694
694
        if self.checker is None:
695
695
            # Escape attributes for the shell
696
 
            escaped_attrs = { attr:
697
 
                                  re.escape(str(getattr(self, attr)))
698
 
                              for attr in self.runtime_expansions }
 
696
            escaped_attrs = dict(
 
697
                (attr, re.escape(unicode(getattr(self, attr))))
 
698
                for attr in
 
699
                self.runtime_expansions)
699
700
            try:
700
701
                command = self.checker_command % escaped_attrs
701
702
            except TypeError as error:
710
711
                # in normal mode, that is already done by daemon(),
711
712
                # and in debug mode we don't want to.  (Stdin is
712
713
                # always replaced by /dev/null.)
713
 
                # The exception is when not debugging but nevertheless
714
 
                # running in the foreground; use the previously
715
 
                # created wnull.
716
 
                popen_args = {}
717
 
                if (not self.server_settings["debug"]
718
 
                    and self.server_settings["foreground"]):
719
 
                    popen_args.update({"stdout": wnull,
720
 
                                       "stderr": wnull })
721
714
                self.checker = subprocess.Popen(command,
722
715
                                                close_fds=True,
723
 
                                                shell=True, cwd="/",
724
 
                                                **popen_args)
 
716
                                                shell=True, cwd="/")
725
717
            except OSError as error:
726
718
                logger.error("Failed to start subprocess",
727
719
                             exc_info=error)
782
774
    # "Set" method, so we fail early here:
783
775
    if byte_arrays and signature != "ay":
784
776
        raise ValueError("Byte arrays not supported for non-'ay'"
785
 
                         " signature {!r}".format(signature))
 
777
                         " signature {0!r}".format(signature))
786
778
    def decorator(func):
787
779
        func._dbus_is_property = True
788
780
        func._dbus_interface = dbus_interface
819
811
    """Decorator to annotate D-Bus methods, signals or properties
820
812
    Usage:
821
813
    
822
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
823
 
                       "org.freedesktop.DBus.Property."
824
 
                       "EmitsChangedSignal": "false"})
825
814
    @dbus_service_property("org.example.Interface", signature="b",
826
815
                           access="r")
 
816
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
817
                        "org.freedesktop.DBus.Property."
 
818
                        "EmitsChangedSignal": "false"})
827
819
    def Property_dbus_property(self):
828
820
        return dbus.Boolean(False)
829
821
    """
836
828
class DBusPropertyException(dbus.exceptions.DBusException):
837
829
    """A base class for D-Bus property-related exceptions
838
830
    """
839
 
    pass
 
831
    def __unicode__(self):
 
832
        return unicode(str(self))
 
833
 
840
834
 
841
835
class DBusPropertyAccessException(DBusPropertyException):
842
836
    """A property's access permissions disallows an operation.
865
859
        If called like _is_dbus_thing("method") it returns a function
866
860
        suitable for use as predicate to inspect.getmembers().
867
861
        """
868
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
862
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
869
863
                                   False)
870
864
    
871
865
    def _get_all_dbus_things(self, thing):
920
914
            # The byte_arrays option is not supported yet on
921
915
            # signatures other than "ay".
922
916
            if prop._dbus_signature != "ay":
923
 
                raise ValueError("Byte arrays not supported for non-"
924
 
                                 "'ay' signature {!r}"
925
 
                                 .format(prop._dbus_signature))
 
917
                raise ValueError
926
918
            value = dbus.ByteArray(b''.join(chr(byte)
927
919
                                            for byte in value))
928
920
        prop(value)
952
944
                                           value.variant_level+1)
953
945
        return dbus.Dictionary(properties, signature="sv")
954
946
    
955
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
956
 
    def PropertiesChanged(self, interface_name, changed_properties,
957
 
                          invalidated_properties):
958
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
959
 
        standard.
960
 
        """
961
 
        pass
962
 
    
963
947
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
964
948
                         out_signature="s",
965
949
                         path_keyword='object_path',
1000
984
                                              (prop,
1001
985
                                               "_dbus_annotations",
1002
986
                                               {}))
1003
 
                        for name, value in annots.items():
 
987
                        for name, value in annots.iteritems():
1004
988
                            ann_tag = document.createElement(
1005
989
                                "annotation")
1006
990
                            ann_tag.setAttribute("name", name)
1009
993
                # Add interface annotation tags
1010
994
                for annotation, value in dict(
1011
995
                    itertools.chain.from_iterable(
1012
 
                        annotations().items()
 
996
                        annotations().iteritems()
1013
997
                        for name, annotations in
1014
998
                        self._get_all_dbus_things("interface")
1015
999
                        if name == if_tag.getAttribute("name")
1016
 
                        )).items():
 
1000
                        )).iteritems():
1017
1001
                    ann_tag = document.createElement("annotation")
1018
1002
                    ann_tag.setAttribute("name", annotation)
1019
1003
                    ann_tag.setAttribute("value", value)
1075
1059
    """
1076
1060
    def wrapper(cls):
1077
1061
        for orig_interface_name, alt_interface_name in (
1078
 
            alt_interface_names.items()):
 
1062
            alt_interface_names.iteritems()):
1079
1063
            attr = {}
1080
1064
            interface_names = set()
1081
1065
            # Go though all attributes of the class
1094
1078
                interface_names.add(alt_interface)
1095
1079
                # Is this a D-Bus signal?
1096
1080
                if getattr(attribute, "_dbus_is_signal", False):
1097
 
                    # Extract the original non-method undecorated
1098
 
                    # function by black magic
 
1081
                    # Extract the original non-method function by
 
1082
                    # black magic
1099
1083
                    nonmethod_func = (dict(
1100
1084
                            zip(attribute.func_code.co_freevars,
1101
1085
                                attribute.__closure__))["func"]
1198
1182
                                        attribute.func_closure)))
1199
1183
            if deprecate:
1200
1184
                # Deprecate all alternate interfaces
1201
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1185
                iname="_AlternateDBusNames_interface_annotation{0}"
1202
1186
                for interface_name in interface_names:
1203
1187
                    @dbus_interface_annotations(interface_name)
1204
1188
                    def func(self):
1213
1197
            if interface_names:
1214
1198
                # Replace the class with a new subclass of it with
1215
1199
                # methods, signals, etc. as created above.
1216
 
                cls = type(b"{}Alternate".format(cls.__name__),
 
1200
                cls = type(b"{0}Alternate".format(cls.__name__),
1217
1201
                           (cls,), attr)
1218
1202
        return cls
1219
1203
    return wrapper
1232
1216
    runtime_expansions = (Client.runtime_expansions
1233
1217
                          + ("dbus_object_path",))
1234
1218
    
1235
 
    _interface = "se.recompile.Mandos.Client"
1236
 
    
1237
1219
    # dbus.service.Object doesn't use super(), so we can't either.
1238
1220
    
1239
1221
    def __init__(self, bus = None, *args, **kwargs):
1241
1223
        Client.__init__(self, *args, **kwargs)
1242
1224
        # Only now, when this client is initialized, can it show up on
1243
1225
        # the D-Bus
1244
 
        client_object_name = str(self.name).translate(
 
1226
        client_object_name = unicode(self.name).translate(
1245
1227
            {ord("."): ord("_"),
1246
1228
             ord("-"): ord("_")})
1247
1229
        self.dbus_object_path = (dbus.ObjectPath
1251
1233
    
1252
1234
    def notifychangeproperty(transform_func,
1253
1235
                             dbus_name, type_func=lambda x: x,
1254
 
                             variant_level=1, invalidate_only=False,
1255
 
                             _interface=_interface):
 
1236
                             variant_level=1):
1256
1237
        """ Modify a variable so that it's a property which announces
1257
1238
        its changes to DBus.
1258
1239
        
1263
1244
                   to the D-Bus.  Default: no transform
1264
1245
        variant_level: D-Bus variant level.  Default: 1
1265
1246
        """
1266
 
        attrname = "_{}".format(dbus_name)
 
1247
        attrname = "_{0}".format(dbus_name)
1267
1248
        def setter(self, value):
1268
1249
            if hasattr(self, "dbus_object_path"):
1269
1250
                if (not hasattr(self, attrname) or
1270
1251
                    type_func(getattr(self, attrname, None))
1271
1252
                    != type_func(value)):
1272
 
                    if invalidate_only:
1273
 
                        self.PropertiesChanged(_interface,
1274
 
                                               dbus.Dictionary(),
1275
 
                                               dbus.Array
1276
 
                                               ((dbus_name,)))
1277
 
                    else:
1278
 
                        dbus_value = transform_func(type_func(value),
1279
 
                                                    variant_level
1280
 
                                                    =variant_level)
1281
 
                        self.PropertyChanged(dbus.String(dbus_name),
1282
 
                                             dbus_value)
1283
 
                        self.PropertiesChanged(_interface,
1284
 
                                               dbus.Dictionary({
1285
 
                                    dbus.String(dbus_name):
1286
 
                                        dbus_value }), dbus.Array())
 
1253
                    dbus_value = transform_func(type_func(value),
 
1254
                                                variant_level
 
1255
                                                =variant_level)
 
1256
                    self.PropertyChanged(dbus.String(dbus_name),
 
1257
                                         dbus_value)
1287
1258
            setattr(self, attrname, value)
1288
1259
        
1289
1260
        return property(lambda self: getattr(self, attrname), setter)
1309
1280
    approval_delay = notifychangeproperty(dbus.UInt64,
1310
1281
                                          "ApprovalDelay",
1311
1282
                                          type_func =
1312
 
                                          lambda td: td.total_seconds()
1313
 
                                          * 1000)
 
1283
                                          timedelta_to_milliseconds)
1314
1284
    approval_duration = notifychangeproperty(
1315
1285
        dbus.UInt64, "ApprovalDuration",
1316
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1286
        type_func = timedelta_to_milliseconds)
1317
1287
    host = notifychangeproperty(dbus.String, "Host")
1318
1288
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
 
                                   type_func = lambda td:
1320
 
                                       td.total_seconds() * 1000)
 
1289
                                   type_func =
 
1290
                                   timedelta_to_milliseconds)
1321
1291
    extended_timeout = notifychangeproperty(
1322
1292
        dbus.UInt64, "ExtendedTimeout",
1323
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1293
        type_func = timedelta_to_milliseconds)
1324
1294
    interval = notifychangeproperty(dbus.UInt64,
1325
1295
                                    "Interval",
1326
1296
                                    type_func =
1327
 
                                    lambda td: td.total_seconds()
1328
 
                                    * 1000)
 
1297
                                    timedelta_to_milliseconds)
1329
1298
    checker_command = notifychangeproperty(dbus.String, "Checker")
1330
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
 
                                  invalidate_only=True)
1332
1299
    
1333
1300
    del notifychangeproperty
1334
1301
    
1361
1328
                                       *args, **kwargs)
1362
1329
    
1363
1330
    def start_checker(self, *args, **kwargs):
1364
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1331
        old_checker = self.checker
 
1332
        if self.checker is not None:
 
1333
            old_checker_pid = self.checker.pid
 
1334
        else:
 
1335
            old_checker_pid = None
1365
1336
        r = Client.start_checker(self, *args, **kwargs)
1366
1337
        # Only if new checker process was started
1367
1338
        if (self.checker is not None
1376
1347
    
1377
1348
    def approve(self, value=True):
1378
1349
        self.approved = value
1379
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1380
 
                                * 1000), self._reset_approved)
 
1350
        gobject.timeout_add(timedelta_to_milliseconds
 
1351
                            (self.approval_duration),
 
1352
                            self._reset_approved)
1381
1353
        self.send_changedstate()
1382
1354
    
1383
1355
    ## D-Bus methods, signals & properties
 
1356
    _interface = "se.recompile.Mandos.Client"
1384
1357
    
1385
1358
    ## Interfaces
1386
1359
    
 
1360
    @dbus_interface_annotations(_interface)
 
1361
    def _foo(self):
 
1362
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1363
                     "false"}
 
1364
    
1387
1365
    ## Signals
1388
1366
    
1389
1367
    # CheckerCompleted - signal
1399
1377
        pass
1400
1378
    
1401
1379
    # PropertyChanged - signal
1402
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1403
1380
    @dbus.service.signal(_interface, signature="sv")
1404
1381
    def PropertyChanged(self, property, value):
1405
1382
        "D-Bus signal"
1481
1458
                           access="readwrite")
1482
1459
    def ApprovalDelay_dbus_property(self, value=None):
1483
1460
        if value is None:       # get
1484
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1485
 
                               * 1000)
 
1461
            return dbus.UInt64(self.approval_delay_milliseconds())
1486
1462
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1487
1463
    
1488
1464
    # ApprovalDuration - property
1490
1466
                           access="readwrite")
1491
1467
    def ApprovalDuration_dbus_property(self, value=None):
1492
1468
        if value is None:       # get
1493
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1494
 
                               * 1000)
 
1469
            return dbus.UInt64(timedelta_to_milliseconds(
 
1470
                    self.approval_duration))
1495
1471
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1496
1472
    
1497
1473
    # Name - property
1510
1486
    def Host_dbus_property(self, value=None):
1511
1487
        if value is None:       # get
1512
1488
            return dbus.String(self.host)
1513
 
        self.host = str(value)
 
1489
        self.host = unicode(value)
1514
1490
    
1515
1491
    # Created - property
1516
1492
    @dbus_service_property(_interface, signature="s", access="read")
1563
1539
                           access="readwrite")
1564
1540
    def Timeout_dbus_property(self, value=None):
1565
1541
        if value is None:       # get
1566
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1542
            return dbus.UInt64(self.timeout_milliseconds())
1567
1543
        old_timeout = self.timeout
1568
1544
        self.timeout = datetime.timedelta(0, 0, 0, value)
1569
1545
        # Reschedule disabling
1580
1556
                gobject.source_remove(self.disable_initiator_tag)
1581
1557
                self.disable_initiator_tag = (
1582
1558
                    gobject.timeout_add(
1583
 
                        int((self.expires - now).total_seconds()
1584
 
                            * 1000), self.disable))
 
1559
                        timedelta_to_milliseconds(self.expires - now),
 
1560
                        self.disable))
1585
1561
    
1586
1562
    # ExtendedTimeout - property
1587
1563
    @dbus_service_property(_interface, signature="t",
1588
1564
                           access="readwrite")
1589
1565
    def ExtendedTimeout_dbus_property(self, value=None):
1590
1566
        if value is None:       # get
1591
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
1592
 
                               * 1000)
 
1567
            return dbus.UInt64(self.extended_timeout_milliseconds())
1593
1568
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1594
1569
    
1595
1570
    # Interval - property
1597
1572
                           access="readwrite")
1598
1573
    def Interval_dbus_property(self, value=None):
1599
1574
        if value is None:       # get
1600
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1575
            return dbus.UInt64(self.interval_milliseconds())
1601
1576
        self.interval = datetime.timedelta(0, 0, 0, value)
1602
1577
        if getattr(self, "checker_initiator_tag", None) is None:
1603
1578
            return
1614
1589
    def Checker_dbus_property(self, value=None):
1615
1590
        if value is None:       # get
1616
1591
            return dbus.String(self.checker_command)
1617
 
        self.checker_command = str(value)
 
1592
        self.checker_command = unicode(value)
1618
1593
    
1619
1594
    # CheckerRunning - property
1620
1595
    @dbus_service_property(_interface, signature="b",
1636
1611
    @dbus_service_property(_interface, signature="ay",
1637
1612
                           access="write", byte_arrays=True)
1638
1613
    def Secret_dbus_property(self, value):
1639
 
        self.secret = bytes(value)
 
1614
        self.secret = str(value)
1640
1615
    
1641
1616
    del _interface
1642
1617
 
1676
1651
    def handle(self):
1677
1652
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1678
1653
            logger.info("TCP connection from: %s",
1679
 
                        str(self.client_address))
 
1654
                        unicode(self.client_address))
1680
1655
            logger.debug("Pipe FD: %d",
1681
1656
                         self.server.child_pipe.fileno())
1682
1657
            
1708
1683
            logger.debug("Protocol version: %r", line)
1709
1684
            try:
1710
1685
                if int(line.strip().split()[0]) > 1:
1711
 
                    raise RuntimeError(line)
 
1686
                    raise RuntimeError
1712
1687
            except (ValueError, IndexError, RuntimeError) as error:
1713
1688
                logger.error("Unknown protocol version: %s", error)
1714
1689
                return
1763
1738
                        if self.server.use_dbus:
1764
1739
                            # Emit D-Bus signal
1765
1740
                            client.NeedApproval(
1766
 
                                client.approval_delay.total_seconds()
1767
 
                                * 1000, client.approved_by_default)
 
1741
                                client.approval_delay_milliseconds(),
 
1742
                                client.approved_by_default)
1768
1743
                    else:
1769
1744
                        logger.warning("Client %s was not approved",
1770
1745
                                       client.name)
1776
1751
                    #wait until timeout or approved
1777
1752
                    time = datetime.datetime.now()
1778
1753
                    client.changedstate.acquire()
1779
 
                    client.changedstate.wait(delay.total_seconds())
 
1754
                    client.changedstate.wait(
 
1755
                        float(timedelta_to_milliseconds(delay)
 
1756
                              / 1000))
1780
1757
                    client.changedstate.release()
1781
1758
                    time2 = datetime.datetime.now()
1782
1759
                    if (time2 - time) >= delay:
1919
1896
    
1920
1897
    def add_pipe(self, parent_pipe, proc):
1921
1898
        """Dummy function; override as necessary"""
1922
 
        raise NotImplementedError()
 
1899
        raise NotImplementedError
1923
1900
 
1924
1901
 
1925
1902
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1981
1958
                try:
1982
1959
                    self.socket.setsockopt(socket.SOL_SOCKET,
1983
1960
                                           SO_BINDTODEVICE,
1984
 
                                           (self.interface + "\0")
1985
 
                                           .encode("utf-8"))
 
1961
                                           str(self.interface + '\0'))
1986
1962
                except socket.error as error:
1987
1963
                    if error.errno == errno.EPERM:
1988
1964
                        logger.error("No permission to bind to"
2002
1978
                if self.address_family == socket.AF_INET6:
2003
1979
                    any_address = "::" # in6addr_any
2004
1980
                else:
2005
 
                    any_address = "0.0.0.0" # INADDR_ANY
 
1981
                    any_address = socket.INADDR_ANY
2006
1982
                self.server_address = (any_address,
2007
1983
                                       self.server_address[1])
2008
1984
            elif not self.server_address[1]:
2191
2167
    token_duration = Token(re.compile(r"P"), None,
2192
2168
                           frozenset((token_year, token_month,
2193
2169
                                      token_day, token_time,
2194
 
                                      token_week)))
 
2170
                                      token_week))),
2195
2171
    # Define starting values
2196
2172
    value = datetime.timedelta() # Value so far
2197
2173
    found_token = None
2198
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2174
    followers = frozenset(token_duration,) # Following valid tokens
2199
2175
    s = duration                # String left to parse
2200
2176
    # Loop until end token is found
2201
2177
    while found_token is not token_end:
2248
2224
    timevalue = datetime.timedelta(0)
2249
2225
    for s in interval.split():
2250
2226
        try:
2251
 
            suffix = s[-1]
 
2227
            suffix = unicode(s[-1])
2252
2228
            value = int(s[:-1])
2253
2229
            if suffix == "d":
2254
2230
                delta = datetime.timedelta(value)
2261
2237
            elif suffix == "w":
2262
2238
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2263
2239
            else:
2264
 
                raise ValueError("Unknown suffix {!r}"
 
2240
                raise ValueError("Unknown suffix {0!r}"
2265
2241
                                 .format(suffix))
2266
 
        except IndexError as e:
 
2242
        except (ValueError, IndexError) as e:
2267
2243
            raise ValueError(*(e.args))
2268
2244
        timevalue += delta
2269
2245
    return timevalue
2284
2260
        # Close all standard open file descriptors
2285
2261
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2286
2262
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2287
 
            raise OSError(errno.ENODEV, "{} not a character device"
 
2263
            raise OSError(errno.ENODEV,
 
2264
                          "{0} not a character device"
2288
2265
                          .format(os.devnull))
2289
2266
        os.dup2(null, sys.stdin.fileno())
2290
2267
        os.dup2(null, sys.stdout.fileno())
2300
2277
    
2301
2278
    parser = argparse.ArgumentParser()
2302
2279
    parser.add_argument("-v", "--version", action="version",
2303
 
                        version = "%(prog)s {}".format(version),
 
2280
                        version = "%(prog)s {0}".format(version),
2304
2281
                        help="show version number and exit")
2305
2282
    parser.add_argument("-i", "--interface", metavar="IF",
2306
2283
                        help="Bind to interface IF")
2312
2289
                        help="Run self-test")
2313
2290
    parser.add_argument("--debug", action="store_true",
2314
2291
                        help="Debug mode; run in foreground and log"
2315
 
                        " to terminal", default=None)
 
2292
                        " to terminal")
2316
2293
    parser.add_argument("--debuglevel", metavar="LEVEL",
2317
2294
                        help="Debug level for stdout output")
2318
2295
    parser.add_argument("--priority", help="GnuTLS"
2325
2302
                        " files")
2326
2303
    parser.add_argument("--no-dbus", action="store_false",
2327
2304
                        dest="use_dbus", help="Do not provide D-Bus"
2328
 
                        " system bus interface", default=None)
 
2305
                        " system bus interface")
2329
2306
    parser.add_argument("--no-ipv6", action="store_false",
2330
 
                        dest="use_ipv6", help="Do not use IPv6",
2331
 
                        default=None)
 
2307
                        dest="use_ipv6", help="Do not use IPv6")
2332
2308
    parser.add_argument("--no-restore", action="store_false",
2333
2309
                        dest="restore", help="Do not restore stored"
2334
 
                        " state", default=None)
 
2310
                        " state")
2335
2311
    parser.add_argument("--socket", type=int,
2336
2312
                        help="Specify a file descriptor to a network"
2337
2313
                        " socket to use instead of creating one")
2338
2314
    parser.add_argument("--statedir", metavar="DIR",
2339
2315
                        help="Directory to save/restore state in")
2340
2316
    parser.add_argument("--foreground", action="store_true",
2341
 
                        help="Run in foreground", default=None)
2342
 
    parser.add_argument("--no-zeroconf", action="store_false",
2343
 
                        dest="zeroconf", help="Do not use Zeroconf",
2344
 
                        default=None)
 
2317
                        help="Run in foreground")
2345
2318
    
2346
2319
    options = parser.parse_args()
2347
2320
    
2348
2321
    if options.check:
2349
2322
        import doctest
2350
 
        fail_count, test_count = doctest.testmod()
2351
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2323
        doctest.testmod()
 
2324
        sys.exit()
2352
2325
    
2353
2326
    # Default values for config file for server-global settings
2354
2327
    server_defaults = { "interface": "",
2356
2329
                        "port": "",
2357
2330
                        "debug": "False",
2358
2331
                        "priority":
2359
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2332
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
2360
2333
                        "servicename": "Mandos",
2361
2334
                        "use_dbus": "True",
2362
2335
                        "use_ipv6": "True",
2365
2338
                        "socket": "",
2366
2339
                        "statedir": "/var/lib/mandos",
2367
2340
                        "foreground": "False",
2368
 
                        "zeroconf": "True",
2369
2341
                        }
2370
2342
    
2371
2343
    # Parse config file for server-global settings
2398
2370
    for option in ("interface", "address", "port", "debug",
2399
2371
                   "priority", "servicename", "configdir",
2400
2372
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2401
 
                   "statedir", "socket", "foreground", "zeroconf"):
 
2373
                   "statedir", "socket", "foreground"):
2402
2374
        value = getattr(options, option)
2403
2375
        if value is not None:
2404
2376
            server_settings[option] = value
2405
2377
    del options
2406
2378
    # Force all strings to be unicode
2407
2379
    for option in server_settings.keys():
2408
 
        if isinstance(server_settings[option], bytes):
2409
 
            server_settings[option] = (server_settings[option]
2410
 
                                       .decode("utf-8"))
2411
 
    # Force all boolean options to be boolean
2412
 
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2413
 
                   "foreground", "zeroconf"):
2414
 
        server_settings[option] = bool(server_settings[option])
 
2380
        if type(server_settings[option]) is str:
 
2381
            server_settings[option] = unicode(server_settings[option])
2415
2382
    # Debug implies foreground
2416
2383
    if server_settings["debug"]:
2417
2384
        server_settings["foreground"] = True
2419
2386
    
2420
2387
    ##################################################################
2421
2388
    
2422
 
    if (not server_settings["zeroconf"] and
2423
 
        not (server_settings["port"]
2424
 
             or server_settings["socket"] != "")):
2425
 
            parser.error("Needs port or socket to work without"
2426
 
                         " Zeroconf")
2427
 
    
2428
2389
    # For convenience
2429
2390
    debug = server_settings["debug"]
2430
2391
    debuglevel = server_settings["debuglevel"]
2433
2394
    stored_state_path = os.path.join(server_settings["statedir"],
2434
2395
                                     stored_state_file)
2435
2396
    foreground = server_settings["foreground"]
2436
 
    zeroconf = server_settings["zeroconf"]
2437
2397
    
2438
2398
    if debug:
2439
2399
        initlogger(debug, logging.DEBUG)
2446
2406
    
2447
2407
    if server_settings["servicename"] != "Mandos":
2448
2408
        syslogger.setFormatter(logging.Formatter
2449
 
                               ('Mandos ({}) [%(process)d]:'
 
2409
                               ('Mandos ({0}) [%(process)d]:'
2450
2410
                                ' %(levelname)s: %(message)s'
2451
2411
                                .format(server_settings
2452
2412
                                        ["servicename"])))
2460
2420
    global mandos_dbus_service
2461
2421
    mandos_dbus_service = None
2462
2422
    
2463
 
    socketfd = None
2464
 
    if server_settings["socket"] != "":
2465
 
        socketfd = server_settings["socket"]
2466
2423
    tcp_server = MandosServer((server_settings["address"],
2467
2424
                               server_settings["port"]),
2468
2425
                              ClientHandler,
2472
2429
                              gnutls_priority=
2473
2430
                              server_settings["priority"],
2474
2431
                              use_dbus=use_dbus,
2475
 
                              socketfd=socketfd)
 
2432
                              socketfd=(server_settings["socket"]
 
2433
                                        or None))
2476
2434
    if not foreground:
2477
 
        pidfilename = "/run/mandos.pid"
2478
 
        if not os.path.isdir("/run/."):
2479
 
            pidfilename = "/var/run/mandos.pid"
 
2435
        pidfilename = "/var/run/mandos.pid"
2480
2436
        pidfile = None
2481
2437
        try:
2482
2438
            pidfile = open(pidfilename, "w")
2499
2455
        os.setuid(uid)
2500
2456
    except OSError as error:
2501
2457
        if error.errno != errno.EPERM:
2502
 
            raise
 
2458
            raise error
2503
2459
    
2504
2460
    if debug:
2505
2461
        # Enable all possible GnuTLS debugging
2548
2504
            use_dbus = False
2549
2505
            server_settings["use_dbus"] = False
2550
2506
            tcp_server.use_dbus = False
2551
 
    if zeroconf:
2552
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2553
 
        service = AvahiServiceToSyslog(name =
2554
 
                                       server_settings["servicename"],
2555
 
                                       servicetype = "_mandos._tcp",
2556
 
                                       protocol = protocol, bus = bus)
2557
 
        if server_settings["interface"]:
2558
 
            service.interface = (if_nametoindex
2559
 
                                 (server_settings["interface"]
2560
 
                                  .encode("utf-8")))
 
2507
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2508
    service = AvahiServiceToSyslog(name =
 
2509
                                   server_settings["servicename"],
 
2510
                                   servicetype = "_mandos._tcp",
 
2511
                                   protocol = protocol, bus = bus)
 
2512
    if server_settings["interface"]:
 
2513
        service.interface = (if_nametoindex
 
2514
                             (str(server_settings["interface"])))
2561
2515
    
2562
2516
    global multiprocessing_manager
2563
2517
    multiprocessing_manager = multiprocessing.Manager()
2570
2524
    old_client_settings = {}
2571
2525
    clients_data = {}
2572
2526
    
2573
 
    # This is used to redirect stdout and stderr for checker processes
2574
 
    global wnull
2575
 
    wnull = open(os.devnull, "w") # A writable /dev/null
2576
 
    # Only used if server is running in foreground but not in debug
2577
 
    # mode
2578
 
    if debug or not foreground:
2579
 
        wnull.close()
2580
 
    
2581
2527
    # Get client data and settings from last running state.
2582
2528
    if server_settings["restore"]:
2583
2529
        try:
2587
2533
            os.remove(stored_state_path)
2588
2534
        except IOError as e:
2589
2535
            if e.errno == errno.ENOENT:
2590
 
                logger.warning("Could not load persistent state: {}"
 
2536
                logger.warning("Could not load persistent state: {0}"
2591
2537
                                .format(os.strerror(e.errno)))
2592
2538
            else:
2593
2539
                logger.critical("Could not load persistent state:",
2598
2544
                           "EOFError:", exc_info=e)
2599
2545
    
2600
2546
    with PGPEngine() as pgp:
2601
 
        for client_name, client in clients_data.items():
2602
 
            # Skip removed clients
2603
 
            if client_name not in client_settings:
2604
 
                continue
2605
 
            
 
2547
        for client_name, client in clients_data.iteritems():
2606
2548
            # Decide which value to use after restoring saved state.
2607
2549
            # We have three different values: Old config file,
2608
2550
            # new config file, and saved state.
2629
2571
                if datetime.datetime.utcnow() >= client["expires"]:
2630
2572
                    if not client["last_checked_ok"]:
2631
2573
                        logger.warning(
2632
 
                            "disabling client {} - Client never "
 
2574
                            "disabling client {0} - Client never "
2633
2575
                            "performed a successful checker"
2634
2576
                            .format(client_name))
2635
2577
                        client["enabled"] = False
2636
2578
                    elif client["last_checker_status"] != 0:
2637
2579
                        logger.warning(
2638
 
                            "disabling client {} - Client last"
2639
 
                            " checker failed with error code {}"
 
2580
                            "disabling client {0} - Client "
 
2581
                            "last checker failed with error code {1}"
2640
2582
                            .format(client_name,
2641
2583
                                    client["last_checker_status"]))
2642
2584
                        client["enabled"] = False
2645
2587
                                             .utcnow()
2646
2588
                                             + client["timeout"])
2647
2589
                        logger.debug("Last checker succeeded,"
2648
 
                                     " keeping {} enabled"
 
2590
                                     " keeping {0} enabled"
2649
2591
                                     .format(client_name))
2650
2592
            try:
2651
2593
                client["secret"] = (
2654
2596
                                ["secret"]))
2655
2597
            except PGPError:
2656
2598
                # If decryption fails, we use secret from new settings
2657
 
                logger.debug("Failed to decrypt {} old secret"
 
2599
                logger.debug("Failed to decrypt {0} old secret"
2658
2600
                             .format(client_name))
2659
2601
                client["secret"] = (
2660
2602
                    client_settings[client_name]["secret"])
2668
2610
        clients_data[client_name] = client_settings[client_name]
2669
2611
    
2670
2612
    # Create all client objects
2671
 
    for client_name, client in clients_data.items():
 
2613
    for client_name, client in clients_data.iteritems():
2672
2614
        tcp_server.clients[client_name] = client_class(
2673
 
            name = client_name, settings = client,
2674
 
            server_settings = server_settings)
 
2615
            name = client_name, settings = client)
2675
2616
    
2676
2617
    if not tcp_server.clients:
2677
2618
        logger.warning("No clients defined")
2681
2622
            try:
2682
2623
                with pidfile:
2683
2624
                    pid = os.getpid()
2684
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2625
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
2685
2626
            except IOError:
2686
2627
                logger.error("Could not write to file %r with PID %d",
2687
2628
                             pidfilename, pid)
2733
2674
            def GetAllClientsWithProperties(self):
2734
2675
                "D-Bus method"
2735
2676
                return dbus.Dictionary(
2736
 
                    { c.dbus_object_path: c.GetAll("")
2737
 
                      for c in tcp_server.clients.itervalues() },
 
2677
                    ((c.dbus_object_path, c.GetAll(""))
 
2678
                     for c in tcp_server.clients.itervalues()),
2738
2679
                    signature="oa{sv}")
2739
2680
            
2740
2681
            @dbus.service.method(_interface, in_signature="o")
2757
2698
    
2758
2699
    def cleanup():
2759
2700
        "Cleanup function; run on exit"
2760
 
        if zeroconf:
2761
 
            service.cleanup()
 
2701
        service.cleanup()
2762
2702
        
2763
2703
        multiprocessing.active_children()
2764
 
        wnull.close()
2765
2704
        if not (tcp_server.clients or client_settings):
2766
2705
            return
2767
2706
        
2778
2717
                
2779
2718
                # A list of attributes that can not be pickled
2780
2719
                # + secret.
2781
 
                exclude = { "bus", "changedstate", "secret",
2782
 
                            "checker", "server_settings" }
 
2720
                exclude = set(("bus", "changedstate", "secret",
 
2721
                               "checker"))
2783
2722
                for name, typ in (inspect.getmembers
2784
2723
                                  (dbus.service.Object)):
2785
2724
                    exclude.add(name)
2808
2747
                except NameError:
2809
2748
                    pass
2810
2749
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2811
 
                logger.warning("Could not save persistent state: {}"
 
2750
                logger.warning("Could not save persistent state: {0}"
2812
2751
                               .format(os.strerror(e.errno)))
2813
2752
            else:
2814
2753
                logger.warning("Could not save persistent state:",
2815
2754
                               exc_info=e)
2816
 
                raise
 
2755
                raise e
2817
2756
        
2818
2757
        # Delete all clients, and settings from config
2819
2758
        while tcp_server.clients:
2843
2782
    tcp_server.server_activate()
2844
2783
    
2845
2784
    # Find out what port we got
2846
 
    if zeroconf:
2847
 
        service.port = tcp_server.socket.getsockname()[1]
 
2785
    service.port = tcp_server.socket.getsockname()[1]
2848
2786
    if use_ipv6:
2849
2787
        logger.info("Now listening on address %r, port %d,"
2850
2788
                    " flowinfo %d, scope_id %d",
2856
2794
    #service.interface = tcp_server.socket.getsockname()[3]
2857
2795
    
2858
2796
    try:
2859
 
        if zeroconf:
2860
 
            # From the Avahi example code
2861
 
            try:
2862
 
                service.activate()
2863
 
            except dbus.exceptions.DBusException as error:
2864
 
                logger.critical("D-Bus Exception", exc_info=error)
2865
 
                cleanup()
2866
 
                sys.exit(1)
2867
 
            # End of Avahi example code
 
2797
        # From the Avahi example code
 
2798
        try:
 
2799
            service.activate()
 
2800
        except dbus.exceptions.DBusException as error:
 
2801
            logger.critical("D-Bus Exception", exc_info=error)
 
2802
            cleanup()
 
2803
            sys.exit(1)
 
2804
        # End of Avahi example code
2868
2805
        
2869
2806
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2870
2807
                             lambda *args, **kwargs: