xref: /netbsd-src/usr.sbin/installboot/installboot.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: installboot.c,v 1.22 2005/12/26 13:30:25 jmmv 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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the NetBSD
21  *	Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #if HAVE_NBTOOL_CONFIG_H
40 #include "nbtool_config.h"
41 #endif
42 
43 #include <sys/cdefs.h>
44 #if defined(__RCSID) && !defined(__lint)
45 __RCSID("$NetBSD: installboot.c,v 1.22 2005/12/26 13:30:25 jmmv Exp $");
46 #endif	/* !__lint */
47 
48 #include <sys/utsname.h>
49 
50 #include <assert.h>
51 #include <err.h>
52 #include <fcntl.h>
53 #include <limits.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <stddef.h>
57 #include <string.h>
58 #include <unistd.h>
59 
60 #include "installboot.h"
61 
62 int		main(int, char *[]);
63 static	void	getmachine(ib_params *, const char *, const char *);
64 static	void	getfstype(ib_params *, const char *, const char *);
65 static	void	parseoptions(ib_params *, const char *);
66 static	void	usage(void);
67 static	void	options_usage(void);
68 static	void	machine_usage(void);
69 static	void	fstype_usage(void);
70 
71 static	ib_params	installboot_params;
72 
73 #define OFFSET(field)    offsetof(ib_params, field)
74 const struct option {
75 	const char	*name;		/* Name of option */
76 	ib_flags	flag;		/* Corresponding IB_xxx flag */
77 	enum {				/* Type of option value... */
78 		OPT_BOOL,		/* no value */
79 		OPT_INT,		/* numeric value */
80 		OPT_WORD,		/* space/tab/, terminated */
81 		OPT_STRING		/* null terminated */
82 	}		type;
83 	int		offset;		/* of field in ib_params */
84 } options[] = {
85 	{ "alphasum",	IB_ALPHASUM,	OPT_BOOL },
86 	{ "append",	IB_APPEND,	OPT_BOOL },
87 	{ "command",	IB_COMMAND,	OPT_STRING,	OFFSET(command) },
88 	{ "console",	IB_CONSOLE,	OPT_WORD,	OFFSET(console) },
89 	{ "ioaddr",	IB_CONSADDR,	OPT_INT,	OFFSET(consaddr) },
90 	{ "keymap",	IB_KEYMAP,	OPT_WORD,	OFFSET(keymap) },
91 	{ "password",	IB_PASSWORD,	OPT_WORD,	OFFSET(password) },
92 	{ "resetvideo",	IB_RESETVIDEO,	OPT_BOOL },
93 	{ "speed",	IB_CONSPEED,	OPT_INT,	OFFSET(conspeed) },
94 	{ "sunsum",	IB_SUNSUM,	OPT_BOOL },
95 	{ "timeout",	IB_TIMEOUT,	OPT_INT,	OFFSET(timeout) },
96 	{ NULL },
97 };
98 #undef OFFSET
99 #define OPTION(params, type, opt) (*(type *)((char *)(params) + (opt)->offset))
100 
101 int
102 main(int argc, char *argv[])
103 {
104 	struct utsname	utsname;
105 	ib_params	*params;
106 	unsigned long	lval;
107 	int		ch, rv, mode;
108 	char 		*p;
109 	const char	*op;
110 	ib_flags	unsupported_flags;
111 
112 	setprogname(argv[0]);
113 	params = &installboot_params;
114 	memset(params, 0, sizeof(*params));
115 	params->fsfd = -1;
116 	params->s1fd = -1;
117 	if ((p = getenv("MACHINE")) != NULL)
118 		getmachine(params, p, "$MACHINE");
119 
120 	while ((ch = getopt(argc, argv, "b:B:cem:no:t:v")) != -1) {
121 		switch (ch) {
122 
123 		case 'b':
124 		case 'B':
125 			if (*optarg == '\0')
126 				goto badblock;
127 			lval = strtoul(optarg, &p, 0);
128 			if (lval > UINT32_MAX || *p != '\0') {
129  badblock:
130 				errx(1, "Invalid block number `%s'", optarg);
131 			}
132 			if (ch == 'b') {
133 				params->s1start = (uint32_t)lval;
134 				params->flags |= IB_STAGE1START;
135 			} else {
136 				params->s2start = (uint32_t)lval;
137 				params->flags |= IB_STAGE2START;
138 			}
139 			break;
140 
141 		case 'c':
142 			params->flags |= IB_CLEAR;
143 			break;
144 
145 		case 'e':
146 			params->flags |= IB_EDIT;
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 	if (unsupported_flags != 0) {
195 		int ndx;
196 		for (ndx = 0; options[ndx].name != NULL; ndx++) {
197 			if (unsupported_flags & options[ndx].flag)
198 				warnx("`-o %s' is not supported for %s",
199 				    options[ndx].name, params->machine->name);
200 		}
201 		if (unsupported_flags & IB_STAGE1START)
202 			warnx("`-b bno' is not supported for %s",
203 			    params->machine->name);
204 		if (unsupported_flags & IB_STAGE2START)
205 			warnx("`-B bno' is not supported for %s",
206 			    params->machine->name);
207 		exit(1);
208 	}
209 	/* and some illegal combinations */
210 	if (params->flags & IB_STAGE1START && params->flags & IB_APPEND) {
211 		warnx("Can't use `-b bno' with `-o append'");
212 		exit(1);
213 	}
214 	if (params->flags & IB_CLEAR &&
215 	    params->flags & (IB_STAGE1START | IB_STAGE2START | IB_APPEND)) {
216 		warnx("Can't use `-b bno', `-B bno' or `-o append' with `-c'");
217 		exit(1);
218 	}
219 
220 	if (argc >= 3) {
221 		params->stage2 = argv[2];
222 	}
223 
224 	params->filesystem = argv[0];
225 	if (params->flags & IB_NOWRITE) {
226 		op = "only";
227 		mode = O_RDONLY;
228 	} else {
229 		op = "write";
230 		mode = O_RDWR;
231 	}
232 	if ((params->fsfd = open(params->filesystem, mode, 0600)) == -1)
233 		err(1, "Opening file system `%s' read-%s",
234 		    params->filesystem, op);
235 	if (fstat(params->fsfd, &params->fsstat) == -1)
236 		err(1, "Examining file system `%s'", params->filesystem);
237 	if (params->fstype != NULL) {
238 		if (! params->fstype->match(params))
239 			errx(1, "File system `%s' is not of type %s",
240 			    params->filesystem, params->fstype->name);
241 	} else {
242 		if (params->stage2 != NULL) {
243 			params->fstype = &fstypes[0];
244 			while (params->fstype->name != NULL &&
245 				    !params->fstype->match(params))
246 				params->fstype++;
247 			if (params->fstype->name == NULL)
248 				errx(1, "File system `%s' is of an unknown type",
249 				    params->filesystem);
250 		}
251 	}
252 
253 	if (argc >= 2) {
254 		params->stage1 = argv[1];
255 		if ((params->s1fd = open(params->stage1, O_RDONLY, 0600)) == -1)
256 			err(1, "Opening primary bootstrap `%s'",
257 			    params->stage1);
258 		if (fstat(params->s1fd, &params->s1stat) == -1)
259 			err(1, "Examining primary bootstrap `%s'",
260 			    params->stage1);
261 		if (!S_ISREG(params->s1stat.st_mode))
262 			errx(1, "`%s' must be a regular file", params->stage1);
263 	}
264 	assert(params->machine != NULL);
265 
266 	if (params->flags & IB_VERBOSE) {
267 		printf("File system:         %s\n", params->filesystem);
268 		if (params->fstype)
269 			printf("File system type:    %s (blocksize %u, "
270 				"needswap %d)\n",
271 			    params->fstype->name, params->fstype->blocksize,
272 			    params->fstype->needswap);
273 		if (!(params->flags & IB_EDIT))
274 			printf("Primary bootstrap:   %s\n",
275 			    (params->flags & IB_CLEAR) ? "(to be cleared)"
276 			    : params->stage1 ? params->stage1 : "(none)" );
277 		if (params->stage2 != NULL)
278 			printf("Secondary bootstrap: %s\n", params->stage2);
279 	}
280 
281 	if (params->flags & IB_EDIT) {
282 		op = "Edit";
283 		rv = params->machine->editboot(params);
284 	} else if (params->flags & IB_CLEAR) {
285 		op = "Clear";
286 		rv = params->machine->clearboot(params);
287 	} else {
288 		if (argc < 2)
289 			errx(EXIT_FAILURE, "Please specify the primary "
290 			    "bootstrap file");
291 		op = "Set";
292 		rv = params->machine->setboot(params);
293 	}
294 	if (rv == 0)
295 		errx(1, "%s bootstrap operation failed", op);
296 
297 	if (S_ISREG(params->fsstat.st_mode)) {
298 		if (fsync(params->fsfd) == -1)
299 			err(1, "Synchronising file system `%s'",
300 			    params->filesystem);
301 	} else {
302 		/* Sync filesystems (to clean in-memory superblock?) */
303 		sync();
304 	}
305 	if (close(params->fsfd) == -1)
306 		err(1, "Closing file system `%s'", params->filesystem);
307 	if (argc == 2)
308 		if (close(params->s1fd) == -1)
309 			err(1, "Closing primary bootstrap `%s'",
310 			    params->stage1);
311 
312 	exit(0);
313 	/* NOTREACHED */
314 }
315 
316 static void
317 parseoptions(ib_params *params, const char *option)
318 {
319 	char *cp;
320 	const struct option *opt;
321 	int len;
322 	unsigned long val;
323 
324 	assert(params != NULL);
325 	assert(option != NULL);
326 
327 	for (;; option += len) {
328 		option += strspn(option, ", \t");
329 		if (*option == 0)
330 			return;
331 		len = strcspn(option, "=,");
332 		for (opt = options; opt->name != NULL; opt++) {
333 			if (memcmp(option, opt->name, len) == 0
334 			    && opt->name[len] == 0)
335 				break;
336 		}
337 		if (opt->name == NULL) {
338 			len = strcspn(option, ",");
339 			warnx("Unknown option `-o %.*s'", len, option);
340 			break;
341 		}
342 		params->flags |= opt->flag;
343 		if (opt->type == OPT_BOOL) {
344 			if (option[len] != '=')
345 				continue;
346 			warnx("Option `%s' must not have a value", opt->name);
347 			break;
348 		}
349 		if (option[len] != '=') {
350 			warnx("Option `%s' must have a value", opt->name);
351 			break;
352 		}
353 		option += len + 1;
354 		len = strcspn(option, ",");
355 		switch (opt->type) {
356 		case OPT_STRING:
357 			len = strlen(option);
358 			/* FALLTHROUGH */
359 		case OPT_WORD:
360 			cp = strdup(option);
361 			if (cp == NULL)
362 				err(1, "strdup");
363 			cp[len] = 0;
364 			OPTION(params, char *, opt) = cp;
365 			continue;
366 		case OPT_INT:
367 			val = strtoul(option, &cp, 0);
368 			if (cp > option + len || (*cp != 0 && *cp != ','))
369 				break;
370 			OPTION(params, int, opt) = val;
371 			if (OPTION(params, int, opt) != val)
372 				/* value got truncated on int convertion */
373 				break;
374 			continue;
375 		default:
376 			errx(1, "Internal error: option `%s' has invalid type %d",
377 				opt->name, opt->type);
378 		}
379 		warnx("Invalid option value `%s=%.*s'", opt->name, len, option);
380 		break;
381 	}
382 	options_usage();
383 	exit(1);
384 }
385 
386 static void
387 options_usage(void)
388 {
389 	int ndx;
390 	const char *pfx;
391 
392 	warnx("Valid options are:");
393 	pfx = "\t";
394 	for (ndx = 0; options[ndx].name != 0; ndx++) {
395 		fprintf(stderr, "%s%s", pfx, options[ndx].name);
396 		switch (options[ndx].type) {
397 		case OPT_INT:
398 			fprintf(stderr, "=number");
399 			break;
400 		case OPT_WORD:
401 			fprintf(stderr, "=word");
402 			break;
403 		case OPT_STRING:
404 			fprintf(stderr, "=string");
405 			break;
406 		default:
407 			break;
408 		}
409 		if ((ndx % 5) == 4)
410 			pfx = ",\n\t";
411 		else
412 			pfx = ", ";
413 	}
414 	fprintf(stderr, "\n");
415 }
416 
417 int
418 no_setboot(ib_params *params)
419 {
420 
421 	assert(params != NULL);
422 
423 	warnx("%s: bootstrap installation is not supported",
424 	    params->machine->name);
425 	return (0);
426 }
427 
428 int
429 no_clearboot(ib_params *params)
430 {
431 
432 	assert(params != NULL);
433 
434 	warnx("%s: bootstrap removal is not supported",
435 	    params->machine->name);
436 	return (0);
437 }
438 
439 int
440 no_editboot(ib_params *params)
441 {
442 
443 	assert(params != NULL);
444 
445 	warnx("%s: bootstrap editing is not supported",
446 	    params->machine->name);
447 	return (0);
448 }
449 
450 
451 static void
452 getmachine(ib_params *param, const char *mach, const char *provider)
453 {
454 	int	i;
455 
456 	assert(param != NULL);
457 	assert(mach != NULL);
458 	assert(provider != NULL);
459 
460 	for (i = 0; machines[i].name != NULL; i++) {
461 		if (strcmp(machines[i].name, mach) == 0) {
462 			param->machine = &machines[i];
463 			return;
464 		}
465 	}
466 	warnx("Invalid machine `%s' from %s", mach, provider);
467 	machine_usage();
468 	exit(1);
469 }
470 
471 static void
472 machine_usage(void)
473 {
474 	const char *prefix;
475 	int	i;
476 
477 	warnx("Supported machines are:");
478 #define MACHS_PER_LINE	9
479 	prefix="";
480 	for (i = 0; machines[i].name != NULL; i++) {
481 		if (i == 0)
482 			prefix="\t";
483 		else if (i % MACHS_PER_LINE)
484 			prefix=", ";
485 		else
486 			prefix=",\n\t";
487 		fprintf(stderr, "%s%s", prefix, machines[i].name);
488 	}
489 	fputs("\n", stderr);
490 }
491 
492 static void
493 getfstype(ib_params *param, const char *fstype, const char *provider)
494 {
495 	int i;
496 
497 	assert(param != NULL);
498 	assert(fstype != NULL);
499 	assert(provider != NULL);
500 
501 	for (i = 0; fstypes[i].name != NULL; i++) {
502 		if (strcmp(fstypes[i].name, fstype) == 0) {
503 			param->fstype = &fstypes[i];
504 			return;
505 		}
506 	}
507 	warnx("Invalid file system type `%s' from %s", fstype, provider);
508 	fstype_usage();
509 	exit(1);
510 }
511 
512 static void
513 fstype_usage(void)
514 {
515 	const char *prefix;
516 	int	i;
517 
518 	warnx("Supported file system types are:");
519 #define FSTYPES_PER_LINE	9
520 	prefix="";
521 	for (i = 0; fstypes[i].name != NULL; i++) {
522 		if (i == 0)
523 			prefix="\t";
524 		else if (i % FSTYPES_PER_LINE)
525 			prefix=", ";
526 		else
527 			prefix=",\n\t";
528 		fprintf(stderr, "%s%s", prefix, fstypes[i].name);
529 	}
530 	fputs("\n", stderr);
531 }
532 
533 static void
534 usage(void)
535 {
536 	const char	*prog;
537 
538 	prog = getprogname();
539 	fprintf(stderr,
540 "usage: %s [-nv] [-B s2bno] [-b s1bno] [-m machine] [-o options]\n"
541 "\t\t   [-t fstype] filesystem primary [secondary]\n"
542 "usage: %s -c [-nv] [-m machine] [-o options] [-t fstype] filesystem\n"
543 "usage: %s -e [-nv] [-m machine] [-o options] bootstrap\n",
544 	    prog, prog, prog);
545 	machine_usage();
546 	fstype_usage();
547 	options_usage();
548 	exit(1);
549 }
550