xref: /freebsd/usr.sbin/boot0cfg/boot0cfg.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /*
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008 Luigi Rizzo
5  * Copyright (c) 1999 Robert Nordier
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
23  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
27  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/disklabel.h>
35 #include <sys/diskmbr.h>
36 #include <sys/stat.h>
37 
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <libgeom.h>
42 #include <paths.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 
48 #define MBRSIZE         512     /* master boot record size */
49 
50 #define OFF_VERSION	0x1b0	/* offset: version number, only boot0version */
51 #define OFF_SERIAL	0x1b8	/* offset: volume serial number */
52 #define OFF_PTBL        0x1be   /* offset: partition table */
53 #define OFF_MAGIC       0x1fe   /* offset: magic number */
54 /*
55  * Offsets to the parameters of the 512-byte boot block.
56  * For historical reasons they are set as macros
57  */
58 struct opt_offsets {
59 	int opt;
60 	int drive;
61 	int flags;
62 	int ticks;
63 };
64 
65 static struct opt_offsets b0_ofs[] = {
66 	{ 0x0, 0x0, 0x0, 0x0 },		/* no boot block */
67 	{ 0x1b9, 0x1ba, 0x1bb, 0x1bc },	/* original block */
68 	{ 0x1b5, 0x1b6, 0x1b7, 0x1bc },	/* NT_SERIAL block */
69 };
70 
71 static int b0_ver;	/* boot block version set by boot0bs */
72 
73 #define OFF_OPT		(b0_ofs[b0_ver].opt)	/* default boot option */
74 #define OFF_DRIVE	(b0_ofs[b0_ver].drive)	/* setdrv drive */
75 #define OFF_FLAGS       (b0_ofs[b0_ver].flags)	/* option flags */
76 #define OFF_TICKS       (b0_ofs[b0_ver].ticks)	/* clock ticks */
77 
78 
79 #define cv2(p)  ((p)[0] | (p)[1] << 010)
80 
81 #define mk2(p, x)                               \
82     (p)[0] = (u_int8_t)(x),                     \
83     (p)[1] = (u_int8_t)((x) >> 010)
84 
85 static const struct {
86     const char *tok;
87     int def;
88 } opttbl[] = {
89     {"packet", 0},
90     {"update", 1},
91     {"setdrv", 0}
92 };
93 static const int nopt = nitems(opttbl);
94 
95 static const char fmt0[] = "#   flag     start chs   type"
96     "       end chs       offset         size\n";
97 
98 static const char fmt1[] = "%d   0x%02x   %4u:%3u:%2u   0x%02x"
99     "   %4u:%3u:%2u   %10u   %10u\n";
100 
101 static int geom_class_available(const char *);
102 static int read_mbr(const char *, u_int8_t **, int);
103 static void write_mbr(const char *, int, u_int8_t *, int, int);
104 static void display_mbr(u_int8_t *);
105 static int boot0version(const u_int8_t *);
106 static int boot0bs(const u_int8_t *);
107 static void stropt(const char *, int *, int *);
108 static int argtoi(const char *, int, int, int);
109 static int set_bell(u_int8_t *, int, int);
110 static void usage(void);
111 
112 static unsigned vol_id[5];	/* 4 plus 1 for flag */
113 
114 static int v_flag;
115 /*
116  * Boot manager installation/configuration utility.
117  */
118 int
119 main(int argc, char *argv[])
120 {
121     u_int8_t *mbr, *boot0;
122     int boot0_size, mbr_size;
123     const char *bpath, *fpath;
124     char *disk;
125     int B_flag, o_flag;
126     int d_arg, m_arg, s_arg, t_arg;
127     int o_and, o_or, o_e = -1;
128     int up, c;
129 
130     bpath = "/boot/boot0";
131     fpath = NULL;
132     B_flag = v_flag = o_flag = 0;
133     d_arg = m_arg = s_arg = t_arg = -1;
134     o_and = 0xff;
135     o_or = 0;
136     while ((c = getopt(argc, argv, "Bvb:d:e:f:i:m:o:s:t:")) != -1)
137         switch (c) {
138         case 'B':
139             B_flag = 1;
140             break;
141         case 'v':
142             v_flag = 1;
143             break;
144         case 'b':
145             bpath = optarg;
146             break;
147         case 'd':
148             d_arg = argtoi(optarg, 0, 0xff, 'd');
149             break;
150         case 'e':
151 	    if (optarg[0] == '0' && optarg[1] == 'x')
152 		sscanf(optarg, "0x%02x", &o_e);
153 	    else
154 		o_e = optarg[0];
155             break;
156         case 'f':
157             fpath = optarg;
158             break;
159         case 'i':
160             if (sscanf(optarg, "%02x%02x-%02x%02x",
161 		vol_id, vol_id+1, vol_id+2, vol_id+3) == 4)
162 			vol_id[4] = 1;
163 	    else
164 		errx(1, "bad argument %s", optarg);
165             break;
166         case 'm':
167             m_arg = argtoi(optarg, 0, 0xf, 'm');
168             break;
169         case 'o':
170             stropt(optarg, &o_and, &o_or);
171             o_flag = 1;
172             break;
173         case 's':
174 	    if (strcasecmp(optarg, "pxe") == 0)
175 		s_arg = 6;
176 	    else
177 		s_arg = argtoi(optarg, 1, 6, 's');
178             break;
179         case 't':
180             t_arg = argtoi(optarg, 1, 0xffff, 't');
181             break;
182         default:
183             usage();
184         }
185     argc -= optind;
186     argv += optind;
187     if (argc != 1)
188         usage();
189     disk = g_device_path(*argv);
190     if (disk == NULL)
191         errx(1, "Unable to get providername for %s\n", *argv);
192     up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || s_arg != -1
193 	|| t_arg != -1;
194 
195     /* open the disk and read in the existing mbr. Either here or
196      * when reading the block from disk, we do check for the version
197      * and abort if a suitable block is not found.
198      */
199     mbr_size = read_mbr(disk, &mbr, !B_flag);
200 
201     /* save the existing MBR if we are asked to do so */
202     if (fpath)
203 	write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size, 0);
204 
205     /*
206      * If we are installing the boot loader, read it from disk and copy the
207      * slice table over from the existing MBR.  If not, then point boot0
208      * back at the MBR we just read in.  After this, boot0 is the data to
209      * write back to disk if we are going to do a write.
210      */
211     if (B_flag) {
212 	boot0_size = read_mbr(bpath, &boot0, 1);
213         memcpy(boot0 + OFF_PTBL, mbr + OFF_PTBL,
214 	    sizeof(struct dos_partition) * NDOSPART);
215 	if (b0_ver == 2)	/* volume serial number support */
216 	    memcpy(boot0 + OFF_SERIAL, mbr + OFF_SERIAL, 4);
217     } else {
218 	boot0 = mbr;
219 	boot0_size = mbr_size;
220     }
221 
222     /* set the drive */
223     if (d_arg != -1)
224 	boot0[OFF_DRIVE] = d_arg;
225 
226     /* set various flags */
227     if (m_arg != -1) {
228 	boot0[OFF_FLAGS] &= 0xf0;
229 	boot0[OFF_FLAGS] |= m_arg;
230     }
231     if (o_flag) {
232         boot0[OFF_FLAGS] &= o_and;
233         boot0[OFF_FLAGS] |= o_or;
234     }
235 
236     /* set the default boot selection */
237     if (s_arg != -1)
238         boot0[OFF_OPT] = s_arg - 1;
239 
240     /* set the timeout */
241     if (t_arg != -1)
242         mk2(boot0 + OFF_TICKS, t_arg);
243 
244     /* set the bell char */
245     if (o_e != -1 && set_bell(boot0, o_e, 0) != -1)
246 	up = 1;
247 
248     if (vol_id[4]) {
249 	if (b0_ver != 2)
250 	    errx(1, "incompatible boot block, cannot set volume ID");
251 	boot0[OFF_SERIAL] = vol_id[0];
252 	boot0[OFF_SERIAL+1] = vol_id[1];
253 	boot0[OFF_SERIAL+2] = vol_id[2];
254 	boot0[OFF_SERIAL+3] = vol_id[3];
255 	up = 1;	/* force update */
256     }
257     /* write the MBR back to disk */
258     if (up)
259 	write_mbr(disk, 0, boot0, boot0_size, vol_id[4] || b0_ver == 1);
260 
261     /* display the MBR */
262     if (v_flag)
263 	display_mbr(boot0);
264 
265     /* clean up */
266     if (mbr != boot0)
267 	free(boot0);
268     free(mbr);
269     free(disk);
270 
271     return 0;
272 }
273 
274 /* get or set the 'bell' character to be used in case of errors.
275  * Lookup for a certain code sequence, return -1 if not found.
276  */
277 static int
278 set_bell(u_int8_t *mbr, int new_bell, int report)
279 {
280     /* lookup sequence: 0x100 means skip, 0x200 means done */
281     static unsigned seq[] =
282 		{ 0xb0, 0x100, 0xe8, 0x100, 0x100, 0x30, 0xe4, 0x200 };
283     int ofs, i, c;
284     for (ofs = 0x60; ofs < 0x180; ofs++) { /* search range */
285 	if (mbr[ofs] != seq[0])	/* search initial pattern */
286 	    continue;
287 	for (i=0;; i++) {
288 	    if (seq[i] == 0x200) {	/* found */
289 		c = mbr[ofs+1];
290 		if (!report)
291 		    mbr[ofs+1] = c = new_bell;
292 		else
293 		    printf("  bell=%c (0x%x)",
294 			(c >= ' ' && c < 0x7f) ? c : ' ', c);
295 		return c;
296 	    }
297 	    if (seq[i] != 0x100 && seq[i] != mbr[ofs+i])
298 		break;
299 	}
300     }
301     warn("bell not found");
302     return -1;
303 }
304 /*
305  * Read in the MBR of the disk.  If it is boot0, then use the version to
306  * read in all of it if necessary.  Use pointers to return a malloc'd
307  * buffer containing the MBR and then return its size.
308  */
309 static int
310 read_mbr(const char *disk, u_int8_t **mbr, int check_version)
311 {
312     u_int8_t buf[MBRSIZE];
313     int mbr_size, fd;
314     int ver;
315     ssize_t n;
316 
317     if ((fd = open(disk, O_RDONLY)) == -1)
318         err(1, "open %s", disk);
319     if ((n = read(fd, buf, MBRSIZE)) == -1)
320         err(1, "read %s", disk);
321     if (n != MBRSIZE)
322         errx(1, "%s: short read", disk);
323     if (cv2(buf + OFF_MAGIC) != 0xaa55)
324         errx(1, "%s: bad magic", disk);
325 
326     if (! (ver = boot0bs(buf))) {
327 	if (check_version)
328 	    errx(1, "%s: unknown or incompatible boot code", disk);
329     } else if (boot0version(buf) == 0x101) {
330 	mbr_size = 1024;
331 	if ((*mbr = malloc(mbr_size)) == NULL)
332 	    errx(1, "%s: unable to allocate read buffer", disk);
333 	if (lseek(fd, 0, SEEK_SET) == -1 ||
334 	    (n = read(fd, *mbr, mbr_size)) == -1)
335 	    err(1, "%s", disk);
336 	if (n != mbr_size)
337 	    errx(1, "%s: short read", disk);
338 	close(fd);
339 	return (mbr_size);
340     }
341     if ((*mbr = malloc(sizeof(buf))) == NULL)
342 	errx(1, "%s: unable to allocate MBR buffer", disk);
343     memcpy(*mbr, buf, sizeof(buf));
344     close(fd);
345 
346     return sizeof(buf);
347 }
348 
349 static int
350 geom_class_available(const char *name)
351 {
352 	struct gclass *class;
353 	struct gmesh mesh;
354 	int error;
355 
356 	error = geom_gettree(&mesh);
357 	if (error != 0)
358 		errc(1, error, "Cannot get GEOM tree");
359 
360 	LIST_FOREACH(class, &mesh.lg_class, lg_class) {
361 		if (strcmp(class->lg_name, name) == 0) {
362 			geom_deletetree(&mesh);
363 			return (1);
364 		}
365 	}
366 
367 	geom_deletetree(&mesh);
368 	return (0);
369 }
370 
371 /*
372  * Write out the mbr to the specified file.
373  */
374 static void
375 write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size,
376     int disable_dsn)
377 {
378 	struct gctl_req *grq;
379 	const char *errmsg;
380 	char *pname;
381 	ssize_t n;
382 	int fd;
383 
384 	fd = open(fname, O_WRONLY | flags, 0666);
385 	if (fd != -1) {
386 		n = write(fd, mbr, mbr_size);
387 		close(fd);
388 		if (n != mbr_size)
389 			errx(1, "%s: short write", fname);
390 		return;
391 	}
392 
393 	/*
394 	 * If we're called to write to a backup file, don't try to
395 	 * write through GEOM.
396 	 */
397 	if (flags != 0)
398 		err(1, "can't open file %s to write backup", fname);
399 
400 	/* Try open it read only. */
401 	fd = open(fname, O_RDONLY);
402 	if (fd == -1) {
403 		warn("error opening %s", fname);
404 		return;
405 	}
406 
407 	pname = g_providername(fd);
408 	if (pname == NULL) {
409 		warn("error getting providername for %s", fname);
410 		return;
411 	}
412 
413 	/* First check that GEOM_PART is available */
414 	if (geom_class_available("PART") != 0) {
415 		grq = gctl_get_handle();
416 		gctl_ro_param(grq, "class", -1, "PART");
417 		gctl_ro_param(grq, "arg0", -1, pname);
418 		gctl_ro_param(grq, "verb", -1, "bootcode");
419 		gctl_ro_param(grq, "bootcode", mbr_size, mbr);
420 		gctl_ro_param(grq, "flags", -1, "C");
421 		if (disable_dsn)
422 			gctl_ro_param(grq, "skip_dsn", sizeof(int),
423 			    &disable_dsn);
424 		errmsg = gctl_issue(grq);
425 		if (errmsg != NULL && errmsg[0] != '\0')
426 			errx(1, "GEOM_PART: write bootcode to %s failed: %s",
427 			    fname, errmsg);
428 		gctl_free(grq);
429 	} else
430 		errx(1, "can't write MBR to %s", fname);
431 	free(pname);
432 }
433 
434 /*
435  * Outputs an informative dump of the data in the MBR to stdout.
436  */
437 static void
438 display_mbr(u_int8_t *mbr)
439 {
440     struct dos_partition *part;
441     int i, version;
442 
443     part = (struct dos_partition *)(mbr + DOSPARTOFF);
444     printf(fmt0);
445     for (i = 0; i < NDOSPART; i++)
446 	if (part[i].dp_typ)
447 	    printf(fmt1, 1 + i, part[i].dp_flag,
448 		part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2),
449 		part[i].dp_shd, part[i].dp_ssect & 0x3f, part[i].dp_typ,
450                 part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2),
451                 part[i].dp_ehd, part[i].dp_esect & 0x3f, part[i].dp_start,
452                 part[i].dp_size);
453     printf("\n");
454     version = boot0version(mbr);
455     printf("version=%d.%d  drive=0x%x  mask=0x%x  ticks=%u",
456 	version >> 8, version & 0xff, mbr[OFF_DRIVE],
457 	mbr[OFF_FLAGS] & 0xf, cv2(mbr + OFF_TICKS));
458     set_bell(mbr, 0, 1);
459     printf("\noptions=");
460     for (i = 0; i < nopt; i++) {
461 	if (i)
462 	    printf(",");
463 	if (!(mbr[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def)
464 	    printf("no");
465 	printf("%s", opttbl[i].tok);
466     }
467     printf("\n");
468     if (b0_ver == 2)
469 	printf("volume serial ID %02x%02x-%02x%02x\n",
470 		mbr[OFF_SERIAL], mbr[OFF_SERIAL+1],
471 		mbr[OFF_SERIAL+2], mbr[OFF_SERIAL+3]);
472     printf("default_selection=F%d (", mbr[OFF_OPT] + 1);
473     if (mbr[OFF_OPT] < 4)
474 	printf("Slice %d", mbr[OFF_OPT] + 1);
475     else if (mbr[OFF_OPT] == 4)
476 	printf("Drive 1");
477     else
478 	printf("PXE");
479     printf(")\n");
480 }
481 
482 /*
483  * Return the boot0 version with the minor revision in the low byte, and
484  * the major revision in the next higher byte.
485  */
486 static int
487 boot0version(const u_int8_t *bs)
488 {
489     /* Check for old version, and return 0x100 if found. */
490     int v = boot0bs(bs);
491     if (v != 0)
492         return v << 8;
493 
494     /* We have a newer boot0, so extract the version number and return it. */
495     return *(const int *)(bs + OFF_VERSION) & 0xffff;
496 }
497 
498 /* descriptor of a pattern to match.
499  * Start from the first entry trying to match the chunk of bytes,
500  * if you hit an entry with len=0 terminate the search and report
501  * off as the version. Otherwise skip to the next block after len=0
502  * An entry with len=0, off=0 is the end marker.
503   */
504 struct byte_pattern {
505     unsigned off;
506     unsigned len;
507     u_int8_t *key;
508 };
509 
510 /*
511  * Decide if we have valid boot0 boot code by looking for
512  * characteristic byte sequences at fixed offsets.
513  */
514 static int
515 boot0bs(const u_int8_t *bs)
516 {
517     /* the initial code sequence */
518     static u_int8_t id0[] = {0xfc, 0x31, 0xc0, 0x8e, 0xc0, 0x8e, 0xd8,
519 			     0x8e, 0xd0, 0xbc, 0x00, 0x7c };
520     /* the drive id */
521     static u_int8_t id1[] = {'D', 'r', 'i', 'v', 'e', ' '};
522     static struct byte_pattern patterns[] = {
523         {0x0,   sizeof(id0), id0},
524         {0x1b2, sizeof(id1), id1},
525         {1, 0, NULL},
526         {0x0,   sizeof(id0), id0},	/* version with NT support */
527         {0x1ae, sizeof(id1), id1},
528         {2, 0, NULL},
529         {0, 0, NULL},
530     };
531     struct byte_pattern *p = patterns;
532 
533     for (;  p->off || p->len; p++) {
534 	if (p->len == 0)
535 	    break;
536 	if (!memcmp(bs + p->off, p->key, p->len))	/* match */
537 	    continue;
538 	while (p->len)	/* skip to next block */
539 	    p++;
540     }
541     b0_ver = p->off;	/* XXX ugly side effect */
542     return p->off;
543 }
544 
545 /*
546  * Adjust "and" and "or" masks for a -o option argument.
547  */
548 static void
549 stropt(const char *arg, int *xa, int *xo)
550 {
551     const char *q;
552     char *s, *s1;
553     int inv, i, x;
554 
555     if (!(s = strdup(arg)))
556         err(1, NULL);
557     for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) {
558         if ((inv = !strncmp(q, "no", 2)))
559             q += 2;
560         for (i = 0; i < nopt; i++)
561             if (!strcmp(q, opttbl[i].tok))
562                 break;
563         if (i == nopt)
564             errx(1, "%s: Unknown -o option", q);
565         if (opttbl[i].def)
566             inv ^= 1;
567         x = 1 << (7 - i);
568         if (inv)
569             *xa &= ~x;
570         else
571             *xo |= x;
572     }
573     free(s);
574 }
575 
576 /*
577  * Convert and check an option argument.
578  */
579 static int
580 argtoi(const char *arg, int lo, int hi, int opt)
581 {
582     char *s;
583     long x;
584 
585     errno = 0;
586     x = strtol(arg, &s, 0);
587     if (errno || !*arg || *s || x < lo || x > hi)
588         errx(1, "%s: Bad argument to -%c option", arg, opt);
589     return x;
590 }
591 
592 /*
593  * Display usage information.
594  */
595 static void
596 usage(void)
597 {
598     fprintf(stderr, "%s\n%s\n",
599     "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]",
600     "                [-o options] [-s slice] [-t ticks] disk");
601     exit(1);
602 }
603