xref: /netbsd-src/usr.sbin/sysinst/target.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*	$NetBSD: target.c,v 1.15 2021/01/31 22:45:47 rillig 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.15 2021/01/31 22:45:47 rillig 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/sysctl.h>
87 #include <sys/stat.h>			/* stat() */
88 #include <sys/mount.h>			/* statfs() */
89 
90 #include <fcntl.h>
91 #include <stdio.h>
92 #include <stdarg.h>
93 #include <unistd.h>
94 #include <curses.h>			/* defines TRUE, but checks  */
95 #include <errno.h>
96 
97 
98 #include "defs.h"
99 #include "md.h"
100 #include "msg_defs.h"
101 #include "menu_defs.h"
102 
103 /*
104  * local  prototypes
105  */
106 
107 static void make_prefixed_dir (const char *prefix, const char *path);
108 static int do_target_chdir (const char *dir, int flag);
109 int	target_test(unsigned int mode, const char *path);
110 int	target_test_dir (const char *path);	/* deprecated */
111 int	target_test_file (const char *path);	/* deprecated */
112 int	target_test_symlink (const char *path);	/* deprecated */
113 
114 void unwind_mounts(void);
115 
116 /* Record a mount for later unwinding of target mounts. */
117 struct unwind_mount {
118 	struct unwind_mount *um_prev;
119 	char um_mountpoint[4];		/* Allocated longer... */
120 };
121 
122 /* Unwind-mount stack */
123 struct unwind_mount *unwind_mountlist = NULL;
124 
125 /*
126  * Debugging options
127  */
128 /*#define DEBUG_ROOT*/		/* turn on what-is-root? debugging. */
129 /*#define DEBUG_UNWIND*/	/* turn on unwind-target-mount debugging. */
130 
131 /*
132  * debugging helper. curses...
133  */
134 #if defined(DEBUG)  ||	defined(DEBUG_ROOT)
135 void
136 backtowin(void)
137 {
138 
139 	fflush(stdout);	/* curses does not leave stdout linebuffered. */
140 	getchar();	/* wait for user to press return */
141 	wrefresh(stdscr);
142 }
143 #endif
144 
145 
146 /*
147  * Is the root partition we're running from the same as the root
148  * which the user has selected to install/upgrade?
149  * Uses global variable "pm->diskdev" to find the selected device for
150  * install/upgrade.
151  */
152 int
153 target_already_root(void)
154 {
155 	char dev[PATH_MAX];
156 	int rootpart = -1;
157 	static struct pm_devs *last_pm;
158 	static int last_res;
159 	part_id ptn;
160 	struct disk_partitions *parts, *inner;
161 	struct disk_part_info info;
162 
163 	if (pm == NULL)
164 		return 1;
165 
166 	if (pm == last_pm)
167 		return last_res;
168 
169 	if (pm->cur_system)
170 		return 1;
171 
172 	last_pm = pm;
173 	last_res = 0;
174 
175 	parts = pm->parts;
176 	if (parts == NULL) {
177 		last_res = 0;
178 		return 0;
179 	}
180 
181 	if (pm->no_part) {
182 		last_res = is_active_rootpart(pm->diskdev, -1);
183 		return last_res;
184 	}
185 
186 	if (pm->parts->pscheme->secondary_partitions != NULL) {
187 		inner = pm->parts->pscheme->secondary_partitions(parts,
188 		    pm->ptstart, false);
189 		if (inner != NULL)
190 			parts = inner;
191 	}
192 
193 	for (ptn = 0; ptn < parts->num_part; ptn++) {
194 		if (!parts->pscheme->get_part_info(parts, ptn, &info))
195 			continue;
196 		if (info.nat_type->generic_ptype != PT_root)
197 			continue;
198 		if (!is_root_part_mount(info.last_mounted))
199 			continue;
200 		if (!parts->pscheme->get_part_device(parts, ptn,
201 		    dev, sizeof dev, &rootpart, plain_name, false, true))
202 			continue;
203 
204 		last_res = is_active_rootpart(dev, rootpart);
205 		break;
206  	}
207 
208 	return last_res;
209 }
210 
211 /*
212  * Could something with this "last mounted on" information be a potential
213  * root partition?
214  */
215 bool
216 is_root_part_mount(const char *last_mounted)
217 {
218 	if (last_mounted == NULL)
219 		return false;
220 
221 	return strcmp(last_mounted, "/") == 0 ||
222 	    strcmp(last_mounted, "/targetroot") == 0 ||
223 	    strcmp(last_mounted, "/altroot") == 0;
224 }
225 
226 /*
227  * Is this device partition (e.g., "sd0a") mounted as root?
228  */
229 int
230 is_active_rootpart(const char *dev, int ptn)
231 {
232 	int mib[2];
233 	char rootdev[SSTRSIZE];
234 	int rootptn;
235 	size_t varlen;
236 
237 	mib[0] = CTL_KERN;
238 	mib[1] = KERN_ROOT_DEVICE;
239 	varlen = sizeof(rootdev);
240 	if (sysctl(mib, 2, rootdev, &varlen, NULL, 0) < 0)
241 		return 1;
242 
243 	if (strcmp(dev, rootdev) != 0)
244 		return 0;
245 
246 	if (ptn < 0)
247 		return 1;	/* device only check, or wedge */
248 
249 	mib[1] = KERN_ROOT_PARTITION;
250 	varlen = sizeof rootptn;
251 	rootptn = -1;
252 	if (sysctl(mib, 2, &rootptn, &varlen, NULL, 0) < 0)
253 		return 1;
254 
255 	return ptn == rootptn;
256 }
257 
258 /*
259  * Pathname  prefixing glue to support installation either
260  * from in-ramdisk miniroots or on-disk diskimages.
261  * If our root is on the target disk, the install target is mounted
262  * on /targetroot and we need to prefix installed pathnames with /targetroot.
263  * otherwise we are installing to the currently-active root and
264  * no prefix is needed.
265  */
266 const char *
267 target_prefix(void)
268 {
269 	/*
270 	 * XXX fetch sysctl variable for current root, and compare
271 	 * to the devicename of the install target disk.
272 	 */
273 	return(target_already_root() ? "" : targetroot_mnt);
274 }
275 
276 /*
277  * concatenate two pathnames.
278  * XXX returns either input args or result in a static buffer.
279  * The caller must copy if it wants to use the pathname past the
280  * next call to a target-prefixing function, or to modify the inputs.
281  * Used only internally so this is probably safe.
282  */
283 const char *
284 concat_paths(const char *prefix, const char *suffix)
285 {
286 	static char real_path[MAXPATHLEN];
287 
288 	/* absolute prefix and null suffix? */
289 	if (prefix[0] == '/' && suffix[0] == 0)
290 		return prefix;
291 
292 	/* null prefix and absolute suffix? */
293 	if (prefix[0] == 0 && suffix[0] == '/')
294 		return suffix;
295 
296 	/* avoid "//" */
297 	if (suffix[0] == '/' || suffix[0] == 0)
298 		snprintf(real_path, sizeof(real_path), "%s%s", prefix, suffix);
299 	else
300 		snprintf(real_path, sizeof(real_path), "%s/%s",
301 		    prefix, suffix);
302 	return (real_path);
303 }
304 
305 /*
306  * Do target prefix expansion on a pathname.
307  * XXX uses concat_paths and so returns result in a static buffer.
308  * The caller must copy if it wants to use the pathname past the
309  * next call to a target-prefixing function, or to modify the inputs.
310  * Used only internally so this is probably safe.
311  *
312  * Not static so other functions can generate target related file names.
313  */
314 const char *
315 target_expand(const char *tgtpath)
316 {
317 
318 	return concat_paths(target_prefix(), tgtpath);
319 }
320 
321 /* Make a directory, with a prefix like "/targetroot" or possibly just "". */
322 static void
323 make_prefixed_dir(const char *prefix, const char *path)
324 {
325 
326 	run_program(0, "/bin/mkdir -p %s", concat_paths(prefix, path));
327 }
328 
329 /* Make a directory with a pathname relative to the installation target. */
330 void
331 make_target_dir(const char *path)
332 {
333 
334 	make_prefixed_dir(target_prefix(), path);
335 }
336 
337 
338 static int
339 do_target_chdir(const char *dir, int must_succeed)
340 {
341 	const char *tgt_dir;
342 	int error;
343 
344 	error = 0;
345 	tgt_dir = target_expand(dir);
346 
347 #ifdef DEBUG
348 	printf("target_chdir (%s)\n", tgt_dir);
349 	//return (0);
350 #endif
351 	/* chdir returns -1 on error and sets errno. */
352 	if (chdir(tgt_dir) < 0)
353 		error = errno;
354 	if (logfp) {
355 		fprintf(logfp, "cd to %s\n", tgt_dir);
356 		fflush(logfp);
357 	}
358 	if (script) {
359 		scripting_fprintf(NULL, "cd %s\n", tgt_dir);
360 		fflush(script);
361 	}
362 
363 	if (error && must_succeed) {
364 		const char *args[] = { target_prefix(), strerror(error) };
365 		char *err = str_arg_subst(msg_string(MSG_realdir),
366 		    __arraycount(args), args);
367 		fprintf(stderr, "%s\n", err);
368 		if (logfp)
369 			fprintf(logfp, "%s\n", err);
370 		free(err);
371 		exit(1);
372 	}
373 	errno = error;
374 	return (error);
375 }
376 
377 void
378 target_chdir_or_die(const char *dir)
379 {
380 
381 	(void)do_target_chdir(dir, 1);
382 }
383 
384 #ifdef notdef
385 int
386 target_chdir(const char *dir)
387 {
388 
389 	return do_target_chdir(dir, 0);
390 }
391 #endif
392 
393 /*
394  * Copy a file from the current root into the target system,
395  * where the  destination pathname is relative to the target root.
396  * Does not check for copy-to-self when target is  current root.
397  */
398 int
399 cp_to_target(const char *srcpath, const char *tgt_path)
400 {
401 	const char *real_path = target_expand(tgt_path);
402 
403 	return run_program(0, "/bin/cp %s %s", srcpath, real_path);
404 }
405 
406 /*
407  * Duplicate a file from the current root to the same pathname
408  * in the target system.  Pathname must be an absolute pathname.
409  * If we're running in the target, do nothing.
410  */
411 void
412 dup_file_into_target(const char *filename)
413 {
414 
415 	if (!target_already_root())
416 		cp_to_target(filename, filename);
417 }
418 
419 
420 /*
421  * Do a mv where both pathnames are within the target filesystem.
422  */
423 void
424 mv_within_target_or_die(const char *frompath, const char *topath)
425 {
426 	char realfrom[STRSIZE];
427 	char realto[STRSIZE];
428 
429 	strlcpy(realfrom, target_expand(frompath), sizeof realfrom);
430 	strlcpy(realto, target_expand(topath), sizeof realto);
431 
432 	run_program(RUN_FATAL, "mv %s %s", realfrom, realto);
433 }
434 
435 /* Do a cp where both pathnames are within the target filesystem. */
436 int
437 cp_within_target(const char *frompath, const char *topath, int optional)
438 {
439 	char realfrom[STRSIZE];
440 	char realto[STRSIZE];
441 
442 	strlcpy(realfrom, target_expand(frompath), sizeof realfrom);
443 	strlcpy(realto, target_expand(topath), sizeof realto);
444 
445 	if (access(realfrom, R_OK) == -1 && optional)
446 		return 0;
447 	return (run_program(0, "cp -p %s %s", realfrom, realto));
448 }
449 
450 /* fopen a pathname in the target. */
451 FILE *
452 target_fopen(const char *filename, const char *type)
453 {
454 
455 	return fopen(target_expand(filename), type);
456 }
457 
458 /*
459  * Do a mount onto a mountpoint in the install target.
460  * Record mountpoint so we can unmount when finished.
461  * NB: does not prefix mount-from, which probably breaks nullfs mounts.
462  */
463 int
464 target_mount_do(const char *opts, const char *from, const char *on)
465 {
466 	struct unwind_mount *m;
467 	int error;
468 	int len;
469 
470 	len = strlen(on);
471 	m = malloc(sizeof *m + len);
472 	if (m == 0)
473 		return (ENOMEM);	/* XXX */
474 
475 	memcpy(m->um_mountpoint, on, len + 1);
476 
477 #ifdef DEBUG_UNWIND
478 	endwin();
479 	fprintf(stderr, "mounting %s with unwind\n", on);
480 	backtowin();
481 #endif
482 
483 	error = run_program(0, "/sbin/mount %s %s %s%s",
484 			opts, from, target_prefix(), on);
485 	if (error) {
486 		free(m);
487 		return error;
488 	}
489 	m->um_prev = unwind_mountlist;
490 	unwind_mountlist = m;
491 	return 0;
492 }
493 
494 /*
495  * Special case - we have mounted the target / readonly
496  * to peek at etc/fstab, and now want it undone.
497  */
498 void
499 umount_root(void)
500 {
501 
502 	/* verify this is the only mount */
503 	if (unwind_mountlist == NULL)
504 		return;
505 	if (unwind_mountlist->um_prev != NULL)
506 		return;
507 
508 	if (run_program(0, "/sbin/umount %s", target_prefix()) != 0)
509 		return;
510 
511 	free(unwind_mountlist);
512 	unwind_mountlist = NULL;
513 }
514 
515 
516 int
517 target_mount(const char *opts, const char *from, const char *on)
518 {
519 	return target_mount_do(opts, from, on);
520 }
521 
522 /*
523  * unwind the mount stack, unmounting mounted filesystems.
524  * For now, ignore any errors in unmount.
525  * (Why would we be unable to unmount?  The user has suspended
526  *  us and forked shell sitting somewhere in the target root?)
527  */
528 void
529 unwind_mounts(void)
530 {
531 	struct unwind_mount *m;
532 	static volatile int unwind_in_progress = 0;
533 
534 	/* signal safety */
535 	if (unwind_in_progress)
536 		return;
537 	unwind_in_progress = 1;
538 
539 	while ((m = unwind_mountlist) != NULL) {
540 		unwind_mountlist = m->um_prev;
541 #ifdef DEBUG_UNWIND
542 		endwin();
543 		fprintf(stderr, "unmounting %s\n", m->um_mountpoint);
544 		backtowin();
545 #endif
546 		run_program(0, "/sbin/umount %s%s",
547 			target_prefix(), m->um_mountpoint);
548 		free(m);
549 	}
550 	unwind_in_progress = 0;
551 }
552 
553 int
554 target_collect_file(int kind, char **buffer, const char *name)
555 {
556 	const char *realname = target_expand(name);
557 
558 #ifdef	DEBUG
559 	printf("collect real name %s\n", realname);
560 #endif
561 	return collect(kind, buffer, "%s", realname);
562 }
563 
564 /*
565  * Verify a pathname already exists in the target root filesystem,
566  * by running  test "testflag" on the expanded target pathname.
567  */
568 int
569 target_test(unsigned int mode, const char *path)
570 {
571 	const char *real_path = target_expand(path);
572 	register int result;
573 
574 	result = !file_mode_match(real_path, mode);
575 	scripting_fprintf(NULL, "if [ $? != 0 ]; then echo \"%s does not exist!\"; fi\n", real_path);
576 
577 #if defined(DEBUG)
578 	printf("target_test(%o, %s) returning %d\n", mode, real_path, result);
579 #endif
580 	return (result);
581 }
582 
583 /*
584  * Verify a directory already exists in the target root
585  * filesystem. Do not create the directory if it doesn't  exist.
586  * Assumes that sysinst has already mounted the target root.
587  */
588 int
589 target_test_dir(const char *path)
590 {
591 
592  	return target_test(S_IFDIR, path);
593 }
594 
595 /*
596  * Verify an ordinary file already exists in the target root
597  * filesystem. Do not create the directory if it doesn't  exist.
598  * Assumes that sysinst has already mounted the target root.
599  */
600 int
601 target_test_file(const char *path)
602 {
603 
604  	return target_test(S_IFREG, path);
605 }
606 
607 int
608 target_test_symlink(const char *path)
609 {
610 
611  	return target_test(S_IFLNK, path);
612 }
613 
614 int
615 target_file_exists_p(const char *path)
616 {
617 
618 	return (target_test_file(path) == 0);
619 }
620 
621 int
622 target_dir_exists_p(const char *path)
623 {
624 
625 	return (target_test_dir(path) == 0);
626 }
627 
628 int
629 target_symlink_exists_p(const char *path)
630 {
631 
632 	return (target_test_symlink(path) == 0);
633 }
634 
635 int
636 target_mounted(void)
637 {
638 	return (unwind_mountlist != NULL);
639 }
640