]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/process-util.c
alloc-util: simplify GREEDY_REALLOC() logic by relying on malloc_usable_size()
[thirdparty/systemd.git] / src / basic / process-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
0b452006 2
4f5dd394 3#include <ctype.h>
0b452006 4#include <errno.h>
11c3a366
TA
5#include <limits.h>
6#include <linux/oom.h>
4f5dd394
LP
7#include <stdbool.h>
8#include <stdio.h>
11c3a366 9#include <stdlib.h>
9bfaffd5 10#include <sys/mman.h>
e2047ba9 11#include <sys/mount.h>
7b3e062c 12#include <sys/personality.h>
405f8907 13#include <sys/prctl.h>
4f5dd394
LP
14#include <sys/types.h>
15#include <sys/wait.h>
11c3a366 16#include <syslog.h>
4f5dd394 17#include <unistd.h>
349cc4a5 18#if HAVE_VALGRIND_VALGRIND_H
dcadc967
EV
19#include <valgrind/valgrind.h>
20#endif
0b452006 21
b5efdb8a 22#include "alloc-util.h"
6e5f1b57 23#include "architecture.h"
21c491e1 24#include "env-util.h"
39090201 25#include "errno-util.h"
aad3a64d 26#include "escape.h"
3ffd4af2 27#include "fd-util.h"
0b452006 28#include "fileio.h"
f4f15635 29#include "fs-util.h"
7b3e062c 30#include "ioprio.h"
e3b4efd2 31#include "locale-util.h"
0b452006 32#include "log.h"
11c3a366 33#include "macro.h"
0a970718 34#include "memory-util.h"
f5947a5e
YW
35#include "missing_sched.h"
36#include "missing_syscall.h"
0cb8e3d1 37#include "namespace-util.h"
aad3a64d 38#include "path-util.h"
93cc7779 39#include "process-util.h"
8869a0b4 40#include "raw-clone.h"
909106eb 41#include "rlimit-util.h"
93cc7779 42#include "signal-util.h"
1359fffa 43#include "stat-util.h"
298f466f 44#include "stdio-util.h"
7b3e062c 45#include "string-table.h"
07630cea 46#include "string-util.h"
4c253ed1 47#include "terminal-util.h"
b1d4f8e1 48#include "user-util.h"
bc28751e 49#include "utf8.h"
0b452006 50
0e85cbcf
ZJS
51/* The kernel limits userspace processes to TASK_COMM_LEN (16 bytes), but allows higher values for its own
52 * workers, e.g. "kworker/u9:3-kcryptd/253:0". Let's pick a fixed smallish limit that will work for the kernel.
53 */
54#define COMM_MAX_LEN 128
55
0a51b45c 56static int get_process_state(pid_t pid) {
5c7b9974 57 _cleanup_free_ char *line = NULL;
0b452006
RC
58 const char *p;
59 char state;
60 int r;
0b452006
RC
61
62 assert(pid >= 0);
63
5c7b9974
LP
64 /* Shortcut: if we are enquired about our own state, we are obviously running */
65 if (pid == 0 || pid == getpid_cached())
66 return (unsigned char) 'R';
67
0b452006 68 p = procfs_file_alloca(pid, "stat");
a644184a 69
0b452006 70 r = read_one_line_file(p, &line);
a644184a
LP
71 if (r == -ENOENT)
72 return -ESRCH;
0b452006
RC
73 if (r < 0)
74 return r;
75
76 p = strrchr(line, ')');
77 if (!p)
78 return -EIO;
79
80 p++;
81
82 if (sscanf(p, " %c", &state) != 1)
83 return -EIO;
84
85 return (unsigned char) state;
86}
87
ce268825
LP
88int get_process_comm(pid_t pid, char **ret) {
89 _cleanup_free_ char *escaped = NULL, *comm = NULL;
0b452006
RC
90 int r;
91
ce268825 92 assert(ret);
0b452006
RC
93 assert(pid >= 0);
94
cde93ba2
LP
95 if (pid == 0 || pid == getpid_cached()) {
96 comm = new0(char, TASK_COMM_LEN + 1); /* Must fit in 16 byte according to prctl(2) */
97 if (!comm)
98 return -ENOMEM;
99
100 if (prctl(PR_GET_NAME, comm) < 0)
101 return -errno;
102 } else {
103 const char *p;
104
105 p = procfs_file_alloca(pid, "comm");
106
107 /* Note that process names of kernel threads can be much longer than TASK_COMM_LEN */
108 r = read_one_line_file(p, &comm);
109 if (r == -ENOENT)
110 return -ESRCH;
111 if (r < 0)
112 return r;
113 }
114
0e85cbcf 115 escaped = new(char, COMM_MAX_LEN);
ce268825
LP
116 if (!escaped)
117 return -ENOMEM;
118
ce268825 119 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
0e85cbcf 120 cellescape(escaped, COMM_MAX_LEN, comm);
0b452006 121
ce268825
LP
122 *ret = TAKE_PTR(escaped);
123 return 0;
0b452006
RC
124}
125
61977664
ZJS
126static int get_process_cmdline_nulstr(
127 pid_t pid,
128 size_t max_size,
129 ProcessCmdlineFlags flags,
130 char **ret,
131 size_t *ret_size) {
132
0b452006 133 const char *p;
61977664 134 char *t;
bc28751e 135 size_t k;
7b7a060e 136 int r;
0b452006 137
61977664
ZJS
138 /* Retrieves a process' command line as a "sized nulstr", i.e. possibly without the last NUL, but
139 * with a specified size.
69281c49 140 *
61977664
ZJS
141 * If PROCESS_CMDLINE_COMM_FALLBACK is specified in flags and the process has no command line set
142 * (the case for kernel threads), or has a command line that resolves to the empty string, will
143 * return the "comm" name of the process instead. This will use at most _SC_ARG_MAX bytes of input
144 * data.
145 *
146 * Returns an error, 0 if output was read but is truncated, 1 otherwise.
147 */
69281c49 148
0b452006 149 p = procfs_file_alloca(pid, "cmdline");
61977664
ZJS
150 r = read_virtual_file(p, max_size, &t, &k); /* Let's assume that each input byte results in >= 1
151 * columns of output. We ignore zero-width codepoints. */
fdeea3f4
ZJS
152 if (r == -ENOENT)
153 return -ESRCH;
154 if (r < 0)
155 return r;
35bbbf85 156
61977664
ZJS
157 if (k == 0) {
158 t = mfree(t);
159
09c1dcee 160 if (!(flags & PROCESS_CMDLINE_COMM_FALLBACK))
0b452006
RC
161 return -ENOENT;
162
bc28751e 163 /* Kernel threads have no argv[] */
61977664 164 _cleanup_free_ char *comm = NULL;
69281c49 165
61977664 166 r = get_process_comm(pid, &comm);
bc28751e
ZJS
167 if (r < 0)
168 return r;
69281c49 169
61977664 170 t = strjoin("[", comm, "]");
bc28751e
ZJS
171 if (!t)
172 return -ENOMEM;
61977664
ZJS
173
174 k = strlen(t);
175 r = k <= max_size;
176 if (r == 0) /* truncation */
177 t[max_size] = '\0';
0b452006
RC
178 }
179
61977664
ZJS
180 *ret = t;
181 *ret_size = k;
182 return r;
183}
eb1ec489 184
61977664
ZJS
185int get_process_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags, char **line) {
186 _cleanup_free_ char *t = NULL;
187 size_t k;
188 char *ans;
e3b4efd2 189
61977664
ZJS
190 assert(line);
191 assert(pid >= 0);
192
19cc6d5e 193 /* Retrieve and format a commandline. See above for discussion of retrieval options.
61977664
ZJS
194 *
195 * There are two main formatting modes:
196 *
197 * - when PROCESS_CMDLINE_QUOTE is specified, output is quoted in C/Python style. If no shell special
198 * characters are present, this output can be copy-pasted into the terminal to execute. UTF-8
199 * output is assumed.
200 *
201 * - otherwise, a compact non-roundtrippable form is returned. Non-UTF8 bytes are replaced by �. The
202 * returned string is of the specified console width at most, abbreviated with an ellipsis.
203 *
204 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
205 * PROCESS_CMDLINE_COMM_FALLBACK is not specified). Returns 0 and sets *line otherwise. */
206
207 int full = get_process_cmdline_nulstr(pid, max_columns, flags, &t, &k);
208 if (full < 0)
209 return full;
210
99009ed0
ZJS
211 if (flags & (PROCESS_CMDLINE_QUOTE | PROCESS_CMDLINE_QUOTE_POSIX)) {
212 ShellEscapeFlags shflags = SHELL_ESCAPE_EMPTY |
213 FLAGS_SET(flags, PROCESS_CMDLINE_QUOTE_POSIX) * SHELL_ESCAPE_POSIX;
214
61977664
ZJS
215 assert(!(flags & PROCESS_CMDLINE_USE_LOCALE));
216
217 _cleanup_strv_free_ char **args = NULL;
218
219 args = strv_parse_nulstr(t, k);
220 if (!args)
221 return -ENOMEM;
222
223 for (size_t i = 0; args[i]; i++) {
224 char *e;
225
99009ed0 226 e = shell_maybe_quote(args[i], shflags);
61977664
ZJS
227 if (!e)
228 return -ENOMEM;
229
230 free_and_replace(args[i], e);
231 }
232
233 ans = strv_join(args, " ");
234 if (!ans)
235 return -ENOMEM;
236
237 } else {
238 /* Arguments are separated by NULs. Let's replace those with spaces. */
239 for (size_t i = 0; i < k - 1; i++)
240 if (t[i] == '\0')
241 t[i] = ' ';
242
243 delete_trailing_chars(t, WHITESPACE);
244
245 bool eight_bit = (flags & PROCESS_CMDLINE_USE_LOCALE) && !is_locale_utf8();
246
247 ans = escape_non_printable_full(t, max_columns,
248 eight_bit * XESCAPE_8_BIT | !full * XESCAPE_FORCE_ELLIPSIS);
249 if (!ans)
250 return -ENOMEM;
251
252 ans = str_realloc(ans);
253 }
eb1ec489 254
61977664 255 *line = ans;
0b452006
RC
256 return 0;
257}
258
ad4f7f67 259static int update_argv(const char name[], size_t l) {
c55104ce
ZJS
260 static int can_do = -1;
261
262 if (can_do == 0)
263 return 0;
264 can_do = false; /* We'll set it to true only if the whole process works */
265
01f989c6
JW
266 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
267 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
268 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
269 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
270 * mmap() is not. */
271 if (geteuid() != 0)
ad4f7f67
ZJS
272 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
273 "Skipping PR_SET_MM, as we don't have privileges.");
274
275 static size_t mm_size = 0;
276 static char *mm = NULL;
277 int r;
278
279 if (mm_size < l+1) {
9bfaffd5
LP
280 size_t nn_size;
281 char *nn;
282
9bfaffd5
LP
283 nn_size = PAGE_ALIGN(l+1);
284 nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
ad4f7f67
ZJS
285 if (nn == MAP_FAILED)
286 return log_debug_errno(errno, "mmap() failed: %m");
405f8907 287
9bfaffd5
LP
288 strncpy(nn, name, nn_size);
289
290 /* Now, let's tell the kernel about this new memory */
291 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
c55104ce
ZJS
292 if (ERRNO_IS_PRIVILEGE(errno))
293 return log_debug_errno(errno, "PR_SET_MM_ARG_START failed: %m");
294
14ee72b7
FS
295 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
296 * below the desired start address, in which case the kernel may have kicked this back due
297 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
298 * action). The proper solution would be to have a prctl() API that could set both start+end
299 * simultaneously, or at least let us query the existing address to anticipate this condition
300 * and respond accordingly. For now, we can only guess at the cause of this failure and try
301 * a workaround--which will briefly expand the arg space to something potentially huge before
302 * resizing it to what we want. */
303 log_debug_errno(errno, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
304
305 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) {
ad4f7f67 306 r = log_debug_errno(errno, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
14ee72b7 307 (void) munmap(nn, nn_size);
ad4f7f67 308 return r;
14ee72b7 309 }
9bfaffd5 310
ad4f7f67
ZJS
311 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0)
312 return log_debug_errno(errno, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
14ee72b7
FS
313 } else {
314 /* And update the end pointer to the new end, too. If this fails, we don't really know what
315 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
316 * and continue. */
317 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0)
318 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
319 }
9bfaffd5
LP
320
321 if (mm)
322 (void) munmap(mm, mm_size);
323
324 mm = nn;
325 mm_size = nn_size;
01f989c6 326 } else {
9bfaffd5
LP
327 strncpy(mm, name, mm_size);
328
01f989c6
JW
329 /* Update the end pointer, continuing regardless of any failure. */
330 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0)
331 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
332 }
333
c55104ce 334 can_do = true;
ad4f7f67
ZJS
335 return 0;
336}
337
338int rename_process(const char name[]) {
339 bool truncated = false;
340
341 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
342 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
343 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
344 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
345 * truncated.
346 *
347 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
348
349 if (isempty(name))
350 return -EINVAL; /* let's not confuse users unnecessarily with an empty name */
351
352 if (!is_main_thread())
353 return -EPERM; /* Let's not allow setting the process name from other threads than the main one, as we
354 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
355 * process name that isn't correct on any other threads */
356
357 size_t l = strlen(name);
358
359 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
360 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
361 if (prctl(PR_SET_NAME, name) < 0)
362 log_debug_errno(errno, "PR_SET_NAME failed: %m");
363 if (l >= TASK_COMM_LEN) /* Linux userspace process names can be 15 chars at max */
364 truncated = true;
365
366 /* Second step, change glibc's ID of the process name. */
367 if (program_invocation_name) {
368 size_t k;
369
370 k = strlen(program_invocation_name);
371 strncpy(program_invocation_name, name, k);
372 if (l > k)
373 truncated = true;
374 }
375
376 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
377 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
378 * the end. This is the best option for changing /proc/self/cmdline. */
379 (void) update_argv(name, l);
380
9bfaffd5
LP
381 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
382 * it still looks here */
405f8907 383 if (saved_argc > 0) {
9bfaffd5
LP
384 if (saved_argv[0]) {
385 size_t k;
386
387 k = strlen(saved_argv[0]);
388 strncpy(saved_argv[0], name, k);
389 if (l > k)
390 truncated = true;
391 }
405f8907 392
ad4f7f67 393 for (int i = 1; i < saved_argc; i++) {
405f8907
LP
394 if (!saved_argv[i])
395 break;
396
397 memzero(saved_argv[i], strlen(saved_argv[i]));
398 }
399 }
9bfaffd5
LP
400
401 return !truncated;
405f8907
LP
402}
403
0b452006 404int is_kernel_thread(pid_t pid) {
36b5119a
LP
405 _cleanup_free_ char *line = NULL;
406 unsigned long long flags;
407 size_t l, i;
0b452006 408 const char *p;
36b5119a
LP
409 char *q;
410 int r;
0b452006 411
4c701096 412 if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
0b452006 413 return 0;
36b5119a
LP
414 if (!pid_is_valid(pid))
415 return -EINVAL;
0b452006 416
36b5119a
LP
417 p = procfs_file_alloca(pid, "stat");
418 r = read_one_line_file(p, &line);
419 if (r == -ENOENT)
420 return -ESRCH;
421 if (r < 0)
422 return r;
0b452006 423
36b5119a
LP
424 /* Skip past the comm field */
425 q = strrchr(line, ')');
426 if (!q)
427 return -EINVAL;
428 q++;
429
430 /* Skip 6 fields to reach the flags field */
431 for (i = 0; i < 6; i++) {
432 l = strspn(q, WHITESPACE);
433 if (l < 1)
434 return -EINVAL;
435 q += l;
436
437 l = strcspn(q, WHITESPACE);
438 if (l < 1)
439 return -EINVAL;
440 q += l;
a644184a 441 }
0b452006 442
f21f31b2 443 /* Skip preceding whitespace */
36b5119a
LP
444 l = strspn(q, WHITESPACE);
445 if (l < 1)
446 return -EINVAL;
447 q += l;
35bbbf85 448
36b5119a
LP
449 /* Truncate the rest */
450 l = strcspn(q, WHITESPACE);
451 if (l < 1)
452 return -EINVAL;
453 q[l] = 0;
0b452006 454
36b5119a
LP
455 r = safe_atollu(q, &flags);
456 if (r < 0)
457 return r;
0b452006 458
36b5119a 459 return !!(flags & PF_KTHREAD);
0b452006
RC
460}
461
462int get_process_capeff(pid_t pid, char **capeff) {
463 const char *p;
a644184a 464 int r;
0b452006
RC
465
466 assert(capeff);
467 assert(pid >= 0);
468
469 p = procfs_file_alloca(pid, "status");
470
c4cd1d4d 471 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
a644184a
LP
472 if (r == -ENOENT)
473 return -ESRCH;
474
475 return r;
0b452006
RC
476}
477
478static int get_process_link_contents(const char *proc_file, char **name) {
479 int r;
480
481 assert(proc_file);
482 assert(name);
483
484 r = readlink_malloc(proc_file, name);
a644184a
LP
485 if (r == -ENOENT)
486 return -ESRCH;
0b452006 487 if (r < 0)
a644184a 488 return r;
0b452006
RC
489
490 return 0;
491}
492
493int get_process_exe(pid_t pid, char **name) {
494 const char *p;
495 char *d;
496 int r;
497
498 assert(pid >= 0);
499
500 p = procfs_file_alloca(pid, "exe");
501 r = get_process_link_contents(p, name);
502 if (r < 0)
503 return r;
504
505 d = endswith(*name, " (deleted)");
506 if (d)
507 *d = '\0';
508
509 return 0;
510}
511
512static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
513 _cleanup_fclose_ FILE *f = NULL;
0b452006 514 const char *p;
7e7a16a0 515 int r;
0b452006
RC
516
517 assert(field);
518 assert(uid);
519
07b38ba5 520 if (pid < 0)
6f8cbcdb
LP
521 return -EINVAL;
522
0b452006 523 p = procfs_file_alloca(pid, "status");
fdeea3f4
ZJS
524 r = fopen_unlocked(p, "re", &f);
525 if (r == -ENOENT)
526 return -ESRCH;
527 if (r < 0)
528 return r;
35bbbf85 529
7e7a16a0
LP
530 for (;;) {
531 _cleanup_free_ char *line = NULL;
0b452006
RC
532 char *l;
533
7e7a16a0
LP
534 r = read_line(f, LONG_LINE_MAX, &line);
535 if (r < 0)
536 return r;
537 if (r == 0)
538 break;
539
0b452006
RC
540 l = strstrip(line);
541
542 if (startswith(l, field)) {
543 l += strlen(field);
544 l += strspn(l, WHITESPACE);
545
546 l[strcspn(l, WHITESPACE)] = 0;
547
548 return parse_uid(l, uid);
549 }
550 }
551
552 return -EIO;
553}
554
555int get_process_uid(pid_t pid, uid_t *uid) {
6f8cbcdb
LP
556
557 if (pid == 0 || pid == getpid_cached()) {
558 *uid = getuid();
559 return 0;
560 }
561
0b452006
RC
562 return get_process_id(pid, "Uid:", uid);
563}
564
565int get_process_gid(pid_t pid, gid_t *gid) {
6f8cbcdb
LP
566
567 if (pid == 0 || pid == getpid_cached()) {
568 *gid = getgid();
569 return 0;
570 }
571
0b452006
RC
572 assert_cc(sizeof(uid_t) == sizeof(gid_t));
573 return get_process_id(pid, "Gid:", gid);
574}
575
576int get_process_cwd(pid_t pid, char **cwd) {
577 const char *p;
578
579 assert(pid >= 0);
580
aad3a64d
LP
581 if (pid == 0 || pid == getpid_cached())
582 return safe_getcwd(cwd);
583
0b452006
RC
584 p = procfs_file_alloca(pid, "cwd");
585
586 return get_process_link_contents(p, cwd);
587}
588
589int get_process_root(pid_t pid, char **root) {
590 const char *p;
591
592 assert(pid >= 0);
593
594 p = procfs_file_alloca(pid, "root");
595
596 return get_process_link_contents(p, root);
597}
598
2a7797e9
LP
599#define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
600
0b452006
RC
601int get_process_environ(pid_t pid, char **env) {
602 _cleanup_fclose_ FILE *f = NULL;
603 _cleanup_free_ char *outcome = NULL;
319a4f4b 604 size_t sz = 0;
2a7797e9
LP
605 const char *p;
606 int r;
0b452006
RC
607
608 assert(pid >= 0);
609 assert(env);
610
611 p = procfs_file_alloca(pid, "environ");
612
fdeea3f4
ZJS
613 r = fopen_unlocked(p, "re", &f);
614 if (r == -ENOENT)
615 return -ESRCH;
616 if (r < 0)
617 return r;
35bbbf85 618
2a7797e9
LP
619 for (;;) {
620 char c;
621
622 if (sz >= ENVIRONMENT_BLOCK_MAX)
623 return -ENOBUFS;
624
319a4f4b 625 if (!GREEDY_REALLOC(outcome, sz + 5))
0b452006
RC
626 return -ENOMEM;
627
2a7797e9
LP
628 r = safe_fgetc(f, &c);
629 if (r < 0)
630 return r;
631 if (r == 0)
632 break;
633
0b452006
RC
634 if (c == '\0')
635 outcome[sz++] = '\n';
636 else
637 sz += cescape_char(c, outcome + sz);
638 }
639
2a7797e9 640 outcome[sz] = '\0';
ae2a15bc 641 *env = TAKE_PTR(outcome);
0b452006
RC
642
643 return 0;
644}
645
6bc73acb 646int get_process_ppid(pid_t pid, pid_t *_ppid) {
0b452006
RC
647 int r;
648 _cleanup_free_ char *line = NULL;
649 long unsigned ppid;
650 const char *p;
651
652 assert(pid >= 0);
653 assert(_ppid);
654
6f8cbcdb 655 if (pid == 0 || pid == getpid_cached()) {
0b452006
RC
656 *_ppid = getppid();
657 return 0;
658 }
659
660 p = procfs_file_alloca(pid, "stat");
661 r = read_one_line_file(p, &line);
a644184a
LP
662 if (r == -ENOENT)
663 return -ESRCH;
0b452006
RC
664 if (r < 0)
665 return r;
666
667 /* Let's skip the pid and comm fields. The latter is enclosed
668 * in () but does not escape any () in its value, so let's
669 * skip over it manually */
670
671 p = strrchr(line, ')');
672 if (!p)
673 return -EIO;
674
675 p++;
676
677 if (sscanf(p, " "
678 "%*c " /* state */
679 "%lu ", /* ppid */
680 &ppid) != 1)
681 return -EIO;
682
683 if ((long unsigned) (pid_t) ppid != ppid)
684 return -ERANGE;
685
686 *_ppid = (pid_t) ppid;
687
688 return 0;
689}
690
5e37d193
FB
691int get_process_umask(pid_t pid, mode_t *umask) {
692 _cleanup_free_ char *m = NULL;
693 const char *p;
694 int r;
695
696 assert(umask);
697 assert(pid >= 0);
698
699 p = procfs_file_alloca(pid, "status");
700
701 r = get_proc_field(p, "Umask", WHITESPACE, &m);
702 if (r == -ENOENT)
703 return -ESRCH;
704
705 return parse_mode(m, umask);
706}
707
0b452006
RC
708int wait_for_terminate(pid_t pid, siginfo_t *status) {
709 siginfo_t dummy;
710
711 assert(pid >= 1);
712
713 if (!status)
714 status = &dummy;
715
716 for (;;) {
717 zero(*status);
718
719 if (waitid(P_PID, pid, status, WEXITED) < 0) {
720
721 if (errno == EINTR)
722 continue;
723
3f0083a2 724 return negative_errno();
0b452006
RC
725 }
726
727 return 0;
728 }
729}
730
731/*
732 * Return values:
733 * < 0 : wait_for_terminate() failed to get the state of the
734 * process, the process was terminated by a signal, or
735 * failed for an unknown reason.
736 * >=0 : The process terminated normally, and its exit code is
737 * returned.
738 *
739 * That is, success is indicated by a return value of zero, and an
740 * error is indicated by a non-zero value.
741 *
742 * A warning is emitted if the process terminates abnormally,
743 * and also if it returns non-zero unless check_exit_code is true.
744 */
7d4904fe
LP
745int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) {
746 _cleanup_free_ char *buffer = NULL;
0b452006 747 siginfo_t status;
7d4904fe 748 int r, prio;
0b452006 749
0b452006
RC
750 assert(pid > 1);
751
7d4904fe
LP
752 if (!name) {
753 r = get_process_comm(pid, &buffer);
754 if (r < 0)
755 log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid);
756 else
757 name = buffer;
758 }
759
760 prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
761
0b452006
RC
762 r = wait_for_terminate(pid, &status);
763 if (r < 0)
7d4904fe 764 return log_full_errno(prio, r, "Failed to wait for %s: %m", strna(name));
0b452006
RC
765
766 if (status.si_code == CLD_EXITED) {
7d4904fe
LP
767 if (status.si_status != EXIT_SUCCESS)
768 log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
769 "%s failed with exit status %i.", strna(name), status.si_status);
0b452006
RC
770 else
771 log_debug("%s succeeded.", name);
772
773 return status.si_status;
7d4904fe 774
3742095b 775 } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
0b452006 776
7d4904fe 777 log_full(prio, "%s terminated by signal %s.", strna(name), signal_to_string(status.si_status));
0b452006
RC
778 return -EPROTO;
779 }
780
7d4904fe 781 log_full(prio, "%s failed due to unknown reason.", strna(name));
0b452006
RC
782 return -EPROTO;
783}
784
d5641e0d
KW
785/*
786 * Return values:
e225e5c3
LP
787 *
788 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
789 * was terminated by a signal, or failed for an unknown reason.
790 *
d5641e0d
KW
791 * >=0 : The process terminated normally with no failures.
792 *
e225e5c3
LP
793 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
794 * states are indicated by error is indicated by a non-zero value.
795 *
796 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
797 * to remain entirely race-free.
d5641e0d
KW
798 */
799int wait_for_terminate_with_timeout(pid_t pid, usec_t timeout) {
800 sigset_t mask;
801 int r;
802 usec_t until;
803
804 assert_se(sigemptyset(&mask) == 0);
805 assert_se(sigaddset(&mask, SIGCHLD) == 0);
806
807 /* Drop into a sigtimewait-based timeout. Waiting for the
808 * pid to exit. */
496db330 809 until = usec_add(now(CLOCK_MONOTONIC), timeout);
d5641e0d
KW
810 for (;;) {
811 usec_t n;
812 siginfo_t status = {};
813 struct timespec ts;
814
815 n = now(CLOCK_MONOTONIC);
816 if (n >= until)
817 break;
818
819 r = sigtimedwait(&mask, NULL, timespec_store(&ts, until - n)) < 0 ? -errno : 0;
820 /* Assuming we woke due to the child exiting. */
821 if (waitid(P_PID, pid, &status, WEXITED|WNOHANG) == 0) {
822 if (status.si_pid == pid) {
823 /* This is the correct child.*/
824 if (status.si_code == CLD_EXITED)
825 return (status.si_status == 0) ? 0 : -EPROTO;
826 else
827 return -EPROTO;
828 }
829 }
830 /* Not the child, check for errors and proceed appropriately */
831 if (r < 0) {
832 switch (r) {
833 case -EAGAIN:
834 /* Timed out, child is likely hung. */
835 return -ETIMEDOUT;
836 case -EINTR:
837 /* Received a different signal and should retry */
838 continue;
839 default:
840 /* Return any unexpected errors */
841 return r;
842 }
843 }
844 }
845
846 return -EPROTO;
847}
848
89c9030d
LP
849void sigkill_wait(pid_t pid) {
850 assert(pid > 1);
851
53640e6f 852 if (kill(pid, SIGKILL) >= 0)
89c9030d
LP
853 (void) wait_for_terminate(pid, NULL);
854}
855
856void sigkill_waitp(pid_t *pid) {
dfd14786
LP
857 PROTECT_ERRNO;
858
4d0d3d41
LP
859 if (!pid)
860 return;
861 if (*pid <= 1)
862 return;
863
89c9030d 864 sigkill_wait(*pid);
4d0d3d41
LP
865}
866
392cf1d0
SL
867void sigterm_wait(pid_t pid) {
868 assert(pid > 1);
869
53640e6f 870 if (kill_and_sigcont(pid, SIGTERM) >= 0)
392cf1d0
SL
871 (void) wait_for_terminate(pid, NULL);
872}
873
0b452006
RC
874int kill_and_sigcont(pid_t pid, int sig) {
875 int r;
876
877 r = kill(pid, sig) < 0 ? -errno : 0;
878
26f417d3
LP
879 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
880 * affected by a process being suspended anyway. */
a3d8d68c 881 if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
26f417d3 882 (void) kill(pid, SIGCONT);
0b452006
RC
883
884 return r;
885}
886
e70f4453 887int getenv_for_pid(pid_t pid, const char *field, char **ret) {
0b452006
RC
888 _cleanup_fclose_ FILE *f = NULL;
889 char *value = NULL;
0b452006 890 const char *path;
0d90bd92
LP
891 size_t l, sum = 0;
892 int r;
0b452006
RC
893
894 assert(pid >= 0);
895 assert(field);
e70f4453
LP
896 assert(ret);
897
898 if (pid == 0 || pid == getpid_cached()) {
899 const char *e;
900
901 e = getenv(field);
902 if (!e) {
903 *ret = NULL;
904 return 0;
905 }
906
907 value = strdup(e);
908 if (!value)
909 return -ENOMEM;
910
911 *ret = value;
912 return 1;
913 }
0b452006 914
0d90bd92
LP
915 if (!pid_is_valid(pid))
916 return -EINVAL;
917
0b452006
RC
918 path = procfs_file_alloca(pid, "environ");
919
fdeea3f4
ZJS
920 r = fopen_unlocked(path, "re", &f);
921 if (r == -ENOENT)
922 return -ESRCH;
923 if (r < 0)
924 return r;
35bbbf85 925
0b452006 926 l = strlen(field);
0d90bd92
LP
927 for (;;) {
928 _cleanup_free_ char *line = NULL;
0b452006 929
0d90bd92
LP
930 if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
931 return -ENOBUFS;
0b452006 932
0d90bd92
LP
933 r = read_nul_string(f, LONG_LINE_MAX, &line);
934 if (r < 0)
935 return r;
936 if (r == 0) /* EOF */
937 break;
0b452006 938
0d90bd92 939 sum += r;
0b452006 940
041b5ae1 941 if (strneq(line, field, l) && line[l] == '=') {
0b452006
RC
942 value = strdup(line + l + 1);
943 if (!value)
944 return -ENOMEM;
945
e70f4453
LP
946 *ret = value;
947 return 1;
0b452006 948 }
0d90bd92 949 }
0b452006 950
e70f4453
LP
951 *ret = NULL;
952 return 0;
0b452006
RC
953}
954
4d051546
FB
955int pid_is_my_child(pid_t pid) {
956 pid_t ppid;
957 int r;
958
959 if (pid <= 1)
960 return false;
961
962 r = get_process_ppid(pid, &ppid);
963 if (r < 0)
964 return r;
965
966 return ppid == getpid_cached();
967}
968
0b452006
RC
969bool pid_is_unwaited(pid_t pid) {
970 /* Checks whether a PID is still valid at all, including a zombie */
971
07b38ba5 972 if (pid < 0)
0b452006
RC
973 return false;
974
5fd9b2c5
LP
975 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
976 return true;
977
6f8cbcdb
LP
978 if (pid == getpid_cached())
979 return true;
980
0b452006
RC
981 if (kill(pid, 0) >= 0)
982 return true;
983
984 return errno != ESRCH;
985}
986
987bool pid_is_alive(pid_t pid) {
988 int r;
989
990 /* Checks whether a PID is still valid and not a zombie */
991
07b38ba5 992 if (pid < 0)
0b452006
RC
993 return false;
994
5fd9b2c5
LP
995 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
996 return true;
997
6f8cbcdb
LP
998 if (pid == getpid_cached())
999 return true;
1000
0b452006 1001 r = get_process_state(pid);
4c701096 1002 if (IN_SET(r, -ESRCH, 'Z'))
0b452006
RC
1003 return false;
1004
1005 return true;
1006}
d4510856 1007
1359fffa
MS
1008int pid_from_same_root_fs(pid_t pid) {
1009 const char *root;
1010
07b38ba5 1011 if (pid < 0)
6f8cbcdb
LP
1012 return false;
1013
1014 if (pid == 0 || pid == getpid_cached())
1015 return true;
1359fffa
MS
1016
1017 root = procfs_file_alloca(pid, "root");
1018
e3f791a2 1019 return files_same(root, "/proc/1/root", 0);
1359fffa
MS
1020}
1021
d4510856
LP
1022bool is_main_thread(void) {
1023 static thread_local int cached = 0;
1024
1025 if (_unlikely_(cached == 0))
df0ff127 1026 cached = getpid_cached() == gettid() ? 1 : -1;
d4510856
LP
1027
1028 return cached > 0;
1029}
7b3e062c 1030
848e863a 1031_noreturn_ void freeze(void) {
7b3e062c 1032
3da48d7a
EV
1033 log_close();
1034
7b3e062c 1035 /* Make sure nobody waits for us on a socket anymore */
7acf581a 1036 (void) close_all_fds(NULL, 0);
7b3e062c
LP
1037
1038 sync();
1039
8647283e
MS
1040 /* Let's not freeze right away, but keep reaping zombies. */
1041 for (;;) {
1042 int r;
1043 siginfo_t si = {};
1044
1045 r = waitid(P_ALL, 0, &si, WEXITED);
1046 if (r < 0 && errno != EINTR)
1047 break;
1048 }
1049
1050 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
7b3e062c
LP
1051 for (;;)
1052 pause();
1053}
1054
1055bool oom_score_adjust_is_valid(int oa) {
1056 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
1057}
1058
1059unsigned long personality_from_string(const char *p) {
6e5f1b57 1060 int architecture;
7b3e062c 1061
0c0fea07
LP
1062 if (!p)
1063 return PERSONALITY_INVALID;
1064
6e5f1b57
LP
1065 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1066 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1067 * the same register size. */
1068
1069 architecture = architecture_from_string(p);
1070 if (architecture < 0)
1071 return PERSONALITY_INVALID;
7b3e062c 1072
0c0fea07 1073 if (architecture == native_architecture())
7b3e062c 1074 return PER_LINUX;
0c0fea07
LP
1075#ifdef SECONDARY_ARCHITECTURE
1076 if (architecture == SECONDARY_ARCHITECTURE)
f2d1736c 1077 return PER_LINUX32;
7b3e062c
LP
1078#endif
1079
1080 return PERSONALITY_INVALID;
1081}
1082
1083const char* personality_to_string(unsigned long p) {
6e5f1b57 1084 int architecture = _ARCHITECTURE_INVALID;
7b3e062c 1085
7b3e062c 1086 if (p == PER_LINUX)
0c0fea07
LP
1087 architecture = native_architecture();
1088#ifdef SECONDARY_ARCHITECTURE
6e5f1b57 1089 else if (p == PER_LINUX32)
0c0fea07 1090 architecture = SECONDARY_ARCHITECTURE;
7b3e062c
LP
1091#endif
1092
6e5f1b57
LP
1093 if (architecture < 0)
1094 return NULL;
1095
1096 return architecture_to_string(architecture);
7b3e062c
LP
1097}
1098
21022b9d
LP
1099int safe_personality(unsigned long p) {
1100 int ret;
1101
1102 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1103 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1104 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1105 * the return value indicating the same issue, so that we are definitely on the safe side.
1106 *
1107 * See https://github.com/systemd/systemd/issues/6737 */
1108
1109 errno = 0;
1110 ret = personality(p);
1111 if (ret < 0) {
1112 if (errno != 0)
1113 return -errno;
1114
1115 errno = -ret;
1116 }
1117
1118 return ret;
1119}
1120
e8132d63
LP
1121int opinionated_personality(unsigned long *ret) {
1122 int current;
1123
1124 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1125 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1126 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1127
21022b9d 1128 current = safe_personality(PERSONALITY_INVALID);
e8132d63 1129 if (current < 0)
21022b9d 1130 return current;
e8132d63
LP
1131
1132 if (((unsigned long) current & 0xffff) == PER_LINUX32)
1133 *ret = PER_LINUX32;
1134 else
1135 *ret = PER_LINUX;
1136
1137 return 0;
1138}
1139
dcadc967 1140void valgrind_summary_hack(void) {
349cc4a5 1141#if HAVE_VALGRIND_VALGRIND_H
df0ff127 1142 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
dcadc967 1143 pid_t pid;
8869a0b4 1144 pid = raw_clone(SIGCHLD);
dcadc967
EV
1145 if (pid < 0)
1146 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
1147 else if (pid == 0)
1148 exit(EXIT_SUCCESS);
1149 else {
1150 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
1151 (void) wait_for_terminate(pid, NULL);
1152 }
1153 }
1154#endif
1155}
1156
93bab288 1157int pid_compare_func(const pid_t *a, const pid_t *b) {
291d565a 1158 /* Suitable for usage in qsort() */
93bab288 1159 return CMP(*a, *b);
291d565a
LP
1160}
1161
7f452159
LP
1162int ioprio_parse_priority(const char *s, int *ret) {
1163 int i, r;
1164
1165 assert(s);
1166 assert(ret);
1167
1168 r = safe_atoi(s, &i);
1169 if (r < 0)
1170 return r;
1171
1172 if (!ioprio_priority_is_valid(i))
1173 return -EINVAL;
1174
1175 *ret = i;
1176 return 0;
1177}
1178
5c30a6d2
LP
1179/* The cached PID, possible values:
1180 *
1181 * == UNSET [0] → cache not initialized yet
1182 * == BUSY [-1] → some thread is initializing it at the moment
1183 * any other → the cached PID
1184 */
1185
1186#define CACHED_PID_UNSET ((pid_t) 0)
1187#define CACHED_PID_BUSY ((pid_t) -1)
1188
1189static pid_t cached_pid = CACHED_PID_UNSET;
1190
799a960d 1191void reset_cached_pid(void) {
5c30a6d2
LP
1192 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1193 cached_pid = CACHED_PID_UNSET;
1194}
1195
1196/* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1197 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1198 * libpthread, as it is part of glibc anyway. */
2bb8d8d9 1199extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void *dso_handle);
d34dae18 1200extern void* __dso_handle _weak_;
5c30a6d2
LP
1201
1202pid_t getpid_cached(void) {
5d71bac3 1203 static bool installed = false;
5c30a6d2
LP
1204 pid_t current_value;
1205
1206 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1207 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1208 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1209 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1210 *
1211 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
a4041e4f 1212 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
5c30a6d2
LP
1213 */
1214
1215 current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1216
1217 switch (current_value) {
1218
1219 case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1220 pid_t new_pid;
1221
996def17 1222 new_pid = raw_getpid();
5c30a6d2 1223
5d71bac3
LP
1224 if (!installed) {
1225 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1226 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1227 * we'll check for errors only in the most generic fashion possible. */
1228
1229 if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) {
1230 /* OOM? Let's try again later */
1231 cached_pid = CACHED_PID_UNSET;
1232 return new_pid;
1233 }
1234
1235 installed = true;
5c30a6d2
LP
1236 }
1237
1238 cached_pid = new_pid;
1239 return new_pid;
1240 }
1241
1242 case CACHED_PID_BUSY: /* Somebody else is currently initializing */
996def17 1243 return raw_getpid();
5c30a6d2
LP
1244
1245 default: /* Properly initialized */
1246 return current_value;
1247 }
1248}
1249
fba868fa
LP
1250int must_be_root(void) {
1251
1252 if (geteuid() == 0)
1253 return 0;
1254
baaa35ad 1255 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be root.");
fba868fa
LP
1256}
1257
4b3abcd0
MG
1258static void restore_sigsetp(sigset_t **ssp) {
1259 if (*ssp)
1260 (void) sigprocmask(SIG_SETMASK, *ssp, NULL);
1261}
1262
4c253ed1
LP
1263int safe_fork_full(
1264 const char *name,
1265 const int except_fds[],
1266 size_t n_except_fds,
1267 ForkFlags flags,
1268 pid_t *ret_pid) {
1269
1270 pid_t original_pid, pid;
1f5d1e02 1271 sigset_t saved_ss, ss;
4b3abcd0 1272 _cleanup_(restore_sigsetp) sigset_t *saved_ssp = NULL;
d7e38115 1273 bool block_signals = false, block_all = false;
b6e1fff1 1274 int prio, r;
4c253ed1
LP
1275
1276 /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1277 * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1278
b6e1fff1
LP
1279 prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG;
1280
4c253ed1
LP
1281 original_pid = getpid_cached();
1282
48f813c4
LP
1283 if (flags & FORK_FLUSH_STDIO) {
1284 fflush(stdout);
1285 fflush(stderr); /* This one shouldn't be necessary, stderr should be unbuffered anyway, but let's better be safe than sorry */
1286 }
1287
1f5d1e02 1288 if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG)) {
1f5d1e02
LP
1289 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1290 * be sure that SIGTERMs are not lost we might send to the child. */
4c253ed1 1291
cd2a429e 1292 assert_se(sigfillset(&ss) >= 0);
d7e38115 1293 block_signals = block_all = true;
1f5d1e02
LP
1294
1295 } else if (flags & FORK_WAIT) {
1f5d1e02
LP
1296 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1297
cd2a429e
ZJS
1298 assert_se(sigemptyset(&ss) >= 0);
1299 assert_se(sigaddset(&ss, SIGCHLD) >= 0);
1f5d1e02 1300 block_signals = true;
4c253ed1
LP
1301 }
1302
4b3abcd0 1303 if (block_signals) {
1f5d1e02
LP
1304 if (sigprocmask(SIG_SETMASK, &ss, &saved_ss) < 0)
1305 return log_full_errno(prio, errno, "Failed to set signal mask: %m");
4b3abcd0
MG
1306 saved_ssp = &saved_ss;
1307 }
1f5d1e02 1308
5f968736
LP
1309 if ((flags & (FORK_NEW_MOUNTNS|FORK_NEW_USERNS)) != 0)
1310 pid = raw_clone(SIGCHLD|
1311 (FLAGS_SET(flags, FORK_NEW_MOUNTNS) ? CLONE_NEWNS : 0) |
1312 (FLAGS_SET(flags, FORK_NEW_USERNS) ? CLONE_NEWUSER : 0));
be39f6ee
LP
1313 else
1314 pid = fork();
4b3abcd0
MG
1315 if (pid < 0)
1316 return log_full_errno(prio, errno, "Failed to fork: %m");
4c253ed1
LP
1317 if (pid > 0) {
1318 /* We are in the parent process */
1319
1f5d1e02
LP
1320 log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid);
1321
1322 if (flags & FORK_WAIT) {
d7e38115
MG
1323 if (block_all) {
1324 /* undo everything except SIGCHLD */
1325 ss = saved_ss;
1326 assert_se(sigaddset(&ss, SIGCHLD) >= 0);
1327 (void) sigprocmask(SIG_SETMASK, &ss, NULL);
1328 }
1329
1f5d1e02
LP
1330 r = wait_for_terminate_and_check(name, pid, (flags & FORK_LOG ? WAIT_LOG : 0));
1331 if (r < 0)
1332 return r;
1333 if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */
1334 return -EPROTO;
1335 }
1336
4c253ed1
LP
1337 if (ret_pid)
1338 *ret_pid = pid;
1339
1340 return 1;
1341 }
1342
1343 /* We are in the child process */
1344
4b3abcd0
MG
1345 /* Restore signal mask manually */
1346 saved_ssp = NULL;
1347
4c253ed1
LP
1348 if (flags & FORK_REOPEN_LOG) {
1349 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1350 log_close();
1351 log_set_open_when_needed(true);
1352 }
1353
1354 if (name) {
1355 r = rename_process(name);
1356 if (r < 0)
b6e1fff1
LP
1357 log_full_errno(flags & FORK_LOG ? LOG_WARNING : LOG_DEBUG,
1358 r, "Failed to rename process, ignoring: %m");
4c253ed1
LP
1359 }
1360
97033ba4
LP
1361 if (flags & (FORK_DEATHSIG|FORK_DEATHSIG_SIGINT))
1362 if (prctl(PR_SET_PDEATHSIG, (flags & FORK_DEATHSIG_SIGINT) ? SIGINT : SIGTERM) < 0) {
b6e1fff1 1363 log_full_errno(prio, errno, "Failed to set death signal: %m");
4c253ed1
LP
1364 _exit(EXIT_FAILURE);
1365 }
1366
1367 if (flags & FORK_RESET_SIGNALS) {
1368 r = reset_all_signal_handlers();
1369 if (r < 0) {
b6e1fff1 1370 log_full_errno(prio, r, "Failed to reset signal handlers: %m");
4c253ed1
LP
1371 _exit(EXIT_FAILURE);
1372 }
1373
1374 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1375 r = reset_signal_mask();
1376 if (r < 0) {
b6e1fff1 1377 log_full_errno(prio, r, "Failed to reset signal mask: %m");
4c253ed1
LP
1378 _exit(EXIT_FAILURE);
1379 }
1380 } else if (block_signals) { /* undo what we did above */
1381 if (sigprocmask(SIG_SETMASK, &saved_ss, NULL) < 0) {
b6e1fff1 1382 log_full_errno(prio, errno, "Failed to restore signal mask: %m");
4c253ed1
LP
1383 _exit(EXIT_FAILURE);
1384 }
1385 }
1386
1387 if (flags & FORK_DEATHSIG) {
7ddc2dc5 1388 pid_t ppid;
4c253ed1
LP
1389 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1390 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1391
7ddc2dc5
SL
1392 ppid = getppid();
1393 if (ppid == 0)
d7b34e38 1394 /* Parent is in a different PID namespace. */;
7ddc2dc5 1395 else if (ppid != original_pid) {
4c253ed1
LP
1396 log_debug("Parent died early, raising SIGTERM.");
1397 (void) raise(SIGTERM);
1398 _exit(EXIT_FAILURE);
1399 }
1400 }
1401
d94a24ca 1402 if (FLAGS_SET(flags, FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE)) {
e2047ba9
LP
1403
1404 /* Optionally, make sure we never propagate mounts to the host. */
1405
1406 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
1407 log_full_errno(prio, errno, "Failed to remount root directory as MS_SLAVE: %m");
1408 _exit(EXIT_FAILURE);
1409 }
1410 }
1411
4c253ed1
LP
1412 if (flags & FORK_CLOSE_ALL_FDS) {
1413 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1414 log_close();
1415
1416 r = close_all_fds(except_fds, n_except_fds);
1417 if (r < 0) {
b6e1fff1 1418 log_full_errno(prio, r, "Failed to close all file descriptors: %m");
4c253ed1
LP
1419 _exit(EXIT_FAILURE);
1420 }
1421 }
1422
1423 /* When we were asked to reopen the logs, do so again now */
1424 if (flags & FORK_REOPEN_LOG) {
1425 log_open();
1426 log_set_open_when_needed(false);
1427 }
1428
1429 if (flags & FORK_NULL_STDIO) {
1430 r = make_null_stdio();
1431 if (r < 0) {
b6e1fff1 1432 log_full_errno(prio, r, "Failed to connect stdin/stdout to /dev/null: %m");
4c253ed1
LP
1433 _exit(EXIT_FAILURE);
1434 }
8987afc4
LP
1435
1436 } else if (flags & FORK_STDOUT_TO_STDERR) {
8987afc4 1437 if (dup2(STDERR_FILENO, STDOUT_FILENO) < 0) {
bddeb54c 1438 log_full_errno(prio, errno, "Failed to connect stdout to stderr: %m");
8987afc4
LP
1439 _exit(EXIT_FAILURE);
1440 }
4c253ed1
LP
1441 }
1442
909106eb
LP
1443 if (flags & FORK_RLIMIT_NOFILE_SAFE) {
1444 r = rlimit_nofile_safe();
1445 if (r < 0) {
1446 log_full_errno(prio, r, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1447 _exit(EXIT_FAILURE);
1448 }
1449 }
1450
4c253ed1
LP
1451 if (ret_pid)
1452 *ret_pid = getpid_cached();
1453
1454 return 0;
1455}
1456
27096982
LP
1457int namespace_fork(
1458 const char *outer_name,
1459 const char *inner_name,
1460 const int except_fds[],
1461 size_t n_except_fds,
1462 ForkFlags flags,
1463 int pidns_fd,
1464 int mntns_fd,
1465 int netns_fd,
1466 int userns_fd,
1467 int root_fd,
1468 pid_t *ret_pid) {
1469
1470 int r;
1471
1472 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1473 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1474 * /proc/self/fd works correctly. */
1475
1476 r = safe_fork_full(outer_name, except_fds, n_except_fds, (flags|FORK_DEATHSIG) & ~(FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE), ret_pid);
1477 if (r < 0)
1478 return r;
1479 if (r == 0) {
1480 pid_t pid;
1481
1482 /* Child */
1483
1484 r = namespace_enter(pidns_fd, mntns_fd, netns_fd, userns_fd, root_fd);
1485 if (r < 0) {
1486 log_full_errno(FLAGS_SET(flags, FORK_LOG) ? LOG_ERR : LOG_DEBUG, r, "Failed to join namespace: %m");
1487 _exit(EXIT_FAILURE);
1488 }
1489
1490 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1491 r = safe_fork_full(inner_name, except_fds, n_except_fds, flags & ~(FORK_WAIT|FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_NULL_STDIO), &pid);
1492 if (r < 0)
1493 _exit(EXIT_FAILURE);
1494 if (r == 0) {
1495 /* Child */
1496 if (ret_pid)
1497 *ret_pid = pid;
1498 return 0;
1499 }
1500
1501 r = wait_for_terminate_and_check(inner_name, pid, FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1502 if (r < 0)
1503 _exit(EXIT_FAILURE);
1504
1505 _exit(r);
1506 }
1507
1508 return 1;
1509}
1510
da6053d0 1511int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) {
78752f2e 1512 bool stdout_is_tty, stderr_is_tty;
da6053d0 1513 size_t n, i;
78752f2e
LP
1514 va_list ap;
1515 char **l;
1516 int r;
1517
1518 assert(path);
1519
1520 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1521
7e0ed2e9
SB
1522 r = safe_fork_full(name,
1523 except,
1524 n_except,
1525 FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_REOPEN_LOG,
1526 ret_pid);
78752f2e
LP
1527 if (r < 0)
1528 return r;
1529 if (r > 0)
1530 return 0;
1531
1532 /* In the child: */
1533
1534 stdout_is_tty = isatty(STDOUT_FILENO);
1535 stderr_is_tty = isatty(STDERR_FILENO);
1536
1537 if (!stdout_is_tty || !stderr_is_tty) {
1538 int fd;
1539
1540 /* Detach from stdout/stderr. and reopen
1541 * /dev/tty for them. This is important to
1542 * ensure that when systemctl is started via
1543 * popen() or a similar call that expects to
1544 * read EOF we actually do generate EOF and
1545 * not delay this indefinitely by because we
1546 * keep an unused copy of stdin around. */
1547 fd = open("/dev/tty", O_WRONLY);
1548 if (fd < 0) {
1549 log_error_errno(errno, "Failed to open /dev/tty: %m");
1550 _exit(EXIT_FAILURE);
1551 }
1552
1553 if (!stdout_is_tty && dup2(fd, STDOUT_FILENO) < 0) {
1554 log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1555 _exit(EXIT_FAILURE);
1556 }
1557
1558 if (!stderr_is_tty && dup2(fd, STDERR_FILENO) < 0) {
1559 log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1560 _exit(EXIT_FAILURE);
1561 }
1562
e7685a77 1563 safe_close_above_stdio(fd);
78752f2e
LP
1564 }
1565
595225af
LP
1566 (void) rlimit_nofile_safe();
1567
78752f2e
LP
1568 /* Count arguments */
1569 va_start(ap, path);
1570 for (n = 0; va_arg(ap, char*); n++)
1571 ;
1572 va_end(ap);
1573
1574 /* Allocate strv */
cf409d15 1575 l = newa(char*, n + 1);
78752f2e
LP
1576
1577 /* Fill in arguments */
1578 va_start(ap, path);
1579 for (i = 0; i <= n; i++)
1580 l[i] = va_arg(ap, char*);
1581 va_end(ap);
1582
1583 execv(path, l);
1584 _exit(EXIT_FAILURE);
1585}
1586
9f8168eb
LP
1587int set_oom_score_adjust(int value) {
1588 char t[DECIMAL_STR_MAX(int)];
1589
1590 sprintf(t, "%i", value);
1591
1592 return write_string_file("/proc/self/oom_score_adj", t,
1593 WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
1594}
1595
298f466f
LP
1596int pidfd_get_pid(int fd, pid_t *ret) {
1597 char path[STRLEN("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
1598 _cleanup_free_ char *fdinfo = NULL;
1599 char *p;
1600 int r;
1601
1602 if (fd < 0)
1603 return -EBADF;
1604
1605 xsprintf(path, "/proc/self/fdinfo/%i", fd);
1606
627055ce 1607 r = read_full_virtual_file(path, &fdinfo, NULL);
298f466f
LP
1608 if (r == -ENOENT) /* if fdinfo doesn't exist we assume the process does not exist */
1609 return -ESRCH;
1610 if (r < 0)
1611 return r;
1612
1613 p = startswith(fdinfo, "Pid:");
1614 if (!p) {
1615 p = strstr(fdinfo, "\nPid:");
1616 if (!p)
1617 return -ENOTTY; /* not a pidfd? */
1618
1619 p += 5;
1620 }
1621
1622 p += strspn(p, WHITESPACE);
1623 p[strcspn(p, WHITESPACE)] = 0;
1624
1625 return parse_pid(p, ret);
1626}
1627
39090201
DJL
1628static int rlimit_to_nice(rlim_t limit) {
1629 if (limit <= 1)
1630 return PRIO_MAX-1; /* i.e. 19 */
1631
1632 if (limit >= -PRIO_MIN + PRIO_MAX)
1633 return PRIO_MIN; /* i.e. -20 */
1634
1635 return PRIO_MAX - (int) limit;
1636}
1637
1638int setpriority_closest(int priority) {
1639 int current, limit, saved_errno;
1640 struct rlimit highest;
1641
1642 /* Try to set requested nice level */
1643 if (setpriority(PRIO_PROCESS, 0, priority) >= 0)
1644 return 1;
1645
1646 /* Permission failed */
1647 saved_errno = -errno;
1648 if (!ERRNO_IS_PRIVILEGE(saved_errno))
1649 return saved_errno;
1650
1651 errno = 0;
1652 current = getpriority(PRIO_PROCESS, 0);
1653 if (errno != 0)
1654 return -errno;
1655
1656 if (priority == current)
1657 return 1;
1658
1659 /* Hmm, we'd expect that raising the nice level from our status quo would always work. If it doesn't,
1660 * then the whole setpriority() system call is blocked to us, hence let's propagate the error
1661 * right-away */
1662 if (priority > current)
1663 return saved_errno;
1664
1665 if (getrlimit(RLIMIT_NICE, &highest) < 0)
1666 return -errno;
1667
1668 limit = rlimit_to_nice(highest.rlim_cur);
1669
1670 /* We are already less nice than limit allows us */
1671 if (current < limit) {
1672 log_debug("Cannot raise nice level, permissions and the resource limit do not allow it.");
1673 return 0;
1674 }
1675
1676 /* Push to the allowed limit */
1677 if (setpriority(PRIO_PROCESS, 0, limit) < 0)
1678 return -errno;
1679
1680 log_debug("Cannot set requested nice level (%i), used next best (%i).", priority, limit);
1681 return 0;
1682}
1683
2306d177
LP
1684bool invoked_as(char *argv[], const char *token) {
1685 if (!argv || isempty(argv[0]))
1686 return false;
1687
1688 if (isempty(token))
1689 return false;
1690
1691 return strstr(last_path_component(argv[0]), token);
1692}
1693
7b3e062c
LP
1694static const char *const ioprio_class_table[] = {
1695 [IOPRIO_CLASS_NONE] = "none",
1696 [IOPRIO_CLASS_RT] = "realtime",
1697 [IOPRIO_CLASS_BE] = "best-effort",
f44b3035 1698 [IOPRIO_CLASS_IDLE] = "idle",
7b3e062c
LP
1699};
1700
10062bbc 1701DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, IOPRIO_N_CLASSES);
7b3e062c
LP
1702
1703static const char *const sigchld_code_table[] = {
1704 [CLD_EXITED] = "exited",
1705 [CLD_KILLED] = "killed",
1706 [CLD_DUMPED] = "dumped",
1707 [CLD_TRAPPED] = "trapped",
1708 [CLD_STOPPED] = "stopped",
1709 [CLD_CONTINUED] = "continued",
1710};
1711
1712DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1713
1714static const char* const sched_policy_table[] = {
1715 [SCHED_OTHER] = "other",
1716 [SCHED_BATCH] = "batch",
1717 [SCHED_IDLE] = "idle",
1718 [SCHED_FIFO] = "fifo",
f44b3035 1719 [SCHED_RR] = "rr",
7b3e062c
LP
1720};
1721
1722DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);