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