xref: /netbsd-src/usr.sbin/installboot/installboot.c (revision f17b710f3d406bee67aa39c65053114ab78297c5)
1 /*	$NetBSD: installboot.c,v 1.38 2015/06/05 07:44:39 mlelstv 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.38 2015/06/05 07:44:39 mlelstv 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 
60 static	void	getmachine(ib_params *, const char *, const char *);
61 static	void	getfstype(ib_params *, const char *, const char *);
62 static	void	parseoptions(ib_params *, const char *);
63 __dead static	void	usage(void);
64 static	void	options_usage(void);
65 static	void	machine_usage(void);
66 static	void	fstype_usage(void);
67 
68 static	ib_params	installboot_params;
69 
70 #define OFFSET(field)    offsetof(ib_params, field)
71 const struct option {
72 	const char	*name;		/* Name of option */
73 	ib_flags	flag;		/* Corresponding IB_xxx flag */
74 	enum {				/* Type of option value... */
75 		OPT_BOOL,		/* no value */
76 		OPT_INT,		/* numeric value */
77 		OPT_WORD,		/* space/tab/, terminated */
78 		OPT_STRING		/* null terminated */
79 	}		type;
80 	int		offset;		/* of field in ib_params */
81 } options[] = {
82 	{ "alphasum",	IB_ALPHASUM,	OPT_BOOL,	0 },
83 	{ "append",	IB_APPEND,	OPT_BOOL,	0 },
84 	{ "command",	IB_COMMAND,	OPT_STRING,	OFFSET(command) },
85 	{ "console",	IB_CONSOLE,	OPT_WORD,	OFFSET(console) },
86 	{ "ioaddr",	IB_CONSADDR,	OPT_INT,	OFFSET(consaddr) },
87 	{ "keymap",	IB_KEYMAP,	OPT_WORD,	OFFSET(keymap) },
88 	{ "password",	IB_PASSWORD,	OPT_WORD,	OFFSET(password) },
89 	{ "resetvideo",	IB_RESETVIDEO,	OPT_BOOL,	0 },
90 	{ "speed",	IB_CONSPEED,	OPT_INT,	OFFSET(conspeed) },
91 	{ "sunsum",	IB_SUNSUM,	OPT_BOOL,	0 },
92 	{ "timeout",	IB_TIMEOUT,	OPT_INT,	OFFSET(timeout) },
93 	{ "modules",	IB_MODULES,	OPT_BOOL,	0 },
94 	{ "bootconf",	IB_BOOTCONF,	OPT_BOOL,	0 },
95 	{ .name = NULL },
96 };
97 #undef OFFSET
98 #define OPTION(params, type, opt) (*(type *)((char *)(params) + (opt)->offset))
99 
100 #define DFL_SECSIZE	512	/* Don't use DEV_BSIZE. It's host's value. */
101 
102 int
103 main(int argc, char *argv[])
104 {
105 	struct utsname	utsname;
106 	ib_params	*params;
107 	unsigned long	lval;
108 	int		ch, rv, mode;
109 	char 		*p;
110 	const char	*op;
111 	ib_flags	unsupported_flags;
112 #if !HAVE_NBTOOL_CONFIG_H
113 	char		specname[MAXPATHLEN];
114 	char		rawname[MAXPATHLEN];
115 	const char	*special, *raw;
116 #endif
117 
118 	setprogname(argv[0]);
119 	params = &installboot_params;
120 	memset(params, 0, sizeof(*params));
121 	params->fsfd = -1;
122 	params->s1fd = -1;
123 	if ((p = getenv("MACHINE")) != NULL)
124 		getmachine(params, p, "$MACHINE");
125 
126 	while ((ch = getopt(argc, argv, "b:B:cefm:no:t:v")) != -1) {
127 		switch (ch) {
128 
129 		case 'b':
130 		case 'B':
131 			if (*optarg == '\0')
132 				goto badblock;
133 			lval = strtoul(optarg, &p, 0);
134 			if (lval > UINT32_MAX || *p != '\0') {
135  badblock:
136 				errx(1, "Invalid block number `%s'", optarg);
137 			}
138 			if (ch == 'b') {
139 				params->s1start = (uint32_t)lval;
140 				params->flags |= IB_STAGE1START;
141 			} else {
142 				params->s2start = (uint32_t)lval;
143 				params->flags |= IB_STAGE2START;
144 			}
145 			break;
146 
147 		case 'c':
148 			params->flags |= IB_CLEAR;
149 			break;
150 
151 		case 'e':
152 			params->flags |= IB_EDIT;
153 			break;
154 
155 		case 'f':
156 			params->flags |= IB_FORCE;
157 			break;
158 
159 		case 'm':
160 			getmachine(params, optarg, "-m");
161 			break;
162 
163 		case 'n':
164 			params->flags |= IB_NOWRITE;
165 			break;
166 
167 		case 'o':
168 			parseoptions(params, optarg);
169 			break;
170 
171 		case 't':
172 			getfstype(params, optarg, "-t");
173 			break;
174 
175 		case 'v':
176 			params->flags |= IB_VERBOSE;
177 			break;
178 
179 		case '?':
180 		default:
181 			usage();
182 			/* NOTREACHED */
183 
184 		}
185 	}
186 	argc -= optind;
187 	argv += optind;
188 
189 	if (params->flags & IB_CLEAR && params->flags & IB_EDIT)
190 		usage();
191 	if (argc < 1 || argc + 2 * !!(params->flags & (IB_CLEAR | IB_EDIT)) > 3)
192 		usage();
193 
194 	/* set missing defaults */
195 	if (params->machine == NULL) {
196 		if (uname(&utsname) == -1)
197 			err(1, "Determine uname");
198 		getmachine(params, utsname.machine, "uname()");
199 	}
200 
201 	/* Check that options are supported by this system */
202 	unsupported_flags = params->flags & ~params->machine->valid_flags;
203 	unsupported_flags &= ~(IB_VERBOSE | IB_NOWRITE | IB_CLEAR | IB_EDIT
204 				| IB_FORCE);
205 	if (unsupported_flags != 0) {
206 		int ndx;
207 		for (ndx = 0; options[ndx].name != NULL; ndx++) {
208 			if (unsupported_flags & options[ndx].flag) {
209 				unsupported_flags &= ~options[ndx].flag;
210 				warnx("`-o %s' is not supported for %s",
211 				    options[ndx].name, params->machine->name);
212 			}
213 		}
214 		if (unsupported_flags & IB_STAGE1START)
215 			warnx("`-b bno' is not supported for %s",
216 			    params->machine->name);
217 		if (unsupported_flags & IB_STAGE2START)
218 			warnx("`-B bno' is not supported for %s",
219 			    params->machine->name);
220 		unsupported_flags &= ~(IB_STAGE1START | IB_STAGE2START);
221 		if (unsupported_flags != 0)
222 			warnx("Unknown unsupported flag %#x (coding error!)",
223 			    unsupported_flags);
224 		exit(1);
225 	}
226 	/* and some illegal combinations */
227 	if (params->flags & IB_STAGE1START && params->flags & IB_APPEND) {
228 		warnx("Can't use `-b bno' with `-o append'");
229 		exit(1);
230 	}
231 	if (params->flags & IB_CLEAR &&
232 	    params->flags & (IB_STAGE1START | IB_STAGE2START | IB_APPEND)) {
233 		warnx("Can't use `-b bno', `-B bno' or `-o append' with `-c'");
234 		exit(1);
235 	}
236 
237 	if (argc >= 3) {
238 		params->stage2 = argv[2];
239 	}
240 
241 #if !HAVE_NBTOOL_CONFIG_H
242 	special = getfsspecname(specname, sizeof(specname), argv[0]);
243 	raw = getdiskrawname(rawname, sizeof(rawname), special);
244 	if (raw != NULL)
245 		special = raw;
246 	params->filesystem = special;
247 #else
248 	params->filesystem = argv[0];
249 #endif
250 
251 	if (params->flags & IB_NOWRITE) {
252 		op = "only";
253 		mode = O_RDONLY;
254 	} else {
255 		op = "write";
256 		mode = O_RDWR;
257 	}
258 	/* XXX should be specified via option */
259 	params->sectorsize = DFL_SECSIZE;
260 	if ((params->fsfd = open(params->filesystem, mode, 0600)) == -1)
261 		err(1, "Opening file system `%s' read-%s",
262 		    params->filesystem, op);
263 	if (fstat(params->fsfd, &params->fsstat) == -1)
264 		err(1, "Examining file system `%s'", params->filesystem);
265 	if (params->fstype != NULL) {
266 		if (! params->fstype->match(params))
267 			errx(1, "File system `%s' is not of type %s",
268 			    params->filesystem, params->fstype->name);
269 	} else {
270 		if (params->stage2 != NULL) {
271 			params->fstype = &fstypes[0];
272 			while (params->fstype->name != NULL &&
273 				    !params->fstype->match(params))
274 				params->fstype++;
275 			if (params->fstype->name == NULL)
276 				errx(1, "File system `%s' is of an unknown type",
277 				    params->filesystem);
278 		}
279 	}
280 
281 	if (argc >= 2) {
282 		if ((params->s1fd = open(argv[1], O_RDONLY, 0600)) == -1)
283 			err(1, "Opening primary bootstrap `%s'", argv[1]);
284 		if (fstat(params->s1fd, &params->s1stat) == -1)
285 			err(1, "Examining primary bootstrap `%s'", argv[1]);
286 		if (!S_ISREG(params->s1stat.st_mode))
287 			errx(1, "`%s' must be a regular file", argv[1]);
288 		params->stage1 = argv[1];
289 	}
290 	assert(params->machine != NULL);
291 
292 	if (params->flags & IB_VERBOSE) {
293 		printf("File system:         %s\n", params->filesystem);
294 		if (params->fstype)
295 			printf("File system type:    %s (blocksize %u, "
296 				"needswap %d)\n",
297 			    params->fstype->name, params->fstype->blocksize,
298 			    params->fstype->needswap);
299 		if (!(params->flags & IB_EDIT))
300 			printf("Primary bootstrap:   %s\n",
301 			    (params->flags & IB_CLEAR) ? "(to be cleared)"
302 			    : params->stage1 ? params->stage1 : "(none)" );
303 		if (params->stage2 != NULL)
304 			printf("Secondary bootstrap: %s\n", params->stage2);
305 	}
306 
307 	if (params->flags & IB_EDIT) {
308 		op = "Edit";
309 		rv = params->machine->editboot(params);
310 	} else if (params->flags & IB_CLEAR) {
311 		op = "Clear";
312 		rv = params->machine->clearboot(params);
313 	} else {
314 		if (argc < 2)
315 			errx(EXIT_FAILURE, "Please specify the primary "
316 			    "bootstrap file");
317 		op = "Set";
318 		rv = params->machine->setboot(params);
319 	}
320 	if (rv == 0)
321 		errx(1, "%s bootstrap operation failed", op);
322 
323 	if (S_ISREG(params->fsstat.st_mode)) {
324 		if (fsync(params->fsfd) == -1)
325 			err(1, "Synchronising file system `%s'",
326 			    params->filesystem);
327 	} else {
328 		/* Sync filesystems (to clean in-memory superblock?) */
329 		sync();
330 	}
331 	if (close(params->fsfd) == -1)
332 		err(1, "Closing file system `%s'", params->filesystem);
333 	if (argc == 2)
334 		if (close(params->s1fd) == -1)
335 			err(1, "Closing primary bootstrap `%s'",
336 			    params->stage1);
337 
338 	exit(0);
339 	/* NOTREACHED */
340 }
341 
342 static void
343 parseoptions(ib_params *params, const char *option)
344 {
345 	char *cp;
346 	const struct option *opt;
347 	int len;
348 	unsigned long val;
349 
350 	assert(params != NULL);
351 	assert(option != NULL);
352 
353 	for (;; option += len) {
354 		option += strspn(option, ", \t");
355 		if (*option == 0)
356 			return;
357 		len = strcspn(option, "=,");
358 		for (opt = options; opt->name != NULL; opt++) {
359 			if (memcmp(option, opt->name, len) == 0
360 			    && opt->name[len] == 0)
361 				break;
362 		}
363 		if (opt->name == NULL) {
364 			len = strcspn(option, ",");
365 			warnx("Unknown option `-o %.*s'", len, option);
366 			break;
367 		}
368 		params->flags |= opt->flag;
369 		if (opt->type == OPT_BOOL) {
370 			if (option[len] != '=')
371 				continue;
372 			warnx("Option `%s' must not have a value", opt->name);
373 			break;
374 		}
375 		if (option[len] != '=') {
376 			warnx("Option `%s' must have a value", opt->name);
377 			break;
378 		}
379 		option += len + 1;
380 		len = strcspn(option, ",");
381 		switch (opt->type) {
382 		case OPT_STRING:
383 			len = strlen(option);
384 			/* FALLTHROUGH */
385 		case OPT_WORD:
386 			cp = strdup(option);
387 			if (cp == NULL)
388 				err(1, "strdup");
389 			cp[len] = 0;
390 			OPTION(params, char *, opt) = cp;
391 			continue;
392 		case OPT_INT:
393 			val = strtoul(option, &cp, 0);
394 			if (cp > option + len || (*cp != 0 && *cp != ','))
395 				break;
396 			if (val > INT_MAX)
397 				break;
398 			OPTION(params, int, opt) = (int)val;
399 			continue;
400 		default:
401 			errx(1, "Internal error: option `%s' has invalid type %d",
402 				opt->name, opt->type);
403 		}
404 		warnx("Invalid option value `%s=%.*s'", opt->name, len, option);
405 		break;
406 	}
407 	options_usage();
408 	exit(1);
409 }
410 
411 static void
412 options_usage(void)
413 {
414 	int ndx;
415 	const char *pfx;
416 
417 	warnx("Valid options are:");
418 	pfx = "\t";
419 	for (ndx = 0; options[ndx].name != 0; ndx++) {
420 		fprintf(stderr, "%s%s", pfx, options[ndx].name);
421 		switch (options[ndx].type) {
422 		case OPT_INT:
423 			fprintf(stderr, "=number");
424 			break;
425 		case OPT_WORD:
426 			fprintf(stderr, "=word");
427 			break;
428 		case OPT_STRING:
429 			fprintf(stderr, "=string");
430 			break;
431 		default:
432 			break;
433 		}
434 		if ((ndx % 5) == 4)
435 			pfx = ",\n\t";
436 		else
437 			pfx = ", ";
438 	}
439 	fprintf(stderr, "\n");
440 }
441 
442 int
443 no_setboot(ib_params *params)
444 {
445 
446 	assert(params != NULL);
447 
448 	warnx("%s: bootstrap installation is not supported",
449 	    params->machine->name);
450 	return (0);
451 }
452 
453 int
454 no_clearboot(ib_params *params)
455 {
456 
457 	assert(params != NULL);
458 
459 	warnx("%s: bootstrap removal is not supported",
460 	    params->machine->name);
461 	return (0);
462 }
463 
464 int
465 no_editboot(ib_params *params)
466 {
467 
468 	assert(params != NULL);
469 
470 	warnx("%s: bootstrap editing is not supported",
471 	    params->machine->name);
472 	return (0);
473 }
474 
475 
476 static void
477 getmachine(ib_params *param, const char *mach, const char *provider)
478 {
479 	int	i;
480 
481 	assert(param != NULL);
482 	assert(mach != NULL);
483 	assert(provider != NULL);
484 
485 	for (i = 0; machines[i] != NULL; i++) {
486 		if (machines[i]->name == NULL)
487 			continue;
488 		if (strcmp(machines[i]->name, mach) == 0) {
489 			param->machine = machines[i];
490 			return;
491 		}
492 	}
493 	warnx("Invalid machine `%s' from %s", mach, provider);
494 	machine_usage();
495 	exit(1);
496 }
497 
498 static void
499 machine_usage(void)
500 {
501 	const char *prefix;
502 	int	i;
503 	int col, len;
504 	const char *name;
505 	int	wincol=80;
506 #ifdef TIOCGWINSZ
507 	struct winsize win;
508 
509 	if (ioctl(fileno(stderr), TIOCGWINSZ, &win) == 0 && win.ws_col > 0)
510 		wincol = win.ws_col;
511 #endif
512 
513 	warnx("Supported machines are:");
514 	prefix="\t";
515 	col = 8 + 3;
516 	for (i = 0; machines[i] != NULL; i++) {
517 		name = machines[i]->name;
518 		if (name == NULL)
519 			continue;
520 		len = strlen(name);
521 		if (col + len > wincol) {
522 			prefix=",\n\t";
523 			col = -2 + 8 + 3;
524 		}
525 		col += fprintf(stderr, "%s%s", prefix, name);
526 		prefix=", ";
527 	}
528 	fputs("\n", stderr);
529 }
530 
531 static void
532 getfstype(ib_params *param, const char *fstype, const char *provider)
533 {
534 	int i;
535 
536 	assert(param != NULL);
537 	assert(fstype != NULL);
538 	assert(provider != NULL);
539 
540 	for (i = 0; fstypes[i].name != NULL; i++) {
541 		if (strcmp(fstypes[i].name, fstype) == 0) {
542 			param->fstype = &fstypes[i];
543 			return;
544 		}
545 	}
546 	warnx("Invalid file system type `%s' from %s", fstype, provider);
547 	fstype_usage();
548 	exit(1);
549 }
550 
551 static void
552 fstype_usage(void)
553 {
554 #ifndef NO_STAGE2
555 	const char *prefix;
556 	int	i;
557 
558 	warnx("Supported file system types are:");
559 #define FSTYPES_PER_LINE	9
560 	prefix="\t";
561 	for (i = 0; fstypes[i].name != NULL; i++) {
562 		if (i && (i % FSTYPES_PER_LINE) == 0)
563 			prefix=",\n\t";
564 		fprintf(stderr, "%s%s", prefix, fstypes[i].name);
565 		prefix=", ";
566 	}
567 	fputs("\n", stderr);
568 #endif
569 }
570 
571 static void
572 usage(void)
573 {
574 	const char	*prog;
575 
576 	prog = getprogname();
577 	fprintf(stderr,
578 "usage: %s [-fnv] [-B s2bno] [-b s1bno] [-m machine] [-o options]\n"
579 "\t\t   [-t fstype] filesystem primary [secondary]\n"
580 "usage: %s -c [-fnv] [-m machine] [-o options] [-t fstype] filesystem\n"
581 "usage: %s -e [-fnv] [-m machine] [-o options] bootstrap\n",
582 	    prog, prog, prog);
583 	machine_usage();
584 	fstype_usage();
585 	options_usage();
586 	exit(1);
587 }
588