chiark / gitweb /
Prep v221: Update and clean up build system to sync with upstream
[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 <stdbool.h>
21 #include <sys/types.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <assert.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <sys/wait.h>
28 #include <signal.h>
29 #include <ctype.h>
30
31 #include "fileio.h"
32 #include "util.h"
33 #include "log.h"
34 #include "signal-util.h"
35 #include "process-util.h"
36
37 int get_process_state(pid_t pid) {
38         const char *p;
39         char state;
40         int r;
41         _cleanup_free_ char *line = NULL;
42
43         assert(pid >= 0);
44
45         p = procfs_file_alloca(pid, "stat");
46         r = read_one_line_file(p, &line);
47         if (r < 0)
48                 return r;
49
50         p = strrchr(line, ')');
51         if (!p)
52                 return -EIO;
53
54         p++;
55
56         if (sscanf(p, " %c", &state) != 1)
57                 return -EIO;
58
59         return (unsigned char) state;
60 }
61
62 int get_process_comm(pid_t pid, char **name) {
63         const char *p;
64         int r;
65
66         assert(name);
67         assert(pid >= 0);
68
69         p = procfs_file_alloca(pid, "comm");
70
71         r = read_one_line_file(p, name);
72         if (r == -ENOENT)
73                 return -ESRCH;
74
75         return r;
76 }
77
78 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
79         _cleanup_fclose_ FILE *f = NULL;
80         char *r = NULL, *k;
81         const char *p;
82         int c;
83
84         assert(line);
85         assert(pid >= 0);
86
87         p = procfs_file_alloca(pid, "cmdline");
88
89         f = fopen(p, "re");
90         if (!f)
91                 return -errno;
92
93         if (max_length == 0) {
94                 size_t len = 0, allocated = 0;
95
96                 while ((c = getc(f)) != EOF) {
97
98                         if (!GREEDY_REALLOC(r, allocated, len+2)) {
99                                 free(r);
100                                 return -ENOMEM;
101                         }
102
103                         r[len++] = isprint(c) ? c : ' ';
104                 }
105
106                 if (len > 0)
107                         r[len-1] = 0;
108
109         } else {
110                 bool space = false;
111                 size_t left;
112
113                 r = new(char, max_length);
114                 if (!r)
115                         return -ENOMEM;
116
117                 k = r;
118                 left = max_length;
119                 while ((c = getc(f)) != EOF) {
120
121                         if (isprint(c)) {
122                                 if (space) {
123                                         if (left <= 4)
124                                                 break;
125
126                                         *(k++) = ' ';
127                                         left--;
128                                         space = false;
129                                 }
130
131                                 if (left <= 4)
132                                         break;
133
134                                 *(k++) = (char) c;
135                                 left--;
136                         }  else
137                                 space = true;
138                 }
139
140                 if (left <= 4) {
141                         size_t n = MIN(left-1, 3U);
142                         memcpy(k, "...", n);
143                         k[n] = 0;
144                 } else
145                         *k = 0;
146         }
147
148         /* Kernel threads have no argv[] */
149         if (isempty(r)) {
150                 _cleanup_free_ char *t = NULL;
151                 int h;
152
153                 free(r);
154
155                 if (!comm_fallback)
156                         return -ENOENT;
157
158                 h = get_process_comm(pid, &t);
159                 if (h < 0)
160                         return h;
161
162                 r = strjoin("[", t, "]", NULL);
163                 if (!r)
164                         return -ENOMEM;
165         }
166
167         *line = r;
168         return 0;
169 }
170
171 int is_kernel_thread(pid_t pid) {
172         const char *p;
173         size_t count;
174         char c;
175         bool eof;
176         FILE *f;
177
178         if (pid == 0)
179                 return 0;
180
181         assert(pid > 0);
182
183         p = procfs_file_alloca(pid, "cmdline");
184         f = fopen(p, "re");
185         if (!f)
186                 return -errno;
187
188         count = fread(&c, 1, 1, f);
189         eof = feof(f);
190         fclose(f);
191
192         /* Kernel threads have an empty cmdline */
193
194         if (count <= 0)
195                 return eof ? 1 : -errno;
196
197         return 0;
198 }
199
200 /// UNNEEDED by elogind
201 #if 0
202 int get_process_capeff(pid_t pid, char **capeff) {
203         const char *p;
204
205         assert(capeff);
206         assert(pid >= 0);
207
208         p = procfs_file_alloca(pid, "status");
209
210         return get_status_field(p, "\nCapEff:", capeff);
211 }
212 #endif // 0
213
214 static int get_process_link_contents(const char *proc_file, char **name) {
215         int r;
216
217         assert(proc_file);
218         assert(name);
219
220         r = readlink_malloc(proc_file, name);
221         if (r < 0)
222                 return r == -ENOENT ? -ESRCH : r;
223
224         return 0;
225 }
226
227 int get_process_exe(pid_t pid, char **name) {
228         const char *p;
229         char *d;
230         int r;
231
232         assert(pid >= 0);
233
234         p = procfs_file_alloca(pid, "exe");
235         r = get_process_link_contents(p, name);
236         if (r < 0)
237                 return r;
238
239         d = endswith(*name, " (deleted)");
240         if (d)
241                 *d = '\0';
242
243         return 0;
244 }
245
246 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
247         _cleanup_fclose_ FILE *f = NULL;
248         char line[LINE_MAX];
249         const char *p;
250
251         assert(field);
252         assert(uid);
253
254         if (pid == 0)
255                 return getuid();
256
257         p = procfs_file_alloca(pid, "status");
258         f = fopen(p, "re");
259         if (!f)
260                 return -errno;
261
262         FOREACH_LINE(line, f, return -errno) {
263                 char *l;
264
265                 l = strstrip(line);
266
267                 if (startswith(l, field)) {
268                         l += strlen(field);
269                         l += strspn(l, WHITESPACE);
270
271                         l[strcspn(l, WHITESPACE)] = 0;
272
273                         return parse_uid(l, uid);
274                 }
275         }
276
277         return -EIO;
278 }
279
280 int get_process_uid(pid_t pid, uid_t *uid) {
281         return get_process_id(pid, "Uid:", uid);
282 }
283
284 /// UNNEEDED by elogind
285 #if 0
286 int get_process_gid(pid_t pid, gid_t *gid) {
287         assert_cc(sizeof(uid_t) == sizeof(gid_t));
288         return get_process_id(pid, "Gid:", gid);
289 }
290
291 int get_process_cwd(pid_t pid, char **cwd) {
292         const char *p;
293
294         assert(pid >= 0);
295
296         p = procfs_file_alloca(pid, "cwd");
297
298         return get_process_link_contents(p, cwd);
299 }
300
301 int get_process_root(pid_t pid, char **root) {
302         const char *p;
303
304         assert(pid >= 0);
305
306         p = procfs_file_alloca(pid, "root");
307
308         return get_process_link_contents(p, root);
309 }
310
311 int get_process_environ(pid_t pid, char **env) {
312         _cleanup_fclose_ FILE *f = NULL;
313         _cleanup_free_ char *outcome = NULL;
314         int c;
315         const char *p;
316         size_t allocated = 0, sz = 0;
317
318         assert(pid >= 0);
319         assert(env);
320
321         p = procfs_file_alloca(pid, "environ");
322
323         f = fopen(p, "re");
324         if (!f)
325                 return -errno;
326
327         while ((c = fgetc(f)) != EOF) {
328                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
329                         return -ENOMEM;
330
331                 if (c == '\0')
332                         outcome[sz++] = '\n';
333                 else
334                         sz += cescape_char(c, outcome + sz);
335         }
336
337         outcome[sz] = '\0';
338         *env = outcome;
339         outcome = NULL;
340
341         return 0;
342 }
343 #endif // 0
344
345 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
346         int r;
347         _cleanup_free_ char *line = NULL;
348         long unsigned ppid;
349         const char *p;
350
351         assert(pid >= 0);
352         assert(_ppid);
353
354         if (pid == 0) {
355                 *_ppid = getppid();
356                 return 0;
357         }
358
359         p = procfs_file_alloca(pid, "stat");
360         r = read_one_line_file(p, &line);
361         if (r < 0)
362                 return r;
363
364         /* Let's skip the pid and comm fields. The latter is enclosed
365          * in () but does not escape any () in its value, so let's
366          * skip over it manually */
367
368         p = strrchr(line, ')');
369         if (!p)
370                 return -EIO;
371
372         p++;
373
374         if (sscanf(p, " "
375                    "%*c "  /* state */
376                    "%lu ", /* ppid */
377                    &ppid) != 1)
378                 return -EIO;
379
380         if ((long unsigned) (pid_t) ppid != ppid)
381                 return -ERANGE;
382
383         *_ppid = (pid_t) ppid;
384
385         return 0;
386 }
387
388 int wait_for_terminate(pid_t pid, siginfo_t *status) {
389         siginfo_t dummy;
390
391         assert(pid >= 1);
392
393         if (!status)
394                 status = &dummy;
395
396         for (;;) {
397                 zero(*status);
398
399                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
400
401                         if (errno == EINTR)
402                                 continue;
403
404                         return -errno;
405                 }
406
407                 return 0;
408         }
409 }
410
411 /*
412  * Return values:
413  * < 0 : wait_for_terminate() failed to get the state of the
414  *       process, the process was terminated by a signal, or
415  *       failed for an unknown reason.
416  * >=0 : The process terminated normally, and its exit code is
417  *       returned.
418  *
419  * That is, success is indicated by a return value of zero, and an
420  * error is indicated by a non-zero value.
421  *
422  * A warning is emitted if the process terminates abnormally,
423  * and also if it returns non-zero unless check_exit_code is true.
424  */
425 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
426         int r;
427         siginfo_t status;
428
429         assert(name);
430         assert(pid > 1);
431
432         r = wait_for_terminate(pid, &status);
433         if (r < 0)
434                 return log_warning_errno(r, "Failed to wait for %s: %m", name);
435
436         if (status.si_code == CLD_EXITED) {
437                 if (status.si_status != 0)
438                         log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
439                                  "%s failed with error code %i.", name, status.si_status);
440                 else
441                         log_debug("%s succeeded.", name);
442
443                 return status.si_status;
444         } else if (status.si_code == CLD_KILLED ||
445                    status.si_code == CLD_DUMPED) {
446
447                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
448                 return -EPROTO;
449         }
450
451         log_warning("%s failed due to unknown reason.", name);
452         return -EPROTO;
453 }
454
455 int kill_and_sigcont(pid_t pid, int sig) {
456         int r;
457
458         r = kill(pid, sig) < 0 ? -errno : 0;
459
460         if (r >= 0)
461                 kill(pid, SIGCONT);
462
463         return r;
464 }
465
466 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
467         _cleanup_fclose_ FILE *f = NULL;
468         char *value = NULL;
469         int r;
470         bool done = false;
471         size_t l;
472         const char *path;
473
474         assert(pid >= 0);
475         assert(field);
476         assert(_value);
477
478         path = procfs_file_alloca(pid, "environ");
479
480         f = fopen(path, "re");
481         if (!f)
482                 return -errno;
483
484         l = strlen(field);
485         r = 0;
486
487         do {
488                 char line[LINE_MAX];
489                 unsigned i;
490
491                 for (i = 0; i < sizeof(line)-1; i++) {
492                         int c;
493
494                         c = getc(f);
495                         if (_unlikely_(c == EOF)) {
496                                 done = true;
497                                 break;
498                         } else if (c == 0)
499                                 break;
500
501                         line[i] = c;
502                 }
503                 line[i] = 0;
504
505                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
506                         value = strdup(line + l + 1);
507                         if (!value)
508                                 return -ENOMEM;
509
510                         r = 1;
511                         break;
512                 }
513
514         } while (!done);
515
516         *_value = value;
517         return r;
518 }
519
520 bool pid_is_unwaited(pid_t pid) {
521         /* Checks whether a PID is still valid at all, including a zombie */
522
523         if (pid <= 0)
524                 return false;
525
526         if (kill(pid, 0) >= 0)
527                 return true;
528
529         return errno != ESRCH;
530 }
531
532 bool pid_is_alive(pid_t pid) {
533         int r;
534
535         /* Checks whether a PID is still valid and not a zombie */
536
537         if (pid <= 0)
538                 return false;
539
540         r = get_process_state(pid);
541         if (r == -ENOENT || r == 'Z')
542                 return false;
543
544         return true;
545 }