Merge branch 'syslinux-3.8x'
[profile/ivi/syslinux.git] / extlinux / main.c
1 /* ----------------------------------------------------------------------- *
2  *
3  *   Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
4  *
5  *   This program is free software; you can redistribute it and/or modify
6  *   it under the terms of the GNU General Public License as published by
7  *   the Free Software Foundation, Inc., 53 Temple Place Ste 330,
8  *   Boston MA 02111-1307, USA; either version 2 of the License, or
9  *   (at your option) any later version; incorporated herein by reference.
10  *
11  * ----------------------------------------------------------------------- */
12
13 /*
14  * extlinux.c
15  *
16  * Install the extlinux boot block on an ext2/3 filesystem
17  */
18
19 #define  _GNU_SOURCE            /* Enable everything */
20 #include <inttypes.h>
21 /* This is needed to deal with the kernel headers imported into glibc 3.3.3. */
22 typedef uint64_t u64;
23 #include <alloca.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #ifndef __KLIBC__
29 #include <mntent.h>
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33 #include <getopt.h>
34 #include <sysexits.h>
35 #include <sys/ioctl.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 #include <sys/mount.h>
39 #include <sys/vfs.h>
40
41 #include <linux/fd.h>           /* Floppy geometry */
42 #include <linux/hdreg.h>        /* Hard disk geometry */
43 #define statfs _kernel_statfs   /* HACK to deal with broken 2.4 distros */
44 #include <linux/fs.h>           /* FIGETBSZ, FIBMAP */
45 #undef statfs
46
47 #include "ext2_fs.h"
48 #include "../version.h"
49 #include "syslxint.h"
50
51 #ifdef DEBUG
52 # define dprintf printf
53 #else
54 # define dprintf(...) ((void)0)
55 #endif
56
57 /* Global option handling */
58
59 const char *program;
60
61 /* These are the options we can set and their values */
62 struct my_options {
63     unsigned int sectors;
64     unsigned int heads;
65     int raid_mode;
66     int reset_adv;
67     const char *set_once;
68 } opt = {
69 .sectors = 0,.heads = 0,.raid_mode = 0,.reset_adv = 0,.set_once = NULL,};
70
71 static void __attribute__ ((noreturn)) usage(int rv)
72 {
73     fprintf(stderr,
74             "Usage: %s [options] directory\n"
75             "  --install    -i  Install over the current bootsector\n"
76             "  --update     -U  Update a previous EXTLINUX installation\n"
77             "  --zip        -z  Force zipdrive geometry (-H 64 -S 32)\n"
78             "  --sectors=#  -S  Force the number of sectors per track\n"
79             "  --heads=#    -H  Force number of heads\n"
80             "  --raid       -r  Fall back to the next device on boot failure\n"
81             "  --once=...   -o  Execute a command once upon boot\n"
82             "  --clear-once -O  Clear the boot-once command\n"
83             "  --reset-adv      Reset auxilliary data\n"
84             "\n"
85             "  Note: geometry is determined at boot time for devices which\n"
86             "  are considered hard disks by the BIOS.  Unfortunately, this is\n"
87             "  not possible for devices which are considered floppy disks,\n"
88             "  which includes zipdisks and LS-120 superfloppies.\n"
89             "\n"
90             "  The -z option is useful for USB devices which are considered\n"
91             "  hard disks by some BIOSes and zipdrives by other BIOSes.\n",
92             program);
93
94     exit(rv);
95 }
96
97 enum long_only_opt {
98     OPT_NONE,
99     OPT_RESET_ADV,
100 };
101
102 static const struct option long_options[] = {
103     {"install", 0, NULL, 'i'},
104     {"update", 0, NULL, 'U'},
105     {"zipdrive", 0, NULL, 'z'},
106     {"sectors", 1, NULL, 'S'},
107     {"heads", 1, NULL, 'H'},
108     {"raid-mode", 0, NULL, 'r'},
109     {"version", 0, NULL, 'v'},
110     {"help", 0, NULL, 'h'},
111     {"once", 1, NULL, 'o'},
112     {"clear-once", 0, NULL, 'O'},
113     {"reset-adv", 0, NULL, OPT_RESET_ADV},
114     {0, 0, 0, 0}
115 };
116
117 static const char short_options[] = "iUuzS:H:rvho:O";
118
119 #if defined(__linux__) && !defined(BLKGETSIZE64)
120 /* This takes a u64, but the size field says size_t.  Someone screwed big. */
121 # define BLKGETSIZE64 _IOR(0x12,114,size_t)
122 #endif
123
124 #define LDLINUX_MAGIC   0x3eb202fe
125
126 enum bs_offsets {
127     bsJump = 0x00,
128     bsOemName = 0x03,
129     bsBytesPerSec = 0x0b,
130     bsSecPerClust = 0x0d,
131     bsResSectors = 0x0e,
132     bsFATs = 0x10,
133     bsRootDirEnts = 0x11,
134     bsSectors = 0x13,
135     bsMedia = 0x15,
136     bsFATsecs = 0x16,
137     bsSecPerTrack = 0x18,
138     bsHeads = 0x1a,
139     bsHiddenSecs = 0x1c,
140     bsHugeSectors = 0x20,
141
142     /* FAT12/16 only */
143     bs16DriveNumber = 0x24,
144     bs16Reserved1 = 0x25,
145     bs16BootSignature = 0x26,
146     bs16VolumeID = 0x27,
147     bs16VolumeLabel = 0x2b,
148     bs16FileSysType = 0x36,
149     bs16Code = 0x3e,
150
151     /* FAT32 only */
152     bs32FATSz32 = 36,
153     bs32ExtFlags = 40,
154     bs32FSVer = 42,
155     bs32RootClus = 44,
156     bs32FSInfo = 48,
157     bs32BkBootSec = 50,
158     bs32Reserved = 52,
159     bs32DriveNumber = 64,
160     bs32Reserved1 = 65,
161     bs32BootSignature = 66,
162     bs32VolumeID = 67,
163     bs32VolumeLabel = 71,
164     bs32FileSysType = 82,
165     bs32Code = 90,
166
167     bsSignature = 0x1fe
168 };
169
170 #define bsHead      bsJump
171 #define bsHeadLen   (bsOemName-bsHead)
172 #define bsCode      bs32Code    /* The common safe choice */
173 #define bsCodeLen   (bsSignature-bs32Code)
174
175 #ifndef EXT2_SUPER_OFFSET
176 #define EXT2_SUPER_OFFSET 1024
177 #endif
178
179 const char *program;
180
181 /*
182  * Boot block
183  */
184 extern unsigned char extlinux_bootsect[];
185 extern unsigned int extlinux_bootsect_len;
186 #define boot_block      extlinux_bootsect
187 #define boot_block_len  extlinux_bootsect_len
188
189 /*
190  * Image file
191  */
192 extern unsigned char extlinux_image[];
193 extern unsigned int extlinux_image_len;
194 #define boot_image      extlinux_image
195 #define boot_image_len  extlinux_image_len
196
197 /*
198  * Common abort function
199  */
200 void __attribute__ ((noreturn)) die(const char *msg)
201 {
202     fputs(msg, stderr);
203     exit(1);
204 }
205
206 /*
207  * read/write wrapper functions
208  */
209 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
210 {
211     char *bufp = (char *)buf;
212     ssize_t rv;
213     ssize_t done = 0;
214
215     while (count) {
216         rv = pread(fd, bufp, count, offset);
217         if (rv == 0) {
218             die("short read");
219         } else if (rv == -1) {
220             if (errno == EINTR) {
221                 continue;
222             } else {
223                 die(strerror(errno));
224             }
225         } else {
226             bufp += rv;
227             offset += rv;
228             done += rv;
229             count -= rv;
230         }
231     }
232
233     return done;
234 }
235
236 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
237 {
238     const char *bufp = (const char *)buf;
239     ssize_t rv;
240     ssize_t done = 0;
241
242     while (count) {
243         rv = pwrite(fd, bufp, count, offset);
244         if (rv == 0) {
245             die("short write");
246         } else if (rv == -1) {
247             if (errno == EINTR) {
248                 continue;
249             } else {
250                 die(strerror(errno));
251             }
252         } else {
253             bufp += rv;
254             offset += rv;
255             done += rv;
256             count -= rv;
257         }
258     }
259
260     return done;
261 }
262
263 /*
264  * Produce file map
265  */
266 int sectmap(int fd, uint32_t * sectors, int nsectors)
267 {
268     unsigned int blksize, blk, nblk;
269     unsigned int i;
270
271     /* Get block size */
272     if (ioctl(fd, FIGETBSZ, &blksize))
273         return -1;
274
275     /* Number of sectors per block */
276     blksize >>= SECTOR_SHIFT;
277
278     nblk = 0;
279     while (nsectors) {
280
281         blk = nblk++;
282         dprintf("querying block %u\n", blk);
283         if (ioctl(fd, FIBMAP, &blk))
284             return -1;
285
286         blk *= blksize;
287         for (i = 0; i < blksize; i++) {
288             if (!nsectors)
289                 return 0;
290
291             dprintf("Sector: %10u\n", blk);
292             *sectors++ = blk++;
293             nsectors--;
294         }
295     }
296
297     return 0;
298 }
299
300 /*
301  * Get the size of a block device
302  */
303 uint64_t get_size(int devfd)
304 {
305     uint64_t bytes;
306     uint32_t sects;
307     struct stat st;
308
309 #ifdef BLKGETSIZE64
310     if (!ioctl(devfd, BLKGETSIZE64, &bytes))
311         return bytes;
312 #endif
313     if (!ioctl(devfd, BLKGETSIZE, &sects))
314         return (uint64_t) sects << 9;
315     else if (!fstat(devfd, &st) && st.st_size)
316         return st.st_size;
317     else
318         return 0;
319 }
320
321 /*
322  * Get device geometry and partition offset
323  */
324 struct geometry_table {
325     uint64_t bytes;
326     struct hd_geometry g;
327 };
328
329 /* Standard floppy disk geometries, plus LS-120.  Zipdisk geometry
330    (x/64/32) is the final fallback.  I don't know what LS-240 has
331    as its geometry, since I don't have one and don't know anyone that does,
332    and Google wasn't helpful... */
333 static const struct geometry_table standard_geometries[] = {
334     {360 * 1024, {2, 9, 40, 0}},
335     {720 * 1024, {2, 9, 80, 0}},
336     {1200 * 1024, {2, 15, 80, 0}},
337     {1440 * 1024, {2, 18, 80, 0}},
338     {1680 * 1024, {2, 21, 80, 0}},
339     {1722 * 1024, {2, 21, 80, 0}},
340     {2880 * 1024, {2, 36, 80, 0}},
341     {3840 * 1024, {2, 48, 80, 0}},
342     {123264 * 1024, {8, 32, 963, 0}},   /* LS120 */
343     {0, {0, 0, 0, 0}}
344 };
345
346 int get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
347 {
348     struct floppy_struct fd_str;
349     const struct geometry_table *gp;
350
351     memset(geo, 0, sizeof *geo);
352
353     if (!ioctl(devfd, HDIO_GETGEO, &geo)) {
354         return 0;
355     } else if (!ioctl(devfd, FDGETPRM, &fd_str)) {
356         geo->heads = fd_str.head;
357         geo->sectors = fd_str.sect;
358         geo->cylinders = fd_str.track;
359         geo->start = 0;
360         return 0;
361     }
362
363     /* Didn't work.  Let's see if this is one of the standard geometries */
364     for (gp = standard_geometries; gp->bytes; gp++) {
365         if (gp->bytes == totalbytes) {
366             memcpy(geo, &gp->g, sizeof *geo);
367             return 0;
368         }
369     }
370
371     /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
372        what zipdisks use, so this would help if someone has a USB key that
373        they're booting in USB-ZIP mode. */
374
375     geo->heads = opt.heads ? : 64;
376     geo->sectors = opt.sectors ? : 32;
377     geo->cylinders = totalbytes / (geo->heads * geo->sectors << SECTOR_SHIFT);
378     geo->start = 0;
379
380     if (!opt.sectors && !opt.heads)
381         fprintf(stderr,
382                 "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
383                 "         (on hard disks, this is usually harmless.)\n",
384                 geo->heads, geo->sectors);
385
386     return 1;
387 }
388
389 /*
390  * Query the device geometry and put it into the boot sector.
391  * Map the file and put the map in the boot sector and file.
392  * Stick the "current directory" inode number into the file.
393  */
394 void patch_file_and_bootblock(int fd, int dirfd, int devfd)
395 {
396     struct stat dirst;
397     struct hd_geometry geo;
398     uint32_t *sectp;
399     uint64_t totalbytes, totalsectors;
400     int nsect;
401     unsigned char *p, *patcharea;
402     int i, dw;
403     uint32_t csum;
404
405     if (fstat(dirfd, &dirst)) {
406         perror("fstat dirfd");
407         exit(255);              /* This should never happen */
408     }
409
410     totalbytes = get_size(devfd);
411     get_geometry(devfd, totalbytes, &geo);
412
413     if (opt.heads)
414         geo.heads = opt.heads;
415     if (opt.sectors)
416         geo.sectors = opt.sectors;
417
418     /* Patch this into a fake FAT superblock.  This isn't because
419        FAT is a good format in any way, it's because it lets the
420        early bootstrap share code with the FAT version. */
421     dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
422
423     totalsectors = totalbytes >> SECTOR_SHIFT;
424     if (totalsectors >= 65536) {
425         set_16(boot_block + bsSectors, 0);
426     } else {
427         set_16(boot_block + bsSectors, totalsectors);
428     }
429     set_32(boot_block + bsHugeSectors, totalsectors);
430
431     set_16(boot_block + bsBytesPerSec, SECTOR_SIZE);
432     set_16(boot_block + bsSecPerTrack, geo.sectors);
433     set_16(boot_block + bsHeads, geo.heads);
434     set_32(boot_block + bsHiddenSecs, geo.start);
435
436     /* If we're in RAID mode then patch the appropriate instruction;
437        either way write the proper boot signature */
438     i = get_16(boot_block + 0x1FE);
439     if (opt.raid_mode)
440         set_16(boot_block + i, 0x18CD); /* INT 18h */
441
442     set_16(boot_block + 0x1FE, 0xAA55);
443
444     /* Construct the boot file */
445
446     dprintf("directory inode = %lu\n", (unsigned long)dirst.st_ino);
447     nsect = (boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
448     nsect += 2;                 /* Two sectors for the ADV */
449     sectp = alloca(sizeof(uint32_t) * nsect);
450     if (sectmap(fd, sectp, nsect)) {
451         perror("bmap");
452         exit(1);
453     }
454
455     /* First sector need pointer in boot sector */
456     set_32(boot_block + 0x1F8, *sectp++);
457     nsect--;
458
459     /* Search for LDLINUX_MAGIC to find the patch area */
460     for (p = boot_image; get_32(p) != LDLINUX_MAGIC; p += 4) ;
461     patcharea = p + 8;
462
463     /* Set up the totals */
464     dw = boot_image_len >> 2;   /* COMPLETE dwords, excluding ADV */
465     set_16(patcharea, dw);
466     set_16(patcharea + 2, nsect);       /* Not including the first sector, but
467                                            including the ADV */
468     set_32(patcharea + 8, dirst.st_ino);        /* "Current" directory */
469
470     /* Set the sector pointers */
471     p = patcharea + 12;
472
473     memset(p, 0, 64 * 4);
474     while (nsect--) {
475         set_32(p, *sectp++);
476         p += 4;
477     }
478
479     /* Now produce a checksum */
480     set_32(patcharea + 4, 0);
481
482     csum = LDLINUX_MAGIC;
483     for (i = 0, p = boot_image; i < dw; i++, p += 4)
484         csum -= get_32(p);      /* Negative checksum */
485
486     set_32(patcharea + 4, csum);
487 }
488
489 /*
490  * Read the ADV from an existing instance, or initialize if invalid.
491  * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
492  * ADV was found.
493  */
494 int read_adv(const char *path)
495 {
496     char *file;
497     int fd = -1;
498     struct stat st;
499     int err = 0;
500
501     asprintf(&file, "%s%sextlinux.sys",
502              path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
503
504     if (!file) {
505         perror(program);
506         return -1;
507     }
508
509     fd = open(file, O_RDONLY);
510     if (fd < 0) {
511         if (errno != ENOENT) {
512             err = -1;
513         } else {
514             syslinux_reset_adv(syslinux_adv);
515         }
516     } else if (fstat(fd, &st)) {
517         err = -1;
518     } else if (st.st_size < 2 * ADV_SIZE) {
519         /* Too small to be useful */
520         syslinux_reset_adv(syslinux_adv);
521         err = 0;                /* Nothing to read... */
522     } else if (xpread(fd, syslinux_adv, 2 * ADV_SIZE,
523                       st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
524         err = -1;
525     } else {
526         /* We got it... maybe? */
527         err = syslinux_validate_adv(syslinux_adv) ? 1 : 0;
528     }
529
530     if (err < 0)
531         perror(file);
532
533     if (fd >= 0)
534         close(fd);
535     if (file)
536         free(file);
537
538     return err;
539 }
540
541 /*
542  * Update the ADV in an existing installation.
543  */
544 int write_adv(const char *path)
545 {
546     unsigned char advtmp[2 * ADV_SIZE];
547     char *file;
548     int fd = -1;
549     struct stat st, xst;
550     int err = 0;
551     int flags, nflags;
552
553     asprintf(&file, "%s%sextlinux.sys",
554              path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
555
556     if (!file) {
557         perror(program);
558         return -1;
559     }
560
561     fd = open(file, O_RDONLY);
562     if (fd < 0) {
563         err = -1;
564     } else if (fstat(fd, &st)) {
565         err = -1;
566     } else if (st.st_size < 2 * ADV_SIZE) {
567         /* Too small to be useful */
568         err = -2;
569     } else if (xpread(fd, advtmp, 2 * ADV_SIZE,
570                       st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
571         err = -1;
572     } else {
573         /* We got it... maybe? */
574         err = syslinux_validate_adv(advtmp) ? -2 : 0;
575         if (!err) {
576             /* Got a good one, write our own ADV here */
577             if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
578                 nflags = flags & ~EXT2_IMMUTABLE_FL;
579                 if (nflags != flags)
580                     ioctl(fd, EXT2_IOC_SETFLAGS, &nflags);
581             }
582             if (!(st.st_mode & S_IWUSR))
583                 fchmod(fd, st.st_mode | S_IWUSR);
584
585             /* Need to re-open read-write */
586             close(fd);
587             fd = open(file, O_RDWR | O_SYNC);
588             if (fd < 0) {
589                 err = -1;
590             } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
591                        xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
592                 fprintf(stderr, "%s: race condition on write\n", file);
593                 err = -2;
594             }
595             /* Write our own version ... */
596             if (xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
597                         st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
598                 err = -1;
599             }
600
601             sync();
602
603             if (!(st.st_mode & S_IWUSR))
604                 fchmod(fd, st.st_mode);
605
606             if (nflags != flags)
607                 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
608         }
609     }
610
611     if (err == -2)
612         fprintf(stderr, "%s: cannot write auxilliary data (need --update)?\n",
613                 file);
614     else if (err == -1)
615         perror(file);
616
617     if (fd >= 0)
618         close(fd);
619     if (file)
620         free(file);
621
622     return err;
623 }
624
625 /*
626  * Make any user-specified ADV modifications
627  */
628 int modify_adv(void)
629 {
630     int rv = 0;
631
632     if (opt.set_once) {
633         if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
634             fprintf(stderr, "%s: not enough space for boot-once command\n",
635                     program);
636             rv = -1;
637         }
638     }
639
640     return rv;
641 }
642
643 /*
644  * Install the boot block on the specified device.
645  * Must be run AFTER install_file()!
646  */
647 int install_bootblock(int fd, const char *device)
648 {
649     struct ext2_super_block sb;
650
651     if (xpread(fd, &sb, sizeof sb, EXT2_SUPER_OFFSET) != sizeof sb) {
652         perror("reading superblock");
653         return 1;
654     }
655
656     if (sb.s_magic != EXT2_SUPER_MAGIC) {
657         fprintf(stderr, "no ext2/ext3 superblock found on %s\n", device);
658         return 1;
659     }
660
661     if (xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len) {
662         perror("writing bootblock");
663         return 1;
664     }
665
666     return 0;
667 }
668
669 int install_file(const char *path, int devfd, struct stat *rst)
670 {
671     char *file;
672     int fd = -1, dirfd = -1, flags;
673     struct stat st;
674
675     asprintf(&file, "%s%sextlinux.sys",
676              path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
677     if (!file) {
678         perror(program);
679         return 1;
680     }
681
682     dirfd = open(path, O_RDONLY | O_DIRECTORY);
683     if (dirfd < 0) {
684         perror(path);
685         goto bail;
686     }
687
688     fd = open(file, O_RDONLY);
689     if (fd < 0) {
690         if (errno != ENOENT) {
691             perror(file);
692             goto bail;
693         }
694     } else {
695         /* If file exist, remove the immutable flag and set u+w mode */
696         if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
697             flags &= ~EXT2_IMMUTABLE_FL;
698             ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
699         }
700         if (!fstat(fd, &st)) {
701             fchmod(fd, st.st_mode | S_IWUSR);
702         }
703     }
704     close(fd);
705
706     fd = open(file, O_WRONLY | O_TRUNC | O_CREAT | O_SYNC,
707               S_IRUSR | S_IRGRP | S_IROTH);
708     if (fd < 0) {
709         perror(file);
710         goto bail;
711     }
712
713     /* Write it the first time */
714     if (xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ||
715         xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
716                 boot_image_len) != 2 * ADV_SIZE) {
717         fprintf(stderr, "%s: write failure on %s\n", program, file);
718         goto bail;
719     }
720
721     /* Map the file, and patch the initial sector accordingly */
722     patch_file_and_bootblock(fd, dirfd, devfd);
723
724     /* Write the first sector again - this relies on the file being
725        overwritten in place! */
726     if (xpwrite(fd, boot_image, SECTOR_SIZE, 0) != SECTOR_SIZE) {
727         fprintf(stderr, "%s: write failure on %s\n", program, file);
728         goto bail;
729     }
730
731     /* Attempt to set immutable flag and remove all write access */
732     /* Only set immutable flag if file is owned by root */
733     if (!fstat(fd, &st)) {
734         fchmod(fd, st.st_mode & (S_IRUSR | S_IRGRP | S_IROTH));
735         if (st.st_uid == 0 && !ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
736             flags |= EXT2_IMMUTABLE_FL;
737             ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
738         }
739     }
740
741     if (fstat(fd, rst)) {
742         perror(file);
743         goto bail;
744     }
745
746     close(dirfd);
747     close(fd);
748     return 0;
749
750 bail:
751     if (dirfd >= 0)
752         close(dirfd);
753     if (fd >= 0)
754         close(fd);
755
756     return 1;
757 }
758
759 /* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
760    sector; this is consistent with FAT filesystems. */
761 int already_installed(int devfd)
762 {
763     char buffer[8];
764
765     xpread(devfd, buffer, 8, 3);
766     return !memcmp(buffer, "EXTLINUX", 8);
767 }
768
769 #ifdef __KLIBC__
770 static char devname_buf[64];
771
772 static void device_cleanup(void)
773 {
774     unlink(devname_buf);
775 }
776 #endif
777
778 /* Verify that a device fd and a pathname agree.
779    Return 0 on valid, -1 on error. */
780 static int validate_device(const char *path, int devfd)
781 {
782     struct stat pst, dst;
783
784     if (stat(path, &pst) || fstat(devfd, &dst))
785         return -1;
786
787     return (pst.st_dev == dst.st_rdev) ? 0 : -1;
788 }
789
790 #ifndef __KLIBC__
791 static const char *find_device(const char *mtab_file, dev_t dev)
792 {
793     struct mntent *mnt;
794     struct stat dst;
795     FILE *mtab;
796     const char *devname = NULL;
797
798     mtab = setmntent(mtab_file, "r");
799     if (!mtab)
800         return NULL;
801
802     while ((mnt = getmntent(mtab))) {
803         if ((!strcmp(mnt->mnt_type, "ext2") ||
804              !strcmp(mnt->mnt_type, "ext3")) &&
805             !stat(mnt->mnt_fsname, &dst) && dst.st_rdev == dev) {
806             devname = strdup(mnt->mnt_fsname);
807             break;
808         }
809     }
810     endmntent(mtab);
811
812     return devname;
813 }
814 #endif
815
816 int install_loader(const char *path, int update_only)
817 {
818     struct stat st, fst;
819     int devfd, rv;
820     const char *devname = NULL;
821     struct statfs sfs;
822
823     if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
824         fprintf(stderr, "%s: Not a directory: %s\n", program, path);
825         return 1;
826     }
827
828     if (statfs(path, &sfs)) {
829         fprintf(stderr, "%s: statfs %s: %s\n", program, path, strerror(errno));
830         return 1;
831     }
832
833     if (sfs.f_type != EXT2_SUPER_MAGIC) {
834         fprintf(stderr, "%s: not an ext2/ext3 filesystem: %s\n", program, path);
835         return 1;
836     }
837
838     devfd = -1;
839
840 #ifdef __KLIBC__
841
842     /* klibc doesn't have getmntent and friends; instead, just create
843        a new device with the appropriate device type */
844     snprintf(devname_buf, sizeof devname_buf, "/tmp/dev-%u:%u",
845              major(st.st_dev), minor(st.st_dev));
846
847     if (mknod(devname_buf, S_IFBLK | 0600, st.st_dev)) {
848         fprintf(stderr, "%s: cannot create device %s\n", program, devname);
849         return 1;
850     }
851
852     atexit(device_cleanup);     /* unlink the device node on exit */
853     devname = devname_buf;
854
855 #else
856
857     devname = find_device("/proc/mounts", st.st_dev);
858     if (!devname) {
859         /* Didn't find it in /proc/mounts, try /etc/mtab */
860         devname = find_device("/etc/mtab", st.st_dev);
861     }
862     if (!devname) {
863         fprintf(stderr, "%s: cannot find device for path %s\n", program, path);
864         return 1;
865     }
866
867     fprintf(stderr, "%s is device %s\n", path, devname);
868 #endif
869
870     if ((devfd = open(devname, O_RDWR | O_SYNC)) < 0) {
871         fprintf(stderr, "%s: cannot open device %s\n", program, devname);
872         return 1;
873     }
874
875     /* Verify that the device we opened is the device intended */
876     if (validate_device(path, devfd)) {
877         fprintf(stderr, "%s: path %s doesn't match device %s\n",
878                 program, path, devname);
879         return 1;
880     }
881
882     if (update_only && !already_installed(devfd)) {
883         fprintf(stderr, "%s: no previous extlinux boot sector found\n",
884                 program);
885         return 1;
886     }
887
888     /* Read a pre-existing ADV, if already installed */
889     if (opt.reset_adv)
890         syslinux_reset_adv(syslinux_adv);
891     else if (read_adv(path) < 0)
892         return 1;
893
894     if (modify_adv() < 0)
895         return 1;
896
897     /* Install extlinux.sys */
898     if (install_file(path, devfd, &fst))
899         return 1;
900
901     if (fst.st_dev != st.st_dev) {
902         fprintf(stderr, "%s: file system changed under us - aborting!\n",
903                 program);
904         return 1;
905     }
906
907     sync();
908     rv = install_bootblock(devfd, devname);
909     close(devfd);
910     sync();
911
912     return rv;
913 }
914
915 /*
916  * Modify the ADV of an existing installation
917  */
918 int modify_existing_adv(const char *path)
919 {
920     if (opt.reset_adv)
921         syslinux_reset_adv(syslinux_adv);
922     else if (read_adv(path) < 0)
923         return 1;
924
925     if (modify_adv() < 0)
926         return 1;
927
928     if (write_adv(path) < 0)
929         return 1;
930
931     return 0;
932 }
933
934 int main(int argc, char *argv[])
935 {
936     int o;
937     const char *directory;
938     int update_only = -1;
939
940     program = argv[0];
941
942     while ((o = getopt_long(argc, argv, short_options,
943                             long_options, NULL)) != EOF) {
944         switch (o) {
945         case 'z':
946             opt.heads = 64;
947             opt.sectors = 32;
948             break;
949         case 'S':
950             opt.sectors = strtoul(optarg, NULL, 0);
951             if (opt.sectors < 1 || opt.sectors > 63) {
952                 fprintf(stderr,
953                         "%s: invalid number of sectors: %u (must be 1-63)\n",
954                         program, opt.sectors);
955                 exit(EX_USAGE);
956             }
957             break;
958         case 'H':
959             opt.heads = strtoul(optarg, NULL, 0);
960             if (opt.heads < 1 || opt.heads > 256) {
961                 fprintf(stderr,
962                         "%s: invalid number of heads: %u (must be 1-256)\n",
963                         program, opt.heads);
964                 exit(EX_USAGE);
965             }
966             break;
967         case 'r':
968             opt.raid_mode = 1;
969             break;
970         case 'i':
971             update_only = 0;
972             break;
973         case 'u':
974         case 'U':
975             update_only = 1;
976             break;
977         case 'h':
978             usage(0);
979             break;
980         case 'o':
981             opt.set_once = optarg;
982             break;
983         case 'O':
984             opt.set_once = "";
985             break;
986         case OPT_RESET_ADV:
987             opt.reset_adv = 1;
988             break;
989         case 'v':
990             fputs("extlinux " VERSION_STR
991                   "  Copyright 1994-" YEAR_STR " H. Peter Anvin \n", stderr);
992             exit(0);
993         default:
994             usage(EX_USAGE);
995         }
996     }
997
998     directory = argv[optind];
999
1000     if (!directory)
1001         usage(EX_USAGE);
1002
1003     if (update_only == -1) {
1004         if (opt.reset_adv || opt.set_once) {
1005             return modify_existing_adv(directory);
1006         } else {
1007             usage(EX_USAGE);
1008         }
1009     }
1010
1011     return install_loader(directory, update_only);
1012 }