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