1/*	$NetBSD: fsck.c,v 1.30 2003/08/07 10:04:15 agc Exp $	*/
2
3/*
4 * Copyright (c) 1996 Christos Zoulas. All rights reserved.
5 * Copyright (c) 1980, 1989, 1993, 1994
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 *
32 * From: @(#)mount.c	8.19 (Berkeley) 4/19/94
33 * From: $NetBSD: mount.c,v 1.24 1995/11/18 03:34:29 cgd Exp
34 * $NetBSD: fsck.c,v 1.30 2003/08/07 10:04:15 agc Exp $
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: stable/11/sbin/fsck/fsck.c 315546 2017-03-19 14:05:56Z trasz $");
39
40#include <sys/param.h>
41#include <sys/mount.h>
42#include <sys/queue.h>
43#include <sys/wait.h>
44#include <sys/disk.h>
45#include <sys/ioctl.h>
46
47#include <ctype.h>
48#include <err.h>
49#include <errno.h>
50#include <fstab.h>
51#include <fcntl.h>
52#include <paths.h>
53#include <signal.h>
54#include <stdio.h>
55#include <stdlib.h>
56#include <string.h>
57#include <unistd.h>
58
59#include "fsutil.h"
60
61static enum { IN_LIST, NOT_IN_LIST } which = NOT_IN_LIST;
62
63static TAILQ_HEAD(fstypelist, entry) opthead, selhead;
64
65struct entry {
66	char *type;
67	char *options;
68	TAILQ_ENTRY(entry) entries;
69};
70
71static char *options = NULL;
72static int flags = 0;
73static int forceflag = 0;
74
75static int checkfs(const char *, const char *, const char *, const char *, pid_t *);
76static int selected(const char *);
77static void addoption(char *);
78static const char *getoptions(const char *);
79static void addentry(struct fstypelist *, const char *, const char *);
80static void maketypelist(char *);
81static void catopt(char **, const char *);
82static void mangle(char *, int *, const char ** volatile *, int *);
83static const char *getfstype(const char *);
84static void usage(void) __dead2;
85static int isok(struct fstab *);
86
87static struct {
88	const char *ptype;
89	const char *name;
90} ptype_map[] = {
91	{ "ufs",	"ffs" },
92	{ "ffs",	"ffs" },
93	{ "fat",	"msdosfs" },
94	{ "efi",	"msdosfs" },
95	{ NULL,		NULL },
96};
97
98int
99main(int argc, char *argv[])
100{
101	struct fstab *fs;
102	int i, rval = 0;
103	const char *vfstype = NULL;
104	char globopt[3];
105	const char *etc_fstab;
106
107	globopt[0] = '-';
108	globopt[2] = '\0';
109
110	TAILQ_INIT(&selhead);
111	TAILQ_INIT(&opthead);
112
113	etc_fstab = NULL;
114	while ((i = getopt(argc, argv, "BCdvpfFnyl:t:T:c:")) != -1)
115		switch (i) {
116		case 'B':
117			if (flags & CHECK_BACKGRD)
118				errx(1, "Cannot specify -B and -F.");
119			flags |= DO_BACKGRD;
120			break;
121
122		case 'd':
123			flags |= CHECK_DEBUG;
124			break;
125
126		case 'v':
127			flags |= CHECK_VERBOSE;
128			break;
129
130		case 'F':
131			if (flags & DO_BACKGRD)
132				errx(1, "Cannot specify -B and -F.");
133			flags |= CHECK_BACKGRD;
134			break;
135
136		case 'p':
137			flags |= CHECK_PREEN;
138			/*FALLTHROUGH*/
139		case 'C':
140			flags |= CHECK_CLEAN;
141			/*FALLTHROUGH*/
142		case 'n':
143		case 'y':
144			globopt[1] = i;
145			catopt(&options, globopt);
146			break;
147
148		case 'f':
149			forceflag = 1;
150			globopt[1] = i;
151			catopt(&options, globopt);
152			break;
153
154		case 'l':
155			warnx("Ignoring obsolete -l option\n");
156			break;
157
158		case 'T':
159			if (*optarg)
160				addoption(optarg);
161			break;
162
163		case 't':
164			if (!TAILQ_EMPTY(&selhead))
165				errx(1, "only one -t option may be specified.");
166
167			maketypelist(optarg);
168			vfstype = optarg;
169			break;
170
171		case 'c':
172			etc_fstab = optarg;
173			break;
174
175		case '?':
176		default:
177			usage();
178			/* NOTREACHED */
179		}
180
181	argc -= optind;
182	argv += optind;
183
184	if (etc_fstab != NULL)
185		setfstab(etc_fstab);
186
187	if (argc == 0)
188		return checkfstab(flags, isok, checkfs);
189
190#define	BADTYPE(type)							\
191	(strcmp(type, FSTAB_RO) &&					\
192	    strcmp(type, FSTAB_RW) && strcmp(type, FSTAB_RQ))
193
194
195	for (; argc--; argv++) {
196		const char *spec, *mntpt, *type, *cp;
197		char device[MAXPATHLEN];
198		struct statfs *mntp;
199
200		mntpt = NULL;
201		spec = *argv;
202		cp = strrchr(spec, '/');
203		if (cp == NULL) {
204			(void)snprintf(device, sizeof(device), "%s%s",
205				_PATH_DEV, spec);
206			spec = device;
207		}
208		mntp = getmntpt(spec);
209		if (mntp != NULL) {
210			spec = mntp->f_mntfromname;
211			mntpt = mntp->f_mntonname;
212		}
213		if ((fs = getfsfile(spec)) == NULL &&
214		    (fs = getfsspec(spec)) == NULL) {
215			if (vfstype == NULL)
216				vfstype = getfstype(spec);
217			if (vfstype == NULL)
218				vfstype = "ufs";
219			type = vfstype;
220			devcheck(spec);
221		} else {
222			spec = fs->fs_spec;
223			type = fs->fs_vfstype;
224			mntpt = fs->fs_file;
225			if (BADTYPE(fs->fs_type))
226				errx(1, "%s has unknown file system type.",
227				    spec);
228		}
229		if ((flags & CHECK_BACKGRD) &&
230		    checkfs(type, spec, mntpt, "-F", NULL) == 0) {
231			printf("%s: DEFER FOR BACKGROUND CHECKING\n", *argv);
232			continue;
233		}
234		if ((flags & DO_BACKGRD) && forceflag == 0 &&
235		    checkfs(type, spec, mntpt, "-F", NULL) != 0)
236			continue;
237
238		rval |= checkfs(type, spec, mntpt, NULL, NULL);
239	}
240
241	return rval;
242}
243
244
245static int
246isok(struct fstab *fs)
247{
248	int i;
249
250	if (fs->fs_passno == 0)
251		return (0);
252	if (BADTYPE(fs->fs_type))
253		return (0);
254	if (!selected(fs->fs_vfstype))
255		return (0);
256	/*
257	 * If the -B flag has been given, then process the needed
258	 * background checks. Background checks cannot be run on
259	 * file systems that will be mounted read-only or that were
260	 * not mounted at boot time (typically those marked `noauto').
261	 * If these basic tests are passed, check with the file system
262	 * itself to see if it is willing to do background checking
263	 * by invoking its check program with the -F flag.
264	 */
265	if (flags & DO_BACKGRD) {
266		if (!strcmp(fs->fs_type, FSTAB_RO))
267			return (0);
268		if (getmntpt(fs->fs_spec) == NULL)
269			return (0);
270		if (checkfs(fs->fs_vfstype, fs->fs_spec, fs->fs_file, "-F", 0))
271			return (0);
272		return (1);
273	}
274	/*
275	 * If the -F flag has been given, then consider deferring the
276	 * check to background. Background checks cannot be run on
277	 * file systems that will be mounted read-only or that will
278	 * not be mounted at boot time (e.g., marked `noauto'). If
279	 * these basic tests are passed, check with the file system
280	 * itself to see if it is willing to defer to background
281	 * checking by invoking its check program with the -F flag.
282	 */
283	if ((flags & CHECK_BACKGRD) == 0 || !strcmp(fs->fs_type, FSTAB_RO))
284		return (1);
285	for (i = strlen(fs->fs_mntops) - 6; i >= 0; i--)
286		if (!strncmp(&fs->fs_mntops[i], "noauto", 6))
287			break;
288	if (i >= 0)
289		return (1);
290	if (checkfs(fs->fs_vfstype, fs->fs_spec, fs->fs_file, "-F", NULL) != 0)
291		return (1);
292	printf("%s: DEFER FOR BACKGROUND CHECKING\n", fs->fs_spec);
293	return (0);
294}
295
296
297static int
298checkfs(const char *pvfstype, const char *spec, const char *mntpt,
299    const char *auxopt, pid_t *pidp)
300{
301	const char ** volatile argv;
302	pid_t pid;
303	int argc, i, status, maxargc;
304	char *optbuf, execbase[MAXPATHLEN];
305	char *vfstype = NULL;
306	const char *extra = NULL;
307
308#ifdef __GNUC__
309	/* Avoid vfork clobbering */
310	(void) &optbuf;
311	(void) &vfstype;
312#endif
313	/*
314	 * We convert the vfstype to lowercase and any spaces to underscores
315	 * to not confuse the issue
316	 *
317	 * XXX This is a kludge to make automatic filesystem type guessing
318	 * from the disklabel work for "4.2BSD" filesystems.  It does a
319	 * very limited subset of transliteration to a normalised form of
320	 * filesystem name, and we do not seem to enforce a filesystem
321	 * name character set.
322	 */
323	vfstype = strdup(pvfstype);
324	if (vfstype == NULL)
325		perr("strdup(pvfstype)");
326	for (i = 0; i < (int)strlen(vfstype); i++) {
327		vfstype[i] = tolower(vfstype[i]);
328		if (vfstype[i] == ' ')
329			vfstype[i] = '_';
330	}
331
332	extra = getoptions(vfstype);
333	optbuf = NULL;
334	if (options)
335		catopt(&optbuf, options);
336	if (extra)
337		catopt(&optbuf, extra);
338	if (auxopt)
339		catopt(&optbuf, auxopt);
340	else if (flags & DO_BACKGRD)
341		catopt(&optbuf, "-B");
342
343	maxargc = 64;
344	argv = emalloc(sizeof(char *) * maxargc);
345
346	(void) snprintf(execbase, sizeof(execbase), "fsck_%s", vfstype);
347	argc = 0;
348	argv[argc++] = execbase;
349	if (optbuf)
350		mangle(optbuf, &argc, &argv, &maxargc);
351	argv[argc++] = spec;
352	argv[argc] = NULL;
353
354	if (flags & (CHECK_DEBUG|CHECK_VERBOSE)) {
355		(void)printf("start %s %swait", mntpt,
356			pidp ? "no" : "");
357		for (i = 0; i < argc; i++)
358			(void)printf(" %s", argv[i]);
359		(void)printf("\n");
360	}
361
362	switch (pid = vfork()) {
363	case -1:				/* Error. */
364		warn("vfork");
365		if (optbuf)
366			free(optbuf);
367		free(vfstype);
368		return (1);
369
370	case 0:					/* Child. */
371		if ((flags & CHECK_DEBUG) && auxopt == NULL)
372			_exit(0);
373
374		/* Go find an executable. */
375		execvP(execbase, _PATH_SYSPATH, __DECONST(char * const *, argv));
376		if (spec)
377			warn("exec %s for %s in %s", execbase, spec, _PATH_SYSPATH);
378		else
379			warn("exec %s in %s", execbase, _PATH_SYSPATH);
380		_exit(1);
381		/* NOTREACHED */
382
383	default:				/* Parent. */
384		if (optbuf)
385			free(optbuf);
386
387		free(vfstype);
388
389		if (pidp) {
390			*pidp = pid;
391			return 0;
392		}
393
394		if (waitpid(pid, &status, 0) < 0) {
395			warn("waitpid");
396			return (1);
397		}
398
399		if (WIFEXITED(status)) {
400			if (WEXITSTATUS(status) != 0)
401				return (WEXITSTATUS(status));
402		}
403		else if (WIFSIGNALED(status)) {
404			warnx("%s: %s", spec, strsignal(WTERMSIG(status)));
405			return (1);
406		}
407		break;
408	}
409
410	return (0);
411}
412
413
414static int
415selected(const char *type)
416{
417	struct entry *e;
418
419	/* If no type specified, it's always selected. */
420	TAILQ_FOREACH(e, &selhead, entries)
421		if (!strncmp(e->type, type, MFSNAMELEN))
422			return which == IN_LIST ? 1 : 0;
423
424	return which == IN_LIST ? 0 : 1;
425}
426
427
428static const char *
429getoptions(const char *type)
430{
431	struct entry *e;
432
433	TAILQ_FOREACH(e, &opthead, entries)
434		if (!strncmp(e->type, type, MFSNAMELEN))
435			return e->options;
436	return "";
437}
438
439
440static void
441addoption(char *optstr)
442{
443	char *newoptions;
444	struct entry *e;
445
446	if ((newoptions = strchr(optstr, ':')) == NULL)
447		errx(1, "Invalid option string");
448
449	*newoptions++ = '\0';
450
451	TAILQ_FOREACH(e, &opthead, entries)
452		if (!strncmp(e->type, optstr, MFSNAMELEN)) {
453			catopt(&e->options, newoptions);
454			return;
455		}
456	addentry(&opthead, optstr, newoptions);
457}
458
459
460static void
461addentry(struct fstypelist *list, const char *type, const char *opts)
462{
463	struct entry *e;
464
465	e = emalloc(sizeof(struct entry));
466	e->type = estrdup(type);
467	e->options = estrdup(opts);
468	TAILQ_INSERT_TAIL(list, e, entries);
469}
470
471
472static void
473maketypelist(char *fslist)
474{
475	char *ptr;
476
477	if ((fslist == NULL) || (fslist[0] == '\0'))
478		errx(1, "empty type list");
479
480	if (fslist[0] == 'n' && fslist[1] == 'o') {
481		fslist += 2;
482		which = NOT_IN_LIST;
483	}
484	else
485		which = IN_LIST;
486
487	while ((ptr = strsep(&fslist, ",")) != NULL)
488		addentry(&selhead, ptr, "");
489
490}
491
492
493static void
494catopt(char **sp, const char *o)
495{
496	char *s;
497	size_t i, j;
498
499	s = *sp;
500	if (s) {
501		i = strlen(s);
502		j = i + 1 + strlen(o) + 1;
503		s = erealloc(s, j);
504		(void)snprintf(s + i, j, ",%s", o);
505	} else
506		s = estrdup(o);
507	*sp = s;
508}
509
510
511static void
512mangle(char *opts, int *argcp, const char ** volatile *argvp, int *maxargcp)
513{
514	char *p, *s;
515	int argc, maxargc;
516	const char **argv;
517
518	argc = *argcp;
519	argv = *argvp;
520	maxargc = *maxargcp;
521
522	for (s = opts; (p = strsep(&s, ",")) != NULL;) {
523		/* Always leave space for one more argument and the NULL. */
524		if (argc >= maxargc - 3) {
525			maxargc <<= 1;
526			argv = erealloc(argv, maxargc * sizeof(char *));
527		}
528		if (*p != '\0')  {
529			if (*p == '-') {
530				argv[argc++] = p;
531				p = strchr(p, '=');
532				if (p) {
533					*p = '\0';
534					argv[argc++] = p+1;
535				}
536			} else {
537				argv[argc++] = "-o";
538				argv[argc++] = p;
539			}
540		}
541	}
542
543	*argcp = argc;
544	*argvp = argv;
545	*maxargcp = maxargc;
546}
547
548static const char *
549getfstype(const char *str)
550{
551	struct diocgattr_arg attr;
552	int fd, i;
553
554	if ((fd = open(str, O_RDONLY)) == -1)
555		err(1, "cannot open `%s'", str);
556
557	strncpy(attr.name, "PART::type", sizeof(attr.name));
558	memset(&attr.value, 0, sizeof(attr.value));
559	attr.len = sizeof(attr.value);
560	if (ioctl(fd, DIOCGATTR, &attr) == -1) {
561		(void) close(fd);
562		return(NULL);
563	}
564	(void) close(fd);
565	for (i = 0; ptype_map[i].ptype != NULL; i++)
566		if (strstr(attr.value.str, ptype_map[i].ptype) != NULL)
567			return (ptype_map[i].name);
568	return (NULL);
569}
570
571
572static void
573usage(void)
574{
575	static const char common[] =
576	    "[-Cdfnpvy] [-B | -F] [-T fstype:fsoptions] [-t fstype] [-c fstab]";
577
578	(void)fprintf(stderr, "usage: %s %s [special | node] ...\n",
579	    getprogname(), common);
580	exit(1);
581}
582