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