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