Home | History | Annotate | Line # | Download | only in sysinst
util.c revision 1.14
      1 /*	$NetBSD: util.c,v 1.14 2018/11/07 21:20:23 martin Exp $	*/
      2 
      3 /*
      4  * Copyright 1997 Piermont Information Systems Inc.
      5  * All rights reserved.
      6  *
      7  * Written by Philip A. Nelson for Piermont Information Systems Inc.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. The name of Piermont Information Systems Inc. may not be used to endorse
     18  *    or promote products derived from this software without specific prior
     19  *    written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
     22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
     25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     31  * THE POSSIBILITY OF SUCH DAMAGE.
     32  *
     33  */
     34 
     35 /* util.c -- routines that don't really fit anywhere else... */
     36 
     37 #include <stdio.h>
     38 #include <stdarg.h>
     39 #include <string.h>
     40 #include <unistd.h>
     41 #include <sys/mount.h>
     42 #include <sys/disklabel.h>
     43 #include <sys/dkio.h>
     44 #include <sys/ioctl.h>
     45 #include <sys/types.h>
     46 #include <sys/param.h>
     47 #include <sys/sysctl.h>
     48 #include <sys/stat.h>
     49 #include <sys/statvfs.h>
     50 #include <isofs/cd9660/iso.h>
     51 #include <curses.h>
     52 #include <err.h>
     53 #include <errno.h>
     54 #include <dirent.h>
     55 #include <util.h>
     56 #include "defs.h"
     57 #include "md.h"
     58 #include "msg_defs.h"
     59 #include "menu_defs.h"
     60 
     61 #ifndef MD_SETS_SELECTED
     62 #define MD_SETS_SELECTED SET_KERNEL_1, SET_SYSTEM, SET_X11, SET_MD
     63 #endif
     64 #ifndef MD_SETS_SELECTED_MINIMAL
     65 #define MD_SETS_SELECTED_MINIMAL SET_KERNEL_1, SET_CORE
     66 #endif
     67 #ifndef MD_SETS_SELECTED_NOX
     68 #define MD_SETS_SELECTED_NOX SET_KERNEL_1, SET_SYSTEM, SET_MD
     69 #endif
     70 #ifndef MD_SETS_VALID
     71 #define MD_SETS_VALID SET_KERNEL, SET_SYSTEM, SET_X11, SET_MD, SET_SOURCE, SET_DEBUGGING
     72 #endif
     73 
     74 #define MAX_CD_DEVS	256	/* how many cd drives do we expect to attach */
     75 #define ISO_BLKSIZE	ISO_DEFAULT_BLOCK_SIZE
     76 
     77 static const char *msg_yes, *msg_no, *msg_all, *msg_some, *msg_none;
     78 static const char *msg_cur_distsets_row;
     79 static int select_menu_width;
     80 
     81 static uint8_t set_status[SET_GROUP_END];
     82 #define SET_VALID	0x01
     83 #define SET_SELECTED	0x02
     84 #define SET_SKIPPED	0x04
     85 #define SET_INSTALLED	0x08
     86 
     87 struct  tarstats {
     88 	int nselected;
     89 	int nfound;
     90 	int nnotfound;
     91 	int nerror;
     92 	int nsuccess;
     93 	int nskipped;
     94 } tarstats;
     95 
     96 distinfo dist_list[] = {
     97 #ifdef SET_KERNEL_1_NAME
     98 	{SET_KERNEL_1_NAME,	SET_KERNEL_1,		false, MSG_set_kernel_1, NULL},
     99 #endif
    100 #ifdef SET_KERNEL_2_NAME
    101 	{SET_KERNEL_2_NAME,	SET_KERNEL_2,		false, MSG_set_kernel_2, NULL},
    102 #endif
    103 #ifdef SET_KERNEL_3_NAME
    104 	{SET_KERNEL_3_NAME,	SET_KERNEL_3,		false, MSG_set_kernel_3, NULL},
    105 #endif
    106 #ifdef SET_KERNEL_4_NAME
    107 	{SET_KERNEL_4_NAME,	SET_KERNEL_4,		false, MSG_set_kernel_4, NULL},
    108 #endif
    109 #ifdef SET_KERNEL_5_NAME
    110 	{SET_KERNEL_5_NAME,	SET_KERNEL_5,		false, MSG_set_kernel_5, NULL},
    111 #endif
    112 #ifdef SET_KERNEL_6_NAME
    113 	{SET_KERNEL_6_NAME,	SET_KERNEL_6,		false, MSG_set_kernel_6, NULL},
    114 #endif
    115 #ifdef SET_KERNEL_7_NAME
    116 	{SET_KERNEL_7_NAME,	SET_KERNEL_7,		false, MSG_set_kernel_7, NULL},
    117 #endif
    118 #ifdef SET_KERNEL_8_NAME
    119 	{SET_KERNEL_8_NAME,	SET_KERNEL_8,		false, MSG_set_kernel_8, NULL},
    120 #endif
    121 #ifdef SET_KERNEL_9_NAME
    122 	{SET_KERNEL_9_NAME,	SET_KERNEL_9,		false, MSG_set_kernel_9, NULL},
    123 #endif
    124 
    125 	{"modules",		SET_MODULES,		false, MSG_set_modules, NULL},
    126 	{"base",		SET_BASE,		false, MSG_set_base, NULL},
    127 	{"etc",			SET_ETC,		false, MSG_set_system, NULL},
    128 	{"comp",		SET_COMPILER,		false, MSG_set_compiler, NULL},
    129 	{"games",		SET_GAMES,		false, MSG_set_games, NULL},
    130 	{"man",			SET_MAN_PAGES,		false, MSG_set_man_pages, NULL},
    131 	{"misc",		SET_MISC,		false, MSG_set_misc, NULL},
    132 	{"tests",		SET_TESTS,		false, MSG_set_tests, NULL},
    133 	{"text",		SET_TEXT_TOOLS,		false, MSG_set_text_tools, NULL},
    134 
    135 	{NULL,			SET_GROUP,		false, MSG_set_X11, NULL},
    136 	{"xbase",		SET_X11_BASE,		false, MSG_set_X11_base, NULL},
    137 	{"xcomp",		SET_X11_PROG,		false, MSG_set_X11_prog, NULL},
    138 	{"xetc",		SET_X11_ETC,		false, MSG_set_X11_etc, NULL},
    139 	{"xfont",		SET_X11_FONTS,		false, MSG_set_X11_fonts, NULL},
    140 	{"xserver",		SET_X11_SERVERS,	false, MSG_set_X11_servers, NULL},
    141 	{NULL,			SET_GROUP_END,		false, NULL, NULL},
    142 
    143 #ifdef SET_MD_1_NAME
    144 	{SET_MD_1_NAME,		SET_MD_1,		false, MSG_set_md_1, NULL},
    145 #endif
    146 #ifdef SET_MD_2_NAME
    147 	{SET_MD_2_NAME,		SET_MD_2,		false, MSG_set_md_2, NULL},
    148 #endif
    149 #ifdef SET_MD_3_NAME
    150 	{SET_MD_3_NAME,		SET_MD_3,		false, MSG_set_md_3, NULL},
    151 #endif
    152 #ifdef SET_MD_4_NAME
    153 	{SET_MD_4_NAME,		SET_MD_4,		false, MSG_set_md_4, NULL},
    154 #endif
    155 
    156 	{NULL,			SET_GROUP,		true, MSG_set_source, NULL},
    157 	{"syssrc",		SET_SYSSRC,		true, MSG_set_syssrc, NULL},
    158 	{"src",			SET_SRC,		true, MSG_set_src, NULL},
    159 	{"sharesrc",		SET_SHARESRC,		true, MSG_set_sharesrc, NULL},
    160 	{"gnusrc",		SET_GNUSRC,		true, MSG_set_gnusrc, NULL},
    161 	{"xsrc",		SET_XSRC,		true, MSG_set_xsrc, NULL},
    162 	{"debug",		SET_DEBUG,		false, MSG_set_debug, NULL},
    163 	{"xdebug",		SET_X11_DEBUG,		false, MSG_set_xdebug, NULL},
    164 	{NULL,			SET_GROUP_END,		false, NULL, NULL},
    165 
    166 	{NULL,			SET_LAST,		false, NULL, NULL},
    167 };
    168 
    169 #define MAX_CD_INFOS	16	/* how many media can be found? */
    170 struct cd_info {
    171 	char device_name[16];
    172 	char menu[100];
    173 };
    174 static struct cd_info cds[MAX_CD_INFOS];
    175 
    176 /*
    177  * local prototypes
    178  */
    179 
    180 static int check_for(unsigned int mode, const char *pathname);
    181 static int get_iso9660_volname(int dev, int sess, char *volname);
    182 static int get_available_cds(void);
    183 
    184 void
    185 init_set_status(int flags)
    186 {
    187 	static const uint8_t sets_valid[] = {MD_SETS_VALID};
    188 	static const uint8_t sets_selected_full[] = {MD_SETS_SELECTED};
    189 	static const uint8_t sets_selected_minimal[] = {MD_SETS_SELECTED_MINIMAL};
    190 	static const uint8_t sets_selected_nox[] = {MD_SETS_SELECTED_NOX};
    191 	static const uint8_t *sets_selected;
    192 	unsigned int nelem_selected;
    193 	unsigned int i, len;
    194 	const char *longest;
    195 
    196 	if (flags & SFLAG_MINIMAL) {
    197 		sets_selected = sets_selected_minimal;
    198 		nelem_selected = nelem(sets_selected_minimal);
    199 	} else if (flags & SFLAG_NOX) {
    200 		sets_selected = sets_selected_nox;
    201 		nelem_selected = nelem(sets_selected_nox);
    202 	} else {
    203 		sets_selected = sets_selected_full;
    204 		nelem_selected = nelem(sets_selected_full);
    205 	}
    206 
    207 	for (i = 0; i < nelem(sets_valid); i++)
    208 		set_status[sets_valid[i]] = SET_VALID;
    209 	for (i = 0; i < nelem_selected; i++)
    210 		set_status[sets_selected[i]] |= SET_SELECTED;
    211 
    212 	set_status[SET_GROUP] = SET_VALID;
    213 
    214 	/* Lookup some strings we need lots of times */
    215 	msg_yes = msg_string(MSG_Yes);
    216 	msg_no = msg_string(MSG_No);
    217 	msg_all = msg_string(MSG_All);
    218 	msg_some = msg_string(MSG_Some);
    219 	msg_none = msg_string(MSG_None);
    220 	msg_cur_distsets_row = msg_string(MSG_cur_distsets_row);
    221 
    222 	/* Find longest and use it to determine width of selection menu */
    223 	len = strlen(msg_no); longest = msg_no;
    224 	i = strlen(msg_yes); if (i > len) {len = i; longest = msg_yes; }
    225 	i = strlen(msg_all); if (i > len) {len = i; longest = msg_all; }
    226 	i = strlen(msg_some); if (i > len) {len = i; longest = msg_some; }
    227 	i = strlen(msg_none); if (i > len) {len = i; longest = msg_none; }
    228 	select_menu_width = snprintf(NULL, 0, msg_cur_distsets_row, "",longest);
    229 
    230 	/* Give the md code a chance to choose the right kernel, etc. */
    231 	md_init_set_status(flags);
    232 }
    233 
    234 int
    235 dir_exists_p(const char *path)
    236 {
    237 
    238 	return file_mode_match(path, S_IFDIR);
    239 }
    240 
    241 int
    242 file_exists_p(const char *path)
    243 {
    244 
    245 	return file_mode_match(path, S_IFREG);
    246 }
    247 
    248 int
    249 file_mode_match(const char *path, unsigned int mode)
    250 {
    251 	struct stat st;
    252 
    253 	return (stat(path, &st) == 0 && (st.st_mode & S_IFMT) == mode);
    254 }
    255 
    256 uint
    257 get_ramsize(void)
    258 {
    259 	uint64_t ramsize;
    260 	size_t len = sizeof ramsize;
    261 	int mib[2] = {CTL_HW, HW_PHYSMEM64};
    262 
    263 	sysctl(mib, 2, &ramsize, &len, NULL, 0);
    264 
    265 	/* Find out how many Megs ... round up. */
    266 	return (ramsize + MEG - 1) / MEG;
    267 }
    268 
    269 void
    270 run_makedev(void)
    271 {
    272 	char *owd;
    273 
    274 	msg_display_add("\n\n");
    275 	msg_display_add(MSG_makedev);
    276 
    277 	owd = getcwd(NULL, 0);
    278 
    279 	/* make /dev, in case the user  didn't extract it. */
    280 	make_target_dir("/dev");
    281 	target_chdir_or_die("/dev");
    282 	run_program(0, "/bin/sh MAKEDEV all");
    283 
    284 	chdir(owd);
    285 	free(owd);
    286 }
    287 
    288 /*
    289  * Performs in-place replacement of a set of patterns in a file that lives
    290  * inside the installed system.  The patterns must be separated by a semicolon.
    291  * For example:
    292  *
    293  * replace("/etc/some-file.conf", "s/prop1=NO/prop1=YES/;s/foo/bar/");
    294  */
    295 void
    296 replace(const char *path, const char *patterns, ...)
    297 {
    298 	char *spatterns;
    299 	va_list ap;
    300 
    301 	va_start(ap, patterns);
    302 	vasprintf(&spatterns, patterns, ap);
    303 	va_end(ap);
    304 	if (spatterns == NULL)
    305 		err(1, "vasprintf(&spatterns, \"%s\", ...)", patterns);
    306 
    307 	run_program(RUN_CHROOT, "sed -an -e '%s;H;$!d;g;w %s' %s", spatterns,
    308 	    path, path);
    309 
    310 	free(spatterns);
    311 }
    312 
    313 static int
    314 floppy_fetch(const char *set_name)
    315 {
    316 	char post[4];
    317 	msg errmsg;
    318 	int menu;
    319 	int status;
    320 	const char *write_mode = ">";
    321 
    322 	strcpy(post, "aa");
    323 
    324 	errmsg = "";
    325 	menu = MENU_fdok;
    326 	for (;;) {
    327 		umount_mnt2();
    328 		msg_display(errmsg);
    329 		msg_display_add(MSG_fdmount, set_name, post);
    330 		process_menu(menu, &status);
    331 		if (status != SET_CONTINUE)
    332 			return status;
    333 		menu = MENU_fdremount;
    334 		errmsg = MSG_fdremount;
    335 		if (run_program(0, "/sbin/mount -r -t %s %s /mnt2",
    336 							fd_type, fd_dev))
    337 			continue;
    338 		mnt2_mounted = 1;
    339 		errmsg = MSG_fdnotfound;
    340 
    341 		/* Display this because it might take a while.... */
    342 		if (run_program(RUN_DISPLAY,
    343 			    "sh -c '/bin/cat /mnt2/%s.%s %s %s/%s/%s%s'",
    344 			    set_name, post, write_mode,
    345 			    target_prefix(), xfer_dir, set_name,
    346 			    set_postfix(set_name)))
    347 			/* XXX: a read error will give a corrupt file! */
    348 			continue;
    349 
    350 		/* We got that file, advance to next fragment */
    351 		if (post[1] < 'z')
    352 			post[1]++;
    353 		else
    354 			post[1] = 'a', post[0]++;
    355 		write_mode = ">>";
    356 		errmsg = "";
    357 		menu = MENU_fdok;
    358 	}
    359 }
    360 
    361 /*
    362  * Load files from floppy.  Requires a /mnt2 directory for mounting them.
    363  */
    364 int
    365 get_via_floppy(void)
    366 {
    367 	int rv = -1;
    368 
    369 	process_menu(MENU_floppysource, &rv);
    370 	if (rv == SET_RETRY)
    371 		return SET_RETRY;
    372 
    373 	fetch_fn = floppy_fetch;
    374 
    375 	/* Set ext_dir for absolute path. */
    376 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s", target_prefix(), xfer_dir);
    377 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s", target_prefix(), xfer_dir);
    378 
    379 	return SET_OK;
    380 }
    381 
    382 /*
    383  * Get the volume name of a ISO9660 file system
    384  */
    385 static int
    386 get_iso9660_volname(int dev, int sess, char *volname)
    387 {
    388 	int blkno, error, last;
    389 	char buf[ISO_BLKSIZE];
    390 	struct iso_volume_descriptor *vd = NULL;
    391 	struct iso_primary_descriptor *pd = NULL;
    392 
    393 	for (blkno = sess+16; blkno < sess+16+100; blkno++) {
    394 		error = pread(dev, buf, ISO_BLKSIZE, blkno*ISO_BLKSIZE);
    395 		if (error == -1)
    396 			return -1;
    397 		vd = (struct iso_volume_descriptor *)&buf;
    398 		if (memcmp(vd->id, ISO_STANDARD_ID, sizeof(vd->id)) != 0)
    399 			return -1;
    400 		if (isonum_711((const unsigned char *)&vd->type)
    401 		     == ISO_VD_PRIMARY) {
    402 			pd = (struct iso_primary_descriptor*)buf;
    403 			strncpy(volname, pd->volume_id, sizeof pd->volume_id);
    404 			last = sizeof pd->volume_id-1;
    405 			while (last >= 0
    406 			    && (volname[last] == ' ' || volname[last] == 0))
    407 				last--;
    408 			volname[last+1] = 0;
    409 			return 0;
    410 		}
    411 	}
    412 	return -1;
    413 }
    414 
    415 /*
    416  * Get a list of all available CD media (not drives!), return
    417  * the number of entries collected.
    418  */
    419 static int
    420 get_available_cds(void)
    421 {
    422 	static const char *cdrom_devices[] = { CD_NAMES, 0 };
    423 	char dname[16], volname[80], fmt[80], tmp[80], *star;
    424 	struct cd_info *info = cds;
    425 	struct disklabel label;
    426 	int i, part, dev, error, sess, ready, count = 0;
    427 
    428 	for (const char **dev_pat = cdrom_devices; *dev_pat; dev_pat++) {
    429 		for (i = 0; i < MAX_CD_DEVS; i++) {
    430 			strcpy(fmt, *dev_pat);
    431 			star = strchr(fmt, '*');
    432 			if (star) {
    433 				strcpy(star, "%d");
    434 				sprintf(tmp, "/dev/r%s%%c", fmt);
    435 				sprintf(dname, tmp, i, 'a'+RAW_PART);
    436 			} else {
    437 				sprintf(dname, "/dev/r%s%c", fmt,
    438 				    'a'+RAW_PART);
    439 			}
    440 			dev = open(dname, O_RDONLY, 0);
    441 			if (dev == -1)
    442 				continue;
    443 			ready = 0;
    444 			error = ioctl(dev, DIOCTUR, &ready);
    445 			if (error != 0 || ready == 0) {
    446 				close(dev);
    447 				continue;
    448 			}
    449 			error = ioctl(dev, DIOCGDINFO, &label);
    450 			close(dev);
    451 			if (error == 0) {
    452 				for (part = 0; part < label.d_npartitions;
    453 				    part++) {
    454 					if (label.d_partitions[part].p_fstype
    455 						== FS_UNUSED
    456 					    || label.d_partitions[part].p_size == 0)
    457 						continue;
    458 					if (label.d_partitions[part].p_fstype
    459 					    == FS_ISO9660) {
    460 						sess = label.d_partitions[part]
    461 						    .p_cdsession;
    462 						sprintf(dname, "/dev/rcd%d%c", i,
    463 						    'a'+part);
    464 						dev = open(dname, O_RDONLY, 0);
    465 						if (dev == -1)
    466 							continue;
    467 						error = get_iso9660_volname(dev, sess,
    468 						    volname);
    469 						close(dev);
    470 						if (error) continue;
    471 						sprintf(info->device_name, "cd%d%c",
    472 							i, 'a'+part);
    473 						sprintf(info->menu, "%s (%s)",
    474 							info->device_name,
    475 							volname);
    476 					} else {
    477 						/*
    478 						 * All install CDs use partition
    479 						 * a for the sets.
    480 						 */
    481 						if (part > 0)
    482 							continue;
    483 						sprintf(info->device_name, "cd%d%c",
    484 							i, 'a'+part);
    485 						strcpy(info->menu, info->device_name);
    486 					}
    487 					info++;
    488 					if (++count >= MAX_CD_INFOS)
    489 						break;
    490 				}
    491 			}
    492 			if (++count >= MAX_CD_INFOS)
    493 				break;
    494 			if (!star)
    495 				break;
    496 		}
    497 		if (++count >= MAX_CD_INFOS)
    498 			break;
    499 	}
    500 	return count;
    501 }
    502 
    503 static int
    504 cd_has_sets(void)
    505 {
    506 	/* Mount it */
    507 	if (run_program(RUN_SILENT, "/sbin/mount -rt cd9660 /dev/%s /mnt2",
    508 	    cdrom_dev) != 0)
    509 		return 0;
    510 
    511 	mnt2_mounted = 1;
    512 
    513 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s", "/mnt2", set_dir_bin);
    514 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s", "/mnt2", set_dir_src);
    515 	return dir_exists_p(ext_dir_bin);
    516 }
    517 
    518 /*
    519  * Check whether we can remove the boot media.
    520  * If it is not a local filesystem, return -1.
    521  * If we can not decide for sure (can not tell MD content from plain ffs
    522  * on hard disk, for example), return 0.
    523  * If it is a CD/DVD, return 1.
    524  */
    525 int
    526 boot_media_still_needed(void)
    527 {
    528 	struct statvfs sb;
    529 
    530 	if (statvfs("/", &sb) == 0) {
    531 		if (!(sb.f_flag & ST_LOCAL))
    532 			return -1;
    533 		if (strcmp(sb.f_fstypename, MOUNT_CD9660) == 0
    534 			   || strcmp(sb.f_fstypename, MOUNT_UDF) == 0)
    535 			return 1;
    536 	}
    537 
    538 	return 0;
    539 }
    540 
    541 /*
    542  * Get from a CDROM distribution.
    543  * Also used on "installation using bootable install media"
    544  * as the default option in the "distmedium" menu.
    545  */
    546 int
    547 get_via_cdrom(void)
    548 {
    549 	menu_ent cd_menu[MAX_CD_INFOS];
    550 	struct stat sb;
    551 	int rv, num_cds, menu_cd, i, selected_cd = 0;
    552 	bool silent = false;
    553 	int mib[2];
    554 	char rootdev[SSTRSIZE] = "";
    555 	size_t varlen;
    556 
    557 	/* If root is not md(4) and we have set dir, skip this step. */
    558 	mib[0] = CTL_KERN;
    559 	mib[1] = KERN_ROOT_DEVICE;
    560 	varlen = sizeof(rootdev);
    561 	(void)sysctl(mib, 2, rootdev, &varlen, NULL, 0);
    562 	if (stat(set_dir_bin, &sb) == 0 && S_ISDIR(sb.st_mode) &&
    563 	    strncmp("md", rootdev, 2) != 0) {
    564 	    	strlcpy(ext_dir_bin, set_dir_bin, sizeof ext_dir_bin);
    565 	    	strlcpy(ext_dir_src, set_dir_src, sizeof ext_dir_src);
    566 		return SET_OK;
    567 	}
    568 
    569 	num_cds = get_available_cds();
    570 	if (num_cds <= 0) {
    571 		silent = true;
    572 	} else if (num_cds == 1) {
    573 		/* single CD found, check for sets on it */
    574 		strcpy(cdrom_dev, cds[0].device_name);
    575 		if (cd_has_sets())
    576 			return SET_OK;
    577 	} else {
    578 		for (i = 0; i< num_cds; i++) {
    579 			cd_menu[i].opt_name = cds[i].menu;
    580 			cd_menu[i].opt_menu = OPT_NOMENU;
    581 			cd_menu[i].opt_flags = OPT_EXIT;
    582 			cd_menu[i].opt_action = set_menu_select;
    583 		}
    584 		/* create a menu offering available choices */
    585 		menu_cd = new_menu(MSG_Available_cds,
    586 			cd_menu, num_cds, -1, 4, 0, 0,
    587 			MC_SCROLL | MC_NOEXITOPT,
    588 			NULL, NULL, NULL, NULL, NULL);
    589 		if (menu_cd == -1)
    590 			return SET_RETRY;
    591 		msg_display(MSG_ask_cd);
    592 		process_menu(menu_cd, &selected_cd);
    593 		free_menu(menu_cd);
    594 		strcpy(cdrom_dev, cds[selected_cd].device_name);
    595 		if (cd_has_sets())
    596 			return SET_OK;
    597 	}
    598 
    599 	if (silent)
    600 		msg_display("");
    601 	else {
    602 		umount_mnt2();
    603 		msg_display(MSG_cd_path_not_found);
    604 		process_menu(MENU_ok, NULL);
    605 	}
    606 
    607 	/* ask for paths on the CD */
    608 	rv = -1;
    609 	process_menu(MENU_cdromsource, &rv);
    610 	if (rv == SET_RETRY)
    611 		return SET_RETRY;
    612 
    613 	if (cd_has_sets())
    614 		return SET_OK;
    615 
    616 	return SET_RETRY;
    617 }
    618 
    619 
    620 /*
    621  * Get from a pathname inside an unmounted local filesystem
    622  * (e.g., where sets were preloaded onto a local DOS partition)
    623  */
    624 int
    625 get_via_localfs(void)
    626 {
    627 	int rv = -1;
    628 
    629 	/* Get device, filesystem, and filepath */
    630 	process_menu (MENU_localfssource, &rv);
    631 	if (rv == SET_RETRY)
    632 		return SET_RETRY;
    633 
    634 	/* Mount it */
    635 	if (run_program(0, "/sbin/mount -rt %s /dev/%s /mnt2",
    636 	    localfs_fs, localfs_dev))
    637 		return SET_RETRY;
    638 
    639 	mnt2_mounted = 1;
    640 
    641 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s/%s",
    642 		"/mnt2", localfs_dir, set_dir_bin);
    643 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s/%s",
    644 		"/mnt2", localfs_dir, set_dir_src);
    645 
    646 	return SET_OK;
    647 }
    648 
    649 /*
    650  * Get from an already-mounted pathname.
    651  */
    652 
    653 int
    654 get_via_localdir(void)
    655 {
    656 	int rv = -1;
    657 
    658 	/* Get filepath */
    659 	process_menu(MENU_localdirsource, &rv);
    660 	if (rv == SET_RETRY)
    661 		return SET_RETRY;
    662 
    663 	/*
    664 	 * We have to have an absolute path ('cos pax runs in a
    665 	 * different directory), make it so.
    666 	 */
    667 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "/%s/%s", localfs_dir, set_dir_bin);
    668 	snprintf(ext_dir_src, sizeof ext_dir_src, "/%s/%s", localfs_dir, set_dir_src);
    669 
    670 	return SET_OK;
    671 }
    672 
    673 
    674 /*
    675  * Support for custom distribution fetches / unpacks.
    676  */
    677 
    678 unsigned int
    679 set_X11_selected(void)
    680 {
    681 	int i;
    682 
    683 	for (i = SET_X11_FIRST; ++i < SET_X11_LAST;)
    684 		if (set_status[i] & SET_SELECTED)
    685 			return 1;
    686 	return 0;
    687 }
    688 
    689 unsigned int
    690 get_kernel_set(void)
    691 {
    692 	int i;
    693 
    694 	for (i = SET_KERNEL_FIRST; ++i < SET_KERNEL_LAST;)
    695 		if (set_status[i] & SET_SELECTED)
    696 			return i;
    697 	return SET_NONE;
    698 }
    699 
    700 void
    701 set_kernel_set(unsigned int kernel_set)
    702 {
    703 	int i;
    704 
    705 	/* only one kernel set is allowed */
    706 	for (i = SET_KERNEL_FIRST; ++i < SET_KERNEL_LAST;)
    707 		set_status[i] &= ~SET_SELECTED;
    708 	set_status[kernel_set] |= SET_SELECTED;
    709 }
    710 
    711 static int
    712 set_toggle(menudesc *menu, void *arg)
    713 {
    714 	distinfo **distp = arg;
    715 	int set = distp[menu->cursel]->set;
    716 
    717 	if (set > SET_KERNEL_FIRST && set < SET_KERNEL_LAST &&
    718 	    !(set_status[set] & SET_SELECTED))
    719 		set_kernel_set(set);
    720 	else
    721 		set_status[set] ^= SET_SELECTED;
    722 	return 0;
    723 }
    724 
    725 static int
    726 set_all_none(menudesc *menu, void *arg, int set, int clr)
    727 {
    728 	distinfo **distp = arg;
    729 	distinfo *dist = *distp;
    730 	int nested;
    731 
    732 	for (nested = 0; dist->set != SET_GROUP_END || nested--; dist++) {
    733 		if (dist->set == SET_GROUP) {
    734 			nested++;
    735 			continue;
    736 		}
    737 		set_status[dist->set] = (set_status[dist->set] & ~clr) | set;
    738 	}
    739 	return 0;
    740 }
    741 
    742 static int
    743 set_all(menudesc *menu, void *arg)
    744 {
    745 	return set_all_none(menu, arg, SET_SELECTED, 0);
    746 }
    747 
    748 static int
    749 set_none(menudesc *menu, void *arg)
    750 {
    751 	return set_all_none(menu, arg, 0, SET_SELECTED);
    752 }
    753 
    754 static void
    755 set_label(menudesc *menu, int opt, void *arg)
    756 {
    757 	distinfo **distp = arg;
    758 	distinfo *dist = distp[opt];
    759 	const char *selected;
    760 	const char *desc;
    761 	int nested;
    762 
    763 	desc = dist->desc;
    764 
    765 	if (dist->set != SET_GROUP)
    766 		selected = set_status[dist->set] & SET_SELECTED ? msg_yes : msg_no;
    767 	else {
    768 		/* sub menu - display None/Some/All */
    769 		nested = 0;
    770 		selected = "unknown";
    771 		while ((++dist)->set != SET_GROUP_END || nested--) {
    772 			if (dist->set == SET_GROUP) {
    773 				nested++;
    774 				continue;
    775 			}
    776 			if (!(set_status[dist->set] & SET_VALID))
    777 				continue;
    778 			if (set_status[dist->set] & SET_SELECTED) {
    779 				if (selected == msg_none) {
    780 					selected = msg_some;
    781 					break;
    782 				}
    783 				selected = msg_all;
    784 			} else {
    785 				if (selected == msg_all) {
    786 					selected = msg_some;
    787 					break;
    788 				}
    789 				selected = msg_none;
    790 			}
    791 		}
    792 	}
    793 
    794 	wprintw(menu->mw, msg_cur_distsets_row, msg_string(desc), selected);
    795 }
    796 
    797 static int set_sublist(menudesc *menu, void *arg);
    798 
    799 static int
    800 initialise_set_menu(distinfo *dist, menu_ent *me, distinfo **de, int all_none)
    801 {
    802 	int set;
    803 	int sets;
    804 	int nested;
    805 
    806 	for (sets = 0; ; dist++) {
    807 		set = dist->set;
    808 		if (set == SET_LAST || set == SET_GROUP_END)
    809 			break;
    810 		if (!(set_status[set] & SET_VALID))
    811 			continue;
    812 		*de = dist;
    813 		me->opt_menu = OPT_NOMENU;
    814 		me->opt_flags = 0;
    815 		me->opt_name = NULL;
    816 		if (set != SET_GROUP)
    817 			me->opt_action = set_toggle;
    818 		else {
    819 			/* Collapse sublist */
    820 			nested = 0;
    821 			while ((++dist)->set != SET_GROUP_END || nested--) {
    822 				if (dist->set == SET_GROUP)
    823 					nested++;
    824 			}
    825 			me->opt_action = set_sublist;
    826 		}
    827 		sets++;
    828 		de++;
    829 		me++;
    830 	}
    831 
    832 	if (all_none) {
    833 		me->opt_menu = OPT_NOMENU;
    834 		me->opt_flags = 0;
    835 		me->opt_name = MSG_select_all;
    836 		me->opt_action = set_all;
    837 		me++;
    838 		me->opt_menu = OPT_NOMENU;
    839 		me->opt_flags = 0;
    840 		me->opt_name = MSG_select_none;
    841 		me->opt_action = set_none;
    842 		sets += 2;
    843 	}
    844 
    845 	return sets;
    846 }
    847 
    848 static int
    849 set_sublist(menudesc *menu, void *arg)
    850 {
    851 	distinfo *de[SET_LAST];
    852 	menu_ent me[SET_LAST];
    853 	distinfo **dist = arg;
    854 	int menu_no;
    855 	int sets;
    856 
    857 	sets = initialise_set_menu(dist[menu->cursel] + 1, me, de, 1);
    858 
    859 	menu_no = new_menu(NULL, me, sets, 20, 10, 0, select_menu_width,
    860 		MC_SUBMENU | MC_SCROLL | MC_DFLTEXIT,
    861 		NULL, set_label, NULL, NULL,
    862 		MSG_install_selected_sets);
    863 
    864 	process_menu(menu_no, de);
    865 	free_menu(menu_no);
    866 
    867 	return 0;
    868 }
    869 
    870 void
    871 customise_sets(void)
    872 {
    873 	distinfo *de[SET_LAST];
    874 	menu_ent me[SET_LAST];
    875 	int sets;
    876 	int menu_no;
    877 
    878 	msg_display(MSG_cur_distsets);
    879 	msg_table_add(MSG_cur_distsets_header);
    880 
    881 	sets = initialise_set_menu(dist_list, me, de, 0);
    882 
    883 	menu_no = new_menu(NULL, me, sets, 0, 5, 0, select_menu_width,
    884 		MC_SCROLL | MC_NOBOX | MC_DFLTEXIT | MC_NOCLEAR,
    885 		NULL, set_label, NULL, NULL,
    886 		MSG_install_selected_sets);
    887 
    888 	process_menu(menu_no, de);
    889 	free_menu(menu_no);
    890 }
    891 
    892 /*
    893  * Extract_file **REQUIRES** an absolute path in ext_dir.  Any code
    894  * that sets up xfer_dir for use by extract_file needs to put in the
    895  * full path name to the directory.
    896  */
    897 
    898 int
    899 extract_file(distinfo *dist, int update)
    900 {
    901 	char path[STRSIZE];
    902 	char *owd;
    903 	int   rval;
    904 
    905 	/* If we might need to tidy up, ensure directory exists */
    906 	if (fetch_fn != NULL)
    907 		make_target_dir(xfer_dir);
    908 
    909 	(void)snprintf(path, sizeof path, "%s/%s%s",
    910 	    ext_dir_for_set(dist->name), dist->name, set_postfix(dist->name));
    911 
    912 	owd = getcwd(NULL, 0);
    913 
    914 	/* Do we need to fetch the file now? */
    915 	if (fetch_fn != NULL) {
    916 		rval = fetch_fn(dist->name);
    917 		if (rval != SET_OK)
    918 			return rval;
    919 	}
    920 
    921 	/* check tarfile exists */
    922 	if (!file_exists_p(path)) {
    923 
    924 #ifdef SUPPORT_8_3_SOURCE_FILESYSTEM
    925 	/*
    926 	 * Update path to use dist->name truncated to the first eight
    927 	 * characters and check again
    928 	 */
    929 	(void)snprintf(path, sizeof path, "%s/%.8s%.4s", /* 4 as includes '.' */
    930 	    ext_dir_for_set(dist->name), dist->name, set_postfix(dist->name));
    931 		if (!file_exists_p(path)) {
    932 #endif /* SUPPORT_8_3_SOURCE_FILESYSTEM */
    933 
    934 		tarstats.nnotfound++;
    935 
    936 		msg_display(MSG_notarfile, path);
    937 		process_menu(MENU_ok, NULL);
    938 		return SET_RETRY;
    939 	}
    940 #ifdef SUPPORT_8_3_SOURCE_FILESYSTEM
    941 	}
    942 #endif /* SUPPORT_8_3_SOURCE_FILESYSTEM */
    943 
    944 	tarstats.nfound++;
    945 	/* cd to the target root. */
    946 	if (update && (dist->set == SET_ETC || dist->set == SET_X11_ETC)) {
    947 		make_target_dir("/.sysinst");
    948 		target_chdir_or_die("/.sysinst");
    949 	} else if (dist->set == SET_PKGSRC)
    950 		target_chdir_or_die("/usr");
    951 	else
    952 		target_chdir_or_die("/");
    953 
    954 	/*
    955 	 * /usr/X11R7/lib/X11/xkb/symbols/pc was a directory in 5.0
    956 	 * but is a file in 5.1 and beyond, so on upgrades we need to
    957 	 * delete it before extracting the xbase set.
    958 	 */
    959 	if (update && dist->set == SET_X11_BASE)
    960 		run_program(0, "rm -rf usr/X11R7/lib/X11/xkb/symbols/pc");
    961 
    962 	/* now extract set files into "./". */
    963 	rval = run_program(RUN_DISPLAY | RUN_PROGRESS,
    964 			"progress -zf %s tar --chroot -xhepf -", path);
    965 
    966 	chdir(owd);
    967 	free(owd);
    968 
    969 	/* Check rval for errors and give warning. */
    970 	if (rval != 0) {
    971 		tarstats.nerror++;
    972 		msg_display(MSG_tarerror, path);
    973 		process_menu(MENU_ok, NULL);
    974 		return SET_RETRY;
    975 	}
    976 
    977 	if (fetch_fn != NULL && clean_xfer_dir) {
    978 		run_program(0, "rm %s", path);
    979 		/* Plausibly we should unlink an empty xfer_dir as well */
    980 	}
    981 
    982 	set_status[dist->set] |= SET_INSTALLED;
    983 	tarstats.nsuccess++;
    984 	return SET_OK;
    985 }
    986 
    987 static void
    988 skip_set(distinfo *dist, int skip_type)
    989 {
    990 	int nested;
    991 	int set;
    992 
    993 	nested = 0;
    994 	while ((++dist)->set != SET_GROUP_END || nested--) {
    995 		set = dist->set;
    996 		if (set == SET_GROUP) {
    997 			nested++;
    998 			continue;
    999 		}
   1000 		if (set == SET_LAST)
   1001 			break;
   1002 		if (set_status[set] == (SET_SELECTED | SET_VALID))
   1003 			set_status[set] |= SET_SKIPPED;
   1004 		tarstats.nskipped++;
   1005 	}
   1006 }
   1007 
   1008 /*
   1009  * Get and unpack the distribution.
   1010  * Show success_msg if installation completes.
   1011  * Otherwise show failure_msg and wait for the user to ack it before continuing.
   1012  * success_msg and failure_msg must both be 0-adic messages.
   1013  */
   1014 int
   1015 get_and_unpack_sets(int update, msg setupdone_msg, msg success_msg, msg failure_msg)
   1016 {
   1017 	distinfo *dist;
   1018 	int status;
   1019 	int set;
   1020 
   1021 	/* Ensure mountpoint for distribution files exists in current root. */
   1022 	(void)mkdir("/mnt2", S_IRWXU| S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH);
   1023 	if (script)
   1024 		(void)fprintf(script, "mkdir -m 755 /mnt2\n");
   1025 
   1026 	/* reset failure/success counters */
   1027 	memset(&tarstats, 0, sizeof(tarstats));
   1028 
   1029 	/* Find out which files to "get" if we get files. */
   1030 
   1031 	/* Accurately count selected sets */
   1032 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1033 		if (dist->name == NULL)
   1034 			continue;
   1035 		if ((set_status[set] & (SET_VALID | SET_SELECTED))
   1036 		    == (SET_VALID | SET_SELECTED))
   1037 			tarstats.nselected++;
   1038 	}
   1039 
   1040 	status = SET_RETRY;
   1041 	for (dist = dist_list; (set = dist->set) != SET_LAST; dist++) {
   1042 		if (dist->name == NULL)
   1043 			continue;
   1044 		if (set_status[set] != (SET_VALID | SET_SELECTED))
   1045 			continue;
   1046 
   1047 		if (status != SET_OK) {
   1048 			/* This might force a redraw.... */
   1049 			clearok(curscr, 1);
   1050 			touchwin(stdscr);
   1051 			wrefresh(stdscr);
   1052 			/* Sort out the location of the set files */
   1053 			do {
   1054 				umount_mnt2();
   1055 				msg_display(MSG_distmedium, tarstats.nselected,
   1056 				    tarstats.nsuccess + tarstats.nskipped,
   1057 				    dist->name);
   1058 				fetch_fn = NULL;
   1059 				process_menu(MENU_distmedium, &status);
   1060 			} while (status == SET_RETRY);
   1061 
   1062 			if (status == SET_SKIP) {
   1063 				set_status[set] |= SET_SKIPPED;
   1064 				tarstats.nskipped++;
   1065 				continue;
   1066 			}
   1067 			if (status == SET_SKIP_GROUP) {
   1068 				skip_set(dist, status);
   1069 				continue;
   1070 			}
   1071 			if (status != SET_OK) {
   1072 				msg_display(failure_msg);
   1073 				process_menu(MENU_ok, NULL);
   1074 				return 1;
   1075 			}
   1076 		}
   1077 
   1078 		/* Try to extract this set */
   1079 		status = extract_file(dist, update);
   1080 		if (status == SET_RETRY)
   1081 			dist--;
   1082 	}
   1083 
   1084 	if (tarstats.nerror == 0 && tarstats.nsuccess == tarstats.nselected) {
   1085 		msg_display(MSG_endtarok);
   1086 		/* Give user a chance to see the success message */
   1087 		sleep(1);
   1088 	} else {
   1089 		/* We encountered errors. Let the user know. */
   1090 		msg_display(MSG_endtar,
   1091 		    tarstats.nselected, tarstats.nnotfound, tarstats.nskipped,
   1092 		    tarstats.nfound, tarstats.nsuccess, tarstats.nerror);
   1093 		process_menu(MENU_ok, NULL);
   1094 		msg_clear();
   1095 	}
   1096 
   1097 	/*
   1098 	 * postinstall needs to be run after extracting all sets, because
   1099 	 * otherwise /var/db/obsolete will only have current information
   1100 	 * from the base, comp, and etc sets.
   1101 	 */
   1102 	if (update && (set_status[SET_ETC] & SET_INSTALLED)) {
   1103 		int oldsendmail;
   1104 		oldsendmail = run_program(RUN_DISPLAY | RUN_CHROOT |
   1105 					  RUN_ERROR_OK | RUN_PROGRESS,
   1106 					  "/usr/sbin/postinstall -s /.sysinst -d / check mailerconf");
   1107 		if (oldsendmail == 1) {
   1108 			msg_display(MSG_oldsendmail);
   1109 			if (ask_yesno(NULL)) {
   1110 				run_program(RUN_DISPLAY | RUN_CHROOT,
   1111 					    "/usr/sbin/postinstall -s /.sysinst -d / fix mailerconf");
   1112 			}
   1113 		}
   1114 		run_program(RUN_DISPLAY | RUN_CHROOT,
   1115 			"/usr/sbin/postinstall -s /.sysinst -d / fix");
   1116 
   1117 		/* Don't discard the system's old entropy if any */
   1118 		run_program(RUN_CHROOT | RUN_SILENT,
   1119 			    "/etc/rc.d/random_seed start");
   1120 	}
   1121 
   1122 	/* Configure the system */
   1123 	if (set_status[SET_BASE] & SET_INSTALLED)
   1124 		run_makedev();
   1125 
   1126 	if (!update) {
   1127 		struct stat sb1, sb2;
   1128 
   1129 		if (stat(target_expand("/"), &sb1) == 0
   1130 		    && stat(target_expand("/var"), &sb2) == 0
   1131 		    && sb1.st_dev != sb2.st_dev) {
   1132 			add_rc_conf("random_file=/etc/entropy-file\n");
   1133 			if (target_file_exists_p("/boot.cfg")) {
   1134 				run_program(RUN_CHROOT|RUN_FATAL,
   1135 					    "sh -c 'sed -e s./var/db/./etc/. "
   1136 					    "< /boot.cfg "
   1137 					    "> /tmp/boot.cfg.tmp'");
   1138 				mv_within_target_or_die("/tmp/boot.cfg.tmp",
   1139 							"/boot.cfg");
   1140 			}
   1141 		}
   1142 
   1143 		/* Save keyboard type */
   1144 		save_kb_encoding();
   1145 
   1146 		/* Other configuration. */
   1147 		mnt_net_config();
   1148 	}
   1149 
   1150 	/* Mounted dist dir? */
   1151 	umount_mnt2();
   1152 
   1153 	/* Save entropy -- on some systems it's ~all we'll ever get */
   1154 	run_program(RUN_DISPLAY | RUN_CHROOT | RUN_FATAL | RUN_PROGRESS,
   1155 		    "/etc/rc.d/random_seed stop");
   1156 	/* Install/Upgrade complete ... reboot or exit to script */
   1157 	msg_display(success_msg);
   1158 	process_menu(MENU_ok, NULL);
   1159 	return 0;
   1160 }
   1161 
   1162 void
   1163 umount_mnt2(void)
   1164 {
   1165 	if (!mnt2_mounted)
   1166 		return;
   1167 	run_program(RUN_SILENT, "/sbin/umount /mnt2");
   1168 	mnt2_mounted = 0;
   1169 }
   1170 
   1171 
   1172 /*
   1173  * Do a quick sanity check that  the target can reboot.
   1174  * return 1 if everything OK, 0 if there is a problem.
   1175  * Uses a table of files we expect to find after a base install/upgrade.
   1176  */
   1177 
   1178 /* test flag and pathname to check for after unpacking. */
   1179 struct check_table { unsigned int mode; const char *path;} checks[] = {
   1180   { S_IFREG, "/netbsd" },
   1181   { S_IFDIR, "/etc" },
   1182   { S_IFREG, "/etc/fstab" },
   1183   { S_IFREG, "/sbin/init" },
   1184   { S_IFREG, "/bin/sh" },
   1185   { S_IFREG, "/etc/rc" },
   1186   { S_IFREG, "/etc/rc.subr" },
   1187   { S_IFREG, "/etc/rc.conf" },
   1188   { S_IFDIR, "/dev" },
   1189   { S_IFCHR, "/dev/console" },
   1190 /* XXX check for rootdev in target /dev? */
   1191   { S_IFREG, "/sbin/fsck" },
   1192   { S_IFREG, "/sbin/fsck_ffs" },
   1193   { S_IFREG, "/sbin/mount" },
   1194   { S_IFREG, "/sbin/mount_ffs" },
   1195   { S_IFREG, "/sbin/mount_nfs" },
   1196 #if defined(DEBUG) || defined(DEBUG_CHECK)
   1197   { S_IFREG, "/foo/bar" },		/* bad entry to exercise warning */
   1198 #endif
   1199   { 0, 0 }
   1200 
   1201 };
   1202 
   1203 /*
   1204  * Check target for a single file.
   1205  */
   1206 static int
   1207 check_for(unsigned int mode, const char *pathname)
   1208 {
   1209 	int found;
   1210 
   1211 	found = (target_test(mode, pathname) == 0);
   1212 	if (found == 0)
   1213 		msg_display(MSG_rootmissing, pathname);
   1214 	return found;
   1215 }
   1216 
   1217 /*
   1218  * Check that all the files in check_table are present in the
   1219  * target root. Warn if not found.
   1220  */
   1221 int
   1222 sanity_check(void)
   1223 {
   1224 	int target_ok = 1;
   1225 	struct check_table *p;
   1226 
   1227 	for (p = checks; p->path; p++) {
   1228 		target_ok = target_ok && check_for(p->mode, p->path);
   1229 	}
   1230 	if (target_ok)
   1231 		return 0;
   1232 
   1233 	/* Uh, oh. Something's missing. */
   1234 	msg_display(MSG_badroot);
   1235 	process_menu(MENU_ok, NULL);
   1236 	return 1;
   1237 }
   1238 
   1239 /*
   1240  * Some globals to pass things back from callbacks
   1241  */
   1242 static char zoneinfo_dir[STRSIZE];
   1243 static int zonerootlen;
   1244 static char *tz_selected;	/* timezonename (relative to share/zoneinfo */
   1245 const char *tz_default;		/* UTC, or whatever /etc/localtime points to */
   1246 static char tz_env[STRSIZE];
   1247 static int save_cursel, save_topline;
   1248 
   1249 /*
   1250  * Callback from timezone menu
   1251  */
   1252 static int
   1253 set_tz_select(menudesc *m, void *arg)
   1254 {
   1255 	time_t t;
   1256 	char *new;
   1257 	struct tm *tm;
   1258 
   1259 	if (m && strcmp(tz_selected, m->opts[m->cursel].opt_name) != 0) {
   1260 		/* Change the displayed timezone */
   1261 		new = strdup(m->opts[m->cursel].opt_name);
   1262 		if (new == NULL)
   1263 			return 0;
   1264 		free(tz_selected);
   1265 		tz_selected = new;
   1266 		snprintf(tz_env, sizeof tz_env, "%.*s%s",
   1267 			 zonerootlen, zoneinfo_dir, tz_selected);
   1268 		setenv("TZ", tz_env, 1);
   1269 	}
   1270 	if (m)
   1271 		/* Warp curser to 'Exit' line on menu */
   1272 		m->cursel = -1;
   1273 
   1274 	/* Update displayed time */
   1275 	t = time(NULL);
   1276 	tm = localtime(&t);
   1277 	msg_display(MSG_choose_timezone,
   1278 		    tz_default, tz_selected, safectime(&t), tm ? tm->tm_zone :
   1279 		    "?");
   1280 	return 0;
   1281 }
   1282 
   1283 static int
   1284 set_tz_back(menudesc *m, void *arg)
   1285 {
   1286 
   1287 	zoneinfo_dir[zonerootlen] = 0;
   1288 	m->cursel = save_cursel;
   1289 	m->topline = save_topline;
   1290 	return 0;
   1291 }
   1292 
   1293 static int
   1294 set_tz_dir(menudesc *m, void *arg)
   1295 {
   1296 
   1297 	strlcpy(zoneinfo_dir + zonerootlen, m->opts[m->cursel].opt_name,
   1298 		sizeof zoneinfo_dir - zonerootlen);
   1299 	save_cursel = m->cursel;
   1300 	save_topline = m->topline;
   1301 	m->cursel = 0;
   1302 	m->topline = 0;
   1303 	return 0;
   1304 }
   1305 
   1306 /*
   1307  * Alarm-handler to update example-display
   1308  */
   1309 static void
   1310 /*ARGSUSED*/
   1311 timezone_sig(int sig)
   1312 {
   1313 
   1314 	set_tz_select(NULL, NULL);
   1315 	alarm(60);
   1316 }
   1317 
   1318 static int
   1319 tz_sort(const void *a, const void *b)
   1320 {
   1321 	return strcmp(((const menu_ent *)a)->opt_name, ((const menu_ent *)b)->opt_name);
   1322 }
   1323 
   1324 static void
   1325 tzm_set_names(menudesc *m, void *arg)
   1326 {
   1327 	DIR *dir;
   1328 	struct dirent *dp;
   1329 	static int nfiles;
   1330 	static int maxfiles = 32;
   1331 	static menu_ent *tz_menu;
   1332 	static char **tz_names;
   1333 	void *p;
   1334 	int maxfname;
   1335 	char *fp;
   1336 	struct stat sb;
   1337 
   1338 	if (tz_menu == NULL)
   1339 		tz_menu = malloc(maxfiles * sizeof *tz_menu);
   1340 	if (tz_names == NULL)
   1341 		tz_names = malloc(maxfiles * sizeof *tz_names);
   1342 	if (tz_menu == NULL || tz_names == NULL)
   1343 		return;	/* error - skip timezone setting */
   1344 	while (nfiles > 0)
   1345 		free(tz_names[--nfiles]);
   1346 
   1347 	dir = opendir(zoneinfo_dir);
   1348 	fp = strchr(zoneinfo_dir, 0);
   1349 	if (fp != zoneinfo_dir + zonerootlen) {
   1350 		tz_names[0] = 0;
   1351 		tz_menu[0].opt_name = msg_string(MSG_tz_back);
   1352 		tz_menu[0].opt_menu = OPT_NOMENU;
   1353 		tz_menu[0].opt_flags = 0;
   1354 		tz_menu[0].opt_action = set_tz_back;
   1355 		nfiles = 1;
   1356 	}
   1357 	maxfname = zoneinfo_dir + sizeof zoneinfo_dir - fp - 1;
   1358 	if (dir != NULL) {
   1359 		while ((dp = readdir(dir)) != NULL) {
   1360 			if (dp->d_namlen > maxfname || dp->d_name[0] == '.')
   1361 				continue;
   1362 			strlcpy(fp, dp->d_name, maxfname);
   1363 			if (stat(zoneinfo_dir, &sb) == -1)
   1364 				continue;
   1365 			if (nfiles >= maxfiles) {
   1366 				p = realloc(tz_menu, 2 * maxfiles * sizeof *tz_menu);
   1367 				if (p == NULL)
   1368 					break;
   1369 				tz_menu = p;
   1370 				p = realloc(tz_names, 2 * maxfiles * sizeof *tz_names);
   1371 				if (p == NULL)
   1372 					break;
   1373 				tz_names = p;
   1374 				maxfiles *= 2;
   1375 			}
   1376 			if (S_ISREG(sb.st_mode))
   1377 				tz_menu[nfiles].opt_action = set_tz_select;
   1378 			else if (S_ISDIR(sb.st_mode)) {
   1379 				tz_menu[nfiles].opt_action = set_tz_dir;
   1380 				strlcat(fp, "/",
   1381 				    sizeof(zoneinfo_dir) - (fp - zoneinfo_dir));
   1382 			} else
   1383 				continue;
   1384 			tz_names[nfiles] = strdup(zoneinfo_dir + zonerootlen);
   1385 			tz_menu[nfiles].opt_name = tz_names[nfiles];
   1386 			tz_menu[nfiles].opt_menu = OPT_NOMENU;
   1387 			tz_menu[nfiles].opt_flags = 0;
   1388 			nfiles++;
   1389 		}
   1390 		closedir(dir);
   1391 	}
   1392 	*fp = 0;
   1393 
   1394 	m->opts = tz_menu;
   1395 	m->numopts = nfiles;
   1396 	qsort(tz_menu, nfiles, sizeof *tz_menu, tz_sort);
   1397 }
   1398 
   1399 void
   1400 get_tz_default(void)
   1401 {
   1402 	char localtime_link[STRSIZE];
   1403 	static char localtime_target[STRSIZE];
   1404 	int rc;
   1405 
   1406 	strlcpy(localtime_link, target_expand("/etc/localtime"),
   1407 	    sizeof localtime_link);
   1408 
   1409 	/* Add sanity check that /mnt/usr/share/zoneinfo contains
   1410 	 * something useful
   1411 	 */
   1412 
   1413 	rc = readlink(localtime_link, localtime_target,
   1414 		      sizeof(localtime_target) - 1);
   1415 	if (rc < 0) {
   1416 		/* error, default to UTC */
   1417 		tz_default = "UTC";
   1418 	} else {
   1419 		localtime_target[rc] = '\0';
   1420 		tz_default = strchr(strstr(localtime_target, "zoneinfo"), '/') + 1;
   1421 	}
   1422 }
   1423 
   1424 /*
   1425  * Choose from the files in usr/share/zoneinfo and set etc/localtime
   1426  */
   1427 int
   1428 set_timezone(void)
   1429 {
   1430 	char localtime_link[STRSIZE];
   1431 	char localtime_target[STRSIZE];
   1432 	time_t t;
   1433 	struct tm *tm;
   1434 	int menu_no;
   1435 
   1436 	strlcpy(zoneinfo_dir, target_expand("/usr/share/zoneinfo/"),
   1437 	    sizeof zoneinfo_dir - 1);
   1438 	zonerootlen = strlen(zoneinfo_dir);
   1439 
   1440 	get_tz_default();
   1441 
   1442 	tz_selected = strdup(tz_default);
   1443 	snprintf(tz_env, sizeof(tz_env), "%s%s", zoneinfo_dir, tz_selected);
   1444 	setenv("TZ", tz_env, 1);
   1445 	t = time(NULL);
   1446 	tm = localtime(&t);
   1447 	msg_display(MSG_choose_timezone,
   1448 		    tz_default, tz_selected, safectime(&t), tm ? tm->tm_zone :
   1449 		    "?");
   1450 
   1451 	signal(SIGALRM, timezone_sig);
   1452 	alarm(60);
   1453 
   1454 	menu_no = new_menu(NULL, NULL, 14, 23, 9,
   1455 			   12, 32, MC_ALWAYS_SCROLL | MC_NOSHORTCUT,
   1456 			   tzm_set_names, NULL, NULL,
   1457 			   "\nPlease consult the install documents.", NULL);
   1458 	if (menu_no < 0)
   1459 		goto done;	/* error - skip timezone setting */
   1460 
   1461 	process_menu(menu_no, NULL);
   1462 
   1463 	free_menu(menu_no);
   1464 
   1465 	signal(SIGALRM, SIG_IGN);
   1466 
   1467 	snprintf(localtime_target, sizeof(localtime_target),
   1468 		 "/usr/share/zoneinfo/%s", tz_selected);
   1469 	strlcpy(localtime_link, target_expand("/etc/localtime"),
   1470 	    sizeof localtime_link);
   1471 	unlink(localtime_link);
   1472 	symlink(localtime_target, localtime_link);
   1473 
   1474 done:
   1475 	return 1;
   1476 }
   1477 
   1478 void
   1479 scripting_vfprintf(FILE *f, const char *fmt, va_list ap)
   1480 {
   1481 
   1482 	if (f)
   1483 		(void)vfprintf(f, fmt, ap);
   1484 	if (script)
   1485 		(void)vfprintf(script, fmt, ap);
   1486 }
   1487 
   1488 void
   1489 scripting_fprintf(FILE *f, const char *fmt, ...)
   1490 {
   1491 	va_list ap;
   1492 
   1493 	va_start(ap, fmt);
   1494 	scripting_vfprintf(f, fmt, ap);
   1495 	va_end(ap);
   1496 }
   1497 
   1498 void
   1499 add_rc_conf(const char *fmt, ...)
   1500 {
   1501 	FILE *f;
   1502 	va_list ap;
   1503 
   1504 	va_start(ap, fmt);
   1505 	f = target_fopen("/etc/rc.conf", "a");
   1506 	if (f != 0) {
   1507 		scripting_fprintf(NULL, "cat <<EOF >>%s/etc/rc.conf\n",
   1508 		    target_prefix());
   1509 		scripting_vfprintf(f, fmt, ap);
   1510 		fclose(f);
   1511 		scripting_fprintf(NULL, "EOF\n");
   1512 	}
   1513 	va_end(ap);
   1514 }
   1515 
   1516 int
   1517 del_rc_conf(const char *value)
   1518 {
   1519 	FILE *fp, *nfp;
   1520 	char buf[4096]; /* Ridiculously high, but should be enough in any way */
   1521 	char *rcconf, *tempname = NULL, *bakname = NULL;
   1522 	char *cp;
   1523 	int done = 0;
   1524 	int fd;
   1525 	int retval = 0;
   1526 
   1527 	/* The paths might seem strange, but using /tmp would require copy instead
   1528 	 * of rename operations. */
   1529 	if (asprintf(&rcconf, "%s", target_expand("/etc/rc.conf")) < 0
   1530 			|| asprintf(&tempname, "%s", target_expand("/etc/rc.conf.tmp.XXXXXX")) < 0
   1531 			|| asprintf(&bakname, "%s", target_expand("/etc/rc.conf.bak.XXXXXX")) < 0) {
   1532 		if (rcconf)
   1533 			free(rcconf);
   1534 		if (tempname)
   1535 			free(tempname);
   1536 		msg_display(MSG_rcconf_delete_failed, value);
   1537 		process_menu(MENU_ok, NULL);
   1538 		return -1;
   1539 	}
   1540 
   1541 	if ((fd = mkstemp(bakname)) < 0) {
   1542 		msg_display(MSG_rcconf_delete_failed, value);
   1543 		process_menu(MENU_ok, NULL);
   1544 		return -1;
   1545 	}
   1546 	close(fd);
   1547 
   1548 	if (!(fp = fopen(rcconf, "r+")) || (fd = mkstemp(tempname)) < 0) {
   1549 		if (fp)
   1550 			fclose(fp);
   1551 		msg_display(MSG_rcconf_delete_failed, value);
   1552 		process_menu(MENU_ok, NULL);
   1553 		return -1;
   1554 	}
   1555 
   1556 	nfp = fdopen(fd, "w");
   1557 	if (!nfp) {
   1558 		fclose(fp);
   1559 		close(fd);
   1560 		msg_display(MSG_rcconf_delete_failed, value);
   1561 		process_menu(MENU_ok, NULL);
   1562 		return -1;
   1563 	}
   1564 
   1565 	while (fgets(buf, sizeof buf, fp) != NULL) {
   1566 
   1567 		cp = buf + strspn(buf, " \t"); /* Skip initial spaces */
   1568 		if (strncmp(cp, value, strlen(value)) == 0) {
   1569 			cp += strlen(value);
   1570 			if (*cp != '=')
   1571 				scripting_fprintf(nfp, "%s", buf);
   1572 			else
   1573 				done = 1;
   1574 		} else {
   1575 			scripting_fprintf(nfp, "%s", buf);
   1576 		}
   1577 	}
   1578 	fclose(fp);
   1579 	fclose(nfp);
   1580 
   1581 	if (done) {
   1582 		if (rename(rcconf, bakname)) {
   1583 			msg_display(MSG_rcconf_backup_failed);
   1584 			if (!ask_noyes(NULL)) {
   1585 				retval = -1;
   1586 				goto done;
   1587 			}
   1588 		}
   1589 
   1590 		if (rename(tempname, rcconf)) {
   1591 			if (rename(bakname, rcconf)) {
   1592 				msg_display(MSG_rcconf_restore_failed);
   1593 				process_menu(MENU_ok, NULL);
   1594 			} else {
   1595 				msg_display(MSG_rcconf_delete_failed, value);
   1596 				process_menu(MENU_ok, NULL);
   1597 			}
   1598 		} else {
   1599 			(void)unlink(bakname);
   1600 		}
   1601 	}
   1602 
   1603 done:
   1604 	(void)unlink(tempname);
   1605 	free(rcconf);
   1606 	free(tempname);
   1607 	free(bakname);
   1608 	return retval;
   1609 }
   1610 
   1611 void
   1612 add_sysctl_conf(const char *fmt, ...)
   1613 {
   1614 	FILE *f;
   1615 	va_list ap;
   1616 
   1617 	va_start(ap, fmt);
   1618 	f = target_fopen("/etc/sysctl.conf", "a");
   1619 	if (f != 0) {
   1620 		scripting_fprintf(NULL, "cat <<EOF >>%s/etc/sysctl.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 void
   1630 enable_rc_conf(void)
   1631 {
   1632 
   1633 	replace("/etc/rc.conf", "s/^rc_configured=NO/rc_configured=YES/");
   1634 }
   1635 
   1636 int
   1637 check_lfs_progs(void)
   1638 {
   1639 
   1640 #ifndef NO_LFS
   1641 	return binary_available("fsck_lfs") && binary_available("mount_lfs")
   1642 	    && binary_available("newfs_lfs");
   1643 #else
   1644 	return 0;
   1645 #endif
   1646 }
   1647 
   1648 int
   1649 set_is_source(const char *set_name) {
   1650 	int len = strlen(set_name);
   1651 	return len >= 3 && memcmp(set_name + len - 3, "src", 3) == 0;
   1652 }
   1653 
   1654 const char *
   1655 set_dir_for_set(const char *set_name) {
   1656 	if (strcmp(set_name, "pkgsrc") == 0)
   1657 		return pkgsrc_dir;
   1658 	return set_is_source(set_name) ? set_dir_src : set_dir_bin;
   1659 }
   1660 
   1661 const char *
   1662 ext_dir_for_set(const char *set_name) {
   1663 	if (strcmp(set_name, "pkgsrc") == 0)
   1664 		return ext_dir_pkgsrc;
   1665 	return set_is_source(set_name) ? ext_dir_src : ext_dir_bin;
   1666 }
   1667 
   1668 void
   1669 do_coloring(unsigned int fg, unsigned int bg) {
   1670 	if (bg > COLOR_WHITE)
   1671 		bg = COLOR_BLUE;
   1672 	if (fg > COLOR_WHITE)
   1673 		fg = COLOR_WHITE;
   1674 	if (fg != bg && has_colors()) {
   1675 		init_pair(1, fg, bg);
   1676 		wbkgd(stdscr, COLOR_PAIR(1));
   1677 		wbkgd(mainwin, COLOR_PAIR(1));
   1678 		wattrset(stdscr, COLOR_PAIR(1));
   1679 		wattrset(mainwin, COLOR_PAIR(1));
   1680 	}
   1681 	/* redraw screen */
   1682 	touchwin(stdscr);
   1683 	touchwin(mainwin);
   1684 	wrefresh(stdscr);
   1685 	wrefresh(mainwin);
   1686 	return;
   1687 }
   1688 
   1689 int
   1690 set_menu_select(menudesc *m, void *arg)
   1691 {
   1692 	*(int *)arg = m->cursel;
   1693 	return 1;
   1694 }
   1695 
   1696 /*
   1697  * check wether a binary is available somewhere in PATH,
   1698  * return 1 if found, 0 if not.
   1699  */
   1700 int
   1701 binary_available(const char *prog)
   1702 {
   1703         char *p, tmp[MAXPATHLEN], *path = getenv("PATH"), *opath;
   1704 
   1705         if (path == NULL)
   1706                 return access(prog, X_OK) == 0;
   1707         path = strdup(path);
   1708         if (path == NULL)
   1709                 return 0;
   1710 
   1711 	opath = path;
   1712 
   1713         while ((p = strsep(&path, ":")) != NULL) {
   1714                 if (strlcpy(tmp, p, MAXPATHLEN) >= MAXPATHLEN)
   1715                         continue;
   1716                 if (strlcat(tmp, "/", MAXPATHLEN) >= MAXPATHLEN)
   1717                         continue;
   1718                 if (strlcat(tmp, prog, MAXPATHLEN) >= MAXPATHLEN)
   1719                         continue;
   1720                 if (access(tmp, X_OK) == 0) {
   1721                         free(opath);
   1722                         return 1;
   1723                 }
   1724         }
   1725         free(opath);
   1726         return 0;
   1727 }
   1728 
   1729 const char *
   1730 safectime(time_t *t)
   1731 {
   1732 	const char *s = ctime(t);
   1733 	if (s != NULL)
   1734 		return s;
   1735 
   1736 	// Debugging.
   1737 	fprintf(stderr, "Can't convert to localtime 0x%jx (%s)\n",
   1738 	    (intmax_t)*t, strerror(errno));
   1739 	      /*123456789012345678901234*/
   1740 	return "preposterous clock time\n";
   1741 }
   1742 
   1743 int
   1744 ask_yesno(const char* msgtxt)
   1745 {
   1746 	arg_rv p;
   1747 
   1748 	p.arg = __UNCONST(msgtxt);
   1749 	p.rv = -1;
   1750 
   1751 	process_menu(MENU_yesno, &p);
   1752 	return p.rv;
   1753 }
   1754 
   1755 int
   1756 ask_noyes(const char *msgtxt)
   1757 {
   1758 	arg_rv p;
   1759 
   1760 	p.arg = __UNCONST(msgtxt);
   1761 	p.rv = -1;
   1762 
   1763 	process_menu(MENU_noyes, &p);
   1764 	return p.rv;
   1765 }
   1766 
   1767 bool
   1768 use_tgz_for_set(const char *set_name)
   1769 {
   1770 	const struct distinfo *dist;
   1771 
   1772 	for (dist = dist_list; dist->set != SET_LAST; dist++) {
   1773 		if (dist->name == NULL)
   1774 			continue;
   1775 		if (strcmp(set_name, dist->name) == 0)
   1776 			return dist->force_tgz;
   1777 	}
   1778 
   1779 	return true;
   1780 }
   1781 
   1782 /* Return the postfix used for a given set */
   1783 const char *
   1784 set_postfix(const char *set_name)
   1785 {
   1786 	return use_tgz_for_set(set_name) ? dist_tgz_postfix : dist_postfix;
   1787 }
   1788 
   1789