chiark / gitweb /
74a6e4abf7fa0b0204d5f9379bf83189a9564c37
[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
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 #if 0 /// UNNEEDED by elogind
453 int get_process_capeff(pid_t pid, char **capeff) {
454         const char *p;
455         int r;
456
457         assert(capeff);
458         assert(pid >= 0);
459
460         p = procfs_file_alloca(pid, "status");
461
462         r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
463         if (r == -ENOENT)
464                 return -ESRCH;
465
466         return r;
467 }
468 #endif // 0
469
470 static int get_process_link_contents(const char *proc_file, char **name) {
471         int r;
472
473         assert(proc_file);
474         assert(name);
475
476         r = readlink_malloc(proc_file, name);
477         if (r == -ENOENT)
478                 return -ESRCH;
479         if (r < 0)
480                 return r;
481
482         return 0;
483 }
484
485 int get_process_exe(pid_t pid, char **name) {
486         const char *p;
487         char *d;
488         int r;
489
490         assert(pid >= 0);
491
492         p = procfs_file_alloca(pid, "exe");
493         r = get_process_link_contents(p, name);
494         if (r < 0)
495                 return r;
496
497         d = endswith(*name, " (deleted)");
498         if (d)
499                 *d = '\0';
500
501         return 0;
502 }
503
504 #if 0 /// UNNEEDED by elogind
505 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
506         _cleanup_fclose_ FILE *f = NULL;
507         char line[LINE_MAX];
508         const char *p;
509
510         assert(field);
511         assert(uid);
512
513         if (pid < 0)
514                 return -EINVAL;
515
516         p = procfs_file_alloca(pid, "status");
517         f = fopen(p, "re");
518         if (!f) {
519                 if (errno == ENOENT)
520                         return -ESRCH;
521                 return -errno;
522         }
523
524         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
525
526         FOREACH_LINE(line, f, return -errno) {
527                 char *l;
528
529                 l = strstrip(line);
530
531                 if (startswith(l, field)) {
532                         l += strlen(field);
533                         l += strspn(l, WHITESPACE);
534
535                         l[strcspn(l, WHITESPACE)] = 0;
536
537                         return parse_uid(l, uid);
538                 }
539         }
540
541         return -EIO;
542 }
543
544 int get_process_uid(pid_t pid, uid_t *uid) {
545
546         if (pid == 0 || pid == getpid_cached()) {
547                 *uid = getuid();
548                 return 0;
549         }
550
551         return get_process_id(pid, "Uid:", uid);
552 }
553
554 int get_process_gid(pid_t pid, gid_t *gid) {
555
556         if (pid == 0 || pid == getpid_cached()) {
557                 *gid = getgid();
558                 return 0;
559         }
560
561         assert_cc(sizeof(uid_t) == sizeof(gid_t));
562         return get_process_id(pid, "Gid:", gid);
563 }
564
565 int get_process_cwd(pid_t pid, char **cwd) {
566         const char *p;
567
568         assert(pid >= 0);
569
570         p = procfs_file_alloca(pid, "cwd");
571
572         return get_process_link_contents(p, cwd);
573 }
574
575 int get_process_root(pid_t pid, char **root) {
576         const char *p;
577
578         assert(pid >= 0);
579
580         p = procfs_file_alloca(pid, "root");
581
582         return get_process_link_contents(p, root);
583 }
584
585 int get_process_environ(pid_t pid, char **env) {
586         _cleanup_fclose_ FILE *f = NULL;
587         _cleanup_free_ char *outcome = NULL;
588         int c;
589         const char *p;
590         size_t allocated = 0, sz = 0;
591
592         assert(pid >= 0);
593         assert(env);
594
595         p = procfs_file_alloca(pid, "environ");
596
597         f = fopen(p, "re");
598         if (!f) {
599                 if (errno == ENOENT)
600                         return -ESRCH;
601                 return -errno;
602         }
603
604         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
605
606         while ((c = fgetc(f)) != EOF) {
607                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
608                         return -ENOMEM;
609
610                 if (c == '\0')
611                         outcome[sz++] = '\n';
612                 else
613                         sz += cescape_char(c, outcome + sz);
614         }
615
616         if (!outcome) {
617                 outcome = strdup("");
618                 if (!outcome)
619                         return -ENOMEM;
620         } else
621                 outcome[sz] = '\0';
622
623         *env = TAKE_PTR(outcome);
624
625         return 0;
626 }
627
628 int get_process_ppid(pid_t pid, pid_t *_ppid) {
629         int r;
630         _cleanup_free_ char *line = NULL;
631         long unsigned ppid;
632         const char *p;
633
634         assert(pid >= 0);
635         assert(_ppid);
636
637         if (pid == 0 || pid == getpid_cached()) {
638                 *_ppid = getppid();
639                 return 0;
640         }
641
642         p = procfs_file_alloca(pid, "stat");
643         r = read_one_line_file(p, &line);
644         if (r == -ENOENT)
645                 return -ESRCH;
646         if (r < 0)
647                 return r;
648
649         /* Let's skip the pid and comm fields. The latter is enclosed
650          * in () but does not escape any () in its value, so let's
651          * skip over it manually */
652
653         p = strrchr(line, ')');
654         if (!p)
655                 return -EIO;
656
657         p++;
658
659         if (sscanf(p, " "
660                    "%*c "  /* state */
661                    "%lu ", /* ppid */
662                    &ppid) != 1)
663                 return -EIO;
664
665         if ((long unsigned) (pid_t) ppid != ppid)
666                 return -ERANGE;
667
668         *_ppid = (pid_t) ppid;
669
670         return 0;
671 }
672 #endif // 0
673
674 int wait_for_terminate(pid_t pid, siginfo_t *status) {
675         siginfo_t dummy;
676
677         assert(pid >= 1);
678
679         if (!status)
680                 status = &dummy;
681
682         for (;;) {
683                 zero(*status);
684
685                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
686
687                         if (errno == EINTR)
688                                 continue;
689
690                         return negative_errno();
691                 }
692
693                 return 0;
694         }
695 }
696
697 /*
698  * Return values:
699  * < 0 : wait_for_terminate() failed to get the state of the
700  *       process, the process was terminated by a signal, or
701  *       failed for an unknown reason.
702  * >=0 : The process terminated normally, and its exit code is
703  *       returned.
704  *
705  * That is, success is indicated by a return value of zero, and an
706  * error is indicated by a non-zero value.
707  *
708  * A warning is emitted if the process terminates abnormally,
709  * and also if it returns non-zero unless check_exit_code is true.
710  */
711 int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) {
712         _cleanup_free_ char *buffer = NULL;
713         siginfo_t status;
714         int r, prio;
715
716         assert(pid > 1);
717
718         if (!name) {
719                 r = get_process_comm(pid, &buffer);
720                 if (r < 0)
721                         log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid);
722                 else
723                         name = buffer;
724         }
725
726         prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
727
728         r = wait_for_terminate(pid, &status);
729         if (r < 0)
730                 return log_full_errno(prio, r, "Failed to wait for %s: %m", strna(name));
731
732         if (status.si_code == CLD_EXITED) {
733                 if (status.si_status != EXIT_SUCCESS)
734                         log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
735                                  "%s failed with exit status %i.", strna(name), status.si_status);
736                 else
737                         log_debug("%s succeeded.", name);
738
739                 return status.si_status;
740
741         } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
742
743                 log_full(prio, "%s terminated by signal %s.", strna(name), signal_to_string(status.si_status));
744                 return -EPROTO;
745         }
746
747         log_full(prio, "%s failed due to unknown reason.", strna(name));
748         return -EPROTO;
749 }
750
751 /*
752  * Return values:
753  *
754  * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
755  *       was terminated by a signal, or failed for an unknown reason.
756  *
757  * >=0 : The process terminated normally with no failures.
758  *
759  * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
760  * states are indicated by error is indicated by a non-zero value.
761  *
762  * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
763  * to remain entirely race-free.
764  */
765 int wait_for_terminate_with_timeout(pid_t pid, usec_t timeout) {
766         sigset_t mask;
767         int r;
768         usec_t until;
769
770         assert_se(sigemptyset(&mask) == 0);
771         assert_se(sigaddset(&mask, SIGCHLD) == 0);
772
773         /* Drop into a sigtimewait-based timeout. Waiting for the
774          * pid to exit. */
775         until = now(CLOCK_MONOTONIC) + timeout;
776         for (;;) {
777                 usec_t n;
778                 siginfo_t status = {};
779                 struct timespec ts;
780
781                 n = now(CLOCK_MONOTONIC);
782                 if (n >= until)
783                         break;
784
785                 r = sigtimedwait(&mask, NULL, timespec_store(&ts, until - n)) < 0 ? -errno : 0;
786                 /* Assuming we woke due to the child exiting. */
787                 if (waitid(P_PID, pid, &status, WEXITED|WNOHANG) == 0) {
788                         if (status.si_pid == pid) {
789                                 /* This is the correct child.*/
790                                 if (status.si_code == CLD_EXITED)
791                                         return (status.si_status == 0) ? 0 : -EPROTO;
792                                 else
793                                         return -EPROTO;
794                         }
795                 }
796                 /* Not the child, check for errors and proceed appropriately */
797                 if (r < 0) {
798                         switch (r) {
799                         case -EAGAIN:
800                                 /* Timed out, child is likely hung. */
801                                 return -ETIMEDOUT;
802                         case -EINTR:
803                                 /* Received a different signal and should retry */
804                                 continue;
805                         default:
806                                 /* Return any unexpected errors */
807                                 return r;
808                         }
809                 }
810         }
811
812         return -EPROTO;
813 }
814
815 #if 0 /// UNNEEDED by elogind
816 void sigkill_wait(pid_t pid) {
817         assert(pid > 1);
818
819         if (kill(pid, SIGKILL) > 0)
820                 (void) wait_for_terminate(pid, NULL);
821 }
822
823 void sigkill_waitp(pid_t *pid) {
824         PROTECT_ERRNO;
825
826         if (!pid)
827                 return;
828         if (*pid <= 1)
829                 return;
830
831         sigkill_wait(*pid);
832 }
833 #endif // 0
834
835 void sigterm_wait(pid_t pid) {
836         assert(pid > 1);
837
838         if (kill_and_sigcont(pid, SIGTERM) > 0)
839                 (void) wait_for_terminate(pid, NULL);
840 }
841
842 int kill_and_sigcont(pid_t pid, int sig) {
843         int r;
844
845         r = kill(pid, sig) < 0 ? -errno : 0;
846
847         /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
848          * affected by a process being suspended anyway. */
849         if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
850                 (void) kill(pid, SIGCONT);
851
852         return r;
853 }
854
855 int getenv_for_pid(pid_t pid, const char *field, char **ret) {
856         _cleanup_fclose_ FILE *f = NULL;
857         char *value = NULL;
858         bool done = false;
859         const char *path;
860         size_t l;
861
862         assert(pid >= 0);
863         assert(field);
864         assert(ret);
865
866         if (pid == 0 || pid == getpid_cached()) {
867                 const char *e;
868
869                 e = getenv(field);
870                 if (!e) {
871                         *ret = NULL;
872                         return 0;
873                 }
874
875                 value = strdup(e);
876                 if (!value)
877                         return -ENOMEM;
878
879                 *ret = value;
880                 return 1;
881         }
882
883         path = procfs_file_alloca(pid, "environ");
884
885         f = fopen(path, "re");
886         if (!f) {
887                 if (errno == ENOENT)
888                         return -ESRCH;
889
890                 return -errno;
891         }
892
893         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
894
895         l = strlen(field);
896
897         do {
898                 char line[LINE_MAX];
899                 size_t i;
900
901                 for (i = 0; i < sizeof(line)-1; i++) {
902                         int c;
903
904                         c = getc(f);
905                         if (_unlikely_(c == EOF)) {
906                                 done = true;
907                                 break;
908                         } else if (c == 0)
909                                 break;
910
911                         line[i] = c;
912                 }
913                 line[i] = 0;
914
915                 if (strneq(line, field, l) && line[l] == '=') {
916                         value = strdup(line + l + 1);
917                         if (!value)
918                                 return -ENOMEM;
919
920                         *ret = value;
921                         return 1;
922                 }
923
924         } while (!done);
925
926         *ret = NULL;
927         return 0;
928 }
929
930 bool pid_is_unwaited(pid_t pid) {
931         /* Checks whether a PID is still valid at all, including a zombie */
932
933         if (pid < 0)
934                 return false;
935
936         if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
937                 return true;
938
939         if (pid == getpid_cached())
940                 return true;
941
942         if (kill(pid, 0) >= 0)
943                 return true;
944
945         return errno != ESRCH;
946 }
947
948 bool pid_is_alive(pid_t pid) {
949         int r;
950
951         /* Checks whether a PID is still valid and not a zombie */
952
953         if (pid < 0)
954                 return false;
955
956         if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
957                 return true;
958
959         if (pid == getpid_cached())
960                 return true;
961
962         r = get_process_state(pid);
963         if (IN_SET(r, -ESRCH, 'Z'))
964                 return false;
965
966         return true;
967 }
968
969 #if 0 /// UNNEEDED by elogind
970 int pid_from_same_root_fs(pid_t pid) {
971         const char *root;
972
973         if (pid < 0)
974                 return false;
975
976         if (pid == 0 || pid == getpid_cached())
977                 return true;
978
979         root = procfs_file_alloca(pid, "root");
980
981         return files_same(root, "/proc/1/root", 0);
982 }
983 #endif // 0
984
985 bool is_main_thread(void) {
986         static thread_local int cached = 0;
987
988         if (_unlikely_(cached == 0))
989                 cached = getpid_cached() == gettid() ? 1 : -1;
990
991         return cached > 0;
992 }
993
994 #if 0 /// UNNEEDED by elogind
995 _noreturn_ void freeze(void) {
996
997         log_close();
998
999         /* Make sure nobody waits for us on a socket anymore */
1000         close_all_fds(NULL, 0);
1001
1002         sync();
1003
1004         /* Let's not freeze right away, but keep reaping zombies. */
1005         for (;;) {
1006                 int r;
1007                 siginfo_t si = {};
1008
1009                 r = waitid(P_ALL, 0, &si, WEXITED);
1010                 if (r < 0 && errno != EINTR)
1011                         break;
1012         }
1013
1014         /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
1015         for (;;)
1016                 pause();
1017 }
1018
1019 bool oom_score_adjust_is_valid(int oa) {
1020         return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
1021 }
1022
1023 unsigned long personality_from_string(const char *p) {
1024         int architecture;
1025
1026         if (!p)
1027                 return PERSONALITY_INVALID;
1028
1029         /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1030          * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1031          * the same register size. */
1032
1033         architecture = architecture_from_string(p);
1034         if (architecture < 0)
1035                 return PERSONALITY_INVALID;
1036
1037         if (architecture == native_architecture())
1038                 return PER_LINUX;
1039 #ifdef SECONDARY_ARCHITECTURE
1040         if (architecture == SECONDARY_ARCHITECTURE)
1041                 return PER_LINUX32;
1042 #endif
1043
1044         return PERSONALITY_INVALID;
1045 }
1046
1047 const char* personality_to_string(unsigned long p) {
1048         int architecture = _ARCHITECTURE_INVALID;
1049
1050         if (p == PER_LINUX)
1051                 architecture = native_architecture();
1052 #ifdef SECONDARY_ARCHITECTURE
1053         else if (p == PER_LINUX32)
1054                 architecture = SECONDARY_ARCHITECTURE;
1055 #endif
1056
1057         if (architecture < 0)
1058                 return NULL;
1059
1060         return architecture_to_string(architecture);
1061 }
1062
1063 int safe_personality(unsigned long p) {
1064         int ret;
1065
1066         /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1067          * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1068          * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1069          * the return value indicating the same issue, so that we are definitely on the safe side.
1070          *
1071          * See https://github.com/systemd/systemd/issues/6737 */
1072
1073         errno = 0;
1074         ret = personality(p);
1075         if (ret < 0) {
1076                 if (errno != 0)
1077                         return -errno;
1078
1079                 errno = -ret;
1080         }
1081
1082         return ret;
1083 }
1084
1085 int opinionated_personality(unsigned long *ret) {
1086         int current;
1087
1088         /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1089          * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1090          * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1091
1092         current = safe_personality(PERSONALITY_INVALID);
1093         if (current < 0)
1094                 return current;
1095
1096         if (((unsigned long) current & 0xffff) == PER_LINUX32)
1097                 *ret = PER_LINUX32;
1098         else
1099                 *ret = PER_LINUX;
1100
1101         return 0;
1102 }
1103
1104 void valgrind_summary_hack(void) {
1105 #if HAVE_VALGRIND_VALGRIND_H
1106         if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
1107                 pid_t pid;
1108                 pid = raw_clone(SIGCHLD);
1109                 if (pid < 0)
1110                         log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
1111                 else if (pid == 0)
1112                         exit(EXIT_SUCCESS);
1113                 else {
1114                         log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
1115                         (void) wait_for_terminate(pid, NULL);
1116                 }
1117         }
1118 #endif
1119 }
1120
1121 int pid_compare_func(const void *a, const void *b) {
1122         const pid_t *p = a, *q = b;
1123
1124         /* Suitable for usage in qsort() */
1125
1126         if (*p < *q)
1127                 return -1;
1128         if (*p > *q)
1129                 return 1;
1130         return 0;
1131 }
1132
1133 int ioprio_parse_priority(const char *s, int *ret) {
1134         int i, r;
1135
1136         assert(s);
1137         assert(ret);
1138
1139         r = safe_atoi(s, &i);
1140         if (r < 0)
1141                 return r;
1142
1143         if (!ioprio_priority_is_valid(i))
1144                 return -EINVAL;
1145
1146         *ret = i;
1147         return 0;
1148 }
1149 #endif // 0
1150
1151 /* The cached PID, possible values:
1152  *
1153  *     == UNSET [0]  â†’ cache not initialized yet
1154  *     == BUSY [-1]  â†’ some thread is initializing it at the moment
1155  *     any other     â†’ the cached PID
1156  */
1157
1158 #define CACHED_PID_UNSET ((pid_t) 0)
1159 #define CACHED_PID_BUSY ((pid_t) -1)
1160
1161 static pid_t cached_pid = CACHED_PID_UNSET;
1162
1163 void reset_cached_pid(void) {
1164         /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1165         cached_pid = CACHED_PID_UNSET;
1166 }
1167
1168 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1169  * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1170  * libpthread, as it is part of glibc anyway. */
1171 #ifdef __GLIBC__
1172 extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void * __dso_handle);
1173 extern void* __dso_handle __attribute__ ((__weak__));
1174 #endif // ifdef __GLIBC__
1175
1176 pid_t getpid_cached(void) {
1177         static bool installed = false;
1178         pid_t current_value;
1179
1180         /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1181          * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1182          * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1183          * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1184          *
1185          * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1186          * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1187          */
1188
1189         current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1190
1191         switch (current_value) {
1192
1193         case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1194                 pid_t new_pid;
1195
1196                 new_pid = raw_getpid();
1197
1198                 if (!installed) {
1199                         /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1200                          * only half-documented (glibc doesn't document it but LSB does â€” though only superficially)
1201                          * we'll check for errors only in the most generic fashion possible. */
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                         installed = true;
1210                 }
1211
1212                 cached_pid = new_pid;
1213                 return new_pid;
1214         }
1215
1216         case CACHED_PID_BUSY: /* Somebody else is currently initializing */
1217                 return raw_getpid();
1218
1219         default: /* Properly initialized */
1220                 return current_value;
1221         }
1222 }
1223
1224 int must_be_root(void) {
1225
1226         if (geteuid() == 0)
1227                 return 0;
1228
1229         log_error("Need to be root.");
1230         return -EPERM;
1231 }
1232
1233 int safe_fork_full(
1234                 const char *name,
1235                 const int except_fds[],
1236                 size_t n_except_fds,
1237                 ForkFlags flags,
1238                 pid_t *ret_pid) {
1239
1240         pid_t original_pid, pid;
1241         sigset_t saved_ss, ss;
1242         bool block_signals = false;
1243         int prio, r;
1244
1245         /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1246          * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1247
1248         prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG;
1249
1250         original_pid = getpid_cached();
1251
1252         if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG)) {
1253
1254                 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1255                  * be sure that SIGTERMs are not lost we might send to the child. */
1256
1257                 if (sigfillset(&ss) < 0)
1258                         return log_full_errno(prio, errno, "Failed to reset signal set: %m");
1259
1260                 block_signals = true;
1261
1262         } else if (flags & FORK_WAIT) {
1263
1264                 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1265
1266                 if (sigemptyset(&ss) < 0)
1267                         return log_full_errno(prio, errno, "Failed to clear signal set: %m");
1268
1269                 if (sigaddset(&ss, SIGCHLD) < 0)
1270                         return log_full_errno(prio, errno, "Failed to add SIGCHLD to signal set: %m");
1271
1272                 block_signals = true;
1273         }
1274
1275         if (block_signals)
1276                 if (sigprocmask(SIG_SETMASK, &ss, &saved_ss) < 0)
1277                         return log_full_errno(prio, errno, "Failed to set signal mask: %m");
1278
1279         if (flags & FORK_NEW_MOUNTNS)
1280                 pid = raw_clone(SIGCHLD|CLONE_NEWNS);
1281         else
1282                 pid = fork();
1283         if (pid < 0) {
1284                 r = -errno;
1285
1286                 if (block_signals) /* undo what we did above */
1287                         (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL);
1288
1289                 return log_full_errno(prio, r, "Failed to fork: %m");
1290         }
1291         if (pid > 0) {
1292                 /* We are in the parent process */
1293
1294                 log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid);
1295
1296                 if (flags & FORK_WAIT) {
1297                         r = wait_for_terminate_and_check(name, pid, (flags & FORK_LOG ? WAIT_LOG : 0));
1298                         if (r < 0)
1299                                 return r;
1300                         if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */
1301                                 return -EPROTO;
1302                 }
1303
1304                 if (block_signals) /* undo what we did above */
1305                         (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL);
1306
1307                 if (ret_pid)
1308                         *ret_pid = pid;
1309
1310                 return 1;
1311         }
1312
1313         /* We are in the child process */
1314
1315         if (flags & FORK_REOPEN_LOG) {
1316                 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1317                 log_close();
1318                 log_set_open_when_needed(true);
1319         }
1320
1321         if (name) {
1322                 r = rename_process(name);
1323                 if (r < 0)
1324                         log_full_errno(flags & FORK_LOG ? LOG_WARNING : LOG_DEBUG,
1325                                        r, "Failed to rename process, ignoring: %m");
1326         }
1327
1328         if (flags & FORK_DEATHSIG)
1329                 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) {
1330                         log_full_errno(prio, errno, "Failed to set death signal: %m");
1331                         _exit(EXIT_FAILURE);
1332                 }
1333
1334         if (flags & FORK_RESET_SIGNALS) {
1335                 r = reset_all_signal_handlers();
1336                 if (r < 0) {
1337                         log_full_errno(prio, r, "Failed to reset signal handlers: %m");
1338                         _exit(EXIT_FAILURE);
1339                 }
1340
1341                 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1342                 r = reset_signal_mask();
1343                 if (r < 0) {
1344                         log_full_errno(prio, r, "Failed to reset signal mask: %m");
1345                         _exit(EXIT_FAILURE);
1346                 }
1347         } else if (block_signals) { /* undo what we did above */
1348                 if (sigprocmask(SIG_SETMASK, &saved_ss, NULL) < 0) {
1349                         log_full_errno(prio, errno, "Failed to restore signal mask: %m");
1350                         _exit(EXIT_FAILURE);
1351                 }
1352         }
1353
1354         if (flags & FORK_DEATHSIG) {
1355                 pid_t ppid;
1356                 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1357                  * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1358
1359                 ppid = getppid();
1360                 if (ppid == 0)
1361                         /* Parent is in a differn't PID namespace. */;
1362                 else if (ppid != original_pid) {
1363                         log_debug("Parent died early, raising SIGTERM.");
1364                         (void) raise(SIGTERM);
1365                         _exit(EXIT_FAILURE);
1366                 }
1367         }
1368
1369         if (FLAGS_SET(flags, FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE)) {
1370
1371                 /* Optionally, make sure we never propagate mounts to the host. */
1372
1373                 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
1374                         log_full_errno(prio, errno, "Failed to remount root directory as MS_SLAVE: %m");
1375                         _exit(EXIT_FAILURE);
1376                 }
1377         }
1378
1379         if (flags & FORK_CLOSE_ALL_FDS) {
1380                 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1381                 log_close();
1382
1383                 r = close_all_fds(except_fds, n_except_fds);
1384                 if (r < 0) {
1385                         log_full_errno(prio, r, "Failed to close all file descriptors: %m");
1386                         _exit(EXIT_FAILURE);
1387                 }
1388         }
1389
1390         /* When we were asked to reopen the logs, do so again now */
1391         if (flags & FORK_REOPEN_LOG) {
1392                 log_open();
1393                 log_set_open_when_needed(false);
1394         }
1395
1396         if (flags & FORK_NULL_STDIO) {
1397                 r = make_null_stdio();
1398                 if (r < 0) {
1399                         log_full_errno(prio, r, "Failed to connect stdin/stdout to /dev/null: %m");
1400                         _exit(EXIT_FAILURE);
1401                 }
1402         }
1403
1404         if (ret_pid)
1405                 *ret_pid = getpid_cached();
1406
1407         return 0;
1408 }
1409
1410 int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) {
1411         bool stdout_is_tty, stderr_is_tty;
1412         size_t n, i;
1413         va_list ap;
1414         char **l;
1415         int r;
1416
1417         assert(path);
1418
1419         /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1420
1421         r = safe_fork_full(name, except, n_except, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS, ret_pid);
1422         if (r < 0)
1423                 return r;
1424         if (r > 0)
1425                 return 0;
1426
1427         /* In the child: */
1428
1429         stdout_is_tty = isatty(STDOUT_FILENO);
1430         stderr_is_tty = isatty(STDERR_FILENO);
1431
1432         if (!stdout_is_tty || !stderr_is_tty) {
1433                 int fd;
1434
1435                 /* Detach from stdout/stderr. and reopen
1436                  * /dev/tty for them. This is important to
1437                  * ensure that when systemctl is started via
1438                  * popen() or a similar call that expects to
1439                  * read EOF we actually do generate EOF and
1440                  * not delay this indefinitely by because we
1441                  * keep an unused copy of stdin around. */
1442                 fd = open("/dev/tty", O_WRONLY);
1443                 if (fd < 0) {
1444                         log_error_errno(errno, "Failed to open /dev/tty: %m");
1445                         _exit(EXIT_FAILURE);
1446                 }
1447
1448                 if (!stdout_is_tty && dup2(fd, STDOUT_FILENO) < 0) {
1449                         log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1450                         _exit(EXIT_FAILURE);
1451                 }
1452
1453                 if (!stderr_is_tty && dup2(fd, STDERR_FILENO) < 0) {
1454                         log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1455                         _exit(EXIT_FAILURE);
1456                 }
1457
1458                 safe_close_above_stdio(fd);
1459         }
1460
1461         /* Count arguments */
1462         va_start(ap, path);
1463         for (n = 0; va_arg(ap, char*); n++)
1464                 ;
1465         va_end(ap);
1466
1467         /* Allocate strv */
1468         l = newa(char*, n + 1);
1469
1470         /* Fill in arguments */
1471         va_start(ap, path);
1472         for (i = 0; i <= n; i++)
1473                 l[i] = va_arg(ap, char*);
1474         va_end(ap);
1475
1476         execv(path, l);
1477         _exit(EXIT_FAILURE);
1478 }
1479
1480 int set_oom_score_adjust(int value) {
1481         char t[DECIMAL_STR_MAX(int)];
1482
1483         sprintf(t, "%i", value);
1484
1485         return write_string_file("/proc/self/oom_score_adj", t,
1486                                  WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
1487 }
1488
1489 #if 0 /// UNNEEDED by elogind
1490 static const char *const ioprio_class_table[] = {
1491         [IOPRIO_CLASS_NONE] = "none",
1492         [IOPRIO_CLASS_RT] = "realtime",
1493         [IOPRIO_CLASS_BE] = "best-effort",
1494         [IOPRIO_CLASS_IDLE] = "idle"
1495 };
1496
1497 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, IOPRIO_N_CLASSES);
1498
1499 static const char *const sigchld_code_table[] = {
1500         [CLD_EXITED] = "exited",
1501         [CLD_KILLED] = "killed",
1502         [CLD_DUMPED] = "dumped",
1503         [CLD_TRAPPED] = "trapped",
1504         [CLD_STOPPED] = "stopped",
1505         [CLD_CONTINUED] = "continued",
1506 };
1507
1508 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1509
1510 static const char* const sched_policy_table[] = {
1511         [SCHED_OTHER] = "other",
1512         [SCHED_BATCH] = "batch",
1513         [SCHED_IDLE] = "idle",
1514         [SCHED_FIFO] = "fifo",
1515         [SCHED_RR] = "rr"
1516 };
1517
1518 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
1519 #endif // 0