170
172
# End of Avahi example code
173
class Client(object):
175
class Client(dbus.service.Object):
174
176
"""A representation of a client host served by this server.
176
178
name: string; from the config file, used in log messages
179
181
secret: bytestring; sent verbatim (over TLS) to client
180
182
host: string; available for use by the checker command
181
183
created: datetime.datetime(); object creation, not client host
182
185
last_checked_ok: datetime.datetime() or None if not yet checked OK
183
186
timeout: datetime.timedelta(); How long from last_checked_ok
184
187
until this client is invalid
200
203
_timeout_milliseconds: Used when calling gobject.timeout_add()
201
204
_interval_milliseconds: - '' -
206
interface = u"org.mandos_system.Mandos.Clients"
208
@dbus.service.method(interface, out_signature="s")
210
"D-Bus getter method"
213
@dbus.service.method(interface, out_signature="s")
214
def getFingerprint(self):
215
"D-Bus getter method"
216
return self.fingerprint
218
@dbus.service.method(interface, in_signature="ay",
220
def setSecret(self, secret):
221
"D-Bus setter method"
203
224
def _set_timeout(self, timeout):
204
"Setter function for 'timeout' attribute"
225
"Setter function for the 'timeout' attribute"
205
226
self._timeout = timeout
206
227
self._timeout_milliseconds = ((self.timeout.days
207
228
* 24 * 60 * 60 * 1000)
208
229
+ (self.timeout.seconds * 1000)
209
230
+ (self.timeout.microseconds
211
timeout = property(lambda self: self._timeout,
233
self.TimeoutChanged(self._timeout_milliseconds)
234
timeout = property(lambda self: self._timeout, _set_timeout)
237
@dbus.service.method(interface, out_signature="t")
238
def getTimeout(self):
239
"D-Bus getter method"
240
return self._timeout_milliseconds
242
@dbus.service.signal(interface, signature="t")
243
def TimeoutChanged(self, t):
214
247
def _set_interval(self, interval):
215
"Setter function for 'interval' attribute"
248
"Setter function for the 'interval' attribute"
216
249
self._interval = interval
217
250
self._interval_milliseconds = ((self.interval.days
218
251
* 24 * 60 * 60 * 1000)
221
254
+ (self.interval.microseconds
223
interval = property(lambda self: self._interval,
257
self.IntervalChanged(self._interval_milliseconds)
258
interval = property(lambda self: self._interval, _set_interval)
225
259
del _set_interval
261
@dbus.service.method(interface, out_signature="t")
262
def getInterval(self):
263
"D-Bus getter method"
264
return self._interval_milliseconds
266
@dbus.service.signal(interface, signature="t")
267
def IntervalChanged(self, t):
226
271
def __init__(self, name = None, stop_hook=None, config=None):
227
272
"""Note: the 'checker' key in 'config' sets the
228
273
'checker_command' attribute and *not* the 'checker'
275
dbus.service.Object.__init__(self, bus,
277
% name.replace(".", "_"))
230
278
if config is None:
240
288
if "secret" in config:
241
289
self.secret = config["secret"].decode(u"base64")
242
290
elif "secfile" in config:
243
secfile = open(os.path.expanduser(os.path.expandvars
244
(config["secfile"])))
245
self.secret = secfile.read()
291
with closing(open(os.path.expanduser
293
(config["secfile"])))) \
295
self.secret = secfile.read()
248
297
raise TypeError(u"No secret or secfile for client %s"
250
299
self.host = config.get("host", "")
251
300
self.created = datetime.datetime.now()
252
302
self.last_checked_ok = None
253
303
self.timeout = string_to_delta(config["timeout"])
254
304
self.interval = string_to_delta(config["interval"])
258
308
self.stop_initiator_tag = None
259
309
self.checker_callback_tag = None
260
310
self.check_command = config["checker"]
262
313
"""Start this client's checker and timeout hooks"""
263
315
# Schedule a new checker to be started an 'interval' from now,
264
316
# and every interval from then on.
265
317
self.checker_initiator_tag = gobject.timeout_add\
271
323
self.stop_initiator_tag = gobject.timeout_add\
272
324
(self._timeout_milliseconds,
327
self.StateChanged(True)
329
@dbus.service.signal(interface, signature="b")
330
def StateChanged(self, started):
276
The possibility that a client might be restarted is left open,
277
but not currently used."""
278
# If this client doesn't have a secret, it is already stopped.
279
if hasattr(self, "secret") and self.secret:
335
"""Stop this client."""
336
if getattr(self, "started", False):
280
337
logger.info(u"Stopping client %s", self.name)
284
340
if getattr(self, "stop_initiator_tag", False):
290
346
self.stop_checker()
291
347
if self.stop_hook:
292
348
self.stop_hook(self)
350
self.StateChanged(False)
293
351
# Do not run this again if called by a gobject.timeout_add
354
Stop = dbus.service.method(interface)(stop)
295
356
def __del__(self):
296
357
self.stop_hook = None
298
360
def checker_callback(self, pid, condition):
299
361
"""The checker has completed, so take appropriate actions."""
300
now = datetime.datetime.now()
301
362
self.checker_callback_tag = None
302
363
self.checker = None
303
364
if os.WIFEXITED(condition) \
304
365
and (os.WEXITSTATUS(condition) == 0):
305
366
logger.info(u"Checker for %(name)s succeeded",
307
self.last_checked_ok = now
308
gobject.source_remove(self.stop_initiator_tag)
309
self.stop_initiator_tag = gobject.timeout_add\
310
(self._timeout_milliseconds,
369
self.CheckerCompleted(True)
312
371
elif not os.WIFEXITED(condition):
313
372
logger.warning(u"Checker for %(name)s crashed?",
375
self.CheckerCompleted(False)
316
377
logger.info(u"Checker for %(name)s failed",
380
self.CheckerCompleted(False)
382
@dbus.service.signal(interface, signature="b")
383
def CheckerCompleted(self, success):
387
def bump_timeout(self):
388
"""Bump up the timeout for this client.
389
This should only be called when the client has been seen,
392
self.last_checked_ok = datetime.datetime.now()
393
gobject.source_remove(self.stop_initiator_tag)
394
self.stop_initiator_tag = gobject.timeout_add\
395
(self._timeout_milliseconds, self.stop)
397
bumpTimeout = dbus.service.method(interface)(bump_timeout)
318
399
def start_checker(self):
319
400
"""Start a new checker subprocess if one is not running.
320
401
If a checker already exists, leave it running and do
355
436
self.checker_callback_tag = gobject.child_watch_add\
356
437
(self.checker.pid,
357
438
self.checker_callback)
440
self.CheckerStarted(command)
358
441
except OSError, error:
359
442
logger.error(u"Failed to start subprocess: %s",
361
444
# Re-run this periodically if run by gobject.timeout_add
447
@dbus.service.signal(interface, signature="s")
448
def CheckerStarted(self, command):
451
@dbus.service.method(interface, out_signature="b")
452
def checkerIsRunning(self):
453
"D-Bus getter method"
454
return self.checker is not None
363
456
def stop_checker(self):
364
457
"""Force the checker process, if any, to stop."""
365
458
if self.checker_callback_tag:
377
470
if error.errno != errno.ESRCH: # No such process
379
472
self.checker = None
474
StopChecker = dbus.service.method(interface)(stop_checker)
380
476
def still_valid(self):
381
477
"""Has the timeout not yet passed for this client?"""
382
480
now = datetime.datetime.now()
383
481
if self.last_checked_ok is None:
384
482
return now < (self.created + self.timeout)
386
484
return now < (self.last_checked_ok + self.timeout)
486
stillValid = dbus.service.method(interface, out_signature="b")\
389
492
def peer_certificate(session):
448
551
def handle(self):
449
552
logger.info(u"TCP connection from: %s",
450
unicode(self.client_address))
553
unicode(self.client_address))
451
554
session = gnutls.connection.ClientSession\
452
555
(self.request, gnutls.connection.X509Credentials())
468
571
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
469
572
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
471
priority = "NORMAL" # Fallback default, since this
473
if self.server.settings["priority"]:
474
priority = self.server.settings["priority"]
574
# Use a fallback default, since this MUST be set.
575
priority = self.server.settings.get("priority", "NORMAL")
475
576
gnutls.library.functions.gnutls_priority_set_direct\
476
577
(session._c_object, priority, None)
520
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
623
class IPv6_TCPServer(SocketServer.ForkingMixIn,
624
SocketServer.TCPServer, object):
521
625
"""IPv6 TCP server. Accepts 'None' as address and/or port.
523
627
settings: Server settings
652
756
def if_nametoindex(interface):
653
757
"Get an interface index the hard way, i.e. using fcntl()"
654
758
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
656
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
657
struct.pack("16s16x", interface))
759
with closing(socket.socket()) as s:
760
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
761
struct.pack("16s16x", interface))
659
762
interface_index = struct.unpack("I", ifreq[16:20])[0]
660
763
return interface_index
661
764
return if_nametoindex(interface)