/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 Hogeborn
  • Date: 2008-08-25 10:41:16 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080825104116-cjd54qqs535kpdxq
* mandos-options.xml (address): Refer to IPv4-mapped IPv6 address
                                syntax by name.

* mandos.conf.xml (SEE ALSO): Also refer to gnutls_priority_init(3),
                              RFC 4291, and Zeroconf.

* mandos.xml (SEE ALSO): Also refer to sections 2.2 and 2.5.5.2 of RFC
                         4291.  Stop using <citation> tags.

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
# This program is partly derived from an example program for an Avahi
7
7
# service publisher, downloaded from
8
8
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
9
 
# following functions: "AvahiService.add", "AvahiService.remove",
10
 
# "server_state_changed", "entry_group_state_changed", and some lines
11
 
# in "main".
 
9
# methods "add" and "remove" in the "AvahiService" class, the
 
10
# "server_state_changed" and "entry_group_state_changed" functions,
 
11
# and some lines in "main".
12
12
13
13
# Everything else is
14
14
# Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
61
61
from dbus.mainloop.glib import DBusGMainLoop
62
62
import ctypes
63
63
 
64
 
# Brief description of the operation of this program:
65
 
66
 
# This server announces itself as a Zeroconf service.  Connecting
67
 
# clients use the TLS protocol, with the unusual quirk that this
68
 
# server program acts as a TLS "client" while a connecting client acts
69
 
# as a TLS "server".  The client (acting as a TLS "server") must
70
 
# supply an OpenPGP certificate, and the fingerprint of this
71
 
# certificate is used by this server to look up (in a list read from a
72
 
# file at start time) which binary blob to give the client.  No other
73
 
# authentication or authorization is done by this server.
74
 
 
 
64
version = "1.0"
75
65
 
76
66
logger = logging.Logger('mandos')
77
67
syslogger = logging.handlers.SysLogHandler\
78
 
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON)
 
68
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
69
             address = "/dev/log")
79
70
syslogger.setFormatter(logging.Formatter\
80
 
                        ('%(levelname)s: %(message)s'))
 
71
                        ('Mandos: %(levelname)s: %(message)s'))
81
72
logger.addHandler(syslogger)
82
 
del syslogger
83
73
 
 
74
console = logging.StreamHandler()
 
75
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
 
76
                                       ' %(message)s'))
 
77
logger.addHandler(console)
84
78
 
85
79
class AvahiError(Exception):
86
80
    def __init__(self, value):
96
90
 
97
91
 
98
92
class AvahiService(object):
99
 
    """
 
93
    """An Avahi (Zeroconf) service.
 
94
    Attributes:
100
95
    interface: integer; avahi.IF_UNSPEC or an interface index.
101
96
               Used to optionally bind to the specified interface.
102
 
    name = string; Example: "Mandos"
103
 
    type = string; Example: "_mandos._tcp".
104
 
                   See <http://www.dns-sd.org/ServiceTypes.html>
105
 
    port = integer; what port to announce
106
 
    TXT = list of strings; TXT record for the service
107
 
    domain = string; Domain to publish on, default to .local if empty.
108
 
    host = string; Host to publish records for, default to localhost
109
 
                   if empty.
110
 
    max_renames = integer; maximum number of renames
111
 
    rename_count = integer; counter so we only rename after collisions
112
 
                   a sensible number of times
 
97
    name: string; Example: 'Mandos'
 
98
    type: string; Example: '_mandos._tcp'.
 
99
                  See <http://www.dns-sd.org/ServiceTypes.html>
 
100
    port: integer; what port to announce
 
101
    TXT: list of strings; TXT record for the service
 
102
    domain: string; Domain to publish on, default to .local if empty.
 
103
    host: string; Host to publish records for, default is localhost
 
104
    max_renames: integer; maximum number of renames
 
105
    rename_count: integer; counter so we only rename after collisions
 
106
                  a sensible number of times
113
107
    """
114
108
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
109
                 type = None, port = None, TXT = None, domain = "",
116
 
                 host = "", max_renames = 12):
117
 
        """An Avahi (Zeroconf) service. """
 
110
                 host = "", max_renames = 32768):
118
111
        self.interface = interface
119
112
        self.name = name
120
113
        self.type = type
126
119
        self.domain = domain
127
120
        self.host = host
128
121
        self.rename_count = 0
 
122
        self.max_renames = max_renames
129
123
    def rename(self):
130
124
        """Derived from the Avahi example code"""
131
125
        if self.rename_count >= self.max_renames:
132
126
            logger.critical(u"No suitable service name found after %i"
133
127
                            u" retries, exiting.", rename_count)
134
128
            raise AvahiServiceError("Too many renames")
135
 
        name = server.GetAlternativeServiceName(name)
136
 
        logger.notice(u"Changing name to %r ...", name)
 
129
        self.name = server.GetAlternativeServiceName(self.name)
 
130
        logger.info(u"Changing name to %r ...", str(self.name))
 
131
        syslogger.setFormatter(logging.Formatter\
 
132
                               ('Mandos (%s): %%(levelname)s:'
 
133
                               ' %%(message)s' % self.name))
137
134
        self.remove()
138
135
        self.add()
139
136
        self.rename_count += 1
175
172
    fingerprint: string (40 or 32 hexadecimal digits); used to
176
173
                 uniquely identify the client
177
174
    secret:    bytestring; sent verbatim (over TLS) to client
178
 
    fqdn:      string (FQDN); available for use by the checker command
 
175
    host:      string; available for use by the checker command
179
176
    created:   datetime.datetime(); object creation, not client host
180
177
    last_checked_ok: datetime.datetime() or None if not yet checked OK
181
178
    timeout:   datetime.timedelta(); How long from last_checked_ok
221
218
    interval = property(lambda self: self._interval,
222
219
                        _set_interval)
223
220
    del _set_interval
224
 
    def __init__(self, name=None, stop_hook=None, fingerprint=None,
225
 
                 secret=None, secfile=None, fqdn=None, timeout=None,
226
 
                 interval=-1, checker=None):
227
 
        """Note: the 'checker' argument sets the 'checker_command'
228
 
        attribute and not the 'checker' attribute.."""
 
221
    def __init__(self, name = None, stop_hook=None, config={}):
 
222
        """Note: the 'checker' key in 'config' sets the
 
223
        'checker_command' attribute and *not* the 'checker'
 
224
        attribute."""
229
225
        self.name = name
230
226
        logger.debug(u"Creating client %r", self.name)
231
 
        # Uppercase and remove spaces from fingerprint
232
 
        # for later comparison purposes with return value of
233
 
        # the fingerprint() function
234
 
        self.fingerprint = fingerprint.upper().replace(u" ", u"")
 
227
        # Uppercase and remove spaces from fingerprint for later
 
228
        # comparison purposes with return value from the fingerprint()
 
229
        # function
 
230
        self.fingerprint = config["fingerprint"].upper()\
 
231
                           .replace(u" ", u"")
235
232
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
236
 
        if secret:
237
 
            self.secret = secret.decode(u"base64")
238
 
        elif secfile:
239
 
            sf = open(secfile)
 
233
        if "secret" in config:
 
234
            self.secret = config["secret"].decode(u"base64")
 
235
        elif "secfile" in config:
 
236
            sf = open(config["secfile"])
240
237
            self.secret = sf.read()
241
238
            sf.close()
242
239
        else:
243
240
            raise TypeError(u"No secret or secfile for client %s"
244
241
                            % self.name)
245
 
        self.fqdn = fqdn
 
242
        self.host = config.get("host", "")
246
243
        self.created = datetime.datetime.now()
247
244
        self.last_checked_ok = None
248
 
        self.timeout = string_to_delta(timeout)
249
 
        self.interval = string_to_delta(interval)
 
245
        self.timeout = string_to_delta(config["timeout"])
 
246
        self.interval = string_to_delta(config["interval"])
250
247
        self.stop_hook = stop_hook
251
248
        self.checker = None
252
249
        self.checker_initiator_tag = None
253
250
        self.stop_initiator_tag = None
254
251
        self.checker_callback_tag = None
255
 
        self.check_command = checker
 
252
        self.check_command = config["checker"]
256
253
    def start(self):
257
254
        """Start this client's checker and timeout hooks"""
258
255
        # Schedule a new checker to be started an 'interval' from now,
271
268
        The possibility that a client might be restarted is left open,
272
269
        but not currently used."""
273
270
        # If this client doesn't have a secret, it is already stopped.
274
 
        if self.secret:
275
 
            logger.debug(u"Stopping client %s", self.name)
 
271
        if hasattr(self, "secret") and self.secret:
 
272
            logger.info(u"Stopping client %s", self.name)
276
273
            self.secret = None
277
274
        else:
278
275
            return False
297
294
        self.checker = None
298
295
        if os.WIFEXITED(condition) \
299
296
               and (os.WEXITSTATUS(condition) == 0):
300
 
            logger.debug(u"Checker for %(name)s succeeded",
301
 
                         vars(self))
 
297
            logger.info(u"Checker for %(name)s succeeded",
 
298
                        vars(self))
302
299
            self.last_checked_ok = now
303
300
            gobject.source_remove(self.stop_initiator_tag)
304
301
            self.stop_initiator_tag = gobject.timeout_add\
308
305
            logger.warning(u"Checker for %(name)s crashed?",
309
306
                           vars(self))
310
307
        else:
311
 
            logger.debug(u"Checker for %(name)s failed",
312
 
                         vars(self))
 
308
            logger.info(u"Checker for %(name)s failed",
 
309
                        vars(self))
313
310
    def start_checker(self):
314
311
        """Start a new checker subprocess if one is not running.
315
312
        If a checker already exists, leave it running and do
325
322
        if self.checker is None:
326
323
            try:
327
324
                # In case check_command has exactly one % operator
328
 
                command = self.check_command % self.fqdn
 
325
                command = self.check_command % self.host
329
326
            except TypeError:
330
327
                # Escape attributes for the shell
331
328
                escaped_attrs = dict((key, re.escape(str(val)))
338
335
                                 u' %s', self.check_command, error)
339
336
                    return True # Try again later
340
337
            try:
341
 
                logger.debug(u"Starting checker %r for %s",
342
 
                             command, self.name)
 
338
                logger.info(u"Starting checker %r for %s",
 
339
                            command, self.name)
 
340
                # We don't need to redirect stdout and stderr, since
 
341
                # in normal mode, that is already done by daemon(),
 
342
                # and in debug mode we don't want to.  (Stdin is
 
343
                # always replaced by /dev/null.)
343
344
                self.checker = subprocess.Popen(command,
344
345
                                                close_fds=True,
345
346
                                                shell=True, cwd="/")
346
347
                self.checker_callback_tag = gobject.child_watch_add\
347
348
                                            (self.checker.pid,
348
349
                                             self.checker_callback)
349
 
            except subprocess.OSError, error:
 
350
            except OSError, error:
350
351
                logger.error(u"Failed to start subprocess: %s",
351
352
                             error)
352
353
        # Re-run this periodically if run by gobject.timeout_add
358
359
            self.checker_callback_tag = None
359
360
        if getattr(self, "checker", None) is None:
360
361
            return
361
 
        logger.debug("Stopping checker for %(name)s", vars(self))
 
362
        logger.debug(u"Stopping checker for %(name)s", vars(self))
362
363
        try:
363
364
            os.kill(self.checker.pid, signal.SIGTERM)
364
365
            #os.sleep(0.5)
396
397
 
397
398
def fingerprint(openpgp):
398
399
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
399
 
    # New empty GnuTLS certificate
400
 
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
401
 
    gnutls.library.functions.gnutls_openpgp_crt_init\
402
 
        (ctypes.byref(crt))
403
400
    # New GnuTLS "datum" with the OpenPGP public key
404
401
    datum = gnutls.library.types.gnutls_datum_t\
405
402
        (ctypes.cast(ctypes.c_char_p(openpgp),
406
403
                     ctypes.POINTER(ctypes.c_ubyte)),
407
404
         ctypes.c_uint(len(openpgp)))
 
405
    # New empty GnuTLS certificate
 
406
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
407
    gnutls.library.functions.gnutls_openpgp_crt_init\
 
408
        (ctypes.byref(crt))
408
409
    # Import the OpenPGP public key into the certificate
409
 
    ret = gnutls.library.functions.gnutls_openpgp_crt_import\
410
 
        (crt,
411
 
         ctypes.byref(datum),
412
 
         gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
410
    gnutls.library.functions.gnutls_openpgp_crt_import\
 
411
                    (crt, ctypes.byref(datum),
 
412
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
413
    # Verify the self signature in the key
 
414
    crtverify = ctypes.c_uint();
 
415
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
 
416
        (crt, ctypes.c_uint(0), ctypes.byref(crtverify))
 
417
    if crtverify.value != 0:
 
418
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
419
        raise gnutls.errors.CertificateSecurityError("Verify failed")
413
420
    # New buffer for the fingerprint
414
421
    buffer = ctypes.create_string_buffer(20)
415
422
    buffer_length = ctypes.c_size_t()
431
438
    Note: This will run in its own forked process."""
432
439
    
433
440
    def handle(self):
434
 
        logger.debug(u"TCP connection from: %s",
 
441
        logger.info(u"TCP connection from: %s",
435
442
                     unicode(self.client_address))
436
443
        session = gnutls.connection.ClientSession\
437
444
                  (self.request, gnutls.connection.X509Credentials())
 
445
        
 
446
        line = self.request.makefile().readline()
 
447
        logger.debug(u"Protocol version: %r", line)
 
448
        try:
 
449
            if int(line.strip().split()[0]) > 1:
 
450
                raise RuntimeError
 
451
        except (ValueError, IndexError, RuntimeError), error:
 
452
            logger.error(u"Unknown protocol version: %s", error)
 
453
            return
 
454
        
438
455
        # Note: gnutls.connection.X509Credentials is really a generic
439
456
        # GnuTLS certificate credentials object so long as no X.509
440
457
        # keys are added to it.  Therefore, we can use it here despite
453
470
        try:
454
471
            session.handshake()
455
472
        except gnutls.errors.GNUTLSError, error:
456
 
            logger.debug(u"Handshake failed: %s", error)
 
473
            logger.warning(u"Handshake failed: %s", error)
457
474
            # Do not run session.bye() here: the session is not
458
475
            # established.  Just abandon the request.
459
476
            return
460
477
        try:
461
478
            fpr = fingerprint(peer_certificate(session))
462
479
        except (TypeError, gnutls.errors.GNUTLSError), error:
463
 
            logger.debug(u"Bad certificate: %s", error)
 
480
            logger.warning(u"Bad certificate: %s", error)
464
481
            session.bye()
465
482
            return
466
483
        logger.debug(u"Fingerprint: %s", fpr)
470
487
                client = c
471
488
                break
472
489
        if not client:
473
 
            logger.debug(u"Client not found for fingerprint: %s", fpr)
 
490
            logger.warning(u"Client not found for fingerprint: %s",
 
491
                           fpr)
474
492
            session.bye()
475
493
            return
476
494
        # Have to check if client.still_valid(), since it is possible
477
495
        # that the client timed out while establishing the GnuTLS
478
496
        # session.
479
497
        if not client.still_valid():
480
 
            logger.debug(u"Client %(name)s is invalid", vars(client))
 
498
            logger.warning(u"Client %(name)s is invalid",
 
499
                           vars(client))
481
500
            session.bye()
482
501
            return
483
502
        sent_size = 0
518
537
                                       self.settings["interface"])
519
538
            except socket.error, error:
520
539
                if error[0] == errno.EPERM:
521
 
                    logger.warning(u"No permission to"
522
 
                                   u" bind to interface %s",
523
 
                                   self.settings["interface"])
 
540
                    logger.error(u"No permission to"
 
541
                                 u" bind to interface %s",
 
542
                                 self.settings["interface"])
524
543
                else:
525
544
                    raise error
526
545
        # Only bind(2) the socket if we really need to.
529
548
                in6addr_any = "::"
530
549
                self.server_address = (in6addr_any,
531
550
                                       self.server_address[1])
532
 
            elif self.server_address[1] is None:
 
551
            elif not self.server_address[1]:
533
552
                self.server_address = (self.server_address[0],
534
553
                                       0)
 
554
#                 if self.settings["interface"]:
 
555
#                     self.server_address = (self.server_address[0],
 
556
#                                            0, # port
 
557
#                                            0, # flowinfo
 
558
#                                            if_nametoindex
 
559
#                                            (self.settings
 
560
#                                             ["interface"]))
535
561
            return super(type(self), self).server_bind()
536
562
 
537
563
 
548
574
    datetime.timedelta(1)
549
575
    >>> string_to_delta(u'1w')
550
576
    datetime.timedelta(7)
 
577
    >>> string_to_delta('5m 30s')
 
578
    datetime.timedelta(0, 330)
551
579
    """
552
 
    try:
553
 
        suffix=unicode(interval[-1])
554
 
        value=int(interval[:-1])
555
 
        if suffix == u"d":
556
 
            delta = datetime.timedelta(value)
557
 
        elif suffix == u"s":
558
 
            delta = datetime.timedelta(0, value)
559
 
        elif suffix == u"m":
560
 
            delta = datetime.timedelta(0, 0, 0, 0, value)
561
 
        elif suffix == u"h":
562
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, value)
563
 
        elif suffix == u"w":
564
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
565
 
        else:
 
580
    timevalue = datetime.timedelta(0)
 
581
    for s in interval.split():
 
582
        try:
 
583
            suffix=unicode(s[-1])
 
584
            value=int(s[:-1])
 
585
            if suffix == u"d":
 
586
                delta = datetime.timedelta(value)
 
587
            elif suffix == u"s":
 
588
                delta = datetime.timedelta(0, value)
 
589
            elif suffix == u"m":
 
590
                delta = datetime.timedelta(0, 0, 0, 0, value)
 
591
            elif suffix == u"h":
 
592
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
 
593
            elif suffix == u"w":
 
594
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
 
595
            else:
 
596
                raise ValueError
 
597
        except (ValueError, IndexError):
566
598
            raise ValueError
567
 
    except (ValueError, IndexError):
568
 
        raise ValueError
569
 
    return delta
 
599
        timevalue += delta
 
600
    return timevalue
570
601
 
571
602
 
572
603
def server_state_changed(state):
573
604
    """Derived from the Avahi example code"""
574
605
    if state == avahi.SERVER_COLLISION:
575
 
        logger.warning(u"Server name collision")
 
606
        logger.error(u"Server name collision")
576
607
        service.remove()
577
608
    elif state == avahi.SERVER_RUNNING:
578
609
        service.add()
592
623
                        unicode(error))
593
624
        raise AvahiGroupError("State changed: %s", str(error))
594
625
 
595
 
def if_nametoindex(interface, _func=[None]):
 
626
def if_nametoindex(interface):
596
627
    """Call the C function if_nametoindex(), or equivalent"""
597
 
    if _func[0] is not None:
598
 
        return _func[0](interface)
 
628
    global if_nametoindex
599
629
    try:
600
630
        if "ctypes.util" not in sys.modules:
601
631
            import ctypes.util
602
 
        while True:
603
 
            try:
604
 
                libc = ctypes.cdll.LoadLibrary\
605
 
                       (ctypes.util.find_library("c"))
606
 
                _func[0] = libc.if_nametoindex
607
 
                return _func[0](interface)
608
 
            except IOError, e:
609
 
                if e != errno.EINTR:
610
 
                    raise
 
632
        if_nametoindex = ctypes.cdll.LoadLibrary\
 
633
            (ctypes.util.find_library("c")).if_nametoindex
611
634
    except (OSError, AttributeError):
612
635
        if "struct" not in sys.modules:
613
636
            import struct
614
637
        if "fcntl" not in sys.modules:
615
638
            import fcntl
616
 
        def the_hard_way(interface):
 
639
        def if_nametoindex(interface):
617
640
            "Get an interface index the hard way, i.e. using fcntl()"
618
641
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
619
642
            s = socket.socket()
622
645
            s.close()
623
646
            interface_index = struct.unpack("I", ifreq[16:20])[0]
624
647
            return interface_index
625
 
        _func[0] = the_hard_way
626
 
        return _func[0](interface)
627
 
 
628
 
 
629
 
def daemon(nochdir, noclose):
 
648
    return if_nametoindex(interface)
 
649
 
 
650
 
 
651
def daemon(nochdir = False, noclose = False):
630
652
    """See daemon(3).  Standard BSD Unix function.
631
653
    This should really exist as os.daemon, but it doesn't (yet)."""
632
654
    if os.fork():
634
656
    os.setsid()
635
657
    if not nochdir:
636
658
        os.chdir("/")
 
659
    if os.fork():
 
660
        sys.exit()
637
661
    if not noclose:
638
662
        # Close all standard open file descriptors
639
663
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
651
675
    global main_loop_started
652
676
    main_loop_started = False
653
677
    
654
 
    parser = OptionParser()
 
678
    parser = OptionParser(version = "%%prog %s" % version)
655
679
    parser.add_option("-i", "--interface", type="string",
656
680
                      metavar="IF", help="Bind to interface IF")
657
681
    parser.add_option("-a", "--address", type="string",
660
684
                      help="Port number to receive requests on")
661
685
    parser.add_option("--check", action="store_true", default=False,
662
686
                      help="Run self-test")
663
 
    parser.add_option("--debug", action="store_true", default=False,
 
687
    parser.add_option("--debug", action="store_true",
664
688
                      help="Debug mode; run in foreground and log to"
665
689
                      " terminal")
666
690
    parser.add_option("--priority", type="string", help="GnuTLS"
691
715
    # Parse config file for server-global settings
692
716
    server_config = ConfigParser.SafeConfigParser(server_defaults)
693
717
    del server_defaults
694
 
    server_config.read(os.path.join(options.configdir, "server.conf"))
695
 
    server_section = "server"
 
718
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
696
719
    # Convert the SafeConfigParser object to a dict
697
 
    server_settings = dict(server_config.items(server_section))
 
720
    server_settings = server_config.defaults()
698
721
    # Use getboolean on the boolean config option
699
722
    server_settings["debug"] = server_config.getboolean\
700
 
                               (server_section, "debug")
 
723
                               ("DEFAULT", "debug")
701
724
    del server_config
702
725
    
703
726
    # Override the settings from the config file with command line
710
733
    del options
711
734
    # Now we have our good server settings in "server_settings"
712
735
    
 
736
    debug = server_settings["debug"]
 
737
    
 
738
    if not debug:
 
739
        syslogger.setLevel(logging.WARNING)
 
740
        console.setLevel(logging.WARNING)
 
741
    
 
742
    if server_settings["servicename"] != "Mandos":
 
743
        syslogger.setFormatter(logging.Formatter\
 
744
                               ('Mandos (%s): %%(levelname)s:'
 
745
                                ' %%(message)s'
 
746
                                % server_settings["servicename"]))
 
747
    
713
748
    # Parse config file with clients
714
749
    client_defaults = { "timeout": "1h",
715
750
                        "interval": "5m",
716
 
                        "checker": "fping -q -- %%(fqdn)s",
 
751
                        "checker": "fping -q -- %(host)s",
 
752
                        "host": "",
717
753
                        }
718
754
    client_config = ConfigParser.SafeConfigParser(client_defaults)
719
755
    client_config.read(os.path.join(server_settings["configdir"],
737
773
            avahi.DBUS_INTERFACE_SERVER )
738
774
    # End of Avahi example code
739
775
    
740
 
    debug = server_settings["debug"]
741
 
    
742
 
    if debug:
743
 
        console = logging.StreamHandler()
744
 
        # console.setLevel(logging.DEBUG)
745
 
        console.setFormatter(logging.Formatter\
746
 
                             ('%(levelname)s: %(message)s'))
747
 
        logger.addHandler(console)
748
 
        del console
749
 
    
750
776
    clients = Set()
751
777
    def remove_from_clients(client):
752
778
        clients.remove(client)
753
779
        if not clients:
754
 
            logger.debug(u"No clients left, exiting")
 
780
            logger.critical(u"No clients left, exiting")
755
781
            sys.exit()
756
782
    
757
 
    clients.update(Set(Client(name=section,
 
783
    clients.update(Set(Client(name = section,
758
784
                              stop_hook = remove_from_clients,
759
 
                              **(dict(client_config\
760
 
                                      .items(section))))
 
785
                              config
 
786
                              = dict(client_config.items(section)))
761
787
                       for section in client_config.sections()))
762
 
    
763
 
    if not debug:
764
 
        daemon(False, False)
 
788
    if not clients:
 
789
        logger.critical(u"No clients defined")
 
790
        sys.exit(1)
 
791
    
 
792
    if debug:
 
793
        # Redirect stdin so all checkers get /dev/null
 
794
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
795
        os.dup2(null, sys.stdin.fileno())
 
796
        if null > 2:
 
797
            os.close(null)
 
798
    else:
 
799
        # No console logging
 
800
        logger.removeHandler(console)
 
801
        # Close all input and output, do double fork, etc.
 
802
        daemon()
 
803
    
 
804
    pidfilename = "/var/run/mandos/mandos.pid"
 
805
    pid = os.getpid()
 
806
    try:
 
807
        pidfile = open(pidfilename, "w")
 
808
        pidfile.write(str(pid) + "\n")
 
809
        pidfile.close()
 
810
        del pidfile
 
811
    except IOError, err:
 
812
        logger.error(u"Could not write %s file with PID %d",
 
813
                     pidfilename, os.getpid())
765
814
    
766
815
    def cleanup():
767
816
        "Cleanup function; run on exit"
794
843
                                clients=clients)
795
844
    # Find out what port we got
796
845
    service.port = tcp_server.socket.getsockname()[1]
797
 
    logger.debug(u"Now listening on address %r, port %d, flowinfo %d,"
798
 
                 u" scope_id %d" % tcp_server.socket.getsockname())
 
846
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
 
847
                u" scope_id %d" % tcp_server.socket.getsockname())
799
848
    
800
849
    #service.interface = tcp_server.socket.getsockname()[3]
801
850
    
814
863
                             tcp_server.handle_request\
815
864
                             (*args[2:], **kwargs) or True)
816
865
        
817
 
        logger.debug("Starting main loop")
 
866
        logger.debug(u"Starting main loop")
818
867
        main_loop_started = True
819
868
        main_loop.run()
820
869
    except AvahiError, error: