chiark / gitweb /
Prep v220: Apply "Fixes to user and session saving"
[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 "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 int get_process_capeff(pid_t pid, char **capeff) {
201         const char *p;
202
203         assert(capeff);
204         assert(pid >= 0);
205
206         p = procfs_file_alloca(pid, "status");
207
208         return get_status_field(p, "\nCapEff:", capeff);
209 }
210
211 static int get_process_link_contents(const char *proc_file, char **name) {
212         int r;
213
214         assert(proc_file);
215         assert(name);
216
217         r = readlink_malloc(proc_file, name);
218         if (r < 0)
219                 return r == -ENOENT ? -ESRCH : r;
220
221         return 0;
222 }
223
224 int get_process_exe(pid_t pid, char **name) {
225         const char *p;
226         char *d;
227         int r;
228
229         assert(pid >= 0);
230
231         p = procfs_file_alloca(pid, "exe");
232         r = get_process_link_contents(p, name);
233         if (r < 0)
234                 return r;
235
236         d = endswith(*name, " (deleted)");
237         if (d)
238                 *d = '\0';
239
240         return 0;
241 }
242
243 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
244         _cleanup_fclose_ FILE *f = NULL;
245         char line[LINE_MAX];
246         const char *p;
247
248         assert(field);
249         assert(uid);
250
251         if (pid == 0)
252                 return getuid();
253
254         p = procfs_file_alloca(pid, "status");
255         f = fopen(p, "re");
256         if (!f)
257                 return -errno;
258
259         FOREACH_LINE(line, f, return -errno) {
260                 char *l;
261
262                 l = strstrip(line);
263
264                 if (startswith(l, field)) {
265                         l += strlen(field);
266                         l += strspn(l, WHITESPACE);
267
268                         l[strcspn(l, WHITESPACE)] = 0;
269
270                         return parse_uid(l, uid);
271                 }
272         }
273
274         return -EIO;
275 }
276
277 int get_process_uid(pid_t pid, uid_t *uid) {
278         return get_process_id(pid, "Uid:", uid);
279 }
280
281 int get_process_gid(pid_t pid, gid_t *gid) {
282         assert_cc(sizeof(uid_t) == sizeof(gid_t));
283         return get_process_id(pid, "Gid:", gid);
284 }
285
286 int get_process_cwd(pid_t pid, char **cwd) {
287         const char *p;
288
289         assert(pid >= 0);
290
291         p = procfs_file_alloca(pid, "cwd");
292
293         return get_process_link_contents(p, cwd);
294 }
295
296 int get_process_root(pid_t pid, char **root) {
297         const char *p;
298
299         assert(pid >= 0);
300
301         p = procfs_file_alloca(pid, "root");
302
303         return get_process_link_contents(p, root);
304 }
305
306 int get_process_environ(pid_t pid, char **env) {
307         _cleanup_fclose_ FILE *f = NULL;
308         _cleanup_free_ char *outcome = NULL;
309         int c;
310         const char *p;
311         size_t allocated = 0, sz = 0;
312
313         assert(pid >= 0);
314         assert(env);
315
316         p = procfs_file_alloca(pid, "environ");
317
318         f = fopen(p, "re");
319         if (!f)
320                 return -errno;
321
322         while ((c = fgetc(f)) != EOF) {
323                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
324                         return -ENOMEM;
325
326                 if (c == '\0')
327                         outcome[sz++] = '\n';
328                 else
329                         sz += cescape_char(c, outcome + sz);
330         }
331
332         outcome[sz] = '\0';
333         *env = outcome;
334         outcome = NULL;
335
336         return 0;
337 }
338
339 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
340         int r;
341         _cleanup_free_ char *line = NULL;
342         long unsigned ppid;
343         const char *p;
344
345         assert(pid >= 0);
346         assert(_ppid);
347
348         if (pid == 0) {
349                 *_ppid = getppid();
350                 return 0;
351         }
352
353         p = procfs_file_alloca(pid, "stat");
354         r = read_one_line_file(p, &line);
355         if (r < 0)
356                 return r;
357
358         /* Let's skip the pid and comm fields. The latter is enclosed
359          * in () but does not escape any () in its value, so let's
360          * skip over it manually */
361
362         p = strrchr(line, ')');
363         if (!p)
364                 return -EIO;
365
366         p++;
367
368         if (sscanf(p, " "
369                    "%*c "  /* state */
370                    "%lu ", /* ppid */
371                    &ppid) != 1)
372                 return -EIO;
373
374         if ((long unsigned) (pid_t) ppid != ppid)
375                 return -ERANGE;
376
377         *_ppid = (pid_t) ppid;
378
379         return 0;
380 }
381
382 int wait_for_terminate(pid_t pid, siginfo_t *status) {
383         siginfo_t dummy;
384
385         assert(pid >= 1);
386
387         if (!status)
388                 status = &dummy;
389
390         for (;;) {
391                 zero(*status);
392
393                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
394
395                         if (errno == EINTR)
396                                 continue;
397
398                         return -errno;
399                 }
400
401                 return 0;
402         }
403 }
404
405 /*
406  * Return values:
407  * < 0 : wait_for_terminate() failed to get the state of the
408  *       process, the process was terminated by a signal, or
409  *       failed for an unknown reason.
410  * >=0 : The process terminated normally, and its exit code is
411  *       returned.
412  *
413  * That is, success is indicated by a return value of zero, and an
414  * error is indicated by a non-zero value.
415  *
416  * A warning is emitted if the process terminates abnormally,
417  * and also if it returns non-zero unless check_exit_code is true.
418  */
419 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
420         int r;
421         siginfo_t status;
422
423         assert(name);
424         assert(pid > 1);
425
426         r = wait_for_terminate(pid, &status);
427         if (r < 0)
428                 return log_warning_errno(r, "Failed to wait for %s: %m", name);
429
430         if (status.si_code == CLD_EXITED) {
431                 if (status.si_status != 0)
432                         log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
433                                  "%s failed with error code %i.", name, status.si_status);
434                 else
435                         log_debug("%s succeeded.", name);
436
437                 return status.si_status;
438         } else if (status.si_code == CLD_KILLED ||
439                    status.si_code == CLD_DUMPED) {
440
441                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
442                 return -EPROTO;
443         }
444
445         log_warning("%s failed due to unknown reason.", name);
446         return -EPROTO;
447 }
448
449 int kill_and_sigcont(pid_t pid, int sig) {
450         int r;
451
452         r = kill(pid, sig) < 0 ? -errno : 0;
453
454         if (r >= 0)
455                 kill(pid, SIGCONT);
456
457         return r;
458 }
459
460 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
461         _cleanup_fclose_ FILE *f = NULL;
462         char *value = NULL;
463         int r;
464         bool done = false;
465         size_t l;
466         const char *path;
467
468         assert(pid >= 0);
469         assert(field);
470         assert(_value);
471
472         path = procfs_file_alloca(pid, "environ");
473
474         f = fopen(path, "re");
475         if (!f)
476                 return -errno;
477
478         l = strlen(field);
479         r = 0;
480
481         do {
482                 char line[LINE_MAX];
483                 unsigned i;
484
485                 for (i = 0; i < sizeof(line)-1; i++) {
486                         int c;
487
488                         c = getc(f);
489                         if (_unlikely_(c == EOF)) {
490                                 done = true;
491                                 break;
492                         } else if (c == 0)
493                                 break;
494
495                         line[i] = c;
496                 }
497                 line[i] = 0;
498
499                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
500                         value = strdup(line + l + 1);
501                         if (!value)
502                                 return -ENOMEM;
503
504                         r = 1;
505                         break;
506                 }
507
508         } while (!done);
509
510         *_value = value;
511         return r;
512 }
513
514 bool pid_is_unwaited(pid_t pid) {
515         /* Checks whether a PID is still valid at all, including a zombie */
516
517         if (pid <= 0)
518                 return false;
519
520         if (kill(pid, 0) >= 0)
521                 return true;
522
523         return errno != ESRCH;
524 }
525
526 bool pid_is_alive(pid_t pid) {
527         int r;
528
529         /* Checks whether a PID is still valid and not a zombie */
530
531         if (pid <= 0)
532                 return false;
533
534         r = get_process_state(pid);
535         if (r == -ENOENT || r == 'Z')
536                 return false;
537
538         return true;
539 }