chiark / gitweb /
basic/strv: add STRPTR_IN_SET
[elogind.git] / src / basic / process-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <ctype.h>
21 #include <errno.h>
22 #include <limits.h>
23 #include <linux/oom.h>
24 #include <sched.h>
25 #include <signal.h>
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/personality.h>
31 #include <sys/prctl.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <syslog.h>
35 #include <unistd.h>
36 #ifdef HAVE_VALGRIND_VALGRIND_H
37 #include <valgrind/valgrind.h>
38 #endif
39
40 #include "alloc-util.h"
41 //#include "architecture.h"
42 #include "escape.h"
43 #include "fd-util.h"
44 #include "fileio.h"
45 #include "fs-util.h"
46 //#include "ioprio.h"
47 #include "log.h"
48 #include "macro.h"
49 #include "missing.h"
50 #include "process-util.h"
51 #include "signal-util.h"
52 //#include "stat-util.h"
53 #include "string-table.h"
54 #include "string-util.h"
55 #include "user-util.h"
56 #include "util.h"
57
58 int get_process_state(pid_t pid) {
59         const char *p;
60         char state;
61         int r;
62         _cleanup_free_ char *line = NULL;
63
64         assert(pid >= 0);
65
66         p = procfs_file_alloca(pid, "stat");
67
68         r = read_one_line_file(p, &line);
69         if (r == -ENOENT)
70                 return -ESRCH;
71         if (r < 0)
72                 return r;
73
74         p = strrchr(line, ')');
75         if (!p)
76                 return -EIO;
77
78         p++;
79
80         if (sscanf(p, " %c", &state) != 1)
81                 return -EIO;
82
83         return (unsigned char) state;
84 }
85
86 int get_process_comm(pid_t pid, char **name) {
87         const char *p;
88         int r;
89
90         assert(name);
91         assert(pid >= 0);
92
93         p = procfs_file_alloca(pid, "comm");
94
95         r = read_one_line_file(p, name);
96         if (r == -ENOENT)
97                 return -ESRCH;
98
99         return r;
100 }
101
102 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
103         _cleanup_fclose_ FILE *f = NULL;
104         bool space = false;
105         char *r = NULL, *k;
106         const char *p;
107         int c;
108
109         assert(line);
110         assert(pid >= 0);
111
112         /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
113          * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
114          * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
115          * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
116          * command line that resolves to the empty string will return the "comm" name of the process instead.
117          *
118          * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
119          * comm_fallback is false). */
120
121         p = procfs_file_alloca(pid, "cmdline");
122
123         f = fopen(p, "re");
124         if (!f) {
125                 if (errno == ENOENT)
126                         return -ESRCH;
127                 return -errno;
128         }
129
130         if (max_length == 1) {
131
132                 /* If there's only room for one byte, return the empty string */
133                 r = new0(char, 1);
134                 if (!r)
135                         return -ENOMEM;
136
137                 *line = r;
138                 return 0;
139
140         } else if (max_length == 0) {
141                 size_t len = 0, allocated = 0;
142
143                 while ((c = getc(f)) != EOF) {
144
145                         if (!GREEDY_REALLOC(r, allocated, len+3)) {
146                                 free(r);
147                                 return -ENOMEM;
148                         }
149
150                         if (isprint(c)) {
151                                 if (space) {
152                                         r[len++] = ' ';
153                                         space = false;
154                                 }
155
156                                 r[len++] = c;
157                         } else if (len > 0)
158                                 space = true;
159                }
160
161                 if (len > 0)
162                         r[len] = 0;
163                 else
164                         r = mfree(r);
165
166         } else {
167                 bool dotdotdot = false;
168                 size_t left;
169
170                 r = new(char, max_length);
171                 if (!r)
172                         return -ENOMEM;
173
174                 k = r;
175                 left = max_length;
176                 while ((c = getc(f)) != EOF) {
177
178                         if (isprint(c)) {
179
180                                 if (space) {
181                                         if (left <= 2) {
182                                                 dotdotdot = true;
183                                                 break;
184                                         }
185
186                                         *(k++) = ' ';
187                                         left--;
188                                         space = false;
189                                 }
190
191                                 if (left <= 1) {
192                                         dotdotdot = true;
193                                         break;
194                                 }
195
196                                 *(k++) = (char) c;
197                                 left--;
198                         } else if (k > r)
199                                 space = true;
200                 }
201
202                 if (dotdotdot) {
203                         if (max_length <= 4) {
204                                 k = r;
205                                 left = max_length;
206                         } else {
207                                 k = r + max_length - 4;
208                                 left = 4;
209
210                                 /* Eat up final spaces */
211                                 while (k > r && isspace(k[-1])) {
212                                         k--;
213                                         left++;
214                                 }
215                         }
216
217                         strncpy(k, "...", left-1);
218                         k[left-1] = 0;
219                 } else
220                         *k = 0;
221         }
222
223         /* Kernel threads have no argv[] */
224         if (isempty(r)) {
225                 _cleanup_free_ char *t = NULL;
226                 int h;
227
228                 free(r);
229
230                 if (!comm_fallback)
231                         return -ENOENT;
232
233                 h = get_process_comm(pid, &t);
234                 if (h < 0)
235                         return h;
236
237                 if (max_length == 0)
238                         r = strjoin("[", t, "]", NULL);
239                 else {
240                         size_t l;
241
242                         l = strlen(t);
243
244                         if (l + 3 <= max_length)
245                                 r = strjoin("[", t, "]", NULL);
246                         else if (max_length <= 6) {
247
248                                 r = new(char, max_length);
249                                 if (!r)
250                                         return -ENOMEM;
251
252                                 memcpy(r, "[...]", max_length-1);
253                                 r[max_length-1] = 0;
254                         } else {
255                                 char *e;
256
257                                 t[max_length - 6] = 0;
258
259                                 /* Chop off final spaces */
260                                 e = strchr(t, 0);
261                                 while (e > t && isspace(e[-1]))
262                                         e--;
263                                 *e = 0;
264
265                                 r = strjoin("[", t, "...]", NULL);
266                         }
267                 }
268                 if (!r)
269                         return -ENOMEM;
270         }
271
272         *line = r;
273         return 0;
274 }
275
276 #if 0 /// UNNEEDED by elogind
277 void rename_process(const char name[8]) {
278         assert(name);
279
280         /* This is a like a poor man's setproctitle(). It changes the
281          * comm field, argv[0], and also the glibc's internally used
282          * name of the process. For the first one a limit of 16 chars
283          * applies, to the second one usually one of 10 (i.e. length
284          * of "/sbin/init"), to the third one one of 7 (i.e. length of
285          * "systemd"). If you pass a longer string it will be
286          * truncated */
287
288         (void) prctl(PR_SET_NAME, name);
289
290         if (program_invocation_name)
291                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
292
293         if (saved_argc > 0) {
294                 int i;
295
296                 if (saved_argv[0])
297                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
298
299                 for (i = 1; i < saved_argc; i++) {
300                         if (!saved_argv[i])
301                                 break;
302
303                         memzero(saved_argv[i], strlen(saved_argv[i]));
304                 }
305         }
306 }
307 #endif // 0
308
309 int is_kernel_thread(pid_t pid) {
310         const char *p;
311         size_t count;
312         char c;
313         bool eof;
314         FILE *f;
315
316         if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
317                 return 0;
318
319         assert(pid > 1);
320
321         p = procfs_file_alloca(pid, "cmdline");
322         f = fopen(p, "re");
323         if (!f) {
324                 if (errno == ENOENT)
325                         return -ESRCH;
326                 return -errno;
327         }
328
329         count = fread(&c, 1, 1, f);
330         eof = feof(f);
331         fclose(f);
332
333         /* Kernel threads have an empty cmdline */
334
335         if (count <= 0)
336                 return eof ? 1 : -errno;
337
338         return 0;
339 }
340
341 #if 0 /// UNNEEDED by elogind
342 int get_process_capeff(pid_t pid, char **capeff) {
343         const char *p;
344         int r;
345
346         assert(capeff);
347         assert(pid >= 0);
348
349         p = procfs_file_alloca(pid, "status");
350
351         r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
352         if (r == -ENOENT)
353                 return -ESRCH;
354
355         return r;
356 }
357 #endif // 0
358
359 static int get_process_link_contents(const char *proc_file, char **name) {
360         int r;
361
362         assert(proc_file);
363         assert(name);
364
365         r = readlink_malloc(proc_file, name);
366         if (r == -ENOENT)
367                 return -ESRCH;
368         if (r < 0)
369                 return r;
370
371         return 0;
372 }
373
374 int get_process_exe(pid_t pid, char **name) {
375         const char *p;
376         char *d;
377         int r;
378
379         assert(pid >= 0);
380
381         p = procfs_file_alloca(pid, "exe");
382         r = get_process_link_contents(p, name);
383         if (r < 0)
384                 return r;
385
386         d = endswith(*name, " (deleted)");
387         if (d)
388                 *d = '\0';
389
390         return 0;
391 }
392
393 #if 0 /// UNNEEDED by elogind
394 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
395         _cleanup_fclose_ FILE *f = NULL;
396         char line[LINE_MAX];
397         const char *p;
398
399         assert(field);
400         assert(uid);
401
402         p = procfs_file_alloca(pid, "status");
403         f = fopen(p, "re");
404         if (!f) {
405                 if (errno == ENOENT)
406                         return -ESRCH;
407                 return -errno;
408         }
409
410         FOREACH_LINE(line, f, return -errno) {
411                 char *l;
412
413                 l = strstrip(line);
414
415                 if (startswith(l, field)) {
416                         l += strlen(field);
417                         l += strspn(l, WHITESPACE);
418
419                         l[strcspn(l, WHITESPACE)] = 0;
420
421                         return parse_uid(l, uid);
422                 }
423         }
424
425         return -EIO;
426 }
427
428 int get_process_uid(pid_t pid, uid_t *uid) {
429         return get_process_id(pid, "Uid:", uid);
430 }
431
432 int get_process_gid(pid_t pid, gid_t *gid) {
433         assert_cc(sizeof(uid_t) == sizeof(gid_t));
434         return get_process_id(pid, "Gid:", gid);
435 }
436
437 int get_process_cwd(pid_t pid, char **cwd) {
438         const char *p;
439
440         assert(pid >= 0);
441
442         p = procfs_file_alloca(pid, "cwd");
443
444         return get_process_link_contents(p, cwd);
445 }
446
447 int get_process_root(pid_t pid, char **root) {
448         const char *p;
449
450         assert(pid >= 0);
451
452         p = procfs_file_alloca(pid, "root");
453
454         return get_process_link_contents(p, root);
455 }
456
457 int get_process_environ(pid_t pid, char **env) {
458         _cleanup_fclose_ FILE *f = NULL;
459         _cleanup_free_ char *outcome = NULL;
460         int c;
461         const char *p;
462         size_t allocated = 0, sz = 0;
463
464         assert(pid >= 0);
465         assert(env);
466
467         p = procfs_file_alloca(pid, "environ");
468
469         f = fopen(p, "re");
470         if (!f) {
471                 if (errno == ENOENT)
472                         return -ESRCH;
473                 return -errno;
474         }
475
476         while ((c = fgetc(f)) != EOF) {
477                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
478                         return -ENOMEM;
479
480                 if (c == '\0')
481                         outcome[sz++] = '\n';
482                 else
483                         sz += cescape_char(c, outcome + sz);
484         }
485
486         if (!outcome) {
487                 outcome = strdup("");
488                 if (!outcome)
489                         return -ENOMEM;
490         } else
491                 outcome[sz] = '\0';
492
493         *env = outcome;
494         outcome = NULL;
495
496         return 0;
497 }
498
499 int get_process_ppid(pid_t pid, pid_t *_ppid) {
500         int r;
501         _cleanup_free_ char *line = NULL;
502         long unsigned ppid;
503         const char *p;
504
505         assert(pid >= 0);
506         assert(_ppid);
507
508         if (pid == 0) {
509                 *_ppid = getppid();
510                 return 0;
511         }
512
513         p = procfs_file_alloca(pid, "stat");
514         r = read_one_line_file(p, &line);
515         if (r == -ENOENT)
516                 return -ESRCH;
517         if (r < 0)
518                 return r;
519
520         /* Let's skip the pid and comm fields. The latter is enclosed
521          * in () but does not escape any () in its value, so let's
522          * skip over it manually */
523
524         p = strrchr(line, ')');
525         if (!p)
526                 return -EIO;
527
528         p++;
529
530         if (sscanf(p, " "
531                    "%*c "  /* state */
532                    "%lu ", /* ppid */
533                    &ppid) != 1)
534                 return -EIO;
535
536         if ((long unsigned) (pid_t) ppid != ppid)
537                 return -ERANGE;
538
539         *_ppid = (pid_t) ppid;
540
541         return 0;
542 }
543 #endif // 0
544
545 int wait_for_terminate(pid_t pid, siginfo_t *status) {
546         siginfo_t dummy;
547
548         assert(pid >= 1);
549
550         if (!status)
551                 status = &dummy;
552
553         for (;;) {
554                 zero(*status);
555
556                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
557
558                         if (errno == EINTR)
559                                 continue;
560
561                         return negative_errno();
562                 }
563
564                 return 0;
565         }
566 }
567
568 /*
569  * Return values:
570  * < 0 : wait_for_terminate() failed to get the state of the
571  *       process, the process was terminated by a signal, or
572  *       failed for an unknown reason.
573  * >=0 : The process terminated normally, and its exit code is
574  *       returned.
575  *
576  * That is, success is indicated by a return value of zero, and an
577  * error is indicated by a non-zero value.
578  *
579  * A warning is emitted if the process terminates abnormally,
580  * and also if it returns non-zero unless check_exit_code is true.
581  */
582 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
583         int r;
584         siginfo_t status;
585
586         assert(name);
587         assert(pid > 1);
588
589         r = wait_for_terminate(pid, &status);
590         if (r < 0)
591                 return log_warning_errno(r, "Failed to wait for %s: %m", name);
592
593         if (status.si_code == CLD_EXITED) {
594                 if (status.si_status != 0)
595                         log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
596                                  "%s failed with error code %i.", name, status.si_status);
597                 else
598                         log_debug("%s succeeded.", name);
599
600                 return status.si_status;
601         } else if (status.si_code == CLD_KILLED ||
602                    status.si_code == CLD_DUMPED) {
603
604                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
605                 return -EPROTO;
606         }
607
608         log_warning("%s failed due to unknown reason.", name);
609         return -EPROTO;
610 }
611
612 #if 0 /// UNNEEDED by elogind
613 void sigkill_wait(pid_t pid) {
614         assert(pid > 1);
615
616         if (kill(pid, SIGKILL) > 0)
617                 (void) wait_for_terminate(pid, NULL);
618 }
619
620 void sigkill_waitp(pid_t *pid) {
621         if (!pid)
622                 return;
623         if (*pid <= 1)
624                 return;
625
626         sigkill_wait(*pid);
627 }
628
629 int kill_and_sigcont(pid_t pid, int sig) {
630         int r;
631
632         r = kill(pid, sig) < 0 ? -errno : 0;
633
634         /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
635          * affected by a process being suspended anyway. */
636         if (r >= 0 && !IN_SET(SIGCONT, SIGKILL))
637                 (void) kill(pid, SIGCONT);
638
639         return r;
640 }
641 #endif // 0
642
643 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
644         _cleanup_fclose_ FILE *f = NULL;
645         char *value = NULL;
646         int r;
647         bool done = false;
648         size_t l;
649         const char *path;
650
651         assert(pid >= 0);
652         assert(field);
653         assert(_value);
654
655         path = procfs_file_alloca(pid, "environ");
656
657         f = fopen(path, "re");
658         if (!f) {
659                 if (errno == ENOENT)
660                         return -ESRCH;
661                 return -errno;
662         }
663
664         l = strlen(field);
665         r = 0;
666
667         do {
668                 char line[LINE_MAX];
669                 unsigned i;
670
671                 for (i = 0; i < sizeof(line)-1; i++) {
672                         int c;
673
674                         c = getc(f);
675                         if (_unlikely_(c == EOF)) {
676                                 done = true;
677                                 break;
678                         } else if (c == 0)
679                                 break;
680
681                         line[i] = c;
682                 }
683                 line[i] = 0;
684
685                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
686                         value = strdup(line + l + 1);
687                         if (!value)
688                                 return -ENOMEM;
689
690                         r = 1;
691                         break;
692                 }
693
694         } while (!done);
695
696         *_value = value;
697         return r;
698 }
699
700 bool pid_is_unwaited(pid_t pid) {
701         /* Checks whether a PID is still valid at all, including a zombie */
702
703         if (pid < 0)
704                 return false;
705
706         if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
707                 return true;
708
709         if (kill(pid, 0) >= 0)
710                 return true;
711
712         return errno != ESRCH;
713 }
714
715 bool pid_is_alive(pid_t pid) {
716         int r;
717
718         /* Checks whether a PID is still valid and not a zombie */
719
720         if (pid < 0)
721                 return false;
722
723         if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
724                 return true;
725
726         r = get_process_state(pid);
727         if (r == -ESRCH || r == 'Z')
728                 return false;
729
730         return true;
731 }
732
733 #if 0 /// UNNEEDED by elogind
734 int pid_from_same_root_fs(pid_t pid) {
735         const char *root;
736
737         if (pid < 0)
738                 return 0;
739
740         root = procfs_file_alloca(pid, "root");
741
742         return files_same(root, "/proc/1/root");
743 }
744 #endif // 0
745
746 bool is_main_thread(void) {
747         static thread_local int cached = 0;
748
749         if (_unlikely_(cached == 0))
750                 cached = getpid() == gettid() ? 1 : -1;
751
752         return cached > 0;
753 }
754
755 #if 0 /// UNNEEDED by elogind
756 noreturn void freeze(void) {
757
758         log_close();
759
760         /* Make sure nobody waits for us on a socket anymore */
761         close_all_fds(NULL, 0);
762
763         sync();
764
765         for (;;)
766                 pause();
767 }
768
769 bool oom_score_adjust_is_valid(int oa) {
770         return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
771 }
772
773 unsigned long personality_from_string(const char *p) {
774         int architecture;
775
776         if (!p)
777                 return PERSONALITY_INVALID;
778
779         /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
780          * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
781          * the same register size. */
782
783         architecture = architecture_from_string(p);
784         if (architecture < 0)
785                 return PERSONALITY_INVALID;
786
787         if (architecture == native_architecture())
788                 return PER_LINUX;
789 #ifdef SECONDARY_ARCHITECTURE
790         if (architecture == SECONDARY_ARCHITECTURE)
791                 return PER_LINUX32;
792 #endif
793
794         return PERSONALITY_INVALID;
795 }
796
797 const char* personality_to_string(unsigned long p) {
798         int architecture = _ARCHITECTURE_INVALID;
799
800         if (p == PER_LINUX)
801                 architecture = native_architecture();
802 #ifdef SECONDARY_ARCHITECTURE
803         else if (p == PER_LINUX32)
804                 architecture = SECONDARY_ARCHITECTURE;
805 #endif
806
807         if (architecture < 0)
808                 return NULL;
809
810         return architecture_to_string(architecture);
811 }
812
813 void valgrind_summary_hack(void) {
814 #ifdef HAVE_VALGRIND_VALGRIND_H
815         if (getpid() == 1 && RUNNING_ON_VALGRIND) {
816                 pid_t pid;
817                 pid = raw_clone(SIGCHLD);
818                 if (pid < 0)
819                         log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
820                 else if (pid == 0)
821                         exit(EXIT_SUCCESS);
822                 else {
823                         log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
824                         (void) wait_for_terminate(pid, NULL);
825                 }
826         }
827 #endif
828 }
829
830 int pid_compare_func(const void *a, const void *b) {
831         const pid_t *p = a, *q = b;
832
833         /* Suitable for usage in qsort() */
834
835         if (*p < *q)
836                 return -1;
837         if (*p > *q)
838                 return 1;
839         return 0;
840 }
841
842 static const char *const ioprio_class_table[] = {
843         [IOPRIO_CLASS_NONE] = "none",
844         [IOPRIO_CLASS_RT] = "realtime",
845         [IOPRIO_CLASS_BE] = "best-effort",
846         [IOPRIO_CLASS_IDLE] = "idle"
847 };
848
849 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
850
851 static const char *const sigchld_code_table[] = {
852         [CLD_EXITED] = "exited",
853         [CLD_KILLED] = "killed",
854         [CLD_DUMPED] = "dumped",
855         [CLD_TRAPPED] = "trapped",
856         [CLD_STOPPED] = "stopped",
857         [CLD_CONTINUED] = "continued",
858 };
859
860 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
861
862 static const char* const sched_policy_table[] = {
863         [SCHED_OTHER] = "other",
864         [SCHED_BATCH] = "batch",
865         [SCHED_IDLE] = "idle",
866         [SCHED_FIFO] = "fifo",
867         [SCHED_RR] = "rr"
868 };
869
870 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
871 #endif // 0