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