/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-21 19:34:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110321193439-lkj3kwvhmujd8lwv
* plugins.d/mandos-client.c (good_interface): Reject non-ARP
                                              interfaces.

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
 
246
247
    checker:    subprocess.Popen(); a running checker process used
247
248
                                    to see if the client lives.
248
249
                                    'None' if no process is running.
249
 
    checker_callback_tag:  - '' -
 
250
    checker_callback_tag: a gobject event source tag, or None
250
251
    checker_command: string; External command which is run to check
251
252
                     if client lives.  %() expansions are done at
252
253
                     runtime with vars(self) as dict, so that for
255
256
    created:    datetime.datetime(); (UTC) object creation
256
257
    current_checker_command: string; current running checker_command
257
258
    disable_hook:  If set, called by disable() as disable_hook(self)
258
 
    disable_initiator_tag: - '' -
 
259
    disable_initiator_tag: a gobject event source tag, or None
259
260
    enabled:    bool()
260
261
    fingerprint: string (40 or 32 hexadecimal digits); used to
261
262
                 uniquely identify the client
262
263
    host:       string; available for use by the checker command
263
264
    interval:   datetime.timedelta(); How often to start a new checker
 
265
    last_approval_request: datetime.datetime(); (UTC) or None
264
266
    last_checked_ok: datetime.datetime(); (UTC) or None
265
267
    last_enabled: datetime.datetime(); (UTC)
266
268
    name:       string; from the config file, used in log messages and
271
273
    runtime_expansions: Allowed attributes for runtime expansion.
272
274
    """
273
275
    
274
 
    runtime_expansions = (u"approval_delay", u"approval_duration",
275
 
                          u"created", u"enabled", u"fingerprint",
276
 
                          u"host", u"interval", u"last_checked_ok",
277
 
                          u"last_enabled", u"name", u"timeout")
 
276
    runtime_expansions = ("approval_delay", "approval_duration",
 
277
                          "created", "enabled", "fingerprint",
 
278
                          "host", "interval", "last_checked_ok",
 
279
                          "last_enabled", "name", "timeout")
278
280
    
279
281
    @staticmethod
280
282
    def _timedelta_to_milliseconds(td):
301
303
        self.name = name
302
304
        if config is None:
303
305
            config = {}
304
 
        logger.debug(u"Creating client %r", self.name)
 
306
        logger.debug("Creating client %r", self.name)
305
307
        # Uppercase and remove spaces from fingerprint for later
306
308
        # comparison purposes with return value from the fingerprint()
307
309
        # function
308
 
        self.fingerprint = (config[u"fingerprint"].upper()
309
 
                            .replace(u" ", u""))
310
 
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
311
 
        if u"secret" in config:
312
 
            self.secret = config[u"secret"].decode(u"base64")
313
 
        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:
314
316
            with open(os.path.expanduser(os.path.expandvars
315
 
                                         (config[u"secfile"])),
 
317
                                         (config["secfile"])),
316
318
                      "rb") as secfile:
317
319
                self.secret = secfile.read()
318
320
        else:
319
 
            raise TypeError(u"No secret or secfile for client %s"
 
321
            raise TypeError("No secret or secfile for client %s"
320
322
                            % self.name)
321
 
        self.host = config.get(u"host", u"")
 
323
        self.host = config.get("host", "")
322
324
        self.created = datetime.datetime.utcnow()
323
325
        self.enabled = False
 
326
        self.last_approval_request = None
324
327
        self.last_enabled = None
325
328
        self.last_checked_ok = None
326
 
        self.timeout = string_to_delta(config[u"timeout"])
327
 
        self.interval = string_to_delta(config[u"interval"])
 
329
        self.timeout = string_to_delta(config["timeout"])
 
330
        self.interval = string_to_delta(config["interval"])
328
331
        self.disable_hook = disable_hook
329
332
        self.checker = None
330
333
        self.checker_initiator_tag = None
331
334
        self.disable_initiator_tag = None
332
335
        self.checker_callback_tag = None
333
 
        self.checker_command = config[u"checker"]
 
336
        self.checker_command = config["checker"]
334
337
        self.current_checker_command = None
335
338
        self.last_connect = None
336
339
        self._approved = None
337
 
        self.approved_by_default = config.get(u"approved_by_default",
 
340
        self.approved_by_default = config.get("approved_by_default",
338
341
                                              True)
339
342
        self.approvals_pending = 0
340
343
        self.approval_delay = string_to_delta(
341
 
            config[u"approval_delay"])
 
344
            config["approval_delay"])
342
345
        self.approval_duration = string_to_delta(
343
 
            config[u"approval_duration"])
 
346
            config["approval_duration"])
344
347
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
345
348
    
346
349
    def send_changedstate(self):
350
353
        
351
354
    def enable(self):
352
355
        """Start this client's checker and timeout hooks"""
353
 
        if getattr(self, u"enabled", False):
 
356
        if getattr(self, "enabled", False):
354
357
            # Already enabled
355
358
            return
356
359
        self.send_changedstate()
375
378
        if not quiet:
376
379
            self.send_changedstate()
377
380
        if not quiet:
378
 
            logger.info(u"Disabling client %s", self.name)
379
 
        if getattr(self, u"disable_initiator_tag", False):
 
381
            logger.info("Disabling client %s", self.name)
 
382
        if getattr(self, "disable_initiator_tag", False):
380
383
            gobject.source_remove(self.disable_initiator_tag)
381
384
            self.disable_initiator_tag = None
382
 
        if getattr(self, u"checker_initiator_tag", False):
 
385
        if getattr(self, "checker_initiator_tag", False):
383
386
            gobject.source_remove(self.checker_initiator_tag)
384
387
            self.checker_initiator_tag = None
385
388
        self.stop_checker()
400
403
        if os.WIFEXITED(condition):
401
404
            exitstatus = os.WEXITSTATUS(condition)
402
405
            if exitstatus == 0:
403
 
                logger.info(u"Checker for %(name)s succeeded",
 
406
                logger.info("Checker for %(name)s succeeded",
404
407
                            vars(self))
405
408
                self.checked_ok()
406
409
            else:
407
 
                logger.info(u"Checker for %(name)s failed",
 
410
                logger.info("Checker for %(name)s failed",
408
411
                            vars(self))
409
412
        else:
410
 
            logger.warning(u"Checker for %(name)s crashed?",
 
413
            logger.warning("Checker for %(name)s crashed?",
411
414
                           vars(self))
412
415
    
413
416
    def checked_ok(self):
422
425
                                      (self.timeout_milliseconds(),
423
426
                                       self.disable))
424
427
    
 
428
    def need_approval(self):
 
429
        self.last_approval_request = datetime.datetime.utcnow()
 
430
    
425
431
    def start_checker(self):
426
432
        """Start a new checker subprocess if one is not running.
427
433
        
445
451
                raise error
446
452
        else:
447
453
            if pid:
448
 
                logger.warning(u"Checker was a zombie")
 
454
                logger.warning("Checker was a zombie")
449
455
                gobject.source_remove(self.checker_callback_tag)
450
456
                self.checker_callback(pid, status,
451
457
                                      self.current_checker_command)
458
464
                # Escape attributes for the shell
459
465
                escaped_attrs = dict(
460
466
                    (attr,
461
 
                     re.escape(unicode(str(getattr(self, attr, u"")),
 
467
                     re.escape(unicode(str(getattr(self, attr, "")),
462
468
                                       errors=
463
 
                                       u'replace')))
 
469
                                       'replace')))
464
470
                    for attr in
465
471
                    self.runtime_expansions)
466
472
 
467
473
                try:
468
474
                    command = self.checker_command % escaped_attrs
469
475
                except TypeError, error:
470
 
                    logger.error(u'Could not format string "%s":'
471
 
                                 u' %s', self.checker_command, error)
 
476
                    logger.error('Could not format string "%s":'
 
477
                                 ' %s', self.checker_command, error)
472
478
                    return True # Try again later
473
479
            self.current_checker_command = command
474
480
            try:
475
 
                logger.info(u"Starting checker %r for %s",
 
481
                logger.info("Starting checker %r for %s",
476
482
                            command, self.name)
477
483
                # We don't need to redirect stdout and stderr, since
478
484
                # in normal mode, that is already done by daemon(),
480
486
                # always replaced by /dev/null.)
481
487
                self.checker = subprocess.Popen(command,
482
488
                                                close_fds=True,
483
 
                                                shell=True, cwd=u"/")
 
489
                                                shell=True, cwd="/")
484
490
                self.checker_callback_tag = (gobject.child_watch_add
485
491
                                             (self.checker.pid,
486
492
                                              self.checker_callback,
492
498
                    gobject.source_remove(self.checker_callback_tag)
493
499
                    self.checker_callback(pid, status, command)
494
500
            except OSError, error:
495
 
                logger.error(u"Failed to start subprocess: %s",
 
501
                logger.error("Failed to start subprocess: %s",
496
502
                             error)
497
503
        # Re-run this periodically if run by gobject.timeout_add
498
504
        return True
502
508
        if self.checker_callback_tag:
503
509
            gobject.source_remove(self.checker_callback_tag)
504
510
            self.checker_callback_tag = None
505
 
        if getattr(self, u"checker", None) is None:
 
511
        if getattr(self, "checker", None) is None:
506
512
            return
507
 
        logger.debug(u"Stopping checker for %(name)s", vars(self))
 
513
        logger.debug("Stopping checker for %(name)s", vars(self))
508
514
        try:
509
515
            os.kill(self.checker.pid, signal.SIGTERM)
510
516
            #time.sleep(0.5)
515
521
                raise
516
522
        self.checker = None
517
523
 
518
 
def dbus_service_property(dbus_interface, signature=u"v",
519
 
                          access=u"readwrite", byte_arrays=False):
 
524
def dbus_service_property(dbus_interface, signature="v",
 
525
                          access="readwrite", byte_arrays=False):
520
526
    """Decorators for marking methods of a DBusObjectWithProperties to
521
527
    become properties on the D-Bus.
522
528
    
529
535
    """
530
536
    # Encoding deeply encoded byte arrays is not supported yet by the
531
537
    # "Set" method, so we fail early here:
532
 
    if byte_arrays and signature != u"ay":
533
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
534
 
                         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)
535
541
    def decorator(func):
536
542
        func._dbus_is_property = True
537
543
        func._dbus_interface = dbus_interface
538
544
        func._dbus_signature = signature
539
545
        func._dbus_access = access
540
546
        func._dbus_name = func.__name__
541
 
        if func._dbus_name.endswith(u"_dbus_property"):
 
547
        if func._dbus_name.endswith("_dbus_property"):
542
548
            func._dbus_name = func._dbus_name[:-14]
543
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
 
549
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
544
550
        return func
545
551
    return decorator
546
552
 
574
580
    
575
581
    @staticmethod
576
582
    def _is_dbus_property(obj):
577
 
        return getattr(obj, u"_dbus_is_property", False)
 
583
        return getattr(obj, "_dbus_is_property", False)
578
584
    
579
585
    def _get_all_dbus_properties(self):
580
586
        """Returns a generator of (name, attribute) pairs
588
594
        property with the specified name and interface.
589
595
        """
590
596
        for name in (property_name,
591
 
                     property_name + u"_dbus_property"):
 
597
                     property_name + "_dbus_property"):
592
598
            prop = getattr(self, name, None)
593
599
            if (prop is None
594
600
                or not self._is_dbus_property(prop)
598
604
                continue
599
605
            return prop
600
606
        # No such property
601
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
602
 
                                   + interface_name + u"."
 
607
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
608
                                   + interface_name + "."
603
609
                                   + property_name)
604
610
    
605
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
606
 
                         out_signature=u"v")
 
611
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
 
612
                         out_signature="v")
607
613
    def Get(self, interface_name, property_name):
608
614
        """Standard D-Bus property Get() method, see D-Bus standard.
609
615
        """
610
616
        prop = self._get_dbus_property(interface_name, property_name)
611
 
        if prop._dbus_access == u"write":
 
617
        if prop._dbus_access == "write":
612
618
            raise DBusPropertyAccessException(property_name)
613
619
        value = prop()
614
 
        if not hasattr(value, u"variant_level"):
 
620
        if not hasattr(value, "variant_level"):
615
621
            return value
616
622
        return type(value)(value, variant_level=value.variant_level+1)
617
623
    
618
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
 
624
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
619
625
    def Set(self, interface_name, property_name, value):
620
626
        """Standard D-Bus property Set() method, see D-Bus standard.
621
627
        """
622
628
        prop = self._get_dbus_property(interface_name, property_name)
623
 
        if prop._dbus_access == u"read":
 
629
        if prop._dbus_access == "read":
624
630
            raise DBusPropertyAccessException(property_name)
625
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
 
631
        if prop._dbus_get_args_options["byte_arrays"]:
626
632
            # The byte_arrays option is not supported yet on
627
633
            # signatures other than "ay".
628
 
            if prop._dbus_signature != u"ay":
 
634
            if prop._dbus_signature != "ay":
629
635
                raise ValueError
630
636
            value = dbus.ByteArray(''.join(unichr(byte)
631
637
                                           for byte in value))
632
638
        prop(value)
633
639
    
634
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
635
 
                         out_signature=u"a{sv}")
 
640
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
 
641
                         out_signature="a{sv}")
636
642
    def GetAll(self, interface_name):
637
643
        """Standard D-Bus property GetAll() method, see D-Bus
638
644
        standard.
646
652
                # Interface non-empty but did not match
647
653
                continue
648
654
            # Ignore write-only properties
649
 
            if prop._dbus_access == u"write":
 
655
            if prop._dbus_access == "write":
650
656
                continue
651
657
            value = prop()
652
 
            if not hasattr(value, u"variant_level"):
 
658
            if not hasattr(value, "variant_level"):
653
659
                all[name] = value
654
660
                continue
655
661
            all[name] = type(value)(value, variant_level=
656
662
                                    value.variant_level+1)
657
 
        return dbus.Dictionary(all, signature=u"sv")
 
663
        return dbus.Dictionary(all, signature="sv")
658
664
    
659
665
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
660
 
                         out_signature=u"s",
 
666
                         out_signature="s",
661
667
                         path_keyword='object_path',
662
668
                         connection_keyword='connection')
663
669
    def Introspect(self, object_path, connection):
668
674
        try:
669
675
            document = xml.dom.minidom.parseString(xmlstring)
670
676
            def make_tag(document, name, prop):
671
 
                e = document.createElement(u"property")
672
 
                e.setAttribute(u"name", name)
673
 
                e.setAttribute(u"type", prop._dbus_signature)
674
 
                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)
675
681
                return e
676
 
            for if_tag in document.getElementsByTagName(u"interface"):
 
682
            for if_tag in document.getElementsByTagName("interface"):
677
683
                for tag in (make_tag(document, name, prop)
678
684
                            for name, prop
679
685
                            in self._get_all_dbus_properties()
680
686
                            if prop._dbus_interface
681
 
                            == if_tag.getAttribute(u"name")):
 
687
                            == if_tag.getAttribute("name")):
682
688
                    if_tag.appendChild(tag)
683
689
                # Add the names to the return values for the
684
690
                # "org.freedesktop.DBus.Properties" methods
685
 
                if (if_tag.getAttribute(u"name")
686
 
                    == u"org.freedesktop.DBus.Properties"):
687
 
                    for cn in if_tag.getElementsByTagName(u"method"):
688
 
                        if cn.getAttribute(u"name") == u"Get":
689
 
                            for arg in cn.getElementsByTagName(u"arg"):
690
 
                                if (arg.getAttribute(u"direction")
691
 
                                    == u"out"):
692
 
                                    arg.setAttribute(u"name", u"value")
693
 
                        elif cn.getAttribute(u"name") == u"GetAll":
694
 
                            for arg in cn.getElementsByTagName(u"arg"):
695
 
                                if (arg.getAttribute(u"direction")
696
 
                                    == u"out"):
697
 
                                    arg.setAttribute(u"name", u"props")
698
 
            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")
699
705
            document.unlink()
700
706
        except (AttributeError, xml.dom.DOMException,
701
707
                xml.parsers.expat.ExpatError), error:
702
 
            logger.error(u"Failed to override Introspection method",
 
708
            logger.error("Failed to override Introspection method",
703
709
                         error)
704
710
        return xmlstring
705
711
 
713
719
    """
714
720
    
715
721
    runtime_expansions = (Client.runtime_expansions
716
 
                          + (u"dbus_object_path",))
 
722
                          + ("dbus_object_path",))
717
723
    
718
724
    # dbus.service.Object doesn't use super(), so we can't either.
719
725
    
724
730
        # Only now, when this client is initialized, can it show up on
725
731
        # the D-Bus
726
732
        client_object_name = unicode(self.name).translate(
727
 
            {ord(u"."): ord(u"_"),
728
 
             ord(u"-"): ord(u"_")})
 
733
            {ord("."): ord("_"),
 
734
             ord("-"): ord("_")})
729
735
        self.dbus_object_path = (dbus.ObjectPath
730
 
                                 (u"/clients/" + client_object_name))
 
736
                                 ("/clients/" + client_object_name))
731
737
        DBusObjectWithProperties.__init__(self, self.bus,
732
738
                                          self.dbus_object_path)
733
739
        
740
746
        if (hasattr(self, "dbus_object_path")
741
747
            and bval is not bool(old_value)):
742
748
            dbus_bool = dbus.Boolean(bval, variant_level=1)
743
 
            self.PropertyChanged(dbus.String(u"ApprovalPending"),
 
749
            self.PropertyChanged(dbus.String("ApprovalPending"),
744
750
                                 dbus_bool)
745
751
 
746
752
    approvals_pending = property(_get_approvals_pending,
754
760
                           variant_level=variant_level)
755
761
    
756
762
    def enable(self):
757
 
        oldstate = getattr(self, u"enabled", False)
 
763
        oldstate = getattr(self, "enabled", False)
758
764
        r = Client.enable(self)
759
765
        if oldstate != self.enabled:
760
766
            # Emit D-Bus signals
761
 
            self.PropertyChanged(dbus.String(u"Enabled"),
 
767
            self.PropertyChanged(dbus.String("Enabled"),
762
768
                                 dbus.Boolean(True, variant_level=1))
763
769
            self.PropertyChanged(
764
 
                dbus.String(u"LastEnabled"),
 
770
                dbus.String("LastEnabled"),
765
771
                self._datetime_to_dbus(self.last_enabled,
766
772
                                       variant_level=1))
767
773
        return r
768
774
    
769
775
    def disable(self, quiet = False):
770
 
        oldstate = getattr(self, u"enabled", False)
 
776
        oldstate = getattr(self, "enabled", False)
771
777
        r = Client.disable(self, quiet=quiet)
772
778
        if not quiet and oldstate != self.enabled:
773
779
            # Emit D-Bus signal
774
 
            self.PropertyChanged(dbus.String(u"Enabled"),
 
780
            self.PropertyChanged(dbus.String("Enabled"),
775
781
                                 dbus.Boolean(False, variant_level=1))
776
782
        return r
777
783
    
780
786
            self.remove_from_connection()
781
787
        except LookupError:
782
788
            pass
783
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
 
789
        if hasattr(DBusObjectWithProperties, "__del__"):
784
790
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
785
791
        Client.__del__(self, *args, **kwargs)
786
792
    
789
795
        self.checker_callback_tag = None
790
796
        self.checker = None
791
797
        # Emit D-Bus signal
792
 
        self.PropertyChanged(dbus.String(u"CheckerRunning"),
 
798
        self.PropertyChanged(dbus.String("CheckerRunning"),
793
799
                             dbus.Boolean(False, variant_level=1))
794
800
        if os.WIFEXITED(condition):
795
801
            exitstatus = os.WEXITSTATUS(condition)
810
816
        r = Client.checked_ok(self, *args, **kwargs)
811
817
        # Emit D-Bus signal
812
818
        self.PropertyChanged(
813
 
            dbus.String(u"LastCheckedOK"),
 
819
            dbus.String("LastCheckedOK"),
814
820
            (self._datetime_to_dbus(self.last_checked_ok,
815
821
                                    variant_level=1)))
816
822
        return r
817
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
    
818
833
    def start_checker(self, *args, **kwargs):
819
834
        old_checker = self.checker
820
835
        if self.checker is not None:
828
843
            # Emit D-Bus signal
829
844
            self.CheckerStarted(self.current_checker_command)
830
845
            self.PropertyChanged(
831
 
                dbus.String(u"CheckerRunning"),
 
846
                dbus.String("CheckerRunning"),
832
847
                dbus.Boolean(True, variant_level=1))
833
848
        return r
834
849
    
835
850
    def stop_checker(self, *args, **kwargs):
836
 
        old_checker = getattr(self, u"checker", None)
 
851
        old_checker = getattr(self, "checker", None)
837
852
        r = Client.stop_checker(self, *args, **kwargs)
838
853
        if (old_checker is not None
839
 
            and getattr(self, u"checker", None) is None):
840
 
            self.PropertyChanged(dbus.String(u"CheckerRunning"),
 
854
            and getattr(self, "checker", None) is None):
 
855
            self.PropertyChanged(dbus.String("CheckerRunning"),
841
856
                                 dbus.Boolean(False, variant_level=1))
842
857
        return r
843
858
 
854
869
    
855
870
    
856
871
    ## D-Bus methods, signals & properties
857
 
    _interface = u"se.bsnet.fukt.Mandos.Client"
 
872
    _interface = "se.bsnet.fukt.Mandos.Client"
858
873
    
859
874
    ## Signals
860
875
    
861
876
    # CheckerCompleted - signal
862
 
    @dbus.service.signal(_interface, signature=u"nxs")
 
877
    @dbus.service.signal(_interface, signature="nxs")
863
878
    def CheckerCompleted(self, exitcode, waitstatus, command):
864
879
        "D-Bus signal"
865
880
        pass
866
881
    
867
882
    # CheckerStarted - signal
868
 
    @dbus.service.signal(_interface, signature=u"s")
 
883
    @dbus.service.signal(_interface, signature="s")
869
884
    def CheckerStarted(self, command):
870
885
        "D-Bus signal"
871
886
        pass
872
887
    
873
888
    # PropertyChanged - signal
874
 
    @dbus.service.signal(_interface, signature=u"sv")
 
889
    @dbus.service.signal(_interface, signature="sv")
875
890
    def PropertyChanged(self, property, value):
876
891
        "D-Bus signal"
877
892
        pass
886
901
        pass
887
902
    
888
903
    # Rejected - signal
889
 
    @dbus.service.signal(_interface, signature=u"s")
 
904
    @dbus.service.signal(_interface, signature="s")
890
905
    def Rejected(self, reason):
891
906
        "D-Bus signal"
892
907
        pass
893
908
    
894
909
    # NeedApproval - signal
895
 
    @dbus.service.signal(_interface, signature=u"tb")
 
910
    @dbus.service.signal(_interface, signature="tb")
896
911
    def NeedApproval(self, timeout, default):
897
912
        "D-Bus signal"
898
 
        pass
 
913
        return self.need_approval()
899
914
    
900
915
    ## Methods
901
 
 
 
916
    
902
917
    # Approve - method
903
 
    @dbus.service.method(_interface, in_signature=u"b")
 
918
    @dbus.service.method(_interface, in_signature="b")
904
919
    def Approve(self, value):
905
920
        self.approve(value)
906
 
 
 
921
    
907
922
    # CheckedOK - method
908
923
    @dbus.service.method(_interface)
909
924
    def CheckedOK(self):
935
950
    ## Properties
936
951
    
937
952
    # ApprovalPending - property
938
 
    @dbus_service_property(_interface, signature=u"b", access=u"read")
 
953
    @dbus_service_property(_interface, signature="b", access="read")
939
954
    def ApprovalPending_dbus_property(self):
940
955
        return dbus.Boolean(bool(self.approvals_pending))
941
956
    
942
957
    # ApprovedByDefault - property
943
 
    @dbus_service_property(_interface, signature=u"b",
944
 
                           access=u"readwrite")
 
958
    @dbus_service_property(_interface, signature="b",
 
959
                           access="readwrite")
945
960
    def ApprovedByDefault_dbus_property(self, value=None):
946
961
        if value is None:       # get
947
962
            return dbus.Boolean(self.approved_by_default)
948
963
        self.approved_by_default = bool(value)
949
964
        # Emit D-Bus signal
950
 
        self.PropertyChanged(dbus.String(u"ApprovedByDefault"),
 
965
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
951
966
                             dbus.Boolean(value, variant_level=1))
952
967
    
953
968
    # ApprovalDelay - property
954
 
    @dbus_service_property(_interface, signature=u"t",
955
 
                           access=u"readwrite")
 
969
    @dbus_service_property(_interface, signature="t",
 
970
                           access="readwrite")
956
971
    def ApprovalDelay_dbus_property(self, value=None):
957
972
        if value is None:       # get
958
973
            return dbus.UInt64(self.approval_delay_milliseconds())
959
974
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
960
975
        # Emit D-Bus signal
961
 
        self.PropertyChanged(dbus.String(u"ApprovalDelay"),
 
976
        self.PropertyChanged(dbus.String("ApprovalDelay"),
962
977
                             dbus.UInt64(value, variant_level=1))
963
978
    
964
979
    # ApprovalDuration - property
965
 
    @dbus_service_property(_interface, signature=u"t",
966
 
                           access=u"readwrite")
 
980
    @dbus_service_property(_interface, signature="t",
 
981
                           access="readwrite")
967
982
    def ApprovalDuration_dbus_property(self, value=None):
968
983
        if value is None:       # get
969
984
            return dbus.UInt64(self._timedelta_to_milliseconds(
970
985
                    self.approval_duration))
971
986
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
972
987
        # Emit D-Bus signal
973
 
        self.PropertyChanged(dbus.String(u"ApprovalDuration"),
 
988
        self.PropertyChanged(dbus.String("ApprovalDuration"),
974
989
                             dbus.UInt64(value, variant_level=1))
975
990
    
976
991
    # Name - property
977
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
992
    @dbus_service_property(_interface, signature="s", access="read")
978
993
    def Name_dbus_property(self):
979
994
        return dbus.String(self.name)
980
995
    
981
996
    # Fingerprint - property
982
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
997
    @dbus_service_property(_interface, signature="s", access="read")
983
998
    def Fingerprint_dbus_property(self):
984
999
        return dbus.String(self.fingerprint)
985
1000
    
986
1001
    # Host - property
987
 
    @dbus_service_property(_interface, signature=u"s",
988
 
                           access=u"readwrite")
 
1002
    @dbus_service_property(_interface, signature="s",
 
1003
                           access="readwrite")
989
1004
    def Host_dbus_property(self, value=None):
990
1005
        if value is None:       # get
991
1006
            return dbus.String(self.host)
992
1007
        self.host = value
993
1008
        # Emit D-Bus signal
994
 
        self.PropertyChanged(dbus.String(u"Host"),
 
1009
        self.PropertyChanged(dbus.String("Host"),
995
1010
                             dbus.String(value, variant_level=1))
996
1011
    
997
1012
    # Created - property
998
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
1013
    @dbus_service_property(_interface, signature="s", access="read")
999
1014
    def Created_dbus_property(self):
1000
1015
        return dbus.String(self._datetime_to_dbus(self.created))
1001
1016
    
1002
1017
    # LastEnabled - property
1003
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
1018
    @dbus_service_property(_interface, signature="s", access="read")
1004
1019
    def LastEnabled_dbus_property(self):
1005
1020
        if self.last_enabled is None:
1006
 
            return dbus.String(u"")
 
1021
            return dbus.String("")
1007
1022
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
1008
1023
    
1009
1024
    # Enabled - property
1010
 
    @dbus_service_property(_interface, signature=u"b",
1011
 
                           access=u"readwrite")
 
1025
    @dbus_service_property(_interface, signature="b",
 
1026
                           access="readwrite")
1012
1027
    def Enabled_dbus_property(self, value=None):
1013
1028
        if value is None:       # get
1014
1029
            return dbus.Boolean(self.enabled)
1018
1033
            self.disable()
1019
1034
    
1020
1035
    # LastCheckedOK - property
1021
 
    @dbus_service_property(_interface, signature=u"s",
1022
 
                           access=u"readwrite")
 
1036
    @dbus_service_property(_interface, signature="s",
 
1037
                           access="readwrite")
1023
1038
    def LastCheckedOK_dbus_property(self, value=None):
1024
1039
        if value is not None:
1025
1040
            self.checked_ok()
1026
1041
            return
1027
1042
        if self.last_checked_ok is None:
1028
 
            return dbus.String(u"")
 
1043
            return dbus.String("")
1029
1044
        return dbus.String(self._datetime_to_dbus(self
1030
1045
                                                  .last_checked_ok))
1031
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
    
1032
1056
    # Timeout - property
1033
 
    @dbus_service_property(_interface, signature=u"t",
1034
 
                           access=u"readwrite")
 
1057
    @dbus_service_property(_interface, signature="t",
 
1058
                           access="readwrite")
1035
1059
    def Timeout_dbus_property(self, value=None):
1036
1060
        if value is None:       # get
1037
1061
            return dbus.UInt64(self.timeout_milliseconds())
1038
1062
        self.timeout = datetime.timedelta(0, 0, 0, value)
1039
1063
        # Emit D-Bus signal
1040
 
        self.PropertyChanged(dbus.String(u"Timeout"),
 
1064
        self.PropertyChanged(dbus.String("Timeout"),
1041
1065
                             dbus.UInt64(value, variant_level=1))
1042
 
        if getattr(self, u"disable_initiator_tag", None) is None:
 
1066
        if getattr(self, "disable_initiator_tag", None) is None:
1043
1067
            return
1044
1068
        # Reschedule timeout
1045
1069
        gobject.source_remove(self.disable_initiator_tag)
1058
1082
                                          (time_to_die, self.disable))
1059
1083
    
1060
1084
    # Interval - property
1061
 
    @dbus_service_property(_interface, signature=u"t",
1062
 
                           access=u"readwrite")
 
1085
    @dbus_service_property(_interface, signature="t",
 
1086
                           access="readwrite")
1063
1087
    def Interval_dbus_property(self, value=None):
1064
1088
        if value is None:       # get
1065
1089
            return dbus.UInt64(self.interval_milliseconds())
1066
1090
        self.interval = datetime.timedelta(0, 0, 0, value)
1067
1091
        # Emit D-Bus signal
1068
 
        self.PropertyChanged(dbus.String(u"Interval"),
 
1092
        self.PropertyChanged(dbus.String("Interval"),
1069
1093
                             dbus.UInt64(value, variant_level=1))
1070
 
        if getattr(self, u"checker_initiator_tag", None) is None:
 
1094
        if getattr(self, "checker_initiator_tag", None) is None:
1071
1095
            return
1072
1096
        # Reschedule checker run
1073
1097
        gobject.source_remove(self.checker_initiator_tag)
1076
1100
        self.start_checker()    # Start one now, too
1077
1101
 
1078
1102
    # Checker - property
1079
 
    @dbus_service_property(_interface, signature=u"s",
1080
 
                           access=u"readwrite")
 
1103
    @dbus_service_property(_interface, signature="s",
 
1104
                           access="readwrite")
1081
1105
    def Checker_dbus_property(self, value=None):
1082
1106
        if value is None:       # get
1083
1107
            return dbus.String(self.checker_command)
1084
1108
        self.checker_command = value
1085
1109
        # Emit D-Bus signal
1086
 
        self.PropertyChanged(dbus.String(u"Checker"),
 
1110
        self.PropertyChanged(dbus.String("Checker"),
1087
1111
                             dbus.String(self.checker_command,
1088
1112
                                         variant_level=1))
1089
1113
    
1090
1114
    # CheckerRunning - property
1091
 
    @dbus_service_property(_interface, signature=u"b",
1092
 
                           access=u"readwrite")
 
1115
    @dbus_service_property(_interface, signature="b",
 
1116
                           access="readwrite")
1093
1117
    def CheckerRunning_dbus_property(self, value=None):
1094
1118
        if value is None:       # get
1095
1119
            return dbus.Boolean(self.checker is not None)
1099
1123
            self.stop_checker()
1100
1124
    
1101
1125
    # ObjectPath - property
1102
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
 
1126
    @dbus_service_property(_interface, signature="o", access="read")
1103
1127
    def ObjectPath_dbus_property(self):
1104
1128
        return self.dbus_object_path # is already a dbus.ObjectPath
1105
1129
    
1106
1130
    # Secret = property
1107
 
    @dbus_service_property(_interface, signature=u"ay",
1108
 
                           access=u"write", byte_arrays=True)
 
1131
    @dbus_service_property(_interface, signature="ay",
 
1132
                           access="write", byte_arrays=True)
1109
1133
    def Secret_dbus_property(self, value):
1110
1134
        self.secret = str(value)
1111
1135
    
1146
1170
    
1147
1171
    def handle(self):
1148
1172
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1149
 
            logger.info(u"TCP connection from: %s",
 
1173
            logger.info("TCP connection from: %s",
1150
1174
                        unicode(self.client_address))
1151
 
            logger.debug(u"Pipe FD: %d",
 
1175
            logger.debug("Pipe FD: %d",
1152
1176
                         self.server.child_pipe.fileno())
1153
1177
 
1154
1178
            session = (gnutls.connection
1161
1185
            # no X.509 keys are added to it.  Therefore, we can use it
1162
1186
            # here despite using OpenPGP certificates.
1163
1187
 
1164
 
            #priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1165
 
            #                      u"+AES-256-CBC", u"+SHA1",
1166
 
            #                      u"+COMP-NULL", u"+CTYPE-OPENPGP",
1167
 
            #                      u"+DHE-DSS"))
 
1188
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
1189
            #                      "+AES-256-CBC", "+SHA1",
 
1190
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
 
1191
            #                      "+DHE-DSS"))
1168
1192
            # Use a fallback default, since this MUST be set.
1169
1193
            priority = self.server.gnutls_priority
1170
1194
            if priority is None:
1171
 
                priority = u"NORMAL"
 
1195
                priority = "NORMAL"
1172
1196
            (gnutls.library.functions
1173
1197
             .gnutls_priority_set_direct(session._c_object,
1174
1198
                                         priority, None))
1176
1200
            # Start communication using the Mandos protocol
1177
1201
            # Get protocol number
1178
1202
            line = self.request.makefile().readline()
1179
 
            logger.debug(u"Protocol version: %r", line)
 
1203
            logger.debug("Protocol version: %r", line)
1180
1204
            try:
1181
1205
                if int(line.strip().split()[0]) > 1:
1182
1206
                    raise RuntimeError
1183
1207
            except (ValueError, IndexError, RuntimeError), error:
1184
 
                logger.error(u"Unknown protocol version: %s", error)
 
1208
                logger.error("Unknown protocol version: %s", error)
1185
1209
                return
1186
1210
 
1187
1211
            # Start GnuTLS connection
1188
1212
            try:
1189
1213
                session.handshake()
1190
1214
            except gnutls.errors.GNUTLSError, error:
1191
 
                logger.warning(u"Handshake failed: %s", error)
 
1215
                logger.warning("Handshake failed: %s", error)
1192
1216
                # Do not run session.bye() here: the session is not
1193
1217
                # established.  Just abandon the request.
1194
1218
                return
1195
 
            logger.debug(u"Handshake succeeded")
 
1219
            logger.debug("Handshake succeeded")
1196
1220
 
1197
1221
            approval_required = False
1198
1222
            try:
1200
1224
                    fpr = self.fingerprint(self.peer_certificate
1201
1225
                                           (session))
1202
1226
                except (TypeError, gnutls.errors.GNUTLSError), error:
1203
 
                    logger.warning(u"Bad certificate: %s", error)
 
1227
                    logger.warning("Bad certificate: %s", error)
1204
1228
                    return
1205
 
                logger.debug(u"Fingerprint: %s", fpr)
 
1229
                logger.debug("Fingerprint: %s", fpr)
1206
1230
 
1207
1231
                try:
1208
1232
                    client = ProxyClient(child_pipe, fpr,
1217
1241
                
1218
1242
                while True:
1219
1243
                    if not client.enabled:
1220
 
                        logger.warning(u"Client %s is disabled",
 
1244
                        logger.warning("Client %s is disabled",
1221
1245
                                       client.name)
1222
1246
                        if self.server.use_dbus:
1223
1247
                            # Emit D-Bus signal
1228
1252
                        #We are approved or approval is disabled
1229
1253
                        break
1230
1254
                    elif client._approved is None:
1231
 
                        logger.info(u"Client %s needs approval",
 
1255
                        logger.info("Client %s needs approval",
1232
1256
                                    client.name)
1233
1257
                        if self.server.use_dbus:
1234
1258
                            # Emit D-Bus signal
1236
1260
                                client.approval_delay_milliseconds(),
1237
1261
                                client.approved_by_default)
1238
1262
                    else:
1239
 
                        logger.warning(u"Client %s was not approved",
 
1263
                        logger.warning("Client %s was not approved",
1240
1264
                                       client.name)
1241
1265
                        if self.server.use_dbus:
1242
1266
                            # Emit D-Bus signal
1271
1295
                    except (gnutls.errors.GNUTLSError), error:
1272
1296
                        logger.warning("gnutls send failed")
1273
1297
                        return
1274
 
                    logger.debug(u"Sent: %d, remaining: %d",
 
1298
                    logger.debug("Sent: %d, remaining: %d",
1275
1299
                                 sent, len(client.secret)
1276
1300
                                 - (sent_size + sent))
1277
1301
                    sent_size += sent
1278
1302
 
1279
 
                logger.info(u"Sending secret to %s", client.name)
 
1303
                logger.info("Sending secret to %s", client.name)
1280
1304
                # bump the timeout as if seen
1281
1305
                client.checked_ok()
1282
1306
                if self.server.use_dbus:
1305
1329
                     .gnutls_certificate_get_peers
1306
1330
                     (session._c_object, ctypes.byref(list_size)))
1307
1331
        if not bool(cert_list) and list_size.value != 0:
1308
 
            raise gnutls.errors.GNUTLSError(u"error getting peer"
1309
 
                                            u" certificate")
 
1332
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1333
                                            " certificate")
1310
1334
        if list_size.value == 0:
1311
1335
            return None
1312
1336
        cert = cert_list[0]
1338
1362
        if crtverify.value != 0:
1339
1363
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1340
1364
            raise (gnutls.errors.CertificateSecurityError
1341
 
                   (u"Verify failed"))
 
1365
                   ("Verify failed"))
1342
1366
        # New buffer for the fingerprint
1343
1367
        buf = ctypes.create_string_buffer(20)
1344
1368
        buf_len = ctypes.c_size_t()
1351
1375
        # Convert the buffer to a Python bytestring
1352
1376
        fpr = ctypes.string_at(buf, buf_len.value)
1353
1377
        # Convert the bytestring to hexadecimal notation
1354
 
        hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
 
1378
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1355
1379
        return hex_fpr
1356
1380
 
1357
1381
 
1385
1409
 
1386
1410
    def add_pipe(self, parent_pipe):
1387
1411
        """Dummy function; override as necessary"""
1388
 
        pass
 
1412
        raise NotImplementedError
1389
1413
 
1390
1414
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1391
1415
                     socketserver.TCPServer, object):
1409
1433
        bind to an address or port if they were not specified."""
1410
1434
        if self.interface is not None:
1411
1435
            if SO_BINDTODEVICE is None:
1412
 
                logger.error(u"SO_BINDTODEVICE does not exist;"
1413
 
                             u" cannot bind to interface %s",
 
1436
                logger.error("SO_BINDTODEVICE does not exist;"
 
1437
                             " cannot bind to interface %s",
1414
1438
                             self.interface)
1415
1439
            else:
1416
1440
                try:
1417
1441
                    self.socket.setsockopt(socket.SOL_SOCKET,
1418
1442
                                           SO_BINDTODEVICE,
1419
1443
                                           str(self.interface
1420
 
                                               + u'\0'))
 
1444
                                               + '\0'))
1421
1445
                except socket.error, error:
1422
1446
                    if error[0] == errno.EPERM:
1423
 
                        logger.error(u"No permission to"
1424
 
                                     u" bind to interface %s",
 
1447
                        logger.error("No permission to"
 
1448
                                     " bind to interface %s",
1425
1449
                                     self.interface)
1426
1450
                    elif error[0] == errno.ENOPROTOOPT:
1427
 
                        logger.error(u"SO_BINDTODEVICE not available;"
1428
 
                                     u" cannot bind to interface %s",
 
1451
                        logger.error("SO_BINDTODEVICE not available;"
 
1452
                                     " cannot bind to interface %s",
1429
1453
                                     self.interface)
1430
1454
                    else:
1431
1455
                        raise
1433
1457
        if self.server_address[0] or self.server_address[1]:
1434
1458
            if not self.server_address[0]:
1435
1459
                if self.address_family == socket.AF_INET6:
1436
 
                    any_address = u"::" # in6addr_any
 
1460
                    any_address = "::" # in6addr_any
1437
1461
                else:
1438
1462
                    any_address = socket.INADDR_ANY
1439
1463
                self.server_address = (any_address,
1488
1512
    def handle_ipc(self, source, condition, parent_pipe=None,
1489
1513
                   client_object=None):
1490
1514
        condition_names = {
1491
 
            gobject.IO_IN: u"IN",   # There is data to read.
1492
 
            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
1493
1517
                                    # blocking).
1494
 
            gobject.IO_PRI: u"PRI", # There is urgent data to read.
1495
 
            gobject.IO_ERR: u"ERR", # Error condition.
1496
 
            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
1497
1521
                                    # broken, usually for pipes and
1498
1522
                                    # sockets).
1499
1523
            }
1518
1542
                    client = c
1519
1543
                    break
1520
1544
            else:
1521
 
                logger.warning(u"Client not found for fingerprint: %s, ad"
1522
 
                               u"dress: %s", fpr, address)
 
1545
                logger.warning("Client not found for fingerprint: %s, ad"
 
1546
                               "dress: %s", fpr, address)
1523
1547
                if self.use_dbus:
1524
1548
                    # Emit D-Bus signal
1525
1549
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1559
1583
def string_to_delta(interval):
1560
1584
    """Parse a string and return a datetime.timedelta
1561
1585
    
1562
 
    >>> string_to_delta(u'7d')
 
1586
    >>> string_to_delta('7d')
1563
1587
    datetime.timedelta(7)
1564
 
    >>> string_to_delta(u'60s')
 
1588
    >>> string_to_delta('60s')
1565
1589
    datetime.timedelta(0, 60)
1566
 
    >>> string_to_delta(u'60m')
 
1590
    >>> string_to_delta('60m')
1567
1591
    datetime.timedelta(0, 3600)
1568
 
    >>> string_to_delta(u'24h')
 
1592
    >>> string_to_delta('24h')
1569
1593
    datetime.timedelta(1)
1570
 
    >>> string_to_delta(u'1w')
 
1594
    >>> string_to_delta('1w')
1571
1595
    datetime.timedelta(7)
1572
 
    >>> string_to_delta(u'5m 30s')
 
1596
    >>> string_to_delta('5m 30s')
1573
1597
    datetime.timedelta(0, 330)
1574
1598
    """
1575
1599
    timevalue = datetime.timedelta(0)
1577
1601
        try:
1578
1602
            suffix = unicode(s[-1])
1579
1603
            value = int(s[:-1])
1580
 
            if suffix == u"d":
 
1604
            if suffix == "d":
1581
1605
                delta = datetime.timedelta(value)
1582
 
            elif suffix == u"s":
 
1606
            elif suffix == "s":
1583
1607
                delta = datetime.timedelta(0, value)
1584
 
            elif suffix == u"m":
 
1608
            elif suffix == "m":
1585
1609
                delta = datetime.timedelta(0, 0, 0, 0, value)
1586
 
            elif suffix == u"h":
 
1610
            elif suffix == "h":
1587
1611
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
1588
 
            elif suffix == u"w":
 
1612
            elif suffix == "w":
1589
1613
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1590
1614
            else:
1591
 
                raise ValueError(u"Unknown suffix %r" % suffix)
 
1615
                raise ValueError("Unknown suffix %r" % suffix)
1592
1616
        except (ValueError, IndexError), e:
1593
 
            raise ValueError(e.message)
 
1617
            raise ValueError(*(e.args))
1594
1618
        timevalue += delta
1595
1619
    return timevalue
1596
1620
 
1602
1626
    global if_nametoindex
1603
1627
    try:
1604
1628
        if_nametoindex = (ctypes.cdll.LoadLibrary
1605
 
                          (ctypes.util.find_library(u"c"))
 
1629
                          (ctypes.util.find_library("c"))
1606
1630
                          .if_nametoindex)
1607
1631
    except (OSError, AttributeError):
1608
 
        logger.warning(u"Doing if_nametoindex the hard way")
 
1632
        logger.warning("Doing if_nametoindex the hard way")
1609
1633
        def if_nametoindex(interface):
1610
1634
            "Get an interface index the hard way, i.e. using fcntl()"
1611
1635
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1612
1636
            with contextlib.closing(socket.socket()) as s:
1613
1637
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1614
 
                                    struct.pack(str(u"16s16x"),
 
1638
                                    struct.pack(str("16s16x"),
1615
1639
                                                interface))
1616
 
            interface_index = struct.unpack(str(u"I"),
 
1640
            interface_index = struct.unpack(str("I"),
1617
1641
                                            ifreq[16:20])[0]
1618
1642
            return interface_index
1619
1643
    return if_nametoindex(interface)
1627
1651
        sys.exit()
1628
1652
    os.setsid()
1629
1653
    if not nochdir:
1630
 
        os.chdir(u"/")
 
1654
        os.chdir("/")
1631
1655
    if os.fork():
1632
1656
        sys.exit()
1633
1657
    if not noclose:
1635
1659
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1636
1660
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1637
1661
            raise OSError(errno.ENODEV,
1638
 
                          u"%s not a character device"
 
1662
                          "%s not a character device"
1639
1663
                          % os.path.devnull)
1640
1664
        os.dup2(null, sys.stdin.fileno())
1641
1665
        os.dup2(null, sys.stdout.fileno())
1649
1673
    ##################################################################
1650
1674
    # Parsing of options, both command line and config file
1651
1675
    
1652
 
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1653
 
    parser.add_option("-i", u"--interface", type=u"string",
1654
 
                      metavar="IF", help=u"Bind to interface IF")
1655
 
    parser.add_option("-a", u"--address", type=u"string",
1656
 
                      help=u"Address to listen for requests on")
1657
 
    parser.add_option("-p", u"--port", type=u"int",
1658
 
                      help=u"Port number to receive requests on")
1659
 
    parser.add_option("--check", action=u"store_true",
1660
 
                      help=u"Run self-test")
1661
 
    parser.add_option("--debug", action=u"store_true",
1662
 
                      help=u"Debug mode; run in foreground and log to"
1663
 
                      u" terminal")
1664
 
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
1665
 
                      help=u"Debug level for stdout output")
1666
 
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1667
 
                      u" priority string (see GnuTLS documentation)")
1668
 
    parser.add_option("--servicename", type=u"string",
1669
 
                      metavar=u"NAME", help=u"Zeroconf service name")
1670
 
    parser.add_option("--configdir", type=u"string",
1671
 
                      default=u"/etc/mandos", metavar=u"DIR",
1672
 
                      help=u"Directory to search for configuration"
1673
 
                      u" files")
1674
 
    parser.add_option("--no-dbus", action=u"store_false",
1675
 
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1676
 
                      u" system bus interface")
1677
 
    parser.add_option("--no-ipv6", action=u"store_false",
1678
 
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1679
 
    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()
1680
1707
    
1681
1708
    if options.check:
1682
1709
        import doctest
1684
1711
        sys.exit()
1685
1712
    
1686
1713
    # Default values for config file for server-global settings
1687
 
    server_defaults = { u"interface": u"",
1688
 
                        u"address": u"",
1689
 
                        u"port": u"",
1690
 
                        u"debug": u"False",
1691
 
                        u"priority":
1692
 
                        u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1693
 
                        u"servicename": u"Mandos",
1694
 
                        u"use_dbus": u"True",
1695
 
                        u"use_ipv6": u"True",
1696
 
                        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": "",
1697
1724
                        }
1698
1725
    
1699
1726
    # Parse config file for server-global settings
1700
1727
    server_config = configparser.SafeConfigParser(server_defaults)
1701
1728
    del server_defaults
1702
1729
    server_config.read(os.path.join(options.configdir,
1703
 
                                    u"mandos.conf"))
 
1730
                                    "mandos.conf"))
1704
1731
    # Convert the SafeConfigParser object to a dict
1705
1732
    server_settings = server_config.defaults()
1706
1733
    # Use the appropriate methods on the non-string config options
1707
 
    for option in (u"debug", u"use_dbus", u"use_ipv6"):
1708
 
        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",
1709
1736
                                                           option)
1710
1737
    if server_settings["port"]:
1711
 
        server_settings["port"] = server_config.getint(u"DEFAULT",
1712
 
                                                       u"port")
 
1738
        server_settings["port"] = server_config.getint("DEFAULT",
 
1739
                                                       "port")
1713
1740
    del server_config
1714
1741
    
1715
1742
    # Override the settings from the config file with command line
1716
1743
    # options, if set.
1717
 
    for option in (u"interface", u"address", u"port", u"debug",
1718
 
                   u"priority", u"servicename", u"configdir",
1719
 
                   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"):
1720
1747
        value = getattr(options, option)
1721
1748
        if value is not None:
1722
1749
            server_settings[option] = value
1730
1757
    ##################################################################
1731
1758
    
1732
1759
    # For convenience
1733
 
    debug = server_settings[u"debug"]
1734
 
    debuglevel = server_settings[u"debuglevel"]
1735
 
    use_dbus = server_settings[u"use_dbus"]
1736
 
    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"]
1737
1764
 
1738
 
    if server_settings[u"servicename"] != u"Mandos":
 
1765
    if server_settings["servicename"] != "Mandos":
1739
1766
        syslogger.setFormatter(logging.Formatter
1740
 
                               (u'Mandos (%s) [%%(process)d]:'
1741
 
                                u' %%(levelname)s: %%(message)s'
1742
 
                                % server_settings[u"servicename"]))
 
1767
                               ('Mandos (%s) [%%(process)d]:'
 
1768
                                ' %%(levelname)s: %%(message)s'
 
1769
                                % server_settings["servicename"]))
1743
1770
    
1744
1771
    # Parse config file with clients
1745
 
    client_defaults = { u"timeout": u"1h",
1746
 
                        u"interval": u"5m",
1747
 
                        u"checker": u"fping -q -- %%(host)s",
1748
 
                        u"host": u"",
1749
 
                        u"approval_delay": u"0s",
1750
 
                        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",
1751
1778
                        }
1752
1779
    client_config = configparser.SafeConfigParser(client_defaults)
1753
 
    client_config.read(os.path.join(server_settings[u"configdir"],
1754
 
                                    u"clients.conf"))
 
1780
    client_config.read(os.path.join(server_settings["configdir"],
 
1781
                                    "clients.conf"))
1755
1782
    
1756
1783
    global mandos_dbus_service
1757
1784
    mandos_dbus_service = None
1758
1785
    
1759
 
    tcp_server = MandosServer((server_settings[u"address"],
1760
 
                               server_settings[u"port"]),
 
1786
    tcp_server = MandosServer((server_settings["address"],
 
1787
                               server_settings["port"]),
1761
1788
                              ClientHandler,
1762
 
                              interface=(server_settings[u"interface"]
 
1789
                              interface=(server_settings["interface"]
1763
1790
                                         or None),
1764
1791
                              use_ipv6=use_ipv6,
1765
1792
                              gnutls_priority=
1766
 
                              server_settings[u"priority"],
 
1793
                              server_settings["priority"],
1767
1794
                              use_dbus=use_dbus)
1768
1795
    if not debug:
1769
 
        pidfilename = u"/var/run/mandos.pid"
 
1796
        pidfilename = "/var/run/mandos.pid"
1770
1797
        try:
1771
 
            pidfile = open(pidfilename, u"w")
 
1798
            pidfile = open(pidfilename, "w")
1772
1799
        except IOError:
1773
 
            logger.error(u"Could not open file %r", pidfilename)
 
1800
            logger.error("Could not open file %r", pidfilename)
1774
1801
    
1775
1802
    try:
1776
 
        uid = pwd.getpwnam(u"_mandos").pw_uid
1777
 
        gid = pwd.getpwnam(u"_mandos").pw_gid
 
1803
        uid = pwd.getpwnam("_mandos").pw_uid
 
1804
        gid = pwd.getpwnam("_mandos").pw_gid
1778
1805
    except KeyError:
1779
1806
        try:
1780
 
            uid = pwd.getpwnam(u"mandos").pw_uid
1781
 
            gid = pwd.getpwnam(u"mandos").pw_gid
 
1807
            uid = pwd.getpwnam("mandos").pw_uid
 
1808
            gid = pwd.getpwnam("mandos").pw_gid
1782
1809
        except KeyError:
1783
1810
            try:
1784
 
                uid = pwd.getpwnam(u"nobody").pw_uid
1785
 
                gid = pwd.getpwnam(u"nobody").pw_gid
 
1811
                uid = pwd.getpwnam("nobody").pw_uid
 
1812
                gid = pwd.getpwnam("nobody").pw_gid
1786
1813
            except KeyError:
1787
1814
                uid = 65534
1788
1815
                gid = 65534
1810
1837
        
1811
1838
        @gnutls.library.types.gnutls_log_func
1812
1839
        def debug_gnutls(level, string):
1813
 
            logger.debug(u"GnuTLS: %s", string[:-1])
 
1840
            logger.debug("GnuTLS: %s", string[:-1])
1814
1841
        
1815
1842
        (gnutls.library.functions
1816
1843
         .gnutls_global_set_log_function(debug_gnutls))
1824
1851
        # No console logging
1825
1852
        logger.removeHandler(console)
1826
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()
1827
1858
    
1828
1859
    global main_loop
1829
1860
    # From the Avahi example code
1833
1864
    # End of Avahi example code
1834
1865
    if use_dbus:
1835
1866
        try:
1836
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
 
1867
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1837
1868
                                            bus, do_not_queue=True)
1838
1869
        except dbus.exceptions.NameExistsException, e:
1839
 
            logger.error(unicode(e) + u", disabling D-Bus")
 
1870
            logger.error(unicode(e) + ", disabling D-Bus")
1840
1871
            use_dbus = False
1841
 
            server_settings[u"use_dbus"] = False
 
1872
            server_settings["use_dbus"] = False
1842
1873
            tcp_server.use_dbus = False
1843
1874
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1844
 
    service = AvahiService(name = server_settings[u"servicename"],
1845
 
                           servicetype = u"_mandos._tcp",
 
1875
    service = AvahiService(name = server_settings["servicename"],
 
1876
                           servicetype = "_mandos._tcp",
1846
1877
                           protocol = protocol, bus = bus)
1847
1878
    if server_settings["interface"]:
1848
1879
        service.interface = (if_nametoindex
1849
 
                             (str(server_settings[u"interface"])))
1850
 
 
1851
 
    if not debug:
1852
 
        # Close all input and output, do double fork, etc.
1853
 
        daemon()
1854
 
        
 
1880
                             (str(server_settings["interface"])))
 
1881
    
1855
1882
    global multiprocessing_manager
1856
1883
    multiprocessing_manager = multiprocessing.Manager()
1857
1884
    
1876
1903
                        client_config, section)))
1877
1904
            for section in client_config.sections()))
1878
1905
    if not tcp_server.clients:
1879
 
        logger.warning(u"No clients defined")
 
1906
        logger.warning("No clients defined")
1880
1907
        
1881
1908
    if not debug:
1882
1909
        try:
1883
1910
            with pidfile:
1884
1911
                pid = os.getpid()
1885
 
                pidfile.write(str(pid) + "\n")
 
1912
                pidfile.write(str(pid) + "\n".encode("utf-8"))
1886
1913
            del pidfile
1887
1914
        except IOError:
1888
 
            logger.error(u"Could not write to file %r with PID %d",
 
1915
            logger.error("Could not write to file %r with PID %d",
1889
1916
                         pidfilename, pid)
1890
1917
        except NameError:
1891
1918
            # "pidfile" was never created
1901
1928
        class MandosDBusService(dbus.service.Object):
1902
1929
            """A D-Bus proxy object"""
1903
1930
            def __init__(self):
1904
 
                dbus.service.Object.__init__(self, bus, u"/")
1905
 
            _interface = u"se.bsnet.fukt.Mandos"
 
1931
                dbus.service.Object.__init__(self, bus, "/")
 
1932
            _interface = "se.bsnet.fukt.Mandos"
1906
1933
            
1907
 
            @dbus.service.signal(_interface, signature=u"o")
 
1934
            @dbus.service.signal(_interface, signature="o")
1908
1935
            def ClientAdded(self, objpath):
1909
1936
                "D-Bus signal"
1910
1937
                pass
1911
1938
            
1912
 
            @dbus.service.signal(_interface, signature=u"ss")
 
1939
            @dbus.service.signal(_interface, signature="ss")
1913
1940
            def ClientNotFound(self, fingerprint, address):
1914
1941
                "D-Bus signal"
1915
1942
                pass
1916
1943
            
1917
 
            @dbus.service.signal(_interface, signature=u"os")
 
1944
            @dbus.service.signal(_interface, signature="os")
1918
1945
            def ClientRemoved(self, objpath, name):
1919
1946
                "D-Bus signal"
1920
1947
                pass
1921
1948
            
1922
 
            @dbus.service.method(_interface, out_signature=u"ao")
 
1949
            @dbus.service.method(_interface, out_signature="ao")
1923
1950
            def GetAllClients(self):
1924
1951
                "D-Bus method"
1925
1952
                return dbus.Array(c.dbus_object_path
1926
1953
                                  for c in tcp_server.clients)
1927
1954
            
1928
1955
            @dbus.service.method(_interface,
1929
 
                                 out_signature=u"a{oa{sv}}")
 
1956
                                 out_signature="a{oa{sv}}")
1930
1957
            def GetAllClientsWithProperties(self):
1931
1958
                "D-Bus method"
1932
1959
                return dbus.Dictionary(
1933
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1960
                    ((c.dbus_object_path, c.GetAll(""))
1934
1961
                     for c in tcp_server.clients),
1935
 
                    signature=u"oa{sv}")
 
1962
                    signature="oa{sv}")
1936
1963
            
1937
 
            @dbus.service.method(_interface, in_signature=u"o")
 
1964
            @dbus.service.method(_interface, in_signature="o")
1938
1965
            def RemoveClient(self, object_path):
1939
1966
                "D-Bus method"
1940
1967
                for c in tcp_server.clients:
1982
2009
    # Find out what port we got
1983
2010
    service.port = tcp_server.socket.getsockname()[1]
1984
2011
    if use_ipv6:
1985
 
        logger.info(u"Now listening on address %r, port %d,"
 
2012
        logger.info("Now listening on address %r, port %d,"
1986
2013
                    " flowinfo %d, scope_id %d"
1987
2014
                    % tcp_server.socket.getsockname())
1988
2015
    else:                       # IPv4
1989
 
        logger.info(u"Now listening on address %r, port %d"
 
2016
        logger.info("Now listening on address %r, port %d"
1990
2017
                    % tcp_server.socket.getsockname())
1991
2018
    
1992
2019
    #service.interface = tcp_server.socket.getsockname()[3]
1996
2023
        try:
1997
2024
            service.activate()
1998
2025
        except dbus.exceptions.DBusException, error:
1999
 
            logger.critical(u"DBusException: %s", error)
 
2026
            logger.critical("DBusException: %s", error)
2000
2027
            cleanup()
2001
2028
            sys.exit(1)
2002
2029
        # End of Avahi example code
2006
2033
                             (tcp_server.handle_request
2007
2034
                              (*args[2:], **kwargs) or True))
2008
2035
        
2009
 
        logger.debug(u"Starting main loop")
 
2036
        logger.debug("Starting main loop")
2010
2037
        main_loop.run()
2011
2038
    except AvahiError, error:
2012
 
        logger.critical(u"AvahiError: %s", error)
 
2039
        logger.critical("AvahiError: %s", error)
2013
2040
        cleanup()
2014
2041
        sys.exit(1)
2015
2042
    except KeyboardInterrupt:
2016
2043
        if debug:
2017
 
            print >> sys.stderr
2018
 
        logger.debug(u"Server received KeyboardInterrupt")
2019
 
    logger.debug(u"Server exiting")
 
2044
            print("", file=sys.stderr)
 
2045
        logger.debug("Server received KeyboardInterrupt")
 
2046
    logger.debug("Server exiting")
2020
2047
    # Must run before the D-Bus bus name gets deregistered
2021
2048
    cleanup()
2022
2049