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