82
82
logger.addHandler(console)
84
84
class AvahiError(Exception):
85
def __init__(self, value):
85
def __init__(self, value, *args, **kwargs):
87
super(AvahiError, self).__init__()
89
return repr(self.value)
87
super(AvahiError, self).__init__(value, *args, **kwargs)
88
def __unicode__(self):
89
return unicode(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
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: - '' -
204
use_dbus: bool(); Whether to provide D-Bus interface and signals
205
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
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):
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,
243
221
"""Note: the 'checker' key in 'config' sets the
244
222
'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)
251
225
if config is None:
254
227
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)
255
235
# Uppercase and remove spaces from fingerprint for later
256
236
# comparison purposes with return value from the fingerprint()
288
268
# Schedule a new checker to be started an 'interval' from now,
289
269
# and every interval from then on.
290
270
self.checker_initiator_tag = (gobject.timeout_add
291
(self._interval_milliseconds,
271
(self.interval_milliseconds(),
292
272
self.start_checker))
293
273
# Also start a new checker *right now*.
294
274
self.start_checker()
295
275
# Schedule a disable() when 'timeout' has passed
296
276
self.disable_initiator_tag = (gobject.timeout_add
297
(self._timeout_milliseconds,
277
(self.timeout_milliseconds(),
299
279
self.enabled = True
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,
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,
307
288
def disable(self):
308
289
"""Disable this client."""
333
315
"""The checker has completed, so take appropriate actions."""
334
316
self.checker_callback_tag = None
335
317
self.checker = None
337
self.PropertyChanged(dbus.String(u"checker_running"),
338
dbus.Boolean(False, variant_level=1))
320
self.PropertyChanged(dbus.String(u"checker_running"),
321
dbus.Boolean(False, variant_level=1))
339
322
if (os.WIFEXITED(condition)
340
323
and (os.WEXITSTATUS(condition) == 0)):
341
324
logger.info(u"Checker for %(name)s succeeded",
344
self.CheckerCompleted(dbus.Boolean(True),
345
dbus.UInt16(condition),
346
dbus.String(command))
328
self.CheckerCompleted(dbus.Boolean(True),
329
dbus.UInt16(condition),
330
dbus.String(command))
347
331
self.bump_timeout()
348
332
elif not os.WIFEXITED(condition):
349
333
logger.warning(u"Checker for %(name)s crashed?",
352
self.CheckerCompleted(dbus.Boolean(False),
353
dbus.UInt16(condition),
354
dbus.String(command))
337
self.CheckerCompleted(dbus.Boolean(False),
338
dbus.UInt16(condition),
339
dbus.String(command))
356
341
logger.info(u"Checker for %(name)s failed",
359
self.CheckerCompleted(dbus.Boolean(False),
360
dbus.UInt16(condition),
361
dbus.String(command))
345
self.CheckerCompleted(dbus.Boolean(False),
346
dbus.UInt16(condition),
347
dbus.String(command))
363
349
def bump_timeout(self):
364
350
"""Bump up the timeout for this client.
368
354
self.last_checked_ok = datetime.datetime.utcnow()
369
355
gobject.source_remove(self.disable_initiator_tag)
370
356
self.disable_initiator_tag = (gobject.timeout_add
371
(self._timeout_milliseconds,
357
(self.timeout_milliseconds(),
373
self.PropertyChanged(dbus.String(u"last_checked_ok"),
374
(_datetime_to_dbus(self.last_checked_ok,
361
self.PropertyChanged(
362
dbus.String(u"last_checked_ok"),
363
(_datetime_to_dbus(self.last_checked_ok,
377
366
def start_checker(self):
378
367
"""Start a new checker subprocess if one is not running.
411
400
self.checker = subprocess.Popen(command,
413
402
shell=True, cwd="/")
415
self.CheckerStarted(command)
416
self.PropertyChanged(dbus.String("checker_running"),
417
dbus.Boolean(True, variant_level=1))
405
self.CheckerStarted(command)
406
self.PropertyChanged(
407
dbus.String("checker_running"),
408
dbus.Boolean(True, variant_level=1))
418
409
self.checker_callback_tag = (gobject.child_watch_add
419
410
(self.checker.pid,
420
411
self.checker_callback,
500
492
if self.last_checked_ok is not None
501
493
else dbus.Boolean (False, variant_level=1)),
502
494
dbus.String("timeout"):
503
dbus.UInt64(self._timeout_milliseconds,
495
dbus.UInt64(self.timeout_milliseconds(),
504
496
variant_level=1),
505
497
dbus.String("interval"):
506
dbus.UInt64(self._interval_milliseconds,
498
dbus.UInt64(self.interval_milliseconds(),
507
499
variant_level=1),
508
500
dbus.String("checker"):
509
501
dbus.String(self.checker_command,
529
521
def SetChecker(self, checker):
530
522
"D-Bus setter method"
531
523
self.checker_command = checker
525
self.PropertyChanged(dbus.String(u"checker"),
526
dbus.String(self.checker_command,
533
529
# SetHost - method
534
530
@dbus.service.method(_interface, in_signature="s")
535
531
def SetHost(self, host):
536
532
"D-Bus setter method"
535
self.PropertyChanged(dbus.String(u"host"),
536
dbus.String(self.host, variant_level=1))
539
538
# SetInterval - method
540
539
@dbus.service.method(_interface, in_signature="t")
541
540
def SetInterval(self, milliseconds):
542
self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
541
self.interval = datetime.timedelta(0, 0, 0, milliseconds)
543
self.PropertyChanged(dbus.String(u"interval"),
544
(dbus.UInt64(self.interval_milliseconds(),
544
547
# SetSecret - method
545
548
@dbus.service.method(_interface, in_signature="ay",
552
555
@dbus.service.method(_interface, in_signature="t")
553
556
def SetTimeout(self, milliseconds):
554
557
self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
559
self.PropertyChanged(dbus.String(u"timeout"),
560
(dbus.UInt64(self.timeout_milliseconds(),
556
563
# Enable - method
557
564
Enable = dbus.service.method(_interface)(enable)
889
896
help="Address to listen for requests on")
890
897
parser.add_option("-p", "--port", type="int",
891
898
help="Port number to receive requests on")
892
parser.add_option("--check", action="store_true", default=False,
899
parser.add_option("--check", action="store_true",
893
900
help="Run self-test")
894
901
parser.add_option("--debug", action="store_true",
895
902
help="Debug mode; run in foreground and log to"
925
937
server_config.read(os.path.join(options.configdir, "mandos.conf"))
926
938
# Convert the SafeConfigParser object to a dict
927
939
server_settings = server_config.defaults()
928
# Use getboolean on the boolean config option
940
# Use getboolean on the boolean config options
929
941
server_settings["debug"] = (server_config.getboolean
930
942
("DEFAULT", "debug"))
943
server_settings["use_dbus"] = (server_config.getboolean
944
("DEFAULT", "use_dbus"))
931
945
del server_config
933
947
# Override the settings from the config file with command line
934
948
# options, if set.
935
949
for option in ("interface", "address", "port", "debug",
936
"priority", "servicename", "configdir"):
950
"priority", "servicename", "configdir",
937
952
value = getattr(options, option)
938
953
if value is not None:
939
954
server_settings[option] = value
941
956
# Now we have our good server settings in "server_settings"
943
959
debug = server_settings["debug"]
960
use_dbus = server_settings["use_dbus"]
946
963
syslogger.setLevel(logging.WARNING)
978
995
uid = pwd.getpwnam("_mandos").pw_uid
996
gid = pwd.getpwnam("_mandos").pw_gid
981
999
uid = pwd.getpwnam("mandos").pw_uid
1000
gid = pwd.getpwnam("mandos").pw_gid
982
1001
except KeyError:
984
1003
uid = pwd.getpwnam("nobody").pw_uid
1004
gid = pwd.getpwnam("nogroup").pw_gid
985
1005
except KeyError:
988
gid = pwd.getpwnam("_mandos").pw_gid
991
gid = pwd.getpwnam("mandos").pw_gid
994
gid = pwd.getpwnam("nogroup").pw_gid
1019
1030
avahi.DBUS_PATH_SERVER),
1020
1031
avahi.DBUS_INTERFACE_SERVER)
1021
1032
# End of Avahi example code
1022
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
1034
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
1024
1037
clients.update(Set(Client(name = section,
1026
= dict(client_config.items(section)))
1039
= dict(client_config.items(section)),
1040
use_dbus = use_dbus)
1027
1041
for section in client_config.sections()))
1028
1042
if not clients:
1029
logger.critical(u"No clients defined")
1043
logger.warning(u"No clients defined")
1033
1046
# Redirect stdin so all checkers get /dev/null
1075
1088
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1076
1089
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
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:
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)
1117
mandos_server = MandosServer()
1138
mandos_server = MandosServer()
1119
1140
for client in clients:
1121
mandos_server.ClientAdded(client.dbus_object_path,
1122
client.GetAllProperties())
1143
mandos_server.ClientAdded(client.dbus_object_path,
1144
client.GetAllProperties())
1123
1145
client.enable()
1125
1147
tcp_server.enable()