Debian Codegraph @

src/shared/killall.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2010 ProFUSION embedded systems
4 ***/
5
6 #include <signal.h>
7 #include <sys/wait.h>
8
9 #include "alloc-util.h"
10 #include "errno-util.h"
11 #include "fd-util.h"
12 #include "format-util.h"
13 #include "initrd-util.h"
14 #include "killall.h"
15 #include "log.h"
16 #include "pidref.h"
17 #include "process-util.h"
18 #include "set.h"
19 #include "string-util.h"
20 #include "terminal-util.h"
21 #include "time-util.h"
22
23 static int argv_has_at(const PidRef *pid) {
24 int r;
25
26 assert(pidref_is_set(pid));
27 assert(!pidref_is_remote(pid));
28
29 const char *p = procfs_file_alloca(pid->pid, "cmdline");
30 _cleanup_fclose_ FILE *f = fopen(p, "re");
31 if (!f)
32 return log_debug_errno(errno, "Failed to open %s, ignoring: %m", p);
33
34 /* Try to read the first character of the command line. If the cmdline is empty (which might be the case for
35 * kernel threads but potentially also other stuff), this line won't do anything, but we don't care much, as
36 * actual kernel threads are already filtered out above. */
37 char c = 0;
38 (void) fread(&c, 1, 1, f);
39
40 r = pidref_verify(pid);
41 if (r < 0)
42 return log_debug_errno(r, "Failed to verify pid " PID_FMT ", ignoring: %m", pid->pid);
43
44 /* Processes with argv[0][0] = '@' we ignore from the killing spree.
45 *
46 * https://systemd.io/ROOT_STORAGE_DAEMONS */
47 return c == '@';
48 }
49
50 static bool is_in_survivor_cgroup(const PidRef *pid) {
51 _cleanup_free_ char *cgroup_path = NULL;
52 int r;
53
54 assert(pidref_is_set(pid));
55
56 r = cg_pidref_get_path(pid, &cgroup_path);
57 if (r == -EUNATCH) {
58 log_warning_errno(r, "Process " PID_FMT " appears to originate in foreign namespace, ignoring.", pid->pid);
59 return true;
60 }
61 if (r < 0) {
62 log_warning_errno(r, "Failed to get cgroup path of process " PID_FMT ", ignoring: %m", pid->pid);
63 return false;
64 }
65
66 r = cg_get_xattr_bool(cgroup_path, "user.survive_final_kill_signal");
67 if (r < 0 && !ERRNO_IS_NEG_XATTR_ABSENT(r))
68 log_debug_errno(r,
69 "Failed to get survive_final_kill_signal xattr of %s, ignoring: %m",
70 cgroup_path);
71
72 return r > 0;
73 }
74
75 static bool ignore_proc(PidRef *pid, bool warn_rootfs) {
76 uid_t uid;
77
78 assert(pidref_is_set(pid));
79
80 /* We are PID 1, let's not commit suicide */
81 if (pid->pid == 1)
82 return true;
83
84 /* Ignore kernel threads */
85 if (pidref_is_kernel_thread(pid) != 0)
86 return true; /* also ignore processes where we can't determine this */
87
88 /* Ignore processes that are part of a cgroup marked with the user.survive_final_kill_signal xattr */
89 if (is_in_survivor_cgroup(pid))
90 return true;
91
92 if (pidref_get_uid(pid, &uid) < 0)
93 return true; /* not really, but better safe than sorry */
94
95 /* Non-root processes otherwise are always subject to be killed */
96 if (uid != 0)
97 return false;
98
99 if (argv_has_at(pid) == 0)
100 return false; /* if this fails, ignore the process */
101
102 if (warn_rootfs &&
103 pidref_from_same_root_fs(pid, NULL) > 0) {
104 _cleanup_free_ char *comm = NULL;
105
106 (void) pidref_get_comm(pid, &comm);
107
108 log_notice("Process " PID_FMT " (%s) has been marked to be excluded from killing. It is "
109 "running from the root file system, and thus likely to block re-mounting of the "
110 "root file system to read-only. Please consider moving it into an initrd file "
111 "system instead.", pid->pid, strna(comm));
112 }
113
114 return true;
115 }
116
117 static void log_children_not_yet_killed(Set *pids) {
118 _cleanup_free_ char *lst_child = NULL;
119 int r;
120
121 void *p;
122 SET_FOREACH(p, pids) {
123 _cleanup_free_ char *s = NULL;
124
125 if (pid_get_comm(PTR_TO_PID(p), &s) >= 0)
126 r = strextendf_with_separator(&lst_child, ", ", PID_FMT " (%s)", PTR_TO_PID(p), s);
127 else
128 r = strextendf_with_separator(&lst_child, ", ", PID_FMT, PTR_TO_PID(p));
129 if (r < 0)
130 return (void) log_oom_warning();
131 }
132
133 if (isempty(lst_child))
134 return;
135
136 log_warning("Waiting for process: %s", lst_child);
137 }
138
139 static int wait_for_children(Set *pids, sigset_t *mask, usec_t timeout) {
140 usec_t until, date_log_child, n;
141
142 assert(mask);
143
144 /* Return the number of children remaining in the pids set: That correspond to the number
145 * of processes still "alive" after the timeout */
146
147 if (set_isempty(pids))
148 return 0;
149
150 n = now(CLOCK_MONOTONIC);
151 until = usec_add(n, timeout);
152 date_log_child = usec_add(n, 10u * USEC_PER_SEC);
153 if (date_log_child > until)
154 date_log_child = usec_add(n, timeout / 2u);
155
156 for (;;) {
157 struct timespec ts;
158 int k;
159 void *p;
160
161 /* First, let the kernel inform us about killed
162 * children. Most processes will probably be our
163 * children, but some are not (might be our
164 * grandchildren instead...). */
165 for (;;) {
166 pid_t pid;
167
168 pid = waitpid(-1, NULL, WNOHANG);
169 if (pid == 0)
170 break;
171 if (pid < 0) {
172 if (errno == ECHILD)
173 break;
174
175 return log_error_errno(errno, "waitpid() failed: %m");
176 }
177
178 (void) set_remove(pids, PID_TO_PTR(pid));
179 }
180
181 /* Now explicitly check who might be remaining, who
182 * might not be our child. */
183 SET_FOREACH(p, pids) {
184
185 /* kill(pid, 0) sends no signal, but it tells
186 * us whether the process still exists. */
187 if (kill(PTR_TO_PID(p), 0) == 0)
188 continue;
189
190 if (errno != ESRCH)
191 continue;
192
193 set_remove(pids, p);
194 }
195
196 if (set_isempty(pids))
197 return 0;
198
199 n = now(CLOCK_MONOTONIC);
200 if (date_log_child > 0 && n >= date_log_child) {
201 log_children_not_yet_killed(pids);
202 /* Log the children not yet killed only once */
203 date_log_child = 0;
204 }
205
206 if (n >= until)
207 return set_size(pids);
208
209 if (date_log_child > 0)
210 timespec_store(&ts, MIN(until - n, date_log_child - n));
211 else
212 timespec_store(&ts, until - n);
213
214 k = sigtimedwait(mask, NULL, &ts);
215 if (k != SIGCHLD) {
216
217 if (k < 0 && errno != EAGAIN)
218 return log_error_errno(errno, "sigtimedwait() failed: %m");
219
220 if (k >= 0)
221 log_warning("sigtimedwait() returned unexpected signal.");
222 }
223 }
224 }
225
226 static int killall(int sig, Set *pids, bool send_sighup) {
227 _cleanup_closedir_ DIR *dir = NULL;
228 int n_killed = 0, r;
229
230 /* Send the specified signal to all remaining processes, if not excluded by ignore_proc().
231 * Returns the number of processes to which the specified signal was sent */
232
233 r = proc_dir_open(&dir);
234 if (r < 0)
235 return log_warning_errno(r, "Failed to open %s: %m", "/proc/");
236
237 for (;;) {
238 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
239
240 r = proc_dir_read_pidref(dir, &pidref);
241 if (r < 0)
242 return log_warning_errno(r, "Failed to enumerate /proc/: %m");
243 if (r == 0)
244 break;
245
246 if (ignore_proc(&pidref, sig == SIGKILL && !in_initrd()))
247 continue;
248
249 if (sig == SIGKILL) {
250 _cleanup_free_ char *s = NULL;
251
252 (void) pidref_get_comm(&pidref, &s);
253 log_notice("Sending SIGKILL to PID "PID_FMT" (%s).", pidref.pid, strna(s));
254 }
255
256 r = pidref_kill(&pidref, sig);
257 if (r < 0) {
258 if (r != -ESRCH)
259 log_warning_errno(errno, "Could not kill " PID_FMT ", ignoring: %m", pidref.pid);
260 } else {
261 n_killed++;
262 if (pids) {
263 r = set_put(pids, PID_TO_PTR(pidref.pid));
264 if (r < 0)
265 (void) log_oom_warning();
266 }
267 }
268
269 if (send_sighup) {
270 /* Optionally, also send a SIGHUP signal, but only if the process has a controlling
271 * tty. This is useful to allow handling of shells which ignore SIGTERM but react to
272 * SIGHUP. We do not send this to processes that have no controlling TTY since we
273 * don't want to trigger reloads of daemon processes. Also we make sure to only send
274 * this after SIGTERM so that SIGTERM is always first in the queue. */
275
276 if (get_ctty_devnr(pidref.pid, NULL) >= 0)
277 /* it's OK if the process is gone, just ignore the result */
278 (void) pidref_kill(&pidref, SIGHUP);
279 }
280 }
281
282 return n_killed;
283 }
284
285 int broadcast_signal(int sig, bool wait_for_exit, bool send_sighup, usec_t timeout) {
286 int n_children_left;
287 sigset_t mask, oldmask;
288 _cleanup_set_free_ Set *pids = NULL;
289
290 /* Send the specified signal to all remaining processes, if not excluded by ignore_proc().
291 * Return:
292 * - The number of processes still "alive" after the timeout (that should have been killed)
293 * if the function needs to wait for the end of the processes (wait_for_exit).
294 * - Otherwise, the number of processes to which the specified signal was sent */
295
296 if (wait_for_exit)
297 pids = set_new(NULL);
298
299 assert_se(sigemptyset(&mask) == 0);
300 assert_se(sigaddset(&mask, SIGCHLD) == 0);
301 assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
302
303 if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
304 log_warning_errno(errno, "kill(-1, SIGSTOP) failed: %m");
305
306 n_children_left = killall(sig, pids, send_sighup);
307
308 if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
309 log_warning_errno(errno, "kill(-1, SIGCONT) failed: %m");
310
311 if (wait_for_exit && n_children_left > 0)
312 n_children_left = wait_for_children(pids, &mask, timeout);
313
314 assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
315
316 return n_children_left;
317 }