boot0cfg.c revision 50479
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 50479 1999-08-28 01:35:59Z peter $";
30#endif /* not lint */
31
32#include <sys/param.h>
33#include <sys/disklabel.h>
34#include <sys/stat.h>
35
36#include <err.h>
37#include <errno.h>
38#include <fcntl.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_DRIVE	0x1ba	/* offset: setdrv drive */
48#define OFF_FLAGS       0x1bb   /* offset: option flags */
49#define OFF_TICKS       0x1bc   /* offset: clock ticks */
50#define OFF_PTBL        0x1be   /* offset: partition table */
51#define OFF_MAGIC       0x1fe   /* offset: magic number */
52
53#define cv2(p)  ((p)[0] | (p)[1] << 010)
54
55#define mk2(p, x)                               \
56    (p)[0] = (u_int8_t)(x),                     \
57    (p)[1] = (u_int8_t)((x) >> 010)
58
59static const struct {
60    const char *tok;
61    int def;
62} opttbl[] = {
63    {"packet", 0},
64    {"update", 1},
65    {"setdrv", 0}
66};
67static const int nopt = sizeof(opttbl) / sizeof(opttbl[0]);
68
69static const char fmt0[] = "#   flag     start chs   type"
70    "       end chs       offset         size\n";
71
72static const char fmt1[] = "%d   0x%02x   %4u:%3u:%2u   0x%02x"
73    "   %4u:%3u:%2u   %10u   %10u\n";
74
75static int boot0bs(const u_int8_t *);
76static void stropt(const char *, int *, int *);
77static char *mkrdev(const char *);
78static int argtoi(const char *, int, int, int);
79static void usage(void);
80
81/*
82 * Boot manager installation/configuration utility.
83 */
84int
85main(int argc, char *argv[])
86{
87    u_int8_t buf[MBRSIZE];
88    struct dos_partition part[4];
89    const char *bpath, *fpath, *disk;
90    ssize_t n;
91    int B_flag, v_flag, o_flag;
92    int d_arg, m_arg, t_arg;
93    int o_and, o_or;
94    int fd, fd1, up, c, i;
95
96    bpath = "/boot/boot0";
97    fpath = NULL;
98    B_flag = v_flag = o_flag = 0;
99    d_arg = m_arg = t_arg = -1;
100    o_and = 0xff;
101    o_or = 0;
102    while ((c = getopt(argc, argv, "Bvb:d:f:m:o:t:")) != -1)
103        switch (c) {
104        case 'B':
105            B_flag = 1;
106            break;
107        case 'v':
108            v_flag = 1;
109            break;
110        case 'b':
111            bpath = optarg;
112            break;
113        case 'd':
114            d_arg = argtoi(optarg, 0, 0xff, 'd');
115            break;
116        case 'f':
117            fpath = optarg;
118            break;
119        case 'm':
120            m_arg = argtoi(optarg, 0, 0xf, 'm');
121            break;
122        case 'o':
123            stropt(optarg, &o_and, &o_or);
124            o_flag = 1;
125            break;
126        case 't':
127            t_arg = argtoi(optarg, 1, 0xffff, 't');
128            break;
129        default:
130            usage();
131        }
132    argc -= optind;
133    argv += optind;
134    if (argc != 1)
135        usage();
136    disk = mkrdev(*argv);
137    up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || t_arg != -1;
138    if ((fd = open(disk, up ? O_RDWR : O_RDONLY)) == -1)
139        err(1, "%s", disk);
140    if ((n = read(fd, buf, MBRSIZE)) == -1)
141        err(1, "%s", disk);
142    if (n != MBRSIZE)
143        errx(1, "%s: short read", disk);
144    if (cv2(buf + OFF_MAGIC) != 0xaa55)
145        errx(1, "%s: bad magic", disk);
146    if (!B_flag && !boot0bs(buf))
147	errx(1, "%s: unknown or incompatible boot code", disk);
148    if (fpath) {
149        if ((fd1 = open(fpath, O_WRONLY | O_CREAT | O_TRUNC,
150                        0666)) == -1 ||
151            (n = write(fd1, buf, MBRSIZE)) == -1 || close(fd1))
152            err(1, "%s", fpath);
153        if (n != MBRSIZE)
154            errx(1, "%s: short write", fpath);
155    }
156    memcpy(part, buf + OFF_PTBL, sizeof(part));
157    if (B_flag) {
158        if ((fd1 = open(bpath, O_RDONLY)) == -1 ||
159            (n = read(fd1, buf, MBRSIZE)) == -1 || close(fd1))
160            err(1, "%s", bpath);
161        if (n != MBRSIZE)
162            errx(1, "%s: short read", bpath);
163        if (!boot0bs(buf))
164            errx(1, "%s: unknown or incompatible boot code", bpath);
165        memcpy(buf + OFF_PTBL, part, sizeof(part));
166    }
167    if (d_arg != -1)
168	buf[OFF_DRIVE] = d_arg;
169    if (m_arg != -1) {
170	buf[OFF_FLAGS] &= 0xf0;
171	buf[OFF_FLAGS] |= m_arg;
172    }
173    if (o_flag) {
174        buf[OFF_FLAGS] &= o_and;
175        buf[OFF_FLAGS] |= o_or;
176    }
177    if (t_arg != -1)
178        mk2(buf + OFF_TICKS, t_arg);
179    if (up) {
180        if (lseek(fd, 0, SEEK_SET) == -1 ||
181            (n = write(fd, buf, MBRSIZE)) == -1 || close(fd))
182            err(1, "%s", disk);
183        if (n != MBRSIZE)
184            errx(1, "%s: short write", disk);
185    }
186    if (v_flag) {
187        printf(fmt0);
188        for (i = 0; i < 4; i++)
189            if (part[i].dp_typ) {
190                printf(fmt1,
191                       1 + i,
192                       part[i].dp_flag,
193                  part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2),
194                       part[i].dp_shd,
195                       part[i].dp_ssect & 0x3f,
196                       part[i].dp_typ,
197                  part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2),
198                       part[i].dp_ehd,
199                       part[i].dp_esect & 0x3f,
200                       part[i].dp_start,
201                       part[i].dp_size);
202            }
203        printf("\n");
204        printf("drive=0x%x  mask=0x%x  options=", buf[OFF_DRIVE],
205	       buf[OFF_FLAGS] & 0xf);
206        for (i = 0; i < nopt; i++) {
207            if (i)
208                printf(",");
209            if (!(buf[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def)
210                printf("no");
211            printf("%s", opttbl[i].tok);
212        }
213        printf("  ticks=%u\n", cv2(buf + OFF_TICKS));
214    }
215    return 0;
216}
217
218/*
219 * Decide if we have valid boot0 boot code by looking for
220 * characteristic byte sequences at fixed offsets.
221 */
222static int
223boot0bs(const u_int8_t *bs)
224{
225    static u_int8_t id0[] = {0xfe, 0x45, 0xf2, 0xe9, 0x00, 0x8a};
226    static u_int8_t id1[] = {'D', 'r', 'i', 'v', 'e', ' '};
227    static struct {
228	unsigned off;
229	unsigned len;
230	u_int8_t *key;
231    } ident[2] = {
232        {0x1c,  sizeof(id0), id0},
233        {0x1b2, sizeof(id1), id1}
234    };
235    int i;
236
237    for (i = 0; i < sizeof(ident) / sizeof(ident[0]); i++)
238	if (memcmp(bs + ident[i].off, ident[i].key, ident[i].len))
239	    return 0;
240    return 1;
241};
242
243/*
244 * Adjust "and" and "or" masks for a -o option argument.
245 */
246static void
247stropt(const char *arg, int *xa, int *xo)
248{
249    const char *q;
250    char *s, *s1;
251    int inv, i, x;
252
253    if (!(s = strdup(arg)))
254        err(1, NULL);
255    for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) {
256        if ((inv = !strncmp(q, "no", 2)))
257            q += 2;
258        for (i = 0; i < nopt; i++)
259            if (!strcmp(q, opttbl[i].tok))
260                break;
261        if (i == nopt)
262            errx(1, "%s: Unknown -o option", q);
263        if (opttbl[i].def)
264            inv ^= 1;
265        x = 1 << (7 - i);
266        if (inv)
267            *xa &= ~x;
268        else
269            *xo |= x;
270    }
271    free(s);
272}
273
274/*
275 * Produce a device path for a "canonical" name, where appropriate.
276 */
277static char *
278mkrdev(const char *fname)
279{
280    char buf[MAXPATHLEN];
281    struct stat sb;
282    char *s;
283
284    s = (char *)fname;
285    if (!strchr(fname, '/')) {
286        snprintf(buf, sizeof(buf), "%sr%s", _PATH_DEV, fname);
287        if (stat(buf, &sb))
288            snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
289        if (!(s = strdup(buf)))
290            err(1, NULL);
291    }
292    return s;
293}
294
295/*
296 * Convert and check an option argument.
297 */
298static int
299argtoi(const char *arg, int lo, int hi, int opt)
300{
301    char *s;
302    long x;
303
304    errno = 0;
305    x = strtol(arg, &s, 0);
306    if (errno || !*arg || *s || x < lo || x > hi)
307        errx(1, "%s: Bad argument to -%c option", arg, opt);
308    return x;
309}
310
311/*
312 * Display usage information.
313 */
314static void
315usage(void)
316{
317    fprintf(stderr, "%s\n%s\n",
318    "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]",
319    "                [-o options] [-t ticks] disk");
320    exit(1);
321}
322