/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2009-09-17 11:47:22 UTC
  • mfrom: (237.2.138 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20090917114722-azcwe7sdowxc95ba
Merge from trunk.  Lots of bug fixes, including Debian bug #546928.

Show diffs side-by-side

added added

removed removed

Lines of Context:
55
55
import logging
56
56
import logging.handlers
57
57
import pwd
58
 
import contextlib
 
58
from contextlib import closing
59
59
import struct
60
60
import fcntl
61
61
import functools
62
 
import cPickle as pickle
63
 
import multiprocessing
64
62
 
65
63
import dbus
66
64
import dbus.service
69
67
from dbus.mainloop.glib import DBusGMainLoop
70
68
import ctypes
71
69
import ctypes.util
72
 
import xml.dom.minidom
73
 
import inspect
74
70
 
75
71
try:
76
72
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
81
77
        SO_BINDTODEVICE = None
82
78
 
83
79
 
84
 
version = "1.0.14"
 
80
version = "1.0.11"
85
81
 
86
 
#logger = logging.getLogger(u'mandos')
87
82
logger = logging.Logger(u'mandos')
88
83
syslogger = (logging.handlers.SysLogHandler
89
84
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
157
152
                            u" after %i retries, exiting.",
158
153
                            self.rename_count)
159
154
            raise AvahiServiceError(u"Too many renames")
160
 
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
 
155
        self.name = self.server.GetAlternativeServiceName(self.name)
161
156
        logger.info(u"Changing Zeroconf service name to %r ...",
162
 
                    self.name)
 
157
                    unicode(self.name))
163
158
        syslogger.setFormatter(logging.Formatter
164
159
                               (u'Mandos (%s) [%%(process)d]:'
165
160
                                u' %%(levelname)s: %%(message)s'
166
161
                                % self.name))
167
162
        self.remove()
168
 
        try:
169
 
            self.add()
170
 
        except dbus.exceptions.DBusException, error:
171
 
            logger.critical(u"DBusException: %s", error)
172
 
            self.cleanup()
173
 
            os._exit(1)
 
163
        self.add()
174
164
        self.rename_count += 1
175
165
    def remove(self):
176
166
        """Derived from the Avahi example code"""
184
174
                                    self.server.EntryGroupNew()),
185
175
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
186
176
            self.group.connect_to_signal('StateChanged',
187
 
                                         self
188
 
                                         .entry_group_state_changed)
 
177
                                         self.entry_group_state_changed)
189
178
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
190
179
                     self.name, self.type)
191
180
        self.group.AddService(
199
188
        self.group.Commit()
200
189
    def entry_group_state_changed(self, state, error):
201
190
        """Derived from the Avahi example code"""
202
 
        logger.debug(u"Avahi entry group state change: %i", state)
 
191
        logger.debug(u"Avahi state change: %i", state)
203
192
        
204
193
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
205
194
            logger.debug(u"Zeroconf service established.")
218
207
            self.group = None
219
208
    def server_state_changed(self, state):
220
209
        """Derived from the Avahi example code"""
221
 
        logger.debug(u"Avahi server state change: %i", state)
222
210
        if state == avahi.SERVER_COLLISION:
223
211
            logger.error(u"Zeroconf server name collision")
224
212
            self.remove()
240
228
    """A representation of a client host served by this server.
241
229
    
242
230
    Attributes:
243
 
    _approved:   bool(); 'None' if not yet approved/disapproved
244
 
    approval_delay: datetime.timedelta(); Time to wait for approval
245
 
    approval_duration: datetime.timedelta(); Duration of one approval
 
231
    name:       string; from the config file, used in log messages and
 
232
                        D-Bus identifiers
 
233
    fingerprint: string (40 or 32 hexadecimal digits); used to
 
234
                 uniquely identify the client
 
235
    secret:     bytestring; sent verbatim (over TLS) to client
 
236
    host:       string; available for use by the checker command
 
237
    created:    datetime.datetime(); (UTC) object creation
 
238
    last_enabled: datetime.datetime(); (UTC)
 
239
    enabled:    bool()
 
240
    last_checked_ok: datetime.datetime(); (UTC) or None
 
241
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
242
                                      until this client is invalid
 
243
    interval:   datetime.timedelta(); How often to start a new checker
 
244
    disable_hook:  If set, called by disable() as disable_hook(self)
246
245
    checker:    subprocess.Popen(); a running checker process used
247
246
                                    to see if the client lives.
248
247
                                    'None' if no process is running.
 
248
    checker_initiator_tag: a gobject event source tag, or None
 
249
    disable_initiator_tag:    - '' -
249
250
    checker_callback_tag:  - '' -
250
 
    checker_command: string; External command which is run to check
251
 
                     if client lives.  %() expansions are done at
 
251
    checker_command: string; External command which is run to check if
 
252
                     client lives.  %() expansions are done at
252
253
                     runtime with vars(self) as dict, so that for
253
254
                     instance %(name)s can be used in the command.
254
 
    checker_initiator_tag: a gobject event source tag, or None
255
 
    created:    datetime.datetime(); (UTC) object creation
256
255
    current_checker_command: string; current running checker_command
257
 
    disable_hook:  If set, called by disable() as disable_hook(self)
258
 
    disable_initiator_tag: - '' -
259
 
    enabled:    bool()
260
 
    fingerprint: string (40 or 32 hexadecimal digits); used to
261
 
                 uniquely identify the client
262
 
    host:       string; available for use by the checker command
263
 
    interval:   datetime.timedelta(); How often to start a new checker
264
 
    last_checked_ok: datetime.datetime(); (UTC) or None
265
 
    last_enabled: datetime.datetime(); (UTC)
266
 
    name:       string; from the config file, used in log messages and
267
 
                        D-Bus identifiers
268
 
    secret:     bytestring; sent verbatim (over TLS) to client
269
 
    timeout:    datetime.timedelta(); How long from last_checked_ok
270
 
                                      until this client is disabled
271
 
    runtime_expansions: Allowed attributes for runtime expansion.
272
256
    """
273
257
    
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")
278
 
    
279
258
    @staticmethod
280
 
    def _timedelta_to_milliseconds(td):
281
 
        "Convert a datetime.timedelta() to milliseconds"
282
 
        return ((td.days * 24 * 60 * 60 * 1000)
283
 
                + (td.seconds * 1000)
284
 
                + (td.microseconds // 1000))
 
259
    def _datetime_to_milliseconds(dt):
 
260
        "Convert a datetime.datetime() to milliseconds"
 
261
        return ((dt.days * 24 * 60 * 60 * 1000)
 
262
                + (dt.seconds * 1000)
 
263
                + (dt.microseconds // 1000))
285
264
    
286
265
    def timeout_milliseconds(self):
287
266
        "Return the 'timeout' attribute in milliseconds"
288
 
        return self._timedelta_to_milliseconds(self.timeout)
 
267
        return self._datetime_to_milliseconds(self.timeout)
289
268
    
290
269
    def interval_milliseconds(self):
291
270
        "Return the 'interval' attribute in milliseconds"
292
 
        return self._timedelta_to_milliseconds(self.interval)
293
 
 
294
 
    def approval_delay_milliseconds(self):
295
 
        return self._timedelta_to_milliseconds(self.approval_delay)
 
271
        return self._datetime_to_milliseconds(self.interval)
296
272
    
297
273
    def __init__(self, name = None, disable_hook=None, config=None):
298
274
        """Note: the 'checker' key in 'config' sets the
311
287
        if u"secret" in config:
312
288
            self.secret = config[u"secret"].decode(u"base64")
313
289
        elif u"secfile" in config:
314
 
            with open(os.path.expanduser(os.path.expandvars
315
 
                                         (config[u"secfile"])),
316
 
                      "rb") as secfile:
 
290
            with closing(open(os.path.expanduser
 
291
                              (os.path.expandvars
 
292
                               (config[u"secfile"])))) as secfile:
317
293
                self.secret = secfile.read()
318
294
        else:
319
295
            raise TypeError(u"No secret or secfile for client %s"
333
309
        self.checker_command = config[u"checker"]
334
310
        self.current_checker_command = None
335
311
        self.last_connect = None
336
 
        self._approved = None
337
 
        self.approved_by_default = config.get(u"approved_by_default",
338
 
                                              True)
339
 
        self.approvals_pending = 0
340
 
        self.approval_delay = string_to_delta(
341
 
            config[u"approval_delay"])
342
 
        self.approval_duration = string_to_delta(
343
 
            config[u"approval_duration"])
344
 
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
345
312
    
346
 
    def send_changedstate(self):
347
 
        self.changedstate.acquire()
348
 
        self.changedstate.notify_all()
349
 
        self.changedstate.release()
350
 
        
351
313
    def enable(self):
352
314
        """Start this client's checker and timeout hooks"""
353
315
        if getattr(self, u"enabled", False):
354
316
            # Already enabled
355
317
            return
356
 
        self.send_changedstate()
357
318
        self.last_enabled = datetime.datetime.utcnow()
358
319
        # Schedule a new checker to be started an 'interval' from now,
359
320
        # and every interval from then on.
360
321
        self.checker_initiator_tag = (gobject.timeout_add
361
322
                                      (self.interval_milliseconds(),
362
323
                                       self.start_checker))
 
324
        # Also start a new checker *right now*.
 
325
        self.start_checker()
363
326
        # Schedule a disable() when 'timeout' has passed
364
327
        self.disable_initiator_tag = (gobject.timeout_add
365
328
                                   (self.timeout_milliseconds(),
366
329
                                    self.disable))
367
330
        self.enabled = True
368
 
        # Also start a new checker *right now*.
369
 
        self.start_checker()
370
331
    
371
 
    def disable(self, quiet=True):
 
332
    def disable(self):
372
333
        """Disable this client."""
373
334
        if not getattr(self, "enabled", False):
374
335
            return False
375
 
        if not quiet:
376
 
            self.send_changedstate()
377
 
        if not quiet:
378
 
            logger.info(u"Disabling client %s", self.name)
 
336
        logger.info(u"Disabling client %s", self.name)
379
337
        if getattr(self, u"disable_initiator_tag", False):
380
338
            gobject.source_remove(self.disable_initiator_tag)
381
339
            self.disable_initiator_tag = None
433
391
        # client would inevitably timeout, since no checker would get
434
392
        # a chance to run to completion.  If we instead leave running
435
393
        # checkers alone, the checker would have to take more time
436
 
        # than 'timeout' for the client to be disabled, which is as it
437
 
        # should be.
 
394
        # than 'timeout' for the client to be declared invalid, which
 
395
        # is as it should be.
438
396
        
439
397
        # If a checker exists, make sure it is not a zombie
440
 
        try:
 
398
        if self.checker is not None:
441
399
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
442
 
        except (AttributeError, OSError), error:
443
 
            if (isinstance(error, OSError)
444
 
                and error.errno != errno.ECHILD):
445
 
                raise error
446
 
        else:
447
400
            if pid:
448
401
                logger.warning(u"Checker was a zombie")
449
402
                gobject.source_remove(self.checker_callback_tag)
456
409
                command = self.checker_command % self.host
457
410
            except TypeError:
458
411
                # Escape attributes for the shell
459
 
                escaped_attrs = dict(
460
 
                    (attr,
461
 
                     re.escape(unicode(str(getattr(self, attr, u"")),
462
 
                                       errors=
463
 
                                       u'replace')))
464
 
                    for attr in
465
 
                    self.runtime_expansions)
466
 
 
 
412
                escaped_attrs = dict((key,
 
413
                                      re.escape(unicode(str(val),
 
414
                                                        errors=
 
415
                                                        u'replace')))
 
416
                                     for key, val in
 
417
                                     vars(self).iteritems())
467
418
                try:
468
419
                    command = self.checker_command % escaped_attrs
469
420
                except TypeError, error:
507
458
        logger.debug(u"Stopping checker for %(name)s", vars(self))
508
459
        try:
509
460
            os.kill(self.checker.pid, signal.SIGTERM)
510
 
            #time.sleep(0.5)
 
461
            #os.sleep(0.5)
511
462
            #if self.checker.poll() is None:
512
463
            #    os.kill(self.checker.pid, signal.SIGKILL)
513
464
        except OSError, error:
514
465
            if error.errno != errno.ESRCH: # No such process
515
466
                raise
516
467
        self.checker = None
517
 
 
518
 
def dbus_service_property(dbus_interface, signature=u"v",
519
 
                          access=u"readwrite", byte_arrays=False):
520
 
    """Decorators for marking methods of a DBusObjectWithProperties to
521
 
    become properties on the D-Bus.
522
 
    
523
 
    The decorated method will be called with no arguments by "Get"
524
 
    and with one argument by "Set".
525
 
    
526
 
    The parameters, where they are supported, are the same as
527
 
    dbus.service.method, except there is only "signature", since the
528
 
    type from Get() and the type sent to Set() is the same.
529
 
    """
530
 
    # Encoding deeply encoded byte arrays is not supported yet by the
531
 
    # "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)
535
 
    def decorator(func):
536
 
        func._dbus_is_property = True
537
 
        func._dbus_interface = dbus_interface
538
 
        func._dbus_signature = signature
539
 
        func._dbus_access = access
540
 
        func._dbus_name = func.__name__
541
 
        if func._dbus_name.endswith(u"_dbus_property"):
542
 
            func._dbus_name = func._dbus_name[:-14]
543
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
544
 
        return func
545
 
    return decorator
546
 
 
547
 
 
548
 
class DBusPropertyException(dbus.exceptions.DBusException):
549
 
    """A base class for D-Bus property-related exceptions
550
 
    """
551
 
    def __unicode__(self):
552
 
        return unicode(str(self))
553
 
 
554
 
 
555
 
class DBusPropertyAccessException(DBusPropertyException):
556
 
    """A property's access permissions disallows an operation.
557
 
    """
558
 
    pass
559
 
 
560
 
 
561
 
class DBusPropertyNotFound(DBusPropertyException):
562
 
    """An attempt was made to access a non-existing property.
563
 
    """
564
 
    pass
565
 
 
566
 
 
567
 
class DBusObjectWithProperties(dbus.service.Object):
568
 
    """A D-Bus object with properties.
569
 
 
570
 
    Classes inheriting from this can use the dbus_service_property
571
 
    decorator to expose methods as D-Bus properties.  It exposes the
572
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
573
 
    """
574
 
    
575
 
    @staticmethod
576
 
    def _is_dbus_property(obj):
577
 
        return getattr(obj, u"_dbus_is_property", False)
578
 
    
579
 
    def _get_all_dbus_properties(self):
580
 
        """Returns a generator of (name, attribute) pairs
581
 
        """
582
 
        return ((prop._dbus_name, prop)
583
 
                for name, prop in
584
 
                inspect.getmembers(self, self._is_dbus_property))
585
 
    
586
 
    def _get_dbus_property(self, interface_name, property_name):
587
 
        """Returns a bound method if one exists which is a D-Bus
588
 
        property with the specified name and interface.
589
 
        """
590
 
        for name in (property_name,
591
 
                     property_name + u"_dbus_property"):
592
 
            prop = getattr(self, name, None)
593
 
            if (prop is None
594
 
                or not self._is_dbus_property(prop)
595
 
                or prop._dbus_name != property_name
596
 
                or (interface_name and prop._dbus_interface
597
 
                    and interface_name != prop._dbus_interface)):
598
 
                continue
599
 
            return prop
600
 
        # No such property
601
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
602
 
                                   + interface_name + u"."
603
 
                                   + property_name)
604
 
    
605
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
606
 
                         out_signature=u"v")
607
 
    def Get(self, interface_name, property_name):
608
 
        """Standard D-Bus property Get() method, see D-Bus standard.
609
 
        """
610
 
        prop = self._get_dbus_property(interface_name, property_name)
611
 
        if prop._dbus_access == u"write":
612
 
            raise DBusPropertyAccessException(property_name)
613
 
        value = prop()
614
 
        if not hasattr(value, u"variant_level"):
615
 
            return value
616
 
        return type(value)(value, variant_level=value.variant_level+1)
617
 
    
618
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
619
 
    def Set(self, interface_name, property_name, value):
620
 
        """Standard D-Bus property Set() method, see D-Bus standard.
621
 
        """
622
 
        prop = self._get_dbus_property(interface_name, property_name)
623
 
        if prop._dbus_access == u"read":
624
 
            raise DBusPropertyAccessException(property_name)
625
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
626
 
            # The byte_arrays option is not supported yet on
627
 
            # signatures other than "ay".
628
 
            if prop._dbus_signature != u"ay":
629
 
                raise ValueError
630
 
            value = dbus.ByteArray(''.join(unichr(byte)
631
 
                                           for byte in value))
632
 
        prop(value)
633
 
    
634
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
635
 
                         out_signature=u"a{sv}")
636
 
    def GetAll(self, interface_name):
637
 
        """Standard D-Bus property GetAll() method, see D-Bus
638
 
        standard.
639
 
 
640
 
        Note: Will not include properties with access="write".
641
 
        """
642
 
        all = {}
643
 
        for name, prop in self._get_all_dbus_properties():
644
 
            if (interface_name
645
 
                and interface_name != prop._dbus_interface):
646
 
                # Interface non-empty but did not match
647
 
                continue
648
 
            # Ignore write-only properties
649
 
            if prop._dbus_access == u"write":
650
 
                continue
651
 
            value = prop()
652
 
            if not hasattr(value, u"variant_level"):
653
 
                all[name] = value
654
 
                continue
655
 
            all[name] = type(value)(value, variant_level=
656
 
                                    value.variant_level+1)
657
 
        return dbus.Dictionary(all, signature=u"sv")
658
 
    
659
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
660
 
                         out_signature=u"s",
661
 
                         path_keyword='object_path',
662
 
                         connection_keyword='connection')
663
 
    def Introspect(self, object_path, connection):
664
 
        """Standard D-Bus method, overloaded to insert property tags.
665
 
        """
666
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
667
 
                                                   connection)
668
 
        try:
669
 
            document = xml.dom.minidom.parseString(xmlstring)
670
 
            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)
675
 
                return e
676
 
            for if_tag in document.getElementsByTagName(u"interface"):
677
 
                for tag in (make_tag(document, name, prop)
678
 
                            for name, prop
679
 
                            in self._get_all_dbus_properties()
680
 
                            if prop._dbus_interface
681
 
                            == if_tag.getAttribute(u"name")):
682
 
                    if_tag.appendChild(tag)
683
 
                # Add the names to the return values for the
684
 
                # "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")
699
 
            document.unlink()
700
 
        except (AttributeError, xml.dom.DOMException,
701
 
                xml.parsers.expat.ExpatError), error:
702
 
            logger.error(u"Failed to override Introspection method",
703
 
                         error)
704
 
        return xmlstring
705
 
 
706
 
 
707
 
class ClientDBus(Client, DBusObjectWithProperties):
 
468
    
 
469
    def still_valid(self):
 
470
        """Has the timeout not yet passed for this client?"""
 
471
        if not getattr(self, u"enabled", False):
 
472
            return False
 
473
        now = datetime.datetime.utcnow()
 
474
        if self.last_checked_ok is None:
 
475
            return now < (self.created + self.timeout)
 
476
        else:
 
477
            return now < (self.last_checked_ok + self.timeout)
 
478
 
 
479
 
 
480
class ClientDBus(Client, dbus.service.Object):
708
481
    """A Client class using D-Bus
709
482
    
710
483
    Attributes:
711
484
    dbus_object_path: dbus.ObjectPath
712
485
    bus: dbus.SystemBus()
713
486
    """
714
 
    
715
 
    runtime_expansions = (Client.runtime_expansions
716
 
                          + (u"dbus_object_path",))
717
 
    
718
487
    # dbus.service.Object doesn't use super(), so we can't either.
719
488
    
720
489
    def __init__(self, bus = None, *args, **kwargs):
721
 
        self._approvals_pending = 0
722
490
        self.bus = bus
723
491
        Client.__init__(self, *args, **kwargs)
724
492
        # Only now, when this client is initialized, can it show up on
726
494
        self.dbus_object_path = (dbus.ObjectPath
727
495
                                 (u"/clients/"
728
496
                                  + self.name.replace(u".", u"_")))
729
 
        DBusObjectWithProperties.__init__(self, self.bus,
730
 
                                          self.dbus_object_path)
731
 
        
732
 
    def _get_approvals_pending(self):
733
 
        return self._approvals_pending
734
 
    def _set_approvals_pending(self, value):
735
 
        old_value = self._approvals_pending
736
 
        self._approvals_pending = value
737
 
        bval = bool(value)
738
 
        if (hasattr(self, "dbus_object_path")
739
 
            and bval is not bool(old_value)):
740
 
            dbus_bool = dbus.Boolean(bval, variant_level=1)
741
 
            self.PropertyChanged(dbus.String(u"ApprovalPending"),
742
 
                                 dbus_bool)
743
 
 
744
 
    approvals_pending = property(_get_approvals_pending,
745
 
                                 _set_approvals_pending)
746
 
    del _get_approvals_pending, _set_approvals_pending
 
497
        dbus.service.Object.__init__(self, self.bus,
 
498
                                     self.dbus_object_path)
747
499
    
748
500
    @staticmethod
749
501
    def _datetime_to_dbus(dt, variant_level=0):
756
508
        r = Client.enable(self)
757
509
        if oldstate != self.enabled:
758
510
            # Emit D-Bus signals
759
 
            self.PropertyChanged(dbus.String(u"Enabled"),
 
511
            self.PropertyChanged(dbus.String(u"enabled"),
760
512
                                 dbus.Boolean(True, variant_level=1))
761
513
            self.PropertyChanged(
762
 
                dbus.String(u"LastEnabled"),
 
514
                dbus.String(u"last_enabled"),
763
515
                self._datetime_to_dbus(self.last_enabled,
764
516
                                       variant_level=1))
765
517
        return r
766
518
    
767
 
    def disable(self, quiet = False):
 
519
    def disable(self, signal = True):
768
520
        oldstate = getattr(self, u"enabled", False)
769
 
        r = Client.disable(self, quiet=quiet)
770
 
        if not quiet and oldstate != self.enabled:
 
521
        r = Client.disable(self)
 
522
        if signal and oldstate != self.enabled:
771
523
            # Emit D-Bus signal
772
 
            self.PropertyChanged(dbus.String(u"Enabled"),
 
524
            self.PropertyChanged(dbus.String(u"enabled"),
773
525
                                 dbus.Boolean(False, variant_level=1))
774
526
        return r
775
527
    
778
530
            self.remove_from_connection()
779
531
        except LookupError:
780
532
            pass
781
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
782
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
533
        if hasattr(dbus.service.Object, u"__del__"):
 
534
            dbus.service.Object.__del__(self, *args, **kwargs)
783
535
        Client.__del__(self, *args, **kwargs)
784
536
    
785
537
    def checker_callback(self, pid, condition, command,
787
539
        self.checker_callback_tag = None
788
540
        self.checker = None
789
541
        # Emit D-Bus signal
790
 
        self.PropertyChanged(dbus.String(u"CheckerRunning"),
 
542
        self.PropertyChanged(dbus.String(u"checker_running"),
791
543
                             dbus.Boolean(False, variant_level=1))
792
544
        if os.WIFEXITED(condition):
793
545
            exitstatus = os.WEXITSTATUS(condition)
808
560
        r = Client.checked_ok(self, *args, **kwargs)
809
561
        # Emit D-Bus signal
810
562
        self.PropertyChanged(
811
 
            dbus.String(u"LastCheckedOK"),
 
563
            dbus.String(u"last_checked_ok"),
812
564
            (self._datetime_to_dbus(self.last_checked_ok,
813
565
                                    variant_level=1)))
814
566
        return r
826
578
            # Emit D-Bus signal
827
579
            self.CheckerStarted(self.current_checker_command)
828
580
            self.PropertyChanged(
829
 
                dbus.String(u"CheckerRunning"),
 
581
                dbus.String(u"checker_running"),
830
582
                dbus.Boolean(True, variant_level=1))
831
583
        return r
832
584
    
835
587
        r = Client.stop_checker(self, *args, **kwargs)
836
588
        if (old_checker is not None
837
589
            and getattr(self, u"checker", None) is None):
838
 
            self.PropertyChanged(dbus.String(u"CheckerRunning"),
 
590
            self.PropertyChanged(dbus.String(u"checker_running"),
839
591
                                 dbus.Boolean(False, variant_level=1))
840
592
        return r
841
 
 
842
 
    def _reset_approved(self):
843
 
        self._approved = None
844
 
        return False
845
 
    
846
 
    def approve(self, value=True):
847
 
        self.send_changedstate()
848
 
        self._approved = value
849
 
        gobject.timeout_add(self._timedelta_to_milliseconds
850
 
                            (self.approval_duration),
851
 
                            self._reset_approved)
852
 
    
853
 
    
854
 
    ## D-Bus methods, signals & properties
 
593
    
 
594
    ## D-Bus methods & signals
855
595
    _interface = u"se.bsnet.fukt.Mandos.Client"
856
596
    
857
 
    ## Signals
 
597
    # CheckedOK - method
 
598
    @dbus.service.method(_interface)
 
599
    def CheckedOK(self):
 
600
        return self.checked_ok()
858
601
    
859
602
    # CheckerCompleted - signal
860
603
    @dbus.service.signal(_interface, signature=u"nxs")
868
611
        "D-Bus signal"
869
612
        pass
870
613
    
 
614
    # GetAllProperties - method
 
615
    @dbus.service.method(_interface, out_signature=u"a{sv}")
 
616
    def GetAllProperties(self):
 
617
        "D-Bus method"
 
618
        return dbus.Dictionary({
 
619
                dbus.String(u"name"):
 
620
                    dbus.String(self.name, variant_level=1),
 
621
                dbus.String(u"fingerprint"):
 
622
                    dbus.String(self.fingerprint, variant_level=1),
 
623
                dbus.String(u"host"):
 
624
                    dbus.String(self.host, variant_level=1),
 
625
                dbus.String(u"created"):
 
626
                    self._datetime_to_dbus(self.created,
 
627
                                           variant_level=1),
 
628
                dbus.String(u"last_enabled"):
 
629
                    (self._datetime_to_dbus(self.last_enabled,
 
630
                                            variant_level=1)
 
631
                     if self.last_enabled is not None
 
632
                     else dbus.Boolean(False, variant_level=1)),
 
633
                dbus.String(u"enabled"):
 
634
                    dbus.Boolean(self.enabled, variant_level=1),
 
635
                dbus.String(u"last_checked_ok"):
 
636
                    (self._datetime_to_dbus(self.last_checked_ok,
 
637
                                            variant_level=1)
 
638
                     if self.last_checked_ok is not None
 
639
                     else dbus.Boolean (False, variant_level=1)),
 
640
                dbus.String(u"timeout"):
 
641
                    dbus.UInt64(self.timeout_milliseconds(),
 
642
                                variant_level=1),
 
643
                dbus.String(u"interval"):
 
644
                    dbus.UInt64(self.interval_milliseconds(),
 
645
                                variant_level=1),
 
646
                dbus.String(u"checker"):
 
647
                    dbus.String(self.checker_command,
 
648
                                variant_level=1),
 
649
                dbus.String(u"checker_running"):
 
650
                    dbus.Boolean(self.checker is not None,
 
651
                                 variant_level=1),
 
652
                dbus.String(u"object_path"):
 
653
                    dbus.ObjectPath(self.dbus_object_path,
 
654
                                    variant_level=1)
 
655
                }, signature=u"sv")
 
656
    
 
657
    # IsStillValid - method
 
658
    @dbus.service.method(_interface, out_signature=u"b")
 
659
    def IsStillValid(self):
 
660
        return self.still_valid()
 
661
    
871
662
    # PropertyChanged - signal
872
663
    @dbus.service.signal(_interface, signature=u"sv")
873
664
    def PropertyChanged(self, property, value):
874
665
        "D-Bus signal"
875
666
        pass
876
667
    
877
 
    # GotSecret - signal
 
668
    # ReceivedSecret - signal
878
669
    @dbus.service.signal(_interface)
879
 
    def GotSecret(self):
880
 
        """D-Bus signal
881
 
        Is sent after a successful transfer of secret from the Mandos
882
 
        server to mandos-client
883
 
        """
 
670
    def ReceivedSecret(self):
 
671
        "D-Bus signal"
884
672
        pass
885
673
    
886
674
    # Rejected - signal
887
 
    @dbus.service.signal(_interface, signature=u"s")
888
 
    def Rejected(self, reason):
889
 
        "D-Bus signal"
890
 
        pass
891
 
    
892
 
    # NeedApproval - signal
893
 
    @dbus.service.signal(_interface, signature=u"tb")
894
 
    def NeedApproval(self, timeout, default):
895
 
        "D-Bus signal"
896
 
        pass
897
 
    
898
 
    ## Methods
899
 
 
900
 
    # Approve - method
901
 
    @dbus.service.method(_interface, in_signature=u"b")
902
 
    def Approve(self, value):
903
 
        self.approve(value)
904
 
 
905
 
    # CheckedOK - method
906
 
    @dbus.service.method(_interface)
907
 
    def CheckedOK(self):
908
 
        return self.checked_ok()
 
675
    @dbus.service.signal(_interface)
 
676
    def Rejected(self):
 
677
        "D-Bus signal"
 
678
        pass
 
679
    
 
680
    # SetChecker - method
 
681
    @dbus.service.method(_interface, in_signature=u"s")
 
682
    def SetChecker(self, checker):
 
683
        "D-Bus setter method"
 
684
        self.checker_command = checker
 
685
        # Emit D-Bus signal
 
686
        self.PropertyChanged(dbus.String(u"checker"),
 
687
                             dbus.String(self.checker_command,
 
688
                                         variant_level=1))
 
689
    
 
690
    # SetHost - method
 
691
    @dbus.service.method(_interface, in_signature=u"s")
 
692
    def SetHost(self, host):
 
693
        "D-Bus setter method"
 
694
        self.host = host
 
695
        # Emit D-Bus signal
 
696
        self.PropertyChanged(dbus.String(u"host"),
 
697
                             dbus.String(self.host, variant_level=1))
 
698
    
 
699
    # SetInterval - method
 
700
    @dbus.service.method(_interface, in_signature=u"t")
 
701
    def SetInterval(self, milliseconds):
 
702
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
703
        # Emit D-Bus signal
 
704
        self.PropertyChanged(dbus.String(u"interval"),
 
705
                             (dbus.UInt64(self.interval_milliseconds(),
 
706
                                          variant_level=1)))
 
707
    
 
708
    # SetSecret - method
 
709
    @dbus.service.method(_interface, in_signature=u"ay",
 
710
                         byte_arrays=True)
 
711
    def SetSecret(self, secret):
 
712
        "D-Bus setter method"
 
713
        self.secret = str(secret)
 
714
    
 
715
    # SetTimeout - method
 
716
    @dbus.service.method(_interface, in_signature=u"t")
 
717
    def SetTimeout(self, milliseconds):
 
718
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
719
        # Emit D-Bus signal
 
720
        self.PropertyChanged(dbus.String(u"timeout"),
 
721
                             (dbus.UInt64(self.timeout_milliseconds(),
 
722
                                          variant_level=1)))
909
723
    
910
724
    # Enable - method
911
725
    @dbus.service.method(_interface)
930
744
    def StopChecker(self):
931
745
        self.stop_checker()
932
746
    
933
 
    ## Properties
934
 
    
935
 
    # ApprovalPending - property
936
 
    @dbus_service_property(_interface, signature=u"b", access=u"read")
937
 
    def ApprovalPending_dbus_property(self):
938
 
        return dbus.Boolean(bool(self.approvals_pending))
939
 
    
940
 
    # ApprovedByDefault - property
941
 
    @dbus_service_property(_interface, signature=u"b",
942
 
                           access=u"readwrite")
943
 
    def ApprovedByDefault_dbus_property(self, value=None):
944
 
        if value is None:       # get
945
 
            return dbus.Boolean(self.approved_by_default)
946
 
        self.approved_by_default = bool(value)
947
 
        # Emit D-Bus signal
948
 
        self.PropertyChanged(dbus.String(u"ApprovedByDefault"),
949
 
                             dbus.Boolean(value, variant_level=1))
950
 
    
951
 
    # ApprovalDelay - property
952
 
    @dbus_service_property(_interface, signature=u"t",
953
 
                           access=u"readwrite")
954
 
    def ApprovalDelay_dbus_property(self, value=None):
955
 
        if value is None:       # get
956
 
            return dbus.UInt64(self.approval_delay_milliseconds())
957
 
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
958
 
        # Emit D-Bus signal
959
 
        self.PropertyChanged(dbus.String(u"ApprovalDelay"),
960
 
                             dbus.UInt64(value, variant_level=1))
961
 
    
962
 
    # ApprovalDuration - property
963
 
    @dbus_service_property(_interface, signature=u"t",
964
 
                           access=u"readwrite")
965
 
    def ApprovalDuration_dbus_property(self, value=None):
966
 
        if value is None:       # get
967
 
            return dbus.UInt64(self._timedelta_to_milliseconds(
968
 
                    self.approval_duration))
969
 
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
970
 
        # Emit D-Bus signal
971
 
        self.PropertyChanged(dbus.String(u"ApprovalDuration"),
972
 
                             dbus.UInt64(value, variant_level=1))
973
 
    
974
 
    # Name - property
975
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
976
 
    def Name_dbus_property(self):
977
 
        return dbus.String(self.name)
978
 
    
979
 
    # Fingerprint - property
980
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
981
 
    def Fingerprint_dbus_property(self):
982
 
        return dbus.String(self.fingerprint)
983
 
    
984
 
    # Host - property
985
 
    @dbus_service_property(_interface, signature=u"s",
986
 
                           access=u"readwrite")
987
 
    def Host_dbus_property(self, value=None):
988
 
        if value is None:       # get
989
 
            return dbus.String(self.host)
990
 
        self.host = value
991
 
        # Emit D-Bus signal
992
 
        self.PropertyChanged(dbus.String(u"Host"),
993
 
                             dbus.String(value, variant_level=1))
994
 
    
995
 
    # Created - property
996
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
997
 
    def Created_dbus_property(self):
998
 
        return dbus.String(self._datetime_to_dbus(self.created))
999
 
    
1000
 
    # LastEnabled - property
1001
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
1002
 
    def LastEnabled_dbus_property(self):
1003
 
        if self.last_enabled is None:
1004
 
            return dbus.String(u"")
1005
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
1006
 
    
1007
 
    # Enabled - property
1008
 
    @dbus_service_property(_interface, signature=u"b",
1009
 
                           access=u"readwrite")
1010
 
    def Enabled_dbus_property(self, value=None):
1011
 
        if value is None:       # get
1012
 
            return dbus.Boolean(self.enabled)
1013
 
        if value:
1014
 
            self.enable()
1015
 
        else:
1016
 
            self.disable()
1017
 
    
1018
 
    # LastCheckedOK - property
1019
 
    @dbus_service_property(_interface, signature=u"s",
1020
 
                           access=u"readwrite")
1021
 
    def LastCheckedOK_dbus_property(self, value=None):
1022
 
        if value is not None:
1023
 
            self.checked_ok()
1024
 
            return
1025
 
        if self.last_checked_ok is None:
1026
 
            return dbus.String(u"")
1027
 
        return dbus.String(self._datetime_to_dbus(self
1028
 
                                                  .last_checked_ok))
1029
 
    
1030
 
    # Timeout - property
1031
 
    @dbus_service_property(_interface, signature=u"t",
1032
 
                           access=u"readwrite")
1033
 
    def Timeout_dbus_property(self, value=None):
1034
 
        if value is None:       # get
1035
 
            return dbus.UInt64(self.timeout_milliseconds())
1036
 
        self.timeout = datetime.timedelta(0, 0, 0, value)
1037
 
        # Emit D-Bus signal
1038
 
        self.PropertyChanged(dbus.String(u"Timeout"),
1039
 
                             dbus.UInt64(value, variant_level=1))
1040
 
        if getattr(self, u"disable_initiator_tag", None) is None:
1041
 
            return
1042
 
        # Reschedule timeout
1043
 
        gobject.source_remove(self.disable_initiator_tag)
1044
 
        self.disable_initiator_tag = None
1045
 
        time_to_die = (self.
1046
 
                       _timedelta_to_milliseconds((self
1047
 
                                                   .last_checked_ok
1048
 
                                                   + self.timeout)
1049
 
                                                  - datetime.datetime
1050
 
                                                  .utcnow()))
1051
 
        if time_to_die <= 0:
1052
 
            # The timeout has passed
1053
 
            self.disable()
1054
 
        else:
1055
 
            self.disable_initiator_tag = (gobject.timeout_add
1056
 
                                          (time_to_die, self.disable))
1057
 
    
1058
 
    # Interval - property
1059
 
    @dbus_service_property(_interface, signature=u"t",
1060
 
                           access=u"readwrite")
1061
 
    def Interval_dbus_property(self, value=None):
1062
 
        if value is None:       # get
1063
 
            return dbus.UInt64(self.interval_milliseconds())
1064
 
        self.interval = datetime.timedelta(0, 0, 0, value)
1065
 
        # Emit D-Bus signal
1066
 
        self.PropertyChanged(dbus.String(u"Interval"),
1067
 
                             dbus.UInt64(value, variant_level=1))
1068
 
        if getattr(self, u"checker_initiator_tag", None) is None:
1069
 
            return
1070
 
        # Reschedule checker run
1071
 
        gobject.source_remove(self.checker_initiator_tag)
1072
 
        self.checker_initiator_tag = (gobject.timeout_add
1073
 
                                      (value, self.start_checker))
1074
 
        self.start_checker()    # Start one now, too
1075
 
 
1076
 
    # Checker - property
1077
 
    @dbus_service_property(_interface, signature=u"s",
1078
 
                           access=u"readwrite")
1079
 
    def Checker_dbus_property(self, value=None):
1080
 
        if value is None:       # get
1081
 
            return dbus.String(self.checker_command)
1082
 
        self.checker_command = value
1083
 
        # Emit D-Bus signal
1084
 
        self.PropertyChanged(dbus.String(u"Checker"),
1085
 
                             dbus.String(self.checker_command,
1086
 
                                         variant_level=1))
1087
 
    
1088
 
    # CheckerRunning - property
1089
 
    @dbus_service_property(_interface, signature=u"b",
1090
 
                           access=u"readwrite")
1091
 
    def CheckerRunning_dbus_property(self, value=None):
1092
 
        if value is None:       # get
1093
 
            return dbus.Boolean(self.checker is not None)
1094
 
        if value:
1095
 
            self.start_checker()
1096
 
        else:
1097
 
            self.stop_checker()
1098
 
    
1099
 
    # ObjectPath - property
1100
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
1101
 
    def ObjectPath_dbus_property(self):
1102
 
        return self.dbus_object_path # is already a dbus.ObjectPath
1103
 
    
1104
 
    # Secret = property
1105
 
    @dbus_service_property(_interface, signature=u"ay",
1106
 
                           access=u"write", byte_arrays=True)
1107
 
    def Secret_dbus_property(self, value):
1108
 
        self.secret = str(value)
1109
 
    
1110
747
    del _interface
1111
748
 
1112
749
 
1113
 
class ProxyClient(object):
1114
 
    def __init__(self, child_pipe, fpr, address):
1115
 
        self._pipe = child_pipe
1116
 
        self._pipe.send(('init', fpr, address))
1117
 
        if not self._pipe.recv():
1118
 
            raise KeyError()
1119
 
 
1120
 
    def __getattribute__(self, name):
1121
 
        if(name == '_pipe'):
1122
 
            return super(ProxyClient, self).__getattribute__(name)
1123
 
        self._pipe.send(('getattr', name))
1124
 
        data = self._pipe.recv()
1125
 
        if data[0] == 'data':
1126
 
            return data[1]
1127
 
        if data[0] == 'function':
1128
 
            def func(*args, **kwargs):
1129
 
                self._pipe.send(('funcall', name, args, kwargs))
1130
 
                return self._pipe.recv()[1]
1131
 
            return func
1132
 
 
1133
 
    def __setattr__(self, name, value):
1134
 
        if(name == '_pipe'):
1135
 
            return super(ProxyClient, self).__setattr__(name, value)
1136
 
        self._pipe.send(('setattr', name, value))
1137
 
 
1138
 
 
1139
750
class ClientHandler(socketserver.BaseRequestHandler, object):
1140
751
    """A class to handle client connections.
1141
752
    
1143
754
    Note: This will run in its own forked process."""
1144
755
    
1145
756
    def handle(self):
1146
 
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1147
 
            logger.info(u"TCP connection from: %s",
1148
 
                        unicode(self.client_address))
1149
 
            logger.debug(u"Pipe FD: %d",
1150
 
                         self.server.child_pipe.fileno())
1151
 
 
 
757
        logger.info(u"TCP connection from: %s",
 
758
                    unicode(self.client_address))
 
759
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
 
760
        # Open IPC pipe to parent process
 
761
        with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1152
762
            session = (gnutls.connection
1153
763
                       .ClientSession(self.request,
1154
764
                                      gnutls.connection
1155
765
                                      .X509Credentials()))
1156
 
 
 
766
            
 
767
            line = self.request.makefile().readline()
 
768
            logger.debug(u"Protocol version: %r", line)
 
769
            try:
 
770
                if int(line.strip().split()[0]) > 1:
 
771
                    raise RuntimeError
 
772
            except (ValueError, IndexError, RuntimeError), error:
 
773
                logger.error(u"Unknown protocol version: %s", error)
 
774
                return
 
775
            
1157
776
            # Note: gnutls.connection.X509Credentials is really a
1158
777
            # generic GnuTLS certificate credentials object so long as
1159
778
            # no X.509 keys are added to it.  Therefore, we can use it
1160
779
            # here despite using OpenPGP certificates.
1161
 
 
 
780
            
1162
781
            #priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1163
782
            #                      u"+AES-256-CBC", u"+SHA1",
1164
783
            #                      u"+COMP-NULL", u"+CTYPE-OPENPGP",
1170
789
            (gnutls.library.functions
1171
790
             .gnutls_priority_set_direct(session._c_object,
1172
791
                                         priority, None))
1173
 
 
1174
 
            # Start communication using the Mandos protocol
1175
 
            # Get protocol number
1176
 
            line = self.request.makefile().readline()
1177
 
            logger.debug(u"Protocol version: %r", line)
1178
 
            try:
1179
 
                if int(line.strip().split()[0]) > 1:
1180
 
                    raise RuntimeError
1181
 
            except (ValueError, IndexError, RuntimeError), error:
1182
 
                logger.error(u"Unknown protocol version: %s", error)
1183
 
                return
1184
 
 
1185
 
            # Start GnuTLS connection
 
792
            
1186
793
            try:
1187
794
                session.handshake()
1188
795
            except gnutls.errors.GNUTLSError, error:
1191
798
                # established.  Just abandon the request.
1192
799
                return
1193
800
            logger.debug(u"Handshake succeeded")
1194
 
 
1195
 
            approval_required = False
1196
801
            try:
1197
 
                try:
1198
 
                    fpr = self.fingerprint(self.peer_certificate
1199
 
                                           (session))
1200
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
1201
 
                    logger.warning(u"Bad certificate: %s", error)
1202
 
                    return
1203
 
                logger.debug(u"Fingerprint: %s", fpr)
1204
 
 
1205
 
                try:
1206
 
                    client = ProxyClient(child_pipe, fpr,
1207
 
                                         self.client_address)
1208
 
                except KeyError:
1209
 
                    return
1210
 
                
1211
 
                if client.approval_delay:
1212
 
                    delay = client.approval_delay
1213
 
                    client.approvals_pending += 1
1214
 
                    approval_required = True
1215
 
                
1216
 
                while True:
1217
 
                    if not client.enabled:
1218
 
                        logger.warning(u"Client %s is disabled",
1219
 
                                       client.name)
1220
 
                        if self.server.use_dbus:
1221
 
                            # Emit D-Bus signal
1222
 
                            client.Rejected("Disabled")                    
1223
 
                        return
1224
 
                    
1225
 
                    if client._approved or not client.approval_delay:
1226
 
                        #We are approved or approval is disabled
1227
 
                        break
1228
 
                    elif client._approved is None:
1229
 
                        logger.info(u"Client %s needs approval",
1230
 
                                    client.name)
1231
 
                        if self.server.use_dbus:
1232
 
                            # Emit D-Bus signal
1233
 
                            client.NeedApproval(
1234
 
                                client.approval_delay_milliseconds(),
1235
 
                                client.approved_by_default)
1236
 
                    else:
1237
 
                        logger.warning(u"Client %s was not approved",
1238
 
                                       client.name)
1239
 
                        if self.server.use_dbus:
1240
 
                            # Emit D-Bus signal
1241
 
                            client.Rejected("Denied")
1242
 
                        return
1243
 
                    
1244
 
                    #wait until timeout or approved
1245
 
                    #x = float(client._timedelta_to_milliseconds(delay))
1246
 
                    time = datetime.datetime.now()
1247
 
                    client.changedstate.acquire()
1248
 
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1249
 
                    client.changedstate.release()
1250
 
                    time2 = datetime.datetime.now()
1251
 
                    if (time2 - time) >= delay:
1252
 
                        if not client.approved_by_default:
1253
 
                            logger.warning("Client %s timed out while"
1254
 
                                           " waiting for approval",
1255
 
                                           client.name)
1256
 
                            if self.server.use_dbus:
1257
 
                                # Emit D-Bus signal
1258
 
                                client.Rejected("Approval timed out")
1259
 
                            return
1260
 
                        else:
1261
 
                            break
1262
 
                    else:
1263
 
                        delay -= time2 - time
1264
 
                
1265
 
                sent_size = 0
1266
 
                while sent_size < len(client.secret):
1267
 
                    try:
1268
 
                        sent = session.send(client.secret[sent_size:])
1269
 
                    except (gnutls.errors.GNUTLSError), error:
1270
 
                        logger.warning("gnutls send failed")
1271
 
                        return
1272
 
                    logger.debug(u"Sent: %d, remaining: %d",
1273
 
                                 sent, len(client.secret)
1274
 
                                 - (sent_size + sent))
1275
 
                    sent_size += sent
1276
 
 
1277
 
                logger.info(u"Sending secret to %s", client.name)
1278
 
                # bump the timeout as if seen
1279
 
                client.checked_ok()
1280
 
                if self.server.use_dbus:
1281
 
                    # Emit D-Bus signal
1282
 
                    client.GotSecret()
 
802
                fpr = self.fingerprint(self.peer_certificate(session))
 
803
            except (TypeError, gnutls.errors.GNUTLSError), error:
 
804
                logger.warning(u"Bad certificate: %s", error)
 
805
                session.bye()
 
806
                return
 
807
            logger.debug(u"Fingerprint: %s", fpr)
1283
808
            
1284
 
            finally:
1285
 
                if approval_required:
1286
 
                    client.approvals_pending -= 1
1287
 
                try:
1288
 
                    session.bye()
1289
 
                except (gnutls.errors.GNUTLSError), error:
1290
 
                    logger.warning("GnuTLS bye failed")
 
809
            for c in self.server.clients:
 
810
                if c.fingerprint == fpr:
 
811
                    client = c
 
812
                    break
 
813
            else:
 
814
                ipc.write(u"NOTFOUND %s %s\n"
 
815
                          % (fpr, unicode(self.client_address)))
 
816
                session.bye()
 
817
                return
 
818
            # Have to check if client.still_valid(), since it is
 
819
            # possible that the client timed out while establishing
 
820
            # the GnuTLS session.
 
821
            if not client.still_valid():
 
822
                ipc.write(u"INVALID %s\n" % client.name)
 
823
                session.bye()
 
824
                return
 
825
            ipc.write(u"SENDING %s\n" % client.name)
 
826
            sent_size = 0
 
827
            while sent_size < len(client.secret):
 
828
                sent = session.send(client.secret[sent_size:])
 
829
                logger.debug(u"Sent: %d, remaining: %d",
 
830
                             sent, len(client.secret)
 
831
                             - (sent_size + sent))
 
832
                sent_size += sent
 
833
            session.bye()
1291
834
    
1292
835
    @staticmethod
1293
836
    def peer_certificate(session):
1353
896
        return hex_fpr
1354
897
 
1355
898
 
1356
 
class MultiprocessingMixIn(object):
1357
 
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1358
 
    def sub_process_main(self, request, address):
1359
 
        try:
1360
 
            self.finish_request(request, address)
1361
 
        except:
1362
 
            self.handle_error(request, address)
1363
 
        self.close_request(request)
1364
 
            
1365
 
    def process_request(self, request, address):
1366
 
        """Start a new process to process the request."""
1367
 
        multiprocessing.Process(target = self.sub_process_main,
1368
 
                                args = (request, address)).start()
1369
 
 
1370
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1371
 
    """ adds a pipe to the MixIn """
 
899
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
 
900
    """Like socketserver.ForkingMixIn, but also pass a pipe."""
1372
901
    def process_request(self, request, client_address):
1373
902
        """Overrides and wraps the original process_request().
1374
903
        
1375
904
        This function creates a new pipe in self.pipe
1376
905
        """
1377
 
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1378
 
 
1379
 
        super(MultiprocessingMixInWithPipe,
 
906
        self.pipe = os.pipe()
 
907
        super(ForkingMixInWithPipe,
1380
908
              self).process_request(request, client_address)
1381
 
        self.child_pipe.close()
1382
 
        self.add_pipe(parent_pipe)
1383
 
 
1384
 
    def add_pipe(self, parent_pipe):
 
909
        os.close(self.pipe[1])  # close write end
 
910
        self.add_pipe(self.pipe[0])
 
911
    def add_pipe(self, pipe):
1385
912
        """Dummy function; override as necessary"""
1386
 
        pass
1387
 
 
1388
 
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
 
913
        os.close(pipe)
 
914
 
 
915
 
 
916
class IPv6_TCPServer(ForkingMixInWithPipe,
1389
917
                     socketserver.TCPServer, object):
1390
918
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1391
919
    
1455
983
        clients:        set of Client objects
1456
984
        gnutls_priority GnuTLS priority string
1457
985
        use_dbus:       Boolean; to emit D-Bus signals or not
 
986
        clients:        set of Client objects
 
987
        gnutls_priority GnuTLS priority string
 
988
        use_dbus:       Boolean; to emit D-Bus signals or not
1458
989
    
1459
990
    Assumes a gobject.MainLoop event loop.
1460
991
    """
1476
1007
            return socketserver.TCPServer.server_activate(self)
1477
1008
    def enable(self):
1478
1009
        self.enabled = True
1479
 
    def add_pipe(self, parent_pipe):
 
1010
    def add_pipe(self, pipe):
1480
1011
        # Call "handle_ipc" for both data and EOF events
1481
 
        gobject.io_add_watch(parent_pipe.fileno(),
1482
 
                             gobject.IO_IN | gobject.IO_HUP,
1483
 
                             functools.partial(self.handle_ipc,
1484
 
                                               parent_pipe = parent_pipe))
1485
 
        
1486
 
    def handle_ipc(self, source, condition, parent_pipe=None,
1487
 
                   client_object=None):
 
1012
        gobject.io_add_watch(pipe, gobject.IO_IN | gobject.IO_HUP,
 
1013
                             self.handle_ipc)
 
1014
    def handle_ipc(self, source, condition, file_objects={}):
1488
1015
        condition_names = {
1489
1016
            gobject.IO_IN: u"IN",   # There is data to read.
1490
1017
            gobject.IO_OUT: u"OUT", # Data can be written (without
1499
1026
                                       for cond, name in
1500
1027
                                       condition_names.iteritems()
1501
1028
                                       if cond & condition)
1502
 
        # error or the other end of multiprocessing.Pipe has closed
1503
 
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1504
 
            return False
1505
 
        
1506
 
        # Read a request from the child
1507
 
        request = parent_pipe.recv()
1508
 
        command = request[0]
1509
 
        
1510
 
        if command == 'init':
1511
 
            fpr = request[1]
1512
 
            address = request[2]
1513
 
            
1514
 
            for c in self.clients:
1515
 
                if c.fingerprint == fpr:
1516
 
                    client = c
1517
 
                    break
1518
 
            else:
1519
 
                logger.warning(u"Client not found for fingerprint: %s, ad"
1520
 
                               u"dress: %s", fpr, address)
1521
 
                if self.use_dbus:
1522
 
                    # Emit D-Bus signal
1523
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
1524
 
                parent_pipe.send(False)
1525
 
                return False
1526
 
            
1527
 
            gobject.io_add_watch(parent_pipe.fileno(),
1528
 
                                 gobject.IO_IN | gobject.IO_HUP,
1529
 
                                 functools.partial(self.handle_ipc,
1530
 
                                                   parent_pipe = parent_pipe,
1531
 
                                                   client_object = client))
1532
 
            parent_pipe.send(True)
1533
 
            # remove the old hook in favor of the new above hook on same fileno
1534
 
            return False
1535
 
        if command == 'funcall':
1536
 
            funcname = request[1]
1537
 
            args = request[2]
1538
 
            kwargs = request[3]
1539
 
            
1540
 
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1541
 
 
1542
 
        if command == 'getattr':
1543
 
            attrname = request[1]
1544
 
            if callable(client_object.__getattribute__(attrname)):
1545
 
                parent_pipe.send(('function',))
1546
 
            else:
1547
 
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1548
 
        
1549
 
        if command == 'setattr':
1550
 
            attrname = request[1]
1551
 
            value = request[2]
1552
 
            setattr(client_object, attrname, value)
1553
 
 
 
1029
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
 
1030
                     conditions_string)
 
1031
        
 
1032
        # Turn the pipe file descriptor into a Python file object
 
1033
        if source not in file_objects:
 
1034
            file_objects[source] = os.fdopen(source, u"r", 1)
 
1035
        
 
1036
        # Read a line from the file object
 
1037
        cmdline = file_objects[source].readline()
 
1038
        if not cmdline:             # Empty line means end of file
 
1039
            # close the IPC pipe
 
1040
            file_objects[source].close()
 
1041
            del file_objects[source]
 
1042
            
 
1043
            # Stop calling this function
 
1044
            return False
 
1045
        
 
1046
        logger.debug(u"IPC command: %r", cmdline)
 
1047
        
 
1048
        # Parse and act on command
 
1049
        cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
 
1050
        
 
1051
        if cmd == u"NOTFOUND":
 
1052
            logger.warning(u"Client not found for fingerprint: %s",
 
1053
                           args)
 
1054
            if self.use_dbus:
 
1055
                # Emit D-Bus signal
 
1056
                mandos_dbus_service.ClientNotFound(args)
 
1057
        elif cmd == u"INVALID":
 
1058
            for client in self.clients:
 
1059
                if client.name == args:
 
1060
                    logger.warning(u"Client %s is invalid", args)
 
1061
                    if self.use_dbus:
 
1062
                        # Emit D-Bus signal
 
1063
                        client.Rejected()
 
1064
                    break
 
1065
            else:
 
1066
                logger.error(u"Unknown client %s is invalid", args)
 
1067
        elif cmd == u"SENDING":
 
1068
            for client in self.clients:
 
1069
                if client.name == args:
 
1070
                    logger.info(u"Sending secret to %s", client.name)
 
1071
                    client.checked_ok()
 
1072
                    if self.use_dbus:
 
1073
                        # Emit D-Bus signal
 
1074
                        client.ReceivedSecret()
 
1075
                    break
 
1076
            else:
 
1077
                logger.error(u"Sending secret to unknown client %s",
 
1078
                             args)
 
1079
        else:
 
1080
            logger.error(u"Unknown IPC command: %r", cmdline)
 
1081
        
 
1082
        # Keep calling this function
1554
1083
        return True
1555
1084
 
1556
1085
 
1586
1115
            elif suffix == u"w":
1587
1116
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1588
1117
            else:
1589
 
                raise ValueError(u"Unknown suffix %r" % suffix)
1590
 
        except (ValueError, IndexError), e:
1591
 
            raise ValueError(e.message)
 
1118
                raise ValueError
 
1119
        except (ValueError, IndexError):
 
1120
            raise ValueError
1592
1121
        timevalue += delta
1593
1122
    return timevalue
1594
1123
 
1607
1136
        def if_nametoindex(interface):
1608
1137
            "Get an interface index the hard way, i.e. using fcntl()"
1609
1138
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1610
 
            with contextlib.closing(socket.socket()) as s:
 
1139
            with closing(socket.socket()) as s:
1611
1140
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1612
1141
                                    struct.pack(str(u"16s16x"),
1613
1142
                                                interface))
1633
1162
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1634
1163
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1635
1164
            raise OSError(errno.ENODEV,
1636
 
                          u"%s not a character device"
1637
 
                          % os.path.devnull)
 
1165
                          u"/dev/null not a character device")
1638
1166
        os.dup2(null, sys.stdin.fileno())
1639
1167
        os.dup2(null, sys.stdout.fileno())
1640
1168
        os.dup2(null, sys.stderr.fileno())
1644
1172
 
1645
1173
def main():
1646
1174
    
1647
 
    ##################################################################
 
1175
    ######################################################################
1648
1176
    # Parsing of options, both command line and config file
1649
1177
    
1650
1178
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1659
1187
    parser.add_option("--debug", action=u"store_true",
1660
1188
                      help=u"Debug mode; run in foreground and log to"
1661
1189
                      u" terminal")
1662
 
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
1663
 
                      help=u"Debug level for stdout output")
1664
1190
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1665
1191
                      u" priority string (see GnuTLS documentation)")
1666
1192
    parser.add_option("--servicename", type=u"string",
1670
1196
                      help=u"Directory to search for configuration"
1671
1197
                      u" files")
1672
1198
    parser.add_option("--no-dbus", action=u"store_false",
1673
 
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1674
 
                      u" system bus interface")
 
1199
                      dest=u"use_dbus",
 
1200
                      help=optparse.SUPPRESS_HELP) # XXX: Not done yet
1675
1201
    parser.add_option("--no-ipv6", action=u"store_false",
1676
1202
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1677
1203
    options = parser.parse_args()[0]
1691
1217
                        u"servicename": u"Mandos",
1692
1218
                        u"use_dbus": u"True",
1693
1219
                        u"use_ipv6": u"True",
1694
 
                        u"debuglevel": u"",
1695
1220
                        }
1696
1221
    
1697
1222
    # Parse config file for server-global settings
1714
1239
    # options, if set.
1715
1240
    for option in (u"interface", u"address", u"port", u"debug",
1716
1241
                   u"priority", u"servicename", u"configdir",
1717
 
                   u"use_dbus", u"use_ipv6", u"debuglevel"):
 
1242
                   u"use_dbus", u"use_ipv6"):
1718
1243
        value = getattr(options, option)
1719
1244
        if value is not None:
1720
1245
            server_settings[option] = value
1729
1254
    
1730
1255
    # For convenience
1731
1256
    debug = server_settings[u"debug"]
1732
 
    debuglevel = server_settings[u"debuglevel"]
1733
1257
    use_dbus = server_settings[u"use_dbus"]
 
1258
    use_dbus = False            # XXX: Not done yet
1734
1259
    use_ipv6 = server_settings[u"use_ipv6"]
1735
 
 
 
1260
    
 
1261
    if not debug:
 
1262
        syslogger.setLevel(logging.WARNING)
 
1263
        console.setLevel(logging.WARNING)
 
1264
    
1736
1265
    if server_settings[u"servicename"] != u"Mandos":
1737
1266
        syslogger.setFormatter(logging.Formatter
1738
1267
                               (u'Mandos (%s) [%%(process)d]:'
1744
1273
                        u"interval": u"5m",
1745
1274
                        u"checker": u"fping -q -- %%(host)s",
1746
1275
                        u"host": u"",
1747
 
                        u"approval_delay": u"0s",
1748
 
                        u"approval_duration": u"1s",
1749
1276
                        }
1750
1277
    client_config = configparser.SafeConfigParser(client_defaults)
1751
1278
    client_config.read(os.path.join(server_settings[u"configdir"],
1757
1284
    tcp_server = MandosServer((server_settings[u"address"],
1758
1285
                               server_settings[u"port"]),
1759
1286
                              ClientHandler,
1760
 
                              interface=(server_settings[u"interface"]
1761
 
                                         or None),
 
1287
                              interface=server_settings[u"interface"],
1762
1288
                              use_ipv6=use_ipv6,
1763
1289
                              gnutls_priority=
1764
1290
                              server_settings[u"priority"],
1790
1316
        if error[0] != errno.EPERM:
1791
1317
            raise error
1792
1318
    
1793
 
    if not debug and not debuglevel:
1794
 
        syslogger.setLevel(logging.WARNING)
1795
 
        console.setLevel(logging.WARNING)
1796
 
    if debuglevel:
1797
 
        level = getattr(logging, debuglevel.upper())
1798
 
        syslogger.setLevel(level)
1799
 
        console.setLevel(level)
1800
 
 
 
1319
    # Enable all possible GnuTLS debugging
1801
1320
    if debug:
1802
 
        # Enable all possible GnuTLS debugging
1803
 
        
1804
1321
        # "Use a log level over 10 to enable all debugging options."
1805
1322
        # - GnuTLS manual
1806
1323
        gnutls.library.functions.gnutls_global_set_log_level(11)
1811
1328
        
1812
1329
        (gnutls.library.functions
1813
1330
         .gnutls_global_set_log_function(debug_gnutls))
1814
 
        
1815
 
        # Redirect stdin so all checkers get /dev/null
1816
 
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1817
 
        os.dup2(null, sys.stdin.fileno())
1818
 
        if null > 2:
1819
 
            os.close(null)
1820
 
    else:
1821
 
        # No console logging
1822
 
        logger.removeHandler(console)
1823
 
    
1824
1331
    
1825
1332
    global main_loop
1826
1333
    # From the Avahi example code
1829
1336
    bus = dbus.SystemBus()
1830
1337
    # End of Avahi example code
1831
1338
    if use_dbus:
1832
 
        try:
1833
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1834
 
                                            bus, do_not_queue=True)
1835
 
        except dbus.exceptions.NameExistsException, e:
1836
 
            logger.error(unicode(e) + u", disabling D-Bus")
1837
 
            use_dbus = False
1838
 
            server_settings[u"use_dbus"] = False
1839
 
            tcp_server.use_dbus = False
 
1339
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1840
1340
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1841
1341
    service = AvahiService(name = server_settings[u"servicename"],
1842
1342
                           servicetype = u"_mandos._tcp",
1844
1344
    if server_settings["interface"]:
1845
1345
        service.interface = (if_nametoindex
1846
1346
                             (str(server_settings[u"interface"])))
1847
 
 
1848
 
    if not debug:
1849
 
        # Close all input and output, do double fork, etc.
1850
 
        daemon()
1851
 
        
1852
 
    global multiprocessing_manager
1853
 
    multiprocessing_manager = multiprocessing.Manager()
1854
1347
    
1855
1348
    client_class = Client
1856
1349
    if use_dbus:
1857
1350
        client_class = functools.partial(ClientDBus, bus = bus)
1858
 
    def client_config_items(config, section):
1859
 
        special_settings = {
1860
 
            "approved_by_default":
1861
 
                lambda: config.getboolean(section,
1862
 
                                          "approved_by_default"),
1863
 
            }
1864
 
        for name, value in config.items(section):
1865
 
            try:
1866
 
                yield (name, special_settings[name]())
1867
 
            except KeyError:
1868
 
                yield (name, value)
1869
 
    
1870
1351
    tcp_server.clients.update(set(
1871
1352
            client_class(name = section,
1872
 
                         config= dict(client_config_items(
1873
 
                        client_config, section)))
 
1353
                         config= dict(client_config.items(section)))
1874
1354
            for section in client_config.sections()))
1875
1355
    if not tcp_server.clients:
1876
1356
        logger.warning(u"No clients defined")
1877
 
        
 
1357
    
 
1358
    if debug:
 
1359
        # Redirect stdin so all checkers get /dev/null
 
1360
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
1361
        os.dup2(null, sys.stdin.fileno())
 
1362
        if null > 2:
 
1363
            os.close(null)
 
1364
    else:
 
1365
        # No console logging
 
1366
        logger.removeHandler(console)
 
1367
        # Close all input and output, do double fork, etc.
 
1368
        daemon()
 
1369
    
1878
1370
    try:
1879
 
        with pidfile:
 
1371
        with closing(pidfile):
1880
1372
            pid = os.getpid()
1881
1373
            pidfile.write(str(pid) + "\n")
1882
1374
        del pidfile
1888
1380
        pass
1889
1381
    del pidfilename
1890
1382
    
 
1383
    def cleanup():
 
1384
        "Cleanup function; run on exit"
 
1385
        service.cleanup()
 
1386
        
 
1387
        while tcp_server.clients:
 
1388
            client = tcp_server.clients.pop()
 
1389
            client.disable_hook = None
 
1390
            client.disable()
 
1391
    
 
1392
    atexit.register(cleanup)
 
1393
    
1891
1394
    if not debug:
1892
1395
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1893
1396
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1900
1403
                dbus.service.Object.__init__(self, bus, u"/")
1901
1404
            _interface = u"se.bsnet.fukt.Mandos"
1902
1405
            
1903
 
            @dbus.service.signal(_interface, signature=u"o")
1904
 
            def ClientAdded(self, objpath):
 
1406
            @dbus.service.signal(_interface, signature=u"oa{sv}")
 
1407
            def ClientAdded(self, objpath, properties):
1905
1408
                "D-Bus signal"
1906
1409
                pass
1907
1410
            
1908
 
            @dbus.service.signal(_interface, signature=u"ss")
1909
 
            def ClientNotFound(self, fingerprint, address):
 
1411
            @dbus.service.signal(_interface, signature=u"s")
 
1412
            def ClientNotFound(self, fingerprint):
1910
1413
                "D-Bus signal"
1911
1414
                pass
1912
1415
            
1926
1429
            def GetAllClientsWithProperties(self):
1927
1430
                "D-Bus method"
1928
1431
                return dbus.Dictionary(
1929
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1432
                    ((c.dbus_object_path, c.GetAllProperties())
1930
1433
                     for c in tcp_server.clients),
1931
1434
                    signature=u"oa{sv}")
1932
1435
            
1938
1441
                        tcp_server.clients.remove(c)
1939
1442
                        c.remove_from_connection()
1940
1443
                        # Don't signal anything except ClientRemoved
1941
 
                        c.disable(quiet=True)
 
1444
                        c.disable(signal=False)
1942
1445
                        # Emit D-Bus signal
1943
1446
                        self.ClientRemoved(object_path, c.name)
1944
1447
                        return
1945
 
                raise KeyError(object_path)
 
1448
                raise KeyError
1946
1449
            
1947
1450
            del _interface
1948
1451
        
1949
1452
        mandos_dbus_service = MandosDBusService()
1950
1453
    
1951
 
    def cleanup():
1952
 
        "Cleanup function; run on exit"
1953
 
        service.cleanup()
1954
 
        
1955
 
        while tcp_server.clients:
1956
 
            client = tcp_server.clients.pop()
1957
 
            if use_dbus:
1958
 
                client.remove_from_connection()
1959
 
            client.disable_hook = None
1960
 
            # Don't signal anything except ClientRemoved
1961
 
            client.disable(quiet=True)
1962
 
            if use_dbus:
1963
 
                # Emit D-Bus signal
1964
 
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1965
 
                                                  client.name)
1966
 
    
1967
 
    atexit.register(cleanup)
1968
 
    
1969
1454
    for client in tcp_server.clients:
1970
1455
        if use_dbus:
1971
1456
            # Emit D-Bus signal
1972
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
1457
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1458
                                            client.GetAllProperties())
1973
1459
        client.enable()
1974
1460
    
1975
1461
    tcp_server.enable()
1993
1479
            service.activate()
1994
1480
        except dbus.exceptions.DBusException, error:
1995
1481
            logger.critical(u"DBusException: %s", error)
1996
 
            cleanup()
1997
1482
            sys.exit(1)
1998
1483
        # End of Avahi example code
1999
1484
        
2006
1491
        main_loop.run()
2007
1492
    except AvahiError, error:
2008
1493
        logger.critical(u"AvahiError: %s", error)
2009
 
        cleanup()
2010
1494
        sys.exit(1)
2011
1495
    except KeyboardInterrupt:
2012
1496
        if debug:
2013
1497
            print >> sys.stderr
2014
1498
        logger.debug(u"Server received KeyboardInterrupt")
2015
1499
    logger.debug(u"Server exiting")
2016
 
    # Must run before the D-Bus bus name gets deregistered
2017
 
    cleanup()
2018
1500
 
2019
1501
if __name__ == '__main__':
2020
1502
    main()