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