boot0cfg.c revision 227250
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: head/usr.sbin/boot0cfg/boot0cfg.c 227250 2011-11-06 19:01:35Z ed $");
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 */
56struct opt_offsets {
57	int opt;
58	int drive;
59	int flags;
60	int ticks;
61};
62
63static 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
69static 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
83static const struct {
84    const char *tok;
85    int def;
86} opttbl[] = {
87    {"packet", 0},
88    {"update", 1},
89    {"setdrv", 0}
90};
91static const int nopt = sizeof(opttbl) / sizeof(opttbl[0]);
92
93static const char fmt0[] = "#   flag     start chs   type"
94    "       end chs       offset         size\n";
95
96static const char fmt1[] = "%d   0x%02x   %4u:%3u:%2u   0x%02x"
97    "   %4u:%3u:%2u   %10u   %10u\n";
98
99static int read_mbr(const char *, u_int8_t **, int);
100static void write_mbr(const char *, int, u_int8_t *, int);
101static void display_mbr(u_int8_t *);
102static int boot0version(const u_int8_t *);
103static int boot0bs(const u_int8_t *);
104static void stropt(const char *, int *, int *);
105static int argtoi(const char *, int, int, int);
106static int set_bell(u_int8_t *, int, int);
107static void usage(void);
108
109static unsigned vol_id[5];	/* 4 plus 1 for flag */
110
111static int v_flag;
112/*
113 * Boot manager installation/configuration utility.
114 */
115int
116main(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            s_arg = argtoi(optarg, 1, 5, 's');
172            break;
173        case 't':
174            t_arg = argtoi(optarg, 1, 0xffff, 't');
175            break;
176        default:
177            usage();
178        }
179    argc -= optind;
180    argv += optind;
181    if (argc != 1)
182        usage();
183    disk = g_device_path(*argv);
184    if (disk == NULL)
185        errx(1, "Unable to get providername for %s\n", *argv);
186    up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || s_arg != -1
187	|| t_arg != -1;
188
189    /* open the disk and read in the existing mbr. Either here or
190     * when reading the block from disk, we do check for the version
191     * and abort if a suitable block is not found.
192     */
193    mbr_size = read_mbr(disk, &mbr, !B_flag);
194
195    /* save the existing MBR if we are asked to do so */
196    if (fpath)
197	write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size);
198
199    /*
200     * If we are installing the boot loader, read it from disk and copy the
201     * slice table over from the existing MBR.  If not, then point boot0
202     * back at the MBR we just read in.  After this, boot0 is the data to
203     * write back to disk if we are going to do a write.
204     */
205    if (B_flag) {
206	boot0_size = read_mbr(bpath, &boot0, 1);
207        memcpy(boot0 + OFF_PTBL, mbr + OFF_PTBL,
208	    sizeof(struct dos_partition) * NDOSPART);
209	if (b0_ver == 2)	/* volume serial number support */
210	    memcpy(boot0 + OFF_SERIAL, mbr + OFF_SERIAL, 4);
211    } else {
212	boot0 = mbr;
213	boot0_size = mbr_size;
214    }
215
216    /* set the drive */
217    if (d_arg != -1)
218	boot0[OFF_DRIVE] = d_arg;
219
220    /* set various flags */
221    if (m_arg != -1) {
222	boot0[OFF_FLAGS] &= 0xf0;
223	boot0[OFF_FLAGS] |= m_arg;
224    }
225    if (o_flag) {
226        boot0[OFF_FLAGS] &= o_and;
227        boot0[OFF_FLAGS] |= o_or;
228    }
229
230    /* set the default boot selection */
231    if (s_arg != -1)
232        boot0[OFF_OPT] = s_arg - 1;
233
234    /* set the timeout */
235    if (t_arg != -1)
236        mk2(boot0 + OFF_TICKS, t_arg);
237
238    /* set the bell char */
239    if (o_e != -1 && set_bell(boot0, o_e, 0) != -1)
240	up = 1;
241
242    if (vol_id[4]) {
243	if (b0_ver != 2)
244	    errx(1, "incompatible boot block, cannot set volume ID");
245	boot0[OFF_SERIAL] = vol_id[0];
246	boot0[OFF_SERIAL+1] = vol_id[1];
247	boot0[OFF_SERIAL+2] = vol_id[2];
248	boot0[OFF_SERIAL+3] = vol_id[3];
249	up = 1;	/* force update */
250    }
251    /* write the MBR back to disk */
252    if (up)
253	write_mbr(disk, 0, boot0, boot0_size);
254
255    /* display the MBR */
256    if (v_flag)
257	display_mbr(boot0);
258
259    /* clean up */
260    if (mbr != boot0)
261	free(boot0);
262    free(mbr);
263    free(disk);
264
265    return 0;
266}
267
268/* get or set the 'bell' character to be used in case of errors.
269 * Lookup for a certain code sequence, return -1 if not found.
270 */
271static int
272set_bell(u_int8_t *mbr, int new_bell, int report)
273{
274    /* lookup sequence: 0x100 means skip, 0x200 means done */
275    static unsigned seq[] =
276		{ 0xb0, 0x100, 0xe8, 0x100, 0x100, 0x30, 0xe4, 0x200 };
277    int ofs, i, c;
278    for (ofs = 0x60; ofs < 0x180; ofs++) { /* search range */
279	if (mbr[ofs] != seq[0])	/* search initial pattern */
280	    continue;
281	for (i=0;; i++) {
282	    if (seq[i] == 0x200) {	/* found */
283		c = mbr[ofs+1];
284		if (!report)
285		    mbr[ofs+1] = c = new_bell;
286		else
287		    printf("  bell=%c (0x%x)",
288			(c >= ' ' && c < 0x7f) ? c : ' ', c);
289		return c;
290	    }
291	    if (seq[i] != 0x100 && seq[i] != mbr[ofs+i])
292		break;
293	}
294    }
295    warn("bell not found");
296    return -1;
297}
298/*
299 * Read in the MBR of the disk.  If it is boot0, then use the version to
300 * read in all of it if necessary.  Use pointers to return a malloc'd
301 * buffer containing the MBR and then return its size.
302 */
303static int
304read_mbr(const char *disk, u_int8_t **mbr, int check_version)
305{
306    u_int8_t buf[MBRSIZE];
307    int mbr_size, fd;
308    int ver;
309    ssize_t n;
310
311    if ((fd = open(disk, O_RDONLY)) == -1)
312        err(1, "open %s", disk);
313    if ((n = read(fd, buf, MBRSIZE)) == -1)
314        err(1, "read %s", disk);
315    if (n != MBRSIZE)
316        errx(1, "%s: short read", disk);
317    if (cv2(buf + OFF_MAGIC) != 0xaa55)
318        errx(1, "%s: bad magic", disk);
319
320    if (! (ver = boot0bs(buf))) {
321	if (check_version)
322	    errx(1, "%s: unknown or incompatible boot code", disk);
323    } else if (boot0version(buf) == 0x101) {
324	mbr_size = 1024;
325	if ((*mbr = malloc(mbr_size)) == NULL)
326	    errx(1, "%s: unable to allocate read buffer", disk);
327	if (lseek(fd, 0, SEEK_SET) == -1 ||
328	    (n = read(fd, *mbr, mbr_size)) == -1)
329	    err(1, "%s", disk);
330	if (n != mbr_size)
331	    errx(1, "%s: short read", disk);
332	return (mbr_size);
333    }
334    *mbr = malloc(sizeof(buf));
335    memcpy(*mbr, buf, sizeof(buf));
336
337    return sizeof(buf);
338}
339
340/*
341 * Write out the mbr to the specified file.
342 */
343static void
344write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size)
345{
346    int fd;
347    ssize_t n;
348    const char *errmsg;
349    char *pname;
350    struct gctl_req *grq;
351
352    fd = open(fname, O_WRONLY | flags, 0666);
353    if (fd != -1) {
354	n = write(fd, mbr, mbr_size);
355	close(fd);
356	if (n != mbr_size)
357	   errx(1, "%s: short write", fname);
358	return;
359    }
360
361    /*
362     * If we're called to write to a backup file, don't try to
363     * write through GEOM. It only generates additional errors.
364     */
365    if (flags != 0)
366	return;
367
368    /* Try open it read only. */
369    fd = open(fname, O_RDONLY);
370    if (fd == -1) {
371	warn("error opening %s", fname);
372	return;
373    }
374    pname = g_providername(fd);
375    if (pname == NULL) {
376	warn("error getting providername for %s", fname);
377	return;
378    }
379    grq = gctl_get_handle();
380    gctl_ro_param(grq, "class", -1, "PART");
381    gctl_ro_param(grq, "arg0", -1, pname);
382    gctl_ro_param(grq, "verb", -1, "bootcode");
383    gctl_ro_param(grq, "bootcode", mbr_size, mbr);
384    gctl_ro_param(grq, "flags", -1, "C");
385    errmsg = gctl_issue(grq);
386    if (errmsg == NULL)
387	goto out;
388
389    grq = gctl_get_handle();
390    gctl_ro_param(grq, "verb", -1, "write MBR");
391    gctl_ro_param(grq, "class", -1, "MBR");
392    gctl_ro_param(grq, "geom", -1, pname);
393    gctl_ro_param(grq, "data", mbr_size, mbr);
394    errmsg = gctl_issue(grq);
395    if (errmsg != NULL)
396	err(1, "write_mbr: %s", fname);
397
398out:
399    free(pname);
400    gctl_free(grq);
401}
402
403/*
404 * Outputs an informative dump of the data in the MBR to stdout.
405 */
406static void
407display_mbr(u_int8_t *mbr)
408{
409    struct dos_partition *part;
410    int i, version;
411
412    part = (struct dos_partition *)(mbr + DOSPARTOFF);
413    printf(fmt0);
414    for (i = 0; i < NDOSPART; i++)
415	if (part[i].dp_typ)
416	    printf(fmt1, 1 + i, part[i].dp_flag,
417		part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2),
418		part[i].dp_shd, part[i].dp_ssect & 0x3f, part[i].dp_typ,
419                part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2),
420                part[i].dp_ehd, part[i].dp_esect & 0x3f, part[i].dp_start,
421                part[i].dp_size);
422    printf("\n");
423    version = boot0version(mbr);
424    printf("version=%d.%d  drive=0x%x  mask=0x%x  ticks=%u",
425	version >> 8, version & 0xff, mbr[OFF_DRIVE],
426	mbr[OFF_FLAGS] & 0xf, cv2(mbr + OFF_TICKS));
427    set_bell(mbr, 0, 1);
428    printf("\noptions=");
429    for (i = 0; i < nopt; i++) {
430	if (i)
431	    printf(",");
432	if (!(mbr[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def)
433	    printf("no");
434	printf("%s", opttbl[i].tok);
435    }
436    printf("\n");
437    if (b0_ver == 2)
438	printf("volume serial ID %02x%02x-%02x%02x\n",
439		mbr[OFF_SERIAL], mbr[OFF_SERIAL+1],
440		mbr[OFF_SERIAL+2], mbr[OFF_SERIAL+3]);
441    printf("default_selection=F%d (", mbr[OFF_OPT] + 1);
442    if (mbr[OFF_OPT] < 4)
443	printf("Slice %d", mbr[OFF_OPT] + 1);
444    else
445	printf("Drive 1");
446    printf(")\n");
447}
448
449/*
450 * Return the boot0 version with the minor revision in the low byte, and
451 * the major revision in the next higher byte.
452 */
453static int
454boot0version(const u_int8_t *bs)
455{
456    /* Check for old version, and return 0x100 if found. */
457    int v = boot0bs(bs);
458    if (v != 0)
459        return v << 8;
460
461    /* We have a newer boot0, so extract the version number and return it. */
462    return *(const int *)(bs + OFF_VERSION) & 0xffff;
463}
464
465/* descriptor of a pattern to match.
466 * Start from the first entry trying to match the chunk of bytes,
467 * if you hit an entry with len=0 terminate the search and report
468 * off as the version. Otherwise skip to the next block after len=0
469 * An entry with len=0, off=0 is the end marker.
470  */
471struct byte_pattern {
472    unsigned off;
473    unsigned len;
474    u_int8_t *key;
475};
476
477/*
478 * Decide if we have valid boot0 boot code by looking for
479 * characteristic byte sequences at fixed offsets.
480 */
481static int
482boot0bs(const u_int8_t *bs)
483{
484    /* the initial code sequence */
485    static u_int8_t id0[] = {0xfc, 0x31, 0xc0, 0x8e, 0xc0, 0x8e, 0xd8,
486			     0x8e, 0xd0, 0xbc, 0x00, 0x7c };
487    /* the drive id */
488    static u_int8_t id1[] = {'D', 'r', 'i', 'v', 'e', ' '};
489    static struct byte_pattern patterns[] = {
490        {0x0,   sizeof(id0), id0},
491        {0x1b2, sizeof(id1), id1},
492        {1, 0, NULL},
493        {0x0,   sizeof(id0), id0},	/* version with NT support */
494        {0x1ae, sizeof(id1), id1},
495        {2, 0, NULL},
496        {0, 0, NULL},
497    };
498    struct byte_pattern *p = patterns;
499
500    for (;  p->off || p->len; p++) {
501	if (p->len == 0)
502	    break;
503	if (!memcmp(bs + p->off, p->key, p->len))	/* match */
504	    continue;
505	while (p->len)	/* skip to next block */
506	    p++;
507    }
508    b0_ver = p->off;	/* XXX ugly side effect */
509    return p->off;
510}
511
512/*
513 * Adjust "and" and "or" masks for a -o option argument.
514 */
515static void
516stropt(const char *arg, int *xa, int *xo)
517{
518    const char *q;
519    char *s, *s1;
520    int inv, i, x;
521
522    if (!(s = strdup(arg)))
523        err(1, NULL);
524    for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) {
525        if ((inv = !strncmp(q, "no", 2)))
526            q += 2;
527        for (i = 0; i < nopt; i++)
528            if (!strcmp(q, opttbl[i].tok))
529                break;
530        if (i == nopt)
531            errx(1, "%s: Unknown -o option", q);
532        if (opttbl[i].def)
533            inv ^= 1;
534        x = 1 << (7 - i);
535        if (inv)
536            *xa &= ~x;
537        else
538            *xo |= x;
539    }
540    free(s);
541}
542
543/*
544 * Convert and check an option argument.
545 */
546static int
547argtoi(const char *arg, int lo, int hi, int opt)
548{
549    char *s;
550    long x;
551
552    errno = 0;
553    x = strtol(arg, &s, 0);
554    if (errno || !*arg || *s || x < lo || x > hi)
555        errx(1, "%s: Bad argument to -%c option", arg, opt);
556    return x;
557}
558
559/*
560 * Display usage information.
561 */
562static void
563usage(void)
564{
565    fprintf(stderr, "%s\n%s\n",
566    "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]",
567    "                [-o options] [-s slice] [-t ticks] disk");
568    exit(1);
569}
570