xref: /freebsd/sbin/mount/mount.c (revision 66df505066f51e6d8411b966765d828817f88971)
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 	struct pidfh *pfh;
211 	pid_t mountdpid;
212 
213 	mountdpid = 0;
214 	pfh = pidfile_open(_PATH_MOUNTDPID, 0600, &mountdpid);
215 	if (pfh != NULL) {
216 		/* Mountd is not running. */
217 		pidfile_remove(pfh);
218 		return;
219 	}
220 	if (errno != EEXIST) {
221 		/* Cannot open pidfile for some reason. */
222 		return;
223 	}
224 
225 	/*
226 	 * Refuse to send broadcast or group signals, this has
227 	 * happened due to the bugs in pidfile(3).
228 	 */
229 	if (mountdpid <= 0) {
230 		xo_warnx("mountd pid %d, refusing to send SIGHUP", mountdpid);
231 		return;
232 	}
233 
234 	/* We have mountd(8) PID in mountdpid varible, let's signal it. */
235 	if (kill(mountdpid, SIGHUP) == -1)
236 		xo_err(1, "signal mountd");
237 }
238 
239 int
240 main(int argc, char *argv[])
241 {
242 	const char *mntfromname, **vfslist, *vfstype;
243 	struct fstab *fs;
244 	struct statfs *mntbuf;
245 	int all, ch, i, init_flags, late, failok, mntsize, rval, have_fstab, ro;
246 	int onlylate;
247 	char *cp, *ep, *options;
248 
249 	all = init_flags = late = onlylate = 0;
250 	ro = 0;
251 	options = NULL;
252 	vfslist = NULL;
253 	vfstype = "ufs";
254 
255 	argc = xo_parse_args(argc, argv);
256 	if (argc < 0)
257 		exit(1);
258 	xo_open_container("mount");
259 
260 	while ((ch = getopt(argc, argv, "adF:fLlno:prt:uvw")) != -1)
261 		switch (ch) {
262 		case 'a':
263 			all = 1;
264 			break;
265 		case 'd':
266 			debug = 1;
267 			break;
268 		case 'F':
269 			setfstab(optarg);
270 			break;
271 		case 'f':
272 			init_flags |= MNT_FORCE;
273 			break;
274 		case 'L':
275 			onlylate = 1;
276 			late = 1;
277 			break;
278 		case 'l':
279 			late = 1;
280 			break;
281 		case 'n':
282 			/* For compatibility with the Linux version of mount. */
283 			break;
284 		case 'o':
285 			if (*optarg) {
286 				options = catopt(options, optarg);
287 				if (specified_ro(optarg))
288 					ro = 1;
289 			}
290 			break;
291 		case 'p':
292 			fstab_style = 1;
293 			verbose = 1;
294 			break;
295 		case 'r':
296 			options = catopt(options, "ro");
297 			ro = 1;
298 			break;
299 		case 't':
300 			if (vfslist != NULL)
301 				xo_errx(1, "only one -t option may be specified");
302 			vfslist = makevfslist(optarg);
303 			vfstype = optarg;
304 			break;
305 		case 'u':
306 			init_flags |= MNT_UPDATE;
307 			break;
308 		case 'v':
309 			verbose = 1;
310 			break;
311 		case 'w':
312 			options = catopt(options, "noro");
313 			break;
314 		case '?':
315 		default:
316 			usage();
317 			/* NOTREACHED */
318 		}
319 	argc -= optind;
320 	argv += optind;
321 
322 #define	BADTYPE(type)							\
323 	(strcmp(type, FSTAB_RO) &&					\
324 	    strcmp(type, FSTAB_RW) && strcmp(type, FSTAB_RQ))
325 
326 	if ((init_flags & MNT_UPDATE) && (ro == 0))
327 		options = catopt(options, "noro");
328 
329 	rval = 0;
330 	switch (argc) {
331 	case 0:
332 		if ((mntsize = getmntinfo(&mntbuf,
333 		     verbose ? MNT_WAIT : MNT_NOWAIT)) == 0)
334 			xo_err(1, "getmntinfo");
335 		if (all) {
336 			while ((fs = getfsent()) != NULL) {
337 				if (BADTYPE(fs->fs_type))
338 					continue;
339 				if (checkvfsname(fs->fs_vfstype, vfslist))
340 					continue;
341 				if (hasopt(fs->fs_mntops, "noauto"))
342 					continue;
343 				if (!hasopt(fs->fs_mntops, "late") && onlylate)
344 					continue;
345 				if (hasopt(fs->fs_mntops, "late") && !late)
346 					continue;
347 				if (hasopt(fs->fs_mntops, "failok"))
348 					failok = 1;
349 				else
350 					failok = 0;
351 				if (!(init_flags & MNT_UPDATE) &&
352 				    !hasopt(fs->fs_mntops, "update") &&
353 				    ismounted(fs, mntbuf, mntsize))
354 					continue;
355 				options = update_options(options, fs->fs_mntops,
356 				    mntbuf->f_flags);
357 				if (mountfs(fs->fs_vfstype, fs->fs_spec,
358 				    fs->fs_file, init_flags, options,
359 				    fs->fs_mntops) && !failok)
360 					rval = 1;
361 			}
362 		} else if (fstab_style) {
363 			xo_open_list("fstab");
364 			for (i = 0; i < mntsize; i++) {
365 				if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
366 					continue;
367 				xo_open_instance("fstab");
368 				putfsent(&mntbuf[i]);
369 				xo_close_instance("fstab");
370 			}
371 			xo_close_list("fstab");
372 		} else {
373 			xo_open_list("mounted");
374 			for (i = 0; i < mntsize; i++) {
375 				if (checkvfsname(mntbuf[i].f_fstypename,
376 				    vfslist))
377 					continue;
378 				if (!verbose &&
379 				    (mntbuf[i].f_flags & MNT_IGNORE) != 0)
380 					continue;
381 				xo_open_instance("mounted");
382 				prmount(&mntbuf[i]);
383 				xo_close_instance("mounted");
384 			}
385 			xo_close_list("mounted");
386 		}
387 		EXIT(rval);
388 	case 1:
389 		if (vfslist != NULL)
390 			usage();
391 
392 		rmslashes(*argv, *argv);
393 		if (init_flags & MNT_UPDATE) {
394 			mntfromname = NULL;
395 			have_fstab = 0;
396 			if ((mntbuf = getmntpt(*argv)) == NULL)
397 				xo_errx(1, "not currently mounted %s", *argv);
398 			/*
399 			 * Only get the mntflags from fstab if both mntpoint
400 			 * and mntspec are identical. Also handle the special
401 			 * case where just '/' is mounted and 'spec' is not
402 			 * identical with the one from fstab ('/dev' is missing
403 			 * in the spec-string at boot-time).
404 			 */
405 			if ((fs = getfsfile(mntbuf->f_mntonname)) != NULL) {
406 				if (strcmp(fs->fs_spec,
407 				    mntbuf->f_mntfromname) == 0 &&
408 				    strcmp(fs->fs_file,
409 				    mntbuf->f_mntonname) == 0) {
410 					have_fstab = 1;
411 					mntfromname = mntbuf->f_mntfromname;
412 				} else if (argv[0][0] == '/' &&
413 				    argv[0][1] == '\0' &&
414 				    strcmp(fs->fs_vfstype,
415 				    mntbuf->f_fstypename) == 0) {
416 					fs = getfsfile("/");
417 					have_fstab = 1;
418 					mntfromname = fs->fs_spec;
419 				}
420 			}
421 			if (have_fstab) {
422 				options = update_options(options, fs->fs_mntops,
423 				    mntbuf->f_flags);
424 			} else {
425 				mntfromname = mntbuf->f_mntfromname;
426 				options = update_options(options, NULL,
427 				    mntbuf->f_flags);
428 			}
429 			rval = mountfs(mntbuf->f_fstypename, mntfromname,
430 			    mntbuf->f_mntonname, init_flags, options, 0);
431 			break;
432 		}
433 		if ((fs = getfsfile(*argv)) == NULL &&
434 		    (fs = getfsspec(*argv)) == NULL)
435 			xo_errx(1, "%s: unknown special file or file system",
436 			    *argv);
437 		if (BADTYPE(fs->fs_type))
438 			xo_errx(1, "%s has unknown file system type",
439 			    *argv);
440 		rval = mountfs(fs->fs_vfstype, fs->fs_spec, fs->fs_file,
441 		    init_flags, options, fs->fs_mntops);
442 		break;
443 	case 2:
444 		/*
445 		 * If -t flag has not been specified, the path cannot be
446 		 * found, spec contains either a ':' or a '@', then assume
447 		 * that an NFS file system is being specified ala Sun.
448 		 * Check if the hostname contains only allowed characters
449 		 * to reduce false positives.  IPv6 addresses containing
450 		 * ':' will be correctly parsed only if the separator is '@'.
451 		 * The definition of a valid hostname is taken from RFC 1034.
452 		 */
453 		if (vfslist == NULL && ((ep = strchr(argv[0], '@')) != NULL ||
454 		    (ep = strchr(argv[0], ':')) != NULL)) {
455 			if (*ep == '@') {
456 				cp = ep + 1;
457 				ep = cp + strlen(cp);
458 			} else
459 				cp = argv[0];
460 			while (cp != ep) {
461 				if (!isdigit(*cp) && !isalpha(*cp) &&
462 				    *cp != '.' && *cp != '-' && *cp != ':')
463 					break;
464 				cp++;
465 			}
466 			if (cp == ep)
467 				vfstype = "nfs";
468 		}
469 		rval = mountfs(vfstype,
470 		    argv[0], argv[1], init_flags, options, NULL);
471 		break;
472 	default:
473 		usage();
474 		/* NOTREACHED */
475 	}
476 
477 	/*
478 	 * If the mount was successfully, and done by root, tell mountd the
479 	 * good news.
480 	 */
481 	if (rval == 0 && getuid() == 0)
482 		restart_mountd();
483 
484 	EXIT(rval);
485 }
486 
487 int
488 ismounted(struct fstab *fs, struct statfs *mntbuf, int mntsize)
489 {
490 	char realfsfile[PATH_MAX];
491 	int i;
492 
493 	if (fs->fs_file[0] == '/' && fs->fs_file[1] == '\0')
494 		/* the root file system can always be remounted */
495 		return (0);
496 
497 	/* The user may have specified a symlink in fstab, resolve the path */
498 	if (realpath(fs->fs_file, realfsfile) == NULL) {
499 		/* Cannot resolve the path, use original one */
500 		strlcpy(realfsfile, fs->fs_file, sizeof(realfsfile));
501 	}
502 
503 	/*
504 	 * Consider the filesystem to be mounted if:
505 	 * It has the same mountpoint as a mounted filesytem, and
506 	 * It has the same type as that same mounted filesystem, and
507 	 * It has the same device name as that same mounted filesystem, OR
508 	 *     It is a nonremountable filesystem
509 	 */
510 	for (i = mntsize - 1; i >= 0; --i)
511 		if (strcmp(realfsfile, mntbuf[i].f_mntonname) == 0 &&
512 		    strcmp(fs->fs_vfstype, mntbuf[i].f_fstypename) == 0 &&
513 		    (!isremountable(fs->fs_vfstype) ||
514 		     (strcmp(fs->fs_spec, mntbuf[i].f_mntfromname) == 0)))
515 			return (1);
516 	return (0);
517 }
518 
519 int
520 isremountable(const char *vfsname)
521 {
522 	const char **cp;
523 
524 	for (cp = remountable_fs_names; *cp; cp++)
525 		if (strcmp(*cp, vfsname) == 0)
526 			return (1);
527 	return (0);
528 }
529 
530 int
531 hasopt(const char *mntopts, const char *option)
532 {
533 	int negative, found;
534 	char *opt, *optbuf;
535 
536 	if (option[0] == 'n' && option[1] == 'o') {
537 		negative = 1;
538 		option += 2;
539 	} else
540 		negative = 0;
541 	optbuf = strdup(mntopts);
542 	found = 0;
543 	for (opt = optbuf; (opt = strtok(opt, ",")) != NULL; opt = NULL) {
544 		if (opt[0] == 'n' && opt[1] == 'o') {
545 			if (!strcasecmp(opt + 2, option))
546 				found = negative;
547 		} else if (!strcasecmp(opt, option))
548 			found = !negative;
549 	}
550 	free(optbuf);
551 	return (found);
552 }
553 
554 static void
555 append_arg(struct cpa *sa, char *arg)
556 {
557 	if (sa->c + 1 == sa->sz) {
558 		sa->sz = sa->sz == 0 ? 8 : sa->sz * 2;
559 		sa->a = realloc(sa->a, sizeof(*sa->a) * sa->sz);
560 		if (sa->a == NULL)
561 			xo_errx(1, "realloc failed");
562 	}
563 	sa->a[++sa->c] = arg;
564 }
565 
566 int
567 mountfs(const char *vfstype, const char *spec, const char *name, int flags,
568 	const char *options, const char *mntopts)
569 {
570 	struct statfs sf;
571 	int i, ret;
572 	char *optbuf, execname[PATH_MAX], mntpath[PATH_MAX];
573 	static struct cpa mnt_argv;
574 
575 	/* resolve the mountpoint with realpath(3) */
576 	if (checkpath(name, mntpath) != 0) {
577 		xo_warn("%s", mntpath);
578 		return (1);
579 	}
580 	name = mntpath;
581 
582 	if (mntopts == NULL)
583 		mntopts = "";
584 	optbuf = catopt(strdup(mntopts), options);
585 
586 	if (strcmp(name, "/") == 0)
587 		flags |= MNT_UPDATE;
588 	if (flags & MNT_FORCE)
589 		optbuf = catopt(optbuf, "force");
590 	if (flags & MNT_RDONLY)
591 		optbuf = catopt(optbuf, "ro");
592 	/*
593 	 * XXX
594 	 * The mount_mfs (newfs) command uses -o to select the
595 	 * optimization mode.  We don't pass the default "-o rw"
596 	 * for that reason.
597 	 */
598 	if (flags & MNT_UPDATE)
599 		optbuf = catopt(optbuf, "update");
600 
601 	/* Compatibility glue. */
602 	if (strcmp(vfstype, "msdos") == 0)
603 		vfstype = "msdosfs";
604 
605 	/* Construct the name of the appropriate mount command */
606 	(void)snprintf(execname, sizeof(execname), "mount_%s", vfstype);
607 
608 	mnt_argv.c = -1;
609 	append_arg(&mnt_argv, execname);
610 	mangle(optbuf, &mnt_argv);
611 	if (mountprog != NULL)
612 		strlcpy(execname, mountprog, sizeof(execname));
613 
614 	append_arg(&mnt_argv, strdup(spec));
615 	append_arg(&mnt_argv, strdup(name));
616 	append_arg(&mnt_argv, NULL);
617 
618 	if (debug) {
619 		if (use_mountprog(vfstype))
620 			xo_emit("{Lwc:exec}{:execname/%s}", execname);
621 		else
622 			xo_emit("{:execname/mount}{P: }{l:opts/-t}{P: }{l:opts/%s}", vfstype);
623 		for (i = 1; i < mnt_argv.c; i++)
624 			xo_emit("{P: }{l:opts}", mnt_argv.a[i]);
625 		xo_emit("\n");
626 		free(optbuf);
627 		free(mountprog);
628 		mountprog = NULL;
629 		return (0);
630 	}
631 
632 	if (use_mountprog(vfstype)) {
633 		ret = exec_mountprog(name, execname, mnt_argv.a);
634 	} else {
635 		ret = mount_fs(vfstype, mnt_argv.c, mnt_argv.a);
636 	}
637 
638 	free(optbuf);
639 	free(mountprog);
640 	mountprog = NULL;
641 
642 	if (verbose) {
643 		if (statfs(name, &sf) < 0) {
644 			xo_warn("statfs %s", name);
645 			return (1);
646 		}
647 		if (fstab_style) {
648 			xo_open_list("fstab");
649 			xo_open_instance("fstab");
650 			putfsent(&sf);
651 			xo_close_instance("fstab");
652 			xo_close_list("fstab");
653 		} else {
654 			xo_open_list("mounted");
655 			xo_open_instance("mounted");
656 			prmount(&sf);
657 			xo_close_instance("mounted");
658 			xo_close_list("mounted");
659 		}
660 	}
661 
662 	return (ret);
663 }
664 
665 void
666 prmount(struct statfs *sfp)
667 {
668 	uint64_t flags;
669 	unsigned int i;
670 	struct mntoptnames *o;
671 	struct passwd *pw;
672 	char *fsidbuf;
673 
674 	xo_emit("{:special/%hs}{L: on }{:node/%hs}{L: (}{:fstype}", sfp->f_mntfromname,
675 	    sfp->f_mntonname, sfp->f_fstypename);
676 
677 	flags = sfp->f_flags & MNT_VISFLAGMASK;
678 	for (o = optnames; flags != 0 && o->o_opt != 0; o++)
679 		if (flags & o->o_opt) {
680 			xo_emit("{D:, }{l:opts}", o->o_name);
681 			flags &= ~o->o_opt;
682 		}
683 	/*
684 	 * Inform when file system is mounted by an unprivileged user
685 	 * or privileged non-root user.
686 	 */
687 	if ((flags & MNT_USER) != 0 || sfp->f_owner != 0) {
688 		xo_emit("{D:, }{L:mounted by }");
689 		if ((pw = getpwuid(sfp->f_owner)) != NULL)
690 			xo_emit("{:mounter/%hs}", pw->pw_name);
691 		else
692 			xo_emit("{:mounter/%hs}", sfp->f_owner);
693 	}
694 	if (verbose) {
695 		if (sfp->f_syncwrites != 0 || sfp->f_asyncwrites != 0) {
696 			xo_open_container("writes");
697 			xo_emit("{D:, }{Lwc:writes}{Lw:sync}{w:sync/%ju}{Lw:async}{:async/%ju}",
698 			    (uintmax_t)sfp->f_syncwrites,
699 			    (uintmax_t)sfp->f_asyncwrites);
700 			xo_close_container("writes");
701 		}
702 		if (sfp->f_syncreads != 0 || sfp->f_asyncreads != 0) {
703 			xo_open_container("reads");
704 			xo_emit("{D:, }{Lwc:reads}{Lw:sync}{w:sync/%ju}{Lw:async}{:async/%ju}",
705 			    (uintmax_t)sfp->f_syncreads,
706 			    (uintmax_t)sfp->f_asyncreads);
707 			xo_close_container("reads");
708 		}
709 		if (sfp->f_fsid.val[0] != 0 || sfp->f_fsid.val[1] != 0) {
710 			fsidbuf = malloc(sizeof(sfp->f_fsid) * 2 + 1);
711 			if (fsidbuf == NULL)
712 				xo_errx(1, "malloc failed");
713 			for (i = 0; i < sizeof(sfp->f_fsid); i++)
714 				sprintf(&fsidbuf[i * 2], "%02x",
715 				    ((u_char *)&sfp->f_fsid)[i]);
716 			fsidbuf[i * 2] = '\0';
717 			xo_emit("{D:, }{Lw:fsid}{:fsid}", fsidbuf);
718 			free(fsidbuf);
719 		}
720 	}
721 	xo_emit("{D:)}\n");
722 }
723 
724 struct statfs *
725 getmntpt(const char *name)
726 {
727 	struct statfs *mntbuf;
728 	int i, mntsize;
729 
730 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
731 	for (i = mntsize - 1; i >= 0; i--) {
732 		if (strcmp(mntbuf[i].f_mntfromname, name) == 0 ||
733 		    strcmp(mntbuf[i].f_mntonname, name) == 0)
734 			return (&mntbuf[i]);
735 	}
736 	return (NULL);
737 }
738 
739 char *
740 catopt(char *s0, const char *s1)
741 {
742 	char *cp;
743 
744 	if (s1 == NULL || *s1 == '\0')
745 		return (s0);
746 
747 	if (s0 && *s0) {
748 		if (asprintf(&cp, "%s,%s", s0, s1) == -1)
749 			xo_errx(1, "asprintf failed");
750 	} else
751 		cp = strdup(s1);
752 
753 	if (s0)
754 		free(s0);
755 	return (cp);
756 }
757 
758 void
759 mangle(char *options, struct cpa *a)
760 {
761 	char *p, *s, *val;
762 
763 	for (s = options; (p = strsep(&s, ",")) != NULL;)
764 		if (*p != '\0') {
765 			if (strcmp(p, "noauto") == 0) {
766 				/*
767 				 * Do not pass noauto option to nmount().
768 				 * or external mount program.  noauto is
769 				 * only used to prevent mounting a filesystem
770 				 * when 'mount -a' is specified, and is
771 				 * not a real mount option.
772 				 */
773 				continue;
774 			} else if (strcmp(p, "late") == 0) {
775 				/*
776 				 * "late" is used to prevent certain file
777 				 * systems from being mounted before late
778 				 * in the boot cycle; for instance,
779 				 * loopback NFS mounts can't be mounted
780 				 * before mountd starts.
781 				 */
782 				continue;
783 			} else if (strcmp(p, "failok") == 0) {
784 				/*
785 				 * "failok" is used to prevent certain file
786 				 * systems from being causing the system to
787 				 * drop into single user mode in the boot
788 				 * cycle, and is not a real mount option.
789 				 */
790 				continue;
791 			} else if (strncmp(p, "mountprog", 9) == 0) {
792 				/*
793 				 * "mountprog" is used to force the use of
794 				 * userland mount programs.
795 				 */
796 				val = strchr(p, '=');
797                         	if (val != NULL) {
798                                 	++val;
799 					if (*val != '\0')
800 						mountprog = strdup(val);
801 				}
802 
803 				if (mountprog == NULL) {
804 					xo_errx(1, "Need value for -o mountprog");
805 				}
806 				continue;
807 			} else if (strcmp(p, "userquota") == 0) {
808 				continue;
809 			} else if (strncmp(p, userquotaeq,
810 			    sizeof(userquotaeq) - 1) == 0) {
811 				continue;
812 			} else if (strcmp(p, "groupquota") == 0) {
813 				continue;
814 			} else if (strncmp(p, groupquotaeq,
815 			    sizeof(groupquotaeq) - 1) == 0) {
816 				continue;
817 			} else if (*p == '-') {
818 				append_arg(a, p);
819 				p = strchr(p, '=');
820 				if (p != NULL) {
821 					*p = '\0';
822 					append_arg(a, p + 1);
823 				}
824 			} else {
825 				append_arg(a, strdup("-o"));
826 				append_arg(a, p);
827 			}
828 		}
829 }
830 
831 
832 char *
833 update_options(char *opts, char *fstab, int curflags)
834 {
835 	char *o, *p;
836 	char *cur;
837 	char *expopt, *newopt, *tmpopt;
838 
839 	if (opts == NULL)
840 		return (strdup(""));
841 
842 	/* remove meta options from list */
843 	remopt(fstab, MOUNT_META_OPTION_FSTAB);
844 	remopt(fstab, MOUNT_META_OPTION_CURRENT);
845 	cur = flags2opts(curflags);
846 
847 	/*
848 	 * Expand all meta-options passed to us first.
849 	 */
850 	expopt = NULL;
851 	for (p = opts; (o = strsep(&p, ",")) != NULL;) {
852 		if (strcmp(MOUNT_META_OPTION_FSTAB, o) == 0)
853 			expopt = catopt(expopt, fstab);
854 		else if (strcmp(MOUNT_META_OPTION_CURRENT, o) == 0)
855 			expopt = catopt(expopt, cur);
856 		else
857 			expopt = catopt(expopt, o);
858 	}
859 	free(cur);
860 	free(opts);
861 
862 	/*
863 	 * Remove previous contradictory arguments. Given option "foo" we
864 	 * remove all the "nofoo" options. Given "nofoo" we remove "nonofoo"
865 	 * and "foo" - so we can deal with possible options like "notice".
866 	 */
867 	newopt = NULL;
868 	for (p = expopt; (o = strsep(&p, ",")) != NULL;) {
869 		if ((tmpopt = malloc( strlen(o) + 2 + 1 )) == NULL)
870 			xo_errx(1, "malloc failed");
871 
872 		strcpy(tmpopt, "no");
873 		strcat(tmpopt, o);
874 		remopt(newopt, tmpopt);
875 		free(tmpopt);
876 
877 		if (strncmp("no", o, 2) == 0)
878 			remopt(newopt, o+2);
879 
880 		newopt = catopt(newopt, o);
881 	}
882 	free(expopt);
883 
884 	return (newopt);
885 }
886 
887 void
888 remopt(char *string, const char *opt)
889 {
890 	char *o, *p, *r;
891 
892 	if (string == NULL || *string == '\0' || opt == NULL || *opt == '\0')
893 		return;
894 
895 	r = string;
896 
897 	for (p = string; (o = strsep(&p, ",")) != NULL;) {
898 		if (strcmp(opt, o) != 0) {
899 			if (*r == ',' && *o != '\0')
900 				r++;
901 			while ((*r++ = *o++) != '\0')
902 			    ;
903 			*--r = ',';
904 		}
905 	}
906 	*r = '\0';
907 }
908 
909 void
910 usage(void)
911 {
912 
913 	xo_error("%s\n%s\n%s\n",
914 "usage: mount [-adflpruvw] [-F fstab] [-o options] [-t ufs | external_type]",
915 "       mount [-dfpruvw] special | node",
916 "       mount [-dfpruvw] [-o options] [-t ufs | external_type] special node");
917 	EXIT(1);
918 }
919 
920 void
921 putfsent(struct statfs *ent)
922 {
923 	struct fstab *fst;
924 	char *opts, *rw;
925 	int l;
926 
927 	opts = NULL;
928 	/* flags2opts() doesn't return the "rw" option. */
929 	if ((ent->f_flags & MNT_RDONLY) != 0)
930 		rw = NULL;
931 	else
932 		rw = catopt(NULL, "rw");
933 
934 	opts = flags2opts(ent->f_flags);
935 	opts = catopt(rw, opts);
936 
937 	if (strncmp(ent->f_mntfromname, "<below>", 7) == 0 ||
938 	    strncmp(ent->f_mntfromname, "<above>", 7) == 0) {
939 		strlcpy(ent->f_mntfromname,
940 		    (strnstr(ent->f_mntfromname, ":", 8) +1),
941 		    sizeof(ent->f_mntfromname));
942 	}
943 
944 	l = strlen(ent->f_mntfromname);
945 	xo_emit("{:device}{P:/%s}{P:/%s}{P:/%s}",
946 	    ent->f_mntfromname,
947 	    l < 8 ? "\t" : "",
948 	    l < 16 ? "\t" : "",
949 	    l < 24 ? "\t" : " ");
950 	l = strlen(ent->f_mntonname);
951 	xo_emit("{:mntpoint}{P:/%s}{P:/%s}{P:/%s}",
952 	    ent->f_mntonname,
953 	    l < 8 ? "\t" : "",
954 	    l < 16 ? "\t" : "",
955 	    l < 24 ? "\t" : " ");
956 	xo_emit("{:fstype}{P:\t}", ent->f_fstypename);
957 	l = strlen(opts);
958 	xo_emit("{:opts}{P:/%s}", opts,
959 	    l < 8 ? "\t" : " ");
960 	free(opts);
961 
962 	if ((fst = getfsspec(ent->f_mntfromname)))
963 		xo_emit("{P:\t}{n:dump/%u}{P: }{n:pass/%u}\n",
964 		    fst->fs_freq, fst->fs_passno);
965 	else if ((fst = getfsfile(ent->f_mntonname)))
966 		xo_emit("{P:\t}{n:dump/%u}{P: }{n:pass/%u}\n",
967 		    fst->fs_freq, fst->fs_passno);
968 	else if (strcmp(ent->f_fstypename, "ufs") == 0) {
969 		if (strcmp(ent->f_mntonname, "/") == 0)
970 			xo_emit("{P:\t}{n:dump/1}{P: }{n:pass/1}\n");
971 		else
972 			xo_emit("{P:\t}{n:dump/2}{P: }{n:pass/2}\n");
973 	} else
974 		xo_emit("{P:\t}{n:dump/0}{P: }{n:pass/0}\n");
975 }
976 
977 
978 char *
979 flags2opts(int flags)
980 {
981 	char *res;
982 
983 	res = NULL;
984 
985 	if (flags & MNT_RDONLY)		res = catopt(res, "ro");
986 	if (flags & MNT_SYNCHRONOUS)	res = catopt(res, "sync");
987 	if (flags & MNT_NOEXEC)		res = catopt(res, "noexec");
988 	if (flags & MNT_NOSUID)		res = catopt(res, "nosuid");
989 	if (flags & MNT_UNION)		res = catopt(res, "union");
990 	if (flags & MNT_ASYNC)		res = catopt(res, "async");
991 	if (flags & MNT_NOATIME)	res = catopt(res, "noatime");
992 	if (flags & MNT_NOCLUSTERR)	res = catopt(res, "noclusterr");
993 	if (flags & MNT_NOCLUSTERW)	res = catopt(res, "noclusterw");
994 	if (flags & MNT_NOSYMFOLLOW)	res = catopt(res, "nosymfollow");
995 	if (flags & MNT_SUIDDIR)	res = catopt(res, "suiddir");
996 	if (flags & MNT_MULTILABEL)	res = catopt(res, "multilabel");
997 	if (flags & MNT_ACLS)		res = catopt(res, "acls");
998 	if (flags & MNT_NFS4ACLS)	res = catopt(res, "nfsv4acls");
999 	if (flags & MNT_UNTRUSTED)	res = catopt(res, "untrusted");
1000 	if (flags & MNT_NOCOVER)	res = catopt(res, "nocover");
1001 	if (flags & MNT_EMPTYDIR)	res = catopt(res, "emptydir");
1002 
1003 	return (res);
1004 }
1005