Debian Codegraph @

src/systemctl/systemctl-start-special.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/kexec.h>
4 #include <unistd.h>
5
6 #include "sd-bus.h"
7
8 #include "bootspec.h"
9 #include "bus-error.h"
10 #include "bus-locator.h"
11 #include "efivars.h"
12 #include "fd-util.h"
13 #include "log.h"
14 #include "parse-util.h"
15 #include "path-util.h"
16 #include "process-util.h"
17 #include "reboot-util.h"
18 #include "runtime-scope.h"
19 #include "strv.h"
20 #include "systemctl.h"
21 #include "systemctl-logind.h"
22 #include "systemctl-start-special.h"
23 #include "systemctl-start-unit.h"
24 #include "systemctl-trivial-method.h"
25 #include "systemctl-util.h"
26
27 static int load_kexec_kernel(void) {
28 int r;
29
30 if (kexec_loaded()) {
31 if (arg_kernel_cmdline)
32 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
33 "--kernel-cmdline= specified but kexec kernel already loaded");
34 log_debug("Kexec kernel already loaded.");
35 return 0;
36 }
37
38 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
39 r = boot_config_load_auto(&config, NULL, NULL);
40 if (r == -ENOKEY)
41 /* The call doesn't log about ENOKEY, let's do so here. */
42 return log_error_errno(r,
43 "No kexec kernel loaded and autodetection failed.\n%s",
44 is_efi_boot()
45 ? "Cannot automatically load kernel: ESP mount point not found."
46 : "Automatic loading works only on systems booted with EFI.");
47 if (r < 0)
48 return r;
49
50 r = boot_config_select_special_entries(&config, /* skip_efivars= */ false);
51 if (r < 0)
52 return r;
53
54 const BootEntry *e = boot_config_default_entry(&config);
55 if (!e)
56 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
57 "No boot loader entry suitable as default, refusing to guess.");
58
59 log_debug("Found default boot loader entry in file \"%s\"", e->path);
60
61 if (!e->kernel)
62 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
63 "Boot entry does not refer to Linux kernel, which is not supported currently.");
64 if (strv_length(e->initrd) > 1)
65 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
66 "Boot entry specifies multiple initrds, which is not supported currently.");
67
68 _cleanup_free_ char *kernel = NULL;
69 kernel = path_join(e->root, e->kernel);
70 if (!kernel)
71 return log_oom();
72
73 _cleanup_free_ char *initrd = NULL;
74 if (!strv_isempty(e->initrd)) {
75 initrd = path_join(e->root, e->initrd[0]);
76 if (!initrd)
77 return log_oom();
78 }
79
80 _cleanup_free_ char *options = strv_join(e->options, " ");
81 if (!options)
82 return log_oom();
83
84 if (!isempty(arg_kernel_cmdline) && !strextend_with_separator(&options, " ", arg_kernel_cmdline))
85 return log_oom();
86
87 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
88 "%s %s kernel=\"%s\" cmdline=\"%s\"%s%s%s",
89 arg_dry_run ? "Would call" : "Calling",
90 HAVE_KEXEC_FILE_LOAD_SYSCALL ? "kexec_file_load()" : "kexec",
91 kernel,
92 options,
93 initrd ? " initrd=\"" : "", strempty(initrd), initrd ? "\"" : "");
94 if (arg_dry_run)
95 return 0;
96
97 #if HAVE_KEXEC_FILE_LOAD_SYSCALL
98 _cleanup_close_ int kernel_fd = open(kernel, O_RDONLY|O_CLOEXEC);
99 if (kernel_fd < 0)
100 return log_error_errno(errno, "Failed to open kernel '%s': %m", kernel);
101
102 _cleanup_close_ int initrd_fd = -EBADF;
103 if (initrd) {
104 initrd_fd = open(initrd, O_RDONLY|O_CLOEXEC);
105 if (initrd_fd < 0)
106 return log_error_errno(errno, "Failed to open initrd '%s': %m", initrd);
107 }
108
109 unsigned long flags = initrd ? 0 : KEXEC_FILE_NO_INITRAMFS;
110
111 if (kexec_file_load(kernel_fd, initrd_fd, strlen(options) + 1, options, flags) >= 0)
112 return 0;
113
114 int saved_errno = errno;
115
116 if (IN_SET(saved_errno, ENOEXEC, EINVAL)) {
117 /* The kernel didn't recognize the image format. Try decompressing or extracting the
118 * kernel (e.g. compressed Image, ZBOOT PE, or UKI) and loading again.
119 *
120 * Most architectures' kexec_file_load() returns ENOEXEC when no image loader matches
121 * (the default behavior of kexec_image_probe_default()), but arm64's image_probe()
122 * returns EINVAL for an unrecognized magic. Accept both, otherwise `systemctl kexec`
123 * of a UKI never reaches the extraction path on arm64. */
124 log_debug_errno(saved_errno, "Kernel rejected image, trying decompression/extraction: %m");
125
126 _cleanup_close_ int extracted_kernel_fd = -EBADF, extracted_initrd_fd = -EBADF;
127 r = kexec_maybe_decompress_kernel(
128 kernel, kernel_fd, &extracted_kernel_fd,
129 initrd_fd >= 0 ? NULL : &extracted_initrd_fd);
130 if (r < 0)
131 log_debug_errno(r, "Failed to decompress/extract kernel image, ignoring: %m");
132 else if (r > 0) {
133 int final_initrd_fd = initrd_fd >= 0 ? initrd_fd : extracted_initrd_fd;
134 unsigned long final_flags = final_initrd_fd >= 0 ? 0 : KEXEC_FILE_NO_INITRAMFS;
135
136 if (kexec_file_load(extracted_kernel_fd, final_initrd_fd, strlen(options) + 1, options, final_flags) >= 0)
137 return 0;
138
139 saved_errno = errno;
140 }
141 }
142
143 log_debug_errno(saved_errno, "kexec_file_load() failed, falling back to " KEXEC " binary: %m");
144 #endif
145
146 /* Fall back to kexec binary for architectures without kexec_file_load() or when the
147 * syscall fails (e.g. the kernel's kexec handler doesn't support this image format
148 * but kexec-tools might via the older kexec_load() code path). */
149 if (access(KEXEC, X_OK) < 0)
150 return log_error_errno(errno, KEXEC " is not available: %m");
151
152 r = pidref_safe_fork(
153 "(kexec)",
154 FORK_WAIT|FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG,
155 /* ret= */ NULL);
156 if (r < 0)
157 return r;
158 if (r == 0) {
159 const char* const args[] = {
160 KEXEC,
161 "--load", kernel,
162 "--append", options,
163 initrd ? "--initrd" : NULL, initrd,
164 NULL
165 };
166
167 /* Child */
168 execv(args[0], (char * const *) args);
169 _exit(EXIT_FAILURE);
170 }
171
172 return 0;
173 }
174
175 static int set_exit_code(uint8_t code) {
176 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
177 sd_bus *bus;
178 int r;
179
180 r = acquire_bus(BUS_MANAGER, &bus);
181 if (r < 0)
182 return r;
183
184 r = bus_call_method(bus, bus_systemd_mgr, "SetExitCode", &error, NULL, "y", code);
185 if (r < 0)
186 return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r));
187
188 return 0;
189 }
190
191 int verb_start_special(int argc, char *argv[], uintptr_t data, void *userdata) {
192 bool termination_action; /* An action that terminates the system, can be performed also by signal. */
193 enum action a;
194 int r;
195
196 assert(argv);
197
198 a = verb_to_action(argv[0]);
199
200 r = logind_check_inhibitors(a);
201 if (r < 0)
202 return r;
203
204 if (arg_force >= 2) {
205 r = must_be_root();
206 if (r < 0)
207 return r;
208 }
209
210 termination_action = IN_SET(a, ACTION_HALT, ACTION_POWEROFF, ACTION_REBOOT);
211
212 if (termination_action) {
213 r = prepare_firmware_setup();
214 if (r < 0)
215 return r;
216
217 r = prepare_boot_loader_menu();
218 if (r < 0)
219 return r;
220
221 r = prepare_boot_loader_entry();
222 if (r < 0)
223 return r;
224 }
225
226 if (arg_reboot_argument && IN_SET(a, ACTION_HALT, ACTION_POWEROFF, ACTION_REBOOT, ACTION_KEXEC)) {
227 /* If we are going through an action that involves systemd-shutdown, let's set the reboot
228 * parameter, even if it's not a regular reboot. After all we nowadays send the string to
229 * our supervisor via sd_notify() too. */
230 r = update_reboot_parameter_and_warn(arg_reboot_argument, /* keep= */ false);
231 if (r < 0)
232 return r;
233 }
234
235 if (a == ACTION_KEXEC) {
236 r = load_kexec_kernel();
237 if (r < 0 && arg_force >= 1)
238 log_notice("Failed to load kexec kernel, continuing without.");
239 else if (r < 0)
240 return r;
241
242 } else if (a == ACTION_EXIT && argc > 1) {
243 uint8_t code;
244
245 /* If the exit code is not given on the command line, don't reset it to zero: just keep it as
246 * it might have been set previously. */
247
248 r = safe_atou8(argv[1], &code);
249 if (r < 0)
250 return log_error_errno(r, "Invalid exit code.");
251
252 r = set_exit_code(code);
253 if (r < 0)
254 return r;
255 }
256
257 if (termination_action && arg_force >= 2)
258 return halt_now(a);
259
260 if (arg_force >= 1 &&
261 (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT)))
262 r = verb_trivial_method(argc, argv, data, userdata);
263 else {
264 /* First try logind, to allow authentication with polkit */
265 switch (a) {
266
267 case ACTION_POWEROFF:
268 case ACTION_REBOOT:
269 case ACTION_KEXEC:
270 case ACTION_HALT:
271 case ACTION_SOFT_REBOOT:
272 if (arg_when == 0) {
273 r = logind_reboot(a);
274 if (r >= 0 || IN_SET(r, -EACCES, -EOPNOTSUPP, -EINPROGRESS))
275 /* The latter indicates that the requested operation requires auth,
276 * is not supported or already in progress, in which cases we ignore the error. */
277 return r;
278 } else {
279 r = logind_schedule_shutdown(a);
280 if (r != -ENOSYS)
281 return r;
282 }
283
284 /* On all other errors, try low-level operation. In order to minimize the difference
285 * between operation with and without logind, we explicitly enable non-blocking mode
286 * for this, as logind's shutdown operations are always non-blocking. */
287 arg_no_block = true;
288 break;
289
290 case ACTION_SUSPEND:
291 case ACTION_HIBERNATE:
292 case ACTION_HYBRID_SLEEP:
293 case ACTION_SUSPEND_THEN_HIBERNATE:
294
295 /* For sleep operations, do not automatically fall back to low-level operation for
296 * errors other than logind not available. There's a high chance that logind did
297 * some extra sanity check and that didn't pass. */
298 r = logind_reboot(a);
299 if (r >= 0 || (r != -ENOSYS && arg_force == 0))
300 return r;
301
302 arg_no_block = true;
303 break;
304
305 case ACTION_SLEEP:
306 return logind_reboot(a);
307
308 case ACTION_EXIT:
309 /* Since exit is so close in behaviour to power-off/reboot, let's also make
310 * it asynchronous, in order to not confuse the user needlessly with unexpected
311 * behaviour. */
312 arg_no_block = true;
313 break;
314
315 default:
316 ;
317 }
318
319 r = verb_start(argc, argv, data, userdata);
320 }
321
322 if (termination_action && arg_force < 2 &&
323 IN_SET(r, -ENOENT, -ETIMEDOUT))
324 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
325
326 return r;
327 }
328
329 int verb_start_system_special(int argc, char *argv[], uintptr_t data, void *userdata) {
330 /* Like start_special above, but raises an error when running in user mode */
331
332 if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
333 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
334 "Bad action for %s mode.",
335 runtime_scope_cmdline_option_to_string(arg_runtime_scope));
336
337 return verb_start_special(argc, argv, data, userdata);
338 }