82
82
logger.addHandler(console)
84
84
class AvahiError(Exception):
85
def __init__(self, value, *args, **kwargs):
85
def __init__(self, value):
87
super(AvahiError, self).__init__(value, *args, **kwargs)
88
def __unicode__(self):
89
return unicode(repr(self.value))
87
super(AvahiError, self).__init__()
89
return repr(self.value)
91
91
class AvahiServiceError(AvahiError):
201
201
client lives. %() expansions are done at
202
202
runtime with vars(self) as dict, so that for
203
203
instance %(name)s can be used in the command.
204
use_dbus: bool(); Whether to provide D-Bus interface and signals
205
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
204
dbus_object_path: dbus.ObjectPath
206
_timeout: Real variable for 'timeout'
207
_interval: Real variable for 'interval'
208
_timeout_milliseconds: Used when calling gobject.timeout_add()
209
_interval_milliseconds: - '' -
207
def timeout_milliseconds(self):
208
"Return the 'timeout' attribute in milliseconds"
209
return ((self.timeout.days * 24 * 60 * 60 * 1000)
210
+ (self.timeout.seconds * 1000)
211
+ (self.timeout.microseconds // 1000))
213
def interval_milliseconds(self):
214
"Return the 'interval' attribute in milliseconds"
215
return ((self.interval.days * 24 * 60 * 60 * 1000)
216
+ (self.interval.seconds * 1000)
217
+ (self.interval.microseconds // 1000))
219
def __init__(self, name = None, disable_hook=None, config=None,
211
def _set_timeout(self, timeout):
212
"Setter function for the 'timeout' attribute"
213
self._timeout = timeout
214
self._timeout_milliseconds = ((self.timeout.days
215
* 24 * 60 * 60 * 1000)
216
+ (self.timeout.seconds * 1000)
217
+ (self.timeout.microseconds
220
self.PropertyChanged(dbus.String(u"timeout"),
221
(dbus.UInt64(self._timeout_milliseconds,
223
timeout = property(lambda self: self._timeout, _set_timeout)
226
def _set_interval(self, interval):
227
"Setter function for the 'interval' attribute"
228
self._interval = interval
229
self._interval_milliseconds = ((self.interval.days
230
* 24 * 60 * 60 * 1000)
231
+ (self.interval.seconds
233
+ (self.interval.microseconds
236
self.PropertyChanged(dbus.String(u"interval"),
237
(dbus.UInt64(self._interval_milliseconds,
239
interval = property(lambda self: self._interval, _set_interval)
242
def __init__(self, name = None, disable_hook=None, config=None):
221
243
"""Note: the 'checker' key in 'config' sets the
222
244
'checker_command' attribute and *not* the 'checker'
246
self.dbus_object_path = (dbus.ObjectPath
248
+ name.replace(".", "_")))
249
dbus.service.Object.__init__(self, bus,
250
self.dbus_object_path)
225
251
if config is None:
227
254
logger.debug(u"Creating client %r", self.name)
228
self.use_dbus = use_dbus
230
self.dbus_object_path = (dbus.ObjectPath
232
+ self.name.replace(".", "_")))
233
dbus.service.Object.__init__(self, bus,
234
self.dbus_object_path)
235
255
# Uppercase and remove spaces from fingerprint for later
236
256
# comparison purposes with return value from the fingerprint()
268
288
# Schedule a new checker to be started an 'interval' from now,
269
289
# and every interval from then on.
270
290
self.checker_initiator_tag = (gobject.timeout_add
271
(self.interval_milliseconds(),
291
(self._interval_milliseconds,
272
292
self.start_checker))
273
293
# Also start a new checker *right now*.
274
294
self.start_checker()
275
295
# Schedule a disable() when 'timeout' has passed
276
296
self.disable_initiator_tag = (gobject.timeout_add
277
(self.timeout_milliseconds(),
297
(self._timeout_milliseconds,
279
299
self.enabled = True
282
self.PropertyChanged(dbus.String(u"enabled"),
283
dbus.Boolean(True, variant_level=1))
284
self.PropertyChanged(dbus.String(u"last_enabled"),
285
(_datetime_to_dbus(self.last_enabled,
301
self.PropertyChanged(dbus.String(u"enabled"),
302
dbus.Boolean(True, variant_level=1))
303
self.PropertyChanged(dbus.String(u"last_enabled"),
304
(_datetime_to_dbus(self.last_enabled,
288
307
def disable(self):
289
308
"""Disable this client."""
315
333
"""The checker has completed, so take appropriate actions."""
316
334
self.checker_callback_tag = None
317
335
self.checker = None
320
self.PropertyChanged(dbus.String(u"checker_running"),
321
dbus.Boolean(False, variant_level=1))
337
self.PropertyChanged(dbus.String(u"checker_running"),
338
dbus.Boolean(False, variant_level=1))
322
339
if (os.WIFEXITED(condition)
323
340
and (os.WEXITSTATUS(condition) == 0)):
324
341
logger.info(u"Checker for %(name)s succeeded",
328
self.CheckerCompleted(dbus.Boolean(True),
329
dbus.UInt16(condition),
330
dbus.String(command))
344
self.CheckerCompleted(dbus.Boolean(True),
345
dbus.UInt16(condition),
346
dbus.String(command))
331
347
self.bump_timeout()
332
348
elif not os.WIFEXITED(condition):
333
349
logger.warning(u"Checker for %(name)s crashed?",
337
self.CheckerCompleted(dbus.Boolean(False),
338
dbus.UInt16(condition),
339
dbus.String(command))
352
self.CheckerCompleted(dbus.Boolean(False),
353
dbus.UInt16(condition),
354
dbus.String(command))
341
356
logger.info(u"Checker for %(name)s failed",
345
self.CheckerCompleted(dbus.Boolean(False),
346
dbus.UInt16(condition),
347
dbus.String(command))
359
self.CheckerCompleted(dbus.Boolean(False),
360
dbus.UInt16(condition),
361
dbus.String(command))
349
363
def bump_timeout(self):
350
364
"""Bump up the timeout for this client.
354
368
self.last_checked_ok = datetime.datetime.utcnow()
355
369
gobject.source_remove(self.disable_initiator_tag)
356
370
self.disable_initiator_tag = (gobject.timeout_add
357
(self.timeout_milliseconds(),
371
(self._timeout_milliseconds,
361
self.PropertyChanged(
362
dbus.String(u"last_checked_ok"),
363
(_datetime_to_dbus(self.last_checked_ok,
373
self.PropertyChanged(dbus.String(u"last_checked_ok"),
374
(_datetime_to_dbus(self.last_checked_ok,
366
377
def start_checker(self):
367
378
"""Start a new checker subprocess if one is not running.
400
411
self.checker = subprocess.Popen(command,
402
413
shell=True, cwd="/")
405
self.CheckerStarted(command)
406
self.PropertyChanged(
407
dbus.String("checker_running"),
408
dbus.Boolean(True, variant_level=1))
415
self.CheckerStarted(command)
416
self.PropertyChanged(dbus.String("checker_running"),
417
dbus.Boolean(True, variant_level=1))
409
418
self.checker_callback_tag = (gobject.child_watch_add
410
419
(self.checker.pid,
411
420
self.checker_callback,
492
500
if self.last_checked_ok is not None
493
501
else dbus.Boolean (False, variant_level=1)),
494
502
dbus.String("timeout"):
495
dbus.UInt64(self.timeout_milliseconds(),
503
dbus.UInt64(self._timeout_milliseconds,
496
504
variant_level=1),
497
505
dbus.String("interval"):
498
dbus.UInt64(self.interval_milliseconds(),
506
dbus.UInt64(self._interval_milliseconds,
499
507
variant_level=1),
500
508
dbus.String("checker"):
501
509
dbus.String(self.checker_command,
521
529
def SetChecker(self, checker):
522
530
"D-Bus setter method"
523
531
self.checker_command = checker
525
self.PropertyChanged(dbus.String(u"checker"),
526
dbus.String(self.checker_command,
529
533
# SetHost - method
530
534
@dbus.service.method(_interface, in_signature="s")
531
535
def SetHost(self, host):
532
536
"D-Bus setter method"
535
self.PropertyChanged(dbus.String(u"host"),
536
dbus.String(self.host, variant_level=1))
538
539
# SetInterval - method
539
540
@dbus.service.method(_interface, in_signature="t")
540
541
def SetInterval(self, milliseconds):
541
self.interval = datetime.timedelta(0, 0, 0, milliseconds)
543
self.PropertyChanged(dbus.String(u"interval"),
544
(dbus.UInt64(self.interval_milliseconds(),
542
self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
547
544
# SetSecret - method
548
545
@dbus.service.method(_interface, in_signature="ay",
555
552
@dbus.service.method(_interface, in_signature="t")
556
553
def SetTimeout(self, milliseconds):
557
554
self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
559
self.PropertyChanged(dbus.String(u"timeout"),
560
(dbus.UInt64(self.timeout_milliseconds(),
563
556
# Enable - method
564
557
Enable = dbus.service.method(_interface)(enable)
892
parser = optparse.OptionParser(version = "%%prog %s" % version)
885
parser = OptionParser(version = "%%prog %s" % version)
893
886
parser.add_option("-i", "--interface", type="string",
894
887
metavar="IF", help="Bind to interface IF")
895
888
parser.add_option("-a", "--address", type="string",
896
889
help="Address to listen for requests on")
897
890
parser.add_option("-p", "--port", type="int",
898
891
help="Port number to receive requests on")
899
parser.add_option("--check", action="store_true",
892
parser.add_option("--check", action="store_true", default=False,
900
893
help="Run self-test")
901
894
parser.add_option("--debug", action="store_true",
902
895
help="Debug mode; run in foreground and log to"
937
925
server_config.read(os.path.join(options.configdir, "mandos.conf"))
938
926
# Convert the SafeConfigParser object to a dict
939
927
server_settings = server_config.defaults()
940
# Use getboolean on the boolean config options
928
# Use getboolean on the boolean config option
941
929
server_settings["debug"] = (server_config.getboolean
942
930
("DEFAULT", "debug"))
943
server_settings["use_dbus"] = (server_config.getboolean
944
("DEFAULT", "use_dbus"))
945
931
del server_config
947
933
# Override the settings from the config file with command line
948
934
# options, if set.
949
935
for option in ("interface", "address", "port", "debug",
950
"priority", "servicename", "configdir",
936
"priority", "servicename", "configdir"):
952
937
value = getattr(options, option)
953
938
if value is not None:
954
939
server_settings[option] = value
956
941
# Now we have our good server settings in "server_settings"
959
943
debug = server_settings["debug"]
960
use_dbus = server_settings["use_dbus"]
963
946
syslogger.setLevel(logging.WARNING)
1030
1019
avahi.DBUS_PATH_SERVER),
1031
1020
avahi.DBUS_INTERFACE_SERVER)
1032
1021
# End of Avahi example code
1034
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
1022
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
1037
1024
clients.update(Set(Client(name = section,
1039
= dict(client_config.items(section)),
1040
use_dbus = use_dbus)
1026
= dict(client_config.items(section)))
1041
1027
for section in client_config.sections()))
1042
1028
if not clients:
1043
logger.warning(u"No clients defined")
1029
logger.critical(u"No clients defined")
1046
1033
# Redirect stdin so all checkers get /dev/null
1088
1075
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1089
1076
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1092
class MandosServer(dbus.service.Object):
1093
"""A D-Bus proxy object"""
1095
dbus.service.Object.__init__(self, bus,
1097
_interface = u"org.mandos_system.Mandos"
1099
@dbus.service.signal(_interface, signature="oa{sv}")
1100
def ClientAdded(self, objpath, properties):
1104
@dbus.service.signal(_interface, signature="o")
1105
def ClientRemoved(self, objpath):
1109
@dbus.service.method(_interface, out_signature="ao")
1110
def GetAllClients(self):
1111
return dbus.Array(c.dbus_object_path for c in clients)
1113
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1114
def GetAllClientsWithProperties(self):
1115
return dbus.Dictionary(
1116
((c.dbus_object_path, c.GetAllProperties())
1120
@dbus.service.method(_interface, in_signature="o")
1121
def RemoveClient(self, object_path):
1123
if c.dbus_object_path == object_path:
1125
# Don't signal anything except ClientRemoved
1129
self.ClientRemoved(object_path)
1132
@dbus.service.method(_interface)
1078
class MandosServer(dbus.service.Object):
1079
"""A D-Bus proxy object"""
1081
dbus.service.Object.__init__(self, bus,
1083
_interface = u"org.mandos_system.Mandos"
1085
@dbus.service.signal(_interface, signature="oa{sv}")
1086
def ClientAdded(self, objpath, properties):
1090
@dbus.service.signal(_interface, signature="o")
1091
def ClientRemoved(self, objpath):
1095
@dbus.service.method(_interface, out_signature="ao")
1096
def GetAllClients(self):
1097
return dbus.Array(c.dbus_object_path for c in clients)
1099
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1100
def GetAllClientsWithProperties(self):
1101
return dbus.Dictionary(
1102
((c.dbus_object_path, c.GetAllProperties())
1106
@dbus.service.method(_interface, in_signature="o")
1107
def RemoveClient(self, object_path):
1109
if c.dbus_object_path == object_path:
1138
mandos_server = MandosServer()
1117
mandos_server = MandosServer()
1140
1119
for client in clients:
1143
mandos_server.ClientAdded(client.dbus_object_path,
1144
client.GetAllProperties())
1121
mandos_server.ClientAdded(client.dbus_object_path,
1122
client.GetAllProperties())
1145
1123
client.enable()
1147
1125
tcp_server.enable()