boot0cfg.c revision 104272
1/*
2 * Copyright (c) 1999 Robert Nordier
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
18 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
19 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
20 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
21 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
24 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#ifndef lint
28static const char rcsid[] =
29  "$FreeBSD: head/usr.sbin/boot0cfg/boot0cfg.c 104272 2002-10-01 07:24:55Z phk $";
30#endif /* not lint */
31
32#include <sys/param.h>
33#include <sys/disklabel.h>
34#include <sys/diskmbr.h>
35#include <sys/stat.h>
36
37#include <err.h>
38#include <errno.h>
39#include <fcntl.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 */
49#define OFF_OPT		0x1b9	/* offset: default boot option */
50#define OFF_DRIVE	0x1ba	/* offset: setdrv drive */
51#define OFF_FLAGS       0x1bb   /* offset: option flags */
52#define OFF_TICKS       0x1bc   /* offset: clock ticks */
53#define OFF_PTBL        0x1be   /* offset: partition table */
54#define OFF_MAGIC       0x1fe   /* offset: magic number */
55
56#define cv2(p)  ((p)[0] | (p)[1] << 010)
57
58#define mk2(p, x)                               \
59    (p)[0] = (u_int8_t)(x),                     \
60    (p)[1] = (u_int8_t)((x) >> 010)
61
62static const struct {
63    const char *tok;
64    int def;
65} opttbl[] = {
66    {"packet", 0},
67    {"update", 1},
68    {"setdrv", 0}
69};
70static const int nopt = sizeof(opttbl) / sizeof(opttbl[0]);
71
72static const char fmt0[] = "#   flag     start chs   type"
73    "       end chs       offset         size\n";
74
75static const char fmt1[] = "%d   0x%02x   %4u:%3u:%2u   0x%02x"
76    "   %4u:%3u:%2u   %10u   %10u\n";
77
78static int read_mbr(const char *, u_int8_t **, int);
79static void write_mbr(const char *, int, u_int8_t *, int);
80static void display_mbr(u_int8_t *);
81static int boot0version(const u_int8_t *);
82static int boot0bs(const u_int8_t *);
83static void stropt(const char *, int *, int *);
84static char *mkrdev(const char *);
85static int argtoi(const char *, int, int, int);
86static void usage(void);
87
88/*
89 * Boot manager installation/configuration utility.
90 */
91int
92main(int argc, char *argv[])
93{
94    u_int8_t *mbr, *boot0;
95    int boot0_size, mbr_size;
96    const char *bpath, *fpath;
97    char *disk;
98    int B_flag, v_flag, o_flag;
99    int d_arg, m_arg, s_arg, t_arg;
100    int o_and, o_or;
101    int up, c;
102
103    bpath = "/boot/boot0";
104    fpath = NULL;
105    B_flag = v_flag = o_flag = 0;
106    d_arg = m_arg = s_arg = t_arg = -1;
107    o_and = 0xff;
108    o_or = 0;
109    while ((c = getopt(argc, argv, "Bvb:d:f:m:o:s:t:")) != -1)
110        switch (c) {
111        case 'B':
112            B_flag = 1;
113            break;
114        case 'v':
115            v_flag = 1;
116            break;
117        case 'b':
118            bpath = optarg;
119            break;
120        case 'd':
121            d_arg = argtoi(optarg, 0, 0xff, 'd');
122            break;
123        case 'f':
124            fpath = optarg;
125            break;
126        case 'm':
127            m_arg = argtoi(optarg, 0, 0xf, 'm');
128            break;
129        case 'o':
130            stropt(optarg, &o_and, &o_or);
131            o_flag = 1;
132            break;
133        case 's':
134            s_arg = argtoi(optarg, 1, 5, 's');
135            break;
136        case 't':
137            t_arg = argtoi(optarg, 1, 0xffff, 't');
138            break;
139        default:
140            usage();
141        }
142    argc -= optind;
143    argv += optind;
144    if (argc != 1)
145        usage();
146    disk = mkrdev(*argv);
147    up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || s_arg != -1
148	|| t_arg != -1;
149
150    /* open the disk and read in the existing mbr */
151    mbr_size = read_mbr(disk, &mbr, !B_flag);
152
153    /* save the existing MBR if we are asked to do so */
154    if (fpath)
155	write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size);
156
157    /*
158     * If we are installing the boot loader, read it from disk and copy the
159     * slice table over from the existing MBR.  If not, then point boot0
160     * back at the MBR we just read in.  After this, boot0 is the data to
161     * write back to disk if we are going to do a write.
162     */
163    if (B_flag) {
164	boot0_size = read_mbr(bpath, &boot0, 1);
165        memcpy(boot0 + OFF_PTBL, mbr + OFF_PTBL,
166	    sizeof(struct dos_partition) * NDOSPART);
167    } else {
168	boot0 = mbr;
169	boot0_size = mbr_size;
170    }
171
172    /* set the drive */
173    if (d_arg != -1)
174	boot0[OFF_DRIVE] = d_arg;
175
176    /* set various flags */
177    if (m_arg != -1) {
178	boot0[OFF_FLAGS] &= 0xf0;
179	boot0[OFF_FLAGS] |= m_arg;
180    }
181    if (o_flag) {
182        boot0[OFF_FLAGS] &= o_and;
183        boot0[OFF_FLAGS] |= o_or;
184    }
185
186    /* set the default boot selection */
187    if (s_arg != -1)
188        boot0[OFF_OPT] = s_arg - 1;
189
190    /* set the timeout */
191    if (t_arg != -1)
192        mk2(boot0 + OFF_TICKS, t_arg);
193
194    /* write the MBR back to disk */
195    if (up)
196	write_mbr(disk, 0, boot0, boot0_size);
197
198    /* display the MBR */
199    if (v_flag)
200	display_mbr(boot0);
201
202    /* clean up */
203    if (mbr != boot0)
204	free(boot0);
205    free(mbr);
206    free(disk);
207
208    return 0;
209}
210
211/*
212 * Read in the MBR of the disk.  If it is boot0, then use the version to
213 * read in all of it if necessary.  Use pointers to return a malloc'd
214 * buffer containing the MBR and then return its size.
215 */
216static int
217read_mbr(const char *disk, u_int8_t **mbr, int check_version)
218{
219    u_int8_t buf[MBRSIZE];
220    int mbr_size, fd;
221    ssize_t n;
222
223    if ((fd = open(disk, O_RDONLY)) == -1)
224        err(1, "%s", disk);
225    if ((n = read(fd, buf, MBRSIZE)) == -1)
226        err(1, "%s", disk);
227    if (n != MBRSIZE)
228        errx(1, "%s: short read", disk);
229    if (cv2(buf + OFF_MAGIC) != 0xaa55)
230        errx(1, "%s: bad magic", disk);
231
232    if (!boot0bs(buf)) {
233	if (check_version)
234	    errx(1, "%s: unknown or incompatible boot code", disk);
235    } else if (boot0version(buf) == 0x101) {
236	mbr_size = 1024;
237	if ((*mbr = malloc(mbr_size)) == NULL)
238	    errx(1, "%s: unable to allocate read buffer", disk);
239	if (lseek(fd, 0, SEEK_SET) == -1 ||
240	    (n = read(fd, *mbr, mbr_size)) == -1)
241	    err(1, "%s", disk);
242	if (n != mbr_size)
243	    errx(1, "%s: short read", disk);
244	return (mbr_size);
245    }
246    *mbr = malloc(sizeof(buf));
247    memcpy(*mbr, buf, sizeof(buf));
248
249    return sizeof(buf);
250}
251
252/*
253 * Write out the mbr to the specified file.
254 */
255static void
256write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size)
257{
258    int fd;
259    ssize_t n;
260
261    if ((fd = open(fname, O_WRONLY | flags, 0666)) == -1 ||
262	(n = write(fd, mbr, mbr_size)) == -1 || close(fd))
263	err(1, "%s", fname);
264    if (n != mbr_size)
265	errx(1, "%s: short write", fname);
266}
267
268/*
269 * Outputs an informative dump of the data in the MBR to stdout.
270 */
271static void
272display_mbr(u_int8_t *mbr)
273{
274    struct dos_partition *part;
275    int i, version;
276
277    part = (struct dos_partition *)(mbr + DOSPARTOFF);
278    printf(fmt0);
279    for (i = 0; i < NDOSPART; i++)
280	if (part[i].dp_typ)
281	    printf(fmt1, 1 + i, part[i].dp_flag,
282		part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2),
283		part[i].dp_shd, part[i].dp_ssect & 0x3f, part[i].dp_typ,
284                part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2),
285                part[i].dp_ehd, part[i].dp_esect & 0x3f, part[i].dp_start,
286                part[i].dp_size);
287    printf("\n");
288    version = boot0version(mbr);
289    printf("version=%d.%d  drive=0x%x  mask=0x%x  ticks=%u\noptions=",
290	version >> 8, version & 0xff, mbr[OFF_DRIVE],
291	mbr[OFF_FLAGS] & 0xf, cv2(mbr + OFF_TICKS));
292    for (i = 0; i < nopt; i++) {
293	if (i)
294	    printf(",");
295	if (!(mbr[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def)
296	    printf("no");
297	printf("%s", opttbl[i].tok);
298    }
299    printf("\n");
300    printf("default_selection=F%d (", mbr[OFF_OPT] + 1);
301    if (mbr[OFF_OPT] < 4)
302	printf("Slice %d", mbr[OFF_OPT] + 1);
303    else
304	printf("Drive 1");
305    printf(")\n");
306}
307
308/*
309 * Return the boot0 version with the minor revision in the low byte, and
310 * the major revision in the next higher byte.
311 */
312static int
313boot0version(const u_int8_t *bs)
314{
315    static u_int8_t idold[] = {0xfe, 0x45, 0xf2, 0xe9, 0x00, 0x8a};
316
317    /* Check for old version, and return 0x100 if found. */
318    if (memcmp(bs + 0x1c, idold, sizeof(idold)) == 0)
319        return 0x100;
320
321    /* We have a newer boot0, so extract the version number and return it. */
322    return *(const int *)(bs + OFF_VERSION) & 0xffff;
323}
324
325/*
326 * Decide if we have valid boot0 boot code by looking for
327 * characteristic byte sequences at fixed offsets.
328 */
329static int
330boot0bs(const u_int8_t *bs)
331{
332    static u_int8_t id0[] = {0xfc, 0x31, 0xc0, 0x8e, 0xc0, 0x8e, 0xd8,
333			     0x8e, 0xd0, 0xbc, 0x00, 0x7c };
334    static u_int8_t id1[] = {'D', 'r', 'i', 'v', 'e', ' '};
335    static struct {
336	unsigned off;
337	unsigned len;
338	u_int8_t *key;
339    } ident[2] = {
340        {0x0,   sizeof(id0), id0},
341        {0x1b2, sizeof(id1), id1}
342    };
343    unsigned int i;
344
345    for (i = 0; i < sizeof(ident) / sizeof(ident[0]); i++)
346        if (memcmp(bs + ident[i].off, ident[i].key, ident[i].len))
347	    return 0;
348    return 1;
349};
350
351/*
352 * Adjust "and" and "or" masks for a -o option argument.
353 */
354static void
355stropt(const char *arg, int *xa, int *xo)
356{
357    const char *q;
358    char *s, *s1;
359    int inv, i, x;
360
361    if (!(s = strdup(arg)))
362        err(1, NULL);
363    for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) {
364        if ((inv = !strncmp(q, "no", 2)))
365            q += 2;
366        for (i = 0; i < nopt; i++)
367            if (!strcmp(q, opttbl[i].tok))
368                break;
369        if (i == nopt)
370            errx(1, "%s: Unknown -o option", q);
371        if (opttbl[i].def)
372            inv ^= 1;
373        x = 1 << (7 - i);
374        if (inv)
375            *xa &= ~x;
376        else
377            *xo |= x;
378    }
379    free(s);
380}
381
382/*
383 * Produce a device path for a "canonical" name, where appropriate.
384 */
385static char *
386mkrdev(const char *fname)
387{
388    char buf[MAXPATHLEN];
389    char *s;
390
391    if (!strchr(fname, '/')) {
392	snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
393        s = strdup(buf);
394    } else
395        s = strdup(fname);
396
397    if (s == NULL)
398        errx(1, "No more memory");
399    return s;
400}
401
402/*
403 * Convert and check an option argument.
404 */
405static int
406argtoi(const char *arg, int lo, int hi, int opt)
407{
408    char *s;
409    long x;
410
411    errno = 0;
412    x = strtol(arg, &s, 0);
413    if (errno || !*arg || *s || x < lo || x > hi)
414        errx(1, "%s: Bad argument to -%c option", arg, opt);
415    return x;
416}
417
418/*
419 * Display usage information.
420 */
421static void
422usage(void)
423{
424    fprintf(stderr, "%s\n%s\n",
425    "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]",
426    "                [-o options] [-s slice] [-t ticks] disk");
427    exit(1);
428}
429