xref: /freebsd-14.2/sbin/mdmfs/mdmfs.c (revision 54416c6e)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Dima Dorfman.
5  * 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  *
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
26  * SUCH DAMAGE.
27  */
28 
29 /*
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).
33  */
34 
35 #include <sys/cdefs.h>
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <sys/mdioctl.h>
39 #include <sys/module.h>
40 #include <sys/mount.h>
41 #include <sys/stat.h>
42 #include <sys/wait.h>
43 
44 #include <assert.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <grp.h>
49 #include <inttypes.h>
50 #include <paths.h>
51 #include <pwd.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <ctype.h>
57 #include <unistd.h>
58 
59 typedef enum { false, true } bool;
60 
61 struct mtpt_info {
62 	uid_t		 mi_uid;
63 	bool		 mi_have_uid;
64 	gid_t		 mi_gid;
65 	bool		 mi_have_gid;
66 	mode_t		 mi_mode;
67 	bool		 mi_have_mode;
68 	bool		 mi_forced_pw;
69 };
70 
71 static	bool debug;		/* Emit debugging information? */
72 static	bool loudsubs;		/* Suppress output from helper programs? */
73 static	bool norun;		/* Actually run the helper programs? */
74 static	int unit;      		/* The unit we're working with. */
75 static	const char *mdname;	/* Name of memory disk device (e.g., "md"). */
76 static	const char *mdsuffix;	/* Suffix of memory disk device (e.g., ".uzip"). */
77 static	size_t mdnamelen;	/* Length of mdname. */
78 static	const char *path_mdconfig =_PATH_MDCONFIG;
79 
80 static void	 argappend(char **, const char *, ...) __printflike(2, 3);
81 static void	 debugprintf(const char *, ...) __printflike(1, 2);
82 static void	 do_mdconfig_attach(const char *, const enum md_types);
83 static void	 do_mdconfig_attach_au(const char *, const enum md_types);
84 static void	 do_mdconfig_detach(void);
85 static void	 do_mount_md(const char *, const char *);
86 static void	 do_mount_tmpfs(const char *, const char *);
87 static void	 do_mtptsetup(const char *, struct mtpt_info *);
88 static void	 do_newfs(const char *);
89 static void	 do_copy(const char *, const char *);
90 static void	 extract_ugid(const char *, struct mtpt_info *);
91 static int	 run(int *, const char *, ...) __printflike(2, 3);
92 static const char *run_exitstr(int);
93 static int	 run_exitnumber(int);
94 static void	 usage(void);
95 
96 int
main(int argc,char ** argv)97 main(int argc, char **argv)
98 {
99 	struct mtpt_info mi;		/* Mountpoint info. */
100 	intmax_t mdsize;
101 	char *mdconfig_arg, *newfs_arg,	/* Args to helper programs. */
102 	    *mount_arg;
103 	enum md_types mdtype;		/* The type of our memory disk. */
104 	bool have_mdtype, mlmac;
105 	bool detach, softdep, autounit, newfs;
106 	const char *mtpoint, *size_arg, *skel, *unitstr;
107 	char *p;
108 	int ch, idx, rv;
109 	void *set;
110 	unsigned long ul;
111 
112 	/* Misc. initialization. */
113 	(void)memset(&mi, '\0', sizeof(mi));
114 	detach = true;
115 	softdep = true;
116 	autounit = false;
117 	mlmac = false;
118 	newfs = true;
119 	have_mdtype = false;
120 	skel = NULL;
121 	mdtype = MD_SWAP;
122 	mdname = MD_NAME;
123 	mdnamelen = strlen(mdname);
124 	mdsize = 0;
125 	/*
126 	 * Can't set these to NULL.  They may be passed to the
127 	 * respective programs without modification.  I.e., we may not
128 	 * receive any command-line options which will caused them to
129 	 * be modified.
130 	 */
131 	mdconfig_arg = strdup("");
132 	newfs_arg = strdup("");
133 	mount_arg = strdup("");
134 	size_arg = NULL;
135 
136 	/* If we were started as mount_mfs or mfs, imply -C. */
137 	if (strcmp(getprogname(), "mount_mfs") == 0 ||
138 	    strcmp(getprogname(), "mfs") == 0) {
139 		/* Make compatibility assumptions. */
140 		mi.mi_mode = 01777;
141 		mi.mi_have_mode = true;
142 	}
143 
144 	while ((ch = getopt(argc, argv,
145 	    "a:b:Cc:Dd:E:e:F:f:hi:k:LlMm:NnO:o:Pp:Ss:tT:Uv:w:X")) != -1)
146 		switch (ch) {
147 		case 'a':
148 			argappend(&newfs_arg, "-a %s", optarg);
149 			break;
150 		case 'b':
151 			argappend(&newfs_arg, "-b %s", optarg);
152 			break;
153 		case 'C':
154 			/* Ignored for compatibility. */
155 			break;
156 		case 'c':
157 			argappend(&newfs_arg, "-c %s", optarg);
158 			break;
159 		case 'D':
160 			detach = false;
161 			break;
162 		case 'd':
163 			argappend(&newfs_arg, "-d %s", optarg);
164 			break;
165 		case 'E':
166 			path_mdconfig = optarg;
167 			break;
168 		case 'e':
169 			argappend(&newfs_arg, "-e %s", optarg);
170 			break;
171 		case 'F':
172 			if (have_mdtype)
173 				usage();
174 			mdtype = MD_VNODE;
175 			have_mdtype = true;
176 			argappend(&mdconfig_arg, "-f %s", optarg);
177 			break;
178 		case 'f':
179 			argappend(&newfs_arg, "-f %s", optarg);
180 			break;
181 		case 'h':
182 			usage();
183 			break;
184 		case 'i':
185 			argappend(&newfs_arg, "-i %s", optarg);
186 			break;
187 		case 'k':
188 			skel = optarg;
189 			break;
190 		case 'L':
191 			loudsubs = true;
192 			break;
193 		case 'l':
194 			mlmac = true;
195 			argappend(&newfs_arg, "-l");
196 			break;
197 		case 'M':
198 			if (have_mdtype)
199 				usage();
200 			mdtype = MD_MALLOC;
201 			have_mdtype = true;
202 			argappend(&mdconfig_arg, "-o reserve");
203 			break;
204 		case 'm':
205 			argappend(&newfs_arg, "-m %s", optarg);
206 			break;
207 		case 'N':
208 			norun = true;
209 			break;
210 		case 'n':
211 			argappend(&newfs_arg, "-n");
212 			break;
213 		case 'O':
214 			argappend(&newfs_arg, "-o %s", optarg);
215 			break;
216 		case 'o':
217 			argappend(&mount_arg, "-o %s", optarg);
218 			break;
219 		case 'P':
220 			newfs = false;
221 			break;
222 		case 'p':
223 			if ((set = setmode(optarg)) == NULL)
224 				usage();
225 			mi.mi_mode = getmode(set, S_IRWXU | S_IRWXG | S_IRWXO);
226 			mi.mi_have_mode = true;
227 			mi.mi_forced_pw = true;
228 			free(set);
229 			break;
230 		case 'S':
231 			softdep = false;
232 			break;
233 		case 's':
234 			size_arg = optarg;
235 			break;
236 		case 't':
237 			argappend(&newfs_arg, "-t");
238 			break;
239 		case 'T':
240 			argappend(&mount_arg, "-t %s", optarg);
241 			break;
242 		case 'U':
243 			softdep = true;
244 			break;
245 		case 'v':
246 			argappend(&newfs_arg, "-O %s", optarg);
247 			break;
248 		case 'w':
249 			extract_ugid(optarg, &mi);
250 			mi.mi_forced_pw = true;
251 			break;
252 		case 'X':
253 			debug = true;
254 			break;
255 		default:
256 			usage();
257 		}
258 	argc -= optind;
259 	argv += optind;
260 	if (argc < 2)
261 		usage();
262 
263 	/*
264 	 * Historically our size arg was passed directly to mdconfig, which
265 	 * treats a number without a suffix as a count of 512-byte sectors;
266 	 * tmpfs would treat it as a count of bytes.  To get predictable
267 	 * behavior for 'auto' we document that the size always uses mdconfig
268 	 * rules.  To make that work, decode the size here so it can be passed
269 	 * to either tmpfs or mdconfig as a count of bytes.
270 	 */
271 	if (size_arg != NULL) {
272 		mdsize = (intmax_t)strtoumax(size_arg, &p, 0);
273 		if (p == size_arg || (p[0] != 0 && p[1] != 0) || mdsize < 0)
274 			errx(1, "invalid size '%s'", size_arg);
275 		switch (*p) {
276 		case 'p':
277 		case 'P':
278 			mdsize *= 1024;
279 		case 't':
280 		case 'T':
281 			mdsize *= 1024;
282 		case 'g':
283 		case 'G':
284 			mdsize *= 1024;
285 		case 'm':
286 		case 'M':
287 			mdsize *= 1024;
288 		case 'k':
289 		case 'K':
290 			mdsize *= 1024;
291 		case 'b':
292 		case 'B':
293 			break;
294 		case '\0':
295 			mdsize *= 512;
296 			break;
297 		default:
298 			errx(1, "invalid size suffix on '%s'", size_arg);
299 		}
300 	}
301 
302 	/*
303 	 * Based on the command line 'md-device' either mount a tmpfs filesystem
304 	 * or configure the md device then format and mount a filesystem on it.
305 	 * If the device is 'auto' use tmpfs if it is available and there is no
306 	 * request for multilabel MAC (which tmpfs does not support).
307 	 */
308 	unitstr = argv[0];
309 	mtpoint = argv[1];
310 
311 	if (strcmp(unitstr, "auto") == 0) {
312 		if (mlmac)
313 			idx = -1; /* Must use md for mlmac. */
314 		else if ((idx = modfind("tmpfs")) == -1)
315 			idx = kldload("tmpfs");
316 		if (idx == -1)
317 			unitstr = "md";
318 		else
319 			unitstr = "tmpfs";
320 	}
321 
322 	if (strcmp(unitstr, "tmpfs") == 0) {
323 		if (size_arg != NULL && mdsize != 0)
324 			argappend(&mount_arg, "-o size=%jd", mdsize);
325 		do_mount_tmpfs(mount_arg, mtpoint);
326 	} else {
327 		if (size_arg != NULL)
328 			argappend(&mdconfig_arg, "-s %jdB", mdsize);
329 		if (strncmp(unitstr, "/dev/", 5) == 0)
330 			unitstr += 5;
331 		if (strncmp(unitstr, mdname, mdnamelen) == 0)
332 			unitstr += mdnamelen;
333 		if (!isdigit(*unitstr)) {
334 			autounit = true;
335 			unit = -1;
336 			mdsuffix = unitstr;
337 		} else {
338 			ul = strtoul(unitstr, &p, 10);
339 			if (ul == ULONG_MAX)
340 				errx(1, "bad device unit: %s", unitstr);
341 			unit = ul;
342 			mdsuffix = p;	/* can be empty */
343 		}
344 
345 		if (!have_mdtype)
346 			mdtype = MD_SWAP;
347 		if (softdep)
348 			argappend(&newfs_arg, "-U");
349 		if (mdtype != MD_VNODE && !newfs)
350 			errx(1, "-P requires a vnode-backed disk");
351 
352 		/* Do the work. */
353 		if (detach && !autounit)
354 			do_mdconfig_detach();
355 		if (autounit)
356 			do_mdconfig_attach_au(mdconfig_arg, mdtype);
357 		else
358 			do_mdconfig_attach(mdconfig_arg, mdtype);
359 		if (newfs)
360 			do_newfs(newfs_arg);
361 		if (!softdep) {
362 			rv = run(NULL, "%s %s /dev/%s%d", _PATH_TUNEFS,
363 			    "-n disable", mdname, unit);
364 			if (rv)
365 				errx(1, "tunefs exited %s %d", run_exitstr(rv),
366 				    run_exitnumber(rv));
367 		}
368 		do_mount_md(mount_arg, mtpoint);
369 	}
370 
371 	do_mtptsetup(mtpoint, &mi);
372 	if (skel != NULL)
373 		do_copy(mtpoint, skel);
374 
375 	return (0);
376 }
377 
378 /*
379  * Append the expansion of 'fmt' to the buffer pointed to by '*dstp';
380  * reallocate as required.
381  */
382 static void
argappend(char ** dstp,const char * fmt,...)383 argappend(char **dstp, const char *fmt, ...)
384 {
385 	char *old, *new;
386 	va_list ap;
387 
388 	old = *dstp;
389 	assert(old != NULL);
390 
391 	va_start(ap, fmt);
392 	if (vasprintf(&new, fmt,ap) == -1)
393 		errx(1, "vasprintf");
394 	va_end(ap);
395 
396 	*dstp = new;
397 	if (asprintf(&new, "%s %s", old, new) == -1)
398 		errx(1, "asprintf");
399 	free(*dstp);
400 	free(old);
401 
402 	*dstp = new;
403 }
404 
405 /*
406  * If run-time debugging is enabled, print the expansion of 'fmt'.
407  * Otherwise, do nothing.
408  */
409 static void
debugprintf(const char * fmt,...)410 debugprintf(const char *fmt, ...)
411 {
412 	va_list ap;
413 
414 	if (!debug)
415 		return;
416 	fprintf(stderr, "DEBUG: ");
417 	va_start(ap, fmt);
418 	vfprintf(stderr, fmt, ap);
419 	va_end(ap);
420 	fprintf(stderr, "\n");
421 	fflush(stderr);
422 }
423 
424 /*
425  * Attach a memory disk with a known unit.
426  */
427 static void
do_mdconfig_attach(const char * args,const enum md_types mdtype)428 do_mdconfig_attach(const char *args, const enum md_types mdtype)
429 {
430 	int rv;
431 	const char *ta;		/* Type arg. */
432 
433 	switch (mdtype) {
434 	case MD_SWAP:
435 		ta = "-t swap";
436 		break;
437 	case MD_VNODE:
438 		ta = "-t vnode";
439 		break;
440 	case MD_MALLOC:
441 		ta = "-t malloc";
442 		break;
443 	default:
444 		abort();
445 	}
446 	rv = run(NULL, "%s -a %s%s -u %s%d", path_mdconfig, ta, args,
447 	    mdname, unit);
448 	if (rv)
449 		errx(1, "mdconfig (attach) exited %s %d", run_exitstr(rv),
450 		    run_exitnumber(rv));
451 }
452 
453 /*
454  * Attach a memory disk with an unknown unit; use autounit.
455  */
456 static void
do_mdconfig_attach_au(const char * args,const enum md_types mdtype)457 do_mdconfig_attach_au(const char *args, const enum md_types mdtype)
458 {
459 	const char *ta;		/* Type arg. */
460 	char *linep;
461 	char linebuf[12];	/* 32-bit unit (10) + '\n' (1) + '\0' (1) */
462 	int fd;			/* Standard output of mdconfig invocation. */
463 	FILE *sfd;
464 	int rv;
465 	char *p;
466 	size_t linelen;
467 	unsigned long ul;
468 
469 	switch (mdtype) {
470 	case MD_SWAP:
471 		ta = "-t swap";
472 		break;
473 	case MD_VNODE:
474 		ta = "-t vnode";
475 		break;
476 	case MD_MALLOC:
477 		ta = "-t malloc";
478 		break;
479 	default:
480 		abort();
481 	}
482 	rv = run(&fd, "%s -a %s%s", path_mdconfig, ta, args);
483 	if (rv)
484 		errx(1, "mdconfig (attach) exited %s %d", run_exitstr(rv),
485 		    run_exitnumber(rv));
486 
487 	/* Receive the unit number. */
488 	if (norun) {	/* Since we didn't run, we can't read.  Fake it. */
489 		unit = 0;
490 		return;
491 	}
492 	sfd = fdopen(fd, "r");
493 	if (sfd == NULL)
494 		err(1, "fdopen");
495 	linep = fgetln(sfd, &linelen);
496 	/* If the output format changes, we want to know about it. */
497 	if (linep == NULL || linelen <= mdnamelen + 1 ||
498 	    linelen - mdnamelen >= sizeof(linebuf) ||
499 	    strncmp(linep, mdname, mdnamelen) != 0)
500 		errx(1, "unexpected output from mdconfig (attach)");
501 	linep += mdnamelen;
502 	linelen -= mdnamelen;
503 	/* Can't use strlcpy because linep is not NULL-terminated. */
504 	strncpy(linebuf, linep, linelen);
505 	linebuf[linelen] = '\0';
506 	ul = strtoul(linebuf, &p, 10);
507 	if (ul == ULONG_MAX || *p != '\n')
508 		errx(1, "unexpected output from mdconfig (attach)");
509 	unit = ul;
510 
511 	fclose(sfd);
512 }
513 
514 /*
515  * Detach a memory disk.
516  */
517 static void
do_mdconfig_detach(void)518 do_mdconfig_detach(void)
519 {
520 	int rv;
521 
522 	rv = run(NULL, "%s -d -u %s%d", path_mdconfig, mdname, unit);
523 	if (rv && debug)	/* This is allowed to fail. */
524 		warnx("mdconfig (detach) exited %s %d (ignored)",
525 		    run_exitstr(rv), run_exitnumber(rv));
526 }
527 
528 /*
529  * Mount the configured memory disk.
530  */
531 static void
do_mount_md(const char * args,const char * mtpoint)532 do_mount_md(const char *args, const char *mtpoint)
533 {
534 	int rv;
535 
536 	rv = run(NULL, "%s%s /dev/%s%d%s %s", _PATH_MOUNT, args,
537 	    mdname, unit, mdsuffix, mtpoint);
538 	if (rv)
539 		errx(1, "mount exited %s %d", run_exitstr(rv),
540 		    run_exitnumber(rv));
541 }
542 
543 /*
544  * Mount the configured tmpfs.
545  */
546 static void
do_mount_tmpfs(const char * args,const char * mtpoint)547 do_mount_tmpfs(const char *args, const char *mtpoint)
548 {
549 	int rv;
550 
551 	rv = run(NULL, "%s -t tmpfs %s tmp %s", _PATH_MOUNT, args, mtpoint);
552 	if (rv)
553 		errx(1, "tmpfs mount exited %s %d", run_exitstr(rv),
554 		    run_exitnumber(rv));
555 }
556 
557 /*
558  * Various configuration of the mountpoint.  Mostly, enact 'mip'.
559  */
560 static void
do_mtptsetup(const char * mtpoint,struct mtpt_info * mip)561 do_mtptsetup(const char *mtpoint, struct mtpt_info *mip)
562 {
563 	struct statfs sfs;
564 
565 	if (!mip->mi_have_mode && !mip->mi_have_uid && !mip->mi_have_gid)
566 		return;
567 
568 	if (!norun) {
569 		if (statfs(mtpoint, &sfs) == -1) {
570 			warn("statfs: %s", mtpoint);
571 			return;
572 		}
573 		if ((sfs.f_flags & MNT_RDONLY) != 0) {
574 			if (mip->mi_forced_pw) {
575 				warnx(
576 	"Not changing mode/owner of %s since it is read-only",
577 				    mtpoint);
578 			} else {
579 				debugprintf(
580 	"Not changing mode/owner of %s since it is read-only",
581 				    mtpoint);
582 			}
583 			return;
584 		}
585 	}
586 
587 	if (mip->mi_have_mode) {
588 		debugprintf("changing mode of %s to %o.", mtpoint,
589 		    mip->mi_mode);
590 		if (!norun)
591 			if (chmod(mtpoint, mip->mi_mode) == -1)
592 				err(1, "chmod: %s", mtpoint);
593 	}
594 	/*
595 	 * We have to do these separately because the user may have
596 	 * only specified one of them.
597 	 */
598 	if (mip->mi_have_uid) {
599 		debugprintf("changing owner (user) or %s to %u.", mtpoint,
600 		    mip->mi_uid);
601 		if (!norun)
602 			if (chown(mtpoint, mip->mi_uid, -1) == -1)
603 				err(1, "chown %s to %u (user)", mtpoint,
604 				    mip->mi_uid);
605 	}
606 	if (mip->mi_have_gid) {
607 		debugprintf("changing owner (group) or %s to %u.", mtpoint,
608 		    mip->mi_gid);
609 		if (!norun)
610 			if (chown(mtpoint, -1, mip->mi_gid) == -1)
611 				err(1, "chown %s to %u (group)", mtpoint,
612 				    mip->mi_gid);
613 	}
614 }
615 
616 /*
617  * Put a file system on the memory disk.
618  */
619 static void
do_newfs(const char * args)620 do_newfs(const char *args)
621 {
622 	int rv;
623 
624 	rv = run(NULL, "%s%s /dev/%s%d", _PATH_NEWFS, args, mdname, unit);
625 	if (rv)
626 		errx(1, "newfs exited %s %d", run_exitstr(rv),
627 		    run_exitnumber(rv));
628 }
629 
630 
631 /*
632  * Copy skel into the mountpoint.
633  */
634 static void
do_copy(const char * mtpoint,const char * skel)635 do_copy(const char *mtpoint, const char *skel)
636 {
637 	int rv;
638 
639 	rv = chdir(skel);
640 	if (rv != 0)
641 		err(1, "chdir to %s", skel);
642 	rv = run(NULL, "/bin/pax -rw -pe . %s", mtpoint);
643 	if (rv != 0)
644 		errx(1, "skel copy failed");
645 }
646 
647 /*
648  * 'str' should be a user and group name similar to the last argument
649  * to chown(1); i.e., a user, followed by a colon, followed by a
650  * group.  The user and group in 'str' may be either a [ug]id or a
651  * name.  Upon return, the uid and gid fields in 'mip' will contain
652  * the uid and gid of the user and group name in 'str', respectively.
653  *
654  * In other words, this derives a user and group id from a string
655  * formatted like the last argument to chown(1).
656  *
657  * Notice: At this point we don't support only a username or only a
658  * group name. do_mtptsetup already does, so when this feature is
659  * desired, this is the only routine that needs to be changed.
660  */
661 static void
extract_ugid(const char * str,struct mtpt_info * mip)662 extract_ugid(const char *str, struct mtpt_info *mip)
663 {
664 	char *ug;			/* Writable 'str'. */
665 	char *user, *group;		/* Result of extracton. */
666 	struct passwd *pw;
667 	struct group *gr;
668 	char *p;
669 	uid_t *uid;
670 	gid_t *gid;
671 
672 	uid = &mip->mi_uid;
673 	gid = &mip->mi_gid;
674 	mip->mi_have_uid = mip->mi_have_gid = false;
675 
676 	/* Extract the user and group from 'str'.  Format above. */
677 	ug = strdup(str);
678 	assert(ug != NULL);
679 	group = ug;
680 	user = strsep(&group, ":");
681 	if (user == NULL || group == NULL || *user == '\0' || *group == '\0')
682 		usage();
683 
684 	/* Derive uid. */
685 	*uid = strtoul(user, &p, 10);
686 	if (*uid == (uid_t)ULONG_MAX)
687 		usage();
688 	if (*p != '\0') {
689 		pw = getpwnam(user);
690 		if (pw == NULL)
691 			errx(1, "invalid user: %s", user);
692 		*uid = pw->pw_uid;
693 	}
694 	mip->mi_have_uid = true;
695 
696 	/* Derive gid. */
697 	*gid = strtoul(group, &p, 10);
698 	if (*gid == (gid_t)ULONG_MAX)
699 		usage();
700 	if (*p != '\0') {
701 		gr = getgrnam(group);
702 		if (gr == NULL)
703 			errx(1, "invalid group: %s", group);
704 		*gid = gr->gr_gid;
705 	}
706 	mip->mi_have_gid = true;
707 
708 	free(ug);
709 }
710 
711 /*
712  * Run a process with command name and arguments pointed to by the
713  * formatted string 'cmdline'.  Since system(3) is not used, the first
714  * space-delimited token of 'cmdline' must be the full pathname of the
715  * program to run.
716  *
717  * The return value is the return code of the process spawned, or a negative
718  * signal number if the process exited due to an uncaught signal.
719  *
720  * If 'ofd' is non-NULL, it is set to the standard output of
721  * the program spawned (i.e., you can read from ofd and get the output
722  * of the program).
723  */
724 static int
run(int * ofd,const char * cmdline,...)725 run(int *ofd, const char *cmdline, ...)
726 {
727 	char **argv, **argvp;		/* Result of splitting 'cmd'. */
728 	int argc;
729 	char *cmd;			/* Expansion of 'cmdline'. */
730 	int pid, status;		/* Child info. */
731 	int pfd[2];			/* Pipe to the child. */
732 	int nfd;			/* Null (/dev/null) file descriptor. */
733 	bool dup2dn;			/* Dup /dev/null to stdout? */
734 	va_list ap;
735 	char *p;
736 	int rv, i;
737 
738 	dup2dn = true;
739 	va_start(ap, cmdline);
740 	rv = vasprintf(&cmd, cmdline, ap);
741 	if (rv == -1)
742 		err(1, "vasprintf");
743 	va_end(ap);
744 
745 	/* Split up 'cmd' into 'argv' for use with execve. */
746 	for (argc = 1, p = cmd; (p = strchr(p, ' ')) != NULL; p++)
747 		argc++;		/* 'argc' generation loop. */
748 	argv = (char **)malloc(sizeof(*argv) * (argc + 1));
749 	assert(argv != NULL);
750 	for (p = cmd, argvp = argv; (*argvp = strsep(&p, " ")) != NULL;)
751 		if (**argvp != '\0')
752 			if (++argvp >= &argv[argc]) {
753 				*argvp = NULL;
754 				break;
755 			}
756 	assert(*argv);
757 	/* The argv array ends up NULL-terminated here. */
758 
759 	/* Make sure the above loop works as expected. */
760 	if (debug) {
761 		/*
762 		 * We can't, but should, use debugprintf here.  First,
763 		 * it appends a trailing newline to the output, and
764 		 * second it prepends "DEBUG: " to the output.  The
765 		 * former is a problem for this would-be first call,
766 		 * and the latter for the would-be call inside the
767 		 * loop.
768 		 */
769 		(void)fprintf(stderr, "DEBUG: running:");
770 		/* Should be equivalent to 'cmd' (before strsep, of course). */
771 		for (i = 0; argv[i] != NULL; i++)
772 			(void)fprintf(stderr, " %s", argv[i]);
773 		(void)fprintf(stderr, "\n");
774 	}
775 
776 	/* Create a pipe if necessary and fork the helper program. */
777 	if (ofd != NULL) {
778 		if (pipe(&pfd[0]) == -1)
779 			err(1, "pipe");
780 		*ofd = pfd[0];
781 		dup2dn = false;
782 	}
783 	pid = fork();
784 	switch (pid) {
785 	case 0:
786 		/* XXX can we call err() in here? */
787 		if (norun)
788 			_exit(0);
789 		if (ofd != NULL)
790 			if (dup2(pfd[1], STDOUT_FILENO) < 0)
791 				err(1, "dup2");
792 		if (!loudsubs) {
793 			nfd = open(_PATH_DEVNULL, O_RDWR);
794 			if (nfd == -1)
795 				err(1, "open: %s", _PATH_DEVNULL);
796 			if (dup2(nfd, STDIN_FILENO) < 0)
797 				err(1, "dup2");
798 			if (dup2dn)
799 				if (dup2(nfd, STDOUT_FILENO) < 0)
800 				   err(1, "dup2");
801 			if (dup2(nfd, STDERR_FILENO) < 0)
802 				err(1, "dup2");
803 		}
804 
805 		(void)execv(argv[0], argv);
806 		warn("exec: %s", argv[0]);
807 		_exit(-1);
808 	case -1:
809 		err(1, "fork");
810 	}
811 
812 	free(cmd);
813 	free(argv);
814 	while (waitpid(pid, &status, 0) != pid)
815 		;
816 	if (WIFEXITED(status))
817 		return (WEXITSTATUS(status));
818 	if (WIFSIGNALED(status))
819 		return (-WTERMSIG(status));
820 	err(1, "unexpected waitpid status: 0x%x", status);
821 }
822 
823 /*
824  * If run() returns non-zero, provide a string explaining why.
825  */
826 static const char *
run_exitstr(int rv)827 run_exitstr(int rv)
828 {
829 	if (rv > 0)
830 		return ("with error code");
831 	if (rv < 0)
832 		return ("with signal");
833 	return (NULL);
834 }
835 
836 /*
837  * If run returns non-zero, provide a relevant number.
838  */
839 static int
run_exitnumber(int rv)840 run_exitnumber(int rv)
841 {
842 	if (rv < 0)
843 		return (-rv);
844 	return (rv);
845 }
846 
847 static void
usage(void)848 usage(void)
849 {
850 
851 	fprintf(stderr,
852 "usage: %s [-DLlMNnPStUX] [-a maxcontig] [-b block-size]\n"
853 "\t[-c blocks-per-cylinder-group][-d max-extent-size] [-E path-mdconfig]\n"
854 "\t[-e maxbpg] [-F file] [-f frag-size] [-i bytes] [-k skel]\n"
855 "\t[-m percent-free] [-O optimization] [-o mount-options]\n"
856 "\t[-p permissions] [-s size] [-v version] [-w user:group]\n"
857 "\tmd-device mount-point\n", getprogname());
858 	exit(1);
859 }
860