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