/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: 2010-09-12 03:00:40 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100912030040-b0uopyennste9fdh
Documentation changes:

* DBUS-API: New file documenting the server D-Bus interface.

* clients.conf: Add examples of new approval settings.

* debian/mandos.docs: Added "DBUS-API".

* mandos-clients.conf.xml (OPTIONS): Added "approved_by_default",
                                     "approval_delay", and
                                     "approval_duration".
* mandos.xml (D-BUS INTERFACE): Refer to the "DBUS-API" file.
  (BUGS): Remove mention of lack of a remote query interface.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2010 Teddy Hogeborn
15
 
# Copyright © 2008-2010 Björn Påhlsson
 
14
# Copyright © 2008,2009 Teddy Hogeborn
 
15
# Copyright © 2008,2009 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
81
81
        SO_BINDTODEVICE = None
82
82
 
83
83
 
84
 
version = u"1.2.3"
 
84
version = "1.0.14"
85
85
 
86
86
#logger = logging.getLogger(u'mandos')
87
87
logger = logging.Logger(u'mandos')
88
88
syslogger = (logging.handlers.SysLogHandler
89
89
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
90
 
              address = u"/dev/log"))
 
90
              address = "/dev/log"))
91
91
syslogger.setFormatter(logging.Formatter
92
92
                       (u'Mandos [%(process)d]: %(levelname)s:'
93
93
                        u' %(message)s'))
204
204
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
205
205
            logger.debug(u"Zeroconf service established.")
206
206
        elif state == avahi.ENTRY_GROUP_COLLISION:
207
 
            logger.info(u"Zeroconf service name collision.")
 
207
            logger.warning(u"Zeroconf service name collision.")
208
208
            self.rename()
209
209
        elif state == avahi.ENTRY_GROUP_FAILURE:
210
210
            logger.critical(u"Avahi: Error in group state changed %s",
240
240
    """A representation of a client host served by this server.
241
241
    
242
242
    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
 
243
    name:       string; from the config file, used in log messages and
 
244
                        D-Bus identifiers
 
245
    fingerprint: string (40 or 32 hexadecimal digits); used to
 
246
                 uniquely identify the client
 
247
    secret:     bytestring; sent verbatim (over TLS) to client
 
248
    host:       string; available for use by the checker command
 
249
    created:    datetime.datetime(); (UTC) object creation
 
250
    last_enabled: datetime.datetime(); (UTC)
 
251
    enabled:    bool()
 
252
    last_checked_ok: datetime.datetime(); (UTC) or None
 
253
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
254
                                      until this client is disabled
 
255
    interval:   datetime.timedelta(); How often to start a new checker
 
256
    disable_hook:  If set, called by disable() as disable_hook(self)
246
257
    checker:    subprocess.Popen(); a running checker process used
247
258
                                    to see if the client lives.
248
259
                                    'None' if no process is running.
249
 
    checker_callback_tag: a gobject event source tag, or None
250
 
    checker_command: string; External command which is run to check
251
 
                     if client lives.  %() expansions are done at
 
260
    checker_initiator_tag: a gobject event source tag, or None
 
261
    disable_initiator_tag: - '' -
 
262
    checker_callback_tag:  - '' -
 
263
    checker_command: string; External command which is run to check if
 
264
                     client lives.  %() expansions are done at
252
265
                     runtime with vars(self) as dict, so that for
253
266
                     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
267
    current_checker_command: string; current running checker_command
257
 
    disable_hook:  If set, called by disable() as disable_hook(self)
258
 
    disable_initiator_tag: a gobject event source tag, or None
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_approval_request: datetime.datetime(); (UTC) or None
265
 
    last_checked_ok: datetime.datetime(); (UTC) or None
266
 
    last_enabled: datetime.datetime(); (UTC)
267
 
    name:       string; from the config file, used in log messages and
268
 
                        D-Bus identifiers
269
 
    secret:     bytestring; sent verbatim (over TLS) to client
270
 
    timeout:    datetime.timedelta(); How long from last_checked_ok
271
 
                                      until this client is disabled
272
 
    runtime_expansions: Allowed attributes for runtime expansion.
 
268
    approval_delay: datetime.timedelta(); Time to wait for approval
 
269
    _approved:   bool(); 'None' if not yet approved/disapproved
 
270
    approval_duration: datetime.timedelta(); Duration of one approval
273
271
    """
274
272
    
275
 
    runtime_expansions = (u"approval_delay", u"approval_duration",
276
 
                          u"created", u"enabled", u"fingerprint",
277
 
                          u"host", u"interval", u"last_checked_ok",
278
 
                          u"last_enabled", u"name", u"timeout")
279
 
    
280
273
    @staticmethod
281
274
    def _timedelta_to_milliseconds(td):
282
275
        "Convert a datetime.timedelta() to milliseconds"
314
307
        elif u"secfile" in config:
315
308
            with open(os.path.expanduser(os.path.expandvars
316
309
                                         (config[u"secfile"])),
317
 
                      u"rb") as secfile:
 
310
                      "rb") as secfile:
318
311
                self.secret = secfile.read()
319
312
        else:
320
313
            raise TypeError(u"No secret or secfile for client %s"
322
315
        self.host = config.get(u"host", u"")
323
316
        self.created = datetime.datetime.utcnow()
324
317
        self.enabled = False
325
 
        self.last_approval_request = None
326
318
        self.last_enabled = None
327
319
        self.last_checked_ok = None
328
320
        self.timeout = string_to_delta(config[u"timeout"])
372
364
    
373
365
    def disable(self, quiet=True):
374
366
        """Disable this client."""
375
 
        if not getattr(self, u"enabled", False):
 
367
        if not getattr(self, "enabled", False):
376
368
            return False
377
369
        if not quiet:
378
370
            self.send_changedstate()
424
416
                                      (self.timeout_milliseconds(),
425
417
                                       self.disable))
426
418
    
427
 
    def need_approval(self):
428
 
        self.last_approval_request = datetime.datetime.utcnow()
429
 
    
430
419
    def start_checker(self):
431
420
        """Start a new checker subprocess if one is not running.
432
421
        
461
450
                command = self.checker_command % self.host
462
451
            except TypeError:
463
452
                # Escape attributes for the shell
464
 
                escaped_attrs = dict(
465
 
                    (attr,
466
 
                     re.escape(unicode(str(getattr(self, attr, u"")),
467
 
                                       errors=
468
 
                                       u'replace')))
469
 
                    for attr in
470
 
                    self.runtime_expansions)
471
 
 
 
453
                escaped_attrs = dict((key,
 
454
                                      re.escape(unicode(str(val),
 
455
                                                        errors=
 
456
                                                        u'replace')))
 
457
                                     for key, val in
 
458
                                     vars(self).iteritems())
472
459
                try:
473
460
                    command = self.checker_command % escaped_attrs
474
461
                except TypeError, error:
663
650
    
664
651
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
665
652
                         out_signature=u"s",
666
 
                         path_keyword=u'object_path',
667
 
                         connection_keyword=u'connection')
 
653
                         path_keyword='object_path',
 
654
                         connection_keyword='connection')
668
655
    def Introspect(self, object_path, connection):
669
656
        """Standard D-Bus method, overloaded to insert property tags.
670
657
        """
716
703
    dbus_object_path: dbus.ObjectPath
717
704
    bus: dbus.SystemBus()
718
705
    """
719
 
    
720
 
    runtime_expansions = (Client.runtime_expansions
721
 
                          + (u"dbus_object_path",))
722
 
    
723
706
    # dbus.service.Object doesn't use super(), so we can't either.
724
707
    
725
708
    def __init__(self, bus = None, *args, **kwargs):
728
711
        Client.__init__(self, *args, **kwargs)
729
712
        # Only now, when this client is initialized, can it show up on
730
713
        # the D-Bus
731
 
        client_object_name = unicode(self.name).translate(
732
 
            {ord(u"."): ord(u"_"),
733
 
             ord(u"-"): ord(u"_")})
734
714
        self.dbus_object_path = (dbus.ObjectPath
735
 
                                 (u"/clients/" + client_object_name))
 
715
                                 (u"/clients/"
 
716
                                  + self.name.replace(u".", u"_")))
736
717
        DBusObjectWithProperties.__init__(self, self.bus,
737
718
                                          self.dbus_object_path)
738
719
        
742
723
        old_value = self._approvals_pending
743
724
        self._approvals_pending = value
744
725
        bval = bool(value)
745
 
        if (hasattr(self, u"dbus_object_path")
 
726
        if (hasattr(self, "dbus_object_path")
746
727
            and bval is not bool(old_value)):
747
728
            dbus_bool = dbus.Boolean(bval, variant_level=1)
748
729
            self.PropertyChanged(dbus.String(u"ApprovalPending"),
820
801
                                    variant_level=1)))
821
802
        return r
822
803
    
823
 
    def need_approval(self, *args, **kwargs):
824
 
        r = Client.need_approval(self, *args, **kwargs)
825
 
        # Emit D-Bus signal
826
 
        self.PropertyChanged(
827
 
            dbus.String(u"LastApprovalRequest"),
828
 
            (self._datetime_to_dbus(self.last_approval_request,
829
 
                                    variant_level=1)))
830
 
        return r
831
 
    
832
804
    def start_checker(self, *args, **kwargs):
833
805
        old_checker = self.checker
834
806
        if self.checker is not None:
909
881
    @dbus.service.signal(_interface, signature=u"tb")
910
882
    def NeedApproval(self, timeout, default):
911
883
        "D-Bus signal"
912
 
        return self.need_approval()
 
884
        pass
913
885
    
914
886
    ## Methods
915
 
    
 
887
 
916
888
    # Approve - method
917
889
    @dbus.service.method(_interface, in_signature=u"b")
918
890
    def Approve(self, value):
919
891
        self.approve(value)
920
 
    
 
892
 
921
893
    # CheckedOK - method
922
894
    @dbus.service.method(_interface)
923
895
    def CheckedOK(self):
1043
1015
        return dbus.String(self._datetime_to_dbus(self
1044
1016
                                                  .last_checked_ok))
1045
1017
    
1046
 
    # LastApprovalRequest - property
1047
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
1048
 
    def LastApprovalRequest_dbus_property(self):
1049
 
        if self.last_approval_request is None:
1050
 
            return dbus.String(u"")
1051
 
        return dbus.String(self.
1052
 
                           _datetime_to_dbus(self
1053
 
                                             .last_approval_request))
1054
 
    
1055
1018
    # Timeout - property
1056
1019
    @dbus_service_property(_interface, signature=u"t",
1057
1020
                           access=u"readwrite")
1138
1101
class ProxyClient(object):
1139
1102
    def __init__(self, child_pipe, fpr, address):
1140
1103
        self._pipe = child_pipe
1141
 
        self._pipe.send((u'init', fpr, address))
 
1104
        self._pipe.send(('init', fpr, address))
1142
1105
        if not self._pipe.recv():
1143
1106
            raise KeyError()
1144
1107
 
1145
1108
    def __getattribute__(self, name):
1146
 
        if(name == u'_pipe'):
 
1109
        if(name == '_pipe'):
1147
1110
            return super(ProxyClient, self).__getattribute__(name)
1148
 
        self._pipe.send((u'getattr', name))
 
1111
        self._pipe.send(('getattr', name))
1149
1112
        data = self._pipe.recv()
1150
 
        if data[0] == u'data':
 
1113
        if data[0] == 'data':
1151
1114
            return data[1]
1152
 
        if data[0] == u'function':
 
1115
        if data[0] == 'function':
1153
1116
            def func(*args, **kwargs):
1154
 
                self._pipe.send((u'funcall', name, args, kwargs))
 
1117
                self._pipe.send(('funcall', name, args, kwargs))
1155
1118
                return self._pipe.recv()[1]
1156
1119
            return func
1157
1120
 
1158
1121
    def __setattr__(self, name, value):
1159
 
        if(name == u'_pipe'):
 
1122
        if(name == '_pipe'):
1160
1123
            return super(ProxyClient, self).__setattr__(name, value)
1161
 
        self._pipe.send((u'setattr', name, value))
 
1124
        self._pipe.send(('setattr', name, value))
1162
1125
 
1163
1126
 
1164
1127
class ClientHandler(socketserver.BaseRequestHandler, object):
1244
1207
                                       client.name)
1245
1208
                        if self.server.use_dbus:
1246
1209
                            # Emit D-Bus signal
1247
 
                            client.Rejected(u"Disabled")                    
 
1210
                            client.Rejected("Disabled")                    
1248
1211
                        return
1249
1212
                    
1250
1213
                    if client._approved or not client.approval_delay:
1263
1226
                                       client.name)
1264
1227
                        if self.server.use_dbus:
1265
1228
                            # Emit D-Bus signal
1266
 
                            client.Rejected(u"Denied")
 
1229
                            client.Rejected("Denied")
1267
1230
                        return
1268
1231
                    
1269
1232
                    #wait until timeout or approved
1275
1238
                    time2 = datetime.datetime.now()
1276
1239
                    if (time2 - time) >= delay:
1277
1240
                        if not client.approved_by_default:
1278
 
                            logger.warning(u"Client %s timed out while"
1279
 
                                           u" waiting for approval",
 
1241
                            logger.warning("Client %s timed out while"
 
1242
                                           " waiting for approval",
1280
1243
                                           client.name)
1281
1244
                            if self.server.use_dbus:
1282
1245
                                # Emit D-Bus signal
1283
 
                                client.Rejected(u"Approval timed out")
 
1246
                                client.Rejected("Timed out")
1284
1247
                            return
1285
1248
                        else:
1286
1249
                            break
1292
1255
                    try:
1293
1256
                        sent = session.send(client.secret[sent_size:])
1294
1257
                    except (gnutls.errors.GNUTLSError), error:
1295
 
                        logger.warning(u"gnutls send failed")
 
1258
                        logger.warning("gnutls send failed")
1296
1259
                        return
1297
1260
                    logger.debug(u"Sent: %d, remaining: %d",
1298
1261
                                 sent, len(client.secret)
1312
1275
                try:
1313
1276
                    session.bye()
1314
1277
                except (gnutls.errors.GNUTLSError), error:
1315
 
                    logger.warning(u"GnuTLS bye failed")
 
1278
                    logger.warning("GnuTLS bye failed")
1316
1279
    
1317
1280
    @staticmethod
1318
1281
    def peer_certificate(session):
1520
1483
                                    # broken, usually for pipes and
1521
1484
                                    # sockets).
1522
1485
            }
1523
 
        conditions_string = u' | '.join(name
 
1486
        conditions_string = ' | '.join(name
1524
1487
                                       for cond, name in
1525
1488
                                       condition_names.iteritems()
1526
1489
                                       if cond & condition)
 
1490
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
 
1491
                     conditions_string)
 
1492
 
1527
1493
        # error or the other end of multiprocessing.Pipe has closed
1528
1494
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1529
1495
            return False
1530
1496
        
1531
1497
        # Read a request from the child
1532
1498
        request = parent_pipe.recv()
 
1499
        logger.debug(u"IPC request: %s", repr(request))
1533
1500
        command = request[0]
1534
1501
        
1535
 
        if command == u'init':
 
1502
        if command == 'init':
1536
1503
            fpr = request[1]
1537
1504
            address = request[2]
1538
1505
            
1545
1512
                               u"dress: %s", fpr, address)
1546
1513
                if self.use_dbus:
1547
1514
                    # Emit D-Bus signal
1548
 
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
 
1515
                    mandos_dbus_service.ClientNotFound(fpr, address)
1549
1516
                parent_pipe.send(False)
1550
1517
                return False
1551
1518
            
1557
1524
            parent_pipe.send(True)
1558
1525
            # remove the old hook in favor of the new above hook on same fileno
1559
1526
            return False
1560
 
        if command == u'funcall':
 
1527
        if command == 'funcall':
1561
1528
            funcname = request[1]
1562
1529
            args = request[2]
1563
1530
            kwargs = request[3]
1564
1531
            
1565
 
            parent_pipe.send((u'data', getattr(client_object, funcname)(*args, **kwargs)))
 
1532
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1566
1533
 
1567
 
        if command == u'getattr':
 
1534
        if command == 'getattr':
1568
1535
            attrname = request[1]
1569
1536
            if callable(client_object.__getattribute__(attrname)):
1570
 
                parent_pipe.send((u'function',))
 
1537
                parent_pipe.send(('function',))
1571
1538
            else:
1572
 
                parent_pipe.send((u'data', client_object.__getattribute__(attrname)))
 
1539
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1573
1540
        
1574
 
        if command == u'setattr':
 
1541
        if command == 'setattr':
1575
1542
            attrname = request[1]
1576
1543
            value = request[2]
1577
1544
            setattr(client_object, attrname, value)
1672
1639
    ##################################################################
1673
1640
    # Parsing of options, both command line and config file
1674
1641
    
1675
 
    parser = optparse.OptionParser(version = u"%%prog %s" % version)
1676
 
    parser.add_option(u"-i", u"--interface", type=u"string",
1677
 
                      metavar=u"IF", help=u"Bind to interface IF")
1678
 
    parser.add_option(u"-a", u"--address", type=u"string",
 
1642
    parser = optparse.OptionParser(version = "%%prog %s" % version)
 
1643
    parser.add_option("-i", u"--interface", type=u"string",
 
1644
                      metavar="IF", help=u"Bind to interface IF")
 
1645
    parser.add_option("-a", u"--address", type=u"string",
1679
1646
                      help=u"Address to listen for requests on")
1680
 
    parser.add_option(u"-p", u"--port", type=u"int",
 
1647
    parser.add_option("-p", u"--port", type=u"int",
1681
1648
                      help=u"Port number to receive requests on")
1682
 
    parser.add_option(u"--check", action=u"store_true",
 
1649
    parser.add_option("--check", action=u"store_true",
1683
1650
                      help=u"Run self-test")
1684
 
    parser.add_option(u"--debug", action=u"store_true",
 
1651
    parser.add_option("--debug", action=u"store_true",
1685
1652
                      help=u"Debug mode; run in foreground and log to"
1686
1653
                      u" terminal")
1687
 
    parser.add_option(u"--debuglevel", type=u"string", metavar="LEVEL",
 
1654
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
1688
1655
                      help=u"Debug level for stdout output")
1689
 
    parser.add_option(u"--priority", type=u"string", help=u"GnuTLS"
 
1656
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1690
1657
                      u" priority string (see GnuTLS documentation)")
1691
 
    parser.add_option(u"--servicename", type=u"string",
 
1658
    parser.add_option("--servicename", type=u"string",
1692
1659
                      metavar=u"NAME", help=u"Zeroconf service name")
1693
 
    parser.add_option(u"--configdir", type=u"string",
 
1660
    parser.add_option("--configdir", type=u"string",
1694
1661
                      default=u"/etc/mandos", metavar=u"DIR",
1695
1662
                      help=u"Directory to search for configuration"
1696
1663
                      u" files")
1697
 
    parser.add_option(u"--no-dbus", action=u"store_false",
 
1664
    parser.add_option("--no-dbus", action=u"store_false",
1698
1665
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1699
1666
                      u" system bus interface")
1700
 
    parser.add_option(u"--no-ipv6", action=u"store_false",
 
1667
    parser.add_option("--no-ipv6", action=u"store_false",
1701
1668
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1702
1669
    options = parser.parse_args()[0]
1703
1670
    
1730
1697
    for option in (u"debug", u"use_dbus", u"use_ipv6"):
1731
1698
        server_settings[option] = server_config.getboolean(u"DEFAULT",
1732
1699
                                                           option)
1733
 
    if server_settings[u"port"]:
1734
 
        server_settings[u"port"] = server_config.getint(u"DEFAULT",
 
1700
    if server_settings["port"]:
 
1701
        server_settings["port"] = server_config.getint(u"DEFAULT",
1735
1702
                                                       u"port")
1736
1703
    del server_config
1737
1704
    
1788
1755
                              gnutls_priority=
1789
1756
                              server_settings[u"priority"],
1790
1757
                              use_dbus=use_dbus)
1791
 
    if not debug:
1792
 
        pidfilename = u"/var/run/mandos.pid"
1793
 
        try:
1794
 
            pidfile = open(pidfilename, u"w")
1795
 
        except IOError:
1796
 
            logger.error(u"Could not open file %r", pidfilename)
 
1758
    pidfilename = u"/var/run/mandos.pid"
 
1759
    try:
 
1760
        pidfile = open(pidfilename, u"w")
 
1761
    except IOError:
 
1762
        logger.error(u"Could not open file %r", pidfilename)
1797
1763
    
1798
1764
    try:
1799
1765
        uid = pwd.getpwnam(u"_mandos").pw_uid
1847
1813
        # No console logging
1848
1814
        logger.removeHandler(console)
1849
1815
    
1850
 
    # Need to fork before connecting to D-Bus
1851
 
    if not debug:
1852
 
        # Close all input and output, do double fork, etc.
1853
 
        daemon()
1854
1816
    
1855
1817
    global main_loop
1856
1818
    # From the Avahi example code
1871
1833
    service = AvahiService(name = server_settings[u"servicename"],
1872
1834
                           servicetype = u"_mandos._tcp",
1873
1835
                           protocol = protocol, bus = bus)
1874
 
    if server_settings[u"interface"]:
 
1836
    if server_settings["interface"]:
1875
1837
        service.interface = (if_nametoindex
1876
1838
                             (str(server_settings[u"interface"])))
1877
 
    
 
1839
 
 
1840
    if not debug:
 
1841
        # Close all input and output, do double fork, etc.
 
1842
        daemon()
 
1843
        
1878
1844
    global multiprocessing_manager
1879
1845
    multiprocessing_manager = multiprocessing.Manager()
1880
1846
    
1883
1849
        client_class = functools.partial(ClientDBus, bus = bus)
1884
1850
    def client_config_items(config, section):
1885
1851
        special_settings = {
1886
 
            u"approved_by_default":
 
1852
            "approved_by_default":
1887
1853
                lambda: config.getboolean(section,
1888
 
                                          u"approved_by_default"),
 
1854
                                          "approved_by_default"),
1889
1855
            }
1890
1856
        for name, value in config.items(section):
1891
1857
            try:
1901
1867
    if not tcp_server.clients:
1902
1868
        logger.warning(u"No clients defined")
1903
1869
        
 
1870
    try:
 
1871
        with pidfile:
 
1872
            pid = os.getpid()
 
1873
            pidfile.write(str(pid) + "\n")
 
1874
        del pidfile
 
1875
    except IOError:
 
1876
        logger.error(u"Could not write to file %r with PID %d",
 
1877
                     pidfilename, pid)
 
1878
    except NameError:
 
1879
        # "pidfile" was never created
 
1880
        pass
 
1881
    del pidfilename
 
1882
    
1904
1883
    if not debug:
1905
 
        try:
1906
 
            with pidfile:
1907
 
                pid = os.getpid()
1908
 
                pidfile.write(str(pid) + u"\n".encode("utf-8"))
1909
 
            del pidfile
1910
 
        except IOError:
1911
 
            logger.error(u"Could not write to file %r with PID %d",
1912
 
                         pidfilename, pid)
1913
 
        except NameError:
1914
 
            # "pidfile" was never created
1915
 
            pass
1916
 
        del pidfilename
1917
 
        
1918
1884
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1919
 
 
1920
1885
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1921
1886
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1922
1887
    
2006
1971
    service.port = tcp_server.socket.getsockname()[1]
2007
1972
    if use_ipv6:
2008
1973
        logger.info(u"Now listening on address %r, port %d,"
2009
 
                    u" flowinfo %d, scope_id %d"
 
1974
                    " flowinfo %d, scope_id %d"
2010
1975
                    % tcp_server.socket.getsockname())
2011
1976
    else:                       # IPv4
2012
1977
        logger.info(u"Now listening on address %r, port %d"
2043
2008
    # Must run before the D-Bus bus name gets deregistered
2044
2009
    cleanup()
2045
2010
 
2046
 
if __name__ == u'__main__':
 
2011
if __name__ == '__main__':
2047
2012
    main()