xref: /freebsd/sbin/mount/mount.c (revision faf25f48d601ae39f5752602f3020e2e92605625)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1980, 1989, 1993, 1994\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #if 0
37 static char sccsid[] = "@(#)mount.c	8.25 (Berkeley) 5/8/95";
38 #endif
39 #endif /* not lint */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #define _WANT_MNTOPTNAMES
46 #include <sys/mount.h>
47 #include <sys/stat.h>
48 #include <sys/wait.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <fstab.h>
54 #include <paths.h>
55 #include <pwd.h>
56 #include <signal.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <libutil.h>
63 #include <libxo/xo.h>
64 
65 #include "extern.h"
66 #include "mntopts.h"
67 #include "pathnames.h"
68 
69 #define EXIT(a) {			\
70 	xo_close_container("mount");	\
71 	xo_finish();			\
72 	exit(a);			\
73 	}
74 
75 /* `meta' options */
76 #define MOUNT_META_OPTION_FSTAB		"fstab"
77 #define MOUNT_META_OPTION_CURRENT	"current"
78 
79 static int debug, fstab_style, verbose;
80 
81 struct cpa {
82 	char	**a;
83 	ssize_t	sz;
84 	int	c;
85 };
86 
87 char   *catopt(char *, const char *);
88 struct statfs *getmntpt(const char *);
89 int	hasopt(const char *, const char *);
90 int	ismounted(struct fstab *, struct statfs *, int);
91 int	isremountable(const char *);
92 void	mangle(char *, struct cpa *);
93 char   *update_options(char *, char *, int);
94 int	mountfs(const char *, const char *, const char *,
95 			int, const char *, const char *);
96 void	remopt(char *, const char *);
97 void	prmount(struct statfs *);
98 void	putfsent(struct statfs *);
99 void	usage(void);
100 char   *flags2opts(int);
101 
102 /* Map from mount options to printable formats. */
103 static struct mntoptnames optnames[] = {
104 	MNTOPT_NAMES
105 };
106 
107 /*
108  * List of VFS types that can be remounted without becoming mounted on top
109  * of each other.
110  * XXX Is this list correct?
111  */
112 static const char *
113 remountable_fs_names[] = {
114 	"ufs", "ffs", "ext2fs",
115 	0
116 };
117 
118 static const char userquotaeq[] = "userquota=";
119 static const char groupquotaeq[] = "groupquota=";
120 
121 static char *mountprog = NULL;
122 
123 static int
124 use_mountprog(const char *vfstype)
125 {
126 	/* XXX: We need to get away from implementing external mount
127 	 *      programs for every filesystem, and move towards having
128 	 *	each filesystem properly implement the nmount() system call.
129 	 */
130 	unsigned int i;
131 	const char *fs[] = {
132 	"cd9660", "mfs", "msdosfs", "nfs",
133 	"nullfs", "smbfs", "udf", "unionfs",
134 	NULL
135 	};
136 
137 	if (mountprog != NULL)
138 		return (1);
139 
140 	for (i = 0; fs[i] != NULL; ++i) {
141 		if (strcmp(vfstype, fs[i]) == 0)
142 			return (1);
143 	}
144 
145 	return (0);
146 }
147 
148 static int
149 exec_mountprog(const char *name, const char *execname, char *const argv[])
150 {
151 	pid_t pid;
152 	int status;
153 
154 	switch (pid = fork()) {
155 	case -1:				/* Error. */
156 		xo_warn("fork");
157 		EXIT(1);
158 	case 0:					/* Child. */
159 		/* Go find an executable. */
160 		execvP(execname, _PATH_SYSPATH, argv);
161 		if (errno == ENOENT) {
162 			xo_warn("exec %s not found", execname);
163 			if (execname[0] != '/') {
164 				xo_warnx("in path: %s", _PATH_SYSPATH);
165 			}
166 		}
167 		EXIT(1);
168 	default:				/* Parent. */
169 		if (waitpid(pid, &status, 0) < 0) {
170 			xo_warn("waitpid");
171 			return (1);
172 		}
173 
174 		if (WIFEXITED(status)) {
175 			if (WEXITSTATUS(status) != 0)
176 				return (WEXITSTATUS(status));
177 		} else if (WIFSIGNALED(status)) {
178 			xo_warnx("%s: %s", name, sys_siglist[WTERMSIG(status)]);
179 			return (1);
180 		}
181 		break;
182 	}
183 
184 	return (0);
185 }
186 
187 static int
188 specified_ro(const char *arg)
189 {
190 	char *optbuf, *opt;
191 	int ret = 0;
192 
193 	optbuf = strdup(arg);
194 	if (optbuf == NULL)
195 		 xo_err(1, "strdup failed");
196 
197 	for (opt = optbuf; (opt = strtok(opt, ",")) != NULL; opt = NULL) {
198 		if (strcmp(opt, "ro") == 0) {
199 			ret = 1;
200 			break;
201 		}
202 	}
203 	free(optbuf);
204 	return (ret);
205 }
206 
207 static void
208 restart_mountd(void)
209 {
210 
211 	pidfile_signal(_PATH_MOUNTDPID, SIGHUP, NULL);
212 }
213 
214 int
215 main(int argc, char *argv[])
216 {
217 	const char *mntfromname, **vfslist, *vfstype;
218 	struct fstab *fs;
219 	struct statfs *mntbuf;
220 	int all, ch, i, init_flags, late, failok, mntsize, rval, have_fstab, ro;
221 	int onlylate;
222 	char *cp, *ep, *options;
223 
224 	all = init_flags = late = onlylate = 0;
225 	ro = 0;
226 	options = NULL;
227 	vfslist = NULL;
228 	vfstype = "ufs";
229 
230 	argc = xo_parse_args(argc, argv);
231 	if (argc < 0)
232 		exit(1);
233 	xo_open_container("mount");
234 
235 	while ((ch = getopt(argc, argv, "adF:fLlno:prt:uvw")) != -1)
236 		switch (ch) {
237 		case 'a':
238 			all = 1;
239 			break;
240 		case 'd':
241 			debug = 1;
242 			break;
243 		case 'F':
244 			setfstab(optarg);
245 			break;
246 		case 'f':
247 			init_flags |= MNT_FORCE;
248 			break;
249 		case 'L':
250 			onlylate = 1;
251 			late = 1;
252 			break;
253 		case 'l':
254 			late = 1;
255 			break;
256 		case 'n':
257 			/* For compatibility with the Linux version of mount. */
258 			break;
259 		case 'o':
260 			if (*optarg) {
261 				options = catopt(options, optarg);
262 				if (specified_ro(optarg))
263 					ro = 1;
264 			}
265 			break;
266 		case 'p':
267 			fstab_style = 1;
268 			verbose = 1;
269 			break;
270 		case 'r':
271 			options = catopt(options, "ro");
272 			ro = 1;
273 			break;
274 		case 't':
275 			if (vfslist != NULL)
276 				xo_errx(1, "only one -t option may be specified");
277 			vfslist = makevfslist(optarg);
278 			vfstype = optarg;
279 			break;
280 		case 'u':
281 			init_flags |= MNT_UPDATE;
282 			break;
283 		case 'v':
284 			verbose = 1;
285 			break;
286 		case 'w':
287 			options = catopt(options, "noro");
288 			break;
289 		case '?':
290 		default:
291 			usage();
292 			/* NOTREACHED */
293 		}
294 	argc -= optind;
295 	argv += optind;
296 
297 #define	BADTYPE(type)							\
298 	(strcmp(type, FSTAB_RO) &&					\
299 	    strcmp(type, FSTAB_RW) && strcmp(type, FSTAB_RQ))
300 
301 	if ((init_flags & MNT_UPDATE) && (ro == 0))
302 		options = catopt(options, "noro");
303 
304 	rval = 0;
305 	switch (argc) {
306 	case 0:
307 		if ((mntsize = getmntinfo(&mntbuf,
308 		     verbose ? MNT_WAIT : MNT_NOWAIT)) == 0)
309 			xo_err(1, "getmntinfo");
310 		if (all) {
311 			while ((fs = getfsent()) != NULL) {
312 				if (BADTYPE(fs->fs_type))
313 					continue;
314 				if (checkvfsname(fs->fs_vfstype, vfslist))
315 					continue;
316 				if (hasopt(fs->fs_mntops, "noauto"))
317 					continue;
318 				if (!hasopt(fs->fs_mntops, "late") && onlylate)
319 					continue;
320 				if (hasopt(fs->fs_mntops, "late") && !late)
321 					continue;
322 				if (hasopt(fs->fs_mntops, "failok"))
323 					failok = 1;
324 				else
325 					failok = 0;
326 				if (!(init_flags & MNT_UPDATE) &&
327 				    !hasopt(fs->fs_mntops, "update") &&
328 				    ismounted(fs, mntbuf, mntsize))
329 					continue;
330 				options = update_options(options, fs->fs_mntops,
331 				    mntbuf->f_flags);
332 				if (mountfs(fs->fs_vfstype, fs->fs_spec,
333 				    fs->fs_file, init_flags, options,
334 				    fs->fs_mntops) && !failok)
335 					rval = 1;
336 			}
337 		} else if (fstab_style) {
338 			xo_open_list("fstab");
339 			for (i = 0; i < mntsize; i++) {
340 				if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
341 					continue;
342 				xo_open_instance("fstab");
343 				putfsent(&mntbuf[i]);
344 				xo_close_instance("fstab");
345 			}
346 			xo_close_list("fstab");
347 		} else {
348 			xo_open_list("mounted");
349 			for (i = 0; i < mntsize; i++) {
350 				if (checkvfsname(mntbuf[i].f_fstypename,
351 				    vfslist))
352 					continue;
353 				if (!verbose &&
354 				    (mntbuf[i].f_flags & MNT_IGNORE) != 0)
355 					continue;
356 				xo_open_instance("mounted");
357 				prmount(&mntbuf[i]);
358 				xo_close_instance("mounted");
359 			}
360 			xo_close_list("mounted");
361 		}
362 		EXIT(rval);
363 	case 1:
364 		if (vfslist != NULL)
365 			usage();
366 
367 		rmslashes(*argv, *argv);
368 		if (init_flags & MNT_UPDATE) {
369 			mntfromname = NULL;
370 			have_fstab = 0;
371 			if ((mntbuf = getmntpt(*argv)) == NULL)
372 				xo_errx(1, "not currently mounted %s", *argv);
373 			/*
374 			 * Only get the mntflags from fstab if both mntpoint
375 			 * and mntspec are identical. Also handle the special
376 			 * case where just '/' is mounted and 'spec' is not
377 			 * identical with the one from fstab ('/dev' is missing
378 			 * in the spec-string at boot-time).
379 			 */
380 			if ((fs = getfsfile(mntbuf->f_mntonname)) != NULL) {
381 				if (strcmp(fs->fs_spec,
382 				    mntbuf->f_mntfromname) == 0 &&
383 				    strcmp(fs->fs_file,
384 				    mntbuf->f_mntonname) == 0) {
385 					have_fstab = 1;
386 					mntfromname = mntbuf->f_mntfromname;
387 				} else if (argv[0][0] == '/' &&
388 				    argv[0][1] == '\0' &&
389 				    strcmp(fs->fs_vfstype,
390 				    mntbuf->f_fstypename) == 0) {
391 					fs = getfsfile("/");
392 					have_fstab = 1;
393 					mntfromname = fs->fs_spec;
394 				}
395 			}
396 			if (have_fstab) {
397 				options = update_options(options, fs->fs_mntops,
398 				    mntbuf->f_flags);
399 			} else {
400 				mntfromname = mntbuf->f_mntfromname;
401 				options = update_options(options, NULL,
402 				    mntbuf->f_flags);
403 			}
404 			rval = mountfs(mntbuf->f_fstypename, mntfromname,
405 			    mntbuf->f_mntonname, init_flags, options, 0);
406 			break;
407 		}
408 		if ((fs = getfsfile(*argv)) == NULL &&
409 		    (fs = getfsspec(*argv)) == NULL)
410 			xo_errx(1, "%s: unknown special file or file system",
411 			    *argv);
412 		if (BADTYPE(fs->fs_type))
413 			xo_errx(1, "%s has unknown file system type",
414 			    *argv);
415 		rval = mountfs(fs->fs_vfstype, fs->fs_spec, fs->fs_file,
416 		    init_flags, options, fs->fs_mntops);
417 		break;
418 	case 2:
419 		/*
420 		 * If -t flag has not been specified, the path cannot be
421 		 * found, spec contains either a ':' or a '@', then assume
422 		 * that an NFS file system is being specified ala Sun.
423 		 * Check if the hostname contains only allowed characters
424 		 * to reduce false positives.  IPv6 addresses containing
425 		 * ':' will be correctly parsed only if the separator is '@'.
426 		 * The definition of a valid hostname is taken from RFC 1034.
427 		 */
428 		if (vfslist == NULL && ((ep = strchr(argv[0], '@')) != NULL ||
429 		    (ep = strchr(argv[0], ':')) != NULL)) {
430 			if (*ep == '@') {
431 				cp = ep + 1;
432 				ep = cp + strlen(cp);
433 			} else
434 				cp = argv[0];
435 			while (cp != ep) {
436 				if (!isdigit(*cp) && !isalpha(*cp) &&
437 				    *cp != '.' && *cp != '-' && *cp != ':')
438 					break;
439 				cp++;
440 			}
441 			if (cp == ep)
442 				vfstype = "nfs";
443 		}
444 		rval = mountfs(vfstype,
445 		    argv[0], argv[1], init_flags, options, NULL);
446 		break;
447 	default:
448 		usage();
449 		/* NOTREACHED */
450 	}
451 
452 	/*
453 	 * If the mount was successfully, and done by root, tell mountd the
454 	 * good news.
455 	 */
456 	if (rval == 0 && getuid() == 0)
457 		restart_mountd();
458 
459 	EXIT(rval);
460 }
461 
462 int
463 ismounted(struct fstab *fs, struct statfs *mntbuf, int mntsize)
464 {
465 	char realfsfile[PATH_MAX];
466 	int i;
467 
468 	if (fs->fs_file[0] == '/' && fs->fs_file[1] == '\0')
469 		/* the root file system can always be remounted */
470 		return (0);
471 
472 	/* The user may have specified a symlink in fstab, resolve the path */
473 	if (realpath(fs->fs_file, realfsfile) == NULL) {
474 		/* Cannot resolve the path, use original one */
475 		strlcpy(realfsfile, fs->fs_file, sizeof(realfsfile));
476 	}
477 
478 	/*
479 	 * Consider the filesystem to be mounted if:
480 	 * It has the same mountpoint as a mounted filesystem, and
481 	 * It has the same type as that same mounted filesystem, and
482 	 * It has the same device name as that same mounted filesystem, OR
483 	 *     It is a nonremountable filesystem
484 	 */
485 	for (i = mntsize - 1; i >= 0; --i)
486 		if (strcmp(realfsfile, mntbuf[i].f_mntonname) == 0 &&
487 		    strcmp(fs->fs_vfstype, mntbuf[i].f_fstypename) == 0 &&
488 		    (!isremountable(fs->fs_vfstype) ||
489 		     (strcmp(fs->fs_spec, mntbuf[i].f_mntfromname) == 0)))
490 			return (1);
491 	return (0);
492 }
493 
494 int
495 isremountable(const char *vfsname)
496 {
497 	const char **cp;
498 
499 	for (cp = remountable_fs_names; *cp; cp++)
500 		if (strcmp(*cp, vfsname) == 0)
501 			return (1);
502 	return (0);
503 }
504 
505 int
506 hasopt(const char *mntopts, const char *option)
507 {
508 	int negative, found;
509 	char *opt, *optbuf;
510 
511 	if (option[0] == 'n' && option[1] == 'o') {
512 		negative = 1;
513 		option += 2;
514 	} else
515 		negative = 0;
516 	optbuf = strdup(mntopts);
517 	found = 0;
518 	for (opt = optbuf; (opt = strtok(opt, ",")) != NULL; opt = NULL) {
519 		if (opt[0] == 'n' && opt[1] == 'o') {
520 			if (!strcasecmp(opt + 2, option))
521 				found = negative;
522 		} else if (!strcasecmp(opt, option))
523 			found = !negative;
524 	}
525 	free(optbuf);
526 	return (found);
527 }
528 
529 static void
530 append_arg(struct cpa *sa, char *arg)
531 {
532 	if (sa->c + 1 == sa->sz) {
533 		sa->sz = sa->sz == 0 ? 8 : sa->sz * 2;
534 		sa->a = realloc(sa->a, sizeof(*sa->a) * sa->sz);
535 		if (sa->a == NULL)
536 			xo_errx(1, "realloc failed");
537 	}
538 	sa->a[++sa->c] = arg;
539 }
540 
541 int
542 mountfs(const char *vfstype, const char *spec, const char *name, int flags,
543 	const char *options, const char *mntopts)
544 {
545 	struct statfs sf;
546 	int i, ret;
547 	char *optbuf, execname[PATH_MAX], mntpath[PATH_MAX];
548 	static struct cpa mnt_argv;
549 
550 	/* resolve the mountpoint with realpath(3) */
551 	if (checkpath(name, mntpath) != 0) {
552 		xo_warn("%s", mntpath);
553 		return (1);
554 	}
555 	name = mntpath;
556 
557 	if (mntopts == NULL)
558 		mntopts = "";
559 	optbuf = catopt(strdup(mntopts), options);
560 
561 	if (strcmp(name, "/") == 0)
562 		flags |= MNT_UPDATE;
563 	if (flags & MNT_FORCE)
564 		optbuf = catopt(optbuf, "force");
565 	if (flags & MNT_RDONLY)
566 		optbuf = catopt(optbuf, "ro");
567 	/*
568 	 * XXX
569 	 * The mount_mfs (newfs) command uses -o to select the
570 	 * optimization mode.  We don't pass the default "-o rw"
571 	 * for that reason.
572 	 */
573 	if (flags & MNT_UPDATE)
574 		optbuf = catopt(optbuf, "update");
575 
576 	/* Compatibility glue. */
577 	if (strcmp(vfstype, "msdos") == 0)
578 		vfstype = "msdosfs";
579 
580 	/* Construct the name of the appropriate mount command */
581 	(void)snprintf(execname, sizeof(execname), "mount_%s", vfstype);
582 
583 	mnt_argv.c = -1;
584 	append_arg(&mnt_argv, execname);
585 	mangle(optbuf, &mnt_argv);
586 	if (mountprog != NULL)
587 		strlcpy(execname, mountprog, sizeof(execname));
588 
589 	append_arg(&mnt_argv, strdup(spec));
590 	append_arg(&mnt_argv, strdup(name));
591 	append_arg(&mnt_argv, NULL);
592 
593 	if (debug) {
594 		if (use_mountprog(vfstype))
595 			xo_emit("{Lwc:exec}{:execname/%s}", execname);
596 		else
597 			xo_emit("{:execname/mount}{P: }{l:opts/-t}{P: }{l:opts/%s}", vfstype);
598 		for (i = 1; i < mnt_argv.c; i++)
599 			xo_emit("{P: }{l:opts}", mnt_argv.a[i]);
600 		xo_emit("\n");
601 		free(optbuf);
602 		free(mountprog);
603 		mountprog = NULL;
604 		return (0);
605 	}
606 
607 	if (use_mountprog(vfstype)) {
608 		ret = exec_mountprog(name, execname, mnt_argv.a);
609 	} else {
610 		ret = mount_fs(vfstype, mnt_argv.c, mnt_argv.a);
611 	}
612 
613 	free(optbuf);
614 	free(mountprog);
615 	mountprog = NULL;
616 
617 	if (verbose) {
618 		if (statfs(name, &sf) < 0) {
619 			xo_warn("statfs %s", name);
620 			return (1);
621 		}
622 		if (fstab_style) {
623 			xo_open_list("fstab");
624 			xo_open_instance("fstab");
625 			putfsent(&sf);
626 			xo_close_instance("fstab");
627 			xo_close_list("fstab");
628 		} else {
629 			xo_open_list("mounted");
630 			xo_open_instance("mounted");
631 			prmount(&sf);
632 			xo_close_instance("mounted");
633 			xo_close_list("mounted");
634 		}
635 	}
636 
637 	return (ret);
638 }
639 
640 void
641 prmount(struct statfs *sfp)
642 {
643 	uint64_t flags;
644 	unsigned int i;
645 	struct mntoptnames *o;
646 	struct passwd *pw;
647 	char *fsidbuf;
648 
649 	xo_emit("{:special/%hs}{L: on }{:node/%hs}{L: (}{:fstype}", sfp->f_mntfromname,
650 	    sfp->f_mntonname, sfp->f_fstypename);
651 
652 	flags = sfp->f_flags & MNT_VISFLAGMASK;
653 	for (o = optnames; flags != 0 && o->o_opt != 0; o++)
654 		if (flags & o->o_opt) {
655 			xo_emit("{D:, }{l:opts}", o->o_name);
656 			flags &= ~o->o_opt;
657 		}
658 	/*
659 	 * Inform when file system is mounted by an unprivileged user
660 	 * or privileged non-root user.
661 	 */
662 	if ((flags & MNT_USER) != 0 || sfp->f_owner != 0) {
663 		xo_emit("{D:, }{L:mounted by }");
664 		if ((pw = getpwuid(sfp->f_owner)) != NULL)
665 			xo_emit("{:mounter/%hs}", pw->pw_name);
666 		else
667 			xo_emit("{:mounter/%hs}", sfp->f_owner);
668 	}
669 	if (verbose) {
670 		if (sfp->f_syncwrites != 0 || sfp->f_asyncwrites != 0) {
671 			xo_open_container("writes");
672 			xo_emit("{D:, }{Lwc:writes}{Lw:sync}{w:sync/%ju}{Lw:async}{:async/%ju}",
673 			    (uintmax_t)sfp->f_syncwrites,
674 			    (uintmax_t)sfp->f_asyncwrites);
675 			xo_close_container("writes");
676 		}
677 		if (sfp->f_syncreads != 0 || sfp->f_asyncreads != 0) {
678 			xo_open_container("reads");
679 			xo_emit("{D:, }{Lwc:reads}{Lw:sync}{w:sync/%ju}{Lw:async}{:async/%ju}",
680 			    (uintmax_t)sfp->f_syncreads,
681 			    (uintmax_t)sfp->f_asyncreads);
682 			xo_close_container("reads");
683 		}
684 		if (sfp->f_fsid.val[0] != 0 || sfp->f_fsid.val[1] != 0) {
685 			fsidbuf = malloc(sizeof(sfp->f_fsid) * 2 + 1);
686 			if (fsidbuf == NULL)
687 				xo_errx(1, "malloc failed");
688 			for (i = 0; i < sizeof(sfp->f_fsid); i++)
689 				sprintf(&fsidbuf[i * 2], "%02x",
690 				    ((u_char *)&sfp->f_fsid)[i]);
691 			fsidbuf[i * 2] = '\0';
692 			xo_emit("{D:, }{Lw:fsid}{:fsid}", fsidbuf);
693 			free(fsidbuf);
694 		}
695 		if (sfp->f_nvnodelistsize != 0) {
696 			xo_open_container("vnodes");
697 			xo_emit("{D:, }{Lwc:vnodes}{Lw:count}{w:count/%ju}",
698 			    (uintmax_t)sfp->f_nvnodelistsize);
699 			xo_close_container("vnodes");
700 		}
701 	}
702 	xo_emit("{D:)}\n");
703 }
704 
705 struct statfs *
706 getmntpt(const char *name)
707 {
708 	struct statfs *mntbuf;
709 	int i, mntsize;
710 
711 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
712 	for (i = mntsize - 1; i >= 0; i--) {
713 		if (strcmp(mntbuf[i].f_mntfromname, name) == 0 ||
714 		    strcmp(mntbuf[i].f_mntonname, name) == 0)
715 			return (&mntbuf[i]);
716 	}
717 	return (NULL);
718 }
719 
720 char *
721 catopt(char *s0, const char *s1)
722 {
723 	char *cp;
724 
725 	if (s1 == NULL || *s1 == '\0')
726 		return (s0);
727 
728 	if (s0 && *s0) {
729 		if (asprintf(&cp, "%s,%s", s0, s1) == -1)
730 			xo_errx(1, "asprintf failed");
731 	} else
732 		cp = strdup(s1);
733 
734 	if (s0)
735 		free(s0);
736 	return (cp);
737 }
738 
739 void
740 mangle(char *options, struct cpa *a)
741 {
742 	char *p, *s, *val;
743 
744 	for (s = options; (p = strsep(&s, ",")) != NULL;)
745 		if (*p != '\0') {
746 			if (strcmp(p, "noauto") == 0) {
747 				/*
748 				 * Do not pass noauto option to nmount().
749 				 * or external mount program.  noauto is
750 				 * only used to prevent mounting a filesystem
751 				 * when 'mount -a' is specified, and is
752 				 * not a real mount option.
753 				 */
754 				continue;
755 			} else if (strcmp(p, "late") == 0) {
756 				/*
757 				 * "late" is used to prevent certain file
758 				 * systems from being mounted before late
759 				 * in the boot cycle; for instance,
760 				 * loopback NFS mounts can't be mounted
761 				 * before mountd starts.
762 				 */
763 				continue;
764 			} else if (strcmp(p, "failok") == 0) {
765 				/*
766 				 * "failok" is used to prevent certain file
767 				 * systems from being causing the system to
768 				 * drop into single user mode in the boot
769 				 * cycle, and is not a real mount option.
770 				 */
771 				continue;
772 			} else if (strncmp(p, "mountprog", 9) == 0) {
773 				/*
774 				 * "mountprog" is used to force the use of
775 				 * userland mount programs.
776 				 */
777 				val = strchr(p, '=');
778                         	if (val != NULL) {
779                                 	++val;
780 					if (*val != '\0')
781 						mountprog = strdup(val);
782 				}
783 
784 				if (mountprog == NULL) {
785 					xo_errx(1, "Need value for -o mountprog");
786 				}
787 				continue;
788 			} else if (strcmp(p, "userquota") == 0) {
789 				continue;
790 			} else if (strncmp(p, userquotaeq,
791 			    sizeof(userquotaeq) - 1) == 0) {
792 				continue;
793 			} else if (strcmp(p, "groupquota") == 0) {
794 				continue;
795 			} else if (strncmp(p, groupquotaeq,
796 			    sizeof(groupquotaeq) - 1) == 0) {
797 				continue;
798 			} else if (*p == '-') {
799 				append_arg(a, p);
800 				p = strchr(p, '=');
801 				if (p != NULL) {
802 					*p = '\0';
803 					append_arg(a, p + 1);
804 				}
805 			} else {
806 				append_arg(a, strdup("-o"));
807 				append_arg(a, p);
808 			}
809 		}
810 }
811 
812 
813 char *
814 update_options(char *opts, char *fstab, int curflags)
815 {
816 	char *o, *p;
817 	char *cur;
818 	char *expopt, *newopt, *tmpopt;
819 
820 	if (opts == NULL)
821 		return (strdup(""));
822 
823 	/* remove meta options from list */
824 	remopt(fstab, MOUNT_META_OPTION_FSTAB);
825 	remopt(fstab, MOUNT_META_OPTION_CURRENT);
826 	cur = flags2opts(curflags);
827 
828 	/*
829 	 * Expand all meta-options passed to us first.
830 	 */
831 	expopt = NULL;
832 	for (p = opts; (o = strsep(&p, ",")) != NULL;) {
833 		if (strcmp(MOUNT_META_OPTION_FSTAB, o) == 0)
834 			expopt = catopt(expopt, fstab);
835 		else if (strcmp(MOUNT_META_OPTION_CURRENT, o) == 0)
836 			expopt = catopt(expopt, cur);
837 		else
838 			expopt = catopt(expopt, o);
839 	}
840 	free(cur);
841 	free(opts);
842 
843 	/*
844 	 * Remove previous contradictory arguments. Given option "foo" we
845 	 * remove all the "nofoo" options. Given "nofoo" we remove "nonofoo"
846 	 * and "foo" - so we can deal with possible options like "notice".
847 	 */
848 	newopt = NULL;
849 	for (p = expopt; (o = strsep(&p, ",")) != NULL;) {
850 		if ((tmpopt = malloc( strlen(o) + 2 + 1 )) == NULL)
851 			xo_errx(1, "malloc failed");
852 
853 		strcpy(tmpopt, "no");
854 		strcat(tmpopt, o);
855 		remopt(newopt, tmpopt);
856 		free(tmpopt);
857 
858 		if (strncmp("no", o, 2) == 0)
859 			remopt(newopt, o+2);
860 
861 		newopt = catopt(newopt, o);
862 	}
863 	free(expopt);
864 
865 	return (newopt);
866 }
867 
868 void
869 remopt(char *string, const char *opt)
870 {
871 	char *o, *p, *r;
872 
873 	if (string == NULL || *string == '\0' || opt == NULL || *opt == '\0')
874 		return;
875 
876 	r = string;
877 
878 	for (p = string; (o = strsep(&p, ",")) != NULL;) {
879 		if (strcmp(opt, o) != 0) {
880 			if (*r == ',' && *o != '\0')
881 				r++;
882 			while ((*r++ = *o++) != '\0')
883 			    ;
884 			*--r = ',';
885 		}
886 	}
887 	*r = '\0';
888 }
889 
890 void
891 usage(void)
892 {
893 
894 	xo_error("%s\n%s\n%s\n",
895 "usage: mount [-adflpruvw] [-F fstab] [-o options] [-t ufs | external_type]",
896 "       mount [-dfpruvw] special | node",
897 "       mount [-dfpruvw] [-o options] [-t ufs | external_type] special node");
898 	EXIT(1);
899 }
900 
901 void
902 putfsent(struct statfs *ent)
903 {
904 	struct fstab *fst;
905 	char *opts, *rw;
906 	int l;
907 
908 	opts = NULL;
909 	/* flags2opts() doesn't return the "rw" option. */
910 	if ((ent->f_flags & MNT_RDONLY) != 0)
911 		rw = NULL;
912 	else
913 		rw = catopt(NULL, "rw");
914 
915 	opts = flags2opts(ent->f_flags);
916 	opts = catopt(rw, opts);
917 
918 	if (strncmp(ent->f_mntfromname, "<below>", 7) == 0 ||
919 	    strncmp(ent->f_mntfromname, "<above>", 7) == 0) {
920 		strlcpy(ent->f_mntfromname,
921 		    (strnstr(ent->f_mntfromname, ":", 8) +1),
922 		    sizeof(ent->f_mntfromname));
923 	}
924 
925 	l = strlen(ent->f_mntfromname);
926 	xo_emit("{:device}{P:/%s}{P:/%s}{P:/%s}",
927 	    ent->f_mntfromname,
928 	    l < 8 ? "\t" : "",
929 	    l < 16 ? "\t" : "",
930 	    l < 24 ? "\t" : " ");
931 	l = strlen(ent->f_mntonname);
932 	xo_emit("{:mntpoint}{P:/%s}{P:/%s}{P:/%s}",
933 	    ent->f_mntonname,
934 	    l < 8 ? "\t" : "",
935 	    l < 16 ? "\t" : "",
936 	    l < 24 ? "\t" : " ");
937 	xo_emit("{:fstype}{P:\t}", ent->f_fstypename);
938 	l = strlen(opts);
939 	xo_emit("{:opts}{P:/%s}", opts,
940 	    l < 8 ? "\t" : " ");
941 	free(opts);
942 
943 	if ((fst = getfsspec(ent->f_mntfromname)))
944 		xo_emit("{P:\t}{n:dump/%u}{P: }{n:pass/%u}\n",
945 		    fst->fs_freq, fst->fs_passno);
946 	else if ((fst = getfsfile(ent->f_mntonname)))
947 		xo_emit("{P:\t}{n:dump/%u}{P: }{n:pass/%u}\n",
948 		    fst->fs_freq, fst->fs_passno);
949 	else if (strcmp(ent->f_fstypename, "ufs") == 0) {
950 		if (strcmp(ent->f_mntonname, "/") == 0)
951 			xo_emit("{P:\t}{n:dump/1}{P: }{n:pass/1}\n");
952 		else
953 			xo_emit("{P:\t}{n:dump/2}{P: }{n:pass/2}\n");
954 	} else
955 		xo_emit("{P:\t}{n:dump/0}{P: }{n:pass/0}\n");
956 }
957 
958 
959 char *
960 flags2opts(int flags)
961 {
962 	char *res;
963 
964 	res = NULL;
965 
966 	if (flags & MNT_RDONLY)		res = catopt(res, "ro");
967 	if (flags & MNT_SYNCHRONOUS)	res = catopt(res, "sync");
968 	if (flags & MNT_NOEXEC)		res = catopt(res, "noexec");
969 	if (flags & MNT_NOSUID)		res = catopt(res, "nosuid");
970 	if (flags & MNT_UNION)		res = catopt(res, "union");
971 	if (flags & MNT_ASYNC)		res = catopt(res, "async");
972 	if (flags & MNT_NOATIME)	res = catopt(res, "noatime");
973 	if (flags & MNT_NOCLUSTERR)	res = catopt(res, "noclusterr");
974 	if (flags & MNT_NOCLUSTERW)	res = catopt(res, "noclusterw");
975 	if (flags & MNT_NOSYMFOLLOW)	res = catopt(res, "nosymfollow");
976 	if (flags & MNT_SUIDDIR)	res = catopt(res, "suiddir");
977 	if (flags & MNT_MULTILABEL)	res = catopt(res, "multilabel");
978 	if (flags & MNT_ACLS)		res = catopt(res, "acls");
979 	if (flags & MNT_NFS4ACLS)	res = catopt(res, "nfsv4acls");
980 	if (flags & MNT_UNTRUSTED)	res = catopt(res, "untrusted");
981 	if (flags & MNT_NOCOVER)	res = catopt(res, "nocover");
982 	if (flags & MNT_EMPTYDIR)	res = catopt(res, "emptydir");
983 
984 	return (res);
985 }
986