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