Home | History | Annotate | Line # | Download | only in sysinst
util.c revision 1.75
      1 /*	$NetBSD: util.c,v 1.75 2024/04/09 15:17:24 nia Exp $	*/
      2 
      3 /*
      4  * Copyright 1997 Piermont Information Systems Inc.
      5  * All rights reserved.
      6  *
      7  * Written by Philip A. Nelson for Piermont Information Systems Inc.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. The name of Piermont Information Systems Inc. may not be used to endorse
     18  *    or promote products derived from this software without specific prior
     19  *    written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
     22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
     25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     31  * THE POSSIBILITY OF SUCH DAMAGE.
     32  *
     33  */
     34 
     35 /* util.c -- routines that don't really fit anywhere else... */
     36 
     37 #include <assert.h>
     38 #include <inttypes.h>
     39 #include <stdio.h>
     40 #include <stdarg.h>
     41 #include <string.h>
     42 #include <unistd.h>
     43 #include <sys/mount.h>
     44 #include <sys/dkio.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/types.h>
     47 #include <sys/param.h>
     48 #include <sys/sysctl.h>
     49 #include <sys/stat.h>
     50 #include <sys/statvfs.h>
     51 #include <isofs/cd9660/iso.h>
     52 #include <curses.h>
     53 #include <err.h>
     54 #include <errno.h>
     55 #include <dirent.h>
     56 #include <util.h>
     57 #include "defs.h"
     58 #include "md.h"
     59 #include "defsizes.h"
     60 #include "msg_defs.h"
     61 #include "menu_defs.h"
     62 #ifdef MD_MAY_SWAP_TO
     63 #include <sys/drvctlio.h>
     64 #endif
     65 #ifdef CHECK_ENTROPY
     66 #include <sha2.h>
     67 #include <paths.h>
     68 #endif
     69 
     70 #define MAX_CD_DEVS	256	/* how many cd drives do we expect to attach */
     71 #define ISO_BLKSIZE	ISO_DEFAULT_BLOCK_SIZE
     72 
     73 static const char *msg_yes, *msg_no, *msg_all, *msg_some, *msg_none;
     74 static int select_menu_width;
     75 
     76 static uint8_t set_status[SET_GROUP_END];
     77 #define SET_VALID	0x01
     78 #define SET_SELECTED	0x02
     79 #define SET_SKIPPED	0x04
     80 #define SET_INSTALLED	0x08
     81 #define	SET_NO_EXTRACT	0x10
     82 
     83 struct  tarstats {
     84 	int nselected;
     85 	int nfound;
     86 	int nnotfound;
     87 	int nerror;
     88 	int nsuccess;
     89 	int nskipped;
     90 } tarstats;
     91 
     92 distinfo dist_list[] = {
     93 #ifdef SET_KERNEL_1_NAME
     94 	{SET_KERNEL_1_NAME,	SET_KERNEL_1,		false, MSG_set_kernel_1, NULL},
     95 #endif
     96 #ifdef SET_KERNEL_2_NAME
     97 	{SET_KERNEL_2_NAME,	SET_KERNEL_2,		false, MSG_set_kernel_2, NULL},
     98 #endif
     99 #ifdef SET_KERNEL_3_NAME
    100 	{SET_KERNEL_3_NAME,	SET_KERNEL_3,		false, MSG_set_kernel_3, NULL},
    101 #endif
    102 #ifdef SET_KERNEL_4_NAME
    103 	{SET_KERNEL_4_NAME,	SET_KERNEL_4,		false, MSG_set_kernel_4, NULL},
    104 #endif
    105 #ifdef SET_KERNEL_5_NAME
    106 	{SET_KERNEL_5_NAME,	SET_KERNEL_5,		false, MSG_set_kernel_5, NULL},
    107 #endif
    108 #ifdef SET_KERNEL_6_NAME
    109 	{SET_KERNEL_6_NAME,	SET_KERNEL_6,		false, MSG_set_kernel_6, NULL},
    110 #endif
    111 #ifdef SET_KERNEL_7_NAME
    112 	{SET_KERNEL_7_NAME,	SET_KERNEL_7,		false, MSG_set_kernel_7, NULL},
    113 #endif
    114 #ifdef SET_KERNEL_8_NAME
    115 	{SET_KERNEL_8_NAME,	SET_KERNEL_8,		false, MSG_set_kernel_8, NULL},
    116 #endif
    117 #ifdef SET_KERNEL_9_NAME
    118 	{SET_KERNEL_9_NAME,	SET_KERNEL_9,		false, MSG_set_kernel_9, NULL},
    119 #endif
    120 
    121 #ifdef HAVE_MODULES
    122 	{"modules",		SET_MODULES,		false, MSG_set_modules, NULL},
    123 #endif
    124 	{"base",		SET_BASE,		false, MSG_set_base, NULL},
    125 #ifdef HAVE_BASE32
    126 	{"base32",		SET_BASE32,		false, MSG_set_base32, NULL},
    127 #endif
    128 #ifdef HAVE_DTB
    129 	{"dtb",			SET_DTB,		false, MSG_set_dtb, NULL},
    130 #endif
    131 	{"etc",			SET_ETC,		false, MSG_set_system, NULL},
    132 	{"comp",		SET_COMPILER,		false, MSG_set_compiler, NULL},
    133 	{"games",		SET_GAMES,		false, MSG_set_games, NULL},
    134 	{"gpufw",		SET_GPUFW,		false, MSG_set_gpufw, NULL},
    135 	{"man",			SET_MAN_PAGES,		false, MSG_set_man_pages, NULL},
    136 	{"manhtml",		SET_MAN_PAGES_HTML,	false, MSG_set_man_pages_html, NULL},
    137 	{"misc",		SET_MISC,		false, MSG_set_misc, NULL},
    138 	{"rescue",		SET_RESCUE,		false, MSG_set_rescue, NULL},
    139 	{"tests",		SET_TESTS,		false, MSG_set_tests, NULL},
    140 	{"text",		SET_TEXT_TOOLS,		false, MSG_set_text_tools, NULL},
    141 
    142 	{NULL,			SET_GROUP,		false, MSG_set_X11, NULL},
    143 	{"xbase",		SET_X11_BASE,		false, MSG_set_X11_base, NULL},
    144 	{"xcomp",		SET_X11_PROG,		false, MSG_set_X11_prog, NULL},
    145 	{"xetc",		SET_X11_ETC,		false, MSG_set_X11_etc, NULL},
    146 	{"xfont",		SET_X11_FONTS,		false, MSG_set_X11_fonts, NULL},
    147 	{"xserver",		SET_X11_SERVERS,	false, MSG_set_X11_servers, NULL},
    148 	{NULL,			SET_GROUP_END,		false, NULL, NULL},
    149 
    150 #ifdef SET_MD_1_NAME
    151 	{SET_MD_1_NAME,		SET_MD_1,		false, MSG_set_md_1, NULL},
    152 #endif
    153 #ifdef SET_MD_2_NAME
    154 	{SET_MD_2_NAME,		SET_MD_2,		false, MSG_set_md_2, NULL},
    155 #endif
    156 #ifdef SET_MD_3_NAME
    157 	{SET_MD_3_NAME,		SET_MD_3,		false, MSG_set_md_3, NULL},
    158 #endif
    159 #ifdef SET_MD_4_NAME
    160 	{SET_MD_4_NAME,		SET_MD_4,		false, MSG_set_md_4, NULL},
    161 #endif
    162 
    163 	{NULL,			SET_GROUP,		true, MSG_set_source, NULL},
    164 	{"syssrc",		SET_SYSSRC,		true, MSG_set_syssrc, NULL},
    165 	{"src",			SET_SRC,		true, MSG_set_src, NULL},
    166 	{"sharesrc",		SET_SHARESRC,		true, MSG_set_sharesrc, NULL},
    167 	{"gnusrc",		SET_GNUSRC,		true, MSG_set_gnusrc, NULL},
    168 	{"xsrc",		SET_XSRC,		true, MSG_set_xsrc, NULL},
    169 	{"debug",		SET_DEBUG,		false, MSG_set_debug, NULL},
    170 #ifdef HAVE_DEBUG32
    171 	{"debug32",		SET_DEBUG32,		false, MSG_set_debug32, NULL},
    172 #endif
    173 	{"xdebug",		SET_X11_DEBUG,		false, MSG_set_xdebug, NULL},
    174 	{NULL,			SET_GROUP_END,		false, NULL, NULL},
    175 
    176 	{NULL,			SET_LAST,		false, NULL, NULL},
    177 };
    178 
    179 #define MAX_CD_INFOS	16	/* how many media can be found? */
    180 struct cd_info {
    181 	char device_name[16];
    182 	char menu[100];
    183 };
    184 static struct cd_info cds[MAX_CD_INFOS];
    185 
    186 /* flags whether to offer the respective options (depending on helper
    187    programs available on install media */
    188 int have_raid, have_vnd, have_cgd, have_lvm, have_gpt, have_dk;
    189 
    190 /*
    191  * local prototypes
    192  */
    193 
    194 static int check_for(unsigned int mode, const char *pathname);
    195 static int get_iso9660_volname(int dev, int sess, char *volname,
    196 		size_t volnamelen);
    197 static int get_available_cds(void);
    198 static int binary_available(const char *prog);
    199 
    200 void
    201 init_set_status(int flags)
    202 {
    203 	static const uint8_t sets_valid[] = {MD_SETS_VALID};
    204 	static const uint8_t sets_selected_full[] = {MD_SETS_SELECTED};
    205 	static const uint8_t sets_selected_minimal[] = {MD_SETS_SELECTED_MINIMAL};
    206 	static const uint8_t sets_selected_nox[] = {MD_SETS_SELECTED_NOX};
    207 	static const uint8_t *sets_selected;
    208 	unsigned int nelem_selected;
    209 	unsigned int i, len;
    210 	const char *longest;
    211 
    212 	if (flags & SFLAG_MINIMAL) {
    213 		sets_selected = sets_selected_minimal;
    214 		nelem_selected = __arraycount(sets_selected_minimal);
    215 	} else if (flags & SFLAG_NOX) {
    216 		sets_selected = sets_selected_nox;
    217 		nelem_selected = __arraycount(sets_selected_nox);
    218 	} else {
    219 		sets_selected = sets_selected_full;
    220 		nelem_selected = __arraycount(sets_selected_full);
    221 	}
    222 
    223 	for (i = 0; i < __arraycount(sets_valid); i++)
    224 		set_status[sets_valid[i]] = SET_VALID;
    225 	for (i = 0; i < nelem_selected; i++)
    226 		set_status[sets_selected[i]] |= SET_SELECTED;
    227 
    228 	set_status[SET_GROUP] = SET_VALID;
    229 
    230 	/* Lookup some strings we need lots of times */
    231 	msg_yes = msg_string(MSG_Yes);
    232 	msg_no = msg_string(MSG_No);
    233 	msg_all = msg_string(MSG_All);
    234 	msg_some = msg_string(MSG_Some);
    235 	msg_none = msg_string(MSG_None);
    236 
    237 	/* Find longest and use it to determine width of selection menu */
    238 	len = strlen(msg_no); longest = msg_no;
    239 	i = strlen(msg_yes); if (i > len) {len = i; longest = msg_yes; }
    240 	i = strlen(msg_all); if (i > len) {len = i; longest = msg_all; }
    241 	i = strlen(msg_some); if (i > len) {len = i; longest = msg_some; }
    242 	i = strlen(msg_none); if (i > len) {len = i; longest = msg_none; }
    243 	select_menu_width = snprintf(NULL, 0, "%-30s %s", "", longest);
    244 
    245 	/* Give the md code a chance to choose the right kernel, etc. */
    246 	md_init_set_status(flags);
    247 }
    248 
    249 int
    250 dir_exists_p(const char *path)
    251 {
    252 
    253 	return file_mode_match(path, S_IFDIR);
    254 }
    255 
    256 int
    257 file_exists_p(const char *path)
    258 {
    259 
    260 	return file_mode_match(path, S_IFREG);
    261 }
    262 
    263 int
    264 file_mode_match(const char *path, unsigned int mode)
    265 {
    266 	struct stat st;
    267 
    268 	return (stat(path, &st) == 0 && (st.st_mode & S_IFMT) == mode);
    269 }
    270 
    271 /* return ram size in MB */
    272 uint64_t
    273 get_ramsize(void)
    274 {
    275 	static uint64_t ramsize;
    276 
    277 	if (ramsize == 0) {
    278 		size_t len = sizeof ramsize;
    279 		int mib[2] = {CTL_HW, HW_PHYSMEM64};
    280 
    281 		sysctl(mib, 2, &ramsize, &len, NULL, 0);
    282 	}
    283 
    284 	/* Find out how many Megs ... round up. */
    285 	return (ramsize + MEG - 1) / MEG;
    286 }
    287 
    288 void
    289 run_makedev(void)
    290 {
    291 	char *owd;
    292 
    293 	msg_display_add("\n\n");
    294 	msg_display_add(MSG_makedev);
    295 
    296 	owd = getcwd(NULL, 0);
    297 
    298 	/* make /dev, in case the user  didn't extract it. */
    299 	make_target_dir("/dev");
    300 	target_chdir_or_die("/dev");
    301 	run_program(0, "/bin/sh MAKEDEV all");
    302 
    303 	chdir(owd);
    304 	free(owd);
    305 }
    306 
    307 /*
    308  * Performs in-place replacement of a set of patterns in a file that lives
    309  * inside the installed system.  The patterns must be separated by a semicolon.
    310  * For example:
    311  *
    312  * replace("/etc/some-file.conf", "s/prop1=NO/prop1=YES/;s/foo/bar/");
    313  */
    314 void
    315 replace(const char *path, const char *patterns, ...)
    316 {
    317 	char *spatterns;
    318 	va_list ap;
    319 
    320 	va_start(ap, patterns);
    321 	vasprintf(&spatterns, patterns, ap);
    322 	va_end(ap);
    323 	if (spatterns == NULL)
    324 		err(1, "vasprintf(&spatterns, \"%s\", ...)", patterns);
    325 
    326 	run_program(RUN_CHROOT, "sed -an -e '%s;H;$!d;g;w %s' %s", spatterns,
    327 	    path, path);
    328 
    329 	free(spatterns);
    330 }
    331 
    332 static int
    333 floppy_fetch(const char *set_name)
    334 {
    335 	char post[4];
    336 	msg errmsg;
    337 	int menu;
    338 	int status;
    339 	const char *write_mode = ">";
    340 
    341 	strcpy(post, "aa");
    342 
    343 	errmsg = "";
    344 	menu = MENU_fdok;
    345 	for (;;) {
    346 		umount_mnt2();
    347 		msg_display(errmsg);
    348 		msg_fmt_display_add(MSG_fdmount, "%s%s", set_name, post);
    349 		process_menu(menu, &status);
    350 		if (status != SET_CONTINUE)
    351 			return status;
    352 		menu = MENU_fdremount;
    353 		errmsg = MSG_fdremount;
    354 		if (run_program(0, "/sbin/mount -r -t %s %s /mnt2",
    355 							fd_type, fd_dev))
    356 			continue;
    357 		mnt2_mounted = 1;
    358 		errmsg = MSG_fdnotfound;
    359 
    360 		/* Display this because it might take a while.... */
    361 		if (run_program(RUN_DISPLAY,
    362 			    "sh -c '/bin/cat /mnt2/%s.%s %s %s/%s/%s%s'",
    363 			    set_name, post, write_mode,
    364 			    target_prefix(), xfer_dir, set_name,
    365 			    set_postfix(set_name)))
    366 			/* XXX: a read error will give a corrupt file! */
    367 			continue;
    368 
    369 		/* We got that file, advance to next fragment */
    370 		if (post[1] < 'z')
    371 			post[1]++;
    372 		else
    373 			post[1] = 'a', post[0]++;
    374 		write_mode = ">>";
    375 		errmsg = "";
    376 		menu = MENU_fdok;
    377 	}
    378 }
    379 
    380 /*
    381  * Load files from floppy.  Requires a /mnt2 directory for mounting them.
    382  */
    383 int
    384 get_via_floppy(void)
    385 {
    386 	int rv = -1;
    387 
    388 	process_menu(MENU_floppysource, &rv);
    389 	if (rv == SET_RETRY)
    390 		return SET_RETRY;
    391 
    392 	fetch_fn = floppy_fetch;
    393 
    394 	/* Set ext_dir for absolute path. */
    395 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s", target_prefix(), xfer_dir);
    396 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s", target_prefix(), xfer_dir);
    397 
    398 	return SET_OK;
    399 }
    400 
    401 /*
    402  * Get the volume name of a ISO9660 file system
    403  */
    404 static int
    405 get_iso9660_volname(int dev, int sess, char *volname, size_t volnamelen)
    406 {
    407 	int blkno, error, last;
    408 	static char buf[ISO_BLKSIZE] __aligned(8);
    409 	struct iso_volume_descriptor *vd = NULL;
    410 	struct iso_primary_descriptor *pd = NULL;
    411 
    412 	for (blkno = sess+16; blkno < sess+16+100; blkno++) {
    413 		error = pread(dev, buf, ISO_BLKSIZE, blkno*ISO_BLKSIZE);
    414 		if (error == -1)
    415 			return -1;
    416 		vd = (struct iso_volume_descriptor *)&buf;
    417 		if (memcmp(vd->id, ISO_STANDARD_ID, sizeof(vd->id)) != 0)
    418 			return -1;
    419 		if (isonum_711((const unsigned char *)&vd->type)
    420 		     == ISO_VD_PRIMARY) {
    421 			pd = (struct iso_primary_descriptor*)buf;
    422 			strncpy(volname, pd->volume_id, volnamelen - 1);
    423 			volname[volnamelen - 1] = '\0';
    424 			last = volnamelen - 1;
    425 			while (last >= 0
    426 			    && (volname[last] == ' ' || volname[last] == 0))
    427 				last--;
    428 			volname[last+1] = 0;
    429 			return 0;
    430 		}
    431 	}
    432 	return -1;
    433 }
    434 
    435 /*
    436  * Local state while iterating CDs and collecting volumes
    437  */
    438 struct get_available_cds_state {
    439 	size_t num_mounted;
    440 	struct statvfs *mounted;
    441 	struct cd_info *info;
    442 	size_t count;
    443 };
    444 
    445 /*
    446  * Callback function: if this is a CD, enumerate all volumes on it
    447  */
    448 static bool
    449 get_available_cds_helper(void *arg, const char *device)
    450 {
    451 	struct get_available_cds_state *state = arg;
    452 	char dname[16], tname[16], volname[80], *t;
    453 	struct disklabel label;
    454 	int part, dev, error, sess, ready, tlen;
    455 
    456 	if (!is_cdrom_device(device, false))
    457 		return true;
    458 
    459 	sprintf(dname, "/dev/r%s%c", device, 'a'+RAW_PART);
    460 	tlen = sprintf(tname, "/dev/%s", device);
    461 
    462 	/* check if this is mounted already */
    463 	for (size_t i = 0; i < state->num_mounted; i++) {
    464 		if (strncmp(state->mounted[i].f_mntfromname, tname, tlen)
    465 		    == 0) {
    466 			t = state->mounted[i].f_mntfromname + tlen;
    467 			if (t[0] >= 'a' && t[0] <= 'z' && t[1] == 0)
    468 				return true;
    469 		}
    470 	}
    471 
    472 	dev = open(dname, O_RDONLY, 0);
    473 	if (dev == -1)
    474 		return true;
    475 
    476 	ready = 0;
    477 	error = ioctl(dev, DIOCTUR, &ready);
    478 	if (error != 0 || ready == 0) {
    479 		close(dev);
    480 		return true;
    481 	}
    482 	error = ioctl(dev, DIOCGDINFO, &label);
    483 	close(dev);
    484 	if (error != 0)
    485 		return true;
    486 
    487 	for (part = 0; part < label.d_npartitions; part++) {
    488 
    489 		if (label.d_partitions[part].p_fstype == FS_UNUSED
    490 		    || label.d_partitions[part].p_size == 0)
    491 			continue;
    492 
    493 		if (label.d_partitions[part].p_fstype == FS_ISO9660) {
    494 			sess = label.d_partitions[part].p_cdsession;
    495 			sprintf(dname, "/dev/r%s%c", device, 'a'+part);
    496 			dev = open(dname, O_RDONLY, 0);
    497 			if (dev == -1)
    498 				continue;
    499 			error = get_iso9660_volname(dev, sess, volname,
    500 			    sizeof volname);
    501 			close(dev);
    502 			if (error)
    503 				continue;
    504 			sprintf(state->info->device_name,
    505 			    "%s%c", device, 'a'+part);
    506 			sprintf(state->info->menu, "%s (%s)",
    507 			    state->info->device_name, volname);
    508 		} else {
    509 			/*
    510 			 * All install CDs use partition
    511 			 * a for the sets.
    512 			 */
    513 			if (part > 0)
    514 				continue;
    515 			sprintf(state->info->device_name,
    516 			    "%s%c", device, 'a'+part);
    517 			strcpy(state->info->menu, state->info->device_name);
    518 		}
    519 		state->info++;
    520 		if (++state->count >= MAX_CD_INFOS)
    521 			return false;
    522 	}
    523 
    524 	return true;
    525 }
    526 
    527 /*
    528  * Get a list of all available CD media (not drives!), return
    529  * the number of entries collected.
    530  */
    531 static int
    532 get_available_cds(void)
    533 {
    534 	struct get_available_cds_state data;
    535 	int n, m;
    536 
    537 	memset(&data, 0, sizeof data);
    538 	data.info = cds;
    539 
    540 	n = getvfsstat(NULL, 0, ST_NOWAIT);
    541 	if (n > 0) {
    542 		data.mounted = calloc(n, sizeof(*data.mounted));
    543 		m = getvfsstat(data.mounted, n*sizeof(*data.mounted),
    544 		    ST_NOWAIT);
    545 		assert(m >= 0 && m <= n);
    546 		data.num_mounted = m;
    547 	}
    548 
    549 	enumerate_disks(&data, get_available_cds_helper);
    550 
    551 	free(data.mounted);
    552 
    553 	return data.count;
    554 }
    555 
    556 static int
    557 cd_has_sets(void)
    558 {
    559 
    560 	/* sanity check */
    561 	if (cdrom_dev[0] == 0)
    562 		return 0;
    563 
    564 	/* Mount it */
    565 	if (run_program(RUN_SILENT, "/sbin/mount -rt cd9660 /dev/%s /mnt2",
    566 	    cdrom_dev) != 0)
    567 		return 0;
    568 
    569 	mnt2_mounted = 1;
    570 
    571 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s", "/mnt2", set_dir_bin);
    572 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s", "/mnt2", set_dir_src);
    573 	return dir_exists_p(ext_dir_bin);
    574 }
    575 
    576 /*
    577  * Check whether we can remove the boot media.
    578  * If it is not a local filesystem, return -1.
    579  * If we can not decide for sure (can not tell MD content from plain ffs
    580  * on hard disk, for example), return 0.
    581  * If it is a CD/DVD, return 1.
    582  */
    583 int
    584 boot_media_still_needed(void)
    585 {
    586 	struct statvfs sb;
    587 
    588 	if (statvfs("/", &sb) == 0) {
    589 		if (!(sb.f_flag & ST_LOCAL))
    590 			return -1;
    591 		if (strcmp(sb.f_fstypename, MOUNT_CD9660) == 0
    592 			   || strcmp(sb.f_fstypename, MOUNT_UDF) == 0)
    593 			return 1;
    594 	}
    595 
    596 	return 0;
    597 }
    598 
    599 bool
    600 root_is_read_only(void)
    601 {
    602 	struct statvfs sb;
    603 
    604 	if (statvfs("/", &sb) == 0)
    605 		return sb.f_flag & ST_RDONLY;
    606 
    607 	return false;
    608 }
    609 
    610 /*
    611  * Get from a CDROM distribution.
    612  * Also used on "installation using bootable install media"
    613  * as the default option in the "distmedium" menu.
    614  */
    615 int
    616 get_via_cdrom(void)
    617 {
    618 	menu_ent cd_menu[MAX_CD_INFOS];
    619 	struct stat sb;
    620 	int rv, num_cds, menu_cd, i, selected_cd = 0;
    621 	int mib[2];
    622 	char rootdev[SSTRSIZE] = "";
    623 	size_t varlen;
    624 
    625 	/* If root is not md(4) and we have set dir, skip this step. */
    626 	mib[0] = CTL_KERN;
    627 	mib[1] = KERN_ROOT_DEVICE;
    628 	varlen = sizeof(rootdev);
    629 	(void)sysctl(mib, 2, rootdev, &varlen, NULL, 0);
    630 	if (stat(set_dir_bin, &sb) == 0 && S_ISDIR(sb.st_mode) &&
    631 	    strncmp("md", rootdev, 2) != 0) {
    632 	    	strlcpy(ext_dir_bin, set_dir_bin, sizeof ext_dir_bin);
    633 	    	strlcpy(ext_dir_src, set_dir_src, sizeof ext_dir_src);
    634 		return SET_OK;
    635 	}
    636 
    637 	memset(cd_menu, 0, sizeof(cd_menu));
    638 	num_cds = get_available_cds();
    639 	if (num_cds <= 0) {
    640 		msg_display(MSG_No_cd_found);
    641 		cdrom_dev[0] = 0;
    642 	} else if (num_cds == 1) {
    643 		/* single CD found, check for sets on it */
    644 		strcpy(cdrom_dev, cds[0].device_name);
    645 		if (cd_has_sets())
    646 			return SET_OK;
    647 	} else {
    648 		for (i = 0; i< num_cds; i++) {
    649 			cd_menu[i].opt_name = cds[i].menu;
    650 			cd_menu[i].opt_flags = OPT_EXIT;
    651 			cd_menu[i].opt_action = set_menu_select;
    652 		}
    653 		/* create a menu offering available choices */
    654 		menu_cd = new_menu(MSG_Available_cds,
    655 			cd_menu, num_cds, -1, 4, 0, 0,
    656 			MC_SCROLL | MC_NOEXITOPT,
    657 			NULL, NULL, NULL, NULL, NULL);
    658 		if (menu_cd == -1)
    659 			return SET_RETRY;
    660 		msg_display(MSG_ask_cd);
    661 		process_menu(menu_cd, &selected_cd);
    662 		free_menu(menu_cd);
    663 		strcpy(cdrom_dev, cds[selected_cd].device_name);
    664 		if (cd_has_sets())
    665 			return SET_OK;
    666 	}
    667 
    668 	if (num_cds >= 1 && mnt2_mounted) {
    669 		umount_mnt2();
    670 		hit_enter_to_continue(MSG_cd_path_not_found, NULL);
    671 	}
    672 
    673 	/* ask for paths on the CD */
    674 	rv = -1;
    675 	process_menu(MENU_cdromsource, &rv);
    676 	if (rv == SET_RETRY || rv == SET_ABANDON)
    677 		return rv;
    678 
    679 	if (cd_has_sets())
    680 		return SET_OK;
    681 
    682 	return SET_RETRY;
    683 }
    684 
    685 
    686 /*
    687  * Get from a pathname inside an unmounted local filesystem
    688  * (e.g., where sets were preloaded onto a local DOS partition)
    689  */
    690 int
    691 get_via_localfs(void)
    692 {
    693 	int rv = -1;
    694 
    695 	/* Get device, filesystem, and filepath */
    696 	process_menu (MENU_localfssource, &rv);
    697 	if (rv == SET_RETRY)
    698 		return SET_RETRY;
    699 
    700 	/* Mount it */
    701 	if (run_program(0, "/sbin/mount -rt %s /dev/%s /mnt2",
    702 	    localfs_fs, localfs_dev))
    703 		return SET_RETRY;
    704 
    705 	mnt2_mounted = 1;
    706 
    707 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s/%s",
    708 		"/mnt2", localfs_dir, set_dir_bin);
    709 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s/%s",
    710 		"/mnt2", localfs_dir, set_dir_src);
    711 
    712 	return SET_OK;
    713 }
    714 
    715 /*
    716  * Get from an already-mounted pathname.
    717  */
    718 
    719 int
    720 get_via_localdir(void)
    721 {
    722 	int rv = -1;
    723 
    724 	/* Get filepath */
    725 	process_menu(MENU_localdirsource, &rv);
    726 	if (rv == SET_RETRY)
    727 		return SET_RETRY;
    728 
    729 	/*
    730 	 * We have to have an absolute path ('cos pax runs in a
    731 	 * different directory), make it so.
    732 	 */
    733 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "/%s/%s", localfs_dir, set_dir_bin);
    734 	snprintf(ext_dir_src, sizeof ext_dir_src, "/%s/%s", localfs_dir, set_dir_src);
    735 
    736 	return SET_OK;
    737 }
    738 
    739 
    740 /*
    741  * Support for custom distribution fetches / unpacks.
    742  */
    743 
    744 unsigned int
    745 set_X11_selected(void)
    746 {
    747 	int i;
    748 
    749 	for (i = SET_X11_FIRST; ++i < SET_X11_LAST;)
    750 		if (set_status[i] & SET_SELECTED)
    751 			return 1;
    752 	return 0;
    753 }
    754 
    755 unsigned int
    756 get_kernel_set(void)
    757 {
    758 	int i;
    759 
    760 	for (i = SET_KERNEL_FIRST; ++i < SET_KERNEL_LAST;)
    761 		if (set_status[i] & SET_SELECTED)
    762 			return i;
    763 	return SET_NONE;
    764 }
    765 
    766 void
    767 set_kernel_set(unsigned int kernel_set)
    768 {
    769 	int i;
    770 
    771 	/* only one kernel set is allowed */
    772 	for (i = SET_KERNEL_FIRST; ++i < SET_KERNEL_LAST;)
    773 		set_status[i] &= ~SET_SELECTED;
    774 	set_status[kernel_set] |= SET_SELECTED;
    775 }
    776 
    777 void
    778 set_noextract_set(unsigned int set)
    779 {
    780 
    781 	set_status[set] |= SET_NO_EXTRACT;
    782 }
    783 
    784 static int
    785 set_toggle(menudesc *menu, void *arg)
    786 {
    787 	distinfo **distp = arg;
    788 	int set = distp[menu->cursel]->set;
    789 
    790 	if (set > SET_KERNEL_FIRST && set < SET_KERNEL_LAST &&
    791 	    !(set_status[set] & SET_SELECTED))
    792 		set_kernel_set(set);
    793 	else
    794 		set_status[set] ^= SET_SELECTED;
    795 	return 0;
    796 }
    797 
    798 static int
    799 set_all_none(menudesc *menu, void *arg, int set, int clr)
    800 {
    801 	distinfo **distp = arg;
    802 	distinfo *dist = *distp;
    803 	int nested;
    804 
    805 	for (nested = 0; dist->set != SET_GROUP_END || nested--; dist++) {
    806 		if (dist->set == SET_GROUP) {
    807 			nested++;
    808 			continue;
    809 		}
    810 		set_status[dist->set] = (set_status[dist->set] & ~clr) | set;
    811 	}
    812 	return 0;
    813 }
    814 
    815 static int
    816 set_all(menudesc *menu, void *arg)
    817 {
    818 	return set_all_none(menu, arg, SET_SELECTED, 0);
    819 }
    820 
    821 static int
    822 set_none(menudesc *menu, void *arg)
    823 {
    824 	return set_all_none(menu, arg, 0, SET_SELECTED);
    825 }
    826 
    827 static void
    828 set_label(menudesc *menu, int opt, void *arg)
    829 {
    830 	distinfo **distp = arg;
    831 	distinfo *dist = distp[opt];
    832 	const char *selected;
    833 	const char *desc;
    834 	int nested;
    835 
    836 	desc = dist->desc;
    837 
    838 	if (dist->set != SET_GROUP)
    839 		selected = set_status[dist->set] & SET_SELECTED ? msg_yes : msg_no;
    840 	else {
    841 		/* sub menu - display None/Some/All */
    842 		nested = 0;
    843 		selected = "unknown";
    844 		while ((++dist)->set != SET_GROUP_END || nested--) {
    845 			if (dist->set == SET_GROUP) {
    846 				nested++;
    847 				continue;
    848 			}
    849 			if (!(set_status[dist->set] & SET_VALID))
    850 				continue;
    851 			if (set_status[dist->set] & SET_SELECTED) {
    852 				if (selected == msg_none) {
    853 					selected = msg_some;
    854 					break;
    855 				}
    856 				selected = msg_all;
    857 			} else {
    858 				if (selected == msg_all) {
    859 					selected = msg_some;
    860 					break;
    861 				}
    862 				selected = msg_none;
    863 			}
    864 		}
    865 	}
    866 
    867 	wprintw(menu->mw, "%-30s %s", msg_string(desc), selected);
    868 }
    869 
    870 static int set_sublist(menudesc *menu, void *arg);
    871 
    872 static int
    873 initialise_set_menu(distinfo *dist, menu_ent *me, distinfo **de, int all_none)
    874 {
    875 	int set;
    876 	int sets;
    877 	int nested;
    878 
    879 	for (sets = 0; ; dist++) {
    880 		set = dist->set;
    881 		if (set == SET_LAST || set == SET_GROUP_END)
    882 			break;
    883 		if (!(set_status[set] & SET_VALID))
    884 			continue;
    885 		*de = dist;
    886 		memset(me, 0, sizeof(*me));
    887 		if (set != SET_GROUP)
    888 			me->opt_action = set_toggle;
    889 		else {
    890 			/* Collapse sublist */
    891 			nested = 0;
    892 			while ((++dist)->set != SET_GROUP_END || nested--) {
    893 				if (dist->set == SET_GROUP)
    894 					nested++;
    895 			}
    896 			me->opt_action = set_sublist;
    897 		}
    898 		sets++;
    899 		de++;
    900 		me++;
    901 	}
    902 
    903 	if (all_none) {
    904 		me->opt_name = MSG_select_all;
    905 		me->opt_action = set_all;
    906 		me++;
    907 		me->opt_name = MSG_select_none;
    908 		me->opt_action = set_none;
    909 		sets += 2;
    910 	}
    911 
    912 	return sets;
    913 }
    914 
    915 static int
    916 set_sublist(menudesc *menu, void *arg)
    917 {
    918 	distinfo *de[SET_LAST];
    919 	menu_ent me[SET_LAST];
    920 	distinfo **dist = arg;
    921 	int menu_no;
    922 	int sets;
    923 
    924 	memset(me, 0, sizeof(me));
    925 	sets = initialise_set_menu(dist[menu->cursel] + 1, me, de, 1);
    926 
    927 	menu_no = new_menu(NULL, me, sets, 20, 10, 0, select_menu_width,
    928 		MC_SUBMENU | MC_SCROLL | MC_DFLTEXIT,
    929 		NULL, set_label, NULL, NULL,
    930 		MSG_install_selected_sets);
    931 
    932 	process_menu(menu_no, de);
    933 	free_menu(menu_no);
    934 
    935 	return 0;
    936 }
    937 
    938 void
    939 customise_sets(void)
    940 {
    941 	distinfo *de[SET_LAST];
    942 	menu_ent me[SET_LAST];
    943 	int sets;
    944 	int menu_no;
    945 
    946 	msg_display(MSG_cur_distsets);
    947 	msg_table_add(MSG_cur_distsets_header);
    948 
    949 	memset(me, 0, sizeof(me));
    950 	sets = initialise_set_menu(dist_list, me, de, 0);
    951 
    952 	menu_no = new_menu(NULL, me, sets, 0, 5, 0, select_menu_width,
    953 		MC_SCROLL | MC_NOBOX | MC_DFLTEXIT | MC_NOCLEAR,
    954 		NULL, set_label, NULL, NULL,
    955 		MSG_install_selected_sets);
    956 
    957 	process_menu(menu_no, de);
    958 	free_menu(menu_no);
    959 }
    960 
    961 /*
    962  * Extract_file **REQUIRES** an absolute path in ext_dir.  Any code
    963  * that sets up xfer_dir for use by extract_file needs to put in the
    964  * full path name to the directory.
    965  */
    966 
    967 int
    968 extract_file(distinfo *dist, int update)
    969 {
    970 	const char *dest_dir = NULL;
    971 
    972 	if (update && (dist->set == SET_ETC || dist->set == SET_X11_ETC)) {
    973 		dest_dir = "/.sysinst";
    974 		make_target_dir(dest_dir);
    975 	} else if (dist->set == SET_PKGSRC)
    976 		dest_dir = "/usr";
    977 	else
    978 		dest_dir = "/";
    979 
    980 	return extract_file_to(dist, update, dest_dir, NULL, true);
    981 }
    982 
    983 int
    984 extract_file_to(distinfo *dist, int update, const char *dest_dir,
    985     const char *extr_pattern, bool do_stats)
    986 {
    987 	char path[STRSIZE];
    988 	char *owd;
    989 	int   rval;
    990 
    991 	/* If we might need to tidy up, ensure directory exists */
    992 	if (fetch_fn != NULL)
    993 		make_target_dir(xfer_dir);
    994 
    995 	(void)snprintf(path, sizeof path, "%s/%s%s",
    996 	    ext_dir_for_set(dist->name), dist->name, set_postfix(dist->name));
    997 
    998 	owd = getcwd(NULL, 0);
    999 
   1000 	/* Do we need to fetch the file now? */
   1001 	if (fetch_fn != NULL) {
   1002 		rval = fetch_fn(dist->name);
   1003 		if (rval != SET_OK)
   1004 			return rval;
   1005 	}
   1006 
   1007 	/* check tarfile exists */
   1008 	if (!file_exists_p(path)) {
   1009 
   1010 #ifdef SUPPORT_8_3_SOURCE_FILESYSTEM
   1011 		/*
   1012 		 * Update path to use dist->name truncated to the first eight
   1013 		 * characters and check again
   1014 		 */
   1015 		(void)snprintf(path, sizeof path,
   1016 		    "%s/%.8s%.4s", /* 4 as includes '.' */
   1017 		    ext_dir_for_set(dist->name), dist->name,
   1018 		    set_postfix(dist->name));
   1019 
   1020 		if (!file_exists_p(path)) {
   1021 #endif /* SUPPORT_8_3_SOURCE_FILESYSTEM */
   1022 			if (do_stats)
   1023 				tarstats.nnotfound++;
   1024 
   1025 			char *err = str_arg_subst(msg_string(MSG_notarfile),
   1026 			    1, &dist->name);
   1027 			hit_enter_to_continue(err, NULL);
   1028 			free(err);
   1029 			free(owd);
   1030 			return SET_RETRY;
   1031 		}
   1032 #ifdef SUPPORT_8_3_SOURCE_FILESYSTEM
   1033 	}
   1034 #endif /* SUPPORT_8_3_SOURCE_FILESYSTEM */
   1035 
   1036 	if (do_stats)
   1037 		tarstats.nfound++;
   1038 	/* cd to the target root. */
   1039 	target_chdir_or_die(dest_dir);
   1040 
   1041 	/*
   1042 	 * /usr/X11R7/lib/X11/xkb/symbols/pc was a directory in 5.0
   1043 	 * but is a file in 5.1 and beyond, so on upgrades we need to
   1044 	 * delete it before extracting the xbase set.
   1045 	 */
   1046 	if (update && dist->set == SET_X11_BASE)
   1047 		run_program(0, "rm -rf usr/X11R7/lib/X11/xkb/symbols/pc");
   1048 
   1049 	/* now extract set files into "./". */
   1050 	if (extr_pattern != NULL) {
   1051 		rval = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1052 				"progress -zf %s tar --chroot "
   1053 				TAR_EXTRACT_FLAGS " - '%s'",
   1054 				path, extr_pattern);
   1055 	} else {
   1056 		rval = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1057 				"progress -zf %s tar --chroot "
   1058 				TAR_EXTRACT_FLAGS " -", path);
   1059 	}
   1060 
   1061 	chdir(owd);
   1062 	free(owd);
   1063 
   1064 	/* Check rval for errors and give warning. */
   1065 	if (rval != 0) {
   1066 		if (do_stats)
   1067 			tarstats.nerror++;
   1068 		msg_fmt_display(MSG_tarerror, "%s", path);
   1069 		hit_enter_to_continue(NULL, NULL);
   1070 		return SET_RETRY;
   1071 	}
   1072 
   1073 	if (fetch_fn != NULL && clean_xfer_dir) {
   1074 		run_program(0, "rm %s", path);
   1075 		/* Plausibly we should unlink an empty xfer_dir as well */
   1076 	}
   1077 
   1078 	set_status[dist->set] |= SET_INSTALLED;
   1079 	if (do_stats)
   1080 		tarstats.nsuccess++;
   1081 	return SET_OK;
   1082 }
   1083 
   1084 static void
   1085 skip_set(distinfo *dist, int skip_type)
   1086 {
   1087 	int nested;
   1088 	int set;
   1089 
   1090 	nested = 0;
   1091 	while ((++dist)->set != SET_GROUP_END || nested--) {
   1092 		set = dist->set;
   1093 		if (set == SET_GROUP) {
   1094 			nested++;
   1095 			continue;
   1096 		}
   1097 		if (set == SET_LAST)
   1098 			break;
   1099 		if (set_status[set] == (SET_SELECTED | SET_VALID))
   1100 			set_status[set] |= SET_SKIPPED;
   1101 		tarstats.nskipped++;
   1102 	}
   1103 }
   1104 
   1105 distinfo*
   1106 get_set_distinfo(int opt)
   1107 {
   1108 	distinfo *dist;
   1109 	int set;
   1110 
   1111 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1112 		if (set != opt)
   1113 			continue;
   1114 		if (dist->name == NULL)
   1115 			continue;
   1116 		if ((set_status[set] & (SET_VALID | SET_SELECTED))
   1117 		    != (SET_VALID | SET_SELECTED))
   1118 			continue;
   1119 		return dist;
   1120 	}
   1121 
   1122 	return NULL;
   1123 }
   1124 
   1125 #ifdef CHECK_ENTROPY
   1126 
   1127 char entropy_file[PATH_MAX];
   1128 
   1129 /*
   1130  * Are we short of entropy?
   1131  */
   1132 size_t
   1133 entropy_needed(void)
   1134 {
   1135 	int needed;
   1136 	size_t len;
   1137 
   1138 	len = sizeof(needed);
   1139 	if (sysctlbyname("kern.entropy.needed", &needed, &len, NULL, 0))
   1140 		return 0;
   1141 
   1142 	if (needed < 0)
   1143 		return 0;
   1144 
   1145 	return needed;
   1146 }
   1147 
   1148 static void
   1149 entropy_write_to_kernel(const uint8_t *data, size_t len)
   1150 {
   1151 	int fd;
   1152 
   1153 	fd = open(_PATH_RANDOM, O_RDWR, 0);
   1154 	if (fd >= 0) {
   1155 		write(fd, data, len);
   1156 		close(fd);
   1157 	}
   1158 }
   1159 
   1160 static void
   1161 entropy_add_manual(void)
   1162 {
   1163 	SHA256_CTX ctx;
   1164 	char buf[256];
   1165 	uint8_t digest[SHA256_DIGEST_LENGTH];
   1166 	static const char prompt[] = "> ";
   1167 	size_t l;
   1168 	int txt_y;
   1169 
   1170 	msg_display(MSG_entropy_enter_manual1);
   1171 	msg_printf("\n\n");
   1172 	msg_display_add(MSG_entropy_enter_manual2);
   1173 	msg_printf("\n\n   dd if=/dev/random bs=32 count=1 | openssl base64\n\n");
   1174 	msg_display_add(MSG_entropy_enter_manual3);
   1175 	msg_printf("\n\n");
   1176 	SHA256_Init(&ctx);
   1177 	txt_y = getcury(mainwin)+1;
   1178 
   1179 	echo();
   1180 	wmove(mainwin, txt_y, 0);
   1181 	msg_fmt_table_add(prompt, prompt);
   1182 	mvwgetnstr(mainwin, txt_y, 2, buf, sizeof buf);
   1183 	l = strlen(buf);
   1184 	if (l > 0)
   1185 		SHA256_Update(&ctx, (const uint8_t*)buf, l);
   1186 	noecho();
   1187 	SHA256_Final(digest, &ctx);
   1188 
   1189 	wmove(mainwin, txt_y-1, 0);
   1190 	wclrtobot(mainwin);
   1191 	wrefresh(mainwin);
   1192 
   1193 	entropy_write_to_kernel(digest, sizeof digest);
   1194 }
   1195 
   1196 /*
   1197  * Get a file by some means and return a (potentially only
   1198  * temporary valid) path to the local copy.
   1199  * If mountpt is nonempty, the caller should unmount that
   1200  * directory after processing the file.
   1201  * Return success if the file is available, or failure if
   1202  * the user cancelled the request or network transfer failed.
   1203  */
   1204 static bool
   1205 entropy_get_file(bool use_netbsd_seed, char *path)
   1206 {
   1207 	static struct ftpinfo server = { .user = "ftp" };
   1208 	char url[STRSIZE], tmpf[PATH_MAX], mountpt[PATH_MAX];
   1209 	const char *ftp_opt;
   1210 	arg_rv arg;
   1211 	int rv = 0;
   1212 	const char *file_desc = msg_string(use_netbsd_seed ?
   1213 	    MSG_entropy_seed : MSG_entropy_data);
   1214 	char *dir;
   1215 
   1216 	path[0] = 0;
   1217 	mountpt[0] = 0;
   1218 
   1219 	sprintf(tmpf, "/tmp/entr.%06x", getpid());
   1220 
   1221 	msg_display(use_netbsd_seed ?
   1222 	    MSG_entropy_seed_hdr : MSG_entropy_data_hdr);
   1223 	msg_printf("\n\n    %s\n\n",
   1224 	    use_netbsd_seed ?
   1225 	    "rndctl -S /tmp/entropy-file" :
   1226 	    "dd if=/dev/random bs=32 count=1 of=/tmp/random.tmp");
   1227 	strcpy(entropy_file, use_netbsd_seed ?
   1228 	    "entropy-file" : "random.tmp");
   1229 	process_menu(MENU_entropy_select_file, &rv);
   1230 	switch (rv) {
   1231 	case 1:
   1232 	case 2:
   1233 #ifndef DEBUG
   1234 		if (!network_up)
   1235 			config_network(0);
   1236 #endif
   1237 		server.xfer = rv == 1 ? XFER_HTTP : XFER_FTP;
   1238 		arg.arg = &server;
   1239 		arg.rv = -1;
   1240 		msg_display_add_subst(MSG_entropy_via_download, 1, file_desc);
   1241 		msg_printf("\n\n");
   1242 		process_menu(MENU_entropy_ftpsource, &arg);
   1243 		if (arg.rv == SET_RETRY)
   1244 			return false;
   1245 		make_url(url, &server, entropy_file);
   1246 		if (server.xfer == XFER_FTP &&
   1247 		    strcmp("ftp", server.user) == 0 && server.pass[0] == 0) {
   1248 			/* do anon ftp */
   1249 			ftp_opt = "-a ";
   1250 		} else {
   1251 			ftp_opt = "";
   1252 		}
   1253 		rv = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1254 		    "/usr/bin/ftp %s -o %s %s",
   1255 		    ftp_opt, tmpf, url);
   1256 		strcpy(path, tmpf);
   1257 		return rv == 0;
   1258 	case 3:
   1259 #ifndef DEBUG
   1260 		if (!network_up)
   1261 			config_network(0);
   1262 #endif
   1263 		rv = -1;
   1264 		msg_display_add_subst(MSG_entropy_via_nfs, 1, file_desc);
   1265 		msg_printf("\n\n");
   1266 		process_menu(MENU_entropy_nfssource, &rv);
   1267 		if (rv == SET_RETRY)
   1268 			return false;
   1269 		if (nfs_host[0] != 0 && nfs_dir[0] != 0 &&
   1270 		    entropy_file[0] != 0) {
   1271 			strcpy(mountpt, "/tmp/ent-mnt.XXXXXX");
   1272 			dir = mkdtemp(mountpt);
   1273 			if (dir == NULL)
   1274 				return false;
   1275 			sprintf(path, "%s/%s", mountpt, entropy_file);
   1276 			if (run_program(RUN_SILENT,
   1277 			    "mount -t nfs -r %s:/%s %s",
   1278 			    nfs_host, nfs_dir, mountpt) == 0) {
   1279 				run_program(RUN_SILENT,
   1280 				    "cp %s %s", path, tmpf);
   1281 				run_program(RUN_SILENT,
   1282 				    "umount %s", mountpt);
   1283 				rmdir(mountpt);
   1284 				strcpy(path, tmpf);
   1285 			}
   1286 		}
   1287 		break;
   1288 	case 4:
   1289 		rv = -1;
   1290 		/* Get device, filesystem, and filepath */
   1291 		process_menu (MENU_entropy_localfs, &rv);
   1292 		if (rv == SET_RETRY)
   1293 			return false;
   1294 		if (localfs_dev[0] != 0 && localfs_fs[0] != 0 &&
   1295 		    entropy_file[0] != 0) {
   1296 			strcpy(mountpt, "/tmp/ent-mnt.XXXXXX");
   1297 			dir = mkdtemp(mountpt);
   1298 			if (dir == NULL)
   1299 				return false;
   1300 			sprintf(path, "%s/%s", mountpt, entropy_file);
   1301 			if (run_program(RUN_SILENT,
   1302 			    "mount -t %s -r /dev/%s %s",
   1303 			    localfs_fs, localfs_dev, mountpt) == 0) {
   1304 				run_program(RUN_SILENT,
   1305 				    "cp %s %s", path, tmpf);
   1306 				run_program(RUN_SILENT,
   1307 				    "umount %s", mountpt);
   1308 				rmdir(mountpt);
   1309 				strcpy(path, tmpf);
   1310 			}
   1311 		}
   1312 		break;
   1313 	}
   1314 	return path[0] != 0;
   1315 }
   1316 
   1317 static void
   1318 entropy_add_bin_file(void)
   1319 {
   1320 	char fname[PATH_MAX];
   1321 
   1322 	if (!entropy_get_file(false, fname))
   1323 		return;
   1324 	if (access(fname, R_OK) == 0)
   1325 		run_program(RUN_SILENT, "dd if=%s of=" _PATH_RANDOM,
   1326 		    fname);
   1327 }
   1328 
   1329 static void
   1330 entropy_add_seed(void)
   1331 {
   1332 	char fname[PATH_MAX];
   1333 
   1334 	if (!entropy_get_file(true, fname))
   1335 		return;
   1336 	if (access(fname, R_OK) == 0)
   1337 		run_program(RUN_SILENT, "rndctl -L %s", fname);
   1338 }
   1339 
   1340 /*
   1341  * return true if we have enough entropy
   1342  */
   1343 bool
   1344 do_add_entropy(void)
   1345 {
   1346 	int rv;
   1347 
   1348 	if (entropy_needed() == 0)
   1349 		return true;
   1350 
   1351 	for (;;) {
   1352 		if (entropy_needed() == 0)
   1353 			break;
   1354 
   1355 		msg_clear();
   1356 		rv = 0;
   1357 		process_menu(MENU_not_enough_entropy, &rv);
   1358 		switch (rv) {
   1359 		case 0:
   1360 			return false;
   1361 		case 1:
   1362 			entropy_add_manual();
   1363 			break;
   1364 		case 2:
   1365 			entropy_add_seed();
   1366 			break;
   1367 		case 3:
   1368 			entropy_add_bin_file();
   1369 			break;
   1370 		default:
   1371 			/*
   1372 			 * retry after small delay to give a new USB device
   1373 			 * a chance to attach and do deliver some
   1374 			 * entropy
   1375 			 */
   1376 			msg_display(".");
   1377 			for (size_t i = 0; i < 10; i++) {
   1378 				if (entropy_needed() == 0)
   1379 					return true;
   1380 				sleep(1);
   1381 				msg_display_add(".");
   1382 			}
   1383 		}
   1384 	}
   1385 
   1386 	/*
   1387 	 * Save entropy (maybe again) to give the seed file a good
   1388 	 * entropy estimate.
   1389 	 */
   1390 	run_program(RUN_SILENT | RUN_CHROOT | RUN_ERROR_OK,
   1391 	    "/etc/rc.d/random_seed stop");
   1392 
   1393 	return true;
   1394 }
   1395 #endif
   1396 
   1397 
   1398 
   1399 /*
   1400  * Get and unpack the distribution.
   1401  * Show success_msg if installation completes.
   1402  * Otherwise show failure_msg and wait for the user to ack it before continuing.
   1403  * success_msg and failure_msg must both be 0-adic messages.
   1404  */
   1405 int
   1406 get_and_unpack_sets(int update, msg setupdone_msg, msg success_msg, msg failure_msg)
   1407 {
   1408 	distinfo *dist;
   1409 	int status;
   1410 	int set, olderror, oldfound;
   1411 	bool entropy_loaded = false;
   1412 
   1413 	/* Ensure mountpoint for distribution files exists in current root. */
   1414 	(void)mkdir("/mnt2", S_IRWXU| S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH);
   1415 	if (script)
   1416 		(void)fprintf(script, "mkdir -m 755 /mnt2\n");
   1417 
   1418 	/* reset failure/success counters */
   1419 	memset(&tarstats, 0, sizeof(tarstats));
   1420 
   1421 	/* Find out which files to "get" if we get files. */
   1422 
   1423 	/* Accurately count selected sets */
   1424 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1425 		if (dist->name == NULL)
   1426 			continue;
   1427 		if (set_status[set] & SET_NO_EXTRACT)
   1428 			continue;
   1429 		if ((set_status[set] & (SET_VALID | SET_SELECTED))
   1430 		    == (SET_VALID | SET_SELECTED))
   1431 			tarstats.nselected++;
   1432 	}
   1433 
   1434 	status = SET_RETRY;
   1435 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1436 		if (dist->name == NULL)
   1437 			continue;
   1438 		if (set_status[set] != (SET_VALID | SET_SELECTED))
   1439 			continue;
   1440 
   1441 		/* save stats, in case we will retry */
   1442 		oldfound = tarstats.nfound;
   1443 		olderror = tarstats.nerror;
   1444 
   1445 		if (status != SET_OK) {
   1446 			/* This might force a redraw.... */
   1447 			clearok(curscr, 1);
   1448 			touchwin(stdscr);
   1449 			wrefresh(stdscr);
   1450 			/* Sort out the location of the set files */
   1451 			do {
   1452 				umount_mnt2();
   1453 				msg_fmt_display(MSG_distmedium, "%d%d%s",
   1454 				    tarstats.nselected,
   1455 				    tarstats.nsuccess + tarstats.nskipped,
   1456 				    dist->name);
   1457 				fetch_fn = NULL;
   1458 				process_menu(MENU_distmedium, &status);
   1459 			} while (status == SET_RETRY);
   1460 
   1461 			if (status == SET_SKIP) {
   1462 				set_status[set] |= SET_SKIPPED;
   1463 				tarstats.nskipped++;
   1464 				continue;
   1465 			}
   1466 			if (status == SET_SKIP_GROUP) {
   1467 				skip_set(dist, status);
   1468 				continue;
   1469 			}
   1470 			if (status != SET_OK) {
   1471 				hit_enter_to_continue(failure_msg, NULL);
   1472 				return 1;
   1473 			}
   1474 		}
   1475 
   1476 		if (set_status[set] & SET_NO_EXTRACT)
   1477 			continue;
   1478 
   1479 		/* Try to extract this set */
   1480 		status = extract_file(dist, update);
   1481 		if (status == SET_RETRY) {
   1482 			/* do this set again */
   1483 			dist--;
   1484 			/* and reset statistics to what we had before this
   1485 			 * set */
   1486 			tarstats.nfound = oldfound;
   1487 			tarstats.nerror = olderror;
   1488 		}
   1489 	}
   1490 
   1491 #ifdef MD_SET_EXTRACT_FINALIZE
   1492 	MD_SET_EXTRACT_FINALIZE(update);
   1493 #endif
   1494 
   1495 	if (tarstats.nerror == 0 && tarstats.nsuccess == tarstats.nselected) {
   1496 		msg_display(MSG_endtarok);
   1497 		/* Give user a chance to see the success message */
   1498 		sleep(1);
   1499 	} else {
   1500 		/* We encountered errors. Let the user know. */
   1501 		msg_fmt_display(MSG_endtar, "%d%d%d%d%d%d",
   1502 		    tarstats.nselected, tarstats.nnotfound, tarstats.nskipped,
   1503 		    tarstats.nfound, tarstats.nsuccess, tarstats.nerror);
   1504 		hit_enter_to_continue(NULL, NULL);
   1505 	}
   1506 
   1507 	/*
   1508 	 * postinstall needs to be run after extracting all sets, because
   1509 	 * otherwise /var/db/obsolete will only have current information
   1510 	 * from the base, comp, and etc sets.
   1511 	 */
   1512 	if (update && (set_status[SET_ETC] & SET_INSTALLED)) {
   1513 		int oldsendmail;
   1514 		oldsendmail = run_program(RUN_DISPLAY | RUN_CHROOT |
   1515 					  RUN_ERROR_OK | RUN_PROGRESS,
   1516 					  "/usr/sbin/postinstall -s /.sysinst -d / check mailerconf");
   1517 		if (oldsendmail == 1) {
   1518 			msg_display(MSG_oldsendmail);
   1519 			if (ask_yesno(NULL)) {
   1520 				run_program(RUN_DISPLAY | RUN_CHROOT,
   1521 					    "/usr/sbin/postinstall -s /.sysinst -d / fix mailerconf");
   1522 			}
   1523 		}
   1524 		run_program(RUN_DISPLAY | RUN_CHROOT,
   1525 			"/usr/sbin/postinstall -s /.sysinst -d / fix");
   1526 
   1527 		/* Don't discard the system's old entropy if any */
   1528 		run_program(RUN_CHROOT | RUN_SILENT,
   1529 		    "/etc/rc.d/random_seed start");
   1530 		entropy_loaded = true;
   1531 	}
   1532 
   1533 	/* Configure the system */
   1534 	if (set_status[SET_BASE] & SET_INSTALLED) {
   1535 		run_makedev();
   1536 		if (!update) {
   1537 			run_program(RUN_CHROOT|RUN_DISPLAY,
   1538 			    "/usr/sbin/certctl rehash");
   1539 		}
   1540 	}
   1541 
   1542 	if (!update) {
   1543 		struct stat sb1, sb2;
   1544 
   1545 		if (stat(target_expand("/"), &sb1) == 0
   1546 		    && stat(target_expand("/var"), &sb2) == 0
   1547 		    && sb1.st_dev != sb2.st_dev) {
   1548 			add_rc_conf("random_file=/etc/entropy-file\n");
   1549 			if (target_file_exists_p("/boot.cfg")) {
   1550 				run_program(RUN_CHROOT|RUN_FATAL,
   1551 					    "sh -c 'sed -e s./var/db/./etc/. "
   1552 					    "< /boot.cfg "
   1553 					    "> /tmp/boot.cfg.tmp'");
   1554 				mv_within_target_or_die("/tmp/boot.cfg.tmp",
   1555 							"/boot.cfg");
   1556 
   1557 			}
   1558 		}
   1559 
   1560 #ifdef MD_BOOT_CFG_FINALIZE
   1561 		if (target_file_exists_p("/boot.cfg")) {
   1562 			MD_BOOT_CFG_FINALIZE("/boot.cfg");
   1563 		}
   1564 #endif
   1565 
   1566 		/* Save keyboard type */
   1567 		save_kb_encoding();
   1568 
   1569 		/* Other configuration. */
   1570 		mnt_net_config();
   1571 	}
   1572 
   1573 	/* Mounted dist dir? */
   1574 	umount_mnt2();
   1575 
   1576 #ifdef CHECK_ENTROPY
   1577 	entropy_loaded |= entropy_needed() == 0;
   1578 #endif
   1579 
   1580 	/* Save entropy -- on some systems it's ~all we'll ever get */
   1581 	if (!update || entropy_loaded)
   1582 		run_program(RUN_SILENT | RUN_CHROOT | RUN_ERROR_OK,
   1583 		    "/etc/rc.d/random_seed stop");
   1584 	/* Install/Upgrade complete ... reboot or exit to script */
   1585 	hit_enter_to_continue(success_msg, NULL);
   1586 	return 0;
   1587 }
   1588 
   1589 void
   1590 umount_mnt2(void)
   1591 {
   1592 	if (!mnt2_mounted)
   1593 		return;
   1594 	run_program(RUN_SILENT, "/sbin/umount /mnt2");
   1595 	mnt2_mounted = 0;
   1596 }
   1597 
   1598 
   1599 /*
   1600  * Do a quick sanity check that  the target can reboot.
   1601  * return 1 if everything OK, 0 if there is a problem.
   1602  * Uses a table of files we expect to find after a base install/upgrade.
   1603  */
   1604 
   1605 /* test flag and pathname to check for after unpacking. */
   1606 struct check_table { unsigned int mode; const char *path;} checks[] = {
   1607   { S_IFREG, "/netbsd" },
   1608   { S_IFDIR, "/etc" },
   1609   { S_IFREG, "/etc/fstab" },
   1610   { S_IFREG, "/sbin/init" },
   1611   { S_IFREG, "/bin/sh" },
   1612   { S_IFREG, "/etc/rc" },
   1613   { S_IFREG, "/etc/rc.subr" },
   1614   { S_IFREG, "/etc/rc.conf" },
   1615   { S_IFDIR, "/dev" },
   1616   { S_IFCHR, "/dev/console" },
   1617 /* XXX check for rootdev in target /dev? */
   1618   { S_IFREG, "/sbin/fsck" },
   1619   { S_IFREG, "/sbin/fsck_ffs" },
   1620   { S_IFREG, "/sbin/mount" },
   1621   { S_IFREG, "/sbin/mount_ffs" },
   1622   { S_IFREG, "/sbin/mount_nfs" },
   1623 #if defined(DEBUG) || defined(DEBUG_CHECK)
   1624   { S_IFREG, "/foo/bar" },		/* bad entry to exercise warning */
   1625 #endif
   1626   { 0, 0 }
   1627 
   1628 };
   1629 
   1630 /*
   1631  * Check target for a single file.
   1632  */
   1633 static int
   1634 check_for(unsigned int mode, const char *pathname)
   1635 {
   1636 	int found;
   1637 
   1638 	found = (target_test(mode, pathname) == 0);
   1639 	if (found == 0)
   1640 		msg_fmt_display(MSG_rootmissing, "%s", pathname);
   1641 	return found;
   1642 }
   1643 
   1644 /*
   1645  * Check that all the files in check_table are present in the
   1646  * target root. Warn if not found.
   1647  */
   1648 int
   1649 sanity_check(void)
   1650 {
   1651 	int target_ok = 1;
   1652 	struct check_table *p;
   1653 
   1654 	for (p = checks; p->path; p++) {
   1655 		target_ok = target_ok && check_for(p->mode, p->path);
   1656 	}
   1657 	if (target_ok)
   1658 		return 0;
   1659 
   1660 	/* Uh, oh. Something's missing. */
   1661 	hit_enter_to_continue(MSG_badroot, NULL);
   1662 	return 1;
   1663 }
   1664 
   1665 /*
   1666  * Some globals to pass things back from callbacks
   1667  */
   1668 static char zoneinfo_dir[STRSIZE];
   1669 static int zonerootlen;
   1670 static char *tz_selected;	/* timezonename (relative to share/zoneinfo */
   1671 const char *tz_default;		/* UTC, or whatever /etc/localtime points to */
   1672 static char tz_env[STRSIZE];
   1673 static int save_cursel, save_topline;
   1674 static int time_menu = -1;
   1675 
   1676 static void
   1677 update_time_display(void)
   1678 {
   1679 	time_t t;
   1680 	struct tm *tm;
   1681 	char cur_time[STRSIZE], *p;
   1682 
   1683 	t = time(NULL);
   1684 	tm = localtime(&t);
   1685 	strlcpy(cur_time, safectime(&t), sizeof cur_time);
   1686 	p = strchr(cur_time, '\n');
   1687 	if (p != NULL)
   1688 		*p = 0;
   1689 
   1690 	msg_clear();
   1691 	msg_fmt_table_add(MSG_choose_timezone, "%s%s%s%s",
   1692 	    tz_default, tz_selected, cur_time, tm ? tm->tm_zone : "?");
   1693 }
   1694 
   1695 /*
   1696  * Callback from timezone menu
   1697  */
   1698 static int
   1699 set_tz_select(menudesc *m, void *arg)
   1700 {
   1701 	char *new;
   1702 
   1703 	if (m && strcmp(tz_selected, m->opts[m->cursel].opt_name) != 0) {
   1704 		/* Change the displayed timezone */
   1705 		new = strdup(m->opts[m->cursel].opt_name);
   1706 		if (new == NULL)
   1707 			return 0;
   1708 		free(tz_selected);
   1709 		tz_selected = new;
   1710 		snprintf(tz_env, sizeof tz_env, "%.*s%s",
   1711 			 zonerootlen, zoneinfo_dir, tz_selected);
   1712 		setenv("TZ", tz_env, 1);
   1713 	}
   1714 	if (m)
   1715 		/* Warp curser to 'Exit' line on menu */
   1716 		m->cursel = -1;
   1717 
   1718 	update_time_display();
   1719 	if (time_menu >= 1) {
   1720 		WINDOW *w = get_menudesc(time_menu)->mw;
   1721 		if (w != NULL) {
   1722 			touchwin(w);
   1723 			wrefresh(w);
   1724 		}
   1725 	}
   1726 	return 0;
   1727 }
   1728 
   1729 static int
   1730 set_tz_back(menudesc *m, void *arg)
   1731 {
   1732 
   1733 	zoneinfo_dir[zonerootlen] = 0;
   1734 	m->cursel = save_cursel;
   1735 	m->topline = save_topline;
   1736 	return 0;
   1737 }
   1738 
   1739 static int
   1740 set_tz_dir(menudesc *m, void *arg)
   1741 {
   1742 
   1743 	strlcpy(zoneinfo_dir + zonerootlen, m->opts[m->cursel].opt_name,
   1744 		sizeof zoneinfo_dir - zonerootlen);
   1745 	save_cursel = m->cursel;
   1746 	save_topline = m->topline;
   1747 	m->cursel = 0;
   1748 	m->topline = 0;
   1749 	return 0;
   1750 }
   1751 
   1752 /*
   1753  * Alarm-handler to update example-display
   1754  */
   1755 static void
   1756 /*ARGSUSED*/
   1757 timezone_sig(int sig)
   1758 {
   1759 
   1760 	set_tz_select(NULL, NULL);
   1761 	alarm(60);
   1762 }
   1763 
   1764 static int
   1765 tz_sort(const void *a, const void *b)
   1766 {
   1767 	return strcmp(((const menu_ent *)a)->opt_name, ((const menu_ent *)b)->opt_name);
   1768 }
   1769 
   1770 static void
   1771 tzm_set_names(menudesc *m, void *arg)
   1772 {
   1773 	DIR *dir;
   1774 	struct dirent *dp;
   1775 	static int nfiles;
   1776 	static int maxfiles = 32;
   1777 	static menu_ent *tz_menu;
   1778 	static char **tz_names;
   1779 	void *p;
   1780 	int maxfname;
   1781 	char *fp;
   1782 	struct stat sb;
   1783 
   1784 	if (tz_menu == NULL)
   1785 		tz_menu = calloc(maxfiles, sizeof *tz_menu);
   1786 	if (tz_names == NULL)
   1787 		tz_names = malloc(maxfiles * sizeof *tz_names);
   1788 	if (tz_menu == NULL || tz_names == NULL)
   1789 		return;	/* error - skip timezone setting */
   1790 	while (nfiles > 0)
   1791 		free(tz_names[--nfiles]);
   1792 
   1793 	dir = opendir(zoneinfo_dir);
   1794 	fp = strchr(zoneinfo_dir, 0);
   1795 	if (fp != zoneinfo_dir + zonerootlen) {
   1796 		tz_names[0] = 0;
   1797 		tz_menu[0].opt_name = msg_string(MSG_tz_back);
   1798 		tz_menu[0].opt_action = set_tz_back;
   1799 		nfiles = 1;
   1800 	}
   1801 	maxfname = zoneinfo_dir + sizeof zoneinfo_dir - fp - 1;
   1802 	if (dir != NULL) {
   1803 		while ((dp = readdir(dir)) != NULL) {
   1804 			if (dp->d_namlen > maxfname || dp->d_name[0] == '.')
   1805 				continue;
   1806 			strlcpy(fp, dp->d_name, maxfname);
   1807 			if (stat(zoneinfo_dir, &sb) == -1)
   1808 				continue;
   1809 			if (nfiles >= maxfiles) {
   1810 				p = realloc(tz_menu,
   1811 				    2 * maxfiles * sizeof *tz_menu);
   1812 				if (p == NULL)
   1813 					break;
   1814 				tz_menu = p;
   1815 				memset(tz_menu + maxfiles, 0,
   1816 				    maxfiles * sizeof *tz_menu);
   1817 				p = realloc(tz_names,
   1818 				    2 * maxfiles * sizeof *tz_names);
   1819 				if (p == NULL)
   1820 					break;
   1821 				tz_names = p;
   1822 				memset(tz_names + maxfiles, 0,
   1823 				    maxfiles * sizeof *tz_names);
   1824 				maxfiles *= 2;
   1825 			}
   1826 			if (S_ISREG(sb.st_mode))
   1827 				tz_menu[nfiles].opt_action = set_tz_select;
   1828 			else if (S_ISDIR(sb.st_mode)) {
   1829 				tz_menu[nfiles].opt_action = set_tz_dir;
   1830 				strlcat(fp, "/",
   1831 				    sizeof(zoneinfo_dir) - (fp - zoneinfo_dir));
   1832 			} else
   1833 				continue;
   1834 			tz_names[nfiles] = strdup(zoneinfo_dir + zonerootlen);
   1835 			tz_menu[nfiles].opt_name = tz_names[nfiles];
   1836 			nfiles++;
   1837 		}
   1838 		closedir(dir);
   1839 	}
   1840 	*fp = 0;
   1841 
   1842 	m->opts = tz_menu;
   1843 	m->numopts = nfiles;
   1844 	qsort(tz_menu, nfiles, sizeof *tz_menu, tz_sort);
   1845 }
   1846 
   1847 void
   1848 get_tz_default(void)
   1849 {
   1850 	char localtime_link[STRSIZE];
   1851 	static char localtime_target[STRSIZE];
   1852 	int rc;
   1853 
   1854 	strlcpy(localtime_link, target_expand("/etc/localtime"),
   1855 	    sizeof localtime_link);
   1856 
   1857 	/* Add sanity check that /mnt/usr/share/zoneinfo contains
   1858 	 * something useful
   1859 	 */
   1860 
   1861 	rc = readlink(localtime_link, localtime_target,
   1862 		      sizeof(localtime_target) - 1);
   1863 	if (rc < 0) {
   1864 		/* error, default to UTC */
   1865 		tz_default = "UTC";
   1866 	} else {
   1867 		localtime_target[rc] = '\0';
   1868 		tz_default = strchr(strstr(localtime_target, "zoneinfo"), '/') + 1;
   1869 	}
   1870 }
   1871 
   1872 /*
   1873  * Choose from the files in usr/share/zoneinfo and set etc/localtime
   1874  */
   1875 int
   1876 set_timezone(void)
   1877 {
   1878 	char localtime_link[STRSIZE];
   1879 	char localtime_target[STRSIZE];
   1880 	int menu_no;
   1881 
   1882 	strlcpy(zoneinfo_dir, target_expand("/usr/share/zoneinfo/"),
   1883 	    sizeof zoneinfo_dir - 1);
   1884 	zonerootlen = strlen(zoneinfo_dir);
   1885 
   1886 	get_tz_default();
   1887 
   1888 	tz_selected = strdup(tz_default);
   1889 	snprintf(tz_env, sizeof(tz_env), "%s%s", zoneinfo_dir, tz_selected);
   1890 	setenv("TZ", tz_env, 1);
   1891 	update_time_display();
   1892 
   1893 	signal(SIGALRM, timezone_sig);
   1894 	alarm(60);
   1895 
   1896 	menu_no = new_menu(NULL, NULL, 14, 23, 9,
   1897 			   12, 32, MC_ALWAYS_SCROLL | MC_NOSHORTCUT,
   1898 			   tzm_set_names, NULL, NULL,
   1899 			   "\nPlease consult the install documents.",
   1900 			   MSG_exit_menu_generic);
   1901 	if (menu_no >= 0) {
   1902 		time_menu = menu_no;
   1903 		process_menu(menu_no, NULL);
   1904 		time_menu = -1;
   1905 
   1906 		free_menu(menu_no);
   1907 	}
   1908 
   1909 	alarm(0);
   1910 	signal(SIGALRM, SIG_IGN);
   1911 
   1912 	if (menu_no >= 0) {
   1913 		snprintf(localtime_target, sizeof(localtime_target),
   1914 			 "/usr/share/zoneinfo/%s", tz_selected);
   1915 		strlcpy(localtime_link, target_expand("/etc/localtime"),
   1916 		    sizeof localtime_link);
   1917 		unlink(localtime_link);
   1918 		symlink(localtime_target, localtime_link);
   1919 	}
   1920 
   1921 	return 1;
   1922 }
   1923 
   1924 void
   1925 scripting_vfprintf(FILE *f, const char *fmt, va_list ap)
   1926 {
   1927 	va_list ap2;
   1928 
   1929 	va_copy(ap2, ap);
   1930 	if (f)
   1931 		(void)vfprintf(f, fmt, ap);
   1932 	if (script)
   1933 		(void)vfprintf(script, fmt, ap2);
   1934 }
   1935 
   1936 void
   1937 scripting_fprintf(FILE *f, const char *fmt, ...)
   1938 {
   1939 	va_list ap;
   1940 
   1941 	va_start(ap, fmt);
   1942 	scripting_vfprintf(f, fmt, ap);
   1943 	va_end(ap);
   1944 }
   1945 
   1946 void
   1947 add_rc_conf(const char *fmt, ...)
   1948 {
   1949 	FILE *f;
   1950 	va_list ap;
   1951 
   1952 	va_start(ap, fmt);
   1953 	f = target_fopen("/etc/rc.conf", "a");
   1954 	if (f != 0) {
   1955 		scripting_fprintf(NULL, "cat <<EOF >>%s/etc/rc.conf\n",
   1956 		    target_prefix());
   1957 		scripting_vfprintf(f, fmt, ap);
   1958 		fclose(f);
   1959 		scripting_fprintf(NULL, "EOF\n");
   1960 	}
   1961 	va_end(ap);
   1962 }
   1963 
   1964 int
   1965 del_rc_conf(const char *value)
   1966 {
   1967 	FILE *fp, *nfp;
   1968 	char buf[4096]; /* Ridiculously high, but should be enough in any way */
   1969 	char *rcconf, *tempname = NULL, *bakname = NULL;
   1970 	char *cp;
   1971 	int done = 0;
   1972 	int fd;
   1973 	int retval = 0;
   1974 
   1975 	/* The paths might seem strange, but using /tmp would require copy instead
   1976 	 * of rename operations. */
   1977 	if (asprintf(&rcconf, "%s", target_expand("/etc/rc.conf")) < 0
   1978 			|| asprintf(&tempname, "%s", target_expand("/etc/rc.conf.tmp.XXXXXX")) < 0
   1979 			|| asprintf(&bakname, "%s", target_expand("/etc/rc.conf.bak.XXXXXX")) < 0) {
   1980 		if (rcconf)
   1981 			free(rcconf);
   1982 		if (tempname)
   1983 			free(tempname);
   1984 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   1985 		hit_enter_to_continue(NULL, NULL);
   1986 		return -1;
   1987 	}
   1988 
   1989 	if ((fd = mkstemp(bakname)) < 0) {
   1990 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   1991 		hit_enter_to_continue(NULL, NULL);
   1992 		return -1;
   1993 	}
   1994 	close(fd);
   1995 
   1996 	if (!(fp = fopen(rcconf, "r+")) || (fd = mkstemp(tempname)) < 0) {
   1997 		if (fp)
   1998 			fclose(fp);
   1999 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   2000 		hit_enter_to_continue(NULL, NULL);
   2001 		return -1;
   2002 	}
   2003 
   2004 	nfp = fdopen(fd, "w");
   2005 	if (!nfp) {
   2006 		fclose(fp);
   2007 		close(fd);
   2008 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   2009 		hit_enter_to_continue(NULL, NULL);
   2010 		return -1;
   2011 	}
   2012 
   2013 	while (fgets(buf, sizeof buf, fp) != NULL) {
   2014 
   2015 		cp = buf + strspn(buf, " \t"); /* Skip initial spaces */
   2016 		if (strncmp(cp, value, strlen(value)) == 0) {
   2017 			cp += strlen(value);
   2018 			if (*cp != '=')
   2019 				scripting_fprintf(nfp, "%s", buf);
   2020 			else
   2021 				done = 1;
   2022 		} else {
   2023 			scripting_fprintf(nfp, "%s", buf);
   2024 		}
   2025 	}
   2026 	fclose(fp);
   2027 	fclose(nfp);
   2028 
   2029 	if (done) {
   2030 		if (rename(rcconf, bakname)) {
   2031 			msg_display(MSG_rcconf_backup_failed);
   2032 			if (!ask_noyes(NULL)) {
   2033 				retval = -1;
   2034 				goto done;
   2035 			}
   2036 		}
   2037 
   2038 		if (rename(tempname, rcconf)) {
   2039 			if (rename(bakname, rcconf)) {
   2040 				hit_enter_to_continue(MSG_rcconf_restore_failed,
   2041 				    NULL);
   2042 			} else {
   2043 				hit_enter_to_continue(MSG_rcconf_delete_failed,
   2044 				    NULL);
   2045 			}
   2046 		} else {
   2047 			(void)unlink(bakname);
   2048 		}
   2049 	}
   2050 
   2051 done:
   2052 	(void)unlink(tempname);
   2053 	free(rcconf);
   2054 	free(tempname);
   2055 	free(bakname);
   2056 	return retval;
   2057 }
   2058 
   2059 void
   2060 add_sysctl_conf(const char *fmt, ...)
   2061 {
   2062 	FILE *f;
   2063 	va_list ap;
   2064 
   2065 	va_start(ap, fmt);
   2066 	f = target_fopen("/etc/sysctl.conf", "a");
   2067 	if (f != 0) {
   2068 		scripting_fprintf(NULL, "cat <<EOF >>%s/etc/sysctl.conf\n",
   2069 		    target_prefix());
   2070 		scripting_vfprintf(f, fmt, ap);
   2071 		fclose(f);
   2072 		scripting_fprintf(NULL, "EOF\n");
   2073 	}
   2074 	va_end(ap);
   2075 }
   2076 
   2077 void
   2078 enable_rc_conf(void)
   2079 {
   2080 
   2081 	replace("/etc/rc.conf", "s/^rc_configured=NO/rc_configured=YES/");
   2082 }
   2083 
   2084 int
   2085 check_lfs_progs(void)
   2086 {
   2087 
   2088 #ifndef NO_LFS
   2089 	return binary_available("fsck_lfs") && binary_available("mount_lfs")
   2090 	    && binary_available("newfs_lfs");
   2091 #else
   2092 	return 0;
   2093 #endif
   2094 }
   2095 
   2096 int
   2097 set_is_source(const char *set_name) {
   2098 	int len = strlen(set_name);
   2099 	return len >= 3 && memcmp(set_name + len - 3, "src", 3) == 0;
   2100 }
   2101 
   2102 const char *
   2103 set_dir_for_set(const char *set_name) {
   2104 	if (strcmp(set_name, "pkgsrc") == 0)
   2105 		return pkgsrc_dir;
   2106 	return set_is_source(set_name) ? set_dir_src : set_dir_bin;
   2107 }
   2108 
   2109 const char *
   2110 ext_dir_for_set(const char *set_name) {
   2111 	if (strcmp(set_name, "pkgsrc") == 0)
   2112 		return ext_dir_pkgsrc;
   2113 	return set_is_source(set_name) ? ext_dir_src : ext_dir_bin;
   2114 }
   2115 
   2116 void
   2117 do_coloring(unsigned int fg, unsigned int bg) {
   2118 	if (bg > COLOR_WHITE)
   2119 		bg = COLOR_BLUE;
   2120 	if (fg > COLOR_WHITE)
   2121 		fg = COLOR_WHITE;
   2122 	if (fg != bg && has_colors()) {
   2123 		init_pair(1, fg, bg);
   2124 		wbkgd(stdscr, COLOR_PAIR(1));
   2125 		wbkgd(mainwin, COLOR_PAIR(1));
   2126 		wattrset(stdscr, COLOR_PAIR(1));
   2127 		wattrset(mainwin, COLOR_PAIR(1));
   2128 	}
   2129 	/* redraw screen */
   2130 	touchwin(stdscr);
   2131 	touchwin(mainwin);
   2132 	wrefresh(stdscr);
   2133 	wrefresh(mainwin);
   2134 	return;
   2135 }
   2136 
   2137 int
   2138 set_menu_select(menudesc *m, void *arg)
   2139 {
   2140 	*(int *)arg = m->cursel;
   2141 	return 1;
   2142 }
   2143 
   2144 /*
   2145  * check whether a binary is available somewhere in PATH,
   2146  * return 1 if found, 0 if not.
   2147  */
   2148 static int
   2149 binary_available(const char *prog)
   2150 {
   2151         char *p, tmp[MAXPATHLEN], *path = getenv("PATH"), *opath;
   2152 
   2153         if (path == NULL)
   2154                 return access(prog, X_OK) == 0;
   2155         path = strdup(path);
   2156         if (path == NULL)
   2157                 return 0;
   2158 
   2159 	opath = path;
   2160 
   2161         while ((p = strsep(&path, ":")) != NULL) {
   2162                 if (strlcpy(tmp, p, MAXPATHLEN) >= MAXPATHLEN)
   2163                         continue;
   2164                 if (strlcat(tmp, "/", MAXPATHLEN) >= MAXPATHLEN)
   2165                         continue;
   2166                 if (strlcat(tmp, prog, MAXPATHLEN) >= MAXPATHLEN)
   2167                         continue;
   2168                 if (access(tmp, X_OK) == 0) {
   2169                         free(opath);
   2170                         return 1;
   2171                 }
   2172         }
   2173         free(opath);
   2174         return 0;
   2175 }
   2176 
   2177 const char *
   2178 safectime(time_t *t)
   2179 {
   2180 	const char *s = ctime(t);
   2181 	if (s != NULL)
   2182 		return s;
   2183 
   2184 	// Debugging.
   2185 	fprintf(stderr, "Can't convert to localtime 0x%jx (%s)\n",
   2186 	    (intmax_t)*t, strerror(errno));
   2187 	      /*123456789012345678901234*/
   2188 	return "preposterous clock time\n";
   2189 }
   2190 
   2191 int
   2192 ask_yesno(const char* msgtxt)
   2193 {
   2194 	arg_rv p;
   2195 
   2196 	p.arg = __UNCONST(msgtxt);
   2197 	p.rv = -1;
   2198 
   2199 	process_menu(MENU_yesno, &p);
   2200 	return p.rv;
   2201 }
   2202 
   2203 int
   2204 ask_noyes(const char *msgtxt)
   2205 {
   2206 	arg_rv p;
   2207 
   2208 	p.arg = __UNCONST(msgtxt);
   2209 	p.rv = -1;
   2210 
   2211 	process_menu(MENU_noyes, &p);
   2212 	return p.rv;
   2213 }
   2214 
   2215 int
   2216 ask_reedit(const struct disk_partitions *parts)
   2217 {
   2218 	const char *args[2];
   2219 	arg_rep_int arg;
   2220 
   2221 	args[0] = msg_string(parts->pscheme->name);
   2222 	args[1] = msg_string(parts->pscheme->short_name);
   2223 	arg.args.argv = args;
   2224 	arg.args.argc = 2;
   2225 	arg.rv = 0;
   2226 	process_menu(MENU_reedit, &arg);
   2227 
   2228 	return arg.rv;
   2229 }
   2230 
   2231 bool
   2232 use_tgz_for_set(const char *set_name)
   2233 {
   2234 	const struct distinfo *dist;
   2235 
   2236 	for (dist = dist_list; dist->set != SET_LAST; dist++) {
   2237 		if (dist->name == NULL)
   2238 			continue;
   2239 		if (strcmp(set_name, dist->name) == 0)
   2240 			return dist->force_tgz;
   2241 	}
   2242 
   2243 	return true;
   2244 }
   2245 
   2246 /* Return the postfix used for a given set */
   2247 const char *
   2248 set_postfix(const char *set_name)
   2249 {
   2250 	return use_tgz_for_set(set_name) ? dist_tgz_postfix : dist_postfix;
   2251 }
   2252 
   2253 /*
   2254  * Replace positional arguments (encoded as $0 .. $N) in the string
   2255  * passed by the contents of the passed argument array.
   2256  * Caller must free() the result string.
   2257  */
   2258 char*
   2259 str_arg_subst(const char *src, size_t argc, const char **argv)
   2260 {
   2261 	const char *p, *last;
   2262 	char *out, *t;
   2263 	size_t len;
   2264 
   2265 	len = strlen(src);
   2266 	for (p = strchr(src, '$'); p; p = strchr(p+1, '$')) {
   2267 		char *endp = NULL;
   2268 		size_t n;
   2269 		int e;
   2270 
   2271 		/* $ followed by a correct numeric position? */
   2272 		n = strtou(p+1, &endp, 10, 0, INT_MAX, &e);
   2273 		if ((e == 0 || e == ENOTSUP) && n < argc) {
   2274 			len += strlen(argv[n]);
   2275 			len -= endp-p;
   2276 			p = endp-1;
   2277 		}
   2278 	}
   2279 
   2280 	out = malloc(len+1);
   2281 	if (out == NULL)
   2282 		return NULL;
   2283 
   2284 	t = out;
   2285 	for (last = src, p = strchr(src, '$'); p; p = strchr(p+1, '$')) {
   2286 		char *endp = NULL;
   2287 		size_t n;
   2288 		int e;
   2289 
   2290 		/* $ followed by a correct numeric position? */
   2291 		n = strtou(p+1, &endp, 10, 0, INT_MAX, &e);
   2292 		if ((e == 0 || e == ENOTSUP) && n < argc) {
   2293 			size_t l = p-last;
   2294 			memcpy(t, last, l);
   2295 			t += l;
   2296 			strcpy(t, argv[n]);
   2297 			t += strlen(argv[n]);
   2298 			last = endp;
   2299 		}
   2300 	}
   2301 	if (*last) {
   2302 		strcpy(t, last);
   2303 		t += strlen(last);
   2304 	} else {
   2305 		*t = 0;
   2306 	}
   2307 	assert((size_t)(t-out) == len);
   2308 
   2309 	return out;
   2310 }
   2311 
   2312 /*
   2313  * Does this string have any positional args that need expanding?
   2314  */
   2315 bool
   2316 needs_expanding(const char *src, size_t argc)
   2317 {
   2318 	const char *p;
   2319 
   2320 	for (p = strchr(src, '$'); p; p = strchr(p+1, '$')) {
   2321 		char *endp = NULL;
   2322 		size_t n;
   2323 		int e;
   2324 
   2325 		/* $ followed by a correct numeric position? */
   2326 		n = strtou(p+1, &endp, 10, 0, INT_MAX, &e);
   2327 		if ((e == 0 || e == ENOTSUP) && n < argc)
   2328 			return true;
   2329 	}
   2330 	return false;
   2331 }
   2332 
   2333 /*
   2334  * Replace positional arguments (encoded as $0 .. $N) in the
   2335  * message by the strings passed as ... and call outfunc
   2336  * with the result.
   2337  */
   2338 static void
   2339 msg_display_subst_internal(void (*outfunc)(msg),
   2340     const char *master, size_t argc, va_list ap)
   2341 {
   2342 	const char **args, **arg;
   2343 	char *out;
   2344 
   2345 	args = calloc(argc, sizeof(*args));
   2346 	if (args == NULL)
   2347 		return;
   2348 
   2349 	arg = args;
   2350 	for (size_t i = 0; i < argc; i++)
   2351 		*arg++ = va_arg(ap, const char*);
   2352 
   2353 	out = str_arg_subst(msg_string(master), argc, args);
   2354 	if (out != NULL) {
   2355 		outfunc(out);
   2356 		free(out);
   2357 	}
   2358 	free(args);
   2359 }
   2360 
   2361 /*
   2362  * Replace positional arguments (encoded as $0 .. $N) in the
   2363  * message by the strings passed as ...
   2364  */
   2365 void
   2366 msg_display_subst(const char *master, size_t argc, ...)
   2367 {
   2368 	va_list ap;
   2369 
   2370 	va_start(ap, argc);
   2371 	msg_display_subst_internal(msg_display, master, argc, ap);
   2372 	va_end(ap);
   2373 }
   2374 
   2375 /*
   2376  * Same as above, but add to message instead of starting a new one
   2377  */
   2378 void
   2379 msg_display_add_subst(const char *master, size_t argc, ...)
   2380 {
   2381 	va_list ap;
   2382 
   2383 	va_start(ap, argc);
   2384 	msg_display_subst_internal(msg_display_add, master, argc, ap);
   2385 	va_end(ap);
   2386 }
   2387 
   2388 /* initialize have_* variables */
   2389 void
   2390 check_available_binaries(void)
   2391 {
   2392 	static int did_test = false;
   2393 
   2394 	if (did_test) return;
   2395 	did_test = 1;
   2396 
   2397 	have_raid = binary_available("raidctl");
   2398 	have_vnd = binary_available("vndconfig");
   2399 	have_cgd = binary_available("cgdconfig");
   2400 	have_lvm = binary_available("lvm");
   2401 	have_gpt = binary_available("gpt");
   2402 	have_dk = binary_available("dkctl");
   2403 }
   2404 
   2405 /*
   2406  * Wait for enter and immediately clear the screen after user response
   2407  * (in case some longer action follows, so the user has instant feedback)
   2408  */
   2409 void
   2410 hit_enter_to_continue(const char *prompt, const char *title)
   2411 {
   2412 	if (prompt != NULL)
   2413 		msg_display(prompt);
   2414         process_menu(MENU_ok, __UNCONST(title));
   2415 	msg_clear();
   2416 	wrefresh(mainwin);
   2417 }
   2418 
   2419 /*
   2420  * On auto pilot:
   2421  * convert an existing set of partitions ot a list of part_usage_info
   2422  * so that we "want" exactly what is there already.
   2423  */
   2424 static bool
   2425 usage_info_list_from_parts(struct part_usage_info **list, size_t *count,
   2426     struct disk_partitions *parts)
   2427 {
   2428 	struct disk_part_info info;
   2429 	part_id pno;
   2430 	size_t no, num;
   2431 
   2432 	num = 0;
   2433 	for (pno = 0; pno < parts->num_part; pno++) {
   2434 		if (!parts->pscheme->get_part_info(parts, pno, &info))
   2435 			continue;
   2436 		num++;
   2437 	}
   2438 
   2439 	*list = calloc(num, sizeof(**list));
   2440 	if (*list == NULL)
   2441 		return false;
   2442 
   2443 	*count = num;
   2444 	for (no = pno = 0; pno < parts->num_part && no < num; pno++) {
   2445 		if (!parts->pscheme->get_part_info(parts, pno, &info))
   2446 			continue;
   2447 		(*list)[no].size = info.size;
   2448 		if (info.last_mounted != NULL && *info.last_mounted != 0) {
   2449 			strlcpy((*list)[no].mount, info.last_mounted,
   2450 			    sizeof((*list)[no].mount));
   2451 			(*list)[no].instflags |= PUIINST_MOUNT;
   2452 		}
   2453 		(*list)[no].parts = parts;
   2454 		(*list)[no].cur_part_id = pno;
   2455 		(*list)[no].cur_start = info.start;
   2456 		(*list)[no].cur_flags = info.flags;
   2457 		(*list)[no].type = info.nat_type->generic_ptype;
   2458 		if ((*list)[no].type == PT_swap) {
   2459 			(*list)[no].fs_type = FS_SWAP;
   2460 			(*list)[no].fs_version = 0;
   2461 		} else {
   2462 			(*list)[no].fs_type = info.fs_type;
   2463 			(*list)[no].fs_version = info.fs_sub_type;
   2464 		}
   2465 		(*list)[no].fs_opt1 = info.fs_opt1;
   2466 		(*list)[no].fs_opt2 = info.fs_opt2;
   2467 		(*list)[no].fs_opt3 = info.fs_opt3;
   2468 		no++;
   2469 	}
   2470 	return true;
   2471 }
   2472 
   2473 bool
   2474 empty_usage_set_from_parts(struct partition_usage_set *wanted,
   2475     struct disk_partitions *parts)
   2476 {
   2477 	usage_set_from_parts(wanted, parts);
   2478 	return true;
   2479 }
   2480 
   2481 bool
   2482 usage_set_from_parts(struct partition_usage_set *wanted,
   2483     struct disk_partitions *parts)
   2484 {
   2485 	memset(wanted, 0, sizeof(*wanted));
   2486 	wanted->parts = parts;
   2487 
   2488 	return usage_info_list_from_parts(&wanted->infos, &wanted->num, parts);
   2489 }
   2490 
   2491 bool
   2492 usage_set_from_install_desc(struct partition_usage_set *pset,
   2493     const struct install_partition_desc *install,
   2494     struct disk_partitions *parts)
   2495 {
   2496 	size_t cnt, i;
   2497 
   2498 	memset(pset, 0, sizeof(*pset));
   2499 	pset->parts = parts;
   2500 
   2501 	if (!install->infos || !install->num)
   2502 		return false;
   2503 
   2504 	for (cnt = 0, i = 0; i < install->num; i++) {
   2505 		if (install->infos[i].parts != parts)
   2506 			continue;
   2507 		cnt++;
   2508 	}
   2509 	if (!cnt)
   2510 		return false;
   2511 	pset->num = cnt;
   2512 	pset->infos = calloc(cnt, sizeof(*pset->infos));
   2513 	if (!pset->infos)
   2514 		return false;
   2515 	for (cnt = 0, i = 0; i < install->num; i++) {
   2516 		if (install->infos[i].parts != parts)
   2517 			continue;
   2518 		pset->infos[cnt] = install->infos[i];
   2519 		cnt++;
   2520 	}
   2521 	return true;
   2522 }
   2523 
   2524 bool
   2525 merge_usage_set_into_install_desc(struct install_partition_desc *install,
   2526     const struct partition_usage_set *pset)
   2527 {
   2528 	// XXX
   2529 	return false;
   2530 }
   2531 
   2532 struct disk_partitions *
   2533 get_inner_parts(struct disk_partitions *parts)
   2534 {
   2535 	daddr_t start, size;
   2536 	part_id pno;
   2537 	struct disk_part_info info;
   2538 
   2539 	if (parts->pscheme->secondary_scheme == NULL)
   2540 		return NULL;
   2541 
   2542 	start = -1;
   2543 	size = -1;
   2544 	if (parts->pscheme->guess_install_target == NULL ||
   2545 	    !parts->pscheme->guess_install_target(parts, &start, &size)) {
   2546 		for (pno = 0; pno < parts->num_part; pno++) {
   2547 			if (!parts->pscheme->get_part_info(parts, pno, &info))
   2548 				continue;
   2549 			if (!(info.flags & PTI_SEC_CONTAINER))
   2550 				continue;
   2551 			start = info.start;
   2552 			size = info.size;
   2553 		}
   2554 	}
   2555 
   2556 	if (size > 0)
   2557 		return parts->pscheme->secondary_partitions(parts, start,
   2558 		    false);
   2559 
   2560 	return NULL;
   2561 }
   2562 
   2563 bool
   2564 install_desc_from_parts(struct install_partition_desc *install,
   2565     struct disk_partitions *parts)
   2566 {
   2567 	struct disk_partitions *inner_parts;
   2568 
   2569 	memset(install, 0, sizeof(*install));
   2570 	inner_parts = get_inner_parts(parts);
   2571 	if (inner_parts != NULL)
   2572 		parts = inner_parts;
   2573 
   2574 	return usage_info_list_from_parts(&install->infos, &install->num,
   2575 	    parts);
   2576 }
   2577 
   2578 void
   2579 free_usage_set(struct partition_usage_set *wanted)
   2580 {
   2581 	/* XXX - free parts? free clone src? */
   2582 	free(wanted->write_back);
   2583 	free(wanted->menu_opts);
   2584 	free(wanted->infos);
   2585 }
   2586 
   2587 void
   2588 free_install_desc(struct install_partition_desc *install)
   2589 {
   2590 	size_t i, j;
   2591 
   2592 #ifndef NO_CLONES
   2593 	for (i = 0; i < install->num; i++) {
   2594 		struct selected_partitions *src = install->infos[i].clone_src;
   2595 		if (!(install->infos[i].flags & PUIFLG_CLONE_PARTS) ||
   2596 		    src == NULL)
   2597 			continue;
   2598 		free_selected_partitions(src);
   2599 		for (j = i+1; j < install->num; j++)
   2600 			if (install->infos[j].clone_src == src)
   2601 				install->infos[j].clone_src = NULL;
   2602 	}
   2603 #endif
   2604 
   2605 	for (i = 0; i < install->num; i++) {
   2606 		struct disk_partitions * parts = install->infos[i].parts;
   2607 
   2608 		if (parts == NULL)
   2609 			continue;
   2610 
   2611 		if (parts->pscheme->free)
   2612 			parts->pscheme->free(parts);
   2613 
   2614 		/* NULL all other references to this parts */
   2615 		for (j = i+1; j < install->num; j++)
   2616 			if (install->infos[j].parts == parts)
   2617 				install->infos[j].parts = NULL;
   2618 	}
   2619 
   2620 	free(install->write_back);
   2621 	free(install->infos);
   2622 }
   2623 
   2624 #ifdef MD_MAY_SWAP_TO
   2625 bool
   2626 may_swap_if_not_sdmmc(const char *disk)
   2627 {
   2628 	int fd, res;
   2629 	prop_dictionary_t command_dict, args_dict, results_dict, data_dict;
   2630 	prop_string_t string;
   2631 	prop_number_t number;
   2632 	const char *parent = "";
   2633 
   2634 	fd = open(DRVCTLDEV, O_RDONLY, 0);
   2635 	if (fd == -1)
   2636 		return true;
   2637 
   2638 	command_dict = prop_dictionary_create();
   2639 	args_dict = prop_dictionary_create();
   2640 
   2641 	string = prop_string_create_nocopy("get-properties");
   2642 	prop_dictionary_set(command_dict, "drvctl-command", string);
   2643 	prop_object_release(string);
   2644 
   2645 	string = prop_string_create_copy(disk);
   2646 	prop_dictionary_set(args_dict, "device-name", string);
   2647 	prop_object_release(string);
   2648 
   2649 	prop_dictionary_set(command_dict, "drvctl-arguments",
   2650 	    args_dict);
   2651 	prop_object_release(args_dict);
   2652 
   2653 	res = prop_dictionary_sendrecv_ioctl(command_dict, fd,
   2654 	    DRVCTLCOMMAND, &results_dict);
   2655 	prop_object_release(command_dict);
   2656 	close(fd);
   2657 	if (res)
   2658 		return true;
   2659 
   2660 	number = prop_dictionary_get(results_dict, "drvctl-error");
   2661 	if (prop_number_signed_value(number) == 0) {
   2662 		data_dict = prop_dictionary_get(results_dict,
   2663 		    "drvctl-result-data");
   2664 		if (data_dict != NULL) {
   2665 			string = prop_dictionary_get(data_dict,
   2666 			    "device-parent");
   2667 			if (string != NULL)
   2668 				parent = prop_string_value(string);
   2669 		}
   2670 	}
   2671 
   2672 	prop_object_release(results_dict);
   2673 
   2674 	if (parent == NULL)
   2675 		return true;
   2676 
   2677 	return strncmp(parent, "sdmmc", 5) != 0;
   2678 }
   2679 #endif
   2680