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