122
139
help="Select all clients")
123
140
parser.add_argument("-v", "--verbose", action="store_true",
124
141
help="Print all fields")
125
parser.add_argument("-j", "--dump-json", action="store_true",
142
parser.add_argument("-j", "--dump-json", dest="commands",
143
action="append_const", default=[],
144
const=command.DumpJSON(),
126
145
help="Dump client data in JSON format")
127
146
enable_disable = parser.add_mutually_exclusive_group()
128
enable_disable.add_argument("-e", "--enable", action="store_true",
147
enable_disable.add_argument("-e", "--enable", dest="commands",
148
action="append_const", default=[],
149
const=command.Enable(),
129
150
help="Enable client")
130
enable_disable.add_argument("-d", "--disable",
151
enable_disable.add_argument("-d", "--disable", dest="commands",
152
action="append_const", default=[],
153
const=command.Disable(),
132
154
help="disable client")
133
parser.add_argument("-b", "--bump-timeout", action="store_true",
155
parser.add_argument("-b", "--bump-timeout", dest="commands",
156
action="append_const", default=[],
157
const=command.BumpTimeout(),
134
158
help="Bump timeout for client")
135
159
start_stop_checker = parser.add_mutually_exclusive_group()
136
160
start_stop_checker.add_argument("--start-checker",
162
action="append_const", default=[],
163
const=command.StartChecker(),
138
164
help="Start checker for client")
139
start_stop_checker.add_argument("--stop-checker",
165
start_stop_checker.add_argument("--stop-checker", dest="commands",
166
action="append_const", default=[],
167
const=command.StopChecker(),
141
168
help="Stop checker for client")
142
parser.add_argument("-V", "--is-enabled", action="store_true",
169
parser.add_argument("-V", "--is-enabled", dest="commands",
170
action="append_const", default=[],
171
const=command.IsEnabled(),
143
172
help="Check if client is enabled")
144
parser.add_argument("-r", "--remove", action="store_true",
173
parser.add_argument("-r", "--remove", dest="commands",
174
action="append_const", default=[],
175
const=command.Remove(),
145
176
help="Remove client")
146
parser.add_argument("-c", "--checker",
177
parser.add_argument("-c", "--checker", dest="commands",
178
action="append", default=[],
179
metavar="COMMAND", type=command.SetChecker,
147
180
help="Set checker command for client")
148
parser.add_argument("-t", "--timeout", type=string_to_delta,
149
help="Set timeout for client")
150
parser.add_argument("--extended-timeout", type=string_to_delta,
151
help="Set extended timeout for client")
152
parser.add_argument("-i", "--interval", type=string_to_delta,
153
help="Set checker interval for client")
182
"-t", "--timeout", dest="commands", action="append",
183
default=[], metavar="TIME",
184
type=command.SetTimeout.argparse(string_to_delta),
185
help="Set timeout for client")
187
"--extended-timeout", dest="commands", action="append",
188
default=[], metavar="TIME",
189
type=command.SetExtendedTimeout.argparse(string_to_delta),
190
help="Set extended timeout for client")
192
"-i", "--interval", dest="commands", action="append",
193
default=[], metavar="TIME",
194
type=command.SetInterval.argparse(string_to_delta),
195
help="Set checker interval for client")
154
196
approve_deny_default = parser.add_mutually_exclusive_group()
155
197
approve_deny_default.add_argument(
156
"--approve-by-default", action="store_true",
157
default=None, dest="approved_by_default",
198
"--approve-by-default", dest="commands",
199
action="append_const", default=[],
200
const=command.ApproveByDefault(),
158
201
help="Set client to be approved by default")
159
202
approve_deny_default.add_argument(
160
"--deny-by-default", action="store_false",
161
dest="approved_by_default",
203
"--deny-by-default", dest="commands",
204
action="append_const", default=[],
205
const=command.DenyByDefault(),
162
206
help="Set client to be denied by default")
163
parser.add_argument("--approval-delay", type=string_to_delta,
164
help="Set delay before client approve/deny")
165
parser.add_argument("--approval-duration", type=string_to_delta,
166
help="Set duration of one client approval")
167
parser.add_argument("-H", "--host", help="Set host for client")
168
parser.add_argument("-s", "--secret",
169
type=argparse.FileType(mode="rb"),
170
help="Set password blob (file) for client")
208
"--approval-delay", dest="commands", action="append",
209
default=[], metavar="TIME",
210
type=command.SetApprovalDelay.argparse(string_to_delta),
211
help="Set delay before client approve/deny")
213
"--approval-duration", dest="commands", action="append",
214
default=[], metavar="TIME",
215
type=command.SetApprovalDuration.argparse(string_to_delta),
216
help="Set duration of one client approval")
217
parser.add_argument("-H", "--host", dest="commands",
218
action="append", default=[], metavar="STRING",
219
type=command.SetHost,
220
help="Set host for client")
222
"-s", "--secret", dest="commands", action="append",
223
default=[], metavar="FILENAME",
224
type=command.SetSecret.argparse(argparse.FileType(mode="rb")),
225
help="Set password blob (file) for client")
171
226
approve_deny = parser.add_mutually_exclusive_group()
172
227
approve_deny.add_argument(
173
"-A", "--approve", action="store_true",
228
"-A", "--approve", dest="commands", action="append_const",
229
default=[], const=command.Approve(),
174
230
help="Approve any current client request")
175
approve_deny.add_argument("-D", "--deny", action="store_true",
231
approve_deny.add_argument("-D", "--deny", dest="commands",
232
action="append_const", default=[],
233
const=command.Deny(),
176
234
help="Deny any current client request")
177
235
parser.add_argument("--debug", action="store_true",
178
236
help="Debug mode (show D-Bus commands)")
369
428
"""Apply additional restrictions on options, not expressible in
372
def has_actions(options):
373
return any((options.enable,
375
options.bump_timeout,
376
options.start_checker,
377
options.stop_checker,
380
options.checker is not None,
381
options.timeout is not None,
382
options.extended_timeout is not None,
383
options.interval is not None,
384
options.approved_by_default is not None,
385
options.approval_delay is not None,
386
options.approval_duration is not None,
387
options.host is not None,
388
options.secret is not None,
431
def has_commands(options, commands=None):
433
commands = (command.Enable,
436
command.StartChecker,
442
command.SetExtendedTimeout,
444
command.ApproveByDefault,
445
command.DenyByDefault,
446
command.SetApprovalDelay,
447
command.SetApprovalDuration,
452
return any(isinstance(cmd, commands)
453
for cmd in options.commands)
392
if has_actions(options) and not (options.client or options.all):
455
if has_commands(options) and not (options.client or options.all):
393
456
parser.error("Options require clients names or --all.")
394
if options.verbose and has_actions(options):
457
if options.verbose and has_commands(options):
395
458
parser.error("--verbose can only be used alone.")
396
if options.dump_json and (options.verbose
397
or has_actions(options)):
459
if (has_commands(options, (command.DumpJSON,))
460
and (options.verbose or len(options.commands) > 1)):
398
461
parser.error("--dump-json can only be used alone.")
399
if options.all and not has_actions(options):
462
if options.all and not has_commands(options):
400
463
parser.error("--all requires an action.")
401
if options.is_enabled and len(options.client) > 1:
464
if (has_commands(options, (command.IsEnabled,))
465
and len(options.client) > 1):
402
466
parser.error("--is-enabled requires exactly one client")
404
options.remove = False
405
if has_actions(options) and not options.deny:
406
parser.error("--remove can only be combined with --deny")
407
options.remove = True
413
class SystemBus(object):
467
if (len(options.commands) > 1
468
and has_commands(options, (command.Remove,))
469
and not has_commands(options, (command.Deny,))):
470
parser.error("--remove can only be combined with --deny")
415
477
object_manager_iface = "org.freedesktop.DBus.ObjectManager"
416
478
def get_managed_objects(self, busname, objectpath):
549
619
return new_object
622
class pydbus_adapter:
623
class SystemBus(dbus.MandosBus):
624
def __init__(self, module=pydbus):
626
self.bus = self.pydbus.SystemBus()
628
@contextlib.contextmanager
629
def convert_exception(self, exception_class=dbus.Error):
632
except gi.repository.GLib.Error as e:
633
# This does what "raise from" would do
634
exc = exception_class(*e.args)
638
def call_method(self, methodname, busname, objectpath,
640
proxy_object = self.get(busname, objectpath)
641
log.debug("D-Bus: %s:%s:%s.%s(%s)", busname, objectpath,
642
interface, methodname,
643
", ".join(repr(a) for a in args))
644
method = getattr(proxy_object[interface], methodname)
645
with self.convert_exception():
648
def get(self, busname, objectpath):
649
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
651
with self.convert_exception(dbus.ConnectFailed):
652
if sys.version_info.major <= 2:
653
with warnings.catch_warnings():
654
warnings.filterwarnings(
655
"ignore", "", DeprecationWarning,
656
r"^xml\.etree\.ElementTree$")
657
return self.bus.get(busname, objectpath)
659
return self.bus.get(busname, objectpath)
661
def set_property(self, busname, objectpath, interface, key,
663
proxy_object = self.get(busname, objectpath)
664
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", busname,
665
objectpath, self.properties_iface, interface,
667
setattr(proxy_object[interface], key, value)
669
class CachingBus(SystemBus):
670
"""A caching layer for pydbus_adapter.SystemBus"""
671
def __init__(self, *args, **kwargs):
672
self.object_cache = {}
673
super(pydbus_adapter.CachingBus,
674
self).__init__(*args, **kwargs)
675
def get(self, busname, objectpath):
677
return self.object_cache[(busname, objectpath)]
679
new_object = (super(pydbus_adapter.CachingBus, self)
680
.get(busname, objectpath))
681
self.object_cache[(busname, objectpath)] = new_object
552
685
def commands_from_options(options):
556
if options.is_enabled:
557
commands.append(command.IsEnabled())
560
commands.append(command.Approve())
563
commands.append(command.Deny())
566
commands.append(command.Remove())
568
if options.dump_json:
569
commands.append(command.DumpJSON())
572
commands.append(command.Enable())
575
commands.append(command.Disable())
577
if options.bump_timeout:
578
commands.append(command.BumpTimeout())
580
if options.start_checker:
581
commands.append(command.StartChecker())
583
if options.stop_checker:
584
commands.append(command.StopChecker())
586
if options.approved_by_default is not None:
587
if options.approved_by_default:
588
commands.append(command.ApproveByDefault())
687
commands = list(options.commands)
689
def find_cmd(cmd, commands):
691
for i, c in enumerate(commands):
692
if isinstance(c, cmd):
696
# If command.Remove is present, move any instances of command.Deny
697
# to occur ahead of command.Remove.
698
index_of_remove = find_cmd(command.Remove, commands)
699
before_remove = commands[:index_of_remove]
700
after_remove = commands[index_of_remove:]
702
for cmd in after_remove:
703
if isinstance(cmd, command.Deny):
704
before_remove.append(cmd)
590
commands.append(command.DenyByDefault())
592
if options.checker is not None:
593
commands.append(command.SetChecker(options.checker))
595
if options.host is not None:
596
commands.append(command.SetHost(options.host))
598
if options.secret is not None:
599
commands.append(command.SetSecret(options.secret))
601
if options.timeout is not None:
602
commands.append(command.SetTimeout(options.timeout))
604
if options.extended_timeout:
606
command.SetExtendedTimeout(options.extended_timeout))
608
if options.interval is not None:
609
commands.append(command.SetInterval(options.interval))
611
if options.approval_delay is not None:
613
command.SetApprovalDelay(options.approval_delay))
615
if options.approval_duration is not None:
617
command.SetApprovalDuration(options.approval_duration))
706
cleaned_after.append(cmd)
707
if cleaned_after != after_remove:
708
commands = before_remove + cleaned_after
619
710
# If no command option has been given, show table of clients,
620
711
# optionally verbosely
967
1063
def test_actions_requires_client_or_all(self):
968
1064
for action, value in self.actions.items():
969
options = self.parser.parse_args()
970
setattr(options, action, value)
1065
args = self.actionargs(action, value)
971
1066
with self.assertParseError():
972
self.check_option_syntax(options)
1067
self.parse_args(args)
974
# This mostly corresponds to the definition from has_actions() in
1069
# This mostly corresponds to the definition from has_commands() in
975
1070
# check_option_syntax()
977
# The actual values set here are not that important, but we do
978
# at least stick to the correct types, even though they are
982
"bump_timeout": True,
983
"start_checker": True,
984
"stop_checker": True,
988
"timeout": datetime.timedelta(),
989
"extended_timeout": datetime.timedelta(),
990
"interval": datetime.timedelta(),
991
"approved_by_default": True,
992
"approval_delay": datetime.timedelta(),
993
"approval_duration": datetime.timedelta(),
995
"secret": io.BytesIO(b"x"),
1074
"--bump-timeout": None,
1075
"--start-checker": None,
1076
"--stop-checker": None,
1077
"--is-enabled": None,
1080
"--timeout": "PT0S",
1081
"--extended-timeout": "PT0S",
1082
"--interval": "PT0S",
1083
"--approve-by-default": None,
1084
"--deny-by-default": None,
1085
"--approval-delay": "PT0S",
1086
"--approval-duration": "PT0S",
1087
"--host": "hostname",
1088
"--secret": "/dev/null",
1094
def actionargs(action, value, *args):
1095
if value is not None:
1096
return [action, value] + list(args)
1098
return [action] + list(args)
1000
1100
@contextlib.contextmanager
1001
1101
def assertParseError(self):
1002
1102
with self.assertRaises(SystemExit) as e:
1024
1128
def test_actions_all_conflicts_with_verbose(self):
1025
1129
for action, value in self.actions.items():
1026
options = self.parser.parse_args()
1027
setattr(options, action, value)
1029
options.verbose = True
1130
args = self.actionargs(action, value, "--all",
1030
1132
with self.assertParseError():
1031
self.check_option_syntax(options)
1133
self.parse_args(args)
1033
1135
def test_actions_with_client_conflicts_with_verbose(self):
1034
1136
for action, value in self.actions.items():
1035
options = self.parser.parse_args()
1036
setattr(options, action, value)
1037
options.verbose = True
1038
options.client = ["client"]
1137
args = self.actionargs(action, value, "--verbose",
1039
1139
with self.assertParseError():
1040
self.check_option_syntax(options)
1140
self.parse_args(args)
1042
1142
def test_dump_json_conflicts_with_verbose(self):
1043
options = self.parser.parse_args()
1044
options.dump_json = True
1045
options.verbose = True
1143
args = ["--dump-json", "--verbose"]
1046
1144
with self.assertParseError():
1047
self.check_option_syntax(options)
1145
self.parse_args(args)
1049
1147
def test_dump_json_conflicts_with_action(self):
1050
1148
for action, value in self.actions.items():
1051
options = self.parser.parse_args()
1052
setattr(options, action, value)
1053
options.dump_json = True
1149
args = self.actionargs(action, value, "--dump-json")
1054
1150
with self.assertParseError():
1055
self.check_option_syntax(options)
1151
self.parse_args(args)
1057
1153
def test_all_can_not_be_alone(self):
1058
options = self.parser.parse_args()
1060
1155
with self.assertParseError():
1061
self.check_option_syntax(options)
1156
self.parse_args(args)
1063
1158
def test_all_is_ok_with_any_action(self):
1064
1159
for action, value in self.actions.items():
1065
options = self.parser.parse_args()
1066
setattr(options, action, value)
1068
self.check_option_syntax(options)
1160
args = self.actionargs(action, value, "--all")
1161
self.parse_args(args)
1070
1163
def test_any_action_is_ok_with_one_client(self):
1071
1164
for action, value in self.actions.items():
1072
options = self.parser.parse_args()
1073
setattr(options, action, value)
1074
options.client = ["client"]
1075
self.check_option_syntax(options)
1165
args = self.actionargs(action, value, "client")
1166
self.parse_args(args)
1077
1168
def test_one_client_with_all_actions_except_is_enabled(self):
1078
options = self.parser.parse_args()
1079
1169
for action, value in self.actions.items():
1080
if action == "is_enabled":
1170
if action == "--is-enabled":
1082
setattr(options, action, value)
1083
options.client = ["client"]
1084
self.check_option_syntax(options)
1172
args = self.actionargs(action, value, "client")
1173
self.parse_args(args)
1086
1175
def test_two_clients_with_all_actions_except_is_enabled(self):
1087
options = self.parser.parse_args()
1088
1176
for action, value in self.actions.items():
1089
if action == "is_enabled":
1177
if action == "--is-enabled":
1091
setattr(options, action, value)
1092
options.client = ["client1", "client2"]
1093
self.check_option_syntax(options)
1179
args = self.actionargs(action, value, "client1",
1181
self.parse_args(args)
1095
1183
def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1096
1184
for action, value in self.actions.items():
1097
if action == "is_enabled":
1185
if action == "--is-enabled":
1099
options = self.parser.parse_args()
1100
setattr(options, action, value)
1101
options.client = ["client1", "client2"]
1102
self.check_option_syntax(options)
1187
args = self.actionargs(action, value, "client1",
1189
self.parse_args(args)
1104
1191
def test_is_enabled_fails_without_client(self):
1105
options = self.parser.parse_args()
1106
options.is_enabled = True
1192
args = ["--is-enabled"]
1107
1193
with self.assertParseError():
1108
self.check_option_syntax(options)
1194
self.parse_args(args)
1110
1196
def test_is_enabled_fails_with_two_clients(self):
1111
options = self.parser.parse_args()
1112
options.is_enabled = True
1113
options.client = ["client1", "client2"]
1197
args = ["--is-enabled", "client1", "client2"]
1114
1198
with self.assertParseError():
1115
self.check_option_syntax(options)
1199
self.parse_args(args)
1117
1201
def test_remove_can_only_be_combined_with_action_deny(self):
1118
1202
for action, value in self.actions.items():
1119
if action in {"remove", "deny"}:
1203
if action in {"--remove", "--deny"}:
1121
options = self.parser.parse_args()
1122
setattr(options, action, value)
1124
options.remove = True
1205
args = self.actionargs(action, value, "--all",
1125
1207
with self.assertParseError():
1126
self.check_option_syntax(options)
1208
self.parse_args(args)
1129
1211
class Test_dbus_exceptions(unittest.TestCase):
1516
1625
self.assertIs(obj1, obj1b)
1628
class Test_pydbus_adapter_SystemBus(TestCaseWithAssertLogs):
1630
def Stub_pydbus_func(self, func):
1632
"""stub pydbus module"""
1635
def get(busname, objectpath):
1636
DBusObject = collections.namedtuple(
1637
"DBusObject", ("methodname",))
1638
return {"interface":
1639
DBusObject(methodname=func)}
1642
def call_method(self, bus, methodname, busname, objectpath,
1644
with self.assertLogs(log, logging.DEBUG):
1645
return bus.call_method(methodname, busname, objectpath,
1648
def test_call_method_returns(self):
1649
expected_method_return = Unique()
1650
method_args = (Unique(), Unique())
1652
self.assertEqual(len(method_args), len(args))
1653
for marg, arg in zip(method_args, args):
1654
self.assertIs(marg, arg)
1655
return expected_method_return
1656
stub_pydbus = self.Stub_pydbus_func(func)
1657
bus = pydbus_adapter.SystemBus(stub_pydbus)
1658
ret = self.call_method(bus, "methodname", "busname",
1659
"objectpath", "interface",
1661
self.assertIs(ret, expected_method_return)
1663
def test_call_method_handles_exception(self):
1664
dbus_logger = logging.getLogger("dbus.proxies")
1667
raise gi.repository.GLib.Error()
1669
stub_pydbus = self.Stub_pydbus_func(func)
1670
bus = pydbus_adapter.SystemBus(stub_pydbus)
1672
with self.assertRaises(dbus.Error) as e:
1673
self.call_method(bus, "methodname", "busname",
1674
"objectpath", "interface")
1676
self.assertNotIsInstance(e, dbus.ConnectFailed)
1678
def test_get_converts_to_correct_exception(self):
1679
bus = pydbus_adapter.SystemBus(
1680
self.fake_pydbus_raises_exception_on_connect)
1681
with self.assertRaises(dbus.ConnectFailed):
1682
self.call_method(bus, "methodname", "busname",
1683
"objectpath", "interface")
1685
class fake_pydbus_raises_exception_on_connect:
1686
"""fake dbus-python module"""
1689
def get(busname, objectpath):
1690
raise gi.repository.GLib.Error()
1691
Bus = collections.namedtuple("Bus", ["get"])
1694
def test_set_property_uses_setattr(self):
1701
def get(busname, objectpath):
1702
return {"interface": obj}
1703
bus = pydbus_adapter.SystemBus(pydbus_spy)
1705
bus.set_property("busname", "objectpath", "interface", "key",
1707
self.assertIs(value, obj.key)
1709
def test_get_suppresses_xml_deprecation_warning(self):
1710
if sys.version_info.major >= 3:
1712
class stub_pydbus_get:
1715
def get(busname, objectpath):
1716
warnings.warn_explicit(
1717
"deprecated", DeprecationWarning,
1718
"xml.etree.ElementTree", 0)
1719
bus = pydbus_adapter.SystemBus(stub_pydbus_get)
1720
with warnings.catch_warnings(record=True) as w:
1721
warnings.simplefilter("always")
1722
bus.get("busname", "objectpath")
1723
self.assertEqual(0, len(w))
1726
class Test_pydbus_adapter_CachingBus(unittest.TestCase):
1728
"""stub pydbus module"""
1731
def get(busname, objectpath):
1735
self.bus = pydbus_adapter.CachingBus(self.stub_pydbus)
1737
def test_returns_distinct_objectpaths(self):
1738
obj1 = self.bus.get("busname", "objectpath1")
1739
self.assertIsInstance(obj1, Unique)
1740
obj2 = self.bus.get("busname", "objectpath2")
1741
self.assertIsInstance(obj2, Unique)
1742
self.assertIsNot(obj1, obj2)
1744
def test_returns_distinct_busnames(self):
1745
obj1 = self.bus.get("busname1", "objectpath")
1746
self.assertIsInstance(obj1, Unique)
1747
obj2 = self.bus.get("busname2", "objectpath")
1748
self.assertIsInstance(obj2, Unique)
1749
self.assertIsNot(obj1, obj2)
1751
def test_returns_distinct_both(self):
1752
obj1 = self.bus.get("busname1", "objectpath")
1753
self.assertIsInstance(obj1, Unique)
1754
obj2 = self.bus.get("busname2", "objectpath")
1755
self.assertIsInstance(obj2, Unique)
1756
self.assertIsNot(obj1, obj2)
1758
def test_returns_same(self):
1759
obj1 = self.bus.get("busname", "objectpath")
1760
self.assertIsInstance(obj1, Unique)
1761
obj2 = self.bus.get("busname", "objectpath")
1762
self.assertIsInstance(obj2, Unique)
1763
self.assertIs(obj1, obj2)
1765
def test_returns_same_old(self):
1766
obj1 = self.bus.get("busname1", "objectpath1")
1767
self.assertIsInstance(obj1, Unique)
1768
obj2 = self.bus.get("busname2", "objectpath2")
1769
self.assertIsInstance(obj2, Unique)
1770
obj1b = self.bus.get("busname1", "objectpath1")
1771
self.assertIsInstance(obj1b, Unique)
1772
self.assertIsNot(obj1, obj2)
1773
self.assertIsNot(obj2, obj1b)
1774
self.assertIs(obj1, obj1b)
1519
1777
class Test_commands_from_options(unittest.TestCase):
1521
1779
def setUp(self):