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