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