Home | History | Annotate | Line # | Download | only in sysinst
util.c revision 1.29.2.6
      1 /*	$NetBSD: util.c,v 1.29.2.6 2020/01/28 10:17:58 msaitoh 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 
   1087 	/* Ensure mountpoint for distribution files exists in current root. */
   1088 	(void)mkdir("/mnt2", S_IRWXU| S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH);
   1089 	if (script)
   1090 		(void)fprintf(script, "mkdir -m 755 /mnt2\n");
   1091 
   1092 	/* reset failure/success counters */
   1093 	memset(&tarstats, 0, sizeof(tarstats));
   1094 
   1095 	/* Find out which files to "get" if we get files. */
   1096 
   1097 	/* Accurately count selected sets */
   1098 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1099 		if (dist->name == NULL)
   1100 			continue;
   1101 		if (set_status[set] & SET_NO_EXTRACT)
   1102 			continue;
   1103 		if ((set_status[set] & (SET_VALID | SET_SELECTED))
   1104 		    == (SET_VALID | SET_SELECTED))
   1105 			tarstats.nselected++;
   1106 	}
   1107 
   1108 	status = SET_RETRY;
   1109 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1110 		if (dist->name == NULL)
   1111 			continue;
   1112 		if (set_status[set] != (SET_VALID | SET_SELECTED))
   1113 			continue;
   1114 
   1115 		/* save stats, in case we will retry */
   1116 		oldfound = tarstats.nfound;
   1117 		olderror = tarstats.nerror;
   1118 
   1119 		if (status != SET_OK) {
   1120 			/* This might force a redraw.... */
   1121 			clearok(curscr, 1);
   1122 			touchwin(stdscr);
   1123 			wrefresh(stdscr);
   1124 			/* Sort out the location of the set files */
   1125 			do {
   1126 				umount_mnt2();
   1127 				msg_fmt_display(MSG_distmedium, "%d%d%s",
   1128 				    tarstats.nselected,
   1129 				    tarstats.nsuccess + tarstats.nskipped,
   1130 				    dist->name);
   1131 				fetch_fn = NULL;
   1132 				process_menu(MENU_distmedium, &status);
   1133 			} while (status == SET_RETRY);
   1134 
   1135 			if (status == SET_SKIP) {
   1136 				set_status[set] |= SET_SKIPPED;
   1137 				tarstats.nskipped++;
   1138 				continue;
   1139 			}
   1140 			if (status == SET_SKIP_GROUP) {
   1141 				skip_set(dist, status);
   1142 				continue;
   1143 			}
   1144 			if (status != SET_OK) {
   1145 				hit_enter_to_continue(failure_msg, NULL);
   1146 				return 1;
   1147 			}
   1148 		}
   1149 
   1150 		if (set_status[set] & SET_NO_EXTRACT)
   1151 			continue;
   1152 
   1153 		/* Try to extract this set */
   1154 		status = extract_file(dist, update);
   1155 		if (status == SET_RETRY) {
   1156 			/* do this set again */
   1157 			dist--;
   1158 			/* and reset statistics to what we had before this
   1159 			 * set */
   1160 			tarstats.nfound = oldfound;
   1161 			tarstats.nerror = olderror;
   1162 		}
   1163 	}
   1164 
   1165 #ifdef MD_SET_EXTRACT_FINALIZE
   1166 	MD_SET_EXTRACT_FINALIZE(update);
   1167 #endif
   1168 
   1169 	if (tarstats.nerror == 0 && tarstats.nsuccess == tarstats.nselected) {
   1170 		msg_display(MSG_endtarok);
   1171 		/* Give user a chance to see the success message */
   1172 		sleep(1);
   1173 	} else {
   1174 		/* We encountered errors. Let the user know. */
   1175 		msg_fmt_display(MSG_endtar, "%d%d%d%d%d%d",
   1176 		    tarstats.nselected, tarstats.nnotfound, tarstats.nskipped,
   1177 		    tarstats.nfound, tarstats.nsuccess, tarstats.nerror);
   1178 		hit_enter_to_continue(NULL, NULL);
   1179 	}
   1180 
   1181 	/*
   1182 	 * postinstall needs to be run after extracting all sets, because
   1183 	 * otherwise /var/db/obsolete will only have current information
   1184 	 * from the base, comp, and etc sets.
   1185 	 */
   1186 	if (update && (set_status[SET_ETC] & SET_INSTALLED)) {
   1187 		int oldsendmail;
   1188 		oldsendmail = run_program(RUN_DISPLAY | RUN_CHROOT |
   1189 					  RUN_ERROR_OK | RUN_PROGRESS,
   1190 					  "/usr/sbin/postinstall -s /.sysinst -d / check mailerconf");
   1191 		if (oldsendmail == 1) {
   1192 			msg_display(MSG_oldsendmail);
   1193 			if (ask_yesno(NULL)) {
   1194 				run_program(RUN_DISPLAY | RUN_CHROOT,
   1195 					    "/usr/sbin/postinstall -s /.sysinst -d / fix mailerconf");
   1196 			}
   1197 		}
   1198 		run_program(RUN_DISPLAY | RUN_CHROOT,
   1199 			"/usr/sbin/postinstall -s /.sysinst -d / fix");
   1200 
   1201 		/* Don't discard the system's old entropy if any */
   1202 		run_program(RUN_CHROOT | RUN_SILENT,
   1203 			    "/etc/rc.d/random_seed start");
   1204 	}
   1205 
   1206 	/* Configure the system */
   1207 	if (set_status[SET_BASE] & SET_INSTALLED)
   1208 		run_makedev();
   1209 
   1210 	if (!update) {
   1211 		struct stat sb1, sb2;
   1212 
   1213 		if (stat(target_expand("/"), &sb1) == 0
   1214 		    && stat(target_expand("/var"), &sb2) == 0
   1215 		    && sb1.st_dev != sb2.st_dev) {
   1216 			add_rc_conf("random_file=/etc/entropy-file\n");
   1217 			if (target_file_exists_p("/boot.cfg")) {
   1218 				run_program(RUN_CHROOT|RUN_FATAL,
   1219 					    "sh -c 'sed -e s./var/db/./etc/. "
   1220 					    "< /boot.cfg "
   1221 					    "> /tmp/boot.cfg.tmp'");
   1222 				mv_within_target_or_die("/tmp/boot.cfg.tmp",
   1223 							"/boot.cfg");
   1224 
   1225 			}
   1226 		}
   1227 
   1228 #ifdef MD_BOOT_CFG_FINALIZE
   1229 		if (target_file_exists_p("/boot.cfg")) {
   1230 			MD_BOOT_CFG_FINALIZE("/boot.cfg");
   1231 		}
   1232 #endif
   1233 
   1234 		/* Save keyboard type */
   1235 		save_kb_encoding();
   1236 
   1237 		/* Other configuration. */
   1238 		mnt_net_config();
   1239 	}
   1240 
   1241 	/* Mounted dist dir? */
   1242 	umount_mnt2();
   1243 
   1244 	/* Save entropy -- on some systems it's ~all we'll ever get */
   1245 	run_program(RUN_DISPLAY | RUN_CHROOT | RUN_FATAL | RUN_PROGRESS,
   1246 		    "/etc/rc.d/random_seed stop");
   1247 	/* Install/Upgrade complete ... reboot or exit to script */
   1248 	hit_enter_to_continue(success_msg, NULL);
   1249 	return 0;
   1250 }
   1251 
   1252 void
   1253 umount_mnt2(void)
   1254 {
   1255 	if (!mnt2_mounted)
   1256 		return;
   1257 	run_program(RUN_SILENT, "/sbin/umount /mnt2");
   1258 	mnt2_mounted = 0;
   1259 }
   1260 
   1261 
   1262 /*
   1263  * Do a quick sanity check that  the target can reboot.
   1264  * return 1 if everything OK, 0 if there is a problem.
   1265  * Uses a table of files we expect to find after a base install/upgrade.
   1266  */
   1267 
   1268 /* test flag and pathname to check for after unpacking. */
   1269 struct check_table { unsigned int mode; const char *path;} checks[] = {
   1270   { S_IFREG, "/netbsd" },
   1271   { S_IFDIR, "/etc" },
   1272   { S_IFREG, "/etc/fstab" },
   1273   { S_IFREG, "/sbin/init" },
   1274   { S_IFREG, "/bin/sh" },
   1275   { S_IFREG, "/etc/rc" },
   1276   { S_IFREG, "/etc/rc.subr" },
   1277   { S_IFREG, "/etc/rc.conf" },
   1278   { S_IFDIR, "/dev" },
   1279   { S_IFCHR, "/dev/console" },
   1280 /* XXX check for rootdev in target /dev? */
   1281   { S_IFREG, "/sbin/fsck" },
   1282   { S_IFREG, "/sbin/fsck_ffs" },
   1283   { S_IFREG, "/sbin/mount" },
   1284   { S_IFREG, "/sbin/mount_ffs" },
   1285   { S_IFREG, "/sbin/mount_nfs" },
   1286 #if defined(DEBUG) || defined(DEBUG_CHECK)
   1287   { S_IFREG, "/foo/bar" },		/* bad entry to exercise warning */
   1288 #endif
   1289   { 0, 0 }
   1290 
   1291 };
   1292 
   1293 /*
   1294  * Check target for a single file.
   1295  */
   1296 static int
   1297 check_for(unsigned int mode, const char *pathname)
   1298 {
   1299 	int found;
   1300 
   1301 	found = (target_test(mode, pathname) == 0);
   1302 	if (found == 0)
   1303 		msg_fmt_display(MSG_rootmissing, "%s", pathname);
   1304 	return found;
   1305 }
   1306 
   1307 /*
   1308  * Check that all the files in check_table are present in the
   1309  * target root. Warn if not found.
   1310  */
   1311 int
   1312 sanity_check(void)
   1313 {
   1314 	int target_ok = 1;
   1315 	struct check_table *p;
   1316 
   1317 	for (p = checks; p->path; p++) {
   1318 		target_ok = target_ok && check_for(p->mode, p->path);
   1319 	}
   1320 	if (target_ok)
   1321 		return 0;
   1322 
   1323 	/* Uh, oh. Something's missing. */
   1324 	hit_enter_to_continue(MSG_badroot, NULL);
   1325 	return 1;
   1326 }
   1327 
   1328 /*
   1329  * Some globals to pass things back from callbacks
   1330  */
   1331 static char zoneinfo_dir[STRSIZE];
   1332 static int zonerootlen;
   1333 static char *tz_selected;	/* timezonename (relative to share/zoneinfo */
   1334 const char *tz_default;		/* UTC, or whatever /etc/localtime points to */
   1335 static char tz_env[STRSIZE];
   1336 static int save_cursel, save_topline;
   1337 
   1338 /*
   1339  * Callback from timezone menu
   1340  */
   1341 static int
   1342 set_tz_select(menudesc *m, void *arg)
   1343 {
   1344 	time_t t;
   1345 	char *new;
   1346 	struct tm *tm;
   1347 
   1348 	if (m && strcmp(tz_selected, m->opts[m->cursel].opt_name) != 0) {
   1349 		/* Change the displayed timezone */
   1350 		new = strdup(m->opts[m->cursel].opt_name);
   1351 		if (new == NULL)
   1352 			return 0;
   1353 		free(tz_selected);
   1354 		tz_selected = new;
   1355 		snprintf(tz_env, sizeof tz_env, "%.*s%s",
   1356 			 zonerootlen, zoneinfo_dir, tz_selected);
   1357 		setenv("TZ", tz_env, 1);
   1358 	}
   1359 	if (m)
   1360 		/* Warp curser to 'Exit' line on menu */
   1361 		m->cursel = -1;
   1362 
   1363 	/* Update displayed time */
   1364 	t = time(NULL);
   1365 	tm = localtime(&t);
   1366 	msg_fmt_display(MSG_choose_timezone, "%s%s%s%s",
   1367 		    tz_default, tz_selected, safectime(&t), tm ? tm->tm_zone :
   1368 		    "?");
   1369 	return 0;
   1370 }
   1371 
   1372 static int
   1373 set_tz_back(menudesc *m, void *arg)
   1374 {
   1375 
   1376 	zoneinfo_dir[zonerootlen] = 0;
   1377 	m->cursel = save_cursel;
   1378 	m->topline = save_topline;
   1379 	return 0;
   1380 }
   1381 
   1382 static int
   1383 set_tz_dir(menudesc *m, void *arg)
   1384 {
   1385 
   1386 	strlcpy(zoneinfo_dir + zonerootlen, m->opts[m->cursel].opt_name,
   1387 		sizeof zoneinfo_dir - zonerootlen);
   1388 	save_cursel = m->cursel;
   1389 	save_topline = m->topline;
   1390 	m->cursel = 0;
   1391 	m->topline = 0;
   1392 	return 0;
   1393 }
   1394 
   1395 /*
   1396  * Alarm-handler to update example-display
   1397  */
   1398 static void
   1399 /*ARGSUSED*/
   1400 timezone_sig(int sig)
   1401 {
   1402 
   1403 	set_tz_select(NULL, NULL);
   1404 	alarm(60);
   1405 }
   1406 
   1407 static int
   1408 tz_sort(const void *a, const void *b)
   1409 {
   1410 	return strcmp(((const menu_ent *)a)->opt_name, ((const menu_ent *)b)->opt_name);
   1411 }
   1412 
   1413 static void
   1414 tzm_set_names(menudesc *m, void *arg)
   1415 {
   1416 	DIR *dir;
   1417 	struct dirent *dp;
   1418 	static int nfiles;
   1419 	static int maxfiles = 32;
   1420 	static menu_ent *tz_menu;
   1421 	static char **tz_names;
   1422 	void *p;
   1423 	int maxfname;
   1424 	char *fp;
   1425 	struct stat sb;
   1426 
   1427 	if (tz_menu == NULL)
   1428 		tz_menu = calloc(maxfiles, sizeof *tz_menu);
   1429 	if (tz_names == NULL)
   1430 		tz_names = malloc(maxfiles * sizeof *tz_names);
   1431 	if (tz_menu == NULL || tz_names == NULL)
   1432 		return;	/* error - skip timezone setting */
   1433 	while (nfiles > 0)
   1434 		free(tz_names[--nfiles]);
   1435 
   1436 	dir = opendir(zoneinfo_dir);
   1437 	fp = strchr(zoneinfo_dir, 0);
   1438 	if (fp != zoneinfo_dir + zonerootlen) {
   1439 		tz_names[0] = 0;
   1440 		tz_menu[0].opt_name = msg_string(MSG_tz_back);
   1441 		tz_menu[0].opt_action = set_tz_back;
   1442 		nfiles = 1;
   1443 	}
   1444 	maxfname = zoneinfo_dir + sizeof zoneinfo_dir - fp - 1;
   1445 	if (dir != NULL) {
   1446 		while ((dp = readdir(dir)) != NULL) {
   1447 			if (dp->d_namlen > maxfname || dp->d_name[0] == '.')
   1448 				continue;
   1449 			strlcpy(fp, dp->d_name, maxfname);
   1450 			if (stat(zoneinfo_dir, &sb) == -1)
   1451 				continue;
   1452 			if (nfiles >= maxfiles) {
   1453 				p = realloc(tz_menu,
   1454 				    2 * maxfiles * sizeof *tz_menu);
   1455 				if (p == NULL)
   1456 					break;
   1457 				tz_menu = p;
   1458 				memset(tz_menu + maxfiles, 0,
   1459 				    maxfiles * sizeof *tz_menu);
   1460 				p = realloc(tz_names,
   1461 				    2 * maxfiles * sizeof *tz_names);
   1462 				if (p == NULL)
   1463 					break;
   1464 				tz_names = p;
   1465 				memset(tz_names + maxfiles, 0,
   1466 				    maxfiles * sizeof *tz_names);
   1467 				maxfiles *= 2;
   1468 			}
   1469 			if (S_ISREG(sb.st_mode))
   1470 				tz_menu[nfiles].opt_action = set_tz_select;
   1471 			else if (S_ISDIR(sb.st_mode)) {
   1472 				tz_menu[nfiles].opt_action = set_tz_dir;
   1473 				strlcat(fp, "/",
   1474 				    sizeof(zoneinfo_dir) - (fp - zoneinfo_dir));
   1475 			} else
   1476 				continue;
   1477 			tz_names[nfiles] = strdup(zoneinfo_dir + zonerootlen);
   1478 			tz_menu[nfiles].opt_name = tz_names[nfiles];
   1479 			nfiles++;
   1480 		}
   1481 		closedir(dir);
   1482 	}
   1483 	*fp = 0;
   1484 
   1485 	m->opts = tz_menu;
   1486 	m->numopts = nfiles;
   1487 	qsort(tz_menu, nfiles, sizeof *tz_menu, tz_sort);
   1488 }
   1489 
   1490 void
   1491 get_tz_default(void)
   1492 {
   1493 	char localtime_link[STRSIZE];
   1494 	static char localtime_target[STRSIZE];
   1495 	int rc;
   1496 
   1497 	strlcpy(localtime_link, target_expand("/etc/localtime"),
   1498 	    sizeof localtime_link);
   1499 
   1500 	/* Add sanity check that /mnt/usr/share/zoneinfo contains
   1501 	 * something useful
   1502 	 */
   1503 
   1504 	rc = readlink(localtime_link, localtime_target,
   1505 		      sizeof(localtime_target) - 1);
   1506 	if (rc < 0) {
   1507 		/* error, default to UTC */
   1508 		tz_default = "UTC";
   1509 	} else {
   1510 		localtime_target[rc] = '\0';
   1511 		tz_default = strchr(strstr(localtime_target, "zoneinfo"), '/') + 1;
   1512 	}
   1513 }
   1514 
   1515 /*
   1516  * Choose from the files in usr/share/zoneinfo and set etc/localtime
   1517  */
   1518 int
   1519 set_timezone(void)
   1520 {
   1521 	char localtime_link[STRSIZE];
   1522 	char localtime_target[STRSIZE];
   1523 	time_t t;
   1524 	struct tm *tm;
   1525 	int menu_no;
   1526 
   1527 	strlcpy(zoneinfo_dir, target_expand("/usr/share/zoneinfo/"),
   1528 	    sizeof zoneinfo_dir - 1);
   1529 	zonerootlen = strlen(zoneinfo_dir);
   1530 
   1531 	get_tz_default();
   1532 
   1533 	tz_selected = strdup(tz_default);
   1534 	snprintf(tz_env, sizeof(tz_env), "%s%s", zoneinfo_dir, tz_selected);
   1535 	setenv("TZ", tz_env, 1);
   1536 	t = time(NULL);
   1537 	tm = localtime(&t);
   1538 	msg_fmt_display(MSG_choose_timezone, "%s%s%s%s",
   1539 	    tz_default, tz_selected, safectime(&t), tm ? tm->tm_zone : "?");
   1540 
   1541 	signal(SIGALRM, timezone_sig);
   1542 	alarm(60);
   1543 
   1544 	menu_no = new_menu(NULL, NULL, 14, 23, 9,
   1545 			   12, 32, MC_ALWAYS_SCROLL | MC_NOSHORTCUT,
   1546 			   tzm_set_names, NULL, NULL,
   1547 			   "\nPlease consult the install documents.",
   1548 			   MSG_exit_menu_generic);
   1549 	if (menu_no < 0)
   1550 		goto done;	/* error - skip timezone setting */
   1551 
   1552 	process_menu(menu_no, NULL);
   1553 
   1554 	free_menu(menu_no);
   1555 
   1556 	signal(SIGALRM, SIG_IGN);
   1557 
   1558 	snprintf(localtime_target, sizeof(localtime_target),
   1559 		 "/usr/share/zoneinfo/%s", tz_selected);
   1560 	strlcpy(localtime_link, target_expand("/etc/localtime"),
   1561 	    sizeof localtime_link);
   1562 	unlink(localtime_link);
   1563 	symlink(localtime_target, localtime_link);
   1564 
   1565 done:
   1566 	return 1;
   1567 }
   1568 
   1569 void
   1570 scripting_vfprintf(FILE *f, const char *fmt, va_list ap)
   1571 {
   1572 	va_list ap2;
   1573 
   1574 	va_copy(ap2, ap);
   1575 	if (f)
   1576 		(void)vfprintf(f, fmt, ap);
   1577 	if (script)
   1578 		(void)vfprintf(script, fmt, ap2);
   1579 }
   1580 
   1581 void
   1582 scripting_fprintf(FILE *f, const char *fmt, ...)
   1583 {
   1584 	va_list ap;
   1585 
   1586 	va_start(ap, fmt);
   1587 	scripting_vfprintf(f, fmt, ap);
   1588 	va_end(ap);
   1589 }
   1590 
   1591 void
   1592 add_rc_conf(const char *fmt, ...)
   1593 {
   1594 	FILE *f;
   1595 	va_list ap;
   1596 
   1597 	va_start(ap, fmt);
   1598 	f = target_fopen("/etc/rc.conf", "a");
   1599 	if (f != 0) {
   1600 		scripting_fprintf(NULL, "cat <<EOF >>%s/etc/rc.conf\n",
   1601 		    target_prefix());
   1602 		scripting_vfprintf(f, fmt, ap);
   1603 		fclose(f);
   1604 		scripting_fprintf(NULL, "EOF\n");
   1605 	}
   1606 	va_end(ap);
   1607 }
   1608 
   1609 int
   1610 del_rc_conf(const char *value)
   1611 {
   1612 	FILE *fp, *nfp;
   1613 	char buf[4096]; /* Ridiculously high, but should be enough in any way */
   1614 	char *rcconf, *tempname = NULL, *bakname = NULL;
   1615 	char *cp;
   1616 	int done = 0;
   1617 	int fd;
   1618 	int retval = 0;
   1619 
   1620 	/* The paths might seem strange, but using /tmp would require copy instead
   1621 	 * of rename operations. */
   1622 	if (asprintf(&rcconf, "%s", target_expand("/etc/rc.conf")) < 0
   1623 			|| asprintf(&tempname, "%s", target_expand("/etc/rc.conf.tmp.XXXXXX")) < 0
   1624 			|| asprintf(&bakname, "%s", target_expand("/etc/rc.conf.bak.XXXXXX")) < 0) {
   1625 		if (rcconf)
   1626 			free(rcconf);
   1627 		if (tempname)
   1628 			free(tempname);
   1629 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   1630 		hit_enter_to_continue(NULL, NULL);
   1631 		return -1;
   1632 	}
   1633 
   1634 	if ((fd = mkstemp(bakname)) < 0) {
   1635 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   1636 		hit_enter_to_continue(NULL, NULL);
   1637 		return -1;
   1638 	}
   1639 	close(fd);
   1640 
   1641 	if (!(fp = fopen(rcconf, "r+")) || (fd = mkstemp(tempname)) < 0) {
   1642 		if (fp)
   1643 			fclose(fp);
   1644 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   1645 		hit_enter_to_continue(NULL, NULL);
   1646 		return -1;
   1647 	}
   1648 
   1649 	nfp = fdopen(fd, "w");
   1650 	if (!nfp) {
   1651 		fclose(fp);
   1652 		close(fd);
   1653 		msg_fmt_display(MSG_rcconf_delete_failed, "%s", value);
   1654 		hit_enter_to_continue(NULL, NULL);
   1655 		return -1;
   1656 	}
   1657 
   1658 	while (fgets(buf, sizeof buf, fp) != NULL) {
   1659 
   1660 		cp = buf + strspn(buf, " \t"); /* Skip initial spaces */
   1661 		if (strncmp(cp, value, strlen(value)) == 0) {
   1662 			cp += strlen(value);
   1663 			if (*cp != '=')
   1664 				scripting_fprintf(nfp, "%s", buf);
   1665 			else
   1666 				done = 1;
   1667 		} else {
   1668 			scripting_fprintf(nfp, "%s", buf);
   1669 		}
   1670 	}
   1671 	fclose(fp);
   1672 	fclose(nfp);
   1673 
   1674 	if (done) {
   1675 		if (rename(rcconf, bakname)) {
   1676 			msg_display(MSG_rcconf_backup_failed);
   1677 			if (!ask_noyes(NULL)) {
   1678 				retval = -1;
   1679 				goto done;
   1680 			}
   1681 		}
   1682 
   1683 		if (rename(tempname, rcconf)) {
   1684 			if (rename(bakname, rcconf)) {
   1685 				hit_enter_to_continue(MSG_rcconf_restore_failed,
   1686 				    NULL);
   1687 			} else {
   1688 				hit_enter_to_continue(MSG_rcconf_delete_failed,
   1689 				    NULL);
   1690 			}
   1691 		} else {
   1692 			(void)unlink(bakname);
   1693 		}
   1694 	}
   1695 
   1696 done:
   1697 	(void)unlink(tempname);
   1698 	free(rcconf);
   1699 	free(tempname);
   1700 	free(bakname);
   1701 	return retval;
   1702 }
   1703 
   1704 void
   1705 add_sysctl_conf(const char *fmt, ...)
   1706 {
   1707 	FILE *f;
   1708 	va_list ap;
   1709 
   1710 	va_start(ap, fmt);
   1711 	f = target_fopen("/etc/sysctl.conf", "a");
   1712 	if (f != 0) {
   1713 		scripting_fprintf(NULL, "cat <<EOF >>%s/etc/sysctl.conf\n",
   1714 		    target_prefix());
   1715 		scripting_vfprintf(f, fmt, ap);
   1716 		fclose(f);
   1717 		scripting_fprintf(NULL, "EOF\n");
   1718 	}
   1719 	va_end(ap);
   1720 }
   1721 
   1722 void
   1723 enable_rc_conf(void)
   1724 {
   1725 
   1726 	replace("/etc/rc.conf", "s/^rc_configured=NO/rc_configured=YES/");
   1727 }
   1728 
   1729 int
   1730 check_lfs_progs(void)
   1731 {
   1732 
   1733 #ifndef NO_LFS
   1734 	return binary_available("fsck_lfs") && binary_available("mount_lfs")
   1735 	    && binary_available("newfs_lfs");
   1736 #else
   1737 	return 0;
   1738 #endif
   1739 }
   1740 
   1741 int
   1742 set_is_source(const char *set_name) {
   1743 	int len = strlen(set_name);
   1744 	return len >= 3 && memcmp(set_name + len - 3, "src", 3) == 0;
   1745 }
   1746 
   1747 const char *
   1748 set_dir_for_set(const char *set_name) {
   1749 	if (strcmp(set_name, "pkgsrc") == 0)
   1750 		return pkgsrc_dir;
   1751 	return set_is_source(set_name) ? set_dir_src : set_dir_bin;
   1752 }
   1753 
   1754 const char *
   1755 ext_dir_for_set(const char *set_name) {
   1756 	if (strcmp(set_name, "pkgsrc") == 0)
   1757 		return ext_dir_pkgsrc;
   1758 	return set_is_source(set_name) ? ext_dir_src : ext_dir_bin;
   1759 }
   1760 
   1761 void
   1762 do_coloring(unsigned int fg, unsigned int bg) {
   1763 	if (bg > COLOR_WHITE)
   1764 		bg = COLOR_BLUE;
   1765 	if (fg > COLOR_WHITE)
   1766 		fg = COLOR_WHITE;
   1767 	if (fg != bg && has_colors()) {
   1768 		init_pair(1, fg, bg);
   1769 		wbkgd(stdscr, COLOR_PAIR(1));
   1770 		wbkgd(mainwin, COLOR_PAIR(1));
   1771 		wattrset(stdscr, COLOR_PAIR(1));
   1772 		wattrset(mainwin, COLOR_PAIR(1));
   1773 	}
   1774 	/* redraw screen */
   1775 	touchwin(stdscr);
   1776 	touchwin(mainwin);
   1777 	wrefresh(stdscr);
   1778 	wrefresh(mainwin);
   1779 	return;
   1780 }
   1781 
   1782 int
   1783 set_menu_select(menudesc *m, void *arg)
   1784 {
   1785 	*(int *)arg = m->cursel;
   1786 	return 1;
   1787 }
   1788 
   1789 /*
   1790  * check wether a binary is available somewhere in PATH,
   1791  * return 1 if found, 0 if not.
   1792  */
   1793 static int
   1794 binary_available(const char *prog)
   1795 {
   1796         char *p, tmp[MAXPATHLEN], *path = getenv("PATH"), *opath;
   1797 
   1798         if (path == NULL)
   1799                 return access(prog, X_OK) == 0;
   1800         path = strdup(path);
   1801         if (path == NULL)
   1802                 return 0;
   1803 
   1804 	opath = path;
   1805 
   1806         while ((p = strsep(&path, ":")) != NULL) {
   1807                 if (strlcpy(tmp, p, MAXPATHLEN) >= MAXPATHLEN)
   1808                         continue;
   1809                 if (strlcat(tmp, "/", MAXPATHLEN) >= MAXPATHLEN)
   1810                         continue;
   1811                 if (strlcat(tmp, prog, MAXPATHLEN) >= MAXPATHLEN)
   1812                         continue;
   1813                 if (access(tmp, X_OK) == 0) {
   1814                         free(opath);
   1815                         return 1;
   1816                 }
   1817         }
   1818         free(opath);
   1819         return 0;
   1820 }
   1821 
   1822 const char *
   1823 safectime(time_t *t)
   1824 {
   1825 	const char *s = ctime(t);
   1826 	if (s != NULL)
   1827 		return s;
   1828 
   1829 	// Debugging.
   1830 	fprintf(stderr, "Can't convert to localtime 0x%jx (%s)\n",
   1831 	    (intmax_t)*t, strerror(errno));
   1832 	      /*123456789012345678901234*/
   1833 	return "preposterous clock time\n";
   1834 }
   1835 
   1836 int
   1837 ask_yesno(const char* msgtxt)
   1838 {
   1839 	arg_rv p;
   1840 
   1841 	p.arg = __UNCONST(msgtxt);
   1842 	p.rv = -1;
   1843 
   1844 	process_menu(MENU_yesno, &p);
   1845 	return p.rv;
   1846 }
   1847 
   1848 int
   1849 ask_noyes(const char *msgtxt)
   1850 {
   1851 	arg_rv p;
   1852 
   1853 	p.arg = __UNCONST(msgtxt);
   1854 	p.rv = -1;
   1855 
   1856 	process_menu(MENU_noyes, &p);
   1857 	return p.rv;
   1858 }
   1859 
   1860 int
   1861 ask_reedit(const struct disk_partitions *parts)
   1862 {
   1863 	const char *args[2];
   1864 	arg_rep_int arg;
   1865 
   1866 	args[0] = msg_string(parts->pscheme->name);
   1867 	args[1] = msg_string(parts->pscheme->short_name);
   1868 	arg.args.argv = args;
   1869 	arg.args.argc = 2;
   1870 	arg.rv = 0;
   1871 	process_menu(MENU_reedit, &arg);
   1872 
   1873 	return arg.rv;
   1874 }
   1875 
   1876 bool
   1877 use_tgz_for_set(const char *set_name)
   1878 {
   1879 	const struct distinfo *dist;
   1880 
   1881 	for (dist = dist_list; dist->set != SET_LAST; dist++) {
   1882 		if (dist->name == NULL)
   1883 			continue;
   1884 		if (strcmp(set_name, dist->name) == 0)
   1885 			return dist->force_tgz;
   1886 	}
   1887 
   1888 	return true;
   1889 }
   1890 
   1891 /* Return the postfix used for a given set */
   1892 const char *
   1893 set_postfix(const char *set_name)
   1894 {
   1895 	return use_tgz_for_set(set_name) ? dist_tgz_postfix : dist_postfix;
   1896 }
   1897 
   1898 /*
   1899  * Replace positional arguments (encoded as $0 .. $N) in the string
   1900  * passed by the contents of the passed argument array.
   1901  * Caller must free() the result string.
   1902  */
   1903 char*
   1904 str_arg_subst(const char *src, size_t argc, const char **argv)
   1905 {
   1906 	const char *p, *last;
   1907 	char *out, *t;
   1908 	size_t len;
   1909 
   1910 	len = strlen(src);
   1911 	for (p = strchr(src, '$'); p; p = strchr(p+1, '$')) {
   1912 		char *endp = NULL;
   1913 		size_t n;
   1914 		int e;
   1915 
   1916 		/* $ followed by a correct numeric position? */
   1917 		n = strtou(p+1, &endp, 10, 0, INT_MAX, &e);
   1918 		if ((e == 0 || e == ENOTSUP) && n < argc) {
   1919 			len += strlen(argv[n]);
   1920 			len -= endp-p;
   1921 			p = endp-1;
   1922 		}
   1923 	}
   1924 
   1925 	out = malloc(len+1);
   1926 	if (out == NULL)
   1927 		return NULL;
   1928 
   1929 	t = out;
   1930 	for (last = src, p = strchr(src, '$'); p; p = strchr(p+1, '$')) {
   1931 		char *endp = NULL;
   1932 		size_t n;
   1933 		int e;
   1934 
   1935 		/* $ followed by a correct numeric position? */
   1936 		n = strtou(p+1, &endp, 10, 0, INT_MAX, &e);
   1937 		if ((e == 0 || e == ENOTSUP) && n < argc) {
   1938 			size_t l = p-last;
   1939 			memcpy(t, last, l);
   1940 			t += l;
   1941 			strcpy(t, argv[n]);
   1942 			t += strlen(argv[n]);
   1943 			last = endp;
   1944 		}
   1945 	}
   1946 	if (*last) {
   1947 		strcpy(t, last);
   1948 		t += strlen(last);
   1949 	} else {
   1950 		*t = 0;
   1951 	}
   1952 	assert((size_t)(t-out) == len);
   1953 
   1954 	return out;
   1955 }
   1956 
   1957 /*
   1958  * Does this string have any positional args that need expanding?
   1959  */
   1960 bool
   1961 needs_expanding(const char *src, size_t argc)
   1962 {
   1963 	const char *p;
   1964 
   1965 	for (p = strchr(src, '$'); p; p = strchr(p+1, '$')) {
   1966 		char *endp = NULL;
   1967 		size_t n;
   1968 		int e;
   1969 
   1970 		/* $ followed by a correct numeric position? */
   1971 		n = strtou(p+1, &endp, 10, 0, INT_MAX, &e);
   1972 		if ((e == 0 || e == ENOTSUP) && n < argc)
   1973 			return true;
   1974 	}
   1975 	return false;
   1976 }
   1977 
   1978 /*
   1979  * Replace positional arguments (encoded as $0 .. $N) in the
   1980  * message by the strings passed as ... and call outfunc
   1981  * with the result.
   1982  */
   1983 static void
   1984 msg_display_subst_internal(void (*outfunc)(msg),
   1985     const char *master, size_t argc, va_list ap)
   1986 {
   1987 	const char **args, **arg;
   1988 	char *out;
   1989 
   1990 	args = calloc(argc, sizeof(*args));
   1991 	if (args == NULL)
   1992 		return;
   1993 
   1994 	arg = args;
   1995 	for (size_t i = 0; i < argc; i++)
   1996 		*arg++ = va_arg(ap, const char*);
   1997 
   1998 	out = str_arg_subst(msg_string(master), argc, args);
   1999 	if (out != NULL) {
   2000 		outfunc(out);
   2001 		free(out);
   2002 	}
   2003 	free(args);
   2004 }
   2005 
   2006 /*
   2007  * Replace positional arguments (encoded as $0 .. $N) in the
   2008  * message by the strings passed as ...
   2009  */
   2010 void
   2011 msg_display_subst(const char *master, size_t argc, ...)
   2012 {
   2013 	va_list ap;
   2014 
   2015 	va_start(ap, argc);
   2016 	msg_display_subst_internal(msg_display, master, argc, ap);
   2017 	va_end(ap);
   2018 }
   2019 
   2020 /*
   2021  * Same as above, but add to message instead of starting a new one
   2022  */
   2023 void
   2024 msg_display_add_subst(const char *master, size_t argc, ...)
   2025 {
   2026 	va_list ap;
   2027 
   2028 	va_start(ap, argc);
   2029 	msg_display_subst_internal(msg_display_add, master, argc, ap);
   2030 	va_end(ap);
   2031 }
   2032 
   2033 /* initialize have_* variables */
   2034 void
   2035 check_available_binaries()
   2036 {
   2037 	static int did_test = false;
   2038 
   2039 	if (did_test) return;
   2040 	did_test = 1;
   2041 
   2042 	have_raid = binary_available("raidctl");
   2043 	have_vnd = binary_available("vndconfig");
   2044 	have_cgd = binary_available("cgdconfig");
   2045 	have_lvm = binary_available("lvm");
   2046 	have_gpt = binary_available("gpt");
   2047 	have_dk = binary_available("dkctl");
   2048 }
   2049 
   2050 /*
   2051  * Wait for enter and immediately clear the screen after user response
   2052  * (in case some longer action follows, so the user has instant feedback)
   2053  */
   2054 void
   2055 hit_enter_to_continue(const char *prompt, const char *title)
   2056 {
   2057 	if (prompt != NULL)
   2058 		msg_display(prompt);
   2059         process_menu(MENU_ok, __UNCONST(title));
   2060 	msg_clear();
   2061 	wrefresh(mainwin);
   2062 }
   2063 
   2064 /*
   2065  * On auto pilot:
   2066  * convert an existing set of partitions ot a list of part_usage_info
   2067  * so that we "want" exactly what is there already.
   2068  */
   2069 static bool
   2070 usage_info_list_from_parts(struct part_usage_info **list, size_t *count,
   2071     struct disk_partitions *parts)
   2072 {
   2073 	struct disk_part_info info;
   2074 	part_id pno;
   2075 	size_t no, num;
   2076 
   2077 	num = 0;
   2078 	for (pno = 0; pno < parts->num_part; pno++) {
   2079 		if (!parts->pscheme->get_part_info(parts, pno, &info))
   2080 			continue;
   2081 		num++;
   2082 	}
   2083 
   2084 	*list = calloc(num, sizeof(**list));
   2085 	if (*list == NULL)
   2086 		return false;
   2087 
   2088 	*count = num;
   2089 	for (no = pno = 0; pno < parts->num_part && no < num; pno++) {
   2090 		if (!parts->pscheme->get_part_info(parts, pno, &info))
   2091 			continue;
   2092 		(*list)[no].size = info.size;
   2093 		if (info.last_mounted != NULL && *info.last_mounted != 0) {
   2094 			strlcpy((*list)[no].mount, info.last_mounted,
   2095 			    sizeof((*list)[no].mount));
   2096 			(*list)[no].instflags |= PUIINST_MOUNT;
   2097 		}
   2098 		(*list)[no].parts = parts;
   2099 		(*list)[no].cur_part_id = pno;
   2100 		(*list)[no].cur_start = info.start;
   2101 		(*list)[no].cur_flags = info.flags;
   2102 		(*list)[no].type = info.nat_type->generic_ptype;
   2103 		if ((*list)[no].type == PT_swap) {
   2104 			(*list)[no].fs_type = FS_SWAP;
   2105 			(*list)[no].fs_version = 0;
   2106 		} else {
   2107 			(*list)[no].fs_type = info.fs_type;
   2108 			(*list)[no].fs_version = info.fs_sub_type;
   2109 		}
   2110 		no++;
   2111 	}
   2112 	return true;
   2113 }
   2114 
   2115 bool
   2116 usage_set_from_parts(struct partition_usage_set *wanted,
   2117     struct disk_partitions *parts)
   2118 {
   2119 	memset(wanted, 0, sizeof(*wanted));
   2120 	wanted->parts = parts;
   2121 
   2122 	return usage_info_list_from_parts(&wanted->infos, &wanted->num, parts);
   2123 }
   2124 
   2125 struct disk_partitions *
   2126 get_inner_parts(struct disk_partitions *parts)
   2127 {
   2128 	daddr_t start, size;
   2129 	part_id pno;
   2130 	struct disk_part_info info;
   2131 
   2132 	if (parts->pscheme->secondary_scheme == NULL)
   2133 		return NULL;
   2134 
   2135 	start = -1;
   2136 	size = -1;
   2137 	if (parts->pscheme->guess_install_target == NULL ||
   2138 	    !parts->pscheme->guess_install_target(parts, &start, &size)) {
   2139 		for (pno = 0; pno < parts->num_part; pno++) {
   2140 			if (!parts->pscheme->get_part_info(parts, pno, &info))
   2141 				continue;
   2142 			if (!(info.flags & PTI_SEC_CONTAINER))
   2143 				continue;
   2144 			start = info.start;
   2145 			size = info.size;
   2146 		}
   2147 	}
   2148 
   2149 	if (size > 0)
   2150 		return parts->pscheme->secondary_partitions(parts, start,
   2151 		    false);
   2152 
   2153 	return NULL;
   2154 }
   2155 
   2156 bool
   2157 install_desc_from_parts(struct install_partition_desc *install,
   2158     struct disk_partitions *parts)
   2159 {
   2160 	struct disk_partitions *inner_parts;
   2161 
   2162 	memset(install, 0, sizeof(*install));
   2163 	inner_parts = get_inner_parts(parts);
   2164 	if (inner_parts != NULL)
   2165 		parts = inner_parts;
   2166 
   2167 	return usage_info_list_from_parts(&install->infos, &install->num,
   2168 	    parts);
   2169 }
   2170 
   2171 void
   2172 free_usage_set(struct partition_usage_set *wanted)
   2173 {
   2174 	/* XXX - free parts? free clone src? */
   2175 	free(wanted->menu_opts);
   2176 	free(wanted->infos);
   2177 }
   2178 
   2179 void
   2180 free_install_desc(struct install_partition_desc *install)
   2181 {
   2182 #ifndef NO_CLONES
   2183 	size_t i, j;
   2184 
   2185 	for (i = 0; i < install->num; i++) {
   2186 		struct selected_partitions *src = install->infos[i].clone_src;
   2187 		if (!(install->infos[i].flags & PUIFLG_CLONE_PARTS) ||
   2188 		    src == NULL)
   2189 			continue;
   2190 		free_selected_partitions(src);
   2191 		for (j = i+1; j < install->num; j++)
   2192 			if (install->infos[j].clone_src == src)
   2193 				install->infos[j].clone_src = NULL;
   2194 	}
   2195 #endif
   2196 	free(install->infos);
   2197 }
   2198 
   2199 #ifdef MD_MAY_SWAP_TO
   2200 bool
   2201 may_swap_if_not_sdmmc(const char *disk)
   2202 {
   2203 	int fd, res;
   2204 	prop_dictionary_t command_dict, args_dict, results_dict, data_dict;
   2205 	prop_string_t string;
   2206 	prop_number_t number;
   2207 	const char *parent = "";
   2208 
   2209 	fd = open(DRVCTLDEV, O_RDONLY, 0);
   2210 	if (fd == -1)
   2211 		return true;
   2212 
   2213 	command_dict = prop_dictionary_create();
   2214 	args_dict = prop_dictionary_create();
   2215 
   2216 	string = prop_string_create_cstring_nocopy("get-properties");
   2217 	prop_dictionary_set(command_dict, "drvctl-command", string);
   2218 	prop_object_release(string);
   2219 
   2220 	string = prop_string_create_cstring(disk);
   2221 	prop_dictionary_set(args_dict, "device-name", string);
   2222 	prop_object_release(string);
   2223 
   2224 	prop_dictionary_set(command_dict, "drvctl-arguments",
   2225 	    args_dict);
   2226 	prop_object_release(args_dict);
   2227 
   2228 	res = prop_dictionary_sendrecv_ioctl(command_dict, fd,
   2229 	    DRVCTLCOMMAND, &results_dict);
   2230 	prop_object_release(command_dict);
   2231 	close(fd);
   2232 	if (res)
   2233 		return true;
   2234 
   2235 	number = prop_dictionary_get(results_dict, "drvctl-error");
   2236 	if (prop_number_integer_value(number) == 0) {
   2237 		data_dict = prop_dictionary_get(results_dict,
   2238 		    "drvctl-result-data");
   2239 		if (data_dict != NULL) {
   2240 			string = prop_dictionary_get(data_dict,
   2241 			    "device-parent");
   2242 			if (string != NULL)
   2243 				parent = prop_string_cstring_nocopy(string);
   2244 		}
   2245 	}
   2246 
   2247 	prop_object_release(results_dict);
   2248 
   2249 	if (parent == NULL)
   2250 		return true;
   2251 
   2252 	return strncmp(parent, "sdmmc", 5) != 0;
   2253 }
   2254 #endif
   2255