]>
Commit | Line | Data |
---|---|---|
53e1b683 | 1 | /* SPDX-License-Identifier: LGPL-2.1+ */ |
0b452006 | 2 | |
4f5dd394 | 3 | #include <ctype.h> |
0b452006 | 4 | #include <errno.h> |
11c3a366 TA |
5 | #include <limits.h> |
6 | #include <linux/oom.h> | |
7b3e062c | 7 | #include <sched.h> |
0b452006 | 8 | #include <signal.h> |
4f5dd394 LP |
9 | #include <stdbool.h> |
10 | #include <stdio.h> | |
11c3a366 | 11 | #include <stdlib.h> |
4f5dd394 | 12 | #include <string.h> |
9bfaffd5 | 13 | #include <sys/mman.h> |
e2047ba9 | 14 | #include <sys/mount.h> |
7b3e062c | 15 | #include <sys/personality.h> |
405f8907 | 16 | #include <sys/prctl.h> |
4f5dd394 LP |
17 | #include <sys/types.h> |
18 | #include <sys/wait.h> | |
11c3a366 | 19 | #include <syslog.h> |
4f5dd394 | 20 | #include <unistd.h> |
349cc4a5 | 21 | #if HAVE_VALGRIND_VALGRIND_H |
dcadc967 EV |
22 | #include <valgrind/valgrind.h> |
23 | #endif | |
0b452006 | 24 | |
b5efdb8a | 25 | #include "alloc-util.h" |
6e5f1b57 | 26 | #include "architecture.h" |
4f5dd394 | 27 | #include "escape.h" |
21c491e1 | 28 | #include "env-util.h" |
3ffd4af2 | 29 | #include "fd-util.h" |
0b452006 | 30 | #include "fileio.h" |
f4f15635 | 31 | #include "fs-util.h" |
7b3e062c | 32 | #include "ioprio.h" |
0b452006 | 33 | #include "log.h" |
11c3a366 | 34 | #include "macro.h" |
0a970718 | 35 | #include "memory-util.h" |
11c3a366 | 36 | #include "missing.h" |
0cb8e3d1 | 37 | #include "namespace-util.h" |
93cc7779 | 38 | #include "process-util.h" |
8869a0b4 | 39 | #include "raw-clone.h" |
909106eb | 40 | #include "rlimit-util.h" |
93cc7779 | 41 | #include "signal-util.h" |
1359fffa | 42 | #include "stat-util.h" |
7b3e062c | 43 | #include "string-table.h" |
07630cea | 44 | #include "string-util.h" |
4c253ed1 | 45 | #include "terminal-util.h" |
b1d4f8e1 | 46 | #include "user-util.h" |
bc28751e | 47 | #include "utf8.h" |
0b452006 | 48 | |
0e85cbcf ZJS |
49 | /* The kernel limits userspace processes to TASK_COMM_LEN (16 bytes), but allows higher values for its own |
50 | * workers, e.g. "kworker/u9:3-kcryptd/253:0". Let's pick a fixed smallish limit that will work for the kernel. | |
51 | */ | |
52 | #define COMM_MAX_LEN 128 | |
53 | ||
0a51b45c | 54 | static int get_process_state(pid_t pid) { |
0b452006 RC |
55 | const char *p; |
56 | char state; | |
57 | int r; | |
58 | _cleanup_free_ char *line = NULL; | |
59 | ||
60 | assert(pid >= 0); | |
61 | ||
62 | p = procfs_file_alloca(pid, "stat"); | |
a644184a | 63 | |
0b452006 | 64 | r = read_one_line_file(p, &line); |
a644184a LP |
65 | if (r == -ENOENT) |
66 | return -ESRCH; | |
0b452006 RC |
67 | if (r < 0) |
68 | return r; | |
69 | ||
70 | p = strrchr(line, ')'); | |
71 | if (!p) | |
72 | return -EIO; | |
73 | ||
74 | p++; | |
75 | ||
76 | if (sscanf(p, " %c", &state) != 1) | |
77 | return -EIO; | |
78 | ||
79 | return (unsigned char) state; | |
80 | } | |
81 | ||
ce268825 LP |
82 | int get_process_comm(pid_t pid, char **ret) { |
83 | _cleanup_free_ char *escaped = NULL, *comm = NULL; | |
0b452006 RC |
84 | const char *p; |
85 | int r; | |
86 | ||
ce268825 | 87 | assert(ret); |
0b452006 RC |
88 | assert(pid >= 0); |
89 | ||
0e85cbcf | 90 | escaped = new(char, COMM_MAX_LEN); |
ce268825 LP |
91 | if (!escaped) |
92 | return -ENOMEM; | |
93 | ||
0b452006 RC |
94 | p = procfs_file_alloca(pid, "comm"); |
95 | ||
ce268825 | 96 | r = read_one_line_file(p, &comm); |
0b452006 RC |
97 | if (r == -ENOENT) |
98 | return -ESRCH; | |
ce268825 LP |
99 | if (r < 0) |
100 | return r; | |
101 | ||
102 | /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */ | |
0e85cbcf | 103 | cellescape(escaped, COMM_MAX_LEN, comm); |
0b452006 | 104 | |
ce268825 LP |
105 | *ret = TAKE_PTR(escaped); |
106 | return 0; | |
0b452006 RC |
107 | } |
108 | ||
bc28751e | 109 | int get_process_cmdline(pid_t pid, size_t max_columns, bool comm_fallback, char **line) { |
0b452006 | 110 | _cleanup_fclose_ FILE *f = NULL; |
bc28751e | 111 | _cleanup_free_ char *t = NULL, *ans = NULL; |
0b452006 | 112 | const char *p; |
bc28751e ZJS |
113 | int r; |
114 | size_t k; | |
115 | ||
116 | /* This is supposed to be a safety guard against runaway command lines. */ | |
117 | size_t max_length = sc_arg_max(); | |
0b452006 RC |
118 | |
119 | assert(line); | |
120 | assert(pid >= 0); | |
121 | ||
bc28751e ZJS |
122 | /* Retrieves a process' command line. Replaces non-utf8 bytes by replacement character (�). If |
123 | * max_columns is != -1 will return a string of the specified console width at most, abbreviated with | |
124 | * an ellipsis. If comm_fallback is true and the process has no command line set (the case for kernel | |
125 | * threads), or has a command line that resolves to the empty string will return the "comm" name of | |
126 | * the process instead. This will use at most _SC_ARG_MAX bytes of input data. | |
69281c49 LP |
127 | * |
128 | * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and | |
c0534780 | 129 | * comm_fallback is false). Returns 0 and sets *line otherwise. */ |
69281c49 | 130 | |
0b452006 | 131 | p = procfs_file_alloca(pid, "cmdline"); |
fdeea3f4 ZJS |
132 | r = fopen_unlocked(p, "re", &f); |
133 | if (r == -ENOENT) | |
134 | return -ESRCH; | |
135 | if (r < 0) | |
136 | return r; | |
35bbbf85 | 137 | |
bc28751e ZJS |
138 | /* We assume that each four-byte character uses one or two columns. If we ever check for combining |
139 | * characters, this assumption will need to be adjusted. */ | |
140 | if ((size_t) 4 * max_columns + 1 < max_columns) | |
141 | max_length = MIN(max_length, (size_t) 4 * max_columns + 1); | |
69281c49 | 142 | |
bc28751e ZJS |
143 | t = new(char, max_length); |
144 | if (!t) | |
145 | return -ENOMEM; | |
69281c49 | 146 | |
bc28751e ZJS |
147 | k = fread(t, 1, max_length, f); |
148 | if (k > 0) { | |
149 | /* Arguments are separated by NULs. Let's replace those with spaces. */ | |
150 | for (size_t i = 0; i < k - 1; i++) | |
151 | if (t[i] == '\0') | |
152 | t[i] = ' '; | |
69281c49 | 153 | |
bc28751e | 154 | t[k] = '\0'; /* Normally, t[k] is already NUL, so this is just a guard in case of short read */ |
0b452006 | 155 | } else { |
bc28751e ZJS |
156 | /* We only treat getting nothing as an error. We *could* also get an error after reading some |
157 | * data, but we ignore that case, as such an error is rather unlikely and we prefer to get | |
158 | * some data rather than none. */ | |
159 | if (ferror(f)) | |
160 | return -errno; | |
0b452006 RC |
161 | |
162 | if (!comm_fallback) | |
163 | return -ENOENT; | |
164 | ||
bc28751e ZJS |
165 | /* Kernel threads have no argv[] */ |
166 | _cleanup_free_ char *t2 = NULL; | |
69281c49 | 167 | |
bc28751e ZJS |
168 | r = get_process_comm(pid, &t2); |
169 | if (r < 0) | |
170 | return r; | |
69281c49 | 171 | |
bc28751e ZJS |
172 | mfree(t); |
173 | t = strjoin("[", t2, "]"); | |
174 | if (!t) | |
175 | return -ENOMEM; | |
0b452006 RC |
176 | } |
177 | ||
bc28751e | 178 | delete_trailing_chars(t, WHITESPACE); |
eb1ec489 | 179 | |
bc28751e ZJS |
180 | ans = utf8_escape_non_printable_full(t, max_columns); |
181 | if (!ans) | |
182 | return -ENOMEM; | |
eb1ec489 | 183 | |
bc28751e ZJS |
184 | (void) str_realloc(&ans); |
185 | *line = TAKE_PTR(ans); | |
0b452006 RC |
186 | return 0; |
187 | } | |
188 | ||
9bfaffd5 LP |
189 | int rename_process(const char name[]) { |
190 | static size_t mm_size = 0; | |
191 | static char *mm = NULL; | |
192 | bool truncated = false; | |
193 | size_t l; | |
194 | ||
195 | /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's | |
196 | * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in | |
197 | * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded; | |
198 | * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be | |
199 | * truncated. | |
200 | * | |
201 | * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */ | |
202 | ||
203 | if (isempty(name)) | |
204 | return -EINVAL; /* let's not confuse users unnecessarily with an empty name */ | |
405f8907 | 205 | |
1096bb8a LP |
206 | if (!is_main_thread()) |
207 | return -EPERM; /* Let's not allow setting the process name from other threads than the main one, as we | |
208 | * cache things without locking, and we make assumptions that PR_SET_NAME sets the | |
209 | * process name that isn't correct on any other threads */ | |
210 | ||
9bfaffd5 | 211 | l = strlen(name); |
405f8907 | 212 | |
5a8af747 LP |
213 | /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we |
214 | * can use PR_SET_NAME, which sets the thread name for the calling thread. */ | |
215 | if (prctl(PR_SET_NAME, name) < 0) | |
216 | log_debug_errno(errno, "PR_SET_NAME failed: %m"); | |
0e85cbcf | 217 | if (l >= TASK_COMM_LEN) /* Linux userspace process names can be 15 chars at max */ |
9bfaffd5 LP |
218 | truncated = true; |
219 | ||
220 | /* Second step, change glibc's ID of the process name. */ | |
221 | if (program_invocation_name) { | |
222 | size_t k; | |
223 | ||
224 | k = strlen(program_invocation_name); | |
225 | strncpy(program_invocation_name, name, k); | |
226 | if (l > k) | |
227 | truncated = true; | |
228 | } | |
229 | ||
230 | /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but | |
231 | * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at | |
13e785f7 | 232 | * the end. This is the best option for changing /proc/self/cmdline. */ |
01f989c6 JW |
233 | |
234 | /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the | |
235 | * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is | |
236 | * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if | |
237 | * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but | |
238 | * mmap() is not. */ | |
239 | if (geteuid() != 0) | |
240 | log_debug("Skipping PR_SET_MM, as we don't have privileges."); | |
241 | else if (mm_size < l+1) { | |
9bfaffd5 LP |
242 | size_t nn_size; |
243 | char *nn; | |
244 | ||
9bfaffd5 LP |
245 | nn_size = PAGE_ALIGN(l+1); |
246 | nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); | |
247 | if (nn == MAP_FAILED) { | |
248 | log_debug_errno(errno, "mmap() failed: %m"); | |
249 | goto use_saved_argv; | |
250 | } | |
405f8907 | 251 | |
9bfaffd5 LP |
252 | strncpy(nn, name, nn_size); |
253 | ||
254 | /* Now, let's tell the kernel about this new memory */ | |
255 | if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) { | |
14ee72b7 FS |
256 | /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be |
257 | * below the desired start address, in which case the kernel may have kicked this back due | |
258 | * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in | |
259 | * action). The proper solution would be to have a prctl() API that could set both start+end | |
260 | * simultaneously, or at least let us query the existing address to anticipate this condition | |
261 | * and respond accordingly. For now, we can only guess at the cause of this failure and try | |
262 | * a workaround--which will briefly expand the arg space to something potentially huge before | |
263 | * resizing it to what we want. */ | |
264 | log_debug_errno(errno, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m"); | |
265 | ||
266 | if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) { | |
267 | log_debug_errno(errno, "PR_SET_MM_ARG_END hack failed, proceeding without: %m"); | |
268 | (void) munmap(nn, nn_size); | |
269 | goto use_saved_argv; | |
270 | } | |
9bfaffd5 | 271 | |
14ee72b7 FS |
272 | if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) { |
273 | log_debug_errno(errno, "PR_SET_MM_ARG_START still failed, proceeding without: %m"); | |
274 | goto use_saved_argv; | |
275 | } | |
276 | } else { | |
277 | /* And update the end pointer to the new end, too. If this fails, we don't really know what | |
278 | * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure, | |
279 | * and continue. */ | |
280 | if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) | |
281 | log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m"); | |
282 | } | |
9bfaffd5 LP |
283 | |
284 | if (mm) | |
285 | (void) munmap(mm, mm_size); | |
286 | ||
287 | mm = nn; | |
288 | mm_size = nn_size; | |
01f989c6 | 289 | } else { |
9bfaffd5 LP |
290 | strncpy(mm, name, mm_size); |
291 | ||
01f989c6 JW |
292 | /* Update the end pointer, continuing regardless of any failure. */ |
293 | if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0) | |
294 | log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m"); | |
295 | } | |
296 | ||
9bfaffd5 LP |
297 | use_saved_argv: |
298 | /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if | |
299 | * it still looks here */ | |
405f8907 LP |
300 | |
301 | if (saved_argc > 0) { | |
302 | int i; | |
303 | ||
9bfaffd5 LP |
304 | if (saved_argv[0]) { |
305 | size_t k; | |
306 | ||
307 | k = strlen(saved_argv[0]); | |
308 | strncpy(saved_argv[0], name, k); | |
309 | if (l > k) | |
310 | truncated = true; | |
311 | } | |
405f8907 LP |
312 | |
313 | for (i = 1; i < saved_argc; i++) { | |
314 | if (!saved_argv[i]) | |
315 | break; | |
316 | ||
317 | memzero(saved_argv[i], strlen(saved_argv[i])); | |
318 | } | |
319 | } | |
9bfaffd5 LP |
320 | |
321 | return !truncated; | |
405f8907 LP |
322 | } |
323 | ||
0b452006 | 324 | int is_kernel_thread(pid_t pid) { |
36b5119a LP |
325 | _cleanup_free_ char *line = NULL; |
326 | unsigned long long flags; | |
327 | size_t l, i; | |
0b452006 | 328 | const char *p; |
36b5119a LP |
329 | char *q; |
330 | int r; | |
0b452006 | 331 | |
4c701096 | 332 | if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */ |
0b452006 | 333 | return 0; |
36b5119a LP |
334 | if (!pid_is_valid(pid)) |
335 | return -EINVAL; | |
0b452006 | 336 | |
36b5119a LP |
337 | p = procfs_file_alloca(pid, "stat"); |
338 | r = read_one_line_file(p, &line); | |
339 | if (r == -ENOENT) | |
340 | return -ESRCH; | |
341 | if (r < 0) | |
342 | return r; | |
0b452006 | 343 | |
36b5119a LP |
344 | /* Skip past the comm field */ |
345 | q = strrchr(line, ')'); | |
346 | if (!q) | |
347 | return -EINVAL; | |
348 | q++; | |
349 | ||
350 | /* Skip 6 fields to reach the flags field */ | |
351 | for (i = 0; i < 6; i++) { | |
352 | l = strspn(q, WHITESPACE); | |
353 | if (l < 1) | |
354 | return -EINVAL; | |
355 | q += l; | |
356 | ||
357 | l = strcspn(q, WHITESPACE); | |
358 | if (l < 1) | |
359 | return -EINVAL; | |
360 | q += l; | |
a644184a | 361 | } |
0b452006 | 362 | |
f21f31b2 | 363 | /* Skip preceding whitespace */ |
36b5119a LP |
364 | l = strspn(q, WHITESPACE); |
365 | if (l < 1) | |
366 | return -EINVAL; | |
367 | q += l; | |
35bbbf85 | 368 | |
36b5119a LP |
369 | /* Truncate the rest */ |
370 | l = strcspn(q, WHITESPACE); | |
371 | if (l < 1) | |
372 | return -EINVAL; | |
373 | q[l] = 0; | |
0b452006 | 374 | |
36b5119a LP |
375 | r = safe_atollu(q, &flags); |
376 | if (r < 0) | |
377 | return r; | |
0b452006 | 378 | |
36b5119a | 379 | return !!(flags & PF_KTHREAD); |
0b452006 RC |
380 | } |
381 | ||
382 | int get_process_capeff(pid_t pid, char **capeff) { | |
383 | const char *p; | |
a644184a | 384 | int r; |
0b452006 RC |
385 | |
386 | assert(capeff); | |
387 | assert(pid >= 0); | |
388 | ||
389 | p = procfs_file_alloca(pid, "status"); | |
390 | ||
c4cd1d4d | 391 | r = get_proc_field(p, "CapEff", WHITESPACE, capeff); |
a644184a LP |
392 | if (r == -ENOENT) |
393 | return -ESRCH; | |
394 | ||
395 | return r; | |
0b452006 RC |
396 | } |
397 | ||
398 | static int get_process_link_contents(const char *proc_file, char **name) { | |
399 | int r; | |
400 | ||
401 | assert(proc_file); | |
402 | assert(name); | |
403 | ||
404 | r = readlink_malloc(proc_file, name); | |
a644184a LP |
405 | if (r == -ENOENT) |
406 | return -ESRCH; | |
0b452006 | 407 | if (r < 0) |
a644184a | 408 | return r; |
0b452006 RC |
409 | |
410 | return 0; | |
411 | } | |
412 | ||
413 | int get_process_exe(pid_t pid, char **name) { | |
414 | const char *p; | |
415 | char *d; | |
416 | int r; | |
417 | ||
418 | assert(pid >= 0); | |
419 | ||
420 | p = procfs_file_alloca(pid, "exe"); | |
421 | r = get_process_link_contents(p, name); | |
422 | if (r < 0) | |
423 | return r; | |
424 | ||
425 | d = endswith(*name, " (deleted)"); | |
426 | if (d) | |
427 | *d = '\0'; | |
428 | ||
429 | return 0; | |
430 | } | |
431 | ||
432 | static int get_process_id(pid_t pid, const char *field, uid_t *uid) { | |
433 | _cleanup_fclose_ FILE *f = NULL; | |
0b452006 | 434 | const char *p; |
7e7a16a0 | 435 | int r; |
0b452006 RC |
436 | |
437 | assert(field); | |
438 | assert(uid); | |
439 | ||
07b38ba5 | 440 | if (pid < 0) |
6f8cbcdb LP |
441 | return -EINVAL; |
442 | ||
0b452006 | 443 | p = procfs_file_alloca(pid, "status"); |
fdeea3f4 ZJS |
444 | r = fopen_unlocked(p, "re", &f); |
445 | if (r == -ENOENT) | |
446 | return -ESRCH; | |
447 | if (r < 0) | |
448 | return r; | |
35bbbf85 | 449 | |
7e7a16a0 LP |
450 | for (;;) { |
451 | _cleanup_free_ char *line = NULL; | |
0b452006 RC |
452 | char *l; |
453 | ||
7e7a16a0 LP |
454 | r = read_line(f, LONG_LINE_MAX, &line); |
455 | if (r < 0) | |
456 | return r; | |
457 | if (r == 0) | |
458 | break; | |
459 | ||
0b452006 RC |
460 | l = strstrip(line); |
461 | ||
462 | if (startswith(l, field)) { | |
463 | l += strlen(field); | |
464 | l += strspn(l, WHITESPACE); | |
465 | ||
466 | l[strcspn(l, WHITESPACE)] = 0; | |
467 | ||
468 | return parse_uid(l, uid); | |
469 | } | |
470 | } | |
471 | ||
472 | return -EIO; | |
473 | } | |
474 | ||
475 | int get_process_uid(pid_t pid, uid_t *uid) { | |
6f8cbcdb LP |
476 | |
477 | if (pid == 0 || pid == getpid_cached()) { | |
478 | *uid = getuid(); | |
479 | return 0; | |
480 | } | |
481 | ||
0b452006 RC |
482 | return get_process_id(pid, "Uid:", uid); |
483 | } | |
484 | ||
485 | int get_process_gid(pid_t pid, gid_t *gid) { | |
6f8cbcdb LP |
486 | |
487 | if (pid == 0 || pid == getpid_cached()) { | |
488 | *gid = getgid(); | |
489 | return 0; | |
490 | } | |
491 | ||
0b452006 RC |
492 | assert_cc(sizeof(uid_t) == sizeof(gid_t)); |
493 | return get_process_id(pid, "Gid:", gid); | |
494 | } | |
495 | ||
496 | int get_process_cwd(pid_t pid, char **cwd) { | |
497 | const char *p; | |
498 | ||
499 | assert(pid >= 0); | |
500 | ||
501 | p = procfs_file_alloca(pid, "cwd"); | |
502 | ||
503 | return get_process_link_contents(p, cwd); | |
504 | } | |
505 | ||
506 | int get_process_root(pid_t pid, char **root) { | |
507 | const char *p; | |
508 | ||
509 | assert(pid >= 0); | |
510 | ||
511 | p = procfs_file_alloca(pid, "root"); | |
512 | ||
513 | return get_process_link_contents(p, root); | |
514 | } | |
515 | ||
2a7797e9 LP |
516 | #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U) |
517 | ||
0b452006 RC |
518 | int get_process_environ(pid_t pid, char **env) { |
519 | _cleanup_fclose_ FILE *f = NULL; | |
520 | _cleanup_free_ char *outcome = NULL; | |
0b452006 | 521 | size_t allocated = 0, sz = 0; |
2a7797e9 LP |
522 | const char *p; |
523 | int r; | |
0b452006 RC |
524 | |
525 | assert(pid >= 0); | |
526 | assert(env); | |
527 | ||
528 | p = procfs_file_alloca(pid, "environ"); | |
529 | ||
fdeea3f4 ZJS |
530 | r = fopen_unlocked(p, "re", &f); |
531 | if (r == -ENOENT) | |
532 | return -ESRCH; | |
533 | if (r < 0) | |
534 | return r; | |
35bbbf85 | 535 | |
2a7797e9 LP |
536 | for (;;) { |
537 | char c; | |
538 | ||
539 | if (sz >= ENVIRONMENT_BLOCK_MAX) | |
540 | return -ENOBUFS; | |
541 | ||
0b452006 RC |
542 | if (!GREEDY_REALLOC(outcome, allocated, sz + 5)) |
543 | return -ENOMEM; | |
544 | ||
2a7797e9 LP |
545 | r = safe_fgetc(f, &c); |
546 | if (r < 0) | |
547 | return r; | |
548 | if (r == 0) | |
549 | break; | |
550 | ||
0b452006 RC |
551 | if (c == '\0') |
552 | outcome[sz++] = '\n'; | |
553 | else | |
554 | sz += cescape_char(c, outcome + sz); | |
555 | } | |
556 | ||
2a7797e9 | 557 | outcome[sz] = '\0'; |
ae2a15bc | 558 | *env = TAKE_PTR(outcome); |
0b452006 RC |
559 | |
560 | return 0; | |
561 | } | |
562 | ||
6bc73acb | 563 | int get_process_ppid(pid_t pid, pid_t *_ppid) { |
0b452006 RC |
564 | int r; |
565 | _cleanup_free_ char *line = NULL; | |
566 | long unsigned ppid; | |
567 | const char *p; | |
568 | ||
569 | assert(pid >= 0); | |
570 | assert(_ppid); | |
571 | ||
6f8cbcdb | 572 | if (pid == 0 || pid == getpid_cached()) { |
0b452006 RC |
573 | *_ppid = getppid(); |
574 | return 0; | |
575 | } | |
576 | ||
577 | p = procfs_file_alloca(pid, "stat"); | |
578 | r = read_one_line_file(p, &line); | |
a644184a LP |
579 | if (r == -ENOENT) |
580 | return -ESRCH; | |
0b452006 RC |
581 | if (r < 0) |
582 | return r; | |
583 | ||
584 | /* Let's skip the pid and comm fields. The latter is enclosed | |
585 | * in () but does not escape any () in its value, so let's | |
586 | * skip over it manually */ | |
587 | ||
588 | p = strrchr(line, ')'); | |
589 | if (!p) | |
590 | return -EIO; | |
591 | ||
592 | p++; | |
593 | ||
594 | if (sscanf(p, " " | |
595 | "%*c " /* state */ | |
596 | "%lu ", /* ppid */ | |
597 | &ppid) != 1) | |
598 | return -EIO; | |
599 | ||
600 | if ((long unsigned) (pid_t) ppid != ppid) | |
601 | return -ERANGE; | |
602 | ||
603 | *_ppid = (pid_t) ppid; | |
604 | ||
605 | return 0; | |
606 | } | |
607 | ||
608 | int wait_for_terminate(pid_t pid, siginfo_t *status) { | |
609 | siginfo_t dummy; | |
610 | ||
611 | assert(pid >= 1); | |
612 | ||
613 | if (!status) | |
614 | status = &dummy; | |
615 | ||
616 | for (;;) { | |
617 | zero(*status); | |
618 | ||
619 | if (waitid(P_PID, pid, status, WEXITED) < 0) { | |
620 | ||
621 | if (errno == EINTR) | |
622 | continue; | |
623 | ||
3f0083a2 | 624 | return negative_errno(); |
0b452006 RC |
625 | } |
626 | ||
627 | return 0; | |
628 | } | |
629 | } | |
630 | ||
631 | /* | |
632 | * Return values: | |
633 | * < 0 : wait_for_terminate() failed to get the state of the | |
634 | * process, the process was terminated by a signal, or | |
635 | * failed for an unknown reason. | |
636 | * >=0 : The process terminated normally, and its exit code is | |
637 | * returned. | |
638 | * | |
639 | * That is, success is indicated by a return value of zero, and an | |
640 | * error is indicated by a non-zero value. | |
641 | * | |
642 | * A warning is emitted if the process terminates abnormally, | |
643 | * and also if it returns non-zero unless check_exit_code is true. | |
644 | */ | |
7d4904fe LP |
645 | int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) { |
646 | _cleanup_free_ char *buffer = NULL; | |
0b452006 | 647 | siginfo_t status; |
7d4904fe | 648 | int r, prio; |
0b452006 | 649 | |
0b452006 RC |
650 | assert(pid > 1); |
651 | ||
7d4904fe LP |
652 | if (!name) { |
653 | r = get_process_comm(pid, &buffer); | |
654 | if (r < 0) | |
655 | log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid); | |
656 | else | |
657 | name = buffer; | |
658 | } | |
659 | ||
660 | prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG; | |
661 | ||
0b452006 RC |
662 | r = wait_for_terminate(pid, &status); |
663 | if (r < 0) | |
7d4904fe | 664 | return log_full_errno(prio, r, "Failed to wait for %s: %m", strna(name)); |
0b452006 RC |
665 | |
666 | if (status.si_code == CLD_EXITED) { | |
7d4904fe LP |
667 | if (status.si_status != EXIT_SUCCESS) |
668 | log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG, | |
669 | "%s failed with exit status %i.", strna(name), status.si_status); | |
0b452006 RC |
670 | else |
671 | log_debug("%s succeeded.", name); | |
672 | ||
673 | return status.si_status; | |
7d4904fe | 674 | |
3742095b | 675 | } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) { |
0b452006 | 676 | |
7d4904fe | 677 | log_full(prio, "%s terminated by signal %s.", strna(name), signal_to_string(status.si_status)); |
0b452006 RC |
678 | return -EPROTO; |
679 | } | |
680 | ||
7d4904fe | 681 | log_full(prio, "%s failed due to unknown reason.", strna(name)); |
0b452006 RC |
682 | return -EPROTO; |
683 | } | |
684 | ||
d5641e0d KW |
685 | /* |
686 | * Return values: | |
e225e5c3 LP |
687 | * |
688 | * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process | |
689 | * was terminated by a signal, or failed for an unknown reason. | |
690 | * | |
d5641e0d KW |
691 | * >=0 : The process terminated normally with no failures. |
692 | * | |
e225e5c3 LP |
693 | * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure |
694 | * states are indicated by error is indicated by a non-zero value. | |
695 | * | |
696 | * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off | |
697 | * to remain entirely race-free. | |
d5641e0d KW |
698 | */ |
699 | int wait_for_terminate_with_timeout(pid_t pid, usec_t timeout) { | |
700 | sigset_t mask; | |
701 | int r; | |
702 | usec_t until; | |
703 | ||
704 | assert_se(sigemptyset(&mask) == 0); | |
705 | assert_se(sigaddset(&mask, SIGCHLD) == 0); | |
706 | ||
707 | /* Drop into a sigtimewait-based timeout. Waiting for the | |
708 | * pid to exit. */ | |
709 | until = now(CLOCK_MONOTONIC) + timeout; | |
710 | for (;;) { | |
711 | usec_t n; | |
712 | siginfo_t status = {}; | |
713 | struct timespec ts; | |
714 | ||
715 | n = now(CLOCK_MONOTONIC); | |
716 | if (n >= until) | |
717 | break; | |
718 | ||
719 | r = sigtimedwait(&mask, NULL, timespec_store(&ts, until - n)) < 0 ? -errno : 0; | |
720 | /* Assuming we woke due to the child exiting. */ | |
721 | if (waitid(P_PID, pid, &status, WEXITED|WNOHANG) == 0) { | |
722 | if (status.si_pid == pid) { | |
723 | /* This is the correct child.*/ | |
724 | if (status.si_code == CLD_EXITED) | |
725 | return (status.si_status == 0) ? 0 : -EPROTO; | |
726 | else | |
727 | return -EPROTO; | |
728 | } | |
729 | } | |
730 | /* Not the child, check for errors and proceed appropriately */ | |
731 | if (r < 0) { | |
732 | switch (r) { | |
733 | case -EAGAIN: | |
734 | /* Timed out, child is likely hung. */ | |
735 | return -ETIMEDOUT; | |
736 | case -EINTR: | |
737 | /* Received a different signal and should retry */ | |
738 | continue; | |
739 | default: | |
740 | /* Return any unexpected errors */ | |
741 | return r; | |
742 | } | |
743 | } | |
744 | } | |
745 | ||
746 | return -EPROTO; | |
747 | } | |
748 | ||
89c9030d LP |
749 | void sigkill_wait(pid_t pid) { |
750 | assert(pid > 1); | |
751 | ||
53640e6f | 752 | if (kill(pid, SIGKILL) >= 0) |
89c9030d LP |
753 | (void) wait_for_terminate(pid, NULL); |
754 | } | |
755 | ||
756 | void sigkill_waitp(pid_t *pid) { | |
dfd14786 LP |
757 | PROTECT_ERRNO; |
758 | ||
4d0d3d41 LP |
759 | if (!pid) |
760 | return; | |
761 | if (*pid <= 1) | |
762 | return; | |
763 | ||
89c9030d | 764 | sigkill_wait(*pid); |
4d0d3d41 LP |
765 | } |
766 | ||
392cf1d0 SL |
767 | void sigterm_wait(pid_t pid) { |
768 | assert(pid > 1); | |
769 | ||
53640e6f | 770 | if (kill_and_sigcont(pid, SIGTERM) >= 0) |
392cf1d0 SL |
771 | (void) wait_for_terminate(pid, NULL); |
772 | } | |
773 | ||
0b452006 RC |
774 | int kill_and_sigcont(pid_t pid, int sig) { |
775 | int r; | |
776 | ||
777 | r = kill(pid, sig) < 0 ? -errno : 0; | |
778 | ||
26f417d3 LP |
779 | /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't |
780 | * affected by a process being suspended anyway. */ | |
a3d8d68c | 781 | if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL)) |
26f417d3 | 782 | (void) kill(pid, SIGCONT); |
0b452006 RC |
783 | |
784 | return r; | |
785 | } | |
786 | ||
e70f4453 | 787 | int getenv_for_pid(pid_t pid, const char *field, char **ret) { |
0b452006 RC |
788 | _cleanup_fclose_ FILE *f = NULL; |
789 | char *value = NULL; | |
0b452006 | 790 | const char *path; |
0d90bd92 LP |
791 | size_t l, sum = 0; |
792 | int r; | |
0b452006 RC |
793 | |
794 | assert(pid >= 0); | |
795 | assert(field); | |
e70f4453 LP |
796 | assert(ret); |
797 | ||
798 | if (pid == 0 || pid == getpid_cached()) { | |
799 | const char *e; | |
800 | ||
801 | e = getenv(field); | |
802 | if (!e) { | |
803 | *ret = NULL; | |
804 | return 0; | |
805 | } | |
806 | ||
807 | value = strdup(e); | |
808 | if (!value) | |
809 | return -ENOMEM; | |
810 | ||
811 | *ret = value; | |
812 | return 1; | |
813 | } | |
0b452006 | 814 | |
0d90bd92 LP |
815 | if (!pid_is_valid(pid)) |
816 | return -EINVAL; | |
817 | ||
0b452006 RC |
818 | path = procfs_file_alloca(pid, "environ"); |
819 | ||
fdeea3f4 ZJS |
820 | r = fopen_unlocked(path, "re", &f); |
821 | if (r == -ENOENT) | |
822 | return -ESRCH; | |
823 | if (r < 0) | |
824 | return r; | |
35bbbf85 | 825 | |
0b452006 | 826 | l = strlen(field); |
0d90bd92 LP |
827 | for (;;) { |
828 | _cleanup_free_ char *line = NULL; | |
0b452006 | 829 | |
0d90bd92 LP |
830 | if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */ |
831 | return -ENOBUFS; | |
0b452006 | 832 | |
0d90bd92 LP |
833 | r = read_nul_string(f, LONG_LINE_MAX, &line); |
834 | if (r < 0) | |
835 | return r; | |
836 | if (r == 0) /* EOF */ | |
837 | break; | |
0b452006 | 838 | |
0d90bd92 | 839 | sum += r; |
0b452006 | 840 | |
041b5ae1 | 841 | if (strneq(line, field, l) && line[l] == '=') { |
0b452006 RC |
842 | value = strdup(line + l + 1); |
843 | if (!value) | |
844 | return -ENOMEM; | |
845 | ||
e70f4453 LP |
846 | *ret = value; |
847 | return 1; | |
0b452006 | 848 | } |
0d90bd92 | 849 | } |
0b452006 | 850 | |
e70f4453 LP |
851 | *ret = NULL; |
852 | return 0; | |
0b452006 RC |
853 | } |
854 | ||
4d051546 FB |
855 | int pid_is_my_child(pid_t pid) { |
856 | pid_t ppid; | |
857 | int r; | |
858 | ||
859 | if (pid <= 1) | |
860 | return false; | |
861 | ||
862 | r = get_process_ppid(pid, &ppid); | |
863 | if (r < 0) | |
864 | return r; | |
865 | ||
866 | return ppid == getpid_cached(); | |
867 | } | |
868 | ||
0b452006 RC |
869 | bool pid_is_unwaited(pid_t pid) { |
870 | /* Checks whether a PID is still valid at all, including a zombie */ | |
871 | ||
07b38ba5 | 872 | if (pid < 0) |
0b452006 RC |
873 | return false; |
874 | ||
5fd9b2c5 LP |
875 | if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */ |
876 | return true; | |
877 | ||
6f8cbcdb LP |
878 | if (pid == getpid_cached()) |
879 | return true; | |
880 | ||
0b452006 RC |
881 | if (kill(pid, 0) >= 0) |
882 | return true; | |
883 | ||
884 | return errno != ESRCH; | |
885 | } | |
886 | ||
887 | bool pid_is_alive(pid_t pid) { | |
888 | int r; | |
889 | ||
890 | /* Checks whether a PID is still valid and not a zombie */ | |
891 | ||
07b38ba5 | 892 | if (pid < 0) |
0b452006 RC |
893 | return false; |
894 | ||
5fd9b2c5 LP |
895 | if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */ |
896 | return true; | |
897 | ||
6f8cbcdb LP |
898 | if (pid == getpid_cached()) |
899 | return true; | |
900 | ||
0b452006 | 901 | r = get_process_state(pid); |
4c701096 | 902 | if (IN_SET(r, -ESRCH, 'Z')) |
0b452006 RC |
903 | return false; |
904 | ||
905 | return true; | |
906 | } | |
d4510856 | 907 | |
1359fffa MS |
908 | int pid_from_same_root_fs(pid_t pid) { |
909 | const char *root; | |
910 | ||
07b38ba5 | 911 | if (pid < 0) |
6f8cbcdb LP |
912 | return false; |
913 | ||
914 | if (pid == 0 || pid == getpid_cached()) | |
915 | return true; | |
1359fffa MS |
916 | |
917 | root = procfs_file_alloca(pid, "root"); | |
918 | ||
e3f791a2 | 919 | return files_same(root, "/proc/1/root", 0); |
1359fffa MS |
920 | } |
921 | ||
d4510856 LP |
922 | bool is_main_thread(void) { |
923 | static thread_local int cached = 0; | |
924 | ||
925 | if (_unlikely_(cached == 0)) | |
df0ff127 | 926 | cached = getpid_cached() == gettid() ? 1 : -1; |
d4510856 LP |
927 | |
928 | return cached > 0; | |
929 | } | |
7b3e062c | 930 | |
848e863a | 931 | _noreturn_ void freeze(void) { |
7b3e062c | 932 | |
3da48d7a EV |
933 | log_close(); |
934 | ||
7b3e062c | 935 | /* Make sure nobody waits for us on a socket anymore */ |
7acf581a | 936 | (void) close_all_fds(NULL, 0); |
7b3e062c LP |
937 | |
938 | sync(); | |
939 | ||
8647283e MS |
940 | /* Let's not freeze right away, but keep reaping zombies. */ |
941 | for (;;) { | |
942 | int r; | |
943 | siginfo_t si = {}; | |
944 | ||
945 | r = waitid(P_ALL, 0, &si, WEXITED); | |
946 | if (r < 0 && errno != EINTR) | |
947 | break; | |
948 | } | |
949 | ||
950 | /* waitid() failed with an unexpected error, things are really borked. Freeze now! */ | |
7b3e062c LP |
951 | for (;;) |
952 | pause(); | |
953 | } | |
954 | ||
955 | bool oom_score_adjust_is_valid(int oa) { | |
956 | return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX; | |
957 | } | |
958 | ||
959 | unsigned long personality_from_string(const char *p) { | |
6e5f1b57 | 960 | int architecture; |
7b3e062c | 961 | |
0c0fea07 LP |
962 | if (!p) |
963 | return PERSONALITY_INVALID; | |
964 | ||
6e5f1b57 LP |
965 | /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just |
966 | * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for | |
967 | * the same register size. */ | |
968 | ||
969 | architecture = architecture_from_string(p); | |
970 | if (architecture < 0) | |
971 | return PERSONALITY_INVALID; | |
7b3e062c | 972 | |
0c0fea07 | 973 | if (architecture == native_architecture()) |
7b3e062c | 974 | return PER_LINUX; |
0c0fea07 LP |
975 | #ifdef SECONDARY_ARCHITECTURE |
976 | if (architecture == SECONDARY_ARCHITECTURE) | |
f2d1736c | 977 | return PER_LINUX32; |
7b3e062c LP |
978 | #endif |
979 | ||
980 | return PERSONALITY_INVALID; | |
981 | } | |
982 | ||
983 | const char* personality_to_string(unsigned long p) { | |
6e5f1b57 | 984 | int architecture = _ARCHITECTURE_INVALID; |
7b3e062c | 985 | |
7b3e062c | 986 | if (p == PER_LINUX) |
0c0fea07 LP |
987 | architecture = native_architecture(); |
988 | #ifdef SECONDARY_ARCHITECTURE | |
6e5f1b57 | 989 | else if (p == PER_LINUX32) |
0c0fea07 | 990 | architecture = SECONDARY_ARCHITECTURE; |
7b3e062c LP |
991 | #endif |
992 | ||
6e5f1b57 LP |
993 | if (architecture < 0) |
994 | return NULL; | |
995 | ||
996 | return architecture_to_string(architecture); | |
7b3e062c LP |
997 | } |
998 | ||
21022b9d LP |
999 | int safe_personality(unsigned long p) { |
1000 | int ret; | |
1001 | ||
1002 | /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno, | |
1003 | * and in others as negative return value containing an errno-like value. Let's work around this: this is a | |
1004 | * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and | |
1005 | * the return value indicating the same issue, so that we are definitely on the safe side. | |
1006 | * | |
1007 | * See https://github.com/systemd/systemd/issues/6737 */ | |
1008 | ||
1009 | errno = 0; | |
1010 | ret = personality(p); | |
1011 | if (ret < 0) { | |
1012 | if (errno != 0) | |
1013 | return -errno; | |
1014 | ||
1015 | errno = -ret; | |
1016 | } | |
1017 | ||
1018 | return ret; | |
1019 | } | |
1020 | ||
e8132d63 LP |
1021 | int opinionated_personality(unsigned long *ret) { |
1022 | int current; | |
1023 | ||
1024 | /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit | |
1025 | * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the | |
1026 | * two most relevant personalities: PER_LINUX and PER_LINUX32. */ | |
1027 | ||
21022b9d | 1028 | current = safe_personality(PERSONALITY_INVALID); |
e8132d63 | 1029 | if (current < 0) |
21022b9d | 1030 | return current; |
e8132d63 LP |
1031 | |
1032 | if (((unsigned long) current & 0xffff) == PER_LINUX32) | |
1033 | *ret = PER_LINUX32; | |
1034 | else | |
1035 | *ret = PER_LINUX; | |
1036 | ||
1037 | return 0; | |
1038 | } | |
1039 | ||
dcadc967 | 1040 | void valgrind_summary_hack(void) { |
349cc4a5 | 1041 | #if HAVE_VALGRIND_VALGRIND_H |
df0ff127 | 1042 | if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) { |
dcadc967 | 1043 | pid_t pid; |
8869a0b4 | 1044 | pid = raw_clone(SIGCHLD); |
dcadc967 EV |
1045 | if (pid < 0) |
1046 | log_emergency_errno(errno, "Failed to fork off valgrind helper: %m"); | |
1047 | else if (pid == 0) | |
1048 | exit(EXIT_SUCCESS); | |
1049 | else { | |
1050 | log_info("Spawned valgrind helper as PID "PID_FMT".", pid); | |
1051 | (void) wait_for_terminate(pid, NULL); | |
1052 | } | |
1053 | } | |
1054 | #endif | |
1055 | } | |
1056 | ||
93bab288 | 1057 | int pid_compare_func(const pid_t *a, const pid_t *b) { |
291d565a | 1058 | /* Suitable for usage in qsort() */ |
93bab288 | 1059 | return CMP(*a, *b); |
291d565a LP |
1060 | } |
1061 | ||
7f452159 LP |
1062 | int ioprio_parse_priority(const char *s, int *ret) { |
1063 | int i, r; | |
1064 | ||
1065 | assert(s); | |
1066 | assert(ret); | |
1067 | ||
1068 | r = safe_atoi(s, &i); | |
1069 | if (r < 0) | |
1070 | return r; | |
1071 | ||
1072 | if (!ioprio_priority_is_valid(i)) | |
1073 | return -EINVAL; | |
1074 | ||
1075 | *ret = i; | |
1076 | return 0; | |
1077 | } | |
1078 | ||
5c30a6d2 LP |
1079 | /* The cached PID, possible values: |
1080 | * | |
1081 | * == UNSET [0] → cache not initialized yet | |
1082 | * == BUSY [-1] → some thread is initializing it at the moment | |
1083 | * any other → the cached PID | |
1084 | */ | |
1085 | ||
1086 | #define CACHED_PID_UNSET ((pid_t) 0) | |
1087 | #define CACHED_PID_BUSY ((pid_t) -1) | |
1088 | ||
1089 | static pid_t cached_pid = CACHED_PID_UNSET; | |
1090 | ||
799a960d | 1091 | void reset_cached_pid(void) { |
5c30a6d2 LP |
1092 | /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */ |
1093 | cached_pid = CACHED_PID_UNSET; | |
1094 | } | |
1095 | ||
1096 | /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc | |
1097 | * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against | |
1098 | * libpthread, as it is part of glibc anyway. */ | |
2bb8d8d9 | 1099 | extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void *dso_handle); |
d34dae18 | 1100 | extern void* __dso_handle _weak_; |
5c30a6d2 LP |
1101 | |
1102 | pid_t getpid_cached(void) { | |
5d71bac3 | 1103 | static bool installed = false; |
5c30a6d2 LP |
1104 | pid_t current_value; |
1105 | ||
1106 | /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a | |
1107 | * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally | |
1108 | * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when | |
1109 | * objects were used across fork()s. With this caching the old behaviour is somewhat restored. | |
1110 | * | |
1111 | * https://bugzilla.redhat.com/show_bug.cgi?id=1443976 | |
a4041e4f | 1112 | * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e |
5c30a6d2 LP |
1113 | */ |
1114 | ||
1115 | current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY); | |
1116 | ||
1117 | switch (current_value) { | |
1118 | ||
1119 | case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */ | |
1120 | pid_t new_pid; | |
1121 | ||
996def17 | 1122 | new_pid = raw_getpid(); |
5c30a6d2 | 1123 | |
5d71bac3 LP |
1124 | if (!installed) { |
1125 | /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's | |
1126 | * only half-documented (glibc doesn't document it but LSB does — though only superficially) | |
1127 | * we'll check for errors only in the most generic fashion possible. */ | |
1128 | ||
1129 | if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) { | |
1130 | /* OOM? Let's try again later */ | |
1131 | cached_pid = CACHED_PID_UNSET; | |
1132 | return new_pid; | |
1133 | } | |
1134 | ||
1135 | installed = true; | |
5c30a6d2 LP |
1136 | } |
1137 | ||
1138 | cached_pid = new_pid; | |
1139 | return new_pid; | |
1140 | } | |
1141 | ||
1142 | case CACHED_PID_BUSY: /* Somebody else is currently initializing */ | |
996def17 | 1143 | return raw_getpid(); |
5c30a6d2 LP |
1144 | |
1145 | default: /* Properly initialized */ | |
1146 | return current_value; | |
1147 | } | |
1148 | } | |
1149 | ||
fba868fa LP |
1150 | int must_be_root(void) { |
1151 | ||
1152 | if (geteuid() == 0) | |
1153 | return 0; | |
1154 | ||
baaa35ad | 1155 | return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be root."); |
fba868fa LP |
1156 | } |
1157 | ||
4c253ed1 LP |
1158 | int safe_fork_full( |
1159 | const char *name, | |
1160 | const int except_fds[], | |
1161 | size_t n_except_fds, | |
1162 | ForkFlags flags, | |
1163 | pid_t *ret_pid) { | |
1164 | ||
1165 | pid_t original_pid, pid; | |
1f5d1e02 | 1166 | sigset_t saved_ss, ss; |
a41f6217 | 1167 | bool block_signals = false; |
b6e1fff1 | 1168 | int prio, r; |
4c253ed1 LP |
1169 | |
1170 | /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always | |
1171 | * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */ | |
1172 | ||
b6e1fff1 LP |
1173 | prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG; |
1174 | ||
4c253ed1 LP |
1175 | original_pid = getpid_cached(); |
1176 | ||
1f5d1e02 | 1177 | if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG)) { |
1f5d1e02 LP |
1178 | /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can |
1179 | * be sure that SIGTERMs are not lost we might send to the child. */ | |
4c253ed1 | 1180 | |
cd2a429e | 1181 | assert_se(sigfillset(&ss) >= 0); |
1f5d1e02 LP |
1182 | block_signals = true; |
1183 | ||
1184 | } else if (flags & FORK_WAIT) { | |
1f5d1e02 LP |
1185 | /* Let's block SIGCHLD at least, so that we can safely watch for the child process */ |
1186 | ||
cd2a429e ZJS |
1187 | assert_se(sigemptyset(&ss) >= 0); |
1188 | assert_se(sigaddset(&ss, SIGCHLD) >= 0); | |
1f5d1e02 | 1189 | block_signals = true; |
4c253ed1 LP |
1190 | } |
1191 | ||
1f5d1e02 LP |
1192 | if (block_signals) |
1193 | if (sigprocmask(SIG_SETMASK, &ss, &saved_ss) < 0) | |
1194 | return log_full_errno(prio, errno, "Failed to set signal mask: %m"); | |
1195 | ||
be39f6ee LP |
1196 | if (flags & FORK_NEW_MOUNTNS) |
1197 | pid = raw_clone(SIGCHLD|CLONE_NEWNS); | |
1198 | else | |
1199 | pid = fork(); | |
4c253ed1 LP |
1200 | if (pid < 0) { |
1201 | r = -errno; | |
1202 | ||
1203 | if (block_signals) /* undo what we did above */ | |
1204 | (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL); | |
1205 | ||
b6e1fff1 | 1206 | return log_full_errno(prio, r, "Failed to fork: %m"); |
4c253ed1 LP |
1207 | } |
1208 | if (pid > 0) { | |
1209 | /* We are in the parent process */ | |
1210 | ||
1f5d1e02 LP |
1211 | log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid); |
1212 | ||
1213 | if (flags & FORK_WAIT) { | |
1214 | r = wait_for_terminate_and_check(name, pid, (flags & FORK_LOG ? WAIT_LOG : 0)); | |
1215 | if (r < 0) | |
1216 | return r; | |
1217 | if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */ | |
1218 | return -EPROTO; | |
1219 | } | |
1220 | ||
4c253ed1 LP |
1221 | if (block_signals) /* undo what we did above */ |
1222 | (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL); | |
1223 | ||
4c253ed1 LP |
1224 | if (ret_pid) |
1225 | *ret_pid = pid; | |
1226 | ||
1227 | return 1; | |
1228 | } | |
1229 | ||
1230 | /* We are in the child process */ | |
1231 | ||
1232 | if (flags & FORK_REOPEN_LOG) { | |
1233 | /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */ | |
1234 | log_close(); | |
1235 | log_set_open_when_needed(true); | |
1236 | } | |
1237 | ||
1238 | if (name) { | |
1239 | r = rename_process(name); | |
1240 | if (r < 0) | |
b6e1fff1 LP |
1241 | log_full_errno(flags & FORK_LOG ? LOG_WARNING : LOG_DEBUG, |
1242 | r, "Failed to rename process, ignoring: %m"); | |
4c253ed1 LP |
1243 | } |
1244 | ||
1245 | if (flags & FORK_DEATHSIG) | |
1246 | if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) { | |
b6e1fff1 | 1247 | log_full_errno(prio, errno, "Failed to set death signal: %m"); |
4c253ed1 LP |
1248 | _exit(EXIT_FAILURE); |
1249 | } | |
1250 | ||
1251 | if (flags & FORK_RESET_SIGNALS) { | |
1252 | r = reset_all_signal_handlers(); | |
1253 | if (r < 0) { | |
b6e1fff1 | 1254 | log_full_errno(prio, r, "Failed to reset signal handlers: %m"); |
4c253ed1 LP |
1255 | _exit(EXIT_FAILURE); |
1256 | } | |
1257 | ||
1258 | /* This implicitly undoes the signal mask stuff we did before the fork()ing above */ | |
1259 | r = reset_signal_mask(); | |
1260 | if (r < 0) { | |
b6e1fff1 | 1261 | log_full_errno(prio, r, "Failed to reset signal mask: %m"); |
4c253ed1 LP |
1262 | _exit(EXIT_FAILURE); |
1263 | } | |
1264 | } else if (block_signals) { /* undo what we did above */ | |
1265 | if (sigprocmask(SIG_SETMASK, &saved_ss, NULL) < 0) { | |
b6e1fff1 | 1266 | log_full_errno(prio, errno, "Failed to restore signal mask: %m"); |
4c253ed1 LP |
1267 | _exit(EXIT_FAILURE); |
1268 | } | |
1269 | } | |
1270 | ||
1271 | if (flags & FORK_DEATHSIG) { | |
7ddc2dc5 | 1272 | pid_t ppid; |
4c253ed1 LP |
1273 | /* Let's see if the parent PID is still the one we started from? If not, then the parent |
1274 | * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */ | |
1275 | ||
7ddc2dc5 SL |
1276 | ppid = getppid(); |
1277 | if (ppid == 0) | |
1278 | /* Parent is in a differn't PID namespace. */; | |
1279 | else if (ppid != original_pid) { | |
4c253ed1 LP |
1280 | log_debug("Parent died early, raising SIGTERM."); |
1281 | (void) raise(SIGTERM); | |
1282 | _exit(EXIT_FAILURE); | |
1283 | } | |
1284 | } | |
1285 | ||
d94a24ca | 1286 | if (FLAGS_SET(flags, FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE)) { |
e2047ba9 LP |
1287 | |
1288 | /* Optionally, make sure we never propagate mounts to the host. */ | |
1289 | ||
1290 | if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) { | |
1291 | log_full_errno(prio, errno, "Failed to remount root directory as MS_SLAVE: %m"); | |
1292 | _exit(EXIT_FAILURE); | |
1293 | } | |
1294 | } | |
1295 | ||
4c253ed1 LP |
1296 | if (flags & FORK_CLOSE_ALL_FDS) { |
1297 | /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */ | |
1298 | log_close(); | |
1299 | ||
1300 | r = close_all_fds(except_fds, n_except_fds); | |
1301 | if (r < 0) { | |
b6e1fff1 | 1302 | log_full_errno(prio, r, "Failed to close all file descriptors: %m"); |
4c253ed1 LP |
1303 | _exit(EXIT_FAILURE); |
1304 | } | |
1305 | } | |
1306 | ||
1307 | /* When we were asked to reopen the logs, do so again now */ | |
1308 | if (flags & FORK_REOPEN_LOG) { | |
1309 | log_open(); | |
1310 | log_set_open_when_needed(false); | |
1311 | } | |
1312 | ||
1313 | if (flags & FORK_NULL_STDIO) { | |
1314 | r = make_null_stdio(); | |
1315 | if (r < 0) { | |
b6e1fff1 | 1316 | log_full_errno(prio, r, "Failed to connect stdin/stdout to /dev/null: %m"); |
4c253ed1 LP |
1317 | _exit(EXIT_FAILURE); |
1318 | } | |
1319 | } | |
1320 | ||
909106eb LP |
1321 | if (flags & FORK_RLIMIT_NOFILE_SAFE) { |
1322 | r = rlimit_nofile_safe(); | |
1323 | if (r < 0) { | |
1324 | log_full_errno(prio, r, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m"); | |
1325 | _exit(EXIT_FAILURE); | |
1326 | } | |
1327 | } | |
1328 | ||
4c253ed1 LP |
1329 | if (ret_pid) |
1330 | *ret_pid = getpid_cached(); | |
1331 | ||
1332 | return 0; | |
1333 | } | |
1334 | ||
27096982 LP |
1335 | int namespace_fork( |
1336 | const char *outer_name, | |
1337 | const char *inner_name, | |
1338 | const int except_fds[], | |
1339 | size_t n_except_fds, | |
1340 | ForkFlags flags, | |
1341 | int pidns_fd, | |
1342 | int mntns_fd, | |
1343 | int netns_fd, | |
1344 | int userns_fd, | |
1345 | int root_fd, | |
1346 | pid_t *ret_pid) { | |
1347 | ||
1348 | int r; | |
1349 | ||
1350 | /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle | |
1351 | * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that | |
1352 | * /proc/self/fd works correctly. */ | |
1353 | ||
1354 | r = safe_fork_full(outer_name, except_fds, n_except_fds, (flags|FORK_DEATHSIG) & ~(FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE), ret_pid); | |
1355 | if (r < 0) | |
1356 | return r; | |
1357 | if (r == 0) { | |
1358 | pid_t pid; | |
1359 | ||
1360 | /* Child */ | |
1361 | ||
1362 | r = namespace_enter(pidns_fd, mntns_fd, netns_fd, userns_fd, root_fd); | |
1363 | if (r < 0) { | |
1364 | log_full_errno(FLAGS_SET(flags, FORK_LOG) ? LOG_ERR : LOG_DEBUG, r, "Failed to join namespace: %m"); | |
1365 | _exit(EXIT_FAILURE); | |
1366 | } | |
1367 | ||
1368 | /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */ | |
1369 | r = safe_fork_full(inner_name, except_fds, n_except_fds, flags & ~(FORK_WAIT|FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_NULL_STDIO), &pid); | |
1370 | if (r < 0) | |
1371 | _exit(EXIT_FAILURE); | |
1372 | if (r == 0) { | |
1373 | /* Child */ | |
1374 | if (ret_pid) | |
1375 | *ret_pid = pid; | |
1376 | return 0; | |
1377 | } | |
1378 | ||
1379 | r = wait_for_terminate_and_check(inner_name, pid, FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0); | |
1380 | if (r < 0) | |
1381 | _exit(EXIT_FAILURE); | |
1382 | ||
1383 | _exit(r); | |
1384 | } | |
1385 | ||
1386 | return 1; | |
1387 | } | |
1388 | ||
da6053d0 | 1389 | int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) { |
78752f2e | 1390 | bool stdout_is_tty, stderr_is_tty; |
da6053d0 | 1391 | size_t n, i; |
78752f2e LP |
1392 | va_list ap; |
1393 | char **l; | |
1394 | int r; | |
1395 | ||
1396 | assert(path); | |
1397 | ||
1398 | /* Spawns a temporary TTY agent, making sure it goes away when we go away */ | |
1399 | ||
1400 | r = safe_fork_full(name, except, n_except, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS, ret_pid); | |
1401 | if (r < 0) | |
1402 | return r; | |
1403 | if (r > 0) | |
1404 | return 0; | |
1405 | ||
1406 | /* In the child: */ | |
1407 | ||
1408 | stdout_is_tty = isatty(STDOUT_FILENO); | |
1409 | stderr_is_tty = isatty(STDERR_FILENO); | |
1410 | ||
1411 | if (!stdout_is_tty || !stderr_is_tty) { | |
1412 | int fd; | |
1413 | ||
1414 | /* Detach from stdout/stderr. and reopen | |
1415 | * /dev/tty for them. This is important to | |
1416 | * ensure that when systemctl is started via | |
1417 | * popen() or a similar call that expects to | |
1418 | * read EOF we actually do generate EOF and | |
1419 | * not delay this indefinitely by because we | |
1420 | * keep an unused copy of stdin around. */ | |
1421 | fd = open("/dev/tty", O_WRONLY); | |
1422 | if (fd < 0) { | |
1423 | log_error_errno(errno, "Failed to open /dev/tty: %m"); | |
1424 | _exit(EXIT_FAILURE); | |
1425 | } | |
1426 | ||
1427 | if (!stdout_is_tty && dup2(fd, STDOUT_FILENO) < 0) { | |
1428 | log_error_errno(errno, "Failed to dup2 /dev/tty: %m"); | |
1429 | _exit(EXIT_FAILURE); | |
1430 | } | |
1431 | ||
1432 | if (!stderr_is_tty && dup2(fd, STDERR_FILENO) < 0) { | |
1433 | log_error_errno(errno, "Failed to dup2 /dev/tty: %m"); | |
1434 | _exit(EXIT_FAILURE); | |
1435 | } | |
1436 | ||
e7685a77 | 1437 | safe_close_above_stdio(fd); |
78752f2e LP |
1438 | } |
1439 | ||
595225af LP |
1440 | (void) rlimit_nofile_safe(); |
1441 | ||
78752f2e LP |
1442 | /* Count arguments */ |
1443 | va_start(ap, path); | |
1444 | for (n = 0; va_arg(ap, char*); n++) | |
1445 | ; | |
1446 | va_end(ap); | |
1447 | ||
1448 | /* Allocate strv */ | |
cf409d15 | 1449 | l = newa(char*, n + 1); |
78752f2e LP |
1450 | |
1451 | /* Fill in arguments */ | |
1452 | va_start(ap, path); | |
1453 | for (i = 0; i <= n; i++) | |
1454 | l[i] = va_arg(ap, char*); | |
1455 | va_end(ap); | |
1456 | ||
1457 | execv(path, l); | |
1458 | _exit(EXIT_FAILURE); | |
1459 | } | |
1460 | ||
9f8168eb LP |
1461 | int set_oom_score_adjust(int value) { |
1462 | char t[DECIMAL_STR_MAX(int)]; | |
1463 | ||
1464 | sprintf(t, "%i", value); | |
1465 | ||
1466 | return write_string_file("/proc/self/oom_score_adj", t, | |
1467 | WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER); | |
1468 | } | |
1469 | ||
20ee849d LP |
1470 | int cpus_in_affinity_mask(void) { |
1471 | size_t n = 16; | |
1472 | int r; | |
1473 | ||
1474 | for (;;) { | |
1475 | cpu_set_t *c; | |
1476 | ||
1477 | c = CPU_ALLOC(n); | |
1478 | if (!c) | |
1479 | return -ENOMEM; | |
1480 | ||
1481 | if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), c) >= 0) { | |
1482 | int k; | |
1483 | ||
1484 | k = CPU_COUNT_S(CPU_ALLOC_SIZE(n), c); | |
1485 | CPU_FREE(c); | |
1486 | ||
1487 | if (k <= 0) | |
1488 | return -EINVAL; | |
1489 | ||
1490 | return k; | |
1491 | } | |
1492 | ||
1493 | r = -errno; | |
1494 | CPU_FREE(c); | |
1495 | ||
1496 | if (r != -EINVAL) | |
1497 | return r; | |
1498 | if (n > SIZE_MAX/2) | |
1499 | return -ENOMEM; | |
1500 | n *= 2; | |
1501 | } | |
1502 | } | |
1503 | ||
7b3e062c LP |
1504 | static const char *const ioprio_class_table[] = { |
1505 | [IOPRIO_CLASS_NONE] = "none", | |
1506 | [IOPRIO_CLASS_RT] = "realtime", | |
1507 | [IOPRIO_CLASS_BE] = "best-effort", | |
1508 | [IOPRIO_CLASS_IDLE] = "idle" | |
1509 | }; | |
1510 | ||
10062bbc | 1511 | DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, IOPRIO_N_CLASSES); |
7b3e062c LP |
1512 | |
1513 | static const char *const sigchld_code_table[] = { | |
1514 | [CLD_EXITED] = "exited", | |
1515 | [CLD_KILLED] = "killed", | |
1516 | [CLD_DUMPED] = "dumped", | |
1517 | [CLD_TRAPPED] = "trapped", | |
1518 | [CLD_STOPPED] = "stopped", | |
1519 | [CLD_CONTINUED] = "continued", | |
1520 | }; | |
1521 | ||
1522 | DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int); | |
1523 | ||
1524 | static const char* const sched_policy_table[] = { | |
1525 | [SCHED_OTHER] = "other", | |
1526 | [SCHED_BATCH] = "batch", | |
1527 | [SCHED_IDLE] = "idle", | |
1528 | [SCHED_FIFO] = "fifo", | |
1529 | [SCHED_RR] = "rr" | |
1530 | }; | |
1531 | ||
1532 | DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX); |