1/*	$NetBSD: target.c,v 1.18 2022/02/10 16:11:41 martin Exp $	*/
2
3/*
4 * Copyright 1997 Jonathan Stone
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 *    must display the following acknowledgement:
17 *      This product includes software developed for the NetBSD Project by
18 *      Jonathan Stone.
19 * 4. The name of Jonathan Stone may not be used to endorse
20 *    or promote products derived from this software without specific prior
21 *    written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY JONATHAN STONE ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33 * THE POSSIBILITY OF SUCH DAMAGE.
34 *
35 */
36
37/* Copyright below applies to the realpath() code */
38
39/*
40 * Copyright (c) 1989, 1991, 1993, 1995
41 *      The Regents of the University of California.  All rights reserved.
42 *
43 * This code is derived from software contributed to Berkeley by
44 * Jan-Simon Pendry.
45 *
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
48 * are met:
49 * 1. Redistributions of source code must retain the above copyright
50 *    notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 *    notice, this list of conditions and the following disclaimer in the
53 *    documentation and/or other materials provided with the distribution.
54 * 3. Neither the name of the University nor the names of its contributors
55 *    may be used to endorse or promote products derived from this software
56 *    without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 */
70
71
72#include <sys/cdefs.h>
73#if defined(LIBC_SCCS) && !defined(lint)
74__RCSID("$NetBSD: target.c,v 1.18 2022/02/10 16:11:41 martin Exp $");
75#endif
76
77/*
78 * target.c -- path-prefixing routines to access the target installation
79 *  filesystems. Makes the install tools more independent of whether
80 *  we're installing into a separate filesystem hierarchy mounted under
81 * /targetroot, or into the currently active root mounted on /.
82 */
83
84#include <sys/param.h>			/* XXX vm_param.h always defines TRUE*/
85#include <sys/types.h>
86#include <sys/ioctl.h>
87#include <sys/sysctl.h>
88#include <sys/stat.h>			/* stat() */
89#include <sys/mount.h>			/* statfs() */
90
91#include <fcntl.h>
92#include <stdio.h>
93#include <stdarg.h>
94#include <unistd.h>
95#include <curses.h>			/* defines TRUE, but checks  */
96#include <errno.h>
97#include <util.h>
98
99#include "defs.h"
100#include "md.h"
101#include "msg_defs.h"
102#include "menu_defs.h"
103
104/*
105 * local  prototypes
106 */
107
108static void make_prefixed_dir (const char *prefix, const char *path);
109static int do_target_chdir (const char *dir, int flag);
110int	target_test(unsigned int mode, const char *path);
111int	target_test_dir (const char *path);	/* deprecated */
112int	target_test_file (const char *path);	/* deprecated */
113int	target_test_symlink (const char *path);	/* deprecated */
114
115void unwind_mounts(void);
116
117/* Record a mount for later unwinding of target mounts. */
118struct unwind_mount {
119	struct unwind_mount *um_prev;
120	char um_mountpoint[4];		/* Allocated longer... */
121};
122
123/* Record a wedge for later deletion after all file systems have been unmounted */
124struct umount_delwedge {
125	struct umount_delwedge *next;
126	char disk[DISKNAMESIZE], wedge[DISKNAMESIZE];
127};
128struct umount_delwedge *post_umount_dwlist = NULL;
129
130/* Unwind-mount stack */
131struct unwind_mount *unwind_mountlist = NULL;
132
133/*
134 * Debugging options
135 */
136/*#define DEBUG_ROOT*/		/* turn on what-is-root? debugging. */
137/*#define DEBUG_UNWIND*/	/* turn on unwind-target-mount debugging. */
138
139/*
140 * debugging helper. curses...
141 */
142#if defined(DEBUG)  ||	defined(DEBUG_ROOT)
143void
144backtowin(void)
145{
146
147	fflush(stdout);	/* curses does not leave stdout linebuffered. */
148	getchar();	/* wait for user to press return */
149	wrefresh(stdscr);
150}
151#endif
152
153
154/*
155 * Is the root partition we're running from the same as the root
156 * which the user has selected to install/upgrade?
157 * Uses global variable "pm->diskdev" to find the selected device for
158 * install/upgrade.
159 */
160int
161target_already_root(void)
162{
163	char dev[PATH_MAX];
164	int rootpart = -1;
165	static struct pm_devs *last_pm;
166	static int last_res;
167	part_id ptn;
168	struct disk_partitions *parts, *inner;
169	struct disk_part_info info;
170
171	if (pm == NULL)
172		return 1;
173
174	if (pm == last_pm)
175		return last_res;
176
177	if (pm->cur_system)
178		return 1;
179
180	last_pm = pm;
181	last_res = 0;
182
183	parts = pm->parts;
184	if (parts == NULL) {
185		last_res = 0;
186		return 0;
187	}
188
189	if (pm->no_part) {
190		last_res = is_active_rootpart(pm->diskdev, -1);
191		return last_res;
192	}
193
194	if (pm->parts->pscheme->secondary_partitions != NULL) {
195		inner = pm->parts->pscheme->secondary_partitions(parts,
196		    pm->ptstart, false);
197		if (inner != NULL)
198			parts = inner;
199	}
200
201	for (ptn = 0; ptn < parts->num_part; ptn++) {
202		if (!parts->pscheme->get_part_info(parts, ptn, &info))
203			continue;
204		if (info.nat_type->generic_ptype != PT_root)
205			continue;
206		if (!is_root_part_mount(info.last_mounted))
207			continue;
208		if (!parts->pscheme->get_part_device(parts, ptn,
209		    dev, sizeof dev, &rootpart, plain_name, false, true))
210			continue;
211
212		last_res = is_active_rootpart(dev, rootpart);
213		break;
214 	}
215
216	return last_res;
217}
218
219/*
220 * Could something with this "last mounted on" information be a potential
221 * root partition?
222 */
223bool
224is_root_part_mount(const char *last_mounted)
225{
226	if (last_mounted == NULL)
227		return false;
228
229	return strcmp(last_mounted, "/") == 0 ||
230	    strcmp(last_mounted, "/targetroot") == 0 ||
231	    strcmp(last_mounted, "/altroot") == 0;
232}
233
234/*
235 * Is this device partition (e.g., "sd0a") mounted as root?
236 */
237int
238is_active_rootpart(const char *dev, int ptn)
239{
240	int mib[2];
241	char rootdev[SSTRSIZE];
242	int rootptn;
243	size_t varlen;
244
245	mib[0] = CTL_KERN;
246	mib[1] = KERN_ROOT_DEVICE;
247	varlen = sizeof(rootdev);
248	if (sysctl(mib, 2, rootdev, &varlen, NULL, 0) < 0)
249		return 1;
250
251	if (strcmp(dev, rootdev) != 0)
252		return 0;
253
254	if (ptn < 0)
255		return 1;	/* device only check, or wedge */
256
257	mib[1] = KERN_ROOT_PARTITION;
258	varlen = sizeof rootptn;
259	rootptn = -1;
260	if (sysctl(mib, 2, &rootptn, &varlen, NULL, 0) < 0)
261		return 1;
262
263	return ptn == rootptn;
264}
265
266/*
267 * Pathname  prefixing glue to support installation either
268 * from in-ramdisk miniroots or on-disk diskimages.
269 * If our root is on the target disk, the install target is mounted
270 * on /targetroot and we need to prefix installed pathnames with /targetroot.
271 * otherwise we are installing to the currently-active root and
272 * no prefix is needed.
273 */
274const char *
275target_prefix(void)
276{
277	/*
278	 * XXX fetch sysctl variable for current root, and compare
279	 * to the devicename of the install target disk.
280	 */
281	return(target_already_root() ? "" : targetroot_mnt);
282}
283
284/*
285 * concatenate two pathnames.
286 * XXX returns either input args or result in a static buffer.
287 * The caller must copy if it wants to use the pathname past the
288 * next call to a target-prefixing function, or to modify the inputs.
289 * Used only internally so this is probably safe.
290 */
291const char *
292concat_paths(const char *prefix, const char *suffix)
293{
294	static char real_path[MAXPATHLEN];
295
296	/* absolute prefix and null suffix? */
297	if (prefix[0] == '/' && suffix[0] == 0)
298		return prefix;
299
300	/* null prefix and absolute suffix? */
301	if (prefix[0] == 0 && suffix[0] == '/')
302		return suffix;
303
304	/* avoid "//" */
305	if (suffix[0] == '/' || suffix[0] == 0)
306		snprintf(real_path, sizeof(real_path), "%s%s", prefix, suffix);
307	else
308		snprintf(real_path, sizeof(real_path), "%s/%s",
309		    prefix, suffix);
310	return (real_path);
311}
312
313/*
314 * Do target prefix expansion on a pathname.
315 * XXX uses concat_paths and so returns result in a static buffer.
316 * The caller must copy if it wants to use the pathname past the
317 * next call to a target-prefixing function, or to modify the inputs.
318 * Used only internally so this is probably safe.
319 *
320 * Not static so other functions can generate target related file names.
321 */
322const char *
323target_expand(const char *tgtpath)
324{
325
326	return concat_paths(target_prefix(), tgtpath);
327}
328
329/* Make a directory, with a prefix like "/targetroot" or possibly just "". */
330static void
331make_prefixed_dir(const char *prefix, const char *path)
332{
333
334	run_program(0, "/bin/mkdir -p %s", concat_paths(prefix, path));
335}
336
337/* Make a directory with a pathname relative to the installation target. */
338void
339make_target_dir(const char *path)
340{
341
342	make_prefixed_dir(target_prefix(), path);
343}
344
345
346static int
347do_target_chdir(const char *dir, int must_succeed)
348{
349	const char *tgt_dir;
350	int error;
351
352	error = 0;
353	tgt_dir = target_expand(dir);
354
355#ifdef DEBUG
356	printf("target_chdir (%s)\n", tgt_dir);
357	//return (0);
358#endif
359	/* chdir returns -1 on error and sets errno. */
360	if (chdir(tgt_dir) < 0)
361		error = errno;
362	if (logfp) {
363		fprintf(logfp, "cd to %s\n", tgt_dir);
364		fflush(logfp);
365	}
366	if (script) {
367		scripting_fprintf(NULL, "cd %s\n", tgt_dir);
368		fflush(script);
369	}
370
371	if (error && must_succeed) {
372		const char *args[] = { target_prefix(), strerror(error) };
373		char *err = str_arg_subst(msg_string(MSG_realdir),
374		    __arraycount(args), args);
375		fprintf(stderr, "%s\n", err);
376		if (logfp)
377			fprintf(logfp, "%s\n", err);
378		free(err);
379		exit(1);
380	}
381	errno = error;
382	return (error);
383}
384
385void
386target_chdir_or_die(const char *dir)
387{
388
389	(void)do_target_chdir(dir, 1);
390}
391
392#ifdef notdef
393int
394target_chdir(const char *dir)
395{
396
397	return do_target_chdir(dir, 0);
398}
399#endif
400
401/*
402 * Copy a file from the current root into the target system,
403 * where the  destination pathname is relative to the target root.
404 * Does not check for copy-to-self when target is  current root.
405 */
406int
407cp_to_target(const char *srcpath, const char *tgt_path)
408{
409	const char *real_path = target_expand(tgt_path);
410
411	return run_program(0, "/bin/cp %s %s", srcpath, real_path);
412}
413
414/*
415 * Duplicate a file from the current root to the same pathname
416 * in the target system.  Pathname must be an absolute pathname.
417 * If we're running in the target, do nothing.
418 */
419void
420dup_file_into_target(const char *filename)
421{
422
423	if (!target_already_root())
424		cp_to_target(filename, filename);
425}
426
427
428/*
429 * Do a mv where both pathnames are within the target filesystem.
430 */
431void
432mv_within_target_or_die(const char *frompath, const char *topath)
433{
434	char realfrom[STRSIZE];
435	char realto[STRSIZE];
436
437	strlcpy(realfrom, target_expand(frompath), sizeof realfrom);
438	strlcpy(realto, target_expand(topath), sizeof realto);
439
440	run_program(RUN_FATAL, "mv %s %s", realfrom, realto);
441}
442
443/* Do a cp where both pathnames are within the target filesystem. */
444int
445cp_within_target(const char *frompath, const char *topath, int optional)
446{
447	char realfrom[STRSIZE];
448	char realto[STRSIZE];
449
450	strlcpy(realfrom, target_expand(frompath), sizeof realfrom);
451	strlcpy(realto, target_expand(topath), sizeof realto);
452
453	if (access(realfrom, R_OK) == -1 && optional)
454		return 0;
455	return (run_program(0, "cp -p %s %s", realfrom, realto));
456}
457
458/* fopen a pathname in the target. */
459FILE *
460target_fopen(const char *filename, const char *type)
461{
462
463	return fopen(target_expand(filename), type);
464}
465
466/*
467 * Do a mount onto a mountpoint in the install target.
468 * Record mountpoint so we can unmount when finished.
469 * NB: does not prefix mount-from, which probably breaks nullfs mounts.
470 */
471int
472target_mount_do(const char *opts, const char *from, const char *on)
473{
474	struct unwind_mount *m;
475	int error;
476	int len;
477
478	len = strlen(on);
479	m = malloc(sizeof *m + len);
480	if (m == 0)
481		return (ENOMEM);	/* XXX */
482
483	memcpy(m->um_mountpoint, on, len + 1);
484
485#ifdef DEBUG_UNWIND
486	endwin();
487	fprintf(stderr, "mounting %s with unwind\n", on);
488	backtowin();
489#endif
490
491	error = run_program(0, "/sbin/mount %s %s %s%s",
492			opts, from, target_prefix(), on);
493	if (error) {
494		free(m);
495		return error;
496	}
497	m->um_prev = unwind_mountlist;
498	unwind_mountlist = m;
499	return 0;
500}
501
502/*
503 * Special case - we have mounted the target / readonly
504 * to peek at etc/fstab, and now want it undone.
505 */
506void
507umount_root(void)
508{
509
510	/* verify this is the only mount */
511	if (unwind_mountlist == NULL)
512		return;
513	if (unwind_mountlist->um_prev != NULL)
514		return;
515
516	if (run_program(0, "/sbin/umount %s", target_prefix()) != 0)
517		return;
518
519	free(unwind_mountlist);
520	unwind_mountlist = NULL;
521}
522
523
524int
525target_mount(const char *opts, const char *from, const char *on)
526{
527	return target_mount_do(opts, from, on);
528}
529
530int
531target_unmount(const char *mount_point)
532{
533	struct unwind_mount *m, *prev = NULL;
534	int error;
535
536	for (m = unwind_mountlist; m != NULL; prev = m, m = m->um_prev)
537		if (strcmp(m->um_mountpoint, mount_point) == 0)
538			break;
539
540	if (m == NULL)
541		return ENOTDIR;
542
543	error = run_program(0, "/sbin/umount %s%s",
544		    target_prefix(), m->um_mountpoint);
545	if (error)
546		return error;
547
548	if (m == unwind_mountlist)
549		unwind_mountlist = m->um_prev;
550	else
551		prev->um_prev = m->um_prev;
552	free(m);
553
554	return 0;
555}
556
557static bool
558delete_wedge(const char *disk, const char *wedge)
559{
560	struct dkwedge_info dkw;
561	char diskpath[MAXPATHLEN];
562	int fd, error;
563
564	fd = opendisk(disk, O_RDWR, diskpath, sizeof(diskpath), 0);
565	if (fd < 0)
566		return false;
567	memset(&dkw, 0, sizeof(dkw));
568	strlcpy(dkw.dkw_devname, wedge, sizeof(dkw.dkw_devname));
569	error = ioctl(fd, DIOCDWEDGE, &dkw);
570	close(fd);
571	return error == 0;
572}
573
574void
575register_post_umount_delwedge(const char *disk, const char *wedge)
576{
577	struct umount_delwedge *dw;
578
579	if (unwind_mountlist == NULL) {
580		/* we have nothing mounted, can delete it right now */
581		delete_wedge(disk, wedge);
582		return;
583	}
584
585	dw = calloc(1, sizeof(*dw));
586	dw->next = post_umount_dwlist;
587	strlcpy(dw->disk, disk, sizeof(dw->disk));
588	strlcpy(dw->wedge, wedge, sizeof(dw->wedge));
589	post_umount_dwlist = dw;
590}
591
592/*
593 * unwind the mount stack, unmounting mounted filesystems.
594 * For now, ignore any errors in unmount.
595 * (Why would we be unable to unmount?  The user has suspended
596 *  us and forked shell sitting somewhere in the target root?)
597 */
598void
599unwind_mounts(void)
600{
601	struct unwind_mount *m;
602	struct umount_delwedge *dw;
603	static volatile int unwind_in_progress = 0;
604
605	/* signal safety */
606	if (unwind_in_progress)
607		return;
608	unwind_in_progress = 1;
609
610	while ((m = unwind_mountlist) != NULL) {
611		unwind_mountlist = m->um_prev;
612#ifdef DEBUG_UNWIND
613		endwin();
614		fprintf(stderr, "unmounting %s\n", m->um_mountpoint);
615		backtowin();
616#endif
617		run_program(0, "/sbin/umount %s%s",
618			target_prefix(), m->um_mountpoint);
619		free(m);
620	}
621	while ((dw = post_umount_dwlist) != NULL) {
622		post_umount_dwlist = dw->next;
623		delete_wedge(dw->disk, dw->wedge);
624		free(dw);
625	}
626	unwind_in_progress = 0;
627}
628
629int
630target_collect_file(int kind, char **buffer, const char *name)
631{
632	const char *realname = target_expand(name);
633
634#ifdef	DEBUG
635	printf("collect real name %s\n", realname);
636#endif
637	return collect(kind, buffer, "%s", realname);
638}
639
640/*
641 * Verify a pathname already exists in the target root filesystem,
642 * by running  test "testflag" on the expanded target pathname.
643 */
644int
645target_test(unsigned int mode, const char *path)
646{
647	const char *real_path = target_expand(path);
648	register int result;
649
650	result = !file_mode_match(real_path, mode);
651	scripting_fprintf(NULL, "if [ $? != 0 ]; then echo \"%s does not exist!\"; fi\n", real_path);
652
653#if defined(DEBUG)
654	printf("target_test(%o, %s) returning %d\n", mode, real_path, result);
655#endif
656	return (result);
657}
658
659/*
660 * Verify a directory already exists in the target root
661 * filesystem. Do not create the directory if it doesn't  exist.
662 * Assumes that sysinst has already mounted the target root.
663 */
664int
665target_test_dir(const char *path)
666{
667
668 	return target_test(S_IFDIR, path);
669}
670
671/*
672 * Verify an ordinary file already exists in the target root
673 * filesystem. Do not create the directory if it doesn't  exist.
674 * Assumes that sysinst has already mounted the target root.
675 */
676int
677target_test_file(const char *path)
678{
679
680 	return target_test(S_IFREG, path);
681}
682
683int
684target_test_symlink(const char *path)
685{
686
687 	return target_test(S_IFLNK, path);
688}
689
690int
691target_file_exists_p(const char *path)
692{
693
694	return (target_test_file(path) == 0);
695}
696
697int
698target_dir_exists_p(const char *path)
699{
700
701	return (target_test_dir(path) == 0);
702}
703
704int
705target_symlink_exists_p(const char *path)
706{
707
708	return (target_test_symlink(path) == 0);
709}
710
711int
712target_mounted(void)
713{
714	return (unwind_mountlist != NULL);
715}
716