]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/fsck/fsck.c
tree-wide: set FORK_RLIMIT_NOFILE_SAFE flag
[thirdparty/systemd.git] / src / fsck / fsck.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2014 Holger Hans Peter Freyther
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <stdbool.h>
9 #include <sys/file.h>
10 #include <sys/prctl.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13
14 #include "sd-bus.h"
15 #include "sd-device.h"
16
17 #include "alloc-util.h"
18 #include "bus-common-errors.h"
19 #include "bus-error.h"
20 #include "bus-util.h"
21 #include "device-util.h"
22 #include "fd-util.h"
23 #include "fs-util.h"
24 #include "fsck-util.h"
25 #include "main-func.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "proc-cmdline.h"
29 #include "process-util.h"
30 #include "signal-util.h"
31 #include "socket-util.h"
32 #include "special.h"
33 #include "stdio-util.h"
34
35 static bool arg_skip = false;
36 static bool arg_force = false;
37 static bool arg_show_progress = false;
38 static const char *arg_repair = "-a";
39
40 static void start_target(const char *target, const char *mode) {
41 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
42 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
43 int r;
44
45 assert(target);
46
47 r = bus_connect_system_systemd(&bus);
48 if (r < 0) {
49 log_error_errno(r, "Failed to get D-Bus connection: %m");
50 return;
51 }
52
53 log_info("Requesting %s/start/%s", target, mode);
54
55 /* Start this unit only if we can replace basic.target with it */
56 r = sd_bus_call_method(bus,
57 "org.freedesktop.systemd1",
58 "/org/freedesktop/systemd1",
59 "org.freedesktop.systemd1.Manager",
60 "StartUnitReplace",
61 &error,
62 NULL,
63 "sss", "basic.target", target, mode);
64
65 /* Don't print a warning if we aren't called during startup */
66 if (r < 0 && !sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_JOB))
67 log_error("Failed to start unit: %s", bus_error_message(&error, r));
68 }
69
70 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
71 int r;
72
73 assert(key);
74
75 if (streq(key, "fsck.mode")) {
76
77 if (proc_cmdline_value_missing(key, value))
78 return 0;
79
80 if (streq(value, "auto"))
81 arg_force = arg_skip = false;
82 else if (streq(value, "force"))
83 arg_force = true;
84 else if (streq(value, "skip"))
85 arg_skip = true;
86 else
87 log_warning("Invalid fsck.mode= parameter '%s'. Ignoring.", value);
88
89 } else if (streq(key, "fsck.repair")) {
90
91 if (proc_cmdline_value_missing(key, value))
92 return 0;
93
94 if (streq(value, "preen"))
95 arg_repair = "-a";
96 else {
97 r = parse_boolean(value);
98 if (r > 0)
99 arg_repair = "-y";
100 else if (r == 0)
101 arg_repair = "-n";
102 else
103 log_warning("Invalid fsck.repair= parameter '%s'. Ignoring.", value);
104 }
105 }
106
107 #if HAVE_SYSV_COMPAT
108 else if (streq(key, "fastboot") && !value) {
109 log_warning("Please pass 'fsck.mode=skip' rather than 'fastboot' on the kernel command line.");
110 arg_skip = true;
111
112 } else if (streq(key, "forcefsck") && !value) {
113 log_warning("Please pass 'fsck.mode=force' rather than 'forcefsck' on the kernel command line.");
114 arg_force = true;
115 }
116 #endif
117
118 return 0;
119 }
120
121 static void test_files(void) {
122
123 #if HAVE_SYSV_COMPAT
124 if (access("/fastboot", F_OK) >= 0) {
125 log_error("Please pass 'fsck.mode=skip' on the kernel command line rather than creating /fastboot on the root file system.");
126 arg_skip = true;
127 }
128
129 if (access("/forcefsck", F_OK) >= 0) {
130 log_error("Please pass 'fsck.mode=force' on the kernel command line rather than creating /forcefsck on the root file system.");
131 arg_force = true;
132 }
133 #endif
134
135 arg_show_progress = access("/run/systemd/show-status", F_OK) >= 0;
136 }
137
138 static double percent(int pass, unsigned long cur, unsigned long max) {
139 /* Values stolen from e2fsck */
140
141 static const int pass_table[] = {
142 0, 70, 90, 92, 95, 100
143 };
144
145 if (pass <= 0)
146 return 0.0;
147
148 if ((unsigned) pass >= ELEMENTSOF(pass_table) || max == 0)
149 return 100.0;
150
151 return (double) pass_table[pass-1] +
152 ((double) pass_table[pass] - (double) pass_table[pass-1]) *
153 (double) cur / (double) max;
154 }
155
156 static int process_progress(int fd, FILE* console) {
157 _cleanup_fclose_ FILE *f = NULL;
158 usec_t last = 0;
159 bool locked = false;
160 int clear = 0, r;
161
162 /* No progress pipe to process? Then we are a NOP. */
163 if (fd < 0)
164 return 0;
165
166 f = fdopen(fd, "r");
167 if (!f) {
168 safe_close(fd);
169 return log_debug_errno(errno, "Failed to use pipe: %m");
170 }
171
172 for (;;) {
173 int pass;
174 unsigned long cur, max;
175 _cleanup_free_ char *device = NULL;
176 double p;
177 usec_t t;
178
179 if (fscanf(f, "%i %lu %lu %ms", &pass, &cur, &max, &device) != 4) {
180
181 if (ferror(f))
182 r = log_warning_errno(errno, "Failed to read from progress pipe: %m");
183 else if (feof(f))
184 r = 0;
185 else
186 r = log_warning_errno(SYNTHETIC_ERRNO(errno), "Failed to parse progress pipe data");
187
188 break;
189 }
190
191 /* Only show one progress counter at max */
192 if (!locked) {
193 if (flock(fileno(console), LOCK_EX|LOCK_NB) < 0)
194 continue;
195
196 locked = true;
197 }
198
199 /* Only update once every 50ms */
200 t = now(CLOCK_MONOTONIC);
201 if (last + 50 * USEC_PER_MSEC > t)
202 continue;
203
204 last = t;
205
206 p = percent(pass, cur, max);
207 r = fprintf(console, "\r%s: fsck %3.1f%% complete...\r", device, p);
208 if (r < 0)
209 return -EIO; /* No point in continuing if something happened to our output stream */
210
211 fflush(console);
212 clear = MAX(clear, r);
213 }
214
215 if (clear > 0) {
216 fputc('\r', console);
217 for (int j = 0; j < clear; j++)
218 fputc(' ', console);
219 fputc('\r', console);
220 fflush(console);
221 }
222
223 return r;
224 }
225
226 static int fsck_progress_socket(void) {
227 _cleanup_close_ int fd = -EBADF;
228 int r;
229
230 fd = socket(AF_UNIX, SOCK_STREAM, 0);
231 if (fd < 0)
232 return log_warning_errno(errno, "socket(): %m");
233
234 r = connect_unix_path(fd, AT_FDCWD, "/run/systemd/fsck.progress");
235 if (r < 0)
236 return log_full_errno(IN_SET(r, -ECONNREFUSED, -ENOENT) ? LOG_DEBUG : LOG_WARNING,
237 r, "Failed to connect to progress socket, ignoring: %m");
238
239 return TAKE_FD(fd);
240 }
241
242 static int run(int argc, char *argv[]) {
243 _cleanup_close_pair_ int progress_pipe[2] = PIPE_EBADF;
244 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
245 _cleanup_free_ char *dpath = NULL;
246 _cleanup_fclose_ FILE *console = NULL;
247 const char *device, *type;
248 bool root_directory;
249 struct stat st;
250 int r, exit_status;
251 pid_t pid;
252
253 log_setup();
254
255 if (argc > 2)
256 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
257 "This program expects one or no arguments.");
258
259 umask(0022);
260
261 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
262 if (r < 0)
263 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
264
265 test_files();
266
267 if (!arg_force && arg_skip)
268 return 0;
269
270 if (argc > 1) {
271 dpath = strdup(argv[1]);
272 if (!dpath)
273 return log_oom();
274
275 device = dpath;
276
277 if (stat(device, &st) < 0)
278 return log_error_errno(errno, "Failed to stat %s: %m", device);
279
280 if (!S_ISBLK(st.st_mode))
281 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
282 "%s is not a block device.",
283 device);
284
285 r = sd_device_new_from_stat_rdev(&dev, &st);
286 if (r < 0)
287 return log_error_errno(r, "Failed to detect device %s: %m", device);
288
289 root_directory = false;
290 } else {
291 struct timespec times[2];
292
293 /* Find root device */
294
295 if (stat("/", &st) < 0)
296 return log_error_errno(errno, "Failed to stat() the root directory: %m");
297
298 /* Virtual root devices don't need an fsck */
299 if (major(st.st_dev) == 0) {
300 log_debug("Root directory is virtual or btrfs, skipping check.");
301 return 0;
302 }
303
304 /* check if we are already writable */
305 times[0] = st.st_atim;
306 times[1] = st.st_mtim;
307
308 if (utimensat(AT_FDCWD, "/", times, 0) == 0) {
309 log_info("Root directory is writable, skipping check.");
310 return 0;
311 }
312
313 r = sd_device_new_from_devnum(&dev, 'b', st.st_dev);
314 if (r < 0)
315 return log_error_errno(r, "Failed to detect root device: %m");
316
317 r = sd_device_get_devname(dev, &device);
318 if (r < 0)
319 return log_device_error_errno(dev, r, "Failed to detect device node of root directory: %m");
320
321 root_directory = true;
322 }
323
324 if (sd_device_get_property_value(dev, "ID_FS_TYPE", &type) >= 0) {
325 r = fsck_exists_for_fstype(type);
326 if (r < 0)
327 log_device_warning_errno(dev, r, "Couldn't detect if fsck.%s may be used, proceeding: %m", type);
328 else if (r == 0) {
329 log_device_info(dev, "fsck.%s doesn't exist, not checking file system.", type);
330 return 0;
331 }
332 } else {
333 r = fsck_exists();
334 if (r < 0)
335 log_device_warning_errno(dev, r, "Couldn't detect if the fsck command may be used, proceeding: %m");
336 else if (r == 0) {
337 log_device_info(dev, "The fsck command does not exist, not checking file system.");
338 return 0;
339 }
340 }
341
342 console = fopen("/dev/console", "we");
343 if (console &&
344 arg_show_progress &&
345 pipe(progress_pipe) < 0)
346 return log_error_errno(errno, "pipe(): %m");
347
348 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE, &pid);
349 if (r < 0)
350 return r;
351 if (r == 0) {
352 char dash_c[STRLEN("-C") + DECIMAL_STR_MAX(int) + 1];
353 int progress_socket = -1;
354 const char *cmdline[9];
355 int i = 0;
356
357 /* Child */
358
359 /* Close the reading side of the progress pipe */
360 progress_pipe[0] = safe_close(progress_pipe[0]);
361
362 /* Try to connect to a progress management daemon, if there is one */
363 progress_socket = fsck_progress_socket();
364 if (progress_socket >= 0) {
365 /* If this worked we close the progress pipe early, and just use the socket */
366 progress_pipe[1] = safe_close(progress_pipe[1]);
367 xsprintf(dash_c, "-C%i", progress_socket);
368 } else if (progress_pipe[1] >= 0) {
369 /* Otherwise if we have the progress pipe to our own local handle, we use it */
370 xsprintf(dash_c, "-C%i", progress_pipe[1]);
371 } else
372 dash_c[0] = 0;
373
374 cmdline[i++] = "/sbin/fsck";
375 cmdline[i++] = arg_repair;
376 cmdline[i++] = "-T";
377
378 /*
379 * Since util-linux v2.25 fsck uses /run/fsck/<diskname>.lock files.
380 * The previous versions use flock for the device and conflict with
381 * udevd, see https://bugs.freedesktop.org/show_bug.cgi?id=79576#c5
382 */
383 cmdline[i++] = "-l";
384
385 if (!root_directory)
386 cmdline[i++] = "-M";
387
388 if (arg_force)
389 cmdline[i++] = "-f";
390
391 if (!isempty(dash_c))
392 cmdline[i++] = dash_c;
393
394 cmdline[i++] = device;
395 cmdline[i++] = NULL;
396
397 execv(cmdline[0], (char**) cmdline);
398 _exit(FSCK_OPERATIONAL_ERROR);
399 }
400
401 if (console) {
402 progress_pipe[1] = safe_close(progress_pipe[1]);
403 (void) process_progress(TAKE_FD(progress_pipe[0]), console);
404 }
405
406 exit_status = wait_for_terminate_and_check("fsck", pid, WAIT_LOG_ABNORMAL);
407 if (exit_status < 0)
408 return exit_status;
409 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
410 log_error("fsck failed with exit status %i.", exit_status);
411
412 if ((exit_status & FSCK_SYSTEM_SHOULD_REBOOT) && root_directory) {
413 /* System should be rebooted. */
414 start_target(SPECIAL_REBOOT_TARGET, "replace-irreversibly");
415 return -EINVAL;
416 } else if (!(exit_status & (FSCK_SYSTEM_SHOULD_REBOOT | FSCK_ERRORS_LEFT_UNCORRECTED)))
417 log_warning("Ignoring error.");
418 }
419
420 if (exit_status & FSCK_ERROR_CORRECTED)
421 (void) touch("/run/systemd/quotacheck");
422
423 return !!(exit_status & (FSCK_SYSTEM_SHOULD_REBOOT | FSCK_ERRORS_LEFT_UNCORRECTED));
424 }
425
426 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);