2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2001 Dima Dorfman.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * mdmfs (md/MFS) is a wrapper around mdconfig(8),
31 * newfs(8), and mount(8) that mimics the command line option set of
32 * the deprecated mount_mfs(8).
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include <sys/param.h>
39 #include <sys/linker.h>
40 #include <sys/mdioctl.h>
41 #include <sys/module.h>
42 #include <sys/mount.h>
61 typedef enum { false, true } bool;
73 static bool debug; /* Emit debugging information? */
74 static bool loudsubs; /* Suppress output from helper programs? */
75 static bool norun; /* Actually run the helper programs? */
76 static int unit; /* The unit we're working with. */
77 static const char *mdname; /* Name of memory disk device (e.g., "md"). */
78 static const char *mdsuffix; /* Suffix of memory disk device (e.g., ".uzip"). */
79 static size_t mdnamelen; /* Length of mdname. */
80 static const char *path_mdconfig =_PATH_MDCONFIG;
82 static void argappend(char **, const char *, ...) __printflike(2, 3);
83 static void debugprintf(const char *, ...) __printflike(1, 2);
84 static void do_mdconfig_attach(const char *, const enum md_types);
85 static void do_mdconfig_attach_au(const char *, const enum md_types);
86 static void do_mdconfig_detach(void);
87 static void do_mount_md(const char *, const char *);
88 static void do_mount_tmpfs(const char *, const char *);
89 static void do_mtptsetup(const char *, struct mtpt_info *);
90 static void do_newfs(const char *);
91 static void do_copy(const char *, const char *);
92 static void extract_ugid(const char *, struct mtpt_info *);
93 static int run(int *, const char *, ...) __printflike(2, 3);
94 static const char *run_exitstr(int);
95 static int run_exitnumber(int);
96 static void usage(void);
99 main(int argc, char **argv)
101 struct mtpt_info mi; /* Mountpoint info. */
103 char *mdconfig_arg, *newfs_arg, /* Args to helper programs. */
105 enum md_types mdtype; /* The type of our memory disk. */
106 bool have_mdtype, mlmac;
107 bool detach, softdep, autounit, newfs;
108 const char *mtpoint, *size_arg, *skel, *unitstr;
114 /* Misc. initialization. */
115 (void)memset(&mi, '\0', sizeof(mi));
125 mdnamelen = strlen(mdname);
128 * Can't set these to NULL. They may be passed to the
129 * respective programs without modification. I.e., we may not
130 * receive any command-line options which will caused them to
133 mdconfig_arg = strdup("");
134 newfs_arg = strdup("");
135 mount_arg = strdup("");
138 /* If we were started as mount_mfs or mfs, imply -C. */
139 if (strcmp(getprogname(), "mount_mfs") == 0 ||
140 strcmp(getprogname(), "mfs") == 0) {
141 /* Make compatibility assumptions. */
143 mi.mi_have_mode = true;
146 while ((ch = getopt(argc, argv,
147 "a:b:Cc:Dd:E:e:F:f:hi:k:LlMm:NnO:o:Pp:Ss:tT:Uv:w:X")) != -1)
150 argappend(&newfs_arg, "-a %s", optarg);
153 argappend(&newfs_arg, "-b %s", optarg);
156 /* Ignored for compatibility. */
159 argappend(&newfs_arg, "-c %s", optarg);
165 argappend(&newfs_arg, "-d %s", optarg);
168 path_mdconfig = optarg;
171 argappend(&newfs_arg, "-e %s", optarg);
178 argappend(&mdconfig_arg, "-f %s", optarg);
181 argappend(&newfs_arg, "-f %s", optarg);
187 argappend(&newfs_arg, "-i %s", optarg);
197 argappend(&newfs_arg, "-l");
204 argappend(&mdconfig_arg, "-o reserve");
207 argappend(&newfs_arg, "-m %s", optarg);
213 argappend(&newfs_arg, "-n");
216 argappend(&newfs_arg, "-o %s", optarg);
219 argappend(&mount_arg, "-o %s", optarg);
225 if ((set = setmode(optarg)) == NULL)
227 mi.mi_mode = getmode(set, S_IRWXU | S_IRWXG | S_IRWXO);
228 mi.mi_have_mode = true;
229 mi.mi_forced_pw = true;
239 argappend(&newfs_arg, "-t");
242 argappend(&mount_arg, "-t %s", optarg);
248 argappend(&newfs_arg, "-O %s", optarg);
251 extract_ugid(optarg, &mi);
252 mi.mi_forced_pw = true;
266 * Historically our size arg was passed directly to mdconfig, which
267 * treats a number without a suffix as a count of 512-byte sectors;
268 * tmpfs would treat it as a count of bytes. To get predictable
269 * behavior for 'auto' we document that the size always uses mdconfig
270 * rules. To make that work, decode the size here so it can be passed
271 * to either tmpfs or mdconfig as a count of bytes.
273 if (size_arg != NULL) {
274 mdsize = (intmax_t)strtoumax(size_arg, &p, 0);
275 if (p == size_arg || (p[0] != 0 && p[1] != 0) || mdsize < 0)
276 errx(1, "invalid size '%s'", size_arg);
300 errx(1, "invalid size suffix on '%s'", size_arg);
305 * Based on the command line 'md-device' either mount a tmpfs filesystem
306 * or configure the md device then format and mount a filesystem on it.
307 * If the device is 'auto' use tmpfs if it is available and there is no
308 * request for multilabel MAC (which tmpfs does not support).
313 if (strcmp(unitstr, "auto") == 0) {
315 idx = -1; /* Must use md for mlmac. */
316 else if ((idx = modfind("tmpfs")) == -1)
317 idx = kldload("tmpfs");
324 if (strcmp(unitstr, "tmpfs") == 0) {
325 if (size_arg != NULL && mdsize != 0)
326 argappend(&mount_arg, "-o size=%jd", mdsize);
327 do_mount_tmpfs(mount_arg, mtpoint);
329 if (size_arg != NULL)
330 argappend(&mdconfig_arg, "-s %jdB", mdsize);
331 if (strncmp(unitstr, "/dev/", 5) == 0)
333 if (strncmp(unitstr, mdname, mdnamelen) == 0)
334 unitstr += mdnamelen;
335 if (!isdigit(*unitstr)) {
340 ul = strtoul(unitstr, &p, 10);
342 errx(1, "bad device unit: %s", unitstr);
344 mdsuffix = p; /* can be empty */
350 argappend(&newfs_arg, "-U");
351 if (mdtype != MD_VNODE && !newfs)
352 errx(1, "-P requires a vnode-backed disk");
355 if (detach && !autounit)
356 do_mdconfig_detach();
358 do_mdconfig_attach_au(mdconfig_arg, mdtype);
360 do_mdconfig_attach(mdconfig_arg, mdtype);
363 do_mount_md(mount_arg, mtpoint);
366 do_mtptsetup(mtpoint, &mi);
368 do_copy(mtpoint, skel);
374 * Append the expansion of 'fmt' to the buffer pointed to by '*dstp';
375 * reallocate as required.
378 argappend(char **dstp, const char *fmt, ...)
387 if (vasprintf(&new, fmt,ap) == -1)
388 errx(1, "vasprintf");
392 if (asprintf(&new, "%s %s", old, new) == -1)
401 * If run-time debugging is enabled, print the expansion of 'fmt'.
402 * Otherwise, do nothing.
405 debugprintf(const char *fmt, ...)
411 fprintf(stderr, "DEBUG: ");
413 vfprintf(stderr, fmt, ap);
415 fprintf(stderr, "\n");
420 * Attach a memory disk with a known unit.
423 do_mdconfig_attach(const char *args, const enum md_types mdtype)
426 const char *ta; /* Type arg. */
441 rv = run(NULL, "%s -a %s%s -u %s%d", path_mdconfig, ta, args,
444 errx(1, "mdconfig (attach) exited %s %d", run_exitstr(rv),
449 * Attach a memory disk with an unknown unit; use autounit.
452 do_mdconfig_attach_au(const char *args, const enum md_types mdtype)
454 const char *ta; /* Type arg. */
456 char linebuf[12]; /* 32-bit unit (10) + '\n' (1) + '\0' (1) */
457 int fd; /* Standard output of mdconfig invocation. */
477 rv = run(&fd, "%s -a %s%s", path_mdconfig, ta, args);
479 errx(1, "mdconfig (attach) exited %s %d", run_exitstr(rv),
482 /* Receive the unit number. */
483 if (norun) { /* Since we didn't run, we can't read. Fake it. */
487 sfd = fdopen(fd, "r");
490 linep = fgetln(sfd, &linelen);
491 /* If the output format changes, we want to know about it. */
492 if (linep == NULL || linelen <= mdnamelen + 1 ||
493 linelen - mdnamelen >= sizeof(linebuf) ||
494 strncmp(linep, mdname, mdnamelen) != 0)
495 errx(1, "unexpected output from mdconfig (attach)");
497 linelen -= mdnamelen;
498 /* Can't use strlcpy because linep is not NULL-terminated. */
499 strncpy(linebuf, linep, linelen);
500 linebuf[linelen] = '\0';
501 ul = strtoul(linebuf, &p, 10);
502 if (ul == ULONG_MAX || *p != '\n')
503 errx(1, "unexpected output from mdconfig (attach)");
510 * Detach a memory disk.
513 do_mdconfig_detach(void)
517 rv = run(NULL, "%s -d -u %s%d", path_mdconfig, mdname, unit);
518 if (rv && debug) /* This is allowed to fail. */
519 warnx("mdconfig (detach) exited %s %d (ignored)",
520 run_exitstr(rv), run_exitnumber(rv));
524 * Mount the configured memory disk.
527 do_mount_md(const char *args, const char *mtpoint)
531 rv = run(NULL, "%s%s /dev/%s%d%s %s", _PATH_MOUNT, args,
532 mdname, unit, mdsuffix, mtpoint);
534 errx(1, "mount exited %s %d", run_exitstr(rv),
539 * Mount the configured tmpfs.
542 do_mount_tmpfs(const char *args, const char *mtpoint)
546 rv = run(NULL, "%s -t tmpfs %s tmp %s", _PATH_MOUNT, args, mtpoint);
548 errx(1, "tmpfs mount exited %s %d", run_exitstr(rv),
553 * Various configuration of the mountpoint. Mostly, enact 'mip'.
556 do_mtptsetup(const char *mtpoint, struct mtpt_info *mip)
560 if (!mip->mi_have_mode && !mip->mi_have_uid && !mip->mi_have_gid)
564 if (statfs(mtpoint, &sfs) == -1) {
565 warn("statfs: %s", mtpoint);
568 if ((sfs.f_flags & MNT_RDONLY) != 0) {
569 if (mip->mi_forced_pw) {
571 "Not changing mode/owner of %s since it is read-only",
575 "Not changing mode/owner of %s since it is read-only",
582 if (mip->mi_have_mode) {
583 debugprintf("changing mode of %s to %o.", mtpoint,
586 if (chmod(mtpoint, mip->mi_mode) == -1)
587 err(1, "chmod: %s", mtpoint);
590 * We have to do these separately because the user may have
591 * only specified one of them.
593 if (mip->mi_have_uid) {
594 debugprintf("changing owner (user) or %s to %u.", mtpoint,
597 if (chown(mtpoint, mip->mi_uid, -1) == -1)
598 err(1, "chown %s to %u (user)", mtpoint,
601 if (mip->mi_have_gid) {
602 debugprintf("changing owner (group) or %s to %u.", mtpoint,
605 if (chown(mtpoint, -1, mip->mi_gid) == -1)
606 err(1, "chown %s to %u (group)", mtpoint,
612 * Put a file system on the memory disk.
615 do_newfs(const char *args)
619 rv = run(NULL, "%s%s /dev/%s%d", _PATH_NEWFS, args, mdname, unit);
621 errx(1, "newfs exited %s %d", run_exitstr(rv),
627 * Copy skel into the mountpoint.
630 do_copy(const char *mtpoint, const char *skel)
636 err(1, "chdir to %s", skel);
637 rv = run(NULL, "/bin/pax -rw -pe . %s", mtpoint);
639 errx(1, "skel copy failed");
643 * 'str' should be a user and group name similar to the last argument
644 * to chown(1); i.e., a user, followed by a colon, followed by a
645 * group. The user and group in 'str' may be either a [ug]id or a
646 * name. Upon return, the uid and gid fields in 'mip' will contain
647 * the uid and gid of the user and group name in 'str', respectively.
649 * In other words, this derives a user and group id from a string
650 * formatted like the last argument to chown(1).
652 * Notice: At this point we don't support only a username or only a
653 * group name. do_mtptsetup already does, so when this feature is
654 * desired, this is the only routine that needs to be changed.
657 extract_ugid(const char *str, struct mtpt_info *mip)
659 char *ug; /* Writable 'str'. */
660 char *user, *group; /* Result of extracton. */
669 mip->mi_have_uid = mip->mi_have_gid = false;
671 /* Extract the user and group from 'str'. Format above. */
675 user = strsep(&group, ":");
676 if (user == NULL || group == NULL || *user == '\0' || *group == '\0')
680 *uid = strtoul(user, &p, 10);
681 if (*uid == (uid_t)ULONG_MAX)
686 errx(1, "invalid user: %s", user);
689 mip->mi_have_uid = true;
692 *gid = strtoul(group, &p, 10);
693 if (*gid == (gid_t)ULONG_MAX)
696 gr = getgrnam(group);
698 errx(1, "invalid group: %s", group);
701 mip->mi_have_gid = true;
707 * Run a process with command name and arguments pointed to by the
708 * formatted string 'cmdline'. Since system(3) is not used, the first
709 * space-delimited token of 'cmdline' must be the full pathname of the
712 * The return value is the return code of the process spawned, or a negative
713 * signal number if the process exited due to an uncaught signal.
715 * If 'ofd' is non-NULL, it is set to the standard output of
716 * the program spawned (i.e., you can read from ofd and get the output
720 run(int *ofd, const char *cmdline, ...)
722 char **argv, **argvp; /* Result of splitting 'cmd'. */
724 char *cmd; /* Expansion of 'cmdline'. */
725 int pid, status; /* Child info. */
726 int pfd[2]; /* Pipe to the child. */
727 int nfd; /* Null (/dev/null) file descriptor. */
728 bool dup2dn; /* Dup /dev/null to stdout? */
734 va_start(ap, cmdline);
735 rv = vasprintf(&cmd, cmdline, ap);
740 /* Split up 'cmd' into 'argv' for use with execve. */
741 for (argc = 1, p = cmd; (p = strchr(p, ' ')) != NULL; p++)
742 argc++; /* 'argc' generation loop. */
743 argv = (char **)malloc(sizeof(*argv) * (argc + 1));
744 assert(argv != NULL);
745 for (p = cmd, argvp = argv; (*argvp = strsep(&p, " ")) != NULL;)
747 if (++argvp >= &argv[argc]) {
752 /* The argv array ends up NULL-terminated here. */
754 /* Make sure the above loop works as expected. */
757 * We can't, but should, use debugprintf here. First,
758 * it appends a trailing newline to the output, and
759 * second it prepends "DEBUG: " to the output. The
760 * former is a problem for this would-be first call,
761 * and the latter for the would-be call inside the
764 (void)fprintf(stderr, "DEBUG: running:");
765 /* Should be equivalent to 'cmd' (before strsep, of course). */
766 for (i = 0; argv[i] != NULL; i++)
767 (void)fprintf(stderr, " %s", argv[i]);
768 (void)fprintf(stderr, "\n");
771 /* Create a pipe if necessary and fork the helper program. */
773 if (pipe(&pfd[0]) == -1)
781 /* XXX can we call err() in here? */
785 if (dup2(pfd[1], STDOUT_FILENO) < 0)
788 nfd = open(_PATH_DEVNULL, O_RDWR);
790 err(1, "open: %s", _PATH_DEVNULL);
791 if (dup2(nfd, STDIN_FILENO) < 0)
794 if (dup2(nfd, STDOUT_FILENO) < 0)
796 if (dup2(nfd, STDERR_FILENO) < 0)
800 (void)execv(argv[0], argv);
801 warn("exec: %s", argv[0]);
809 while (waitpid(pid, &status, 0) != pid)
811 if (WIFEXITED(status))
812 return (WEXITSTATUS(status));
813 if (WIFSIGNALED(status))
814 return (-WTERMSIG(status));
815 err(1, "unexpected waitpid status: 0x%x", status);
819 * If run() returns non-zero, provide a string explaining why.
825 return ("with error code");
827 return ("with signal");
832 * If run returns non-zero, provide a relevant number.
835 run_exitnumber(int rv)
847 "usage: %s [-DLlMNnPStUX] [-a maxcontig] [-b block-size]\n"
848 "\t[-c blocks-per-cylinder-group][-d max-extent-size] [-E path-mdconfig]\n"
849 "\t[-e maxbpg] [-F file] [-f frag-size] [-i bytes] [-k skel]\n"
850 "\t[-m percent-free] [-O optimization] [-o mount-options]\n"
851 "\t[-p permissions] [-s size] [-v version] [-w user:group]\n"
852 "\tmd-device mount-point\n", getprogname());