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