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