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