xref: /netbsd-src/usr.sbin/installboot/installboot.c (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
1 /*	$NetBSD: installboot.c,v 1.40 2019/05/07 05:02:42 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn of Wasabi Systems.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
35 
36 #include <sys/cdefs.h>
37 #if !defined(__lint)
38 __RCSID("$NetBSD: installboot.c,v 1.40 2019/05/07 05:02:42 thorpej Exp $");
39 #endif	/* !__lint */
40 
41 #include <sys/param.h>
42 #include <sys/ioctl.h>
43 #include <sys/utsname.h>
44 
45 #include <assert.h>
46 #include <err.h>
47 #include <fcntl.h>
48 #include <limits.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <stddef.h>
52 #include <string.h>
53 #include <unistd.h>
54 #if !HAVE_NBTOOL_CONFIG_H
55 #include <util.h>
56 #endif
57 
58 #include "installboot.h"
59 #include "evboards.h"
60 
61 static	void	getmachine(ib_params *, const char *, const char *);
62 static	void	getfstype(ib_params *, const char *, const char *);
63 static	void	parseoptions(ib_params *, const char *);
64 __dead static	void	usage(void);
65 static	void	options_usage(void);
66 static	void	machine_usage(void);
67 static	void	fstype_usage(void);
68 
69 static	ib_params	installboot_params;
70 
71 #define OFFSET(field)    offsetof(ib_params, field)
72 const struct option {
73 	const char	*name;		/* Name of option */
74 	ib_flags	flag;		/* Corresponding IB_xxx flag */
75 	enum {				/* Type of option value... */
76 		OPT_BOOL,		/* no value */
77 		OPT_INT,		/* numeric value */
78 		OPT_WORD,		/* space/tab/, terminated */
79 		OPT_STRING		/* null terminated */
80 	}		type;
81 	int		offset;		/* of field in ib_params */
82 } options[] = {
83 	{ "alphasum",	IB_ALPHASUM,	OPT_BOOL,	0 },
84 	{ "append",	IB_APPEND,	OPT_BOOL,	0 },
85 	{ "command",	IB_COMMAND,	OPT_STRING,	OFFSET(command) },
86 	{ "console",	IB_CONSOLE,	OPT_WORD,	OFFSET(console) },
87 	{ "ioaddr",	IB_CONSADDR,	OPT_INT,	OFFSET(consaddr) },
88 	{ "keymap",	IB_KEYMAP,	OPT_WORD,	OFFSET(keymap) },
89 	{ "password",	IB_PASSWORD,	OPT_WORD,	OFFSET(password) },
90 	{ "resetvideo",	IB_RESETVIDEO,	OPT_BOOL,	0 },
91 	{ "speed",	IB_CONSPEED,	OPT_INT,	OFFSET(conspeed) },
92 	{ "sunsum",	IB_SUNSUM,	OPT_BOOL,	0 },
93 	{ "timeout",	IB_TIMEOUT,	OPT_INT,	OFFSET(timeout) },
94 	{ "modules",	IB_MODULES,	OPT_BOOL,	0 },
95 	{ "bootconf",	IB_BOOTCONF,	OPT_BOOL,	0 },
96 	{ "board",	IB_BOARD,	OPT_STRING,	OFFSET(board) },
97 	{ "dtb",	IB_DTB,		OPT_STRING,	OFFSET(dtb) },
98 	{ "media",	IB_MEDIA,	OPT_WORD,	OFFSET(media) },
99 	{ .name = NULL },
100 };
101 #undef OFFSET
102 #define OPTION(params, type, opt) (*(type *)((char *)(params) + (opt)->offset))
103 
104 #define DFL_SECSIZE	512	/* Don't use DEV_BSIZE. It's host's value. */
105 
106 int
107 main(int argc, char *argv[])
108 {
109 	struct utsname	utsname;
110 	ib_params	*params;
111 	unsigned long	lval;
112 	int		ch, rv, mode;
113 	char 		*p;
114 	const char	*op;
115 	ib_flags	unsupported_flags;
116 #if !HAVE_NBTOOL_CONFIG_H
117 	char		specname[MAXPATHLEN];
118 	char		rawname[MAXPATHLEN];
119 	const char	*special, *raw;
120 #endif
121 
122 	setprogname(argv[0]);
123 	params = &installboot_params;
124 	memset(params, 0, sizeof(*params));
125 	params->fsfd = -1;
126 	params->s1fd = -1;
127 	if ((p = getenv("MACHINE")) != NULL)
128 		getmachine(params, p, "$MACHINE");
129 
130 	while ((ch = getopt(argc, argv, "b:B:cefm:no:t:v")) != -1) {
131 		switch (ch) {
132 
133 		case 'b':
134 		case 'B':
135 			if (*optarg == '\0')
136 				goto badblock;
137 			lval = strtoul(optarg, &p, 0);
138 			if (lval > UINT32_MAX || *p != '\0') {
139  badblock:
140 				errx(1, "Invalid block number `%s'", optarg);
141 			}
142 			if (ch == 'b') {
143 				params->s1start = (uint32_t)lval;
144 				params->flags |= IB_STAGE1START;
145 			} else {
146 				params->s2start = (uint32_t)lval;
147 				params->flags |= IB_STAGE2START;
148 			}
149 			break;
150 
151 		case 'c':
152 			params->flags |= IB_CLEAR;
153 			break;
154 
155 		case 'e':
156 			params->flags |= IB_EDIT;
157 			break;
158 
159 		case 'f':
160 			params->flags |= IB_FORCE;
161 			break;
162 
163 		case 'm':
164 			getmachine(params, optarg, "-m");
165 			break;
166 
167 		case 'n':
168 			params->flags |= IB_NOWRITE;
169 			break;
170 
171 		case 'o':
172 			parseoptions(params, optarg);
173 			break;
174 
175 		case 't':
176 			getfstype(params, optarg, "-t");
177 			break;
178 
179 		case 'v':
180 			params->flags |= IB_VERBOSE;
181 			break;
182 
183 		case '?':
184 		default:
185 			usage();
186 			/* NOTREACHED */
187 
188 		}
189 	}
190 	argc -= optind;
191 	argv += optind;
192 
193 	if (params->flags & IB_CLEAR && params->flags & IB_EDIT)
194 		usage();
195 	if (argc < 1 || argc + 2 * !!(params->flags & (IB_CLEAR | IB_EDIT)) > 3)
196 		usage();
197 
198 	/* set missing defaults */
199 	if (params->machine == NULL) {
200 		if (uname(&utsname) == -1)
201 			err(1, "Determine uname");
202 		getmachine(params, utsname.machine, "uname()");
203 	}
204 
205 	/* Check that options are supported by this system */
206 	unsupported_flags = params->flags & ~params->machine->valid_flags;
207 	unsupported_flags &= ~(IB_VERBOSE | IB_NOWRITE | IB_CLEAR | IB_EDIT
208 				| IB_FORCE);
209 	if (unsupported_flags != 0) {
210 		int ndx;
211 		for (ndx = 0; options[ndx].name != NULL; ndx++) {
212 			if (unsupported_flags & options[ndx].flag) {
213 				unsupported_flags &= ~options[ndx].flag;
214 				warnx("`-o %s' is not supported for %s",
215 				    options[ndx].name, params->machine->name);
216 			}
217 		}
218 		if (unsupported_flags & IB_STAGE1START)
219 			warnx("`-b bno' is not supported for %s",
220 			    params->machine->name);
221 		if (unsupported_flags & IB_STAGE2START)
222 			warnx("`-B bno' is not supported for %s",
223 			    params->machine->name);
224 		unsupported_flags &= ~(IB_STAGE1START | IB_STAGE2START);
225 		if (unsupported_flags != 0)
226 			warnx("Unknown unsupported flag %#x (coding error!)",
227 			    unsupported_flags);
228 		exit(1);
229 	}
230 	/* and some illegal combinations */
231 	if (params->flags & IB_STAGE1START && params->flags & IB_APPEND) {
232 		warnx("Can't use `-b bno' with `-o append'");
233 		exit(1);
234 	}
235 	if (params->flags & IB_CLEAR &&
236 	    params->flags & (IB_STAGE1START | IB_STAGE2START | IB_APPEND)) {
237 		warnx("Can't use `-b bno', `-B bno' or `-o append' with `-c'");
238 		exit(1);
239 	}
240 
241 	if (argc >= 3) {
242 		params->stage2 = argv[2];
243 	}
244 
245 #if !HAVE_NBTOOL_CONFIG_H
246 	special = getfsspecname(specname, sizeof(specname), argv[0]);
247 	if (special == NULL)
248 		err(1, "%s: %s", argv[0], specname);
249 	raw = getdiskrawname(rawname, sizeof(rawname), special);
250 	if (raw != NULL)
251 		special = raw;
252 	params->filesystem = special;
253 #else
254 	params->filesystem = argv[0];
255 #endif
256 
257 	if (params->flags & IB_NOWRITE) {
258 		op = "only";
259 		mode = O_RDONLY;
260 	} else {
261 		op = "write";
262 		mode = O_RDWR;
263 	}
264 	/* XXX should be specified via option */
265 	params->sectorsize = DFL_SECSIZE;
266 	if ((params->fsfd = open(params->filesystem, mode, 0600)) == -1)
267 		err(1, "Opening file system `%s' read-%s",
268 		    params->filesystem, op);
269 	if (fstat(params->fsfd, &params->fsstat) == -1)
270 		err(1, "Examining file system `%s'", params->filesystem);
271 	if (params->fstype != NULL) {
272 		if (! params->fstype->match(params))
273 			errx(1, "File system `%s' is not of type %s",
274 			    params->filesystem, params->fstype->name);
275 	} else {
276 		if (params->stage2 != NULL) {
277 			params->fstype = &fstypes[0];
278 			while (params->fstype->name != NULL &&
279 				    !params->fstype->match(params))
280 				params->fstype++;
281 			if (params->fstype->name == NULL)
282 				errx(1, "File system `%s' is of an unknown type",
283 				    params->filesystem);
284 		}
285 	}
286 
287 	assert(params->machine != NULL);
288 
289 	if (argc >= 2) {
290 		if ((params->s1fd = open(argv[1], O_RDONLY, 0600)) == -1)
291 			err(1, "Opening primary bootstrap `%s'", argv[1]);
292 		if (fstat(params->s1fd, &params->s1stat) == -1)
293 			err(1, "Examining primary bootstrap `%s'", argv[1]);
294 		if (!S_ISREG(params->s1stat.st_mode)) {
295 			/*
296 			 * If the platform uses u-boot, then the stage1
297 			 * spec might be the directory where the u-boot
298 			 * binaries for the system are located.
299 			 */
300 			if (params->machine->mach_flags & MF_UBOOT) {
301 				if (!S_ISDIR(params->s1stat.st_mode)) {
302 					errx(1, "`%s' must be a regular file "
303 					     "or a directory", argv[1]);
304 				}
305 				(void) close(params->s1fd);
306 				params->s1fd = -1;
307 			} else {
308 				errx(1, "`%s' must be a regular file", argv[1]);
309 			}
310 		}
311 		params->stage1 = argv[1];
312 	}
313 
314 	if (params->flags & IB_VERBOSE) {
315 		printf("File system:         %s\n", params->filesystem);
316 		if (params->fstype)
317 			printf("File system type:    %s (blocksize %u, "
318 				"needswap %d)\n",
319 			    params->fstype->name, params->fstype->blocksize,
320 			    params->fstype->needswap);
321 		if (!(params->flags & IB_EDIT))
322 			printf("Primary bootstrap:   %s%s\n",
323 			    (params->flags & IB_CLEAR) ? "(to be cleared)"
324 			    : params->stage1 ? params->stage1 : "(none)",
325 			    S_ISDIR(params->s1stat.st_mode) ? " (directory)"
326 			    				    : "");
327 		if (params->stage2 != NULL)
328 			printf("Secondary bootstrap: %s\n", params->stage2);
329 	}
330 
331 	if (params->flags & IB_EDIT) {
332 		op = "Edit";
333 		rv = params->machine->editboot(params);
334 	} else if (params->flags & IB_CLEAR) {
335 		op = "Clear";
336 		rv = params->machine->clearboot(params);
337 	} else {
338 		if (argc < 2) {
339 			/*
340 			 * If the platform uses u-boot, then the stage1 spec is
341 			 * optional iff they specified a board (because we can
342 			 * infer a default location for u-boot binaries if the
343 			 * board type is given).
344 			 */
345 			if (!(params->machine->mach_flags & MF_UBOOT)) {
346 				errx(EXIT_FAILURE,
347 				   "Please specify the primary bootstrap file");
348 			}
349 		}
350 		op = "Set";
351 		rv = params->machine->setboot(params);
352 	}
353 	if (rv == 0)
354 		errx(1, "%s bootstrap operation failed", op);
355 
356 	if (S_ISREG(params->fsstat.st_mode)) {
357 		if (fsync(params->fsfd) == -1)
358 			err(1, "Synchronising file system `%s'",
359 			    params->filesystem);
360 	} else {
361 		/* Sync filesystems (to clean in-memory superblock?) */
362 		sync();
363 	}
364 	if (close(params->fsfd) == -1)
365 		err(1, "Closing file system `%s'", params->filesystem);
366 	if (params->s1fd != -1)
367 		if (close(params->s1fd) == -1)
368 			err(1, "Closing primary bootstrap `%s'",
369 			    params->stage1);
370 
371 	exit(0);
372 	/* NOTREACHED */
373 }
374 
375 static void
376 parseoptions(ib_params *params, const char *option)
377 {
378 	char *cp;
379 	const struct option *opt;
380 	int len;
381 	unsigned long val;
382 
383 	assert(params != NULL);
384 	assert(option != NULL);
385 
386 	for (;; option += len) {
387 		option += strspn(option, ", \t");
388 		if (*option == 0)
389 			return;
390 		len = strcspn(option, "=,");
391 		for (opt = options; opt->name != NULL; opt++) {
392 			if (memcmp(option, opt->name, len) == 0
393 			    && opt->name[len] == 0)
394 				break;
395 		}
396 		if (opt->name == NULL) {
397 			len = strcspn(option, ",");
398 			warnx("Unknown option `-o %.*s'", len, option);
399 			break;
400 		}
401 		params->flags |= opt->flag;
402 		if (opt->type == OPT_BOOL) {
403 			if (option[len] != '=')
404 				continue;
405 			warnx("Option `%s' must not have a value", opt->name);
406 			break;
407 		}
408 		if (option[len] != '=') {
409 			warnx("Option `%s' must have a value", opt->name);
410 			break;
411 		}
412 		option += len + 1;
413 		len = strcspn(option, ",");
414 		switch (opt->type) {
415 		case OPT_STRING:
416 			len = strlen(option);
417 			/* FALLTHROUGH */
418 		case OPT_WORD:
419 			cp = strdup(option);
420 			if (cp == NULL)
421 				err(1, "strdup");
422 			cp[len] = 0;
423 			OPTION(params, char *, opt) = cp;
424 			continue;
425 		case OPT_INT:
426 			val = strtoul(option, &cp, 0);
427 			if (cp > option + len || (*cp != 0 && *cp != ','))
428 				break;
429 			if (val > INT_MAX)
430 				break;
431 			OPTION(params, int, opt) = (int)val;
432 			continue;
433 		default:
434 			errx(1, "Internal error: option `%s' has invalid type %d",
435 				opt->name, opt->type);
436 		}
437 		warnx("Invalid option value `%s=%.*s'", opt->name, len, option);
438 		break;
439 	}
440 	options_usage();
441 	exit(1);
442 }
443 
444 static void
445 options_usage(void)
446 {
447 	int ndx;
448 	const char *pfx;
449 
450 	warnx("Valid options are:");
451 	pfx = "\t";
452 	for (ndx = 0; options[ndx].name != 0; ndx++) {
453 		fprintf(stderr, "%s%s", pfx, options[ndx].name);
454 		switch (options[ndx].type) {
455 		case OPT_INT:
456 			fprintf(stderr, "=number");
457 			break;
458 		case OPT_WORD:
459 			fprintf(stderr, "=word");
460 			break;
461 		case OPT_STRING:
462 			fprintf(stderr, "=string");
463 			break;
464 		default:
465 			break;
466 		}
467 		if ((ndx % 5) == 4)
468 			pfx = ",\n\t";
469 		else
470 			pfx = ", ";
471 	}
472 	fprintf(stderr, "\n");
473 }
474 
475 int
476 no_setboot(ib_params *params)
477 {
478 
479 	assert(params != NULL);
480 
481 	warnx("%s: bootstrap installation is not supported",
482 	    params->machine->name);
483 	return (0);
484 }
485 
486 int
487 no_clearboot(ib_params *params)
488 {
489 
490 	assert(params != NULL);
491 
492 	warnx("%s: bootstrap removal is not supported",
493 	    params->machine->name);
494 	return (0);
495 }
496 
497 int
498 no_editboot(ib_params *params)
499 {
500 
501 	assert(params != NULL);
502 
503 	warnx("%s: bootstrap editing is not supported",
504 	    params->machine->name);
505 	return (0);
506 }
507 
508 
509 static void
510 getmachine(ib_params *param, const char *mach, const char *provider)
511 {
512 	int	i;
513 
514 	assert(param != NULL);
515 	assert(mach != NULL);
516 	assert(provider != NULL);
517 
518 	for (i = 0; machines[i] != NULL; i++) {
519 		if (machines[i]->name == NULL)
520 			continue;
521 		if (strcmp(machines[i]->name, mach) == 0) {
522 			param->machine = machines[i];
523 			return;
524 		}
525 	}
526 	warnx("Invalid machine `%s' from %s", mach, provider);
527 	machine_usage();
528 	exit(1);
529 }
530 
531 static void
532 machine_usage(void)
533 {
534 	const char *prefix;
535 	int	i;
536 	int col, len;
537 	const char *name;
538 	int	wincol=80;
539 #ifdef TIOCGWINSZ
540 	struct winsize win;
541 
542 	if (ioctl(fileno(stderr), TIOCGWINSZ, &win) == 0 && win.ws_col > 0)
543 		wincol = win.ws_col;
544 #endif
545 
546 	warnx("Supported machines are:");
547 	prefix="\t";
548 	col = 8 + 3;
549 	for (i = 0; machines[i] != NULL; i++) {
550 		name = machines[i]->name;
551 		if (name == NULL)
552 			continue;
553 		len = strlen(name);
554 		if (col + len > wincol) {
555 			prefix=",\n\t";
556 			col = -2 + 8 + 3;
557 		}
558 		col += fprintf(stderr, "%s%s", prefix, name);
559 		prefix=", ";
560 	}
561 	fputs("\n", stderr);
562 }
563 
564 static void
565 getfstype(ib_params *param, const char *fstype, const char *provider)
566 {
567 	int i;
568 
569 	assert(param != NULL);
570 	assert(fstype != NULL);
571 	assert(provider != NULL);
572 
573 	for (i = 0; fstypes[i].name != NULL; i++) {
574 		if (strcmp(fstypes[i].name, fstype) == 0) {
575 			param->fstype = &fstypes[i];
576 			return;
577 		}
578 	}
579 	warnx("Invalid file system type `%s' from %s", fstype, provider);
580 	fstype_usage();
581 	exit(1);
582 }
583 
584 static void
585 fstype_usage(void)
586 {
587 #ifndef NO_STAGE2
588 	const char *prefix;
589 	int	i;
590 
591 	warnx("Supported file system types are:");
592 #define FSTYPES_PER_LINE	9
593 	prefix="\t";
594 	for (i = 0; fstypes[i].name != NULL; i++) {
595 		if (i && (i % FSTYPES_PER_LINE) == 0)
596 			prefix=",\n\t";
597 		fprintf(stderr, "%s%s", prefix, fstypes[i].name);
598 		prefix=", ";
599 	}
600 	fputs("\n", stderr);
601 #endif
602 }
603 
604 static void
605 usage(void)
606 {
607 	const char	*prog;
608 
609 	prog = getprogname();
610 	fprintf(stderr,
611 "usage: %s [-fnv] [-B s2bno] [-b s1bno] [-m machine] [-o options]\n"
612 "\t\t   [-t fstype] filesystem primary [secondary]\n"
613 "usage: %s -c [-fnv] [-m machine] [-o options] [-t fstype] filesystem\n"
614 "usage: %s -e [-fnv] [-m machine] [-o options] bootstrap\n",
615 	    prog, prog, prog);
616 	machine_usage();
617 	fstype_usage();
618 	options_usage();
619 	if (installboot_params.machine != NULL &&
620 	    installboot_params.machine->usage != NULL)
621 		installboot_params.machine->usage(&installboot_params);
622 	exit(1);
623 }
624