1 /*
2  * fsck --- A generic, parallelizing front-end for the fsck program.
3  * It will automatically try to run fsck programs in parallel if the
4  * devices are on separate spindles.  It is based on the same ideas as
5  * the generic front end for fsck by David Engel and Fred van Kempen,
6  * but it has been completely rewritten from scratch to support
7  * parallel execution.
8  *
9  * Written by Theodore Ts'o, <tytso@mit.edu>
10  *
11  * Miquel van Smoorenburg (miquels@drinkel.ow.org) 20-Oct-1994:
12  *   o Changed -t fstype to behave like with mount when -A (all file
13  *     systems) or -M (like mount) is specified.
14  *   o fsck looks if it can find the fsck.type program to decide
15  *     if it should ignore the fs type. This way more fsck programs
16  *     can be added without changing this front-end.
17  *   o -R flag skip root file system.
18  *
19  * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
20  *	         2001, 2002, 2003, 2004, 2005 by  Theodore Ts'o.
21  *
22  * Copyright (C) 2009-2014 Karel Zak <kzak@redhat.com>
23  *
24  * This file may be redistributed under the terms of the GNU Public
25  * License.
26  */
27 
28 #define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */
29 
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
33 #include <sys/file.h>
34 #include <fcntl.h>
35 #include <limits.h>
36 #include <stdio.h>
37 #include <ctype.h>
38 #include <string.h>
39 #include <time.h>
40 #include <stdlib.h>
41 #include <paths.h>
42 #include <unistd.h>
43 #include <errno.h>
44 #include <signal.h>
45 #include <dirent.h>
46 #include <sys/resource.h>
47 #include <sys/time.h>
48 #include <blkid.h>
49 #include <libmount.h>
50 
51 #include "nls.h"
52 #include "pathnames.h"
53 #include "exitcodes.h"
54 #include "c.h"
55 #include "fileutils.h"
56 #include "monotonic.h"
57 #include "strutils.h"
58 
59 #define XALLOC_EXIT_CODE	FSCK_EX_ERROR
60 #include "xalloc.h"
61 
62 #define CLOSE_EXIT_CODE		FSCK_EX_ERROR
63 #include "closestream.h"
64 
65 #ifndef DEFAULT_FSTYPE
66 # define DEFAULT_FSTYPE	"ext2"
67 #endif
68 
69 #define MAX_DEVICES 32
70 #define MAX_ARGS 32
71 
72 #define FSCK_RUNTIME_DIRNAME	"/run/fsck"
73 
74 static const char *ignored_types[] = {
75 	"ignore",
76 	"iso9660",
77 	"sw",
78 	NULL
79 };
80 
81 static const char *really_wanted[] = {
82 	"minix",
83 	"ext2",
84 	"ext3",
85 	"ext4",
86 	"ext4dev",
87 	"jfs",
88 	"reiserfs"
89 };
90 
91 /*
92  * Internal structure for mount table entries.
93  */
94 struct fsck_fs_data
95 {
96 	const char	*device;
97 	dev_t		disk;
98 	unsigned int	stacked:1,
99 			done:1,
100 			eval_device:1;
101 };
102 
103 /*
104  * Structure to allow exit codes to be stored
105  */
106 struct fsck_instance {
107 	int	pid;
108 	int	flags;		/* FLAG_{DONE|PROGRESS} */
109 
110 	int	lock;		/* flock()ed lockpath file descriptor or -1 */
111 	char	*lockpath;	/* /run/fsck/<diskname>.lock or NULL */
112 
113 	int	exit_status;
114 	struct timeval start_time;
115 	struct timeval end_time;
116 	char *	prog;
117 	char *	type;
118 
119 	struct rusage rusage;
120 	struct libmnt_fs *fs;
121 	struct fsck_instance *next;
122 };
123 
124 #define FLAG_DONE 1
125 #define FLAG_PROGRESS 2
126 
127 /*
128  * Global variables for options
129  */
130 static char *devices[MAX_DEVICES];
131 static char *args[MAX_ARGS];
132 static int num_devices, num_args;
133 
134 static int lockdisk;
135 static int verbose;
136 static int doall;
137 static int noexecute;
138 static int serialize;
139 static int skip_root;
140 static int ignore_mounted;
141 static int notitle;
142 static int parallel_root;
143 static int progress;
144 static int progress_fd;
145 static int force_all_parallel;
146 static int report_stats;
147 static FILE *report_stats_file;
148 
149 static int num_running;
150 static int max_running;
151 
152 static volatile int cancel_requested;
153 static int kill_sent;
154 static char *fstype;
155 static struct fsck_instance *instance_list;
156 
157 #define FSCK_DEFAULT_PATH "/sbin"
158 static char *fsck_path;
159 
160 
161 /* parsed fstab and mtab */
162 static struct libmnt_table *fstab, *mtab;
163 static struct libmnt_cache *mntcache;
164 
165 static int count_slaves(dev_t disk);
166 
string_to_int(const char * s)167 static int string_to_int(const char *s)
168 {
169 	long l;
170 	char *p;
171 
172 	l = strtol(s, &p, 0);
173 	if (*p || l == LONG_MIN || l == LONG_MAX || l < 0 || l > INT_MAX)
174 		return -1;
175 
176 	return (int) l;
177 }
178 
179 /* Do we really really want to check this fs? */
fs_check_required(const char * type)180 static int fs_check_required(const char *type)
181 {
182 	size_t i;
183 
184 	for(i = 0; i < ARRAY_SIZE(really_wanted); i++) {
185 		if (strcmp(type, really_wanted[i]) == 0)
186 			return 1;
187 	}
188 
189 	return 0;
190 }
191 
is_mounted(struct libmnt_fs * fs)192 static int is_mounted(struct libmnt_fs *fs)
193 {
194 	int rc;
195 	const char *src;
196 
197 	src = mnt_fs_get_source(fs);
198 	if (!src)
199 		return 0;
200 	if (!mntcache)
201 		mntcache = mnt_new_cache();
202 	if (!mtab) {
203 		mtab = mnt_new_table();
204 		if (!mtab)
205 			err(FSCK_EX_ERROR, ("failed to initialize libmount table"));
206 		mnt_table_set_cache(mtab, mntcache);
207 		mnt_table_parse_mtab(mtab, NULL);
208 	}
209 
210 	rc = mnt_table_find_source(mtab, src, MNT_ITER_BACKWARD) ? 1 : 0;
211 	if (verbose) {
212 		if (rc)
213 			printf(_("%s is mounted\n"), src);
214 		else
215 			printf(_("%s is not mounted\n"), src);
216 	}
217 	return rc;
218 }
219 
220 static int ignore(struct libmnt_fs *);
221 
fs_create_data(struct libmnt_fs * fs)222 static struct fsck_fs_data *fs_create_data(struct libmnt_fs *fs)
223 {
224 	struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
225 
226 	if (!data) {
227 		data = xcalloc(1, sizeof(*data));
228 		mnt_fs_set_userdata(fs, data);
229 	}
230 	return data;
231 }
232 
233 /*
234  * fs from fstab might contains real device name as well as symlink,
235  * LABEL or UUID, this function returns canonicalized result.
236  */
fs_get_device(struct libmnt_fs * fs)237 static const char *fs_get_device(struct libmnt_fs *fs)
238 {
239 	struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
240 
241 	if (!data || !data->eval_device) {
242 		const char *spec = mnt_fs_get_source(fs);
243 
244 		if (!data)
245 			data = fs_create_data(fs);
246 
247 		data->eval_device = 1;
248 		data->device = mnt_resolve_spec(spec, mnt_table_get_cache(fstab));
249 		if (!data->device)
250 			data->device = xstrdup(spec);
251 	}
252 
253 	return data->device;
254 }
255 
fs_get_disk(struct libmnt_fs * fs,int check)256 static dev_t fs_get_disk(struct libmnt_fs *fs, int check)
257 {
258 	struct fsck_fs_data *data;
259 	const char *device;
260 	struct stat st;
261 
262 	data = mnt_fs_get_userdata(fs);
263 	if (data && data->disk)
264 		return data->disk;
265 
266 	if (!check)
267 		return 0;
268 
269 	if (mnt_fs_is_netfs(fs) || mnt_fs_is_pseudofs(fs))
270 		return 0;
271 
272 	device = fs_get_device(fs);
273 	if (!device)
274 		return 0;
275 
276 	data = fs_create_data(fs);
277 
278 	if (!stat(device, &st) &&
279 	    !blkid_devno_to_wholedisk(st.st_rdev, NULL, 0, &data->disk)) {
280 
281 		if (data->disk)
282 			data->stacked = count_slaves(data->disk) > 0 ? 1 : 0;
283 		return data->disk;
284 	}
285 	return 0;
286 }
287 
fs_is_stacked(struct libmnt_fs * fs)288 static int fs_is_stacked(struct libmnt_fs *fs)
289 {
290 	struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
291 	return data ? data->stacked : 0;
292 }
293 
fs_is_done(struct libmnt_fs * fs)294 static int fs_is_done(struct libmnt_fs *fs)
295 {
296 	struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
297 	return data ? data->done : 0;
298 }
299 
fs_set_done(struct libmnt_fs * fs)300 static void fs_set_done(struct libmnt_fs *fs)
301 {
302 	struct fsck_fs_data *data = fs_create_data(fs);
303 
304 	if (data)
305 		data->done = 1;
306 }
307 
is_irrotational_disk(dev_t disk)308 static int is_irrotational_disk(dev_t disk)
309 {
310 	char path[PATH_MAX];
311 	FILE *f;
312 	int rc, x;
313 
314 
315 	rc = snprintf(path, sizeof(path),
316 			"/sys/dev/block/%d:%d/queue/rotational",
317 			major(disk), minor(disk));
318 
319 	if (rc < 0 || (unsigned int) rc >= sizeof(path))
320 		return 0;
321 
322 	f = fopen(path, "r");
323 	if (!f)
324 		return 0;
325 
326 	rc = fscanf(f, "%d", &x);
327 	if (rc != 1) {
328 		if (ferror(f))
329 			warn(_("cannot read %s"), path);
330 		else
331 			warnx(_("parse error: %s"), path);
332 	}
333 	fclose(f);
334 
335 	return rc == 1 ? !x : 0;
336 }
337 
lock_disk(struct fsck_instance * inst)338 static void lock_disk(struct fsck_instance *inst)
339 {
340 	dev_t disk = fs_get_disk(inst->fs, 1);
341 	char *diskpath = NULL, *diskname;
342 
343 	inst->lock = -1;
344 
345 	if (!disk || is_irrotational_disk(disk))
346 		goto done;
347 
348 	diskpath = blkid_devno_to_devname(disk);
349 	if (!diskpath)
350 		goto done;
351 
352 	if (access(FSCK_RUNTIME_DIRNAME, F_OK) != 0) {
353 		int rc = mkdir(FSCK_RUNTIME_DIRNAME,
354 				    S_IWUSR|
355 				    S_IRUSR|S_IRGRP|S_IROTH|
356 				    S_IXUSR|S_IXGRP|S_IXOTH);
357 		if (rc && errno != EEXIST) {
358 			warn(_("cannot create directory %s"),
359 					FSCK_RUNTIME_DIRNAME);
360 			goto done;
361 		}
362 	}
363 
364 	diskname = stripoff_last_component(diskpath);
365 	if (!diskname)
366 		diskname = diskpath;
367 
368 	xasprintf(&inst->lockpath, FSCK_RUNTIME_DIRNAME "/%s.lock", diskname);
369 
370 	if (verbose)
371 		printf(_("Locking disk by %s ... "), inst->lockpath);
372 
373 	inst->lock = open(inst->lockpath, O_RDONLY|O_CREAT|O_CLOEXEC,
374 				    S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
375 	if (inst->lock >= 0) {
376 		int rc = -1;
377 
378 		/* inform users that we're waiting on the lock */
379 		if (verbose &&
380 		    (rc = flock(inst->lock, LOCK_EX | LOCK_NB)) != 0 &&
381 		    errno == EWOULDBLOCK)
382 			printf(_("(waiting) "));
383 
384 		if (rc != 0 && flock(inst->lock, LOCK_EX) != 0) {
385 			close(inst->lock);			/* failed */
386 			inst->lock = -1;
387 		}
388 	}
389 
390 	if (verbose)
391 		/* TRANSLATORS: These are followups to "Locking disk...". */
392 		printf("%s.\n", inst->lock >= 0 ? _("succeeded") : _("failed"));
393 
394 
395 done:
396 	if (inst->lock < 0) {
397 		free(inst->lockpath);
398 		inst->lockpath = NULL;
399 	}
400 	free(diskpath);
401 }
402 
unlock_disk(struct fsck_instance * inst)403 static void unlock_disk(struct fsck_instance *inst)
404 {
405 	if (inst->lock < 0)
406 		return;
407 
408 	if (verbose)
409 		printf(_("Unlocking %s.\n"), inst->lockpath);
410 
411 	close(inst->lock);			/* unlock */
412 
413 	free(inst->lockpath);
414 
415 	inst->lock = -1;
416 	inst->lockpath = NULL;
417 }
418 
free_instance(struct fsck_instance * i)419 static void free_instance(struct fsck_instance *i)
420 {
421 	if (lockdisk)
422 		unlock_disk(i);
423 	free(i->prog);
424 	free(i->lockpath);
425 	mnt_unref_fs(i->fs);
426 	free(i);
427 }
428 
add_dummy_fs(const char * device)429 static struct libmnt_fs *add_dummy_fs(const char *device)
430 {
431 	struct libmnt_fs *fs = mnt_new_fs();
432 
433 	if (fs && mnt_fs_set_source(fs, device) == 0 &&
434 				  mnt_table_add_fs(fstab, fs) == 0) {
435 		mnt_unref_fs(fs);
436 		return fs;
437 	}
438 
439 	mnt_unref_fs(fs);
440 	err(FSCK_EX_ERROR, _("failed to setup description for %s"), device);
441 }
442 
fs_interpret_type(struct libmnt_fs * fs)443 static void fs_interpret_type(struct libmnt_fs *fs)
444 {
445 	const char *device;
446 	const char *type = mnt_fs_get_fstype(fs);
447 
448 	if (type && strcmp(type, "auto") != 0)
449 		return;
450 
451 	mnt_fs_set_fstype(fs, NULL);
452 
453 	device = fs_get_device(fs);
454 	if (device) {
455 		int ambi = 0;
456 		char *tp;
457 		struct libmnt_cache *cache = mnt_table_get_cache(fstab);
458 
459 		tp = mnt_get_fstype(device, &ambi, cache);
460 		if (!ambi)
461 			mnt_fs_set_fstype(fs, tp);
462 		if (!cache)
463 			free(tp);
464 	}
465 }
466 
parser_errcb(struct libmnt_table * tb,const char * filename,int line)467 static int parser_errcb(struct libmnt_table *tb __attribute__ ((__unused__)),
468 			const char *filename, int line)
469 {
470 	warnx(_("%s: parse error at line %d -- ignored"), filename, line);
471 	return 1;
472 }
473 
474 /*
475  * Load the filesystem database from /etc/fstab
476  */
load_fs_info(void)477 static void load_fs_info(void)
478 {
479 	const char *path;
480 
481 	fstab = mnt_new_table();
482 	if (!fstab)
483 		err(FSCK_EX_ERROR, ("failed to initialize libmount table"));
484 
485 	mnt_table_set_parser_errcb(fstab, parser_errcb);
486 	mnt_table_set_cache(fstab, mntcache);
487 
488 	errno = 0;
489 
490 	/*
491 	 * Let's follow libmount defaults if $FSTAB_FILE is not specified
492 	 */
493 	path = getenv("FSTAB_FILE");
494 
495 	if (mnt_table_parse_fstab(fstab, path)) {
496 		if (!path)
497 			path = mnt_get_fstab_path();
498 
499 		/* don't print error when there is no fstab at all */
500 		if (access(path, F_OK) == 0) {
501 			if (errno)
502 				warn(_("%s: failed to parse fstab"), path);
503 			else
504 				warnx(_("%s: failed to parse fstab"), path);
505 		}
506 	}
507 }
508 
509 /*
510  * Lookup filesys in /etc/fstab and return the corresponding entry.
511  * The @path has to be real path (no TAG) by mnt_resolve_spec().
512  */
lookup(char * path)513 static struct libmnt_fs *lookup(char *path)
514 {
515 	struct libmnt_fs *fs;
516 
517 	if (!path)
518 		return NULL;
519 
520 	fs = mnt_table_find_srcpath(fstab, path, MNT_ITER_FORWARD);
521 	if (!fs) {
522 		/*
523 		 * Maybe mountpoint has been specified on fsck command line.
524 		 * Yeah, crazy feature...
525 		 *
526 		 * Note that mnt_table_find_target() may canonicalize paths in
527 		 * the fstab to support symlinks. This is really unwanted,
528 		 * because readlink() on mountpoints may trigger automounts.
529 		 *
530 		 * So, disable the cache and compare the paths as strings
531 		 * without care about symlinks...
532 		 */
533 		mnt_table_set_cache(fstab, NULL);
534 		fs = mnt_table_find_target(fstab, path, MNT_ITER_FORWARD);
535 		mnt_table_set_cache(fstab, mntcache);
536 	}
537 	return fs;
538 }
539 
540 /* Find fsck program for a given fs type. */
find_fsck(const char * type,char ** progpath)541 static int find_fsck(const char *type, char **progpath)
542 {
543 	char *s;
544 	const char *tpl;
545 	char *prog = NULL;
546 	char *p = xstrdup(fsck_path);
547 	int rc;
548 
549 	/* Are we looking for a program or just a type? */
550 	tpl = (strncmp(type, "fsck.", 5) ? "%s/fsck.%s" : "%s/%s");
551 
552 	for(s = strtok(p, ":"); s; s = strtok(NULL, ":")) {
553 		xasprintf(&prog, tpl, s, type);
554 		if (access(prog, X_OK) == 0)
555 			break;
556 		free(prog);
557 		prog = NULL;
558 	}
559 
560 	free(p);
561 	rc = prog ? 1 : 0;
562 
563 	if (progpath)
564 		*progpath = prog;
565 	else
566 		free(prog);
567 
568 	return rc;
569 }
570 
progress_active(void)571 static int progress_active(void)
572 {
573 	struct fsck_instance *inst;
574 
575 	for (inst = instance_list; inst; inst = inst->next) {
576 		if (inst->flags & FLAG_DONE)
577 			continue;
578 		if (inst->flags & FLAG_PROGRESS)
579 			return 1;
580 	}
581 	return 0;
582 }
583 
584 /*
585  * Process run statistics for finished fsck instances.
586  *
587  * If report_stats is 0, do nothing, otherwise print a selection of
588  * interesting rusage statistics as well as elapsed wallclock time.
589  */
print_stats(struct fsck_instance * inst)590 static void print_stats(struct fsck_instance *inst)
591 {
592 	struct timeval delta;
593 
594 	if (!inst || !report_stats || noexecute)
595 		return;
596 
597 	timersub(&inst->end_time, &inst->start_time, &delta);
598 
599 	if (report_stats_file)
600 		fprintf(report_stats_file, "%s %d %ld "
601 					   "%ld.%06ld %ld.%06ld %ld.%06ld\n",
602 			fs_get_device(inst->fs),
603 			inst->exit_status,
604 			inst->rusage.ru_maxrss,
605 			(long)delta.tv_sec, (long)delta.tv_usec,
606 			(long)inst->rusage.ru_utime.tv_sec,
607 			(long)inst->rusage.ru_utime.tv_usec,
608 			(long)inst->rusage.ru_stime.tv_sec,
609 			(long)inst->rusage.ru_stime.tv_usec);
610 	else
611 		fprintf(stdout, "%s: status %d, rss %ld, "
612 				"real %ld.%06ld, user %ld.%06ld, sys %ld.%06ld\n",
613 			fs_get_device(inst->fs),
614 			inst->exit_status,
615 			inst->rusage.ru_maxrss,
616 			(long)delta.tv_sec, (long)delta.tv_usec,
617 			(long)inst->rusage.ru_utime.tv_sec,
618 			(long)inst->rusage.ru_utime.tv_usec,
619 			(long)inst->rusage.ru_stime.tv_sec,
620 			(long)inst->rusage.ru_stime.tv_usec);
621 }
622 
623 /*
624  * Execute a particular fsck program, and link it into the list of
625  * child processes we are waiting for.
626  */
execute(const char * progname,const char * progpath,const char * type,struct libmnt_fs * fs,int interactive)627 static int execute(const char *progname, const char *progpath,
628 		   const char *type, struct libmnt_fs *fs, int interactive)
629 {
630 	char *argv[80];
631 	int  argc, i;
632 	struct fsck_instance *inst, *p;
633 	pid_t	pid;
634 
635 	inst = xcalloc(1, sizeof(*inst));
636 
637 	argv[0] = xstrdup(progname);
638 	argc = 1;
639 
640 	for (i=0; i <num_args; i++)
641 		argv[argc++] = xstrdup(args[i]);
642 
643 	if (progress &&
644 	       ((strcmp(type, "ext2") == 0) ||
645 		(strcmp(type, "ext3") == 0) ||
646 		(strcmp(type, "ext4") == 0) ||
647 		(strcmp(type, "ext4dev") == 0))) {
648 
649 		char tmp[80];
650 		tmp[0] = 0;
651 		if (!progress_active()) {
652 			snprintf(tmp, 80, "-C%d", progress_fd);
653 			inst->flags |= FLAG_PROGRESS;
654 		} else if (progress_fd)
655 			snprintf(tmp, 80, "-C%d", progress_fd * -1);
656 		if (tmp[0])
657 			argv[argc++] = xstrdup(tmp);
658 	}
659 
660 	argv[argc++] = xstrdup(fs_get_device(fs));
661 	argv[argc] = NULL;
662 
663 	if (verbose || noexecute) {
664 		const char *tgt = mnt_fs_get_target(fs);
665 
666 		if (!tgt)
667 			tgt = fs_get_device(fs);
668 		printf("[%s (%d) -- %s] ", progpath, num_running, tgt);
669 		for (i=0; i < argc; i++)
670 			printf("%s ", argv[i]);
671 		printf("\n");
672 	}
673 
674 	mnt_ref_fs(fs);
675 	inst->fs = fs;
676 	inst->lock = -1;
677 
678 	if (lockdisk)
679 		lock_disk(inst);
680 
681 	/* Fork and execute the correct program. */
682 	if (noexecute)
683 		pid = -1;
684 	else if ((pid = fork()) < 0) {
685 		warn(_("fork failed"));
686 		free_instance(inst);
687 		return errno;
688 	} else if (pid == 0) {
689 		if (!interactive)
690 			close(0);
691 		execv(progpath, argv);
692 		err(FSCK_EX_ERROR, _("%s: execute failed"), progpath);
693 	}
694 
695 	for (i=0; i < argc; i++)
696 		free(argv[i]);
697 
698 	inst->pid = pid;
699 	inst->prog = xstrdup(progname);
700 	inst->type = xstrdup(type);
701 	gettime_monotonic(&inst->start_time);
702 	inst->next = NULL;
703 
704 	/*
705 	 * Find the end of the list, so we add the instance on at the end.
706 	 */
707 	for (p = instance_list; p && p->next; p = p->next);
708 
709 	if (p)
710 		p->next = inst;
711 	else
712 		instance_list = inst;
713 
714 	return 0;
715 }
716 
717 /*
718  * Send a signal to all outstanding fsck child processes
719  */
kill_all(int signum)720 static int kill_all(int signum)
721 {
722 	struct fsck_instance *inst;
723 	int	n = 0;
724 
725 	for (inst = instance_list; inst; inst = inst->next) {
726 		if (inst->flags & FLAG_DONE)
727 			continue;
728 		kill(inst->pid, signum);
729 		n++;
730 	}
731 	return n;
732 }
733 
734 /*
735  * Wait for one child process to exit; when it does, unlink it from
736  * the list of executing child processes, and return it.
737  */
wait_one(int flags)738 static struct fsck_instance *wait_one(int flags)
739 {
740 	int	status = 0;
741 	int	sig;
742 	struct fsck_instance *inst, *inst2, *prev;
743 	pid_t	pid;
744 	struct rusage rusage;
745 
746 	if (!instance_list)
747 		return NULL;
748 
749 	if (noexecute) {
750 		inst = instance_list;
751 		prev = NULL;
752 #ifdef RANDOM_DEBUG
753 		while (inst->next && (random() & 1)) {
754 			prev = inst;
755 			inst = inst->next;
756 		}
757 #endif
758 		inst->exit_status = 0;
759 		goto ret_inst;
760 	}
761 
762 	/*
763 	 * gcc -Wall fails saving throw against stupidity
764 	 * (inst and prev are thought to be uninitialized variables)
765 	 */
766 	inst = prev = NULL;
767 
768 	do {
769 		pid = wait4(-1, &status, flags, &rusage);
770 		if (cancel_requested && !kill_sent) {
771 			kill_all(SIGTERM);
772 			kill_sent++;
773 		}
774 		if ((pid == 0) && (flags & WNOHANG))
775 			return NULL;
776 		if (pid < 0) {
777 			if ((errno == EINTR) || (errno == EAGAIN))
778 				continue;
779 			if (errno == ECHILD) {
780 				warnx(_("wait: no more child process?!?"));
781 				return NULL;
782 			}
783 			warn(_("waitpid failed"));
784 			continue;
785 		}
786 		for (prev = NULL, inst = instance_list;
787 		     inst;
788 		     prev = inst, inst = inst->next) {
789 			if (inst->pid == pid)
790 				break;
791 		}
792 	} while (!inst);
793 
794 	if (WIFEXITED(status))
795 		status = WEXITSTATUS(status);
796 	else if (WIFSIGNALED(status)) {
797 		sig = WTERMSIG(status);
798 		if (sig == SIGINT) {
799 			status = FSCK_EX_UNCORRECTED;
800 		} else {
801 			warnx(_("Warning... %s for device %s exited "
802 			       "with signal %d."),
803 			       inst->prog, fs_get_device(inst->fs), sig);
804 			status = FSCK_EX_ERROR;
805 		}
806 	} else {
807 		warnx(_("%s %s: status is %x, should never happen."),
808 		       inst->prog, fs_get_device(inst->fs), status);
809 		status = FSCK_EX_ERROR;
810 	}
811 
812 	inst->exit_status = status;
813 	inst->flags |= FLAG_DONE;
814 	gettime_monotonic(&inst->end_time);
815 	memcpy(&inst->rusage, &rusage, sizeof(struct rusage));
816 
817 	if (progress && (inst->flags & FLAG_PROGRESS) &&
818 	    !progress_active()) {
819 		for (inst2 = instance_list; inst2; inst2 = inst2->next) {
820 			if (inst2->flags & FLAG_DONE)
821 				continue;
822 			if (strcmp(inst2->type, "ext2") != 0 &&
823 			    strcmp(inst2->type, "ext3") &&
824 			    strcmp(inst2->type, "ext4") != 0 &&
825 			    strcmp(inst2->type, "ext4dev") != 0)
826 				continue;
827 			/*
828 			 * If we've just started the fsck, wait a tiny
829 			 * bit before sending the kill, to give it
830 			 * time to set up the signal handler
831 			 */
832 			if (inst2->start_time.tv_sec < time(NULL) + 2) {
833 				if (fork() == 0) {
834 					sleep(1);
835 					kill(inst2->pid, SIGUSR1);
836 					exit(FSCK_EX_OK);
837 				}
838 			} else
839 				kill(inst2->pid, SIGUSR1);
840 			inst2->flags |= FLAG_PROGRESS;
841 			break;
842 		}
843 	}
844 ret_inst:
845 	if (prev)
846 		prev->next = inst->next;
847 	else
848 		instance_list = inst->next;
849 
850 	print_stats(inst);
851 
852 	if (verbose > 1)
853 		printf(_("Finished with %s (exit status %d)\n"),
854 		       fs_get_device(inst->fs), inst->exit_status);
855 	num_running--;
856 	return inst;
857 }
858 
859 #define FLAG_WAIT_ALL		0
860 #define FLAG_WAIT_ATLEAST_ONE	1
861 /*
862  * Wait until all executing child processes have exited; return the
863  * logical OR of all of their exit code values.
864  */
wait_many(int flags)865 static int wait_many(int flags)
866 {
867 	struct fsck_instance *inst;
868 	int	global_status = 0;
869 	int	wait_flags = 0;
870 
871 	while ((inst = wait_one(wait_flags))) {
872 		global_status |= inst->exit_status;
873 		free_instance(inst);
874 #ifdef RANDOM_DEBUG
875 		if (noexecute && (flags & WNOHANG) && !(random() % 3))
876 			break;
877 #endif
878 		if (flags & FLAG_WAIT_ATLEAST_ONE)
879 			wait_flags = WNOHANG;
880 	}
881 	return global_status;
882 }
883 
884 /*
885  * Run the fsck program on a particular device
886  *
887  * If the type is specified using -t, and it isn't prefixed with "no"
888  * (as in "noext2") and only one filesystem type is specified, then
889  * use that type regardless of what is specified in /etc/fstab.
890  *
891  * If the type isn't specified by the user, then use either the type
892  * specified in /etc/fstab, or DEFAULT_FSTYPE.
893  */
fsck_device(struct libmnt_fs * fs,int interactive)894 static int fsck_device(struct libmnt_fs *fs, int interactive)
895 {
896 	char *progname, *progpath;
897 	const char *type;
898 	int retval;
899 
900 	fs_interpret_type(fs);
901 
902 	type = mnt_fs_get_fstype(fs);
903 
904 	if (type && strcmp(type, "auto") != 0)
905 		;
906 	else if (fstype && strncmp(fstype, "no", 2) != 0 &&
907 	    strncmp(fstype, "opts=", 5) != 0 && strncmp(fstype, "loop", 4) != 0 &&
908 	    !strchr(fstype, ','))
909 		type = fstype;
910 	else
911 		type = DEFAULT_FSTYPE;
912 
913 	xasprintf(&progname, "fsck.%s", type);
914 
915 	if (!find_fsck(progname, &progpath)) {
916 		free(progname);
917 		if (fs_check_required(type)) {
918 			retval = ENOENT;
919 			goto err;
920 		}
921 		return 0;
922 	}
923 
924 	num_running++;
925 	retval = execute(progname, progpath, type, fs, interactive);
926 	free(progname);
927 	free(progpath);
928 	if (retval) {
929 		num_running--;
930 		goto err;
931 	}
932 	return 0;
933 err:
934 	warnx(_("error %d (%m) while executing fsck.%s for %s"),
935 			retval, type, fs_get_device(fs));
936 	return FSCK_EX_ERROR;
937 }
938 
939 
940 /*
941  * Deal with the fsck -t argument.
942  */
943 static struct fs_type_compile {
944 	char **list;
945 	int *type;
946 	int  negate;
947 } fs_type_compiled;
948 
949 #define FS_TYPE_NORMAL	0
950 #define FS_TYPE_OPT	1
951 #define FS_TYPE_NEGOPT	2
952 
compile_fs_type(char * fs_type,struct fs_type_compile * cmp)953 static void compile_fs_type(char *fs_type, struct fs_type_compile *cmp)
954 {
955 	char	*cp, *list, *s;
956 	int	num = 2;
957 	int	negate, first_negate = 1;
958 
959 	if (fs_type) {
960 		for (cp=fs_type; *cp; cp++) {
961 			if (*cp == ',')
962 				num++;
963 		}
964 	}
965 
966 	cmp->list = xcalloc(num, sizeof(char *));
967 	cmp->type = xcalloc(num, sizeof(int));
968 	cmp->negate = 0;
969 
970 	if (!fs_type)
971 		return;
972 
973 	list = xstrdup(fs_type);
974 	num = 0;
975 	s = strtok(list, ",");
976 	while(s) {
977 		negate = 0;
978 		if (strncmp(s, "no", 2) == 0) {
979 			s += 2;
980 			negate = 1;
981 		} else if (*s == '!') {
982 			s++;
983 			negate = 1;
984 		}
985 		if (strcmp(s, "loop") == 0)
986 			/* loop is really short-hand for opts=loop */
987 			goto loop_special_case;
988 		else if (strncmp(s, "opts=", 5) == 0) {
989 			s += 5;
990 		loop_special_case:
991 			cmp->type[num] = negate ? FS_TYPE_NEGOPT : FS_TYPE_OPT;
992 		} else {
993 			if (first_negate) {
994 				cmp->negate = negate;
995 				first_negate = 0;
996 			}
997 			if ((negate && !cmp->negate) ||
998 			    (!negate && cmp->negate)) {
999 				errx(FSCK_EX_USAGE,
1000 					_("Either all or none of the filesystem types passed to -t must be prefixed\n"
1001 					  "with 'no' or '!'."));
1002 			}
1003 		}
1004 
1005 		cmp->list[num++] = xstrdup(s);
1006 		s = strtok(NULL, ",");
1007 	}
1008 	free(list);
1009 }
1010 
1011 /*
1012  * This function returns true if a particular option appears in a
1013  * comma-delimited options list
1014  */
opt_in_list(const char * opt,const char * optlist)1015 static int opt_in_list(const char *opt, const char *optlist)
1016 {
1017 	char	*list, *s;
1018 
1019 	if (!optlist)
1020 		return 0;
1021 	list = xstrdup(optlist);
1022 
1023 	s = strtok(list, ",");
1024 	while(s) {
1025 		if (strcmp(s, opt) == 0) {
1026 			free(list);
1027 			return 1;
1028 		}
1029 		s = strtok(NULL, ",");
1030 	}
1031 	free(list);
1032 	return 0;
1033 }
1034 
1035 /* See if the filesystem matches the criteria given by the -t option */
fs_match(struct libmnt_fs * fs,struct fs_type_compile * cmp)1036 static int fs_match(struct libmnt_fs *fs, struct fs_type_compile *cmp)
1037 {
1038 	int n, ret = 0, checked_type = 0;
1039 	char *cp;
1040 
1041 	if (cmp->list == NULL || cmp->list[0] == NULL)
1042 		return 1;
1043 
1044 	for (n=0; (cp = cmp->list[n]); n++) {
1045 		switch (cmp->type[n]) {
1046 		case FS_TYPE_NORMAL:
1047 		{
1048 			const char *type = mnt_fs_get_fstype(fs);
1049 
1050 			checked_type++;
1051 			if (type && strcmp(cp, type) == 0)
1052 				ret = 1;
1053 			break;
1054 		}
1055 		case FS_TYPE_NEGOPT:
1056 			if (opt_in_list(cp, mnt_fs_get_options(fs)))
1057 				return 0;
1058 			break;
1059 		case FS_TYPE_OPT:
1060 			if (!opt_in_list(cp, mnt_fs_get_options(fs)))
1061 				return 0;
1062 			break;
1063 		}
1064 	}
1065 	if (checked_type == 0)
1066 		return 1;
1067 	return (cmp->negate ? !ret : ret);
1068 }
1069 
1070 /*
1071  * Check if a device exists
1072  */
device_exists(const char * device)1073 static int device_exists(const char *device)
1074 {
1075 	struct stat st;
1076 
1077 	if (stat(device, &st) == -1)
1078 		return 0;
1079 	if (!S_ISBLK(st.st_mode))
1080 		return 0;
1081 	return 1;
1082 }
1083 
fs_ignored_type(struct libmnt_fs * fs)1084 static int fs_ignored_type(struct libmnt_fs *fs)
1085 {
1086 	const char **ip, *type;
1087 
1088 	if (mnt_fs_is_netfs(fs) || mnt_fs_is_pseudofs(fs) || mnt_fs_is_swaparea(fs))
1089 		return 1;
1090 
1091 	type = mnt_fs_get_fstype(fs);
1092 
1093 	for(ip = ignored_types; type && *ip; ip++) {
1094 		if (strcmp(type, *ip) == 0)
1095 			return 1;
1096 	}
1097 
1098 	return 0;
1099 }
1100 
1101 /* Check if we should ignore this filesystem. */
ignore(struct libmnt_fs * fs)1102 static int ignore(struct libmnt_fs *fs)
1103 {
1104 	const char *type;
1105 
1106 	/*
1107 	 * If the pass number is 0, ignore it.
1108 	 */
1109 	if (mnt_fs_get_passno(fs) == 0)
1110 		return 1;
1111 
1112 	/*
1113 	 * If this is a bind mount, ignore it.
1114 	 */
1115 	if (opt_in_list("bind", mnt_fs_get_options(fs))) {
1116 		warnx(_("%s: skipping bad line in /etc/fstab: "
1117 			"bind mount with nonzero fsck pass number"),
1118 			mnt_fs_get_target(fs));
1119 		return 1;
1120 	}
1121 
1122 	/*
1123 	 * ignore devices that don't exist and have the "nofail" mount option
1124 	 */
1125 	if (!device_exists(fs_get_device(fs))) {
1126 		if (opt_in_list("nofail", mnt_fs_get_options(fs))) {
1127 			if (verbose)
1128 				printf(_("%s: skipping nonexistent device\n"),
1129 							fs_get_device(fs));
1130 			return 1;
1131 		}
1132 		if (verbose)
1133 			printf(_("%s: nonexistent device (\"nofail\" fstab "
1134 				 "option may be used to skip this device)\n"),
1135 				fs_get_device(fs));
1136 	}
1137 
1138 	fs_interpret_type(fs);
1139 
1140 	/*
1141 	 * If a specific fstype is specified, and it doesn't match,
1142 	 * ignore it.
1143 	 */
1144 	if (!fs_match(fs, &fs_type_compiled))
1145 		return 1;
1146 
1147 	type = mnt_fs_get_fstype(fs);
1148 	if (!type) {
1149 		if (verbose)
1150 			printf(_("%s: skipping unknown filesystem type\n"),
1151 				fs_get_device(fs));
1152 		return 1;
1153 	}
1154 
1155 	/* Are we ignoring this type? */
1156 	if (fs_ignored_type(fs))
1157 		return 1;
1158 
1159 
1160 
1161 	/* See if the <fsck.fs> program is available. */
1162 	if (!find_fsck(type, NULL)) {
1163 		if (fs_check_required(type))
1164 			warnx(_("cannot check %s: fsck.%s not found"),
1165 				fs_get_device(fs), type);
1166 		return 1;
1167 	}
1168 
1169 	/* We can and want to check this file system type. */
1170 	return 0;
1171 }
1172 
count_slaves(dev_t disk)1173 static int count_slaves(dev_t disk)
1174 {
1175 	DIR *dir;
1176 	struct dirent *dp;
1177 	char dirname[PATH_MAX];
1178 	int count = 0;
1179 
1180 	snprintf(dirname, sizeof(dirname),
1181 			"/sys/dev/block/%u:%u/slaves/",
1182 			major(disk), minor(disk));
1183 
1184 	if (!(dir = opendir(dirname)))
1185 		return -1;
1186 
1187 	while ((dp = readdir(dir)) != NULL) {
1188 #ifdef _DIRENT_HAVE_D_TYPE
1189 		if (dp->d_type != DT_UNKNOWN && dp->d_type != DT_LNK)
1190 			continue;
1191 #endif
1192 		if (dp->d_name[0] == '.' &&
1193 		    ((dp->d_name[1] == 0) ||
1194 		     ((dp->d_name[1] == '.') && (dp->d_name[2] == 0))))
1195 			continue;
1196 
1197 		count++;
1198 	}
1199 
1200 	closedir(dir);
1201 	return count;
1202 }
1203 
1204 /*
1205  * Returns TRUE if a partition on the same disk is already being
1206  * checked.
1207  */
disk_already_active(struct libmnt_fs * fs)1208 static int disk_already_active(struct libmnt_fs *fs)
1209 {
1210 	struct fsck_instance *inst;
1211 	dev_t disk;
1212 
1213 	if (force_all_parallel)
1214 		return 0;
1215 
1216 	if (instance_list && fs_is_stacked(instance_list->fs))
1217 		/* any instance for a stacked device is already running */
1218 		return 1;
1219 
1220 	disk = fs_get_disk(fs, 1);
1221 
1222 	/*
1223 	 * If we don't know the base device, assume that the device is
1224 	 * already active if there are any fsck instances running.
1225 	 *
1226 	 * Don't check a stacked device with any other disk too.
1227 	 */
1228 	if (!disk || fs_is_stacked(fs))
1229 		return (instance_list != NULL);
1230 
1231 	for (inst = instance_list; inst; inst = inst->next) {
1232 		dev_t idisk = fs_get_disk(inst->fs, 0);
1233 
1234 		if (!idisk || disk == idisk)
1235 			return 1;
1236 	}
1237 
1238 	return 0;
1239 }
1240 
1241 /* Check all file systems, using the /etc/fstab table. */
check_all(void)1242 static int check_all(void)
1243 {
1244 	int not_done_yet = 1;
1245 	int passno = 1;
1246 	int pass_done;
1247 	int status = FSCK_EX_OK;
1248 
1249 	struct libmnt_fs *fs;
1250 	struct libmnt_iter *itr = mnt_new_iter(MNT_ITER_FORWARD);
1251 
1252 	if (!itr)
1253 		err(FSCK_EX_ERROR, _("failed to allocate iterator"));
1254 
1255 	/*
1256 	 * Do an initial scan over the filesystem; mark filesystems
1257 	 * which should be ignored as done, and resolve any "auto"
1258 	 * filesystem types (done as a side-effect of calling ignore()).
1259 	 */
1260 	while (mnt_table_next_fs(fstab, itr, &fs) == 0) {
1261 		if (ignore(fs)) {
1262 			fs_set_done(fs);
1263 			continue;
1264 		}
1265 	}
1266 
1267 	if (verbose)
1268 		fputs(_("Checking all file systems.\n"), stdout);
1269 
1270 	/*
1271 	 * Find and check the root filesystem.
1272 	 */
1273 	if (!parallel_root) {
1274 		fs = mnt_table_find_target(fstab, "/", MNT_ITER_FORWARD);
1275 		if (fs) {
1276 			if (!skip_root &&
1277 			    !fs_is_done(fs) &&
1278 			    !(ignore_mounted && is_mounted(fs))) {
1279 				status |= fsck_device(fs, 1);
1280 				status |= wait_many(FLAG_WAIT_ALL);
1281 				if (status > FSCK_EX_NONDESTRUCT) {
1282 					mnt_free_iter(itr);
1283 					return status;
1284 				}
1285 			}
1286 			fs_set_done(fs);
1287 		}
1288 	}
1289 
1290 	/*
1291 	 * This is for the bone-headed user who enters the root
1292 	 * filesystem twice.  Skip root will skip all root entries.
1293 	 */
1294 	if (skip_root) {
1295 		mnt_reset_iter(itr, MNT_ITER_FORWARD);
1296 
1297 		while(mnt_table_next_fs(fstab, itr, &fs) == 0) {
1298 			const char *tgt = mnt_fs_get_target(fs);
1299 
1300 			if (tgt && strcmp(tgt, "/") == 0)
1301 				fs_set_done(fs);
1302 		}
1303 	}
1304 
1305 	while (not_done_yet) {
1306 		not_done_yet = 0;
1307 		pass_done = 1;
1308 
1309 		mnt_reset_iter(itr, MNT_ITER_FORWARD);
1310 
1311 		while(mnt_table_next_fs(fstab, itr, &fs) == 0) {
1312 
1313 			if (cancel_requested)
1314 				break;
1315 			if (fs_is_done(fs))
1316 				continue;
1317 			/*
1318 			 * If the filesystem's pass number is higher
1319 			 * than the current pass number, then we don't
1320 			 * do it yet.
1321 			 */
1322 			if (mnt_fs_get_passno(fs) > passno) {
1323 				not_done_yet++;
1324 				continue;
1325 			}
1326 			if (ignore_mounted && is_mounted(fs)) {
1327 				fs_set_done(fs);
1328 				continue;
1329 			}
1330 			/*
1331 			 * If a filesystem on a particular device has
1332 			 * already been spawned, then we need to defer
1333 			 * this to another pass.
1334 			 */
1335 			if (disk_already_active(fs)) {
1336 				pass_done = 0;
1337 				continue;
1338 			}
1339 			/*
1340 			 * Spawn off the fsck process
1341 			 */
1342 			status |= fsck_device(fs, serialize);
1343 			fs_set_done(fs);
1344 
1345 			/*
1346 			 * Only do one filesystem at a time, or if we
1347 			 * have a limit on the number of fsck's extant
1348 			 * at one time, apply that limit.
1349 			 */
1350 			if (serialize ||
1351 			    (max_running && (num_running >= max_running))) {
1352 				pass_done = 0;
1353 				break;
1354 			}
1355 		}
1356 		if (cancel_requested)
1357 			break;
1358 		if (verbose > 1)
1359 			printf(_("--waiting-- (pass %d)\n"), passno);
1360 
1361 		status |= wait_many(pass_done ? FLAG_WAIT_ALL :
1362 				    FLAG_WAIT_ATLEAST_ONE);
1363 		if (pass_done) {
1364 			if (verbose > 1)
1365 				printf("----------------------------------\n");
1366 			passno++;
1367 		} else
1368 			not_done_yet++;
1369 	}
1370 
1371 	if (cancel_requested && !kill_sent) {
1372 		kill_all(SIGTERM);
1373 		kill_sent++;
1374 	}
1375 
1376 	status |= wait_many(FLAG_WAIT_ATLEAST_ONE);
1377 	mnt_free_iter(itr);
1378 	return status;
1379 }
1380 
usage(void)1381 static void __attribute__((__noreturn__)) usage(void)
1382 {
1383 	FILE *out = stdout;
1384 	fputs(USAGE_HEADER, out);
1385 	fprintf(out, _(" %s [options] -- [fs-options] [<filesystem> ...]\n"),
1386 			 program_invocation_short_name);
1387 
1388 	fputs(USAGE_SEPARATOR, out);
1389 	fputs(_("Check and repair a Linux filesystem.\n"), out);
1390 
1391 	fputs(USAGE_OPTIONS, out);
1392 	fputs(_(" -A         check all filesystems\n"), out);
1393 	fputs(_(" -C [<fd>]  display progress bar; file descriptor is for GUIs\n"), out);
1394 	fputs(_(" -l         lock the device to guarantee exclusive access\n"), out);
1395 	fputs(_(" -M         do not check mounted filesystems\n"), out);
1396 	fputs(_(" -N         do not execute, just show what would be done\n"), out);
1397 	fputs(_(" -P         check filesystems in parallel, including root\n"), out);
1398 	fputs(_(" -R         skip root filesystem; useful only with '-A'\n"), out);
1399 	fputs(_(" -r [<fd>]  report statistics for each device checked;\n"
1400 		"            file descriptor is for GUIs\n"), out);
1401 	fputs(_(" -s         serialize the checking operations\n"), out);
1402 	fputs(_(" -T         do not show the title on startup\n"), out);
1403 	fputs(_(" -t <type>  specify filesystem types to be checked;\n"
1404 		"            <type> is allowed to be a comma-separated list\n"), out);
1405 	fputs(_(" -V         explain what is being done\n"), out);
1406 
1407 	fputs(USAGE_SEPARATOR, out);
1408 	printf( " -?, --help     %s\n", USAGE_OPTSTR_HELP);
1409 	printf( "     --version  %s\n", USAGE_OPTSTR_VERSION);
1410 	fputs(USAGE_SEPARATOR, out);
1411 	fputs(_("See the specific fsck.* commands for available fs-options."), out);
1412 	printf(USAGE_MAN_TAIL("fsck(8)"));
1413 	exit(FSCK_EX_OK);
1414 }
1415 
signal_cancel(int sig)1416 static void signal_cancel(int sig __attribute__((__unused__)))
1417 {
1418 	cancel_requested++;
1419 }
1420 
parse_argv(int argc,char * argv[])1421 static void parse_argv(int argc, char *argv[])
1422 {
1423 	int	i, j;
1424 	char	*arg, *dev, *tmp = NULL;
1425 	char	options[128];
1426 	int	opt = 0;
1427 	int     opts_for_fsck = 0;
1428 	struct sigaction	sa;
1429 	int	report_stats_fd = -1;
1430 
1431 	/*
1432 	 * Set up signal action
1433 	 */
1434 	memset(&sa, 0, sizeof(struct sigaction));
1435 	sa.sa_handler = signal_cancel;
1436 	sigaction(SIGINT, &sa, NULL);
1437 	sigaction(SIGTERM, &sa, NULL);
1438 
1439 	num_devices = 0;
1440 	num_args = 0;
1441 	instance_list = NULL;
1442 
1443 	for (i=1; i < argc; i++) {
1444 		arg = argv[i];
1445 		if (!arg)
1446 			continue;
1447 
1448 		/* the only two longopts to satisfy UL standards */
1449 		if (!opts_for_fsck && !strcmp(arg, "--help"))
1450 			usage();
1451 		if (!opts_for_fsck && !strcmp(arg, "--version"))
1452 			print_version(FSCK_EX_OK);
1453 
1454 		if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
1455 			if (num_devices >= MAX_DEVICES)
1456 				errx(FSCK_EX_ERROR, _("too many devices"));
1457 
1458 			dev = mnt_resolve_spec(arg, mntcache);
1459 
1460 			if (!dev && strchr(arg, '=')) {
1461 				/*
1462 				 * Check to see if we failed because
1463 				 * /proc/partitions isn't found.
1464 				 */
1465 				if (access(_PATH_PROC_PARTITIONS, R_OK) < 0) {
1466 					warn(_("cannot open %s"),
1467 						_PATH_PROC_PARTITIONS);
1468 					errx(FSCK_EX_ERROR, _("Is /proc mounted?"));
1469 				}
1470 				/*
1471 				 * Check to see if this is because
1472 				 * we're not running as root
1473 				 */
1474 				if (geteuid())
1475 					errx(FSCK_EX_ERROR,
1476 						_("must be root to scan for matching filesystems: %s"),
1477 						arg);
1478 				else
1479 					errx(FSCK_EX_ERROR,
1480 						_("couldn't find matching filesystem: %s"),
1481 						arg);
1482 			}
1483 			devices[num_devices++] = dev ? dev : xstrdup(arg);
1484 			continue;
1485 		}
1486 		if (arg[0] != '-' || opts_for_fsck) {
1487 			if (num_args >= MAX_ARGS)
1488 				errx(FSCK_EX_ERROR, _("too many arguments"));
1489 			args[num_args++] = xstrdup(arg);
1490 			continue;
1491 		}
1492 		for (j=1; arg[j]; j++) {
1493 			if (opts_for_fsck) {
1494 				options[++opt] = arg[j];
1495 				continue;
1496 			}
1497 			switch (arg[j]) {
1498 			case 'A':
1499 				doall = 1;
1500 				break;
1501 			case 'C':
1502 				progress = 1;
1503 				if (arg[j+1]) {					/* -C<fd> */
1504 					progress_fd = string_to_int(arg+j+1);
1505 					if (progress_fd < 0)
1506 						progress_fd = 0;
1507 					else
1508 						goto next_arg;
1509 				} else if (i+1 < argc && *argv[i+1] != '-') {	/* -C <fd> */
1510 					progress_fd = string_to_int(argv[i+1]);
1511 					if (progress_fd < 0)
1512 						progress_fd = 0;
1513 					else {
1514 						++i;
1515 						goto next_arg;
1516 					}
1517 				}
1518 				break;
1519 			case 'l':
1520 				lockdisk = 1;
1521 				break;
1522 			case 'V':
1523 				verbose++;
1524 				break;
1525 			case 'N':
1526 				noexecute = 1;
1527 				break;
1528 			case 'R':
1529 				skip_root = 1;
1530 				break;
1531 			case 'T':
1532 				notitle = 1;
1533 				break;
1534 			case 'M':
1535 				ignore_mounted = 1;
1536 				break;
1537 			case 'P':
1538 				parallel_root = 1;
1539 				break;
1540 			case 'r':
1541 				report_stats = 1;
1542 				if (arg[j+1]) {					/* -r<fd> */
1543 					report_stats_fd = strtou32_or_err(arg+j+1, _("invalid argument of -r"));
1544 					goto next_arg;
1545 				} else if (i+1 < argc && *argv[i+1] >= '0' && *argv[i+1] <= '9') {	/* -r <fd> */
1546 					report_stats_fd = strtou32_or_err(argv[i+1], _("invalid argument of -r"));
1547 					++i;
1548 					goto next_arg;
1549 				}
1550 				break;
1551 			case 's':
1552 				serialize = 1;
1553 				break;
1554 			case 't':
1555 				tmp = NULL;
1556 				if (fstype)
1557 					errx(FSCK_EX_USAGE,
1558 						_("option '%s' may be specified only once"), "-t");
1559 				if (arg[j+1])
1560 					tmp = arg+j+1;
1561 				else if ((i+1) < argc)
1562 					tmp = argv[++i];
1563 				else
1564 					errx(FSCK_EX_USAGE,
1565 						_("option '%s' requires an argument"), "-t");
1566 				fstype = xstrdup(tmp);
1567 				compile_fs_type(fstype, &fs_type_compiled);
1568 				goto next_arg;
1569 			case '-':
1570 				opts_for_fsck++;
1571 				break;
1572 			case '?':
1573 				usage();
1574 				break;
1575 			default:
1576 				options[++opt] = arg[j];
1577 				break;
1578 			}
1579 		}
1580 	next_arg:
1581 		if (opt) {
1582 			options[0] = '-';
1583 			options[++opt] = '\0';
1584 			if (num_args >= MAX_ARGS)
1585 				errx(FSCK_EX_ERROR, _("too many arguments"));
1586 			args[num_args++] = xstrdup(options);
1587 			opt = 0;
1588 		}
1589 	}
1590 
1591 	/* Validate the report stats file descriptor to avoid disasters */
1592 	if (report_stats_fd >= 0) {
1593 		report_stats_file = fdopen(report_stats_fd, "w");
1594 		if (!report_stats_file)
1595 			err(FSCK_EX_ERROR,
1596 				_("invalid argument of -r: %d"),
1597 				report_stats_fd);
1598 	}
1599 
1600 	if (getenv("FSCK_FORCE_ALL_PARALLEL"))
1601 		force_all_parallel++;
1602 	if ((tmp = getenv("FSCK_MAX_INST")))
1603 	    max_running = atoi(tmp);
1604 }
1605 
main(int argc,char * argv[])1606 int main(int argc, char *argv[])
1607 {
1608 	int i, status = 0;
1609 	int interactive = 0;
1610 	struct libmnt_fs *fs;
1611 	const char *path = getenv("PATH");
1612 
1613 	setvbuf(stdout, NULL, _IONBF, BUFSIZ);
1614 	setvbuf(stderr, NULL, _IONBF, BUFSIZ);
1615 
1616 	setlocale(LC_MESSAGES, "");
1617 	setlocale(LC_CTYPE, "");
1618 	bindtextdomain(PACKAGE, LOCALEDIR);
1619 	textdomain(PACKAGE);
1620 	close_stdout_atexit();
1621 
1622 	strutils_set_exitcode(FSCK_EX_USAGE);
1623 	mnt_init_debug(0);		/* init libmount debug mask */
1624 	mntcache = mnt_new_cache();	/* no fatal error if failed */
1625 
1626 	parse_argv(argc, argv);
1627 
1628 	if (!notitle)
1629 		printf(UTIL_LINUX_VERSION);
1630 
1631 	load_fs_info();
1632 
1633 	fsck_path = xstrdup(path && *path ? path : FSCK_DEFAULT_PATH);
1634 
1635 	if ((num_devices == 1) || (serialize))
1636 		interactive = 1;
1637 
1638 	if (lockdisk && (doall || num_devices > 1)) {
1639 		warnx(_("the -l option can be used with one "
1640 				  "device only -- ignore"));
1641 		lockdisk = 0;
1642 	}
1643 
1644 	/* If -A was specified ("check all"), do that! */
1645 	if (doall)
1646 		return check_all();
1647 
1648 	if (num_devices == 0) {
1649 		serialize++;
1650 		interactive++;
1651 		return check_all();
1652 	}
1653 	for (i = 0 ; i < num_devices; i++) {
1654 		if (cancel_requested) {
1655 			if (!kill_sent) {
1656 				kill_all(SIGTERM);
1657 				kill_sent++;
1658 			}
1659 			break;
1660 		}
1661 		fs = lookup(devices[i]);
1662 		if (!fs)
1663 			fs = add_dummy_fs(devices[i]);
1664 		else if (fs_ignored_type(fs))
1665 			continue;
1666 		if (ignore_mounted && is_mounted(fs))
1667 			continue;
1668 		status |= fsck_device(fs, interactive);
1669 		if (serialize ||
1670 		    (max_running && (num_running >= max_running))) {
1671 			struct fsck_instance *inst;
1672 
1673 			inst = wait_one(0);
1674 			if (inst) {
1675 				status |= inst->exit_status;
1676 				free_instance(inst);
1677 			}
1678 			if (verbose > 1)
1679 				printf("----------------------------------\n");
1680 		}
1681 	}
1682 	status |= wait_many(FLAG_WAIT_ALL);
1683 	free(fsck_path);
1684 	mnt_unref_cache(mntcache);
1685 	mnt_unref_table(fstab);
1686 	mnt_unref_table(mtab);
1687 	return status;
1688 }
1689