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