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