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