Debian Codegraph @

src/libsystemd/sd-login/test-sd-login.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-login.h"
4
5 #include "alloc-util.h"
6 #include "errno-util.h"
7 #include "format-util.h"
8 #include "log.h"
9 #include "main-func.h"
10 #include "parse-util.h"
11 #include "string-util.h"
12 #include "strv.h"
13
14 static const char *arg_verb = NULL; /* NULL means all */
15 static pid_t arg_pid = 0; /* 0 == self */
16
17 static int print_info(void) {
18 const char* const *verbs = arg_verb ?
19 STRV_MAKE_CONST(arg_verb) :
20 STRV_MAKE_CONST("session",
21 "unit",
22 "user_unit",
23 "machine_name",
24 "slice",
25 "user_slice",
26 "owner_uid",
27 "cgroup");
28 int r = 0;
29
30 STRV_FOREACH(verb, verbs) {
31 _cleanup_free_ char *ans = NULL;
32 int k;
33
34 if (streq(*verb, "session"))
35 k = sd_pid_get_session(arg_pid, &ans);
36 else if (streq(*verb, "unit"))
37 k = sd_pid_get_unit(arg_pid, &ans);
38 else if (streq(*verb, "user_unit"))
39 k = sd_pid_get_user_unit(arg_pid, &ans);
40 else if (streq(*verb, "machine_name"))
41 k = sd_pid_get_machine_name(arg_pid, &ans);
42 else if (streq(*verb, "slice"))
43 k = sd_pid_get_slice(arg_pid, &ans);
44 else if (streq(*verb, "user_slice"))
45 k = sd_pid_get_user_slice(arg_pid, &ans);
46 else if (streq(*verb, "owner_uid")) {
47 uid_t owner;
48
49 k = sd_pid_get_owner_uid(arg_pid, &owner);
50 if (k < 0)
51 log_info_errno(k, "sd_pid_get_%s("PID_FMT") → %m", *verb, arg_pid);
52 else
53 log_info("sd_pid_get_%s("PID_FMT") → "UID_FMT, *verb, arg_pid, owner);
54 RET_GATHER(r, k);
55 continue;
56 } else if (streq(*verb, "cgroup"))
57 k = sd_pid_get_cgroup(arg_pid, &ans);
58 else
59 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb '%s'.", *verb);
60
61 log_info("sd_pid_get_%s("PID_FMT") → %s",
62 *verb, arg_pid, k < 0 ? STRERROR(k) : ans);
63 RET_GATHER(r, k);
64 }
65
66 return r;
67 }
68
69 static int parse_argv(int argc, char *argv[]) {
70 int r;
71
72 if (argc > 3)
73 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
74 "Syntax: test-sd-login [VERB|all [PID]]");
75
76 arg_verb = streq_ptr(argv[1], "all") ? NULL : argv[1];
77
78 if (argc == 3) {
79 r = parse_pid(argv[2], &arg_pid);
80 if (r < 0)
81 return log_error_errno(r, "Cannot parse PID %s: %m", argv[2]);
82 }
83
84 return 0;
85 }
86
87 static int run(int argc, char *argv[]) {
88 int r;
89
90 r = parse_argv(argc, argv);
91 if (r < 0)
92 return r;
93
94 r = print_info();
95 if (argc > 1)
96 /* We were called manually… */
97 return r;
98
99 /* This is how we get executed by the test suite.
100 * Do not return the error. */
101 assert_se(IN_SET(r, 0, -ENODATA, -ENOENT));
102 return 0;
103 }
104
105 DEFINE_MAIN_FUNCTION(run);