Merge from vendor branch CVS:
[dragonfly.git] / usr.sbin / boot0cfg / boot0cfg.c
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  * $FreeBSD: src/usr.sbin/boot0cfg/boot0cfg.c,v 1.7.2.4 2002/03/16 01:06:51 mikeh Exp $
27  * $DragonFly: src/usr.sbin/boot0cfg/boot0cfg.c,v 1.4 2004/06/26 02:04:39 dillon Exp $
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 <paths.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43
44 #define MBRSIZE         512     /* master boot record size */
45
46 #define OFF_VERSION     0x1b0   /* offset: version number */
47 #define OFF_OPT         0x1b9   /* offset: default boot option */
48 #define OFF_DRIVE       0x1ba   /* offset: setdrv drive */
49 #define OFF_FLAGS       0x1bb   /* offset: option flags */
50 #define OFF_TICKS       0x1bc   /* offset: clock ticks */
51 #define OFF_PTBL        0x1be   /* offset: partition table */
52 #define OFF_MAGIC       0x1fe   /* offset: magic number */
53
54 #define cv2(p)  ((p)[0] | (p)[1] << 010)
55
56 #define mk2(p, x)                               \
57     (p)[0] = (u_int8_t)(x),                     \
58     (p)[1] = (u_int8_t)((x) >> 010)
59
60 static const struct {
61     const char *tok;
62     int def;
63 } opttbl[] = {
64     {"packet", 0},
65     {"update", 1},
66     {"setdrv", 0}
67 };
68 static const int nopt = sizeof(opttbl) / sizeof(opttbl[0]);
69
70 static const char fmt0[] = "#   flag     start chs   type"
71     "       end chs       offset         size\n";
72
73 static const char fmt1[] = "%d   0x%02x   %4u:%3u:%2u   0x%02x"
74     "   %4u:%3u:%2u   %10u   %10u\n";
75
76 static int read_mbr(const char *, u_int8_t **, int);
77 static void write_mbr(const char *, int, u_int8_t *, int);
78 static void display_mbr(u_int8_t *);
79 static int boot0version(const u_int8_t *);
80 static int boot0bs(const u_int8_t *);
81 static void stropt(const char *, int *, int *);
82 static char *mkrdev(const char *);
83 static int argtoi(const char *, int, int, int);
84 static void usage(void);
85
86 /*
87  * Boot manager installation/configuration utility.
88  */
89 int
90 main(int argc, char *argv[])
91 {
92     u_int8_t *mbr, *boot0;
93     int boot0_size, mbr_size;
94     const char *bpath, *fpath;
95     char *disk;
96     int B_flag, v_flag, o_flag;
97     int d_arg, m_arg, s_arg, t_arg;
98     int o_and, o_or;
99     int up, c;
100
101     bpath = "/boot/boot0";
102     fpath = NULL;
103     B_flag = v_flag = o_flag = 0;
104     d_arg = m_arg = s_arg = t_arg = -1;
105     o_and = 0xff;
106     o_or = 0;
107     while ((c = getopt(argc, argv, "Bvb:d:f:m:o:s:t:")) != -1)
108         switch (c) {
109         case 'B':
110             B_flag = 1;
111             break;
112         case 'v':
113             v_flag = 1;
114             break;
115         case 'b':
116             bpath = optarg;
117             break;
118         case 'd':
119             d_arg = argtoi(optarg, 0, 0xff, 'd');
120             break;
121         case 'f':
122             fpath = optarg;
123             break;
124         case 'm':
125             m_arg = argtoi(optarg, 0, 0xf, 'm');
126             break;
127         case 'o':
128             stropt(optarg, &o_and, &o_or);
129             o_flag = 1;
130             break;
131         case 's':
132             s_arg = argtoi(optarg, 1, 5, 's');
133             break;
134         case 't':
135             t_arg = argtoi(optarg, 1, 0xffff, 't');
136             break;
137         default:
138             usage();
139         }
140     argc -= optind;
141     argv += optind;
142     if (argc != 1)
143         usage();
144     disk = mkrdev(*argv);
145     up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || s_arg != -1
146         || t_arg != -1;
147
148     /* open the disk and read in the existing mbr */
149     mbr_size = read_mbr(disk, &mbr, !B_flag);
150
151     /* save the existing MBR if we are asked to do so */
152     if (fpath)
153         write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size);
154
155     /*
156      * If we are installing the boot loader, read it from disk and copy the
157      * slice table over from the existing MBR.  If not, then point boot0
158      * back at the MBR we just read in.  After this, boot0 is the data to
159      * write back to disk if we are going to do a write.
160      */
161     if (B_flag) {
162         boot0_size = read_mbr(bpath, &boot0, 1);
163         memcpy(boot0 + OFF_PTBL, mbr + OFF_PTBL,
164             sizeof(struct dos_partition) * NDOSPART);
165     } else {
166         boot0 = mbr;
167         boot0_size = mbr_size;
168     }
169
170     /* set the drive */
171     if (d_arg != -1)
172         boot0[OFF_DRIVE] = d_arg;
173
174     /* set various flags */
175     if (m_arg != -1) {
176         boot0[OFF_FLAGS] &= 0xf0;
177         boot0[OFF_FLAGS] |= m_arg;
178     }
179     if (o_flag) {
180         boot0[OFF_FLAGS] &= o_and;
181         boot0[OFF_FLAGS] |= o_or;
182     }
183
184     /* set the default boot selection */
185     if (s_arg != -1)
186         boot0[OFF_OPT] = s_arg - 1;
187
188     /* set the timeout */
189     if (t_arg != -1)
190         mk2(boot0 + OFF_TICKS, t_arg);
191
192     /* write the MBR back to disk */
193     if (up)
194         write_mbr(disk, 0, boot0, boot0_size);
195
196     /* display the MBR */
197     if (v_flag)
198         display_mbr(boot0);
199
200     /* clean up */
201     if (mbr != boot0)
202         free(boot0);
203     free(mbr);
204     free(disk);
205
206     return 0;
207 }
208
209 /*
210  * Read in the MBR of the disk.  If it is boot0, then use the version to
211  * read in all of it if necessary.  Use pointers to return a malloc'd
212  * buffer containing the MBR and then return its size.
213  */
214 static int
215 read_mbr(const char *disk, u_int8_t **mbr, int check_version)
216 {
217     u_int8_t buf[MBRSIZE];
218     int mbr_size, fd;
219     ssize_t n;
220
221     if ((fd = open(disk, O_RDONLY)) == -1)
222         err(1, "%s", disk);
223     if ((n = read(fd, buf, MBRSIZE)) == -1)
224         err(1, "%s", disk);
225     if (n != MBRSIZE)
226         errx(1, "%s: short read", disk);
227     if (cv2(buf + OFF_MAGIC) != 0xaa55)
228         errx(1, "%s: bad magic", disk);
229
230     if (!boot0bs(buf)) {
231         if (check_version)
232             errx(1, "%s: unknown or incompatible boot code", disk);
233     } else if (boot0version(buf) == 0x101) {
234         mbr_size = 1024;
235         if ((*mbr = malloc(mbr_size)) == NULL)
236             errx(1, "%s: unable to allocate read buffer", disk);
237         if (lseek(fd, 0, SEEK_SET) == -1 ||
238             (n = read(fd, *mbr, mbr_size)) == -1)
239             err(1, "%s", disk);
240         if (n != mbr_size)
241             errx(1, "%s: short read", disk);
242         return (mbr_size);
243     }
244     *mbr = malloc(sizeof(buf));
245     memcpy(*mbr, buf, sizeof(buf));
246
247     return sizeof(buf);
248 }
249
250 /*
251  * Write out the mbr to the specified file.
252  */
253 static void
254 write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size)
255 {
256     int fd;
257     ssize_t n;
258     
259     if ((fd = open(fname, O_WRONLY | flags, 0666)) == -1 ||
260         (n = write(fd, mbr, mbr_size)) == -1 || close(fd))
261         err(1, "%s", fname);
262     if (n != mbr_size)
263         errx(1, "%s: short write", fname);
264 }
265
266 /*
267  * Outputs an informative dump of the data in the MBR to stdout.
268  */
269 static void
270 display_mbr(u_int8_t *mbr)
271 {
272     struct dos_partition *part;
273     int i, version;
274
275     part = (struct dos_partition *)(mbr + DOSPARTOFF);
276     printf(fmt0);
277     for (i = 0; i < NDOSPART; i++)
278         if (part[i].dp_typ)
279             printf(fmt1, 1 + i, part[i].dp_flag,
280                 part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2),
281                 part[i].dp_shd, part[i].dp_ssect & 0x3f, part[i].dp_typ,
282                 part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2),
283                 part[i].dp_ehd, part[i].dp_esect & 0x3f, part[i].dp_start,
284                 part[i].dp_size);
285     printf("\n");
286     version = boot0version(mbr);
287     printf("version=%d.%d  drive=0x%x  mask=0x%x  ticks=%u\noptions=",
288         version >> 8, version & 0xff, mbr[OFF_DRIVE],
289         mbr[OFF_FLAGS] & 0xf, cv2(mbr + OFF_TICKS));
290     for (i = 0; i < nopt; i++) {
291         if (i)
292             printf(",");
293         if (!(mbr[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def)
294             printf("no");
295         printf("%s", opttbl[i].tok);
296     }
297     printf("\n");
298     printf("default_selection=F%d (", mbr[OFF_OPT] + 1);
299     if (mbr[OFF_OPT] < 4)
300         printf("Slice %d", mbr[OFF_OPT] + 1);
301     else
302         printf("Drive 1");
303     printf(")\n");
304 }
305
306 /*
307  * Return the boot0 version with the minor revision in the low byte, and
308  * the major revision in the next higher byte.
309  */
310 static int
311 boot0version(const u_int8_t *bs)
312 {
313     static u_int8_t idold[] = {0xfe, 0x45, 0xf2, 0xe9, 0x00, 0x8a};
314
315     /* Check for old version, and return 0x100 if found. */
316     if (memcmp(bs + 0x1c, idold, sizeof(idold)) == 0)
317         return 0x100;
318
319     /* We have a newer boot0, so extract the version number and return it. */
320     return *(const int *)(bs + OFF_VERSION) & 0xffff;
321 }
322
323 /*
324  * Decide if we have valid boot0 boot code by looking for
325  * characteristic byte sequences at fixed offsets.
326  */
327 static int
328 boot0bs(const u_int8_t *bs)
329 {
330     static u_int8_t id0[] = {0xfc, 0x31, 0xc0, 0x8e, 0xc0, 0x8e, 0xd8,
331                              0x8e, 0xd0, 0xbc, 0x00, 0x7c };
332     static u_int8_t id1[] = {0xfc, 0xb8, 0x00, 0x09, 0x8e, 0xc0, 0x8e,
333                              0xd0, 0xbc, 0x00, 0x10 ,0x31 };
334     static u_int8_t id2[] = {'D', 'r', 'i', 'v', 'e', ' '};
335     static struct {
336         unsigned off;
337         unsigned len;
338         u_int8_t *key;
339     } ident[] = {
340         {0x0,   sizeof(id0), id0},
341         {0x0,   sizeof(id1), id1},
342         {0x1b2, sizeof(id2), id2}
343     };
344     unsigned int i;
345     int count = 0;
346
347     for (i = 0; i < sizeof(ident) / sizeof(ident[0]); i++) {
348         if (memcmp(bs + ident[i].off, ident[i].key, ident[i].len) == 0)
349             ++count;
350     }
351     if (count >= 2)
352         return 1;
353     return 0;
354 };
355
356 /*
357  * Adjust "and" and "or" masks for a -o option argument.
358  */
359 static void
360 stropt(const char *arg, int *xa, int *xo)
361 {
362     const char *q;
363     char *s, *s1;
364     int inv, i, x;
365
366     if (!(s = strdup(arg)))
367         err(1, NULL);
368     for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) {
369         if ((inv = !strncmp(q, "no", 2)))
370             q += 2;
371         for (i = 0; i < nopt; i++)
372             if (!strcmp(q, opttbl[i].tok))
373                 break;
374         if (i == nopt)
375             errx(1, "%s: Unknown -o option", q);
376         if (opttbl[i].def)
377             inv ^= 1;
378         x = 1 << (7 - i);
379         if (inv)
380             *xa &= ~x;
381         else
382             *xo |= x;
383     }
384     free(s);
385 }
386
387 /*
388  * Produce a device path for a "canonical" name, where appropriate.
389  */
390 static char *
391 mkrdev(const char *fname)
392 {
393     char buf[MAXPATHLEN];
394     char *s;
395
396     if (!strchr(fname, '/')) {
397         snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
398         s = strdup(buf);
399     } else
400         s = strdup(fname);
401
402     if (s == NULL)
403         errx(1, "No more memory");
404     return s;
405 }
406
407 /*
408  * Convert and check an option argument.
409  */
410 static int
411 argtoi(const char *arg, int lo, int hi, int opt)
412 {
413     char *s;
414     long x;
415
416     errno = 0;
417     x = strtol(arg, &s, 0);
418     if (errno || !*arg || *s || x < lo || x > hi)
419         errx(1, "%s: Bad argument to -%c option", arg, opt);
420     return x;
421 }
422
423 /*
424  * Display usage information.
425  */
426 static void
427 usage(void)
428 {
429     fprintf(stderr, "%s\n%s\n",
430     "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]",
431     "                [-o options] [-s slice] [-t ticks] disk");
432     exit(1);
433 }