udev: String substitutions can be done in ENV, too
[systemd_ALT.git] / src / notify / notify.c
blobf63ec8b355f25e648caba00dfe2f57755a3a2950
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <errno.h>
4 #include <getopt.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
9 #include "sd-daemon.h"
11 #include "alloc-util.h"
12 #include "build.h"
13 #include "env-util.h"
14 #include "fd-util.h"
15 #include "fdset.h"
16 #include "format-util.h"
17 #include "log.h"
18 #include "main-func.h"
19 #include "parse-util.h"
20 #include "pretty-print.h"
21 #include "process-util.h"
22 #include "string-util.h"
23 #include "strv.h"
24 #include "terminal-util.h"
25 #include "time-util.h"
26 #include "user-util.h"
28 static bool arg_ready = false;
29 static bool arg_reloading = false;
30 static bool arg_stopping = false;
31 static pid_t arg_pid = 0;
32 static const char *arg_status = NULL;
33 static bool arg_booted = false;
34 static uid_t arg_uid = UID_INVALID;
35 static gid_t arg_gid = GID_INVALID;
36 static bool arg_no_block = false;
37 static char **arg_env = NULL;
38 static char **arg_exec = NULL;
39 static FDSet *arg_fds = NULL;
40 static char *arg_fdname = NULL;
42 STATIC_DESTRUCTOR_REGISTER(arg_env, strv_freep);
43 STATIC_DESTRUCTOR_REGISTER(arg_exec, strv_freep);
44 STATIC_DESTRUCTOR_REGISTER(arg_fds, fdset_freep);
45 STATIC_DESTRUCTOR_REGISTER(arg_fdname, freep);
47 static int help(void) {
48 _cleanup_free_ char *link = NULL;
49 int r;
51 r = terminal_urlify_man("systemd-notify", "1", &link);
52 if (r < 0)
53 return log_oom();
55 printf("%s [OPTIONS...] [VARIABLE=VALUE...]\n"
56 "%s [OPTIONS...] --exec [VARIABLE=VALUE...] ; CMDLINE...\n"
57 "\n%sNotify the init system about service status updates.%s\n\n"
58 " -h --help Show this help\n"
59 " --version Show package version\n"
60 " --ready Inform the service manager about service start-up/reload\n"
61 " completion\n"
62 " --reloading Inform the service manager about configuration reloading\n"
63 " --stopping Inform the service manager about service shutdown\n"
64 " --pid[=PID] Set main PID of daemon\n"
65 " --uid=USER Set user to send from\n"
66 " --status=TEXT Set status text\n"
67 " --booted Check if the system was booted up with systemd\n"
68 " --no-block Do not wait until operation finished\n"
69 " --exec Execute command line separated by ';' once done\n"
70 " --fd=FD Pass specified file descriptor with along with message\n"
71 " --fdname=NAME Name to assign to passed file descriptor(s)\n"
72 "\nSee the %s for details.\n",
73 program_invocation_short_name,
74 program_invocation_short_name,
75 ansi_highlight(),
76 ansi_normal(),
77 link);
79 return 0;
82 static pid_t manager_pid(void) {
83 const char *e;
84 pid_t pid;
85 int r;
87 /* If we run as a service managed by systemd --user the $MANAGERPID environment variable points to
88 * the service manager's PID. */
89 e = getenv("MANAGERPID");
90 if (!e)
91 return 0;
93 r = parse_pid(e, &pid);
94 if (r < 0) {
95 log_warning_errno(r, "$MANAGERPID is set to an invalid PID, ignoring: %s", e);
96 return 0;
99 return pid;
102 static int parse_argv(int argc, char *argv[]) {
104 enum {
105 ARG_READY = 0x100,
106 ARG_RELOADING,
107 ARG_STOPPING,
108 ARG_VERSION,
109 ARG_PID,
110 ARG_STATUS,
111 ARG_BOOTED,
112 ARG_UID,
113 ARG_NO_BLOCK,
114 ARG_EXEC,
115 ARG_FD,
116 ARG_FDNAME,
119 static const struct option options[] = {
120 { "help", no_argument, NULL, 'h' },
121 { "version", no_argument, NULL, ARG_VERSION },
122 { "ready", no_argument, NULL, ARG_READY },
123 { "reloading", no_argument, NULL, ARG_RELOADING },
124 { "stopping", no_argument, NULL, ARG_STOPPING },
125 { "pid", optional_argument, NULL, ARG_PID },
126 { "status", required_argument, NULL, ARG_STATUS },
127 { "booted", no_argument, NULL, ARG_BOOTED },
128 { "uid", required_argument, NULL, ARG_UID },
129 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
130 { "exec", no_argument, NULL, ARG_EXEC },
131 { "fd", required_argument, NULL, ARG_FD },
132 { "fdname", required_argument, NULL, ARG_FDNAME },
136 _cleanup_fdset_free_ FDSet *passed = NULL;
137 bool do_exec = false;
138 int c, r, n_env;
140 assert(argc >= 0);
141 assert(argv);
143 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
145 switch (c) {
147 case 'h':
148 return help();
150 case ARG_VERSION:
151 return version();
153 case ARG_READY:
154 arg_ready = true;
155 break;
157 case ARG_RELOADING:
158 arg_reloading = true;
159 break;
161 case ARG_STOPPING:
162 arg_stopping = true;
163 break;
165 case ARG_PID:
166 if (isempty(optarg) || streq(optarg, "auto")) {
167 arg_pid = getppid();
169 if (arg_pid <= 1 ||
170 arg_pid == manager_pid()) /* Don't send from PID 1 or the service
171 * manager's PID (which might be distinct from
172 * 1, if we are a --user instance), that'd just
173 * be confusing for the service manager */
174 arg_pid = getpid_cached();
175 } else if (streq(optarg, "parent"))
176 arg_pid = getppid();
177 else if (streq(optarg, "self"))
178 arg_pid = getpid_cached();
179 else {
180 r = parse_pid(optarg, &arg_pid);
181 if (r < 0)
182 return log_error_errno(r, "Failed to parse PID %s.", optarg);
185 break;
187 case ARG_STATUS:
188 arg_status = optarg;
189 break;
191 case ARG_BOOTED:
192 arg_booted = true;
193 break;
195 case ARG_UID: {
196 const char *u = optarg;
198 r = get_user_creds(&u, &arg_uid, &arg_gid, NULL, NULL, 0);
199 if (r == -ESRCH) /* If the user doesn't exist, then accept it anyway as numeric */
200 r = parse_uid(u, &arg_uid);
201 if (r < 0)
202 return log_error_errno(r, "Can't resolve user %s: %m", optarg);
204 break;
207 case ARG_NO_BLOCK:
208 arg_no_block = true;
209 break;
211 case ARG_EXEC:
212 do_exec = true;
213 break;
215 case ARG_FD: {
216 _cleanup_close_ int owned_fd = -EBADF;
217 int fdnr;
219 fdnr = parse_fd(optarg);
220 if (fdnr < 0)
221 return log_error_errno(fdnr, "Failed to parse file descriptor: %s", optarg);
223 if (!passed) {
224 /* Take possession of all passed fds */
225 r = fdset_new_fill(/* filter_cloexec= */ 0, &passed);
226 if (r < 0)
227 return log_error_errno(r, "Failed to take possession of passed file descriptors: %m");
230 if (fdnr < 3) {
231 /* For stdin/stdout/stderr we want to keep the fd, too, hence make a copy */
232 owned_fd = fcntl(fdnr, F_DUPFD_CLOEXEC, 3);
233 if (owned_fd < 0)
234 return log_error_errno(errno, "Failed to duplicate file descriptor: %m");
235 } else {
236 /* Otherwise, move the fd over */
237 owned_fd = fdset_remove(passed, fdnr);
238 if (owned_fd < 0)
239 return log_error_errno(owned_fd, "Specified file descriptor '%i' not passed or specified more than once: %m", fdnr);
242 if (!arg_fds) {
243 arg_fds = fdset_new();
244 if (!arg_fds)
245 return log_oom();
248 r = fdset_consume(arg_fds, TAKE_FD(owned_fd));
249 if (r < 0)
250 return log_error_errno(r, "Failed to add file descriptor to set: %m");
251 break;
254 case ARG_FDNAME:
255 if (!fdname_is_valid(optarg))
256 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File descriptor name invalid: %s", optarg);
258 if (free_and_strdup(&arg_fdname, optarg) < 0)
259 return log_oom();
261 break;
263 case '?':
264 return -EINVAL;
266 default:
267 assert_not_reached();
271 if (optind >= argc &&
272 !arg_ready &&
273 !arg_stopping &&
274 !arg_reloading &&
275 !arg_status &&
276 !arg_pid &&
277 !arg_booted &&
278 fdset_isempty(arg_fds)) {
279 help();
280 return -EINVAL;
283 if (arg_fdname && fdset_isempty(arg_fds))
284 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No file descriptors passed, but --fdname= set, refusing.");
286 if (do_exec) {
287 int i;
289 for (i = optind; i < argc; i++)
290 if (streq(argv[i], ";"))
291 break;
293 if (i >= argc)
294 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "If --exec is used argument list must contain ';' separator, refusing.");
295 if (i+1 == argc)
296 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Empty command line specified after ';' separator, refusing");
298 arg_exec = strv_copy_n(argv + i + 1, argc - i - 1);
299 if (!arg_exec)
300 return log_oom();
302 n_env = i - optind;
303 } else
304 n_env = argc - optind;
306 if (n_env > 0) {
307 arg_env = strv_copy_n(argv + optind, n_env);
308 if (!arg_env)
309 return log_oom();
312 if (!fdset_isempty(passed))
313 log_warning("Warning: %u more file descriptors passed than referenced with --fd=.", fdset_size(passed));
315 return 1;
318 static int run(int argc, char* argv[]) {
319 _cleanup_free_ char *status = NULL, *cpid = NULL, *n = NULL, *monotonic_usec = NULL, *fdn = NULL;
320 _cleanup_strv_free_ char **final_env = NULL;
321 char* our_env[9];
322 size_t i = 0;
323 pid_t source_pid;
324 int r;
326 log_show_color(true);
327 log_parse_environment();
328 log_open();
330 r = parse_argv(argc, argv);
331 if (r <= 0)
332 return r;
334 if (arg_booted) {
335 r = sd_booted();
336 if (r < 0)
337 log_debug_errno(r, "Failed to determine whether we are booted with systemd, assuming we aren't: %m");
338 else
339 log_debug("The system %s booted with systemd.", r ? "was" : "was not");
341 return r <= 0;
344 if (arg_reloading) {
345 our_env[i++] = (char*) "RELOADING=1";
347 if (asprintf(&monotonic_usec, "MONOTONIC_USEC=" USEC_FMT, now(CLOCK_MONOTONIC)) < 0)
348 return log_oom();
350 our_env[i++] = monotonic_usec;
353 if (arg_ready)
354 our_env[i++] = (char*) "READY=1";
356 if (arg_stopping)
357 our_env[i++] = (char*) "STOPPING=1";
359 if (arg_status) {
360 status = strjoin("STATUS=", arg_status);
361 if (!status)
362 return log_oom();
364 our_env[i++] = status;
367 if (arg_pid > 0) {
368 if (asprintf(&cpid, "MAINPID="PID_FMT, arg_pid) < 0)
369 return log_oom();
371 our_env[i++] = cpid;
374 if (!fdset_isempty(arg_fds)) {
375 our_env[i++] = (char*) "FDSTORE=1";
377 if (arg_fdname) {
378 fdn = strjoin("FDNAME=", arg_fdname);
379 if (!fdn)
380 return log_oom();
382 our_env[i++] = fdn;
386 our_env[i++] = NULL;
388 final_env = strv_env_merge(our_env, arg_env);
389 if (!final_env)
390 return log_oom();
392 if (strv_isempty(final_env))
393 return 0;
395 n = strv_join(final_env, "\n");
396 if (!n)
397 return log_oom();
399 /* If this is requested change to the requested UID/GID. Note that we only change the real UID here, and leave
400 the effective UID in effect (which is 0 for this to work). That's because we want the privileges to fake the
401 ucred data, and sd_pid_notify() uses the real UID for filling in ucred. */
403 if (arg_gid != GID_INVALID &&
404 setregid(arg_gid, GID_INVALID) < 0)
405 return log_error_errno(errno, "Failed to change GID: %m");
407 if (arg_uid != UID_INVALID &&
408 setreuid(arg_uid, UID_INVALID) < 0)
409 return log_error_errno(errno, "Failed to change UID: %m");
411 if (arg_pid > 0)
412 source_pid = arg_pid;
413 else {
414 /* Pretend the message originates from our parent, given that we are typically called from a
415 * shell script, i.e. we are not the main process of a service but only a child of it. */
416 source_pid = getppid();
417 if (source_pid <= 1 ||
418 source_pid == manager_pid()) /* safety check: don't claim we'd send anything from PID 1
419 * or the service manager itself */
420 source_pid = 0;
423 if (fdset_isempty(arg_fds))
424 r = sd_pid_notify(source_pid, /* unset_environment= */ false, n);
425 else {
426 _cleanup_free_ int *a = NULL;
427 int k;
429 k = fdset_to_array(arg_fds, &a);
430 if (k < 0)
431 return log_error_errno(k, "Failed to convert file descriptor set to array: %m");
433 r = sd_pid_notify_with_fds(source_pid, /* unset_environment= */ false, n, a, k);
436 if (r < 0)
437 return log_error_errno(r, "Failed to notify init system: %m");
438 if (r == 0)
439 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
440 "No status data could be sent: $NOTIFY_SOCKET was not set");
442 arg_fds = fdset_free(arg_fds); /* Close before we execute anything */
444 if (!arg_no_block) {
445 r = sd_pid_notify_barrier(source_pid, /* unset_environment= */ false, 5 * USEC_PER_SEC);
446 if (r < 0)
447 return log_error_errno(r, "Failed to invoke barrier: %m");
448 if (r == 0)
449 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
450 "No status data could be sent: $NOTIFY_SOCKET was not set");
453 if (arg_exec) {
454 _cleanup_free_ char *cmdline = NULL;
456 execvp(arg_exec[0], arg_exec);
458 cmdline = strv_join(arg_exec, " ");
459 if (!cmdline)
460 return log_oom();
462 return log_error_errno(errno, "Failed to execute command line: %s", cmdline);
465 /* The DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE() boilerplate will send the exit status via
466 * sd_notify(). Which is normally fine, but very confusing in systemd-notify, whose purpose is to
467 * send user-controllable notification messages, and not implicit ones. Let's turn if off, by
468 * unsetting the $NOTIFY_SOCKET environment variable. */
469 (void) unsetenv("NOTIFY_SOCKET");
470 return 0;
473 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);