/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: teddy at bsnet
  • Date: 2011-03-15 19:15:24 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110315191524-jc3ajgqu2za7dcly
* mandos: Use the new argparse library instead of optparse.
* debian/control (mandos): Depend on python (<=2.7) | python-argparse

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008,2009 Teddy Hogeborn
15
 
# Copyright © 2008,2009 Björn Påhlsson
 
14
# Copyright © 2008-2011 Teddy Hogeborn
 
15
# Copyright © 2008-2011 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
31
31
# Contact the authors at <mandos@fukt.bsnet.se>.
32
32
33
33
 
34
 
from __future__ import division, with_statement, absolute_import
 
34
from __future__ import (division, absolute_import, print_function,
 
35
                        unicode_literals)
35
36
 
36
37
import SocketServer as socketserver
37
38
import socket
38
 
import optparse
 
39
import argparse
39
40
import datetime
40
41
import errno
41
42
import gnutls.crypto
81
82
        SO_BINDTODEVICE = None
82
83
 
83
84
 
84
 
version = "1.0.14"
 
85
version = "1.3.0"
85
86
 
86
 
#logger = logging.getLogger(u'mandos')
87
 
logger = logging.Logger(u'mandos')
 
87
#logger = logging.getLogger('mandos')
 
88
logger = logging.Logger('mandos')
88
89
syslogger = (logging.handlers.SysLogHandler
89
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
90
 
              address = "/dev/log"))
 
91
              address = str("/dev/log")))
91
92
syslogger.setFormatter(logging.Formatter
92
 
                       (u'Mandos [%(process)d]: %(levelname)s:'
93
 
                        u' %(message)s'))
 
93
                       ('Mandos [%(process)d]: %(levelname)s:'
 
94
                        ' %(message)s'))
94
95
logger.addHandler(syslogger)
95
96
 
96
97
console = logging.StreamHandler()
97
 
console.setFormatter(logging.Formatter(u'%(name)s [%(process)d]:'
98
 
                                       u' %(levelname)s:'
99
 
                                       u' %(message)s'))
 
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
99
                                       ' %(levelname)s:'
 
100
                                       ' %(message)s'))
100
101
logger.addHandler(console)
101
102
 
102
103
class AvahiError(Exception):
119
120
    Attributes:
120
121
    interface: integer; avahi.IF_UNSPEC or an interface index.
121
122
               Used to optionally bind to the specified interface.
122
 
    name: string; Example: u'Mandos'
123
 
    type: string; Example: u'_mandos._tcp'.
 
123
    name: string; Example: 'Mandos'
 
124
    type: string; Example: '_mandos._tcp'.
124
125
                  See <http://www.dns-sd.org/ServiceTypes.html>
125
126
    port: integer; what port to announce
126
127
    TXT: list of strings; TXT record for the service
135
136
    """
136
137
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
137
138
                 servicetype = None, port = None, TXT = None,
138
 
                 domain = u"", host = u"", max_renames = 32768,
 
139
                 domain = "", host = "", max_renames = 32768,
139
140
                 protocol = avahi.PROTO_UNSPEC, bus = None):
140
141
        self.interface = interface
141
142
        self.name = name
153
154
    def rename(self):
154
155
        """Derived from the Avahi example code"""
155
156
        if self.rename_count >= self.max_renames:
156
 
            logger.critical(u"No suitable Zeroconf service name found"
157
 
                            u" after %i retries, exiting.",
 
157
            logger.critical("No suitable Zeroconf service name found"
 
158
                            " after %i retries, exiting.",
158
159
                            self.rename_count)
159
 
            raise AvahiServiceError(u"Too many renames")
 
160
            raise AvahiServiceError("Too many renames")
160
161
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
161
 
        logger.info(u"Changing Zeroconf service name to %r ...",
 
162
        logger.info("Changing Zeroconf service name to %r ...",
162
163
                    self.name)
163
164
        syslogger.setFormatter(logging.Formatter
164
 
                               (u'Mandos (%s) [%%(process)d]:'
165
 
                                u' %%(levelname)s: %%(message)s'
 
165
                               ('Mandos (%s) [%%(process)d]:'
 
166
                                ' %%(levelname)s: %%(message)s'
166
167
                                % self.name))
167
168
        self.remove()
168
169
        try:
169
170
            self.add()
170
171
        except dbus.exceptions.DBusException, error:
171
 
            logger.critical(u"DBusException: %s", error)
 
172
            logger.critical("DBusException: %s", error)
172
173
            self.cleanup()
173
174
            os._exit(1)
174
175
        self.rename_count += 1
186
187
            self.group.connect_to_signal('StateChanged',
187
188
                                         self
188
189
                                         .entry_group_state_changed)
189
 
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
 
190
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
190
191
                     self.name, self.type)
191
192
        self.group.AddService(
192
193
            self.interface,
199
200
        self.group.Commit()
200
201
    def entry_group_state_changed(self, state, error):
201
202
        """Derived from the Avahi example code"""
202
 
        logger.debug(u"Avahi entry group state change: %i", state)
 
203
        logger.debug("Avahi entry group state change: %i", state)
203
204
        
204
205
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
205
 
            logger.debug(u"Zeroconf service established.")
 
206
            logger.debug("Zeroconf service established.")
206
207
        elif state == avahi.ENTRY_GROUP_COLLISION:
207
 
            logger.warning(u"Zeroconf service name collision.")
 
208
            logger.info("Zeroconf service name collision.")
208
209
            self.rename()
209
210
        elif state == avahi.ENTRY_GROUP_FAILURE:
210
 
            logger.critical(u"Avahi: Error in group state changed %s",
 
211
            logger.critical("Avahi: Error in group state changed %s",
211
212
                            unicode(error))
212
 
            raise AvahiGroupError(u"State changed: %s"
 
213
            raise AvahiGroupError("State changed: %s"
213
214
                                  % unicode(error))
214
215
    def cleanup(self):
215
216
        """Derived from the Avahi example code"""
218
219
            self.group = None
219
220
    def server_state_changed(self, state):
220
221
        """Derived from the Avahi example code"""
221
 
        logger.debug(u"Avahi server state change: %i", state)
 
222
        logger.debug("Avahi server state change: %i", state)
222
223
        if state == avahi.SERVER_COLLISION:
223
 
            logger.error(u"Zeroconf server name collision")
 
224
            logger.error("Zeroconf server name collision")
224
225
            self.remove()
225
226
        elif state == avahi.SERVER_RUNNING:
226
227
            self.add()
231
232
                self.bus.get_object(avahi.DBUS_NAME,
232
233
                                    avahi.DBUS_PATH_SERVER),
233
234
                avahi.DBUS_INTERFACE_SERVER)
234
 
        self.server.connect_to_signal(u"StateChanged",
 
235
        self.server.connect_to_signal("StateChanged",
235
236
                                 self.server_state_changed)
236
237
        self.server_state_changed(self.server.GetState())
237
238
 
240
241
    """A representation of a client host served by this server.
241
242
    
242
243
    Attributes:
243
 
    name:       string; from the config file, used in log messages and
244
 
                        D-Bus identifiers
 
244
    _approved:   bool(); 'None' if not yet approved/disapproved
 
245
    approval_delay: datetime.timedelta(); Time to wait for approval
 
246
    approval_duration: datetime.timedelta(); Duration of one approval
 
247
    checker:    subprocess.Popen(); a running checker process used
 
248
                                    to see if the client lives.
 
249
                                    'None' if no process is running.
 
250
    checker_callback_tag: a gobject event source tag, or None
 
251
    checker_command: string; External command which is run to check
 
252
                     if client lives.  %() expansions are done at
 
253
                     runtime with vars(self) as dict, so that for
 
254
                     instance %(name)s can be used in the command.
 
255
    checker_initiator_tag: a gobject event source tag, or None
 
256
    created:    datetime.datetime(); (UTC) object creation
 
257
    current_checker_command: string; current running checker_command
 
258
    disable_hook:  If set, called by disable() as disable_hook(self)
 
259
    disable_initiator_tag: a gobject event source tag, or None
 
260
    enabled:    bool()
245
261
    fingerprint: string (40 or 32 hexadecimal digits); used to
246
262
                 uniquely identify the client
247
 
    secret:     bytestring; sent verbatim (over TLS) to client
248
263
    host:       string; available for use by the checker command
249
 
    created:    datetime.datetime(); (UTC) object creation
 
264
    interval:   datetime.timedelta(); How often to start a new checker
 
265
    last_approval_request: datetime.datetime(); (UTC) or None
 
266
    last_checked_ok: datetime.datetime(); (UTC) or None
250
267
    last_enabled: datetime.datetime(); (UTC)
251
 
    enabled:    bool()
252
 
    last_checked_ok: datetime.datetime(); (UTC) or None
 
268
    name:       string; from the config file, used in log messages and
 
269
                        D-Bus identifiers
 
270
    secret:     bytestring; sent verbatim (over TLS) to client
253
271
    timeout:    datetime.timedelta(); How long from last_checked_ok
254
272
                                      until this client is disabled
255
 
    interval:   datetime.timedelta(); How often to start a new checker
256
 
    disable_hook:  If set, called by disable() as disable_hook(self)
257
 
    checker:    subprocess.Popen(); a running checker process used
258
 
                                    to see if the client lives.
259
 
                                    'None' if no process is running.
260
 
    checker_initiator_tag: a gobject event source tag, or None
261
 
    disable_initiator_tag: - '' -
262
 
    checker_callback_tag:  - '' -
263
 
    checker_command: string; External command which is run to check if
264
 
                     client lives.  %() expansions are done at
265
 
                     runtime with vars(self) as dict, so that for
266
 
                     instance %(name)s can be used in the command.
267
 
    current_checker_command: string; current running checker_command
268
 
    approval_delay: datetime.timedelta(); Time to wait for approval
269
 
    _approved:   bool(); 'None' if not yet approved/disapproved
270
 
    approval_duration: datetime.timedelta(); Duration of one approval
 
273
    runtime_expansions: Allowed attributes for runtime expansion.
271
274
    """
272
275
    
 
276
    runtime_expansions = ("approval_delay", "approval_duration",
 
277
                          "created", "enabled", "fingerprint",
 
278
                          "host", "interval", "last_checked_ok",
 
279
                          "last_enabled", "name", "timeout")
 
280
    
273
281
    @staticmethod
274
282
    def _timedelta_to_milliseconds(td):
275
283
        "Convert a datetime.timedelta() to milliseconds"
295
303
        self.name = name
296
304
        if config is None:
297
305
            config = {}
298
 
        logger.debug(u"Creating client %r", self.name)
 
306
        logger.debug("Creating client %r", self.name)
299
307
        # Uppercase and remove spaces from fingerprint for later
300
308
        # comparison purposes with return value from the fingerprint()
301
309
        # function
302
 
        self.fingerprint = (config[u"fingerprint"].upper()
303
 
                            .replace(u" ", u""))
304
 
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
305
 
        if u"secret" in config:
306
 
            self.secret = config[u"secret"].decode(u"base64")
307
 
        elif u"secfile" in config:
 
310
        self.fingerprint = (config["fingerprint"].upper()
 
311
                            .replace(" ", ""))
 
312
        logger.debug("  Fingerprint: %s", self.fingerprint)
 
313
        if "secret" in config:
 
314
            self.secret = config["secret"].decode("base64")
 
315
        elif "secfile" in config:
308
316
            with open(os.path.expanduser(os.path.expandvars
309
 
                                         (config[u"secfile"])),
 
317
                                         (config["secfile"])),
310
318
                      "rb") as secfile:
311
319
                self.secret = secfile.read()
312
320
        else:
313
 
            raise TypeError(u"No secret or secfile for client %s"
 
321
            raise TypeError("No secret or secfile for client %s"
314
322
                            % self.name)
315
 
        self.host = config.get(u"host", u"")
 
323
        self.host = config.get("host", "")
316
324
        self.created = datetime.datetime.utcnow()
317
325
        self.enabled = False
 
326
        self.last_approval_request = None
318
327
        self.last_enabled = None
319
328
        self.last_checked_ok = None
320
 
        self.timeout = string_to_delta(config[u"timeout"])
321
 
        self.interval = string_to_delta(config[u"interval"])
 
329
        self.timeout = string_to_delta(config["timeout"])
 
330
        self.interval = string_to_delta(config["interval"])
322
331
        self.disable_hook = disable_hook
323
332
        self.checker = None
324
333
        self.checker_initiator_tag = None
325
334
        self.disable_initiator_tag = None
326
335
        self.checker_callback_tag = None
327
 
        self.checker_command = config[u"checker"]
 
336
        self.checker_command = config["checker"]
328
337
        self.current_checker_command = None
329
338
        self.last_connect = None
330
339
        self._approved = None
331
 
        self.approved_by_default = config.get(u"approved_by_default",
 
340
        self.approved_by_default = config.get("approved_by_default",
332
341
                                              True)
333
342
        self.approvals_pending = 0
334
343
        self.approval_delay = string_to_delta(
335
 
            config[u"approval_delay"])
 
344
            config["approval_delay"])
336
345
        self.approval_duration = string_to_delta(
337
 
            config[u"approval_duration"])
 
346
            config["approval_duration"])
338
347
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
339
348
    
340
349
    def send_changedstate(self):
344
353
        
345
354
    def enable(self):
346
355
        """Start this client's checker and timeout hooks"""
347
 
        if getattr(self, u"enabled", False):
 
356
        if getattr(self, "enabled", False):
348
357
            # Already enabled
349
358
            return
350
359
        self.send_changedstate()
369
378
        if not quiet:
370
379
            self.send_changedstate()
371
380
        if not quiet:
372
 
            logger.info(u"Disabling client %s", self.name)
373
 
        if getattr(self, u"disable_initiator_tag", False):
 
381
            logger.info("Disabling client %s", self.name)
 
382
        if getattr(self, "disable_initiator_tag", False):
374
383
            gobject.source_remove(self.disable_initiator_tag)
375
384
            self.disable_initiator_tag = None
376
 
        if getattr(self, u"checker_initiator_tag", False):
 
385
        if getattr(self, "checker_initiator_tag", False):
377
386
            gobject.source_remove(self.checker_initiator_tag)
378
387
            self.checker_initiator_tag = None
379
388
        self.stop_checker()
394
403
        if os.WIFEXITED(condition):
395
404
            exitstatus = os.WEXITSTATUS(condition)
396
405
            if exitstatus == 0:
397
 
                logger.info(u"Checker for %(name)s succeeded",
 
406
                logger.info("Checker for %(name)s succeeded",
398
407
                            vars(self))
399
408
                self.checked_ok()
400
409
            else:
401
 
                logger.info(u"Checker for %(name)s failed",
 
410
                logger.info("Checker for %(name)s failed",
402
411
                            vars(self))
403
412
        else:
404
 
            logger.warning(u"Checker for %(name)s crashed?",
 
413
            logger.warning("Checker for %(name)s crashed?",
405
414
                           vars(self))
406
415
    
407
416
    def checked_ok(self):
416
425
                                      (self.timeout_milliseconds(),
417
426
                                       self.disable))
418
427
    
 
428
    def need_approval(self):
 
429
        self.last_approval_request = datetime.datetime.utcnow()
 
430
    
419
431
    def start_checker(self):
420
432
        """Start a new checker subprocess if one is not running.
421
433
        
439
451
                raise error
440
452
        else:
441
453
            if pid:
442
 
                logger.warning(u"Checker was a zombie")
 
454
                logger.warning("Checker was a zombie")
443
455
                gobject.source_remove(self.checker_callback_tag)
444
456
                self.checker_callback(pid, status,
445
457
                                      self.current_checker_command)
450
462
                command = self.checker_command % self.host
451
463
            except TypeError:
452
464
                # Escape attributes for the shell
453
 
                escaped_attrs = dict((key,
454
 
                                      re.escape(unicode(str(val),
455
 
                                                        errors=
456
 
                                                        u'replace')))
457
 
                                     for key, val in
458
 
                                     vars(self).iteritems())
 
465
                escaped_attrs = dict(
 
466
                    (attr,
 
467
                     re.escape(unicode(str(getattr(self, attr, "")),
 
468
                                       errors=
 
469
                                       'replace')))
 
470
                    for attr in
 
471
                    self.runtime_expansions)
 
472
 
459
473
                try:
460
474
                    command = self.checker_command % escaped_attrs
461
475
                except TypeError, error:
462
 
                    logger.error(u'Could not format string "%s":'
463
 
                                 u' %s', self.checker_command, error)
 
476
                    logger.error('Could not format string "%s":'
 
477
                                 ' %s', self.checker_command, error)
464
478
                    return True # Try again later
465
479
            self.current_checker_command = command
466
480
            try:
467
 
                logger.info(u"Starting checker %r for %s",
 
481
                logger.info("Starting checker %r for %s",
468
482
                            command, self.name)
469
483
                # We don't need to redirect stdout and stderr, since
470
484
                # in normal mode, that is already done by daemon(),
472
486
                # always replaced by /dev/null.)
473
487
                self.checker = subprocess.Popen(command,
474
488
                                                close_fds=True,
475
 
                                                shell=True, cwd=u"/")
 
489
                                                shell=True, cwd="/")
476
490
                self.checker_callback_tag = (gobject.child_watch_add
477
491
                                             (self.checker.pid,
478
492
                                              self.checker_callback,
484
498
                    gobject.source_remove(self.checker_callback_tag)
485
499
                    self.checker_callback(pid, status, command)
486
500
            except OSError, error:
487
 
                logger.error(u"Failed to start subprocess: %s",
 
501
                logger.error("Failed to start subprocess: %s",
488
502
                             error)
489
503
        # Re-run this periodically if run by gobject.timeout_add
490
504
        return True
494
508
        if self.checker_callback_tag:
495
509
            gobject.source_remove(self.checker_callback_tag)
496
510
            self.checker_callback_tag = None
497
 
        if getattr(self, u"checker", None) is None:
 
511
        if getattr(self, "checker", None) is None:
498
512
            return
499
 
        logger.debug(u"Stopping checker for %(name)s", vars(self))
 
513
        logger.debug("Stopping checker for %(name)s", vars(self))
500
514
        try:
501
515
            os.kill(self.checker.pid, signal.SIGTERM)
502
516
            #time.sleep(0.5)
507
521
                raise
508
522
        self.checker = None
509
523
 
510
 
def dbus_service_property(dbus_interface, signature=u"v",
511
 
                          access=u"readwrite", byte_arrays=False):
 
524
def dbus_service_property(dbus_interface, signature="v",
 
525
                          access="readwrite", byte_arrays=False):
512
526
    """Decorators for marking methods of a DBusObjectWithProperties to
513
527
    become properties on the D-Bus.
514
528
    
521
535
    """
522
536
    # Encoding deeply encoded byte arrays is not supported yet by the
523
537
    # "Set" method, so we fail early here:
524
 
    if byte_arrays and signature != u"ay":
525
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
526
 
                         u" signature %r" % signature)
 
538
    if byte_arrays and signature != "ay":
 
539
        raise ValueError("Byte arrays not supported for non-'ay'"
 
540
                         " signature %r" % signature)
527
541
    def decorator(func):
528
542
        func._dbus_is_property = True
529
543
        func._dbus_interface = dbus_interface
530
544
        func._dbus_signature = signature
531
545
        func._dbus_access = access
532
546
        func._dbus_name = func.__name__
533
 
        if func._dbus_name.endswith(u"_dbus_property"):
 
547
        if func._dbus_name.endswith("_dbus_property"):
534
548
            func._dbus_name = func._dbus_name[:-14]
535
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
 
549
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
536
550
        return func
537
551
    return decorator
538
552
 
566
580
    
567
581
    @staticmethod
568
582
    def _is_dbus_property(obj):
569
 
        return getattr(obj, u"_dbus_is_property", False)
 
583
        return getattr(obj, "_dbus_is_property", False)
570
584
    
571
585
    def _get_all_dbus_properties(self):
572
586
        """Returns a generator of (name, attribute) pairs
580
594
        property with the specified name and interface.
581
595
        """
582
596
        for name in (property_name,
583
 
                     property_name + u"_dbus_property"):
 
597
                     property_name + "_dbus_property"):
584
598
            prop = getattr(self, name, None)
585
599
            if (prop is None
586
600
                or not self._is_dbus_property(prop)
590
604
                continue
591
605
            return prop
592
606
        # No such property
593
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
594
 
                                   + interface_name + u"."
 
607
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
608
                                   + interface_name + "."
595
609
                                   + property_name)
596
610
    
597
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
598
 
                         out_signature=u"v")
 
611
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
 
612
                         out_signature="v")
599
613
    def Get(self, interface_name, property_name):
600
614
        """Standard D-Bus property Get() method, see D-Bus standard.
601
615
        """
602
616
        prop = self._get_dbus_property(interface_name, property_name)
603
 
        if prop._dbus_access == u"write":
 
617
        if prop._dbus_access == "write":
604
618
            raise DBusPropertyAccessException(property_name)
605
619
        value = prop()
606
 
        if not hasattr(value, u"variant_level"):
 
620
        if not hasattr(value, "variant_level"):
607
621
            return value
608
622
        return type(value)(value, variant_level=value.variant_level+1)
609
623
    
610
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
 
624
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
611
625
    def Set(self, interface_name, property_name, value):
612
626
        """Standard D-Bus property Set() method, see D-Bus standard.
613
627
        """
614
628
        prop = self._get_dbus_property(interface_name, property_name)
615
 
        if prop._dbus_access == u"read":
 
629
        if prop._dbus_access == "read":
616
630
            raise DBusPropertyAccessException(property_name)
617
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
 
631
        if prop._dbus_get_args_options["byte_arrays"]:
618
632
            # The byte_arrays option is not supported yet on
619
633
            # signatures other than "ay".
620
 
            if prop._dbus_signature != u"ay":
 
634
            if prop._dbus_signature != "ay":
621
635
                raise ValueError
622
636
            value = dbus.ByteArray(''.join(unichr(byte)
623
637
                                           for byte in value))
624
638
        prop(value)
625
639
    
626
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
627
 
                         out_signature=u"a{sv}")
 
640
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
 
641
                         out_signature="a{sv}")
628
642
    def GetAll(self, interface_name):
629
643
        """Standard D-Bus property GetAll() method, see D-Bus
630
644
        standard.
638
652
                # Interface non-empty but did not match
639
653
                continue
640
654
            # Ignore write-only properties
641
 
            if prop._dbus_access == u"write":
 
655
            if prop._dbus_access == "write":
642
656
                continue
643
657
            value = prop()
644
 
            if not hasattr(value, u"variant_level"):
 
658
            if not hasattr(value, "variant_level"):
645
659
                all[name] = value
646
660
                continue
647
661
            all[name] = type(value)(value, variant_level=
648
662
                                    value.variant_level+1)
649
 
        return dbus.Dictionary(all, signature=u"sv")
 
663
        return dbus.Dictionary(all, signature="sv")
650
664
    
651
665
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
652
 
                         out_signature=u"s",
 
666
                         out_signature="s",
653
667
                         path_keyword='object_path',
654
668
                         connection_keyword='connection')
655
669
    def Introspect(self, object_path, connection):
660
674
        try:
661
675
            document = xml.dom.minidom.parseString(xmlstring)
662
676
            def make_tag(document, name, prop):
663
 
                e = document.createElement(u"property")
664
 
                e.setAttribute(u"name", name)
665
 
                e.setAttribute(u"type", prop._dbus_signature)
666
 
                e.setAttribute(u"access", prop._dbus_access)
 
677
                e = document.createElement("property")
 
678
                e.setAttribute("name", name)
 
679
                e.setAttribute("type", prop._dbus_signature)
 
680
                e.setAttribute("access", prop._dbus_access)
667
681
                return e
668
 
            for if_tag in document.getElementsByTagName(u"interface"):
 
682
            for if_tag in document.getElementsByTagName("interface"):
669
683
                for tag in (make_tag(document, name, prop)
670
684
                            for name, prop
671
685
                            in self._get_all_dbus_properties()
672
686
                            if prop._dbus_interface
673
 
                            == if_tag.getAttribute(u"name")):
 
687
                            == if_tag.getAttribute("name")):
674
688
                    if_tag.appendChild(tag)
675
689
                # Add the names to the return values for the
676
690
                # "org.freedesktop.DBus.Properties" methods
677
 
                if (if_tag.getAttribute(u"name")
678
 
                    == u"org.freedesktop.DBus.Properties"):
679
 
                    for cn in if_tag.getElementsByTagName(u"method"):
680
 
                        if cn.getAttribute(u"name") == u"Get":
681
 
                            for arg in cn.getElementsByTagName(u"arg"):
682
 
                                if (arg.getAttribute(u"direction")
683
 
                                    == u"out"):
684
 
                                    arg.setAttribute(u"name", u"value")
685
 
                        elif cn.getAttribute(u"name") == u"GetAll":
686
 
                            for arg in cn.getElementsByTagName(u"arg"):
687
 
                                if (arg.getAttribute(u"direction")
688
 
                                    == u"out"):
689
 
                                    arg.setAttribute(u"name", u"props")
690
 
            xmlstring = document.toxml(u"utf-8")
 
691
                if (if_tag.getAttribute("name")
 
692
                    == "org.freedesktop.DBus.Properties"):
 
693
                    for cn in if_tag.getElementsByTagName("method"):
 
694
                        if cn.getAttribute("name") == "Get":
 
695
                            for arg in cn.getElementsByTagName("arg"):
 
696
                                if (arg.getAttribute("direction")
 
697
                                    == "out"):
 
698
                                    arg.setAttribute("name", "value")
 
699
                        elif cn.getAttribute("name") == "GetAll":
 
700
                            for arg in cn.getElementsByTagName("arg"):
 
701
                                if (arg.getAttribute("direction")
 
702
                                    == "out"):
 
703
                                    arg.setAttribute("name", "props")
 
704
            xmlstring = document.toxml("utf-8")
691
705
            document.unlink()
692
706
        except (AttributeError, xml.dom.DOMException,
693
707
                xml.parsers.expat.ExpatError), error:
694
 
            logger.error(u"Failed to override Introspection method",
 
708
            logger.error("Failed to override Introspection method",
695
709
                         error)
696
710
        return xmlstring
697
711
 
703
717
    dbus_object_path: dbus.ObjectPath
704
718
    bus: dbus.SystemBus()
705
719
    """
 
720
    
 
721
    runtime_expansions = (Client.runtime_expansions
 
722
                          + ("dbus_object_path",))
 
723
    
706
724
    # dbus.service.Object doesn't use super(), so we can't either.
707
725
    
708
726
    def __init__(self, bus = None, *args, **kwargs):
711
729
        Client.__init__(self, *args, **kwargs)
712
730
        # Only now, when this client is initialized, can it show up on
713
731
        # the D-Bus
 
732
        client_object_name = unicode(self.name).translate(
 
733
            {ord("."): ord("_"),
 
734
             ord("-"): ord("_")})
714
735
        self.dbus_object_path = (dbus.ObjectPath
715
 
                                 (u"/clients/"
716
 
                                  + self.name.replace(u".", u"_")))
 
736
                                 ("/clients/" + client_object_name))
717
737
        DBusObjectWithProperties.__init__(self, self.bus,
718
738
                                          self.dbus_object_path)
719
739
        
726
746
        if (hasattr(self, "dbus_object_path")
727
747
            and bval is not bool(old_value)):
728
748
            dbus_bool = dbus.Boolean(bval, variant_level=1)
729
 
            self.PropertyChanged(dbus.String(u"ApprovalPending"),
 
749
            self.PropertyChanged(dbus.String("ApprovalPending"),
730
750
                                 dbus_bool)
731
751
 
732
752
    approvals_pending = property(_get_approvals_pending,
740
760
                           variant_level=variant_level)
741
761
    
742
762
    def enable(self):
743
 
        oldstate = getattr(self, u"enabled", False)
 
763
        oldstate = getattr(self, "enabled", False)
744
764
        r = Client.enable(self)
745
765
        if oldstate != self.enabled:
746
766
            # Emit D-Bus signals
747
 
            self.PropertyChanged(dbus.String(u"Enabled"),
 
767
            self.PropertyChanged(dbus.String("Enabled"),
748
768
                                 dbus.Boolean(True, variant_level=1))
749
769
            self.PropertyChanged(
750
 
                dbus.String(u"LastEnabled"),
 
770
                dbus.String("LastEnabled"),
751
771
                self._datetime_to_dbus(self.last_enabled,
752
772
                                       variant_level=1))
753
773
        return r
754
774
    
755
775
    def disable(self, quiet = False):
756
 
        oldstate = getattr(self, u"enabled", False)
 
776
        oldstate = getattr(self, "enabled", False)
757
777
        r = Client.disable(self, quiet=quiet)
758
778
        if not quiet and oldstate != self.enabled:
759
779
            # Emit D-Bus signal
760
 
            self.PropertyChanged(dbus.String(u"Enabled"),
 
780
            self.PropertyChanged(dbus.String("Enabled"),
761
781
                                 dbus.Boolean(False, variant_level=1))
762
782
        return r
763
783
    
766
786
            self.remove_from_connection()
767
787
        except LookupError:
768
788
            pass
769
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
 
789
        if hasattr(DBusObjectWithProperties, "__del__"):
770
790
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
771
791
        Client.__del__(self, *args, **kwargs)
772
792
    
775
795
        self.checker_callback_tag = None
776
796
        self.checker = None
777
797
        # Emit D-Bus signal
778
 
        self.PropertyChanged(dbus.String(u"CheckerRunning"),
 
798
        self.PropertyChanged(dbus.String("CheckerRunning"),
779
799
                             dbus.Boolean(False, variant_level=1))
780
800
        if os.WIFEXITED(condition):
781
801
            exitstatus = os.WEXITSTATUS(condition)
796
816
        r = Client.checked_ok(self, *args, **kwargs)
797
817
        # Emit D-Bus signal
798
818
        self.PropertyChanged(
799
 
            dbus.String(u"LastCheckedOK"),
 
819
            dbus.String("LastCheckedOK"),
800
820
            (self._datetime_to_dbus(self.last_checked_ok,
801
821
                                    variant_level=1)))
802
822
        return r
803
823
    
 
824
    def need_approval(self, *args, **kwargs):
 
825
        r = Client.need_approval(self, *args, **kwargs)
 
826
        # Emit D-Bus signal
 
827
        self.PropertyChanged(
 
828
            dbus.String("LastApprovalRequest"),
 
829
            (self._datetime_to_dbus(self.last_approval_request,
 
830
                                    variant_level=1)))
 
831
        return r
 
832
    
804
833
    def start_checker(self, *args, **kwargs):
805
834
        old_checker = self.checker
806
835
        if self.checker is not None:
814
843
            # Emit D-Bus signal
815
844
            self.CheckerStarted(self.current_checker_command)
816
845
            self.PropertyChanged(
817
 
                dbus.String(u"CheckerRunning"),
 
846
                dbus.String("CheckerRunning"),
818
847
                dbus.Boolean(True, variant_level=1))
819
848
        return r
820
849
    
821
850
    def stop_checker(self, *args, **kwargs):
822
 
        old_checker = getattr(self, u"checker", None)
 
851
        old_checker = getattr(self, "checker", None)
823
852
        r = Client.stop_checker(self, *args, **kwargs)
824
853
        if (old_checker is not None
825
 
            and getattr(self, u"checker", None) is None):
826
 
            self.PropertyChanged(dbus.String(u"CheckerRunning"),
 
854
            and getattr(self, "checker", None) is None):
 
855
            self.PropertyChanged(dbus.String("CheckerRunning"),
827
856
                                 dbus.Boolean(False, variant_level=1))
828
857
        return r
829
858
 
840
869
    
841
870
    
842
871
    ## D-Bus methods, signals & properties
843
 
    _interface = u"se.bsnet.fukt.Mandos.Client"
 
872
    _interface = "se.bsnet.fukt.Mandos.Client"
844
873
    
845
874
    ## Signals
846
875
    
847
876
    # CheckerCompleted - signal
848
 
    @dbus.service.signal(_interface, signature=u"nxs")
 
877
    @dbus.service.signal(_interface, signature="nxs")
849
878
    def CheckerCompleted(self, exitcode, waitstatus, command):
850
879
        "D-Bus signal"
851
880
        pass
852
881
    
853
882
    # CheckerStarted - signal
854
 
    @dbus.service.signal(_interface, signature=u"s")
 
883
    @dbus.service.signal(_interface, signature="s")
855
884
    def CheckerStarted(self, command):
856
885
        "D-Bus signal"
857
886
        pass
858
887
    
859
888
    # PropertyChanged - signal
860
 
    @dbus.service.signal(_interface, signature=u"sv")
 
889
    @dbus.service.signal(_interface, signature="sv")
861
890
    def PropertyChanged(self, property, value):
862
891
        "D-Bus signal"
863
892
        pass
872
901
        pass
873
902
    
874
903
    # Rejected - signal
875
 
    @dbus.service.signal(_interface, signature=u"s")
 
904
    @dbus.service.signal(_interface, signature="s")
876
905
    def Rejected(self, reason):
877
906
        "D-Bus signal"
878
907
        pass
879
908
    
880
909
    # NeedApproval - signal
881
 
    @dbus.service.signal(_interface, signature=u"tb")
 
910
    @dbus.service.signal(_interface, signature="tb")
882
911
    def NeedApproval(self, timeout, default):
883
912
        "D-Bus signal"
884
 
        pass
 
913
        return self.need_approval()
885
914
    
886
915
    ## Methods
887
 
 
 
916
    
888
917
    # Approve - method
889
 
    @dbus.service.method(_interface, in_signature=u"b")
 
918
    @dbus.service.method(_interface, in_signature="b")
890
919
    def Approve(self, value):
891
920
        self.approve(value)
892
 
 
 
921
    
893
922
    # CheckedOK - method
894
923
    @dbus.service.method(_interface)
895
924
    def CheckedOK(self):
921
950
    ## Properties
922
951
    
923
952
    # ApprovalPending - property
924
 
    @dbus_service_property(_interface, signature=u"b", access=u"read")
 
953
    @dbus_service_property(_interface, signature="b", access="read")
925
954
    def ApprovalPending_dbus_property(self):
926
955
        return dbus.Boolean(bool(self.approvals_pending))
927
956
    
928
957
    # ApprovedByDefault - property
929
 
    @dbus_service_property(_interface, signature=u"b",
930
 
                           access=u"readwrite")
 
958
    @dbus_service_property(_interface, signature="b",
 
959
                           access="readwrite")
931
960
    def ApprovedByDefault_dbus_property(self, value=None):
932
961
        if value is None:       # get
933
962
            return dbus.Boolean(self.approved_by_default)
934
963
        self.approved_by_default = bool(value)
935
964
        # Emit D-Bus signal
936
 
        self.PropertyChanged(dbus.String(u"ApprovedByDefault"),
 
965
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
937
966
                             dbus.Boolean(value, variant_level=1))
938
967
    
939
968
    # ApprovalDelay - property
940
 
    @dbus_service_property(_interface, signature=u"t",
941
 
                           access=u"readwrite")
 
969
    @dbus_service_property(_interface, signature="t",
 
970
                           access="readwrite")
942
971
    def ApprovalDelay_dbus_property(self, value=None):
943
972
        if value is None:       # get
944
973
            return dbus.UInt64(self.approval_delay_milliseconds())
945
974
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
946
975
        # Emit D-Bus signal
947
 
        self.PropertyChanged(dbus.String(u"ApprovalDelay"),
 
976
        self.PropertyChanged(dbus.String("ApprovalDelay"),
948
977
                             dbus.UInt64(value, variant_level=1))
949
978
    
950
979
    # ApprovalDuration - property
951
 
    @dbus_service_property(_interface, signature=u"t",
952
 
                           access=u"readwrite")
 
980
    @dbus_service_property(_interface, signature="t",
 
981
                           access="readwrite")
953
982
    def ApprovalDuration_dbus_property(self, value=None):
954
983
        if value is None:       # get
955
984
            return dbus.UInt64(self._timedelta_to_milliseconds(
956
985
                    self.approval_duration))
957
986
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
958
987
        # Emit D-Bus signal
959
 
        self.PropertyChanged(dbus.String(u"ApprovalDuration"),
 
988
        self.PropertyChanged(dbus.String("ApprovalDuration"),
960
989
                             dbus.UInt64(value, variant_level=1))
961
990
    
962
991
    # Name - property
963
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
992
    @dbus_service_property(_interface, signature="s", access="read")
964
993
    def Name_dbus_property(self):
965
994
        return dbus.String(self.name)
966
995
    
967
996
    # Fingerprint - property
968
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
997
    @dbus_service_property(_interface, signature="s", access="read")
969
998
    def Fingerprint_dbus_property(self):
970
999
        return dbus.String(self.fingerprint)
971
1000
    
972
1001
    # Host - property
973
 
    @dbus_service_property(_interface, signature=u"s",
974
 
                           access=u"readwrite")
 
1002
    @dbus_service_property(_interface, signature="s",
 
1003
                           access="readwrite")
975
1004
    def Host_dbus_property(self, value=None):
976
1005
        if value is None:       # get
977
1006
            return dbus.String(self.host)
978
1007
        self.host = value
979
1008
        # Emit D-Bus signal
980
 
        self.PropertyChanged(dbus.String(u"Host"),
 
1009
        self.PropertyChanged(dbus.String("Host"),
981
1010
                             dbus.String(value, variant_level=1))
982
1011
    
983
1012
    # Created - property
984
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
1013
    @dbus_service_property(_interface, signature="s", access="read")
985
1014
    def Created_dbus_property(self):
986
1015
        return dbus.String(self._datetime_to_dbus(self.created))
987
1016
    
988
1017
    # LastEnabled - property
989
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
1018
    @dbus_service_property(_interface, signature="s", access="read")
990
1019
    def LastEnabled_dbus_property(self):
991
1020
        if self.last_enabled is None:
992
 
            return dbus.String(u"")
 
1021
            return dbus.String("")
993
1022
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
994
1023
    
995
1024
    # Enabled - property
996
 
    @dbus_service_property(_interface, signature=u"b",
997
 
                           access=u"readwrite")
 
1025
    @dbus_service_property(_interface, signature="b",
 
1026
                           access="readwrite")
998
1027
    def Enabled_dbus_property(self, value=None):
999
1028
        if value is None:       # get
1000
1029
            return dbus.Boolean(self.enabled)
1004
1033
            self.disable()
1005
1034
    
1006
1035
    # LastCheckedOK - property
1007
 
    @dbus_service_property(_interface, signature=u"s",
1008
 
                           access=u"readwrite")
 
1036
    @dbus_service_property(_interface, signature="s",
 
1037
                           access="readwrite")
1009
1038
    def LastCheckedOK_dbus_property(self, value=None):
1010
1039
        if value is not None:
1011
1040
            self.checked_ok()
1012
1041
            return
1013
1042
        if self.last_checked_ok is None:
1014
 
            return dbus.String(u"")
 
1043
            return dbus.String("")
1015
1044
        return dbus.String(self._datetime_to_dbus(self
1016
1045
                                                  .last_checked_ok))
1017
1046
    
 
1047
    # LastApprovalRequest - property
 
1048
    @dbus_service_property(_interface, signature="s", access="read")
 
1049
    def LastApprovalRequest_dbus_property(self):
 
1050
        if self.last_approval_request is None:
 
1051
            return dbus.String("")
 
1052
        return dbus.String(self.
 
1053
                           _datetime_to_dbus(self
 
1054
                                             .last_approval_request))
 
1055
    
1018
1056
    # Timeout - property
1019
 
    @dbus_service_property(_interface, signature=u"t",
1020
 
                           access=u"readwrite")
 
1057
    @dbus_service_property(_interface, signature="t",
 
1058
                           access="readwrite")
1021
1059
    def Timeout_dbus_property(self, value=None):
1022
1060
        if value is None:       # get
1023
1061
            return dbus.UInt64(self.timeout_milliseconds())
1024
1062
        self.timeout = datetime.timedelta(0, 0, 0, value)
1025
1063
        # Emit D-Bus signal
1026
 
        self.PropertyChanged(dbus.String(u"Timeout"),
 
1064
        self.PropertyChanged(dbus.String("Timeout"),
1027
1065
                             dbus.UInt64(value, variant_level=1))
1028
 
        if getattr(self, u"disable_initiator_tag", None) is None:
 
1066
        if getattr(self, "disable_initiator_tag", None) is None:
1029
1067
            return
1030
1068
        # Reschedule timeout
1031
1069
        gobject.source_remove(self.disable_initiator_tag)
1044
1082
                                          (time_to_die, self.disable))
1045
1083
    
1046
1084
    # Interval - property
1047
 
    @dbus_service_property(_interface, signature=u"t",
1048
 
                           access=u"readwrite")
 
1085
    @dbus_service_property(_interface, signature="t",
 
1086
                           access="readwrite")
1049
1087
    def Interval_dbus_property(self, value=None):
1050
1088
        if value is None:       # get
1051
1089
            return dbus.UInt64(self.interval_milliseconds())
1052
1090
        self.interval = datetime.timedelta(0, 0, 0, value)
1053
1091
        # Emit D-Bus signal
1054
 
        self.PropertyChanged(dbus.String(u"Interval"),
 
1092
        self.PropertyChanged(dbus.String("Interval"),
1055
1093
                             dbus.UInt64(value, variant_level=1))
1056
 
        if getattr(self, u"checker_initiator_tag", None) is None:
 
1094
        if getattr(self, "checker_initiator_tag", None) is None:
1057
1095
            return
1058
1096
        # Reschedule checker run
1059
1097
        gobject.source_remove(self.checker_initiator_tag)
1062
1100
        self.start_checker()    # Start one now, too
1063
1101
 
1064
1102
    # Checker - property
1065
 
    @dbus_service_property(_interface, signature=u"s",
1066
 
                           access=u"readwrite")
 
1103
    @dbus_service_property(_interface, signature="s",
 
1104
                           access="readwrite")
1067
1105
    def Checker_dbus_property(self, value=None):
1068
1106
        if value is None:       # get
1069
1107
            return dbus.String(self.checker_command)
1070
1108
        self.checker_command = value
1071
1109
        # Emit D-Bus signal
1072
 
        self.PropertyChanged(dbus.String(u"Checker"),
 
1110
        self.PropertyChanged(dbus.String("Checker"),
1073
1111
                             dbus.String(self.checker_command,
1074
1112
                                         variant_level=1))
1075
1113
    
1076
1114
    # CheckerRunning - property
1077
 
    @dbus_service_property(_interface, signature=u"b",
1078
 
                           access=u"readwrite")
 
1115
    @dbus_service_property(_interface, signature="b",
 
1116
                           access="readwrite")
1079
1117
    def CheckerRunning_dbus_property(self, value=None):
1080
1118
        if value is None:       # get
1081
1119
            return dbus.Boolean(self.checker is not None)
1085
1123
            self.stop_checker()
1086
1124
    
1087
1125
    # ObjectPath - property
1088
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
 
1126
    @dbus_service_property(_interface, signature="o", access="read")
1089
1127
    def ObjectPath_dbus_property(self):
1090
1128
        return self.dbus_object_path # is already a dbus.ObjectPath
1091
1129
    
1092
1130
    # Secret = property
1093
 
    @dbus_service_property(_interface, signature=u"ay",
1094
 
                           access=u"write", byte_arrays=True)
 
1131
    @dbus_service_property(_interface, signature="ay",
 
1132
                           access="write", byte_arrays=True)
1095
1133
    def Secret_dbus_property(self, value):
1096
1134
        self.secret = str(value)
1097
1135
    
1132
1170
    
1133
1171
    def handle(self):
1134
1172
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1135
 
            logger.info(u"TCP connection from: %s",
 
1173
            logger.info("TCP connection from: %s",
1136
1174
                        unicode(self.client_address))
1137
 
            logger.debug(u"Pipe FD: %d",
 
1175
            logger.debug("Pipe FD: %d",
1138
1176
                         self.server.child_pipe.fileno())
1139
1177
 
1140
1178
            session = (gnutls.connection
1147
1185
            # no X.509 keys are added to it.  Therefore, we can use it
1148
1186
            # here despite using OpenPGP certificates.
1149
1187
 
1150
 
            #priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1151
 
            #                      u"+AES-256-CBC", u"+SHA1",
1152
 
            #                      u"+COMP-NULL", u"+CTYPE-OPENPGP",
1153
 
            #                      u"+DHE-DSS"))
 
1188
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
1189
            #                      "+AES-256-CBC", "+SHA1",
 
1190
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
 
1191
            #                      "+DHE-DSS"))
1154
1192
            # Use a fallback default, since this MUST be set.
1155
1193
            priority = self.server.gnutls_priority
1156
1194
            if priority is None:
1157
 
                priority = u"NORMAL"
 
1195
                priority = "NORMAL"
1158
1196
            (gnutls.library.functions
1159
1197
             .gnutls_priority_set_direct(session._c_object,
1160
1198
                                         priority, None))
1162
1200
            # Start communication using the Mandos protocol
1163
1201
            # Get protocol number
1164
1202
            line = self.request.makefile().readline()
1165
 
            logger.debug(u"Protocol version: %r", line)
 
1203
            logger.debug("Protocol version: %r", line)
1166
1204
            try:
1167
1205
                if int(line.strip().split()[0]) > 1:
1168
1206
                    raise RuntimeError
1169
1207
            except (ValueError, IndexError, RuntimeError), error:
1170
 
                logger.error(u"Unknown protocol version: %s", error)
 
1208
                logger.error("Unknown protocol version: %s", error)
1171
1209
                return
1172
1210
 
1173
1211
            # Start GnuTLS connection
1174
1212
            try:
1175
1213
                session.handshake()
1176
1214
            except gnutls.errors.GNUTLSError, error:
1177
 
                logger.warning(u"Handshake failed: %s", error)
 
1215
                logger.warning("Handshake failed: %s", error)
1178
1216
                # Do not run session.bye() here: the session is not
1179
1217
                # established.  Just abandon the request.
1180
1218
                return
1181
 
            logger.debug(u"Handshake succeeded")
 
1219
            logger.debug("Handshake succeeded")
1182
1220
 
1183
1221
            approval_required = False
1184
1222
            try:
1186
1224
                    fpr = self.fingerprint(self.peer_certificate
1187
1225
                                           (session))
1188
1226
                except (TypeError, gnutls.errors.GNUTLSError), error:
1189
 
                    logger.warning(u"Bad certificate: %s", error)
 
1227
                    logger.warning("Bad certificate: %s", error)
1190
1228
                    return
1191
 
                logger.debug(u"Fingerprint: %s", fpr)
 
1229
                logger.debug("Fingerprint: %s", fpr)
1192
1230
 
1193
1231
                try:
1194
1232
                    client = ProxyClient(child_pipe, fpr,
1203
1241
                
1204
1242
                while True:
1205
1243
                    if not client.enabled:
1206
 
                        logger.warning(u"Client %s is disabled",
 
1244
                        logger.warning("Client %s is disabled",
1207
1245
                                       client.name)
1208
1246
                        if self.server.use_dbus:
1209
1247
                            # Emit D-Bus signal
1214
1252
                        #We are approved or approval is disabled
1215
1253
                        break
1216
1254
                    elif client._approved is None:
1217
 
                        logger.info(u"Client %s needs approval",
 
1255
                        logger.info("Client %s needs approval",
1218
1256
                                    client.name)
1219
1257
                        if self.server.use_dbus:
1220
1258
                            # Emit D-Bus signal
1222
1260
                                client.approval_delay_milliseconds(),
1223
1261
                                client.approved_by_default)
1224
1262
                    else:
1225
 
                        logger.warning(u"Client %s was not approved",
 
1263
                        logger.warning("Client %s was not approved",
1226
1264
                                       client.name)
1227
1265
                        if self.server.use_dbus:
1228
1266
                            # Emit D-Bus signal
1257
1295
                    except (gnutls.errors.GNUTLSError), error:
1258
1296
                        logger.warning("gnutls send failed")
1259
1297
                        return
1260
 
                    logger.debug(u"Sent: %d, remaining: %d",
 
1298
                    logger.debug("Sent: %d, remaining: %d",
1261
1299
                                 sent, len(client.secret)
1262
1300
                                 - (sent_size + sent))
1263
1301
                    sent_size += sent
1264
1302
 
1265
 
                logger.info(u"Sending secret to %s", client.name)
 
1303
                logger.info("Sending secret to %s", client.name)
1266
1304
                # bump the timeout as if seen
1267
1305
                client.checked_ok()
1268
1306
                if self.server.use_dbus:
1291
1329
                     .gnutls_certificate_get_peers
1292
1330
                     (session._c_object, ctypes.byref(list_size)))
1293
1331
        if not bool(cert_list) and list_size.value != 0:
1294
 
            raise gnutls.errors.GNUTLSError(u"error getting peer"
1295
 
                                            u" certificate")
 
1332
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1333
                                            " certificate")
1296
1334
        if list_size.value == 0:
1297
1335
            return None
1298
1336
        cert = cert_list[0]
1324
1362
        if crtverify.value != 0:
1325
1363
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1326
1364
            raise (gnutls.errors.CertificateSecurityError
1327
 
                   (u"Verify failed"))
 
1365
                   ("Verify failed"))
1328
1366
        # New buffer for the fingerprint
1329
1367
        buf = ctypes.create_string_buffer(20)
1330
1368
        buf_len = ctypes.c_size_t()
1337
1375
        # Convert the buffer to a Python bytestring
1338
1376
        fpr = ctypes.string_at(buf, buf_len.value)
1339
1377
        # Convert the bytestring to hexadecimal notation
1340
 
        hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
 
1378
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1341
1379
        return hex_fpr
1342
1380
 
1343
1381
 
1371
1409
 
1372
1410
    def add_pipe(self, parent_pipe):
1373
1411
        """Dummy function; override as necessary"""
1374
 
        pass
 
1412
        raise NotImplementedError
1375
1413
 
1376
1414
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1377
1415
                     socketserver.TCPServer, object):
1395
1433
        bind to an address or port if they were not specified."""
1396
1434
        if self.interface is not None:
1397
1435
            if SO_BINDTODEVICE is None:
1398
 
                logger.error(u"SO_BINDTODEVICE does not exist;"
1399
 
                             u" cannot bind to interface %s",
 
1436
                logger.error("SO_BINDTODEVICE does not exist;"
 
1437
                             " cannot bind to interface %s",
1400
1438
                             self.interface)
1401
1439
            else:
1402
1440
                try:
1403
1441
                    self.socket.setsockopt(socket.SOL_SOCKET,
1404
1442
                                           SO_BINDTODEVICE,
1405
1443
                                           str(self.interface
1406
 
                                               + u'\0'))
 
1444
                                               + '\0'))
1407
1445
                except socket.error, error:
1408
1446
                    if error[0] == errno.EPERM:
1409
 
                        logger.error(u"No permission to"
1410
 
                                     u" bind to interface %s",
 
1447
                        logger.error("No permission to"
 
1448
                                     " bind to interface %s",
1411
1449
                                     self.interface)
1412
1450
                    elif error[0] == errno.ENOPROTOOPT:
1413
 
                        logger.error(u"SO_BINDTODEVICE not available;"
1414
 
                                     u" cannot bind to interface %s",
 
1451
                        logger.error("SO_BINDTODEVICE not available;"
 
1452
                                     " cannot bind to interface %s",
1415
1453
                                     self.interface)
1416
1454
                    else:
1417
1455
                        raise
1419
1457
        if self.server_address[0] or self.server_address[1]:
1420
1458
            if not self.server_address[0]:
1421
1459
                if self.address_family == socket.AF_INET6:
1422
 
                    any_address = u"::" # in6addr_any
 
1460
                    any_address = "::" # in6addr_any
1423
1461
                else:
1424
1462
                    any_address = socket.INADDR_ANY
1425
1463
                self.server_address = (any_address,
1474
1512
    def handle_ipc(self, source, condition, parent_pipe=None,
1475
1513
                   client_object=None):
1476
1514
        condition_names = {
1477
 
            gobject.IO_IN: u"IN",   # There is data to read.
1478
 
            gobject.IO_OUT: u"OUT", # Data can be written (without
 
1515
            gobject.IO_IN: "IN",   # There is data to read.
 
1516
            gobject.IO_OUT: "OUT", # Data can be written (without
1479
1517
                                    # blocking).
1480
 
            gobject.IO_PRI: u"PRI", # There is urgent data to read.
1481
 
            gobject.IO_ERR: u"ERR", # Error condition.
1482
 
            gobject.IO_HUP: u"HUP"  # Hung up (the connection has been
 
1518
            gobject.IO_PRI: "PRI", # There is urgent data to read.
 
1519
            gobject.IO_ERR: "ERR", # Error condition.
 
1520
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
1483
1521
                                    # broken, usually for pipes and
1484
1522
                                    # sockets).
1485
1523
            }
1504
1542
                    client = c
1505
1543
                    break
1506
1544
            else:
1507
 
                logger.warning(u"Client not found for fingerprint: %s, ad"
1508
 
                               u"dress: %s", fpr, address)
 
1545
                logger.warning("Client not found for fingerprint: %s, ad"
 
1546
                               "dress: %s", fpr, address)
1509
1547
                if self.use_dbus:
1510
1548
                    # Emit D-Bus signal
1511
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
 
1549
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1512
1550
                parent_pipe.send(False)
1513
1551
                return False
1514
1552
            
1545
1583
def string_to_delta(interval):
1546
1584
    """Parse a string and return a datetime.timedelta
1547
1585
    
1548
 
    >>> string_to_delta(u'7d')
 
1586
    >>> string_to_delta('7d')
1549
1587
    datetime.timedelta(7)
1550
 
    >>> string_to_delta(u'60s')
 
1588
    >>> string_to_delta('60s')
1551
1589
    datetime.timedelta(0, 60)
1552
 
    >>> string_to_delta(u'60m')
 
1590
    >>> string_to_delta('60m')
1553
1591
    datetime.timedelta(0, 3600)
1554
 
    >>> string_to_delta(u'24h')
 
1592
    >>> string_to_delta('24h')
1555
1593
    datetime.timedelta(1)
1556
 
    >>> string_to_delta(u'1w')
 
1594
    >>> string_to_delta('1w')
1557
1595
    datetime.timedelta(7)
1558
 
    >>> string_to_delta(u'5m 30s')
 
1596
    >>> string_to_delta('5m 30s')
1559
1597
    datetime.timedelta(0, 330)
1560
1598
    """
1561
1599
    timevalue = datetime.timedelta(0)
1563
1601
        try:
1564
1602
            suffix = unicode(s[-1])
1565
1603
            value = int(s[:-1])
1566
 
            if suffix == u"d":
 
1604
            if suffix == "d":
1567
1605
                delta = datetime.timedelta(value)
1568
 
            elif suffix == u"s":
 
1606
            elif suffix == "s":
1569
1607
                delta = datetime.timedelta(0, value)
1570
 
            elif suffix == u"m":
 
1608
            elif suffix == "m":
1571
1609
                delta = datetime.timedelta(0, 0, 0, 0, value)
1572
 
            elif suffix == u"h":
 
1610
            elif suffix == "h":
1573
1611
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
1574
 
            elif suffix == u"w":
 
1612
            elif suffix == "w":
1575
1613
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1576
1614
            else:
1577
 
                raise ValueError(u"Unknown suffix %r" % suffix)
 
1615
                raise ValueError("Unknown suffix %r" % suffix)
1578
1616
        except (ValueError, IndexError), e:
1579
 
            raise ValueError(e.message)
 
1617
            raise ValueError(*(e.args))
1580
1618
        timevalue += delta
1581
1619
    return timevalue
1582
1620
 
1588
1626
    global if_nametoindex
1589
1627
    try:
1590
1628
        if_nametoindex = (ctypes.cdll.LoadLibrary
1591
 
                          (ctypes.util.find_library(u"c"))
 
1629
                          (ctypes.util.find_library("c"))
1592
1630
                          .if_nametoindex)
1593
1631
    except (OSError, AttributeError):
1594
 
        logger.warning(u"Doing if_nametoindex the hard way")
 
1632
        logger.warning("Doing if_nametoindex the hard way")
1595
1633
        def if_nametoindex(interface):
1596
1634
            "Get an interface index the hard way, i.e. using fcntl()"
1597
1635
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1598
1636
            with contextlib.closing(socket.socket()) as s:
1599
1637
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1600
 
                                    struct.pack(str(u"16s16x"),
 
1638
                                    struct.pack(str("16s16x"),
1601
1639
                                                interface))
1602
 
            interface_index = struct.unpack(str(u"I"),
 
1640
            interface_index = struct.unpack(str("I"),
1603
1641
                                            ifreq[16:20])[0]
1604
1642
            return interface_index
1605
1643
    return if_nametoindex(interface)
1613
1651
        sys.exit()
1614
1652
    os.setsid()
1615
1653
    if not nochdir:
1616
 
        os.chdir(u"/")
 
1654
        os.chdir("/")
1617
1655
    if os.fork():
1618
1656
        sys.exit()
1619
1657
    if not noclose:
1621
1659
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1622
1660
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1623
1661
            raise OSError(errno.ENODEV,
1624
 
                          u"%s not a character device"
 
1662
                          "%s not a character device"
1625
1663
                          % os.path.devnull)
1626
1664
        os.dup2(null, sys.stdin.fileno())
1627
1665
        os.dup2(null, sys.stdout.fileno())
1635
1673
    ##################################################################
1636
1674
    # Parsing of options, both command line and config file
1637
1675
    
1638
 
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1639
 
    parser.add_option("-i", u"--interface", type=u"string",
1640
 
                      metavar="IF", help=u"Bind to interface IF")
1641
 
    parser.add_option("-a", u"--address", type=u"string",
1642
 
                      help=u"Address to listen for requests on")
1643
 
    parser.add_option("-p", u"--port", type=u"int",
1644
 
                      help=u"Port number to receive requests on")
1645
 
    parser.add_option("--check", action=u"store_true",
1646
 
                      help=u"Run self-test")
1647
 
    parser.add_option("--debug", action=u"store_true",
1648
 
                      help=u"Debug mode; run in foreground and log to"
1649
 
                      u" terminal")
1650
 
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
1651
 
                      help=u"Debug level for stdout output")
1652
 
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1653
 
                      u" priority string (see GnuTLS documentation)")
1654
 
    parser.add_option("--servicename", type=u"string",
1655
 
                      metavar=u"NAME", help=u"Zeroconf service name")
1656
 
    parser.add_option("--configdir", type=u"string",
1657
 
                      default=u"/etc/mandos", metavar=u"DIR",
1658
 
                      help=u"Directory to search for configuration"
1659
 
                      u" files")
1660
 
    parser.add_option("--no-dbus", action=u"store_false",
1661
 
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1662
 
                      u" system bus interface")
1663
 
    parser.add_option("--no-ipv6", action=u"store_false",
1664
 
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1665
 
    options = parser.parse_args()[0]
 
1676
    parser = argparse.ArgumentParser()
 
1677
    parser.add_argument("-v", "--version", action="version",
 
1678
                        version = "%%(prog)s %s" % version,
 
1679
                        help="show version number and exit")
 
1680
    parser.add_argument("-i", "--interface", metavar="IF",
 
1681
                        help="Bind to interface IF")
 
1682
    parser.add_argument("-a", "--address",
 
1683
                        help="Address to listen for requests on")
 
1684
    parser.add_argument("-p", "--port", type=int,
 
1685
                        help="Port number to receive requests on")
 
1686
    parser.add_argument("--check", action="store_true",
 
1687
                        help="Run self-test")
 
1688
    parser.add_argument("--debug", action="store_true",
 
1689
                        help="Debug mode; run in foreground and log"
 
1690
                        " to terminal")
 
1691
    parser.add_argument("--debuglevel", metavar="LEVEL",
 
1692
                        help="Debug level for stdout output")
 
1693
    parser.add_argument("--priority", help="GnuTLS"
 
1694
                        " priority string (see GnuTLS documentation)")
 
1695
    parser.add_argument("--servicename",
 
1696
                        metavar="NAME", help="Zeroconf service name")
 
1697
    parser.add_argument("--configdir",
 
1698
                        default="/etc/mandos", metavar="DIR",
 
1699
                        help="Directory to search for configuration"
 
1700
                        " files")
 
1701
    parser.add_argument("--no-dbus", action="store_false",
 
1702
                        dest="use_dbus", help="Do not provide D-Bus"
 
1703
                        " system bus interface")
 
1704
    parser.add_argument("--no-ipv6", action="store_false",
 
1705
                        dest="use_ipv6", help="Do not use IPv6")
 
1706
    options = parser.parse_args()
1666
1707
    
1667
1708
    if options.check:
1668
1709
        import doctest
1670
1711
        sys.exit()
1671
1712
    
1672
1713
    # Default values for config file for server-global settings
1673
 
    server_defaults = { u"interface": u"",
1674
 
                        u"address": u"",
1675
 
                        u"port": u"",
1676
 
                        u"debug": u"False",
1677
 
                        u"priority":
1678
 
                        u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1679
 
                        u"servicename": u"Mandos",
1680
 
                        u"use_dbus": u"True",
1681
 
                        u"use_ipv6": u"True",
1682
 
                        u"debuglevel": u"",
 
1714
    server_defaults = { "interface": "",
 
1715
                        "address": "",
 
1716
                        "port": "",
 
1717
                        "debug": "False",
 
1718
                        "priority":
 
1719
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
 
1720
                        "servicename": "Mandos",
 
1721
                        "use_dbus": "True",
 
1722
                        "use_ipv6": "True",
 
1723
                        "debuglevel": "",
1683
1724
                        }
1684
1725
    
1685
1726
    # Parse config file for server-global settings
1686
1727
    server_config = configparser.SafeConfigParser(server_defaults)
1687
1728
    del server_defaults
1688
1729
    server_config.read(os.path.join(options.configdir,
1689
 
                                    u"mandos.conf"))
 
1730
                                    "mandos.conf"))
1690
1731
    # Convert the SafeConfigParser object to a dict
1691
1732
    server_settings = server_config.defaults()
1692
1733
    # Use the appropriate methods on the non-string config options
1693
 
    for option in (u"debug", u"use_dbus", u"use_ipv6"):
1694
 
        server_settings[option] = server_config.getboolean(u"DEFAULT",
 
1734
    for option in ("debug", "use_dbus", "use_ipv6"):
 
1735
        server_settings[option] = server_config.getboolean("DEFAULT",
1695
1736
                                                           option)
1696
1737
    if server_settings["port"]:
1697
 
        server_settings["port"] = server_config.getint(u"DEFAULT",
1698
 
                                                       u"port")
 
1738
        server_settings["port"] = server_config.getint("DEFAULT",
 
1739
                                                       "port")
1699
1740
    del server_config
1700
1741
    
1701
1742
    # Override the settings from the config file with command line
1702
1743
    # options, if set.
1703
 
    for option in (u"interface", u"address", u"port", u"debug",
1704
 
                   u"priority", u"servicename", u"configdir",
1705
 
                   u"use_dbus", u"use_ipv6", u"debuglevel"):
 
1744
    for option in ("interface", "address", "port", "debug",
 
1745
                   "priority", "servicename", "configdir",
 
1746
                   "use_dbus", "use_ipv6", "debuglevel"):
1706
1747
        value = getattr(options, option)
1707
1748
        if value is not None:
1708
1749
            server_settings[option] = value
1716
1757
    ##################################################################
1717
1758
    
1718
1759
    # For convenience
1719
 
    debug = server_settings[u"debug"]
1720
 
    debuglevel = server_settings[u"debuglevel"]
1721
 
    use_dbus = server_settings[u"use_dbus"]
1722
 
    use_ipv6 = server_settings[u"use_ipv6"]
 
1760
    debug = server_settings["debug"]
 
1761
    debuglevel = server_settings["debuglevel"]
 
1762
    use_dbus = server_settings["use_dbus"]
 
1763
    use_ipv6 = server_settings["use_ipv6"]
1723
1764
 
1724
 
    if server_settings[u"servicename"] != u"Mandos":
 
1765
    if server_settings["servicename"] != "Mandos":
1725
1766
        syslogger.setFormatter(logging.Formatter
1726
 
                               (u'Mandos (%s) [%%(process)d]:'
1727
 
                                u' %%(levelname)s: %%(message)s'
1728
 
                                % server_settings[u"servicename"]))
 
1767
                               ('Mandos (%s) [%%(process)d]:'
 
1768
                                ' %%(levelname)s: %%(message)s'
 
1769
                                % server_settings["servicename"]))
1729
1770
    
1730
1771
    # Parse config file with clients
1731
 
    client_defaults = { u"timeout": u"1h",
1732
 
                        u"interval": u"5m",
1733
 
                        u"checker": u"fping -q -- %%(host)s",
1734
 
                        u"host": u"",
1735
 
                        u"approval_delay": u"0s",
1736
 
                        u"approval_duration": u"1s",
 
1772
    client_defaults = { "timeout": "1h",
 
1773
                        "interval": "5m",
 
1774
                        "checker": "fping -q -- %%(host)s",
 
1775
                        "host": "",
 
1776
                        "approval_delay": "0s",
 
1777
                        "approval_duration": "1s",
1737
1778
                        }
1738
1779
    client_config = configparser.SafeConfigParser(client_defaults)
1739
 
    client_config.read(os.path.join(server_settings[u"configdir"],
1740
 
                                    u"clients.conf"))
 
1780
    client_config.read(os.path.join(server_settings["configdir"],
 
1781
                                    "clients.conf"))
1741
1782
    
1742
1783
    global mandos_dbus_service
1743
1784
    mandos_dbus_service = None
1744
1785
    
1745
 
    tcp_server = MandosServer((server_settings[u"address"],
1746
 
                               server_settings[u"port"]),
 
1786
    tcp_server = MandosServer((server_settings["address"],
 
1787
                               server_settings["port"]),
1747
1788
                              ClientHandler,
1748
 
                              interface=(server_settings[u"interface"]
 
1789
                              interface=(server_settings["interface"]
1749
1790
                                         or None),
1750
1791
                              use_ipv6=use_ipv6,
1751
1792
                              gnutls_priority=
1752
 
                              server_settings[u"priority"],
 
1793
                              server_settings["priority"],
1753
1794
                              use_dbus=use_dbus)
1754
 
    pidfilename = u"/var/run/mandos.pid"
1755
 
    try:
1756
 
        pidfile = open(pidfilename, u"w")
1757
 
    except IOError:
1758
 
        logger.error(u"Could not open file %r", pidfilename)
 
1795
    if not debug:
 
1796
        pidfilename = "/var/run/mandos.pid"
 
1797
        try:
 
1798
            pidfile = open(pidfilename, "w")
 
1799
        except IOError:
 
1800
            logger.error("Could not open file %r", pidfilename)
1759
1801
    
1760
1802
    try:
1761
 
        uid = pwd.getpwnam(u"_mandos").pw_uid
1762
 
        gid = pwd.getpwnam(u"_mandos").pw_gid
 
1803
        uid = pwd.getpwnam("_mandos").pw_uid
 
1804
        gid = pwd.getpwnam("_mandos").pw_gid
1763
1805
    except KeyError:
1764
1806
        try:
1765
 
            uid = pwd.getpwnam(u"mandos").pw_uid
1766
 
            gid = pwd.getpwnam(u"mandos").pw_gid
 
1807
            uid = pwd.getpwnam("mandos").pw_uid
 
1808
            gid = pwd.getpwnam("mandos").pw_gid
1767
1809
        except KeyError:
1768
1810
            try:
1769
 
                uid = pwd.getpwnam(u"nobody").pw_uid
1770
 
                gid = pwd.getpwnam(u"nobody").pw_gid
 
1811
                uid = pwd.getpwnam("nobody").pw_uid
 
1812
                gid = pwd.getpwnam("nobody").pw_gid
1771
1813
            except KeyError:
1772
1814
                uid = 65534
1773
1815
                gid = 65534
1795
1837
        
1796
1838
        @gnutls.library.types.gnutls_log_func
1797
1839
        def debug_gnutls(level, string):
1798
 
            logger.debug(u"GnuTLS: %s", string[:-1])
 
1840
            logger.debug("GnuTLS: %s", string[:-1])
1799
1841
        
1800
1842
        (gnutls.library.functions
1801
1843
         .gnutls_global_set_log_function(debug_gnutls))
1809
1851
        # No console logging
1810
1852
        logger.removeHandler(console)
1811
1853
    
 
1854
    # Need to fork before connecting to D-Bus
 
1855
    if not debug:
 
1856
        # Close all input and output, do double fork, etc.
 
1857
        daemon()
1812
1858
    
1813
1859
    global main_loop
1814
1860
    # From the Avahi example code
1818
1864
    # End of Avahi example code
1819
1865
    if use_dbus:
1820
1866
        try:
1821
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
 
1867
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1822
1868
                                            bus, do_not_queue=True)
1823
1869
        except dbus.exceptions.NameExistsException, e:
1824
 
            logger.error(unicode(e) + u", disabling D-Bus")
 
1870
            logger.error(unicode(e) + ", disabling D-Bus")
1825
1871
            use_dbus = False
1826
 
            server_settings[u"use_dbus"] = False
 
1872
            server_settings["use_dbus"] = False
1827
1873
            tcp_server.use_dbus = False
1828
1874
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1829
 
    service = AvahiService(name = server_settings[u"servicename"],
1830
 
                           servicetype = u"_mandos._tcp",
 
1875
    service = AvahiService(name = server_settings["servicename"],
 
1876
                           servicetype = "_mandos._tcp",
1831
1877
                           protocol = protocol, bus = bus)
1832
1878
    if server_settings["interface"]:
1833
1879
        service.interface = (if_nametoindex
1834
 
                             (str(server_settings[u"interface"])))
1835
 
 
1836
 
    if not debug:
1837
 
        # Close all input and output, do double fork, etc.
1838
 
        daemon()
1839
 
        
 
1880
                             (str(server_settings["interface"])))
 
1881
    
1840
1882
    global multiprocessing_manager
1841
1883
    multiprocessing_manager = multiprocessing.Manager()
1842
1884
    
1861
1903
                        client_config, section)))
1862
1904
            for section in client_config.sections()))
1863
1905
    if not tcp_server.clients:
1864
 
        logger.warning(u"No clients defined")
 
1906
        logger.warning("No clients defined")
1865
1907
        
1866
 
    try:
1867
 
        with pidfile:
1868
 
            pid = os.getpid()
1869
 
            pidfile.write(str(pid) + "\n")
1870
 
        del pidfile
1871
 
    except IOError:
1872
 
        logger.error(u"Could not write to file %r with PID %d",
1873
 
                     pidfilename, pid)
1874
 
    except NameError:
1875
 
        # "pidfile" was never created
1876
 
        pass
1877
 
    del pidfilename
1878
 
    
1879
1908
    if not debug:
 
1909
        try:
 
1910
            with pidfile:
 
1911
                pid = os.getpid()
 
1912
                pidfile.write(str(pid) + "\n".encode("utf-8"))
 
1913
            del pidfile
 
1914
        except IOError:
 
1915
            logger.error("Could not write to file %r with PID %d",
 
1916
                         pidfilename, pid)
 
1917
        except NameError:
 
1918
            # "pidfile" was never created
 
1919
            pass
 
1920
        del pidfilename
 
1921
        
1880
1922
        signal.signal(signal.SIGINT, signal.SIG_IGN)
 
1923
 
1881
1924
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1882
1925
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1883
1926
    
1885
1928
        class MandosDBusService(dbus.service.Object):
1886
1929
            """A D-Bus proxy object"""
1887
1930
            def __init__(self):
1888
 
                dbus.service.Object.__init__(self, bus, u"/")
1889
 
            _interface = u"se.bsnet.fukt.Mandos"
 
1931
                dbus.service.Object.__init__(self, bus, "/")
 
1932
            _interface = "se.bsnet.fukt.Mandos"
1890
1933
            
1891
 
            @dbus.service.signal(_interface, signature=u"o")
 
1934
            @dbus.service.signal(_interface, signature="o")
1892
1935
            def ClientAdded(self, objpath):
1893
1936
                "D-Bus signal"
1894
1937
                pass
1895
1938
            
1896
 
            @dbus.service.signal(_interface, signature=u"ss")
 
1939
            @dbus.service.signal(_interface, signature="ss")
1897
1940
            def ClientNotFound(self, fingerprint, address):
1898
1941
                "D-Bus signal"
1899
1942
                pass
1900
1943
            
1901
 
            @dbus.service.signal(_interface, signature=u"os")
 
1944
            @dbus.service.signal(_interface, signature="os")
1902
1945
            def ClientRemoved(self, objpath, name):
1903
1946
                "D-Bus signal"
1904
1947
                pass
1905
1948
            
1906
 
            @dbus.service.method(_interface, out_signature=u"ao")
 
1949
            @dbus.service.method(_interface, out_signature="ao")
1907
1950
            def GetAllClients(self):
1908
1951
                "D-Bus method"
1909
1952
                return dbus.Array(c.dbus_object_path
1910
1953
                                  for c in tcp_server.clients)
1911
1954
            
1912
1955
            @dbus.service.method(_interface,
1913
 
                                 out_signature=u"a{oa{sv}}")
 
1956
                                 out_signature="a{oa{sv}}")
1914
1957
            def GetAllClientsWithProperties(self):
1915
1958
                "D-Bus method"
1916
1959
                return dbus.Dictionary(
1917
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1960
                    ((c.dbus_object_path, c.GetAll(""))
1918
1961
                     for c in tcp_server.clients),
1919
 
                    signature=u"oa{sv}")
 
1962
                    signature="oa{sv}")
1920
1963
            
1921
 
            @dbus.service.method(_interface, in_signature=u"o")
 
1964
            @dbus.service.method(_interface, in_signature="o")
1922
1965
            def RemoveClient(self, object_path):
1923
1966
                "D-Bus method"
1924
1967
                for c in tcp_server.clients:
1966
2009
    # Find out what port we got
1967
2010
    service.port = tcp_server.socket.getsockname()[1]
1968
2011
    if use_ipv6:
1969
 
        logger.info(u"Now listening on address %r, port %d,"
 
2012
        logger.info("Now listening on address %r, port %d,"
1970
2013
                    " flowinfo %d, scope_id %d"
1971
2014
                    % tcp_server.socket.getsockname())
1972
2015
    else:                       # IPv4
1973
 
        logger.info(u"Now listening on address %r, port %d"
 
2016
        logger.info("Now listening on address %r, port %d"
1974
2017
                    % tcp_server.socket.getsockname())
1975
2018
    
1976
2019
    #service.interface = tcp_server.socket.getsockname()[3]
1980
2023
        try:
1981
2024
            service.activate()
1982
2025
        except dbus.exceptions.DBusException, error:
1983
 
            logger.critical(u"DBusException: %s", error)
 
2026
            logger.critical("DBusException: %s", error)
1984
2027
            cleanup()
1985
2028
            sys.exit(1)
1986
2029
        # End of Avahi example code
1990
2033
                             (tcp_server.handle_request
1991
2034
                              (*args[2:], **kwargs) or True))
1992
2035
        
1993
 
        logger.debug(u"Starting main loop")
 
2036
        logger.debug("Starting main loop")
1994
2037
        main_loop.run()
1995
2038
    except AvahiError, error:
1996
 
        logger.critical(u"AvahiError: %s", error)
 
2039
        logger.critical("AvahiError: %s", error)
1997
2040
        cleanup()
1998
2041
        sys.exit(1)
1999
2042
    except KeyboardInterrupt:
2000
2043
        if debug:
2001
 
            print >> sys.stderr
2002
 
        logger.debug(u"Server received KeyboardInterrupt")
2003
 
    logger.debug(u"Server exiting")
 
2044
            print("", file=sys.stderr)
 
2045
        logger.debug("Server received KeyboardInterrupt")
 
2046
    logger.debug("Server exiting")
2004
2047
    # Must run before the D-Bus bus name gets deregistered
2005
2048
    cleanup()
2006
2049