/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk
3 by Björn Påhlsson
Python based server
1
#!/usr/bin/python
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2
# -*- mode: python; coding: utf-8 -*-
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
3
# 
4
# Mandos server - give out binary blobs to connecting clients.
5
# 
6
# This program is partly derived from an example program for an Avahi
7
# service publisher, downloaded from
8
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
336 by Teddy Hogeborn
Code cleanup.
9
# methods "add", "remove", "server_state_changed",
10
# "entry_group_state_changed", "cleanup", and "activate" in the
11
# "AvahiService" class, and some lines in "main".
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
12
# 
28 by Teddy Hogeborn
* server.conf: New file.
13
# Everything else is
466 by Teddy Hogeborn
Update copyright year to "2011" wherever appropriate.
14
# Copyright © 2008-2011 Teddy Hogeborn
15
# Copyright © 2008-2011 Björn Påhlsson
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
16
# 
17
# This program is free software: you can redistribute it and/or modify
18
# it under the terms of the GNU General Public License as published by
19
# the Free Software Foundation, either version 3 of the License, or
20
# (at your option) any later version.
21
#
22
#     This program is distributed in the hope that it will be useful,
23
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
24
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
#     GNU General Public License for more details.
26
# 
27
# You should have received a copy of the GNU General Public License
109 by Teddy Hogeborn
* .bzrignore: New.
28
# along with this program.  If not, see
29
# <http://www.gnu.org/licenses/>.
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
30
# 
28 by Teddy Hogeborn
* server.conf: New file.
31
# Contact the authors at <mandos@fukt.bsnet.se>.
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
32
# 
3 by Björn Påhlsson
Python based server
33
463.1.5 by teddy at bsnet
* mandos: Use unicode string literals.
34
from __future__ import (division, absolute_import, print_function,
35
                        unicode_literals)
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
36
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
37
import SocketServer as socketserver
3 by Björn Påhlsson
Python based server
38
import socket
474 by teddy at bsnet
* mandos: Use the new argparse library instead of optparse.
39
import argparse
3 by Björn Påhlsson
Python based server
40
import datetime
41
import errno
42
import gnutls.crypto
43
import gnutls.connection
44
import gnutls.errors
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
45
import gnutls.library.functions
46
import gnutls.library.constants
47
import gnutls.library.types
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
48
import ConfigParser as configparser
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
49
import sys
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
50
import re
51
import os
52
import signal
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
53
import subprocess
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
54
import atexit
55
import stat
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
56
import logging
57
import logging.handlers
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
58
import pwd
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
59
import contextlib
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
60
import struct
61
import fcntl
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
62
import functools
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
63
import cPickle as pickle
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
64
import multiprocessing
5 by Teddy Hogeborn
* server.py (server_metaclass): New.
65
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
66
import dbus
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
67
import dbus.service
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
68
import gobject
69
import avahi
70
from dbus.mainloop.glib import DBusGMainLoop
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
71
import ctypes
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
72
import ctypes.util
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
73
import xml.dom.minidom
74
import inspect
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
75
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
76
try:
77
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
78
except AttributeError:
79
    try:
80
        from IN import SO_BINDTODEVICE
81
    except ImportError:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
82
        SO_BINDTODEVICE = None
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
83
84
237.4.16 by Teddy Hogeborn
* Makefile (version): Changed to "1.3.1".
85
version = "1.3.1"
13 by Björn Påhlsson
Added following support:
86
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
89
syslogger = (logging.handlers.SysLogHandler
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
463.1.6 by teddy at bsnet
* mandos: Bug fix: pass str("/dev/log") to logging.SysLogHandler(),
91
              address = str("/dev/log")))
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
92
syslogger.setFormatter(logging.Formatter
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
93
                       ('Mandos [%(process)d]: %(levelname)s:'
94
                        ' %(message)s'))
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
95
logger.addHandler(syslogger)
13 by Björn Påhlsson
Added following support:
96
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
97
console = logging.StreamHandler()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
99
                                       ' %(levelname)s:'
100
                                       ' %(message)s'))
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
101
logger.addHandler(console)
28 by Teddy Hogeborn
* server.conf: New file.
102
103
class AvahiError(Exception):
242 by Teddy Hogeborn
* mandos (AvahiError): Converted to use unicode. All users changed.
104
    def __init__(self, value, *args, **kwargs):
28 by Teddy Hogeborn
* server.conf: New file.
105
        self.value = value
242 by Teddy Hogeborn
* mandos (AvahiError): Converted to use unicode. All users changed.
106
        super(AvahiError, self).__init__(value, *args, **kwargs)
107
    def __unicode__(self):
108
        return unicode(repr(self.value))
28 by Teddy Hogeborn
* server.conf: New file.
109
110
class AvahiServiceError(AvahiError):
111
    pass
112
113
class AvahiGroupError(AvahiError):
114
    pass
115
116
117
class AvahiService(object):
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
118
    """An Avahi (Zeroconf) service.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
119
    
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
120
    Attributes:
28 by Teddy Hogeborn
* server.conf: New file.
121
    interface: integer; avahi.IF_UNSPEC or an interface index.
122
               Used to optionally bind to the specified interface.
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
123
    name: string; Example: 'Mandos'
124
    type: string; Example: '_mandos._tcp'.
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
125
                  See <http://www.dns-sd.org/ServiceTypes.html>
126
    port: integer; what port to announce
127
    TXT: list of strings; TXT record for the service
128
    domain: string; Domain to publish on, default to .local if empty.
129
    host: string; Host to publish records for, default is localhost
130
    max_renames: integer; maximum number of renames
131
    rename_count: integer; counter so we only rename after collisions
132
                  a sensible number of times
336 by Teddy Hogeborn
Code cleanup.
133
    group: D-Bus Entry Group
134
    server: D-Bus Server
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
135
    bus: dbus.SystemBus()
28 by Teddy Hogeborn
* server.conf: New file.
136
    """
137
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
138
                 servicetype = None, port = None, TXT = None,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
139
                 domain = "", host = "", max_renames = 32768,
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
140
                 protocol = avahi.PROTO_UNSPEC, bus = None):
28 by Teddy Hogeborn
* server.conf: New file.
141
        self.interface = interface
142
        self.name = name
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
143
        self.type = servicetype
28 by Teddy Hogeborn
* server.conf: New file.
144
        self.port = port
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
145
        self.TXT = TXT if TXT is not None else []
28 by Teddy Hogeborn
* server.conf: New file.
146
        self.domain = domain
147
        self.host = host
148
        self.rename_count = 0
76 by Teddy Hogeborn
* plugins.d/password-request.c (init_gnutls_global): Renamed
149
        self.max_renames = max_renames
314 by Teddy Hogeborn
Support not using IPv6 in server:
150
        self.protocol = protocol
336 by Teddy Hogeborn
Code cleanup.
151
        self.group = None       # our entry group
152
        self.server = None
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
153
        self.bus = bus
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
154
        self.entry_group_state_changed_match = None
28 by Teddy Hogeborn
* server.conf: New file.
155
    def rename(self):
156
        """Derived from the Avahi example code"""
157
        if self.rename_count >= self.max_renames:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
158
            logger.critical("No suitable Zeroconf service name found"
159
                            " after %i retries, exiting.",
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
160
                            self.rename_count)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
161
            raise AvahiServiceError("Too many renames")
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
162
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
163
        logger.info("Changing Zeroconf service name to %r ...",
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
164
                    self.name)
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
165
        syslogger.setFormatter(logging.Formatter
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
166
                               ('Mandos (%s) [%%(process)d]:'
167
                                ' %%(levelname)s: %%(message)s'
327 by Teddy Hogeborn
Merge from pipe IPC branch.
168
                                % self.name))
28 by Teddy Hogeborn
* server.conf: New file.
169
        self.remove()
24.1.160 by Björn Påhlsson
fixed bug with local name collisions after a non-local name collision
170
        try:
171
            self.add()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
172
        except dbus.exceptions.DBusException as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
173
            logger.critical("DBusException: %s", error)
24.1.160 by Björn Påhlsson
fixed bug with local name collisions after a non-local name collision
174
            self.cleanup()
175
            os._exit(1)
28 by Teddy Hogeborn
* server.conf: New file.
176
        self.rename_count += 1
177
    def remove(self):
178
        """Derived from the Avahi example code"""
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
179
        if self.entry_group_state_changed_match is not None:
180
            self.entry_group_state_changed_match.remove()
181
            self.entry_group_state_changed_match = None
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
182
        if self.group is not None:
183
            self.group.Reset()
28 by Teddy Hogeborn
* server.conf: New file.
184
    def add(self):
185
        """Derived from the Avahi example code"""
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
186
        self.remove()
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
187
        if self.group is None:
188
            self.group = dbus.Interface(
189
                self.bus.get_object(avahi.DBUS_NAME,
190
                                    self.server.EntryGroupNew()),
191
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
192
        self.entry_group_state_changed_match = (
193
            self.group.connect_to_signal(
194
                'StateChanged', self .entry_group_state_changed))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
195
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
336 by Teddy Hogeborn
Code cleanup.
196
                     self.name, self.type)
197
        self.group.AddService(
198
            self.interface,
199
            self.protocol,
200
            dbus.UInt32(0),     # flags
201
            self.name, self.type,
202
            self.domain, self.host,
203
            dbus.UInt16(self.port),
204
            avahi.string_array_to_txt_array(self.TXT))
205
        self.group.Commit()
206
    def entry_group_state_changed(self, state, error):
207
        """Derived from the Avahi example code"""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
208
        logger.debug("Avahi entry group state change: %i", state)
336 by Teddy Hogeborn
Code cleanup.
209
        
210
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
211
            logger.debug("Zeroconf service established.")
336 by Teddy Hogeborn
Code cleanup.
212
        elif state == avahi.ENTRY_GROUP_COLLISION:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
213
            logger.info("Zeroconf service name collision.")
336 by Teddy Hogeborn
Code cleanup.
214
            self.rename()
215
        elif state == avahi.ENTRY_GROUP_FAILURE:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
216
            logger.critical("Avahi: Error in group state changed %s",
336 by Teddy Hogeborn
Code cleanup.
217
                            unicode(error))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
218
            raise AvahiGroupError("State changed: %s"
336 by Teddy Hogeborn
Code cleanup.
219
                                  % unicode(error))
220
    def cleanup(self):
221
        """Derived from the Avahi example code"""
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
222
        if self.group is not None:
223
            try:
224
                self.group.Free()
225
            except (dbus.exceptions.UnknownMethodException,
226
                    dbus.exceptions.DBusException) as e:
227
                pass
228
            self.group = None
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
229
        self.remove()
230
    def server_state_changed(self, state, error=None):
336 by Teddy Hogeborn
Code cleanup.
231
        """Derived from the Avahi example code"""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
232
        logger.debug("Avahi server state change: %i", state)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
233
        bad_states = { avahi.SERVER_INVALID:
234
                           "Zeroconf server invalid",
235
                       avahi.SERVER_REGISTERING: None,
236
                       avahi.SERVER_COLLISION:
237
                           "Zeroconf server name collision",
238
                       avahi.SERVER_FAILURE:
239
                           "Zeroconf server failure" }
240
        if state in bad_states:
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
241
            if bad_states[state] is not None:
242
                if error is None:
243
                    logger.error(bad_states[state])
244
                else:
245
                    logger.error(bad_states[state] + ": %r", error)
246
            self.cleanup()
336 by Teddy Hogeborn
Code cleanup.
247
        elif state == avahi.SERVER_RUNNING:
248
            self.add()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
249
        else:
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
250
            if error is None:
251
                logger.debug("Unknown state: %r", state)
252
            else:
253
                logger.debug("Unknown state: %r: %r", state, error)
336 by Teddy Hogeborn
Code cleanup.
254
    def activate(self):
255
        """Derived from the Avahi example code"""
256
        if self.server is None:
257
            self.server = dbus.Interface(
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
258
                self.bus.get_object(avahi.DBUS_NAME,
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
259
                                    avahi.DBUS_PATH_SERVER,
260
                                    follow_name_owner_changes=True),
336 by Teddy Hogeborn
Code cleanup.
261
                avahi.DBUS_INTERFACE_SERVER)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
262
        self.server.connect_to_signal("StateChanged",
336 by Teddy Hogeborn
Code cleanup.
263
                                 self.server_state_changed)
264
        self.server_state_changed(self.server.GetState())
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
265
266
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
267
class Client(object):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
268
    """A representation of a client host served by this server.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
269
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
270
    Attributes:
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
271
    _approved:   bool(); 'None' if not yet approved/disapproved
272
    approval_delay: datetime.timedelta(); Time to wait for approval
273
    approval_duration: datetime.timedelta(); Duration of one approval
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
274
    checker:    subprocess.Popen(); a running checker process used
275
                                    to see if the client lives.
276
                                    'None' if no process is running.
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
277
    checker_callback_tag: a gobject event source tag, or None
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
278
    checker_command: string; External command which is run to check
279
                     if client lives.  %() expansions are done at
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
280
                     runtime with vars(self) as dict, so that for
281
                     instance %(name)s can be used in the command.
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
282
    checker_initiator_tag: a gobject event source tag, or None
283
    created:    datetime.datetime(); (UTC) object creation
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
284
    current_checker_command: string; current running checker_command
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
285
    disable_hook:  If set, called by disable() as disable_hook(self)
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
286
    disable_initiator_tag: a gobject event source tag, or None
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
287
    enabled:    bool()
288
    fingerprint: string (40 or 32 hexadecimal digits); used to
289
                 uniquely identify the client
290
    host:       string; available for use by the checker command
291
    interval:   datetime.timedelta(); How often to start a new checker
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
292
    last_approval_request: datetime.datetime(); (UTC) or None
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
293
    last_checked_ok: datetime.datetime(); (UTC) or None
294
    last_enabled: datetime.datetime(); (UTC)
295
    name:       string; from the config file, used in log messages and
296
                        D-Bus identifiers
297
    secret:     bytestring; sent verbatim (over TLS) to client
298
    timeout:    datetime.timedelta(); How long from last_checked_ok
299
                                      until this client is disabled
24.1.179 by Björn Påhlsson
New feature:
300
    extended_timeout:   extra long timeout when password has been sent
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
301
    runtime_expansions: Allowed attributes for runtime expansion.
24.1.179 by Björn Påhlsson
New feature:
302
    expire:     datetime.datetime(); time (UTC) when a client will be
303
                disabled, or None
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
304
    """
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
305
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
306
    runtime_expansions = ("approval_delay", "approval_duration",
307
                          "created", "enabled", "fingerprint",
308
                          "host", "interval", "last_checked_ok",
309
                          "last_enabled", "name", "timeout")
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
310
    
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
311
    @staticmethod
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
312
    def _timedelta_to_milliseconds(td):
313
        "Convert a datetime.timedelta() to milliseconds"
314
        return ((td.days * 24 * 60 * 60 * 1000)
315
                + (td.seconds * 1000)
316
                + (td.microseconds // 1000))
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
317
    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
318
    def timeout_milliseconds(self):
319
        "Return the 'timeout' attribute in milliseconds"
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
320
        return self._timedelta_to_milliseconds(self.timeout)
24.1.179 by Björn Påhlsson
New feature:
321
322
    def extended_timeout_milliseconds(self):
323
        "Return the 'extended_timeout' attribute in milliseconds"
324
        return self._timedelta_to_milliseconds(self.extended_timeout)    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
325
    
326
    def interval_milliseconds(self):
327
        "Return the 'interval' attribute in milliseconds"
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
328
        return self._timedelta_to_milliseconds(self.interval)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
329
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
330
    def approval_delay_milliseconds(self):
331
        return self._timedelta_to_milliseconds(self.approval_delay)
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
332
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
333
    def __init__(self, name = None, disable_hook=None, config=None):
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
334
        """Note: the 'checker' key in 'config' sets the
335
        'checker_command' attribute and *not* the 'checker'
336
        attribute."""
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
337
        self.name = name
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
338
        if config is None:
339
            config = {}
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
340
        logger.debug("Creating client %r", self.name)
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
341
        # Uppercase and remove spaces from fingerprint for later
342
        # comparison purposes with return value from the fingerprint()
343
        # function
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
344
        self.fingerprint = (config["fingerprint"].upper()
345
                            .replace(" ", ""))
346
        logger.debug("  Fingerprint: %s", self.fingerprint)
347
        if "secret" in config:
348
            self.secret = config["secret"].decode("base64")
349
        elif "secfile" in config:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
350
            with open(os.path.expanduser(os.path.expandvars
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
351
                                         (config["secfile"])),
352
                      "rb") as secfile:
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
353
                self.secret = secfile.read()
3 by Björn Påhlsson
Python based server
354
        else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
355
            raise TypeError("No secret or secfile for client %s"
28 by Teddy Hogeborn
* server.conf: New file.
356
                            % self.name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
357
        self.host = config.get("host", "")
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
358
        self.created = datetime.datetime.utcnow()
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
359
        self.enabled = False
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
360
        self.last_approval_request = None
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
361
        self.last_enabled = None
28 by Teddy Hogeborn
* server.conf: New file.
362
        self.last_checked_ok = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
363
        self.timeout = string_to_delta(config["timeout"])
24.1.179 by Björn Påhlsson
New feature:
364
        self.extended_timeout = string_to_delta(config["extended_timeout"])
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
365
        self.interval = string_to_delta(config["interval"])
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
366
        self.disable_hook = disable_hook
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
367
        self.checker = None
368
        self.checker_initiator_tag = None
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
369
        self.disable_initiator_tag = None
24.1.179 by Björn Påhlsson
New feature:
370
        self.expires = None
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
371
        self.checker_callback_tag = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
372
        self.checker_command = config["checker"]
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
373
        self.current_checker_command = None
279 by Teddy Hogeborn
* mandos (Client.__init__): Disable D-Bus during init to avoid
374
        self.last_connect = None
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
375
        self._approved = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
376
        self.approved_by_default = config.get("approved_by_default",
24.2.1 by teddy at bsnet
* debian/control (mandos/Depends): Added "python-urwid".
377
                                              True)
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
378
        self.approvals_pending = 0
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
379
        self.approval_delay = string_to_delta(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
380
            config["approval_delay"])
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
381
        self.approval_duration = string_to_delta(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
382
            config["approval_duration"])
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
383
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
384
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
385
    def send_changedstate(self):
386
        self.changedstate.acquire()
387
        self.changedstate.notify_all()
388
        self.changedstate.release()
389
        
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
390
    def enable(self):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
391
        """Start this client's checker and timeout hooks"""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
392
        if getattr(self, "enabled", False):
341 by Teddy Hogeborn
Code cleanup and one bug fix.
393
            # Already enabled
394
            return
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
395
        self.send_changedstate()
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
396
        self.last_enabled = datetime.datetime.utcnow()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
397
        # Schedule a new checker to be started an 'interval' from now,
398
        # and every interval from then on.
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
399
        self.checker_initiator_tag = (gobject.timeout_add
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
400
                                      (self.interval_milliseconds(),
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
401
                                       self.start_checker))
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
402
        # Schedule a disable() when 'timeout' has passed
24.1.179 by Björn Påhlsson
New feature:
403
        self.expires = datetime.datetime.utcnow() + self.timeout
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
404
        self.disable_initiator_tag = (gobject.timeout_add
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
405
                                   (self.timeout_milliseconds(),
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
406
                                    self.disable))
407
        self.enabled = True
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
408
        # Also start a new checker *right now*.
409
        self.start_checker()
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
410
    
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
411
    def disable(self, quiet=True):
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
412
        """Disable this client."""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
413
        if not getattr(self, "enabled", False):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
414
            return False
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
415
        if not quiet:
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
416
            self.send_changedstate()
417
        if not quiet:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
418
            logger.info("Disabling client %s", self.name)
419
        if getattr(self, "disable_initiator_tag", False):
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
420
            gobject.source_remove(self.disable_initiator_tag)
421
            self.disable_initiator_tag = None
24.1.179 by Björn Påhlsson
New feature:
422
        self.expires = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
423
        if getattr(self, "checker_initiator_tag", False):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
424
            gobject.source_remove(self.checker_initiator_tag)
425
            self.checker_initiator_tag = None
426
        self.stop_checker()
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
427
        if self.disable_hook:
428
            self.disable_hook(self)
429
        self.enabled = False
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
430
        # Do not run this again if called by a gobject.timeout_add
431
        return False
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
432
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
433
    def __del__(self):
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
434
        self.disable_hook = None
435
        self.disable()
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
436
    
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
437
    def checker_callback(self, pid, condition, command):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
438
        """The checker has completed, so take appropriate actions."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
439
        self.checker_callback_tag = None
440
        self.checker = None
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
441
        if os.WIFEXITED(condition):
442
            exitstatus = os.WEXITSTATUS(condition)
443
            if exitstatus == 0:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
444
                logger.info("Checker for %(name)s succeeded",
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
445
                            vars(self))
281 by Teddy Hogeborn
* mandos (Client.bump_timeout): Renamed to "checked_ok". All callers
446
                self.checked_ok()
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
447
            else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
448
                logger.info("Checker for %(name)s failed",
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
449
                            vars(self))
450
        else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
451
            logger.warning("Checker for %(name)s crashed?",
13 by Björn Påhlsson
Added following support:
452
                           vars(self))
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
453
    
24.1.179 by Björn Påhlsson
New feature:
454
    def checked_ok(self, timeout=None):
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
455
        """Bump up the timeout for this client.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
456
        
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
457
        This should only be called when the client has been seen,
458
        alive and well.
459
        """
24.1.179 by Björn Påhlsson
New feature:
460
        if timeout is None:
461
            timeout = self.timeout
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
462
        self.last_checked_ok = datetime.datetime.utcnow()
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
463
        gobject.source_remove(self.disable_initiator_tag)
24.1.179 by Björn Påhlsson
New feature:
464
        self.expires = datetime.datetime.utcnow() + timeout
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
465
        self.disable_initiator_tag = (gobject.timeout_add
24.1.179 by Björn Påhlsson
New feature:
466
                                      (self._timedelta_to_milliseconds(timeout),
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
467
                                       self.disable))
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
468
    
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
469
    def need_approval(self):
470
        self.last_approval_request = datetime.datetime.utcnow()
471
    
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
472
    def start_checker(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
473
        """Start a new checker subprocess if one is not running.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
474
        
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
475
        If a checker already exists, leave it running and do
476
        nothing."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
477
        # The reason for not killing a running checker is that if we
478
        # did that, then if a checker (for some reason) started
479
        # running slowly and taking more than 'interval' time, the
480
        # client would inevitably timeout, since no checker would get
481
        # a chance to run to completion.  If we instead leave running
482
        # checkers alone, the checker would have to take more time
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
483
        # than 'timeout' for the client to be disabled, which is as it
484
        # should be.
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
485
        
486
        # If a checker exists, make sure it is not a zombie
383 by Teddy Hogeborn
* mandos (Client.start_checker): Bug fix: Fix race condition with
487
        try:
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
488
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
489
        except (AttributeError, OSError) as error:
383 by Teddy Hogeborn
* mandos (Client.start_checker): Bug fix: Fix race condition with
490
            if (isinstance(error, OSError)
491
                and error.errno != errno.ECHILD):
492
                raise error
493
        else:
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
494
            if pid:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
495
                logger.warning("Checker was a zombie")
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
496
                gobject.source_remove(self.checker_callback_tag)
497
                self.checker_callback(pid, status,
498
                                      self.current_checker_command)
499
        # Start a new checker if needed
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
500
        if self.checker is None:
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
501
            try:
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
502
                # In case checker_command has exactly one % operator
503
                command = self.checker_command % self.host
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
504
            except TypeError:
28 by Teddy Hogeborn
* server.conf: New file.
505
                # Escape attributes for the shell
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
506
                escaped_attrs = dict(
507
                    (attr,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
508
                     re.escape(unicode(str(getattr(self, attr, "")),
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
509
                                       errors=
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
510
                                       'replace')))
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
511
                    for attr in
512
                    self.runtime_expansions)
513
13 by Björn Påhlsson
Added following support:
514
                try:
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
515
                    command = self.checker_command % escaped_attrs
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
516
                except TypeError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
517
                    logger.error('Could not format string "%s":'
518
                                 ' %s', self.checker_command, error)
13 by Björn Påhlsson
Added following support:
519
                    return True # Try again later
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
520
            self.current_checker_command = command
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
521
            try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
522
                logger.info("Starting checker %r for %s",
44 by Teddy Hogeborn
* ca.pem: Removed.
523
                            command, self.name)
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
524
                # We don't need to redirect stdout and stderr, since
525
                # in normal mode, that is already done by daemon(),
526
                # and in debug mode we don't want to.  (Stdin is
527
                # always replaced by /dev/null.)
28 by Teddy Hogeborn
* server.conf: New file.
528
                self.checker = subprocess.Popen(command,
529
                                                close_fds=True,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
530
                                                shell=True, cwd="/")
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
531
                self.checker_callback_tag = (gobject.child_watch_add
532
                                             (self.checker.pid,
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
533
                                              self.checker_callback,
534
                                              data=command))
310 by Teddy Hogeborn
* mandos (Client.start_checker): Bug fix: Add extra check in case the
535
                # The checker may have completed before the gobject
536
                # watch was added.  Check for this.
537
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
538
                if pid:
539
                    gobject.source_remove(self.checker_callback_tag)
540
                    self.checker_callback(pid, status, command)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
541
            except OSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
542
                logger.error("Failed to start subprocess: %s",
13 by Björn Påhlsson
Added following support:
543
                             error)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
544
        # Re-run this periodically if run by gobject.timeout_add
545
        return True
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
546
    
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
547
    def stop_checker(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
548
        """Force the checker process, if any, to stop."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
549
        if self.checker_callback_tag:
550
            gobject.source_remove(self.checker_callback_tag)
551
            self.checker_callback_tag = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
552
        if getattr(self, "checker", None) is None:
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
553
            return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
554
        logger.debug("Stopping checker for %(name)s", vars(self))
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
555
        try:
556
            os.kill(self.checker.pid, signal.SIGTERM)
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
557
            #time.sleep(0.5)
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
558
            #if self.checker.poll() is None:
559
            #    os.kill(self.checker.pid, signal.SIGKILL)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
560
        except OSError as error:
28 by Teddy Hogeborn
* server.conf: New file.
561
            if error.errno != errno.ESRCH: # No such process
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
562
                raise
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
563
        self.checker = None
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
564
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
565
def dbus_service_property(dbus_interface, signature="v",
566
                          access="readwrite", byte_arrays=False):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
567
    """Decorators for marking methods of a DBusObjectWithProperties to
568
    become properties on the D-Bus.
569
    
570
    The decorated method will be called with no arguments by "Get"
571
    and with one argument by "Set".
572
    
573
    The parameters, where they are supported, are the same as
574
    dbus.service.method, except there is only "signature", since the
575
    type from Get() and the type sent to Set() is the same.
576
    """
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
577
    # Encoding deeply encoded byte arrays is not supported yet by the
578
    # "Set" method, so we fail early here:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
579
    if byte_arrays and signature != "ay":
580
        raise ValueError("Byte arrays not supported for non-'ay'"
581
                         " signature %r" % signature)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
582
    def decorator(func):
583
        func._dbus_is_property = True
584
        func._dbus_interface = dbus_interface
585
        func._dbus_signature = signature
586
        func._dbus_access = access
587
        func._dbus_name = func.__name__
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
588
        if func._dbus_name.endswith("_dbus_property"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
589
            func._dbus_name = func._dbus_name[:-14]
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
590
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
591
        return func
592
    return decorator
593
594
595
class DBusPropertyException(dbus.exceptions.DBusException):
596
    """A base class for D-Bus property-related exceptions
597
    """
598
    def __unicode__(self):
599
        return unicode(str(self))
600
601
602
class DBusPropertyAccessException(DBusPropertyException):
603
    """A property's access permissions disallows an operation.
604
    """
605
    pass
606
607
608
class DBusPropertyNotFound(DBusPropertyException):
609
    """An attempt was made to access a non-existing property.
610
    """
611
    pass
612
613
614
class DBusObjectWithProperties(dbus.service.Object):
615
    """A D-Bus object with properties.
616
617
    Classes inheriting from this can use the dbus_service_property
618
    decorator to expose methods as D-Bus properties.  It exposes the
619
    standard Get(), Set(), and GetAll() methods on the D-Bus.
620
    """
621
    
622
    @staticmethod
623
    def _is_dbus_property(obj):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
624
        return getattr(obj, "_dbus_is_property", False)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
625
    
626
    def _get_all_dbus_properties(self):
627
        """Returns a generator of (name, attribute) pairs
628
        """
629
        return ((prop._dbus_name, prop)
630
                for name, prop in
631
                inspect.getmembers(self, self._is_dbus_property))
632
    
633
    def _get_dbus_property(self, interface_name, property_name):
634
        """Returns a bound method if one exists which is a D-Bus
635
        property with the specified name and interface.
636
        """
637
        for name in (property_name,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
638
                     property_name + "_dbus_property"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
639
            prop = getattr(self, name, None)
640
            if (prop is None
641
                or not self._is_dbus_property(prop)
642
                or prop._dbus_name != property_name
643
                or (interface_name and prop._dbus_interface
644
                    and interface_name != prop._dbus_interface)):
645
                continue
646
            return prop
647
        # No such property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
648
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
649
                                   + interface_name + "."
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
650
                                   + property_name)
651
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
652
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
653
                         out_signature="v")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
654
    def Get(self, interface_name, property_name):
655
        """Standard D-Bus property Get() method, see D-Bus standard.
656
        """
657
        prop = self._get_dbus_property(interface_name, property_name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
658
        if prop._dbus_access == "write":
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
659
            raise DBusPropertyAccessException(property_name)
660
        value = prop()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
661
        if not hasattr(value, "variant_level"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
662
            return value
663
        return type(value)(value, variant_level=value.variant_level+1)
664
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
665
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
666
    def Set(self, interface_name, property_name, value):
667
        """Standard D-Bus property Set() method, see D-Bus standard.
668
        """
669
        prop = self._get_dbus_property(interface_name, property_name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
670
        if prop._dbus_access == "read":
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
671
            raise DBusPropertyAccessException(property_name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
672
        if prop._dbus_get_args_options["byte_arrays"]:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
673
            # The byte_arrays option is not supported yet on
674
            # signatures other than "ay".
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
675
            if prop._dbus_signature != "ay":
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
676
                raise ValueError
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
677
            value = dbus.ByteArray(''.join(unichr(byte)
678
                                           for byte in value))
679
        prop(value)
680
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
681
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
682
                         out_signature="a{sv}")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
683
    def GetAll(self, interface_name):
684
        """Standard D-Bus property GetAll() method, see D-Bus
685
        standard.
686
687
        Note: Will not include properties with access="write".
688
        """
689
        all = {}
690
        for name, prop in self._get_all_dbus_properties():
691
            if (interface_name
692
                and interface_name != prop._dbus_interface):
693
                # Interface non-empty but did not match
694
                continue
695
            # Ignore write-only properties
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
696
            if prop._dbus_access == "write":
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
697
                continue
698
            value = prop()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
699
            if not hasattr(value, "variant_level"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
700
                all[name] = value
701
                continue
702
            all[name] = type(value)(value, variant_level=
703
                                    value.variant_level+1)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
704
        return dbus.Dictionary(all, signature="sv")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
705
    
706
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
707
                         out_signature="s",
708
                         path_keyword='object_path',
709
                         connection_keyword='connection')
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
710
    def Introspect(self, object_path, connection):
711
        """Standard D-Bus method, overloaded to insert property tags.
712
        """
713
        xmlstring = dbus.service.Object.Introspect(self, object_path,
386 by Teddy Hogeborn
* mandos (DBusObjectWithProperties.Introspect): Add the name
714
                                                   connection)
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
715
        try:
716
            document = xml.dom.minidom.parseString(xmlstring)
717
            def make_tag(document, name, prop):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
718
                e = document.createElement("property")
719
                e.setAttribute("name", name)
720
                e.setAttribute("type", prop._dbus_signature)
721
                e.setAttribute("access", prop._dbus_access)
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
722
                return e
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
723
            for if_tag in document.getElementsByTagName("interface"):
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
724
                for tag in (make_tag(document, name, prop)
725
                            for name, prop
726
                            in self._get_all_dbus_properties()
727
                            if prop._dbus_interface
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
728
                            == if_tag.getAttribute("name")):
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
729
                    if_tag.appendChild(tag)
730
                # Add the names to the return values for the
731
                # "org.freedesktop.DBus.Properties" methods
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
732
                if (if_tag.getAttribute("name")
733
                    == "org.freedesktop.DBus.Properties"):
734
                    for cn in if_tag.getElementsByTagName("method"):
735
                        if cn.getAttribute("name") == "Get":
736
                            for arg in cn.getElementsByTagName("arg"):
737
                                if (arg.getAttribute("direction")
738
                                    == "out"):
739
                                    arg.setAttribute("name", "value")
740
                        elif cn.getAttribute("name") == "GetAll":
741
                            for arg in cn.getElementsByTagName("arg"):
742
                                if (arg.getAttribute("direction")
743
                                    == "out"):
744
                                    arg.setAttribute("name", "props")
745
            xmlstring = document.toxml("utf-8")
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
746
            document.unlink()
747
        except (AttributeError, xml.dom.DOMException,
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
748
                xml.parsers.expat.ExpatError) as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
749
            logger.error("Failed to override Introspection method",
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
750
                         error)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
751
        return xmlstring
752
753
754
class ClientDBus(Client, DBusObjectWithProperties):
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
755
    """A Client class using D-Bus
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
756
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
757
    Attributes:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
758
    dbus_object_path: dbus.ObjectPath
759
    bus: dbus.SystemBus()
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
760
    """
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
761
    
762
    runtime_expansions = (Client.runtime_expansions
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
763
                          + ("dbus_object_path",))
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
764
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
765
    # dbus.service.Object doesn't use super(), so we can't either.
766
    
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
767
    def __init__(self, bus = None, *args, **kwargs):
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
768
        self._approvals_pending = 0
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
769
        self.bus = bus
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
770
        Client.__init__(self, *args, **kwargs)
771
        # Only now, when this client is initialized, can it show up on
772
        # the D-Bus
441 by Teddy Hogeborn
* mandos (ClientDBus.__init__): Bug fix: Translate "-" in client names
773
        client_object_name = unicode(self.name).translate(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
774
            {ord("."): ord("_"),
775
             ord("-"): ord("_")})
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
776
        self.dbus_object_path = (dbus.ObjectPath
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
777
                                 ("/clients/" + client_object_name))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
778
        DBusObjectWithProperties.__init__(self, self.bus,
779
                                          self.dbus_object_path)
24.1.179 by Björn Påhlsson
New feature:
780
    def _set_expires(self, value):
781
        old_value = getattr(self, "_expires", None)
782
        self._expires = value
783
        if hasattr(self, "dbus_object_path") and old_value != value:
784
            dbus_time = (self._datetime_to_dbus(self._expires,
785
                                                variant_level=1))
786
            self.PropertyChanged(dbus.String("Expires"),
787
                                 dbus_time)
788
    expires = property(lambda self: self._expires, _set_expires)
789
    del _set_expires
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
790
        
24.1.154 by Björn Påhlsson
merge
791
    def _get_approvals_pending(self):
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
792
        return self._approvals_pending
24.2.5 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Bug fix: Only send D-Bus
793
    def _set_approvals_pending(self, value):
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
794
        old_value = self._approvals_pending
795
        self._approvals_pending = value
796
        bval = bool(value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
797
        if (hasattr(self, "dbus_object_path")
24.1.154 by Björn Påhlsson
merge
798
            and bval is not bool(old_value)):
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
799
            dbus_bool = dbus.Boolean(bval, variant_level=1)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
800
            self.PropertyChanged(dbus.String("ApprovalPending"),
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
801
                                 dbus_bool)
24.1.154 by Björn Påhlsson
merge
802
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
803
    approvals_pending = property(_get_approvals_pending,
804
                                 _set_approvals_pending)
805
    del _get_approvals_pending, _set_approvals_pending
806
    
336 by Teddy Hogeborn
Code cleanup.
807
    @staticmethod
808
    def _datetime_to_dbus(dt, variant_level=0):
809
        """Convert a UTC datetime.datetime() to a D-Bus type."""
24.1.179 by Björn Påhlsson
New feature:
810
        if dt is None:
811
            return dbus.String("", variant_level = variant_level)
336 by Teddy Hogeborn
Code cleanup.
812
        return dbus.String(dt.isoformat(),
813
                           variant_level=variant_level)
814
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
815
    def enable(self):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
816
        oldstate = getattr(self, "enabled", False)
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
817
        r = Client.enable(self)
818
        if oldstate != self.enabled:
819
            # Emit D-Bus signals
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
820
            self.PropertyChanged(dbus.String("Enabled"),
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
821
                                 dbus.Boolean(True, variant_level=1))
336 by Teddy Hogeborn
Code cleanup.
822
            self.PropertyChanged(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
823
                dbus.String("LastEnabled"),
336 by Teddy Hogeborn
Code cleanup.
824
                self._datetime_to_dbus(self.last_enabled,
825
                                       variant_level=1))
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
826
        return r
827
    
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
828
    def disable(self, quiet = False):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
829
        oldstate = getattr(self, "enabled", False)
403 by Teddy Hogeborn
* mandos (ClientDBus.disable): Bug fix: complete rename of "log" and
830
        r = Client.disable(self, quiet=quiet)
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
831
        if not quiet and oldstate != self.enabled:
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
832
            # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
833
            self.PropertyChanged(dbus.String("Enabled"),
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
834
                                 dbus.Boolean(False, variant_level=1))
835
        return r
836
    
837
    def __del__(self, *args, **kwargs):
838
        try:
839
            self.remove_from_connection()
329 by Teddy Hogeborn
* mandos (ClientDBus.__del__): Bug fix: Correct mispasted code, and do
840
        except LookupError:
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
841
            pass
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
842
        if hasattr(DBusObjectWithProperties, "__del__"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
843
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
844
        Client.__del__(self, *args, **kwargs)
845
    
846
    def checker_callback(self, pid, condition, command,
847
                         *args, **kwargs):
848
        self.checker_callback_tag = None
849
        self.checker = None
850
        # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
851
        self.PropertyChanged(dbus.String("CheckerRunning"),
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
852
                             dbus.Boolean(False, variant_level=1))
853
        if os.WIFEXITED(condition):
854
            exitstatus = os.WEXITSTATUS(condition)
855
            # Emit D-Bus signal
856
            self.CheckerCompleted(dbus.Int16(exitstatus),
857
                                  dbus.Int64(condition),
858
                                  dbus.String(command))
859
        else:
860
            # Emit D-Bus signal
861
            self.CheckerCompleted(dbus.Int16(-1),
862
                                  dbus.Int64(condition),
863
                                  dbus.String(command))
864
        
865
        return Client.checker_callback(self, pid, condition, command,
866
                                       *args, **kwargs)
867
    
868
    def checked_ok(self, *args, **kwargs):
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
869
        Client.checked_ok(self, *args, **kwargs)
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
870
        # Emit D-Bus signal
871
        self.PropertyChanged(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
872
            dbus.String("LastCheckedOK"),
336 by Teddy Hogeborn
Code cleanup.
873
            (self._datetime_to_dbus(self.last_checked_ok,
874
                                    variant_level=1)))
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
875
    
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
876
    def need_approval(self, *args, **kwargs):
877
        r = Client.need_approval(self, *args, **kwargs)
878
        # Emit D-Bus signal
879
        self.PropertyChanged(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
880
            dbus.String("LastApprovalRequest"),
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
881
            (self._datetime_to_dbus(self.last_approval_request,
882
                                    variant_level=1)))
883
        return r
884
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
885
    def start_checker(self, *args, **kwargs):
886
        old_checker = self.checker
887
        if self.checker is not None:
888
            old_checker_pid = self.checker.pid
889
        else:
890
            old_checker_pid = None
891
        r = Client.start_checker(self, *args, **kwargs)
329 by Teddy Hogeborn
* mandos (ClientDBus.__del__): Bug fix: Correct mispasted code, and do
892
        # Only if new checker process was started
893
        if (self.checker is not None
894
            and old_checker_pid != self.checker.pid):
895
            # Emit D-Bus signal
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
896
            self.CheckerStarted(self.current_checker_command)
897
            self.PropertyChanged(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
898
                dbus.String("CheckerRunning"),
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
899
                dbus.Boolean(True, variant_level=1))
900
        return r
901
    
902
    def stop_checker(self, *args, **kwargs):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
903
        old_checker = getattr(self, "checker", None)
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
904
        r = Client.stop_checker(self, *args, **kwargs)
905
        if (old_checker is not None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
906
            and getattr(self, "checker", None) is None):
907
            self.PropertyChanged(dbus.String("CheckerRunning"),
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
908
                                 dbus.Boolean(False, variant_level=1))
909
        return r
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
910
911
    def _reset_approved(self):
912
        self._approved = None
913
        return False
914
    
915
    def approve(self, value=True):
24.1.154 by Björn Påhlsson
merge
916
        self.send_changedstate()
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
917
        self._approved = value
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
918
        gobject.timeout_add(self._timedelta_to_milliseconds
919
                            (self.approval_duration),
24.1.154 by Björn Påhlsson
merge
920
                            self._reset_approved)
24.2.1 by teddy at bsnet
* debian/control (mandos/Depends): Added "python-urwid".
921
    
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
922
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
923
    ## D-Bus methods, signals & properties
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
924
    _interface = "se.bsnet.fukt.Mandos.Client"
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
925
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
926
    ## Signals
381 by Teddy Hogeborn
Restore some poor D-Bus methods who got a bit hastily deleted. Enable
927
    
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
928
    # CheckerCompleted - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
929
    @dbus.service.signal(_interface, signature="nxs")
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
930
    def CheckerCompleted(self, exitcode, waitstatus, command):
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
931
        "D-Bus signal"
932
        pass
933
    
934
    # CheckerStarted - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
935
    @dbus.service.signal(_interface, signature="s")
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
936
    def CheckerStarted(self, command):
937
        "D-Bus signal"
938
        pass
939
    
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
940
    # PropertyChanged - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
941
    @dbus.service.signal(_interface, signature="sv")
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
942
    def PropertyChanged(self, property, value):
943
        "D-Bus signal"
944
        pass
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
945
    
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
946
    # GotSecret - signal
327 by Teddy Hogeborn
Merge from pipe IPC branch.
947
    @dbus.service.signal(_interface)
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
948
    def GotSecret(self):
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
949
        """D-Bus signal
950
        Is sent after a successful transfer of secret from the Mandos
951
        server to mandos-client
952
        """
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
953
        pass
327 by Teddy Hogeborn
Merge from pipe IPC branch.
954
    
955
    # Rejected - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
956
    @dbus.service.signal(_interface, signature="s")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
957
    def Rejected(self, reason):
958
        "D-Bus signal"
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
959
        pass
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
960
    
961
    # NeedApproval - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
962
    @dbus.service.signal(_interface, signature="tb")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
963
    def NeedApproval(self, timeout, default):
327 by Teddy Hogeborn
Merge from pipe IPC branch.
964
        "D-Bus signal"
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
965
        return self.need_approval()
327 by Teddy Hogeborn
Merge from pipe IPC branch.
966
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
967
    ## Methods
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
968
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
969
    # Approve - method
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
970
    @dbus.service.method(_interface, in_signature="b")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
971
    def Approve(self, value):
972
        self.approve(value)
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
973
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
974
    # CheckedOK - method
975
    @dbus.service.method(_interface)
976
    def CheckedOK(self):
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
977
        self.checked_ok()
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
978
    
381 by Teddy Hogeborn
Restore some poor D-Bus methods who got a bit hastily deleted. Enable
979
    # Enable - method
980
    @dbus.service.method(_interface)
981
    def Enable(self):
982
        "D-Bus method"
983
        self.enable()
984
    
985
    # StartChecker - method
986
    @dbus.service.method(_interface)
987
    def StartChecker(self):
988
        "D-Bus method"
989
        self.start_checker()
990
    
991
    # Disable - method
992
    @dbus.service.method(_interface)
993
    def Disable(self):
994
        "D-Bus method"
995
        self.disable()
996
    
997
    # StopChecker - method
998
    @dbus.service.method(_interface)
999
    def StopChecker(self):
1000
        self.stop_checker()
1001
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1002
    ## Properties
1003
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1004
    # ApprovalPending - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1005
    @dbus_service_property(_interface, signature="b", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1006
    def ApprovalPending_dbus_property(self):
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
1007
        return dbus.Boolean(bool(self.approvals_pending))
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1008
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1009
    # ApprovedByDefault - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1010
    @dbus_service_property(_interface, signature="b",
1011
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1012
    def ApprovedByDefault_dbus_property(self, value=None):
1013
        if value is None:       # get
1014
            return dbus.Boolean(self.approved_by_default)
24.1.179 by Björn Påhlsson
New feature:
1015
        old_value = self.approved_by_default
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1016
        self.approved_by_default = bool(value)
1017
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1018
        if old_value != self.approved_by_default:
1019
            self.PropertyChanged(dbus.String("ApprovedByDefault"),
1020
                                 dbus.Boolean(value, variant_level=1))
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1021
    
1022
    # ApprovalDelay - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1023
    @dbus_service_property(_interface, signature="t",
1024
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1025
    def ApprovalDelay_dbus_property(self, value=None):
1026
        if value is None:       # get
1027
            return dbus.UInt64(self.approval_delay_milliseconds())
24.1.179 by Björn Påhlsson
New feature:
1028
        old_value = self.approval_delay
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1029
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1030
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1031
        if old_value != self.approval_delay:
1032
            self.PropertyChanged(dbus.String("ApprovalDelay"),
1033
                                 dbus.UInt64(value, variant_level=1))
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1034
    
1035
    # ApprovalDuration - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1036
    @dbus_service_property(_interface, signature="t",
1037
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1038
    def ApprovalDuration_dbus_property(self, value=None):
1039
        if value is None:       # get
1040
            return dbus.UInt64(self._timedelta_to_milliseconds(
1041
                    self.approval_duration))
24.1.179 by Björn Påhlsson
New feature:
1042
        old_value = self.approval_duration
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1043
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1044
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1045
        if old_value != self.approval_duration:
1046
            self.PropertyChanged(dbus.String("ApprovalDuration"),
1047
                                 dbus.UInt64(value, variant_level=1))
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1048
    
1049
    # Name - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1050
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1051
    def Name_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1052
        return dbus.String(self.name)
1053
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1054
    # Fingerprint - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1055
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1056
    def Fingerprint_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1057
        return dbus.String(self.fingerprint)
1058
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1059
    # Host - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1060
    @dbus_service_property(_interface, signature="s",
1061
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1062
    def Host_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1063
        if value is None:       # get
1064
            return dbus.String(self.host)
24.1.179 by Björn Påhlsson
New feature:
1065
        old_value = self.host
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1066
        self.host = value
1067
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1068
        if old_value != self.host:
1069
            self.PropertyChanged(dbus.String("Host"),
1070
                                 dbus.String(value, variant_level=1))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1071
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1072
    # Created - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1073
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1074
    def Created_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1075
        return dbus.String(self._datetime_to_dbus(self.created))
1076
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1077
    # LastEnabled - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1078
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1079
    def LastEnabled_dbus_property(self):
24.1.179 by Björn Påhlsson
New feature:
1080
        return self._datetime_to_dbus(self.last_enabled)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1081
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1082
    # Enabled - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1083
    @dbus_service_property(_interface, signature="b",
1084
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1085
    def Enabled_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1086
        if value is None:       # get
1087
            return dbus.Boolean(self.enabled)
1088
        if value:
1089
            self.enable()
1090
        else:
1091
            self.disable()
1092
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1093
    # LastCheckedOK - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1094
    @dbus_service_property(_interface, signature="s",
1095
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1096
    def LastCheckedOK_dbus_property(self, value=None):
381 by Teddy Hogeborn
Restore some poor D-Bus methods who got a bit hastily deleted. Enable
1097
        if value is not None:
1098
            self.checked_ok()
1099
            return
24.1.179 by Björn Påhlsson
New feature:
1100
        return self._datetime_to_dbus(self.last_checked_ok)
1101
    
1102
    # Expires - property
1103
    @dbus_service_property(_interface, signature="s", access="read")
1104
    def Expires_dbus_property(self):
1105
        return self._datetime_to_dbus(self.expires)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1106
    
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1107
    # LastApprovalRequest - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1108
    @dbus_service_property(_interface, signature="s", access="read")
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1109
    def LastApprovalRequest_dbus_property(self):
24.1.179 by Björn Påhlsson
New feature:
1110
        return self._datetime_to_dbus(self.last_approval_request)
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1111
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1112
    # Timeout - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1113
    @dbus_service_property(_interface, signature="t",
1114
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1115
    def Timeout_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1116
        if value is None:       # get
1117
            return dbus.UInt64(self.timeout_milliseconds())
24.1.179 by Björn Påhlsson
New feature:
1118
        old_value = self.timeout
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1119
        self.timeout = datetime.timedelta(0, 0, 0, value)
1120
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1121
        if old_value != self.timeout:
1122
            self.PropertyChanged(dbus.String("Timeout"),
1123
                                 dbus.UInt64(value, variant_level=1))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1124
        if getattr(self, "disable_initiator_tag", None) is None:
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1125
            return
1126
        # Reschedule timeout
1127
        gobject.source_remove(self.disable_initiator_tag)
1128
        self.disable_initiator_tag = None
24.1.179 by Björn Påhlsson
New feature:
1129
        self.expires = None
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1130
        time_to_die = (self.
1131
                       _timedelta_to_milliseconds((self
1132
                                                   .last_checked_ok
1133
                                                   + self.timeout)
1134
                                                  - datetime.datetime
1135
                                                  .utcnow()))
1136
        if time_to_die <= 0:
1137
            # The timeout has passed
1138
            self.disable()
1139
        else:
24.1.179 by Björn Påhlsson
New feature:
1140
            self.expires = (datetime.datetime.utcnow()
1141
                            + datetime.timedelta(milliseconds = time_to_die))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1142
            self.disable_initiator_tag = (gobject.timeout_add
1143
                                          (time_to_die, self.disable))
24.1.179 by Björn Påhlsson
New feature:
1144
1145
    # ExtendedTimeout - property
1146
    @dbus_service_property(_interface, signature="t",
1147
                           access="readwrite")
1148
    def ExtendedTimeout_dbus_property(self, value=None):
1149
        if value is None:       # get
1150
            return dbus.UInt64(self.extended_timeout_milliseconds())
1151
        old_value = self.extended_timeout
1152
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1153
        # Emit D-Bus signal
1154
        if old_value != self.extended_timeout:
1155
            self.PropertyChanged(dbus.String("ExtendedTimeout"),
1156
                                 dbus.UInt64(value, variant_level=1))
1157
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1158
    # Interval - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1159
    @dbus_service_property(_interface, signature="t",
1160
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1161
    def Interval_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1162
        if value is None:       # get
1163
            return dbus.UInt64(self.interval_milliseconds())
24.1.179 by Björn Påhlsson
New feature:
1164
        old_value = self.interval
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1165
        self.interval = datetime.timedelta(0, 0, 0, value)
1166
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1167
        if old_value != self.interval:
1168
            self.PropertyChanged(dbus.String("Interval"),
1169
                                 dbus.UInt64(value, variant_level=1))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1170
        if getattr(self, "checker_initiator_tag", None) is None:
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1171
            return
1172
        # Reschedule checker run
1173
        gobject.source_remove(self.checker_initiator_tag)
1174
        self.checker_initiator_tag = (gobject.timeout_add
1175
                                      (value, self.start_checker))
1176
        self.start_checker()    # Start one now, too
1177
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1178
    # Checker - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1179
    @dbus_service_property(_interface, signature="s",
1180
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1181
    def Checker_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1182
        if value is None:       # get
1183
            return dbus.String(self.checker_command)
24.1.179 by Björn Påhlsson
New feature:
1184
        old_value = self.checker_command
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1185
        self.checker_command = value
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
1186
        # Emit D-Bus signal
24.1.179 by Björn Påhlsson
New feature:
1187
        if old_value != self.checker_command:
1188
            self.PropertyChanged(dbus.String("Checker"),
1189
                                 dbus.String(self.checker_command,
1190
                                             variant_level=1))
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1191
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1192
    # CheckerRunning - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1193
    @dbus_service_property(_interface, signature="b",
1194
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1195
    def CheckerRunning_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1196
        if value is None:       # get
1197
            return dbus.Boolean(self.checker is not None)
1198
        if value:
1199
            self.start_checker()
1200
        else:
1201
            self.stop_checker()
1202
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1203
    # ObjectPath - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1204
    @dbus_service_property(_interface, signature="o", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1205
    def ObjectPath_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1206
        return self.dbus_object_path # is already a dbus.ObjectPath
1207
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1208
    # Secret = property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1209
    @dbus_service_property(_interface, signature="ay",
1210
                           access="write", byte_arrays=True)
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1211
    def Secret_dbus_property(self, value):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1212
        self.secret = str(value)
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1213
    
1214
    del _interface
3 by Björn Påhlsson
Python based server
1215
1216
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1217
class ProxyClient(object):
1218
    def __init__(self, child_pipe, fpr, address):
1219
        self._pipe = child_pipe
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1220
        self._pipe.send(('init', fpr, address))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1221
        if not self._pipe.recv():
1222
            raise KeyError()
1223
1224
    def __getattribute__(self, name):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1225
        if(name == '_pipe'):
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1226
            return super(ProxyClient, self).__getattribute__(name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1227
        self._pipe.send(('getattr', name))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1228
        data = self._pipe.recv()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1229
        if data[0] == 'data':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1230
            return data[1]
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1231
        if data[0] == 'function':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1232
            def func(*args, **kwargs):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1233
                self._pipe.send(('funcall', name, args, kwargs))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1234
                return self._pipe.recv()[1]
1235
            return func
1236
1237
    def __setattr__(self, name, value):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1238
        if(name == '_pipe'):
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1239
            return super(ProxyClient, self).__setattr__(name, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1240
        self._pipe.send(('setattr', name, value))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1241
1242
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1243
class ClientHandler(socketserver.BaseRequestHandler, object):
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1244
    """A class to handle client connections.
1245
    
1246
    Instantiated once for each connection to handle it.
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1247
    Note: This will run in its own forked process."""
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
1248
    
3 by Björn Påhlsson
Python based server
1249
    def handle(self):
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1250
        with contextlib.closing(self.server.child_pipe) as child_pipe:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1251
            logger.info("TCP connection from: %s",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1252
                        unicode(self.client_address))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1253
            logger.debug("Pipe FD: %d",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1254
                         self.server.child_pipe.fileno())
1255
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1256
            session = (gnutls.connection
1257
                       .ClientSession(self.request,
1258
                                      gnutls.connection
1259
                                      .X509Credentials()))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1260
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1261
            # Note: gnutls.connection.X509Credentials is really a
1262
            # generic GnuTLS certificate credentials object so long as
1263
            # no X.509 keys are added to it.  Therefore, we can use it
1264
            # here despite using OpenPGP certificates.
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1265
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1266
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1267
            #                      "+AES-256-CBC", "+SHA1",
1268
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1269
            #                      "+DHE-DSS"))
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1270
            # Use a fallback default, since this MUST be set.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1271
            priority = self.server.gnutls_priority
1272
            if priority is None:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1273
                priority = "NORMAL"
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1274
            (gnutls.library.functions
1275
             .gnutls_priority_set_direct(session._c_object,
1276
                                         priority, None))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1277
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1278
            # Start communication using the Mandos protocol
1279
            # Get protocol number
1280
            line = self.request.makefile().readline()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1281
            logger.debug("Protocol version: %r", line)
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1282
            try:
1283
                if int(line.strip().split()[0]) > 1:
1284
                    raise RuntimeError
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1285
            except (ValueError, IndexError, RuntimeError) as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1286
                logger.error("Unknown protocol version: %s", error)
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1287
                return
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1288
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1289
            # Start GnuTLS connection
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1290
            try:
1291
                session.handshake()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1292
            except gnutls.errors.GNUTLSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1293
                logger.warning("Handshake failed: %s", error)
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1294
                # Do not run session.bye() here: the session is not
1295
                # established.  Just abandon the request.
1296
                return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1297
            logger.debug("Handshake succeeded")
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1298
1299
            approval_required = False
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1300
            try:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1301
                try:
1302
                    fpr = self.fingerprint(self.peer_certificate
1303
                                           (session))
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1304
                except (TypeError,
1305
                        gnutls.errors.GNUTLSError) as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1306
                    logger.warning("Bad certificate: %s", error)
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1307
                    return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1308
                logger.debug("Fingerprint: %s", fpr)
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1309
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1310
                try:
1311
                    client = ProxyClient(child_pipe, fpr,
1312
                                         self.client_address)
1313
                except KeyError:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1314
                    return
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1315
                
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1316
                if client.approval_delay:
1317
                    delay = client.approval_delay
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1318
                    client.approvals_pending += 1
1319
                    approval_required = True
1320
                
24.1.148 by Björn Påhlsson
half working on-demand password and approved code
1321
                while True:
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1322
                    if not client.enabled:
24.1.174 by Björn Påhlsson
* Makefile (CFLAGS): Added "-lrt" to include real time library.
1323
                        logger.info("Client %s is disabled",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1324
                                       client.name)
1325
                        if self.server.use_dbus:
1326
                            # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1327
                            client.Rejected("Disabled")                    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1328
                        return
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1329
                    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1330
                    if client._approved or not client.approval_delay:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1331
                        #We are approved or approval is disabled
1332
                        break
1333
                    elif client._approved is None:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1334
                        logger.info("Client %s needs approval",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1335
                                    client.name)
1336
                        if self.server.use_dbus:
1337
                            # Emit D-Bus signal
1338
                            client.NeedApproval(
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1339
                                client.approval_delay_milliseconds(),
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1340
                                client.approved_by_default)
1341
                    else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1342
                        logger.warning("Client %s was not approved",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1343
                                       client.name)
1344
                        if self.server.use_dbus:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1345
                            # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1346
                            client.Rejected("Denied")
24.1.148 by Björn Påhlsson
half working on-demand password and approved code
1347
                        return
1348
                    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1349
                    #wait until timeout or approved
1350
                    #x = float(client._timedelta_to_milliseconds(delay))
1351
                    time = datetime.datetime.now()
1352
                    client.changedstate.acquire()
1353
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1354
                    client.changedstate.release()
1355
                    time2 = datetime.datetime.now()
1356
                    if (time2 - time) >= delay:
1357
                        if not client.approved_by_default:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1358
                            logger.warning("Client %s timed out while"
1359
                                           " waiting for approval",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1360
                                           client.name)
1361
                            if self.server.use_dbus:
1362
                                # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1363
                                client.Rejected("Approval timed out")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1364
                            return
1365
                        else:
1366
                            break
1367
                    else:
1368
                        delay -= time2 - time
1369
                
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1370
                sent_size = 0
1371
                while sent_size < len(client.secret):
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1372
                    try:
1373
                        sent = session.send(client.secret[sent_size:])
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1374
                    except gnutls.errors.GNUTLSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1375
                        logger.warning("gnutls send failed")
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1376
                        return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1377
                    logger.debug("Sent: %d, remaining: %d",
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1378
                                 sent, len(client.secret)
1379
                                 - (sent_size + sent))
1380
                    sent_size += sent
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1381
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1382
                logger.info("Sending secret to %s", client.name)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1383
                # bump the timeout as if seen
24.1.179 by Björn Påhlsson
New feature:
1384
                client.checked_ok(client.extended_timeout)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1385
                if self.server.use_dbus:
1386
                    # Emit D-Bus signal
1387
                    client.GotSecret()
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1388
            
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1389
            finally:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1390
                if approval_required:
1391
                    client.approvals_pending -= 1
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1392
                try:
1393
                    session.bye()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1394
                except gnutls.errors.GNUTLSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1395
                    logger.warning("GnuTLS bye failed")
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1396
    
1397
    @staticmethod
1398
    def peer_certificate(session):
1399
        "Return the peer's OpenPGP certificate as a bytestring"
1400
        # If not an OpenPGP certificate...
1401
        if (gnutls.library.functions
1402
            .gnutls_certificate_type_get(session._c_object)
1403
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1404
            # ...do the normal thing
1405
            return session.peer_certificate
1406
        list_size = ctypes.c_uint(1)
1407
        cert_list = (gnutls.library.functions
1408
                     .gnutls_certificate_get_peers
1409
                     (session._c_object, ctypes.byref(list_size)))
1410
        if not bool(cert_list) and list_size.value != 0:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1411
            raise gnutls.errors.GNUTLSError("error getting peer"
1412
                                            " certificate")
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1413
        if list_size.value == 0:
1414
            return None
1415
        cert = cert_list[0]
1416
        return ctypes.string_at(cert.data, cert.size)
1417
    
1418
    @staticmethod
1419
    def fingerprint(openpgp):
1420
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1421
        # New GnuTLS "datum" with the OpenPGP public key
1422
        datum = (gnutls.library.types
1423
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1424
                                             ctypes.POINTER
1425
                                             (ctypes.c_ubyte)),
1426
                                 ctypes.c_uint(len(openpgp))))
1427
        # New empty GnuTLS certificate
1428
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1429
        (gnutls.library.functions
1430
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1431
        # Import the OpenPGP public key into the certificate
1432
        (gnutls.library.functions
1433
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1434
                                    gnutls.library.constants
1435
                                    .GNUTLS_OPENPGP_FMT_RAW))
1436
        # Verify the self signature in the key
1437
        crtverify = ctypes.c_uint()
1438
        (gnutls.library.functions
1439
         .gnutls_openpgp_crt_verify_self(crt, 0,
1440
                                         ctypes.byref(crtverify)))
1441
        if crtverify.value != 0:
1442
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1443
            raise (gnutls.errors.CertificateSecurityError
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1444
                   ("Verify failed"))
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1445
        # New buffer for the fingerprint
1446
        buf = ctypes.create_string_buffer(20)
1447
        buf_len = ctypes.c_size_t()
1448
        # Get the fingerprint from the certificate into the buffer
1449
        (gnutls.library.functions
1450
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1451
                                             ctypes.byref(buf_len)))
1452
        # Deinit the certificate
1453
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1454
        # Convert the buffer to a Python bytestring
1455
        fpr = ctypes.string_at(buf, buf_len.value)
1456
        # Convert the bytestring to hexadecimal notation
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1457
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1458
        return hex_fpr
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1459
1460
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1461
class MultiprocessingMixIn(object):
1462
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1463
    def sub_process_main(self, request, address):
1464
        try:
1465
            self.finish_request(request, address)
1466
        except:
1467
            self.handle_error(request, address)
1468
        self.close_request(request)
1469
            
1470
    def process_request(self, request, address):
1471
        """Start a new process to process the request."""
1472
        multiprocessing.Process(target = self.sub_process_main,
1473
                                args = (request, address)).start()
1474
1475
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1476
    """ adds a pipe to the MixIn """
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1477
    def process_request(self, request, client_address):
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1478
        """Overrides and wraps the original process_request().
1479
        
355 by Teddy Hogeborn
* mandos: White-space fixes only.
1480
        This function creates a new pipe in self.pipe
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1481
        """
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1482
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1483
1484
        super(MultiprocessingMixInWithPipe,
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1485
              self).process_request(request, client_address)
24.1.152 by Björn Påhlsson
bug fixes that prevent problems when runing server as root
1486
        self.child_pipe.close()
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1487
        self.add_pipe(parent_pipe)
24.1.154 by Björn Påhlsson
merge
1488
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1489
    def add_pipe(self, parent_pipe):
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1490
        """Dummy function; override as necessary"""
464 by Teddy Hogeborn
* debian/mandos-client.postrm (purge): Bug fix: update initramfs also
1491
        raise NotImplementedError
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1492
1493
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1494
                     socketserver.TCPServer, object):
237.2.13 by Teddy Hogeborn
Merge from trunk. Notable changes:
1495
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1496
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1497
    Attributes:
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1498
        enabled:        Boolean; whether this server is activated yet
1499
        interface:      None or a network interface name (string)
1500
        use_ipv6:       Boolean; to use IPv6 or not
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1501
    """
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1502
    def __init__(self, server_address, RequestHandlerClass,
339 by Teddy Hogeborn
Code cleanup.
1503
                 interface=None, use_ipv6=True):
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1504
        self.interface = interface
1505
        if use_ipv6:
1506
            self.address_family = socket.AF_INET6
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1507
        socketserver.TCPServer.__init__(self, server_address,
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1508
                                        RequestHandlerClass)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1509
    def server_bind(self):
1510
        """This overrides the normal server_bind() function
1511
        to bind to an interface if one was specified, and also NOT to
1512
        bind to an address or port if they were not specified."""
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1513
        if self.interface is not None:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1514
            if SO_BINDTODEVICE is None:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1515
                logger.error("SO_BINDTODEVICE does not exist;"
1516
                             " cannot bind to interface %s",
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1517
                             self.interface)
1518
            else:
1519
                try:
1520
                    self.socket.setsockopt(socket.SOL_SOCKET,
1521
                                           SO_BINDTODEVICE,
1522
                                           str(self.interface
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1523
                                               + '\0'))
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1524
                except socket.error as error:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1525
                    if error[0] == errno.EPERM:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1526
                        logger.error("No permission to"
1527
                                     " bind to interface %s",
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1528
                                     self.interface)
1529
                    elif error[0] == errno.ENOPROTOOPT:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1530
                        logger.error("SO_BINDTODEVICE not available;"
1531
                                     " cannot bind to interface %s",
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1532
                                     self.interface)
1533
                    else:
1534
                        raise
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1535
        # Only bind(2) the socket if we really need to.
1536
        if self.server_address[0] or self.server_address[1]:
1537
            if not self.server_address[0]:
314 by Teddy Hogeborn
Support not using IPv6 in server:
1538
                if self.address_family == socket.AF_INET6:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1539
                    any_address = "::" # in6addr_any
314 by Teddy Hogeborn
Support not using IPv6 in server:
1540
                else:
1541
                    any_address = socket.INADDR_ANY
1542
                self.server_address = (any_address,
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1543
                                       self.server_address[1])
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
1544
            elif not self.server_address[1]:
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1545
                self.server_address = (self.server_address[0],
1546
                                       0)
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1547
#                 if self.interface:
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
1548
#                     self.server_address = (self.server_address[0],
1549
#                                            0, # port
1550
#                                            0, # flowinfo
1551
#                                            if_nametoindex
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1552
#                                            (self.interface))
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1553
            return socketserver.TCPServer.server_bind(self)
339 by Teddy Hogeborn
Code cleanup.
1554
1555
1556
class MandosServer(IPv6_TCPServer):
1557
    """Mandos server.
1558
    
1559
    Attributes:
1560
        clients:        set of Client objects
1561
        gnutls_priority GnuTLS priority string
1562
        use_dbus:       Boolean; to emit D-Bus signals or not
340 by Teddy Hogeborn
Code cleanup.
1563
    
1564
    Assumes a gobject.MainLoop event loop.
339 by Teddy Hogeborn
Code cleanup.
1565
    """
1566
    def __init__(self, server_address, RequestHandlerClass,
1567
                 interface=None, use_ipv6=True, clients=None,
1568
                 gnutls_priority=None, use_dbus=True):
1569
        self.enabled = False
1570
        self.clients = clients
341 by Teddy Hogeborn
Code cleanup and one bug fix.
1571
        if self.clients is None:
1572
            self.clients = set()
339 by Teddy Hogeborn
Code cleanup.
1573
        self.use_dbus = use_dbus
1574
        self.gnutls_priority = gnutls_priority
1575
        IPv6_TCPServer.__init__(self, server_address,
1576
                                RequestHandlerClass,
1577
                                interface = interface,
1578
                                use_ipv6 = use_ipv6)
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1579
    def server_activate(self):
1580
        if self.enabled:
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1581
            return socketserver.TCPServer.server_activate(self)
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1582
    def enable(self):
1583
        self.enabled = True
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1584
    def add_pipe(self, parent_pipe):
340 by Teddy Hogeborn
Code cleanup.
1585
        # Call "handle_ipc" for both data and EOF events
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1586
        gobject.io_add_watch(parent_pipe.fileno(),
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1587
                             gobject.IO_IN | gobject.IO_HUP,
1588
                             functools.partial(self.handle_ipc,
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1589
                                               parent_pipe = parent_pipe))
1590
        
1591
    def handle_ipc(self, source, condition, parent_pipe=None,
1592
                   client_object=None):
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1593
        condition_names = {
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1594
            gobject.IO_IN: "IN",   # There is data to read.
1595
            gobject.IO_OUT: "OUT", # Data can be written (without
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1596
                                    # blocking).
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1597
            gobject.IO_PRI: "PRI", # There is urgent data to read.
1598
            gobject.IO_ERR: "ERR", # Error condition.
1599
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1600
                                    # broken, usually for pipes and
1601
                                    # sockets).
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1602
            }
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1603
        conditions_string = ' | '.join(name
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1604
                                       for cond, name in
1605
                                       condition_names.iteritems()
1606
                                       if cond & condition)
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1607
        # error or the other end of multiprocessing.Pipe has closed
1608
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
24.1.152 by Björn Påhlsson
bug fixes that prevent problems when runing server as root
1609
            return False
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1610
        
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1611
        # Read a request from the child
1612
        request = parent_pipe.recv()
1613
        command = request[0]
1614
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1615
        if command == 'init':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1616
            fpr = request[1]
1617
            address = request[2]
1618
            
1619
            for c in self.clients:
1620
                if c.fingerprint == fpr:
1621
                    client = c
1622
                    break
1623
            else:
24.1.174 by Björn Påhlsson
* Makefile (CFLAGS): Added "-lrt" to include real time library.
1624
                logger.info("Client not found for fingerprint: %s, ad"
1625
                            "dress: %s", fpr, address)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1626
                if self.use_dbus:
1627
                    # Emit D-Bus signal
441 by Teddy Hogeborn
* mandos (ClientDBus.__init__): Bug fix: Translate "-" in client names
1628
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1629
                parent_pipe.send(False)
1630
                return False
1631
            
1632
            gobject.io_add_watch(parent_pipe.fileno(),
1633
                                 gobject.IO_IN | gobject.IO_HUP,
1634
                                 functools.partial(self.handle_ipc,
1635
                                                   parent_pipe = parent_pipe,
1636
                                                   client_object = client))
1637
            parent_pipe.send(True)
1638
            # remove the old hook in favor of the new above hook on same fileno
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1639
            return False
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1640
        if command == 'funcall':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1641
            funcname = request[1]
1642
            args = request[2]
1643
            kwargs = request[3]
1644
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1645
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1646
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1647
        if command == 'getattr':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1648
            attrname = request[1]
1649
            if callable(client_object.__getattribute__(attrname)):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1650
                parent_pipe.send(('function',))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1651
            else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1652
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
1653
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1654
        if command == 'setattr':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1655
            attrname = request[1]
1656
            value = request[2]
1657
            setattr(client_object, attrname, value)
24.1.154 by Björn Påhlsson
merge
1658
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1659
        return True
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
1660
3 by Björn Påhlsson
Python based server
1661
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1662
def string_to_delta(interval):
1663
    """Parse a string and return a datetime.timedelta
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1664
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1665
    >>> string_to_delta('7d')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1666
    datetime.timedelta(7)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1667
    >>> string_to_delta('60s')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1668
    datetime.timedelta(0, 60)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1669
    >>> string_to_delta('60m')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1670
    datetime.timedelta(0, 3600)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1671
    >>> string_to_delta('24h')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1672
    datetime.timedelta(1)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1673
    >>> string_to_delta('1w')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1674
    datetime.timedelta(7)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1675
    >>> string_to_delta('5m 30s')
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1676
    datetime.timedelta(0, 330)
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1677
    """
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1678
    timevalue = datetime.timedelta(0)
1679
    for s in interval.split():
1680
        try:
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
1681
            suffix = unicode(s[-1])
1682
            value = int(s[:-1])
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1683
            if suffix == "d":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1684
                delta = datetime.timedelta(value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1685
            elif suffix == "s":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1686
                delta = datetime.timedelta(0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1687
            elif suffix == "m":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1688
                delta = datetime.timedelta(0, 0, 0, 0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1689
            elif suffix == "h":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1690
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1691
            elif suffix == "w":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1692
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1693
            else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1694
                raise ValueError("Unknown suffix %r" % suffix)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1695
        except (ValueError, IndexError) as e:
464 by Teddy Hogeborn
* debian/mandos-client.postrm (purge): Bug fix: update initramfs also
1696
            raise ValueError(*(e.args))
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1697
        timevalue += delta
1698
    return timevalue
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1699
8 by Teddy Hogeborn
* Makefile (client_debug): Bug fix; add quotes and / to CERT_ROOT.
1700
24.1.13 by Björn Påhlsson
mandosclient
1701
def if_nametoindex(interface):
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1702
    """Call the C function if_nametoindex(), or equivalent
1703
    
1704
    Note: This function cannot accept a unicode string."""
24.1.13 by Björn Påhlsson
mandosclient
1705
    global if_nametoindex
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1706
    try:
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1707
        if_nametoindex = (ctypes.cdll.LoadLibrary
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1708
                          (ctypes.util.find_library("c"))
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1709
                          .if_nametoindex)
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
1710
    except (OSError, AttributeError):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1711
        logger.warning("Doing if_nametoindex the hard way")
24.1.13 by Björn Påhlsson
mandosclient
1712
        def if_nametoindex(interface):
28 by Teddy Hogeborn
* server.conf: New file.
1713
            "Get an interface index the hard way, i.e. using fcntl()"
1714
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1715
            with contextlib.closing(socket.socket()) as s:
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
1716
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1717
                                    struct.pack(str("16s16x"),
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1718
                                                interface))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1719
            interface_index = struct.unpack(str("I"),
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1720
                                            ifreq[16:20])[0]
28 by Teddy Hogeborn
* server.conf: New file.
1721
            return interface_index
24.1.13 by Björn Påhlsson
mandosclient
1722
    return if_nametoindex(interface)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1723
1724
47 by Teddy Hogeborn
* plugbasedclient.c: Renamed to "mandos-client.c". All users changed.
1725
def daemon(nochdir = False, noclose = False):
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1726
    """See daemon(3).  Standard BSD Unix function.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1727
    
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1728
    This should really exist as os.daemon, but it doesn't (yet)."""
1729
    if os.fork():
1730
        sys.exit()
1731
    os.setsid()
1732
    if not nochdir:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1733
        os.chdir("/")
46 by Teddy Hogeborn
* network-protocol.txt: New.
1734
    if os.fork():
1735
        sys.exit()
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1736
    if not noclose:
1737
        # Close all standard open file descriptors
28 by Teddy Hogeborn
* server.conf: New file.
1738
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1739
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1740
            raise OSError(errno.ENODEV,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1741
                          "%s not a character device"
388 by Teddy Hogeborn
* mandos (daemon): Use "os.path.devnull" in the error message.
1742
                          % os.path.devnull)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1743
        os.dup2(null, sys.stdin.fileno())
1744
        os.dup2(null, sys.stdout.fileno())
1745
        os.dup2(null, sys.stderr.fileno())
1746
        if null > 2:
1747
            os.close(null)
1748
1749
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
1750
def main():
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1751
    
379 by Teddy Hogeborn
* mandos: Fix line lengths.
1752
    ##################################################################
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1753
    # Parsing of options, both command line and config file
1754
    
474 by teddy at bsnet
* mandos: Use the new argparse library instead of optparse.
1755
    parser = argparse.ArgumentParser()
1756
    parser.add_argument("-v", "--version", action="version",
1757
                        version = "%%(prog)s %s" % version,
1758
                        help="show version number and exit")
1759
    parser.add_argument("-i", "--interface", metavar="IF",
1760
                        help="Bind to interface IF")
1761
    parser.add_argument("-a", "--address",
1762
                        help="Address to listen for requests on")
1763
    parser.add_argument("-p", "--port", type=int,
1764
                        help="Port number to receive requests on")
1765
    parser.add_argument("--check", action="store_true",
1766
                        help="Run self-test")
1767
    parser.add_argument("--debug", action="store_true",
1768
                        help="Debug mode; run in foreground and log"
1769
                        " to terminal")
1770
    parser.add_argument("--debuglevel", metavar="LEVEL",
1771
                        help="Debug level for stdout output")
1772
    parser.add_argument("--priority", help="GnuTLS"
1773
                        " priority string (see GnuTLS documentation)")
1774
    parser.add_argument("--servicename",
1775
                        metavar="NAME", help="Zeroconf service name")
1776
    parser.add_argument("--configdir",
1777
                        default="/etc/mandos", metavar="DIR",
1778
                        help="Directory to search for configuration"
1779
                        " files")
1780
    parser.add_argument("--no-dbus", action="store_false",
1781
                        dest="use_dbus", help="Do not provide D-Bus"
1782
                        " system bus interface")
1783
    parser.add_argument("--no-ipv6", action="store_false",
1784
                        dest="use_ipv6", help="Do not use IPv6")
1785
    options = parser.parse_args()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1786
    
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1787
    if options.check:
1788
        import doctest
1789
        doctest.testmod()
1790
        sys.exit()
3 by Björn Påhlsson
Python based server
1791
    
28 by Teddy Hogeborn
* server.conf: New file.
1792
    # Default values for config file for server-global settings
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1793
    server_defaults = { "interface": "",
1794
                        "address": "",
1795
                        "port": "",
1796
                        "debug": "False",
1797
                        "priority":
1798
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1799
                        "servicename": "Mandos",
1800
                        "use_dbus": "True",
1801
                        "use_ipv6": "True",
1802
                        "debuglevel": "",
28 by Teddy Hogeborn
* server.conf: New file.
1803
                        }
1804
    
1805
    # Parse config file for server-global settings
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1806
    server_config = configparser.SafeConfigParser(server_defaults)
28 by Teddy Hogeborn
* server.conf: New file.
1807
    del server_defaults
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1808
    server_config.read(os.path.join(options.configdir,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1809
                                    "mandos.conf"))
28 by Teddy Hogeborn
* server.conf: New file.
1810
    # Convert the SafeConfigParser object to a dict
89 by Teddy Hogeborn
* Makefile: Bug fix: fixed creation of man pages for section 5 pages.
1811
    server_settings = server_config.defaults()
282 by Teddy Hogeborn
* mandos (main): Bug fix: use "getint" on the "port" config file
1812
    # Use the appropriate methods on the non-string config options
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1813
    for option in ("debug", "use_dbus", "use_ipv6"):
1814
        server_settings[option] = server_config.getboolean("DEFAULT",
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1815
                                                           option)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1816
    if server_settings["port"]:
1817
        server_settings["port"] = server_config.getint("DEFAULT",
1818
                                                       "port")
28 by Teddy Hogeborn
* server.conf: New file.
1819
    del server_config
1820
    
1821
    # Override the settings from the config file with command line
1822
    # options, if set.
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1823
    for option in ("interface", "address", "port", "debug",
1824
                   "priority", "servicename", "configdir",
1825
                   "use_dbus", "use_ipv6", "debuglevel"):
28 by Teddy Hogeborn
* server.conf: New file.
1826
        value = getattr(options, option)
1827
        if value is not None:
1828
            server_settings[option] = value
1829
    del options
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1830
    # Force all strings to be unicode
1831
    for option in server_settings.keys():
1832
        if type(server_settings[option]) is str:
1833
            server_settings[option] = unicode(server_settings[option])
28 by Teddy Hogeborn
* server.conf: New file.
1834
    # Now we have our good server settings in "server_settings"
1835
    
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1836
    ##################################################################
1837
    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
1838
    # For convenience
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1839
    debug = server_settings["debug"]
1840
    debuglevel = server_settings["debuglevel"]
1841
    use_dbus = server_settings["use_dbus"]
1842
    use_ipv6 = server_settings["use_ipv6"]
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1843
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1844
    if server_settings["servicename"] != "Mandos":
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1845
        syslogger.setFormatter(logging.Formatter
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1846
                               ('Mandos (%s) [%%(process)d]:'
1847
                                ' %%(levelname)s: %%(message)s'
1848
                                % server_settings["servicename"]))
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
1849
    
28 by Teddy Hogeborn
* server.conf: New file.
1850
    # Parse config file with clients
24.1.179 by Björn Påhlsson
New feature:
1851
    client_defaults = { "timeout": "5m",
1852
                        "extended_timeout": "15m",
1853
                        "interval": "2m",
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1854
                        "checker": "fping -q -- %%(host)s",
1855
                        "host": "",
1856
                        "approval_delay": "0s",
1857
                        "approval_duration": "1s",
28 by Teddy Hogeborn
* server.conf: New file.
1858
                        }
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1859
    client_config = configparser.SafeConfigParser(client_defaults)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1860
    client_config.read(os.path.join(server_settings["configdir"],
1861
                                    "clients.conf"))
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1862
    
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1863
    global mandos_dbus_service
1864
    mandos_dbus_service = None
28 by Teddy Hogeborn
* server.conf: New file.
1865
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1866
    tcp_server = MandosServer((server_settings["address"],
1867
                               server_settings["port"]),
339 by Teddy Hogeborn
Code cleanup.
1868
                              ClientHandler,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1869
                              interface=(server_settings["interface"]
237.2.35 by teddy at bsnet
* mandos (main): Bug fix: Don't try to bind to an empty string
1870
                                         or None),
339 by Teddy Hogeborn
Code cleanup.
1871
                              use_ipv6=use_ipv6,
1872
                              gnutls_priority=
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1873
                              server_settings["priority"],
339 by Teddy Hogeborn
Code cleanup.
1874
                              use_dbus=use_dbus)
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
1875
    if not debug:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1876
        pidfilename = "/var/run/mandos.pid"
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
1877
        try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1878
            pidfile = open(pidfilename, "w")
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
1879
        except IOError:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1880
            logger.error("Could not open file %r", pidfilename)
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
1881
    
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
1882
    try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1883
        uid = pwd.getpwnam("_mandos").pw_uid
1884
        gid = pwd.getpwnam("_mandos").pw_gid
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
1885
    except KeyError:
1886
        try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1887
            uid = pwd.getpwnam("mandos").pw_uid
1888
            gid = pwd.getpwnam("mandos").pw_gid
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
1889
        except KeyError:
1890
            try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1891
                uid = pwd.getpwnam("nobody").pw_uid
1892
                gid = pwd.getpwnam("nobody").pw_gid
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
1893
            except KeyError:
1894
                uid = 65534
1895
                gid = 65534
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1896
    try:
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1897
        os.setgid(gid)
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1898
        os.setuid(uid)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1899
    except OSError as error:
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1900
        if error[0] != errno.EPERM:
1901
            raise error
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
1902
    
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1903
    if not debug and not debuglevel:
1904
        syslogger.setLevel(logging.WARNING)
1905
        console.setLevel(logging.WARNING)
1906
    if debuglevel:
1907
        level = getattr(logging, debuglevel.upper())
1908
        syslogger.setLevel(level)
1909
        console.setLevel(level)
1910
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1911
    if debug:
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1912
        # Enable all possible GnuTLS debugging
1913
        
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1914
        # "Use a log level over 10 to enable all debugging options."
1915
        # - GnuTLS manual
1916
        gnutls.library.functions.gnutls_global_set_log_level(11)
1917
        
1918
        @gnutls.library.types.gnutls_log_func
1919
        def debug_gnutls(level, string):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1920
            logger.debug("GnuTLS: %s", string[:-1])
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1921
        
1922
        (gnutls.library.functions
1923
         .gnutls_global_set_log_function(debug_gnutls))
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1924
        
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1925
        # Redirect stdin so all checkers get /dev/null
1926
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1927
        os.dup2(null, sys.stdin.fileno())
1928
        if null > 2:
1929
            os.close(null)
1930
    else:
1931
        # No console logging
1932
        logger.removeHandler(console)
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1933
    
458 by teddy at bsnet
* mandos (main): Bug fix: Fork before connecting to D-Bus.
1934
    # Need to fork before connecting to D-Bus
1935
    if not debug:
1936
        # Close all input and output, do double fork, etc.
1937
        daemon()
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1938
    
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
1939
    global main_loop
1940
    # From the Avahi example code
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1941
    DBusGMainLoop(set_as_default=True )
1942
    main_loop = gobject.MainLoop()
1943
    bus = dbus.SystemBus()
1944
    # End of Avahi example code
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
1945
    if use_dbus:
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
1946
        try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1947
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
1948
                                            bus, do_not_queue=True)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1949
        except dbus.exceptions.NameExistsException as e:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1950
            logger.error(unicode(e) + ", disabling D-Bus")
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
1951
            use_dbus = False
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1952
            server_settings["use_dbus"] = False
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
1953
            tcp_server.use_dbus = False
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
1954
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1955
    service = AvahiService(name = server_settings["servicename"],
1956
                           servicetype = "_mandos._tcp",
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
1957
                           protocol = protocol, bus = bus)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1958
    if server_settings["interface"]:
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
1959
        service.interface = (if_nametoindex
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1960
                             (str(server_settings["interface"])))
458 by teddy at bsnet
* mandos (main): Bug fix: Fork before connecting to D-Bus.
1961
    
24.1.152 by Björn Påhlsson
bug fixes that prevent problems when runing server as root
1962
    global multiprocessing_manager
1963
    multiprocessing_manager = multiprocessing.Manager()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1964
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1965
    client_class = Client
1966
    if use_dbus:
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
1967
        client_class = functools.partial(ClientDBus, bus = bus)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1968
    def client_config_items(config, section):
1969
        special_settings = {
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1970
            "approved_by_default":
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1971
                lambda: config.getboolean(section,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1972
                                          "approved_by_default"),
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1973
            }
1974
        for name, value in config.items(section):
1975
            try:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1976
                yield (name, special_settings[name]())
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1977
            except KeyError:
1978
                yield (name, value)
1979
    
341 by Teddy Hogeborn
Code cleanup and one bug fix.
1980
    tcp_server.clients.update(set(
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1981
            client_class(name = section,
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1982
                         config= dict(client_config_items(
1983
                        client_config, section)))
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1984
            for section in client_config.sections()))
341 by Teddy Hogeborn
Code cleanup and one bug fix.
1985
    if not tcp_server.clients:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1986
        logger.warning("No clients defined")
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1987
        
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1988
    if not debug:
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
1989
        try:
1990
            with pidfile:
1991
                pid = os.getpid()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1992
                pidfile.write(str(pid) + "\n".encode("utf-8"))
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
1993
            del pidfile
1994
        except IOError:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1995
            logger.error("Could not write to file %r with PID %d",
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
1996
                         pidfilename, pid)
1997
        except NameError:
1998
            # "pidfile" was never created
1999
            pass
2000
        del pidfilename
2001
        
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2002
        signal.signal(signal.SIGINT, signal.SIG_IGN)
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2003
28 by Teddy Hogeborn
* server.conf: New file.
2004
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2005
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2006
    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2007
    if use_dbus:
327 by Teddy Hogeborn
Merge from pipe IPC branch.
2008
        class MandosDBusService(dbus.service.Object):
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2009
            """A D-Bus proxy object"""
2010
            def __init__(self):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2011
                dbus.service.Object.__init__(self, bus, "/")
2012
            _interface = "se.bsnet.fukt.Mandos"
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2013
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2014
            @dbus.service.signal(_interface, signature="o")
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
2015
            def ClientAdded(self, objpath):
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2016
                "D-Bus signal"
2017
                pass
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2018
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2019
            @dbus.service.signal(_interface, signature="ss")
409 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
2020
            def ClientNotFound(self, fingerprint, address):
327 by Teddy Hogeborn
Merge from pipe IPC branch.
2021
                "D-Bus signal"
2022
                pass
2023
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2024
            @dbus.service.signal(_interface, signature="os")
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2025
            def ClientRemoved(self, objpath, name):
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2026
                "D-Bus signal"
2027
                pass
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2028
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2029
            @dbus.service.method(_interface, out_signature="ao")
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2030
            def GetAllClients(self):
283 by Teddy Hogeborn
* mandos (peer_certificate): Handle NULL pointer from
2031
                "D-Bus method"
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2032
                return dbus.Array(c.dbus_object_path
2033
                                  for c in tcp_server.clients)
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2034
            
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
2035
            @dbus.service.method(_interface,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2036
                                 out_signature="a{oa{sv}}")
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2037
            def GetAllClientsWithProperties(self):
283 by Teddy Hogeborn
* mandos (peer_certificate): Handle NULL pointer from
2038
                "D-Bus method"
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2039
                return dbus.Dictionary(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2040
                    ((c.dbus_object_path, c.GetAll(""))
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2041
                     for c in tcp_server.clients),
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2042
                    signature="oa{sv}")
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2043
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2044
            @dbus.service.method(_interface, in_signature="o")
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2045
            def RemoveClient(self, object_path):
283 by Teddy Hogeborn
* mandos (peer_certificate): Handle NULL pointer from
2046
                "D-Bus method"
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2047
                for c in tcp_server.clients:
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2048
                    if c.dbus_object_path == object_path:
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2049
                        tcp_server.clients.remove(c)
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
2050
                        c.remove_from_connection()
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2051
                        # Don't signal anything except ClientRemoved
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2052
                        c.disable(quiet=True)
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2053
                        # Emit D-Bus signal
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2054
                        self.ClientRemoved(object_path, c.name)
2055
                        return
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2056
                raise KeyError(object_path)
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2057
            
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2058
            del _interface
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2059
        
327 by Teddy Hogeborn
Merge from pipe IPC branch.
2060
        mandos_dbus_service = MandosDBusService()
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
2061
    
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2062
    def cleanup():
2063
        "Cleanup function; run on exit"
2064
        service.cleanup()
2065
        
2066
        while tcp_server.clients:
2067
            client = tcp_server.clients.pop()
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2068
            if use_dbus:
2069
                client.remove_from_connection()
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2070
            client.disable_hook = None
2071
            # Don't signal anything except ClientRemoved
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2072
            client.disable(quiet=True)
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2073
            if use_dbus:
2074
                # Emit D-Bus signal
2075
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2076
                                                  client.name)
2077
    
2078
    atexit.register(cleanup)
2079
    
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2080
    for client in tcp_server.clients:
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2081
        if use_dbus:
2082
            # Emit D-Bus signal
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
2083
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
2084
        client.enable()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2085
    
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
2086
    tcp_server.enable()
2087
    tcp_server.server_activate()
2088
    
28 by Teddy Hogeborn
* server.conf: New file.
2089
    # Find out what port we got
2090
    service.port = tcp_server.socket.getsockname()[1]
314 by Teddy Hogeborn
Support not using IPv6 in server:
2091
    if use_ipv6:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2092
        logger.info("Now listening on address %r, port %d,"
2093
                    " flowinfo %d, scope_id %d"
314 by Teddy Hogeborn
Support not using IPv6 in server:
2094
                    % tcp_server.socket.getsockname())
2095
    else:                       # IPv4
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2096
        logger.info("Now listening on address %r, port %d"
314 by Teddy Hogeborn
Support not using IPv6 in server:
2097
                    % tcp_server.socket.getsockname())
28 by Teddy Hogeborn
* server.conf: New file.
2098
    
29 by Teddy Hogeborn
* plugins.d/mandosclient.c (start_mandos_communication): Changed
2099
    #service.interface = tcp_server.socket.getsockname()[3]
28 by Teddy Hogeborn
* server.conf: New file.
2100
    
2101
    try:
2102
        # From the Avahi example code
2103
        try:
336 by Teddy Hogeborn
Code cleanup.
2104
            service.activate()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
2105
        except dbus.exceptions.DBusException as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2106
            logger.critical("DBusException: %s", error)
401 by Teddy Hogeborn
* README (FAQ): Fix typo.
2107
            cleanup()
28 by Teddy Hogeborn
* server.conf: New file.
2108
            sys.exit(1)
2109
        # End of Avahi example code
2110
        
2111
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2112
                             lambda *args, **kwargs:
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
2113
                             (tcp_server.handle_request
2114
                              (*args[2:], **kwargs) or True))
28 by Teddy Hogeborn
* server.conf: New file.
2115
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2116
        logger.debug("Starting main loop")
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2117
        main_loop.run()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
2118
    except AvahiError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2119
        logger.critical("AvahiError: %s", error)
401 by Teddy Hogeborn
* README (FAQ): Fix typo.
2120
        cleanup()
28 by Teddy Hogeborn
* server.conf: New file.
2121
        sys.exit(1)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2122
    except KeyboardInterrupt:
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2123
        if debug:
463.1.5 by teddy at bsnet
* mandos: Use unicode string literals.
2124
            print("", file=sys.stderr)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2125
        logger.debug("Server received KeyboardInterrupt")
2126
    logger.debug("Server exiting")
401 by Teddy Hogeborn
* README (FAQ): Fix typo.
2127
    # Must run before the D-Bus bus name gets deregistered
2128
    cleanup()
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
2129
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2130
if __name__ == '__main__':
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
2131
    main()