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