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