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