Debian Codegraph @

src/fsck/fsck.c

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