Merge commit 'pam/disklib-fixes'
[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 /*
180  * Boot block
181  */
182 extern unsigned char extlinux_bootsect[];
183 extern unsigned int extlinux_bootsect_len;
184 #define boot_block      extlinux_bootsect
185 #define boot_block_len  extlinux_bootsect_len
186
187 /*
188  * Image file
189  */
190 extern unsigned char extlinux_image[];
191 extern unsigned int extlinux_image_len;
192 #define boot_image      extlinux_image
193 #define boot_image_len  extlinux_image_len
194
195 /*
196  * Common abort function
197  */
198 void __attribute__ ((noreturn)) die(const char *msg)
199 {
200     fputs(msg, stderr);
201     exit(1);
202 }
203
204 /*
205  * read/write wrapper functions
206  */
207 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
208 {
209     char *bufp = (char *)buf;
210     ssize_t rv;
211     ssize_t done = 0;
212
213     while (count) {
214         rv = pread(fd, bufp, count, offset);
215         if (rv == 0) {
216             die("short read");
217         } else if (rv == -1) {
218             if (errno == EINTR) {
219                 continue;
220             } else {
221                 die(strerror(errno));
222             }
223         } else {
224             bufp += rv;
225             offset += rv;
226             done += rv;
227             count -= rv;
228         }
229     }
230
231     return done;
232 }
233
234 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
235 {
236     const char *bufp = (const char *)buf;
237     ssize_t rv;
238     ssize_t done = 0;
239
240     while (count) {
241         rv = pwrite(fd, bufp, count, offset);
242         if (rv == 0) {
243             die("short write");
244         } else if (rv == -1) {
245             if (errno == EINTR) {
246                 continue;
247             } else {
248                 die(strerror(errno));
249             }
250         } else {
251             bufp += rv;
252             offset += rv;
253             done += rv;
254             count -= rv;
255         }
256     }
257
258     return done;
259 }
260
261 /*
262  * Produce file map
263  */
264 int sectmap(int fd, uint32_t * sectors, int nsectors)
265 {
266     unsigned int blksize, blk, nblk;
267     unsigned int i;
268
269     /* Get block size */
270     if (ioctl(fd, FIGETBSZ, &blksize))
271         return -1;
272
273     /* Number of sectors per block */
274     blksize >>= SECTOR_SHIFT;
275
276     nblk = 0;
277     while (nsectors) {
278
279         blk = nblk++;
280         dprintf("querying block %u\n", blk);
281         if (ioctl(fd, FIBMAP, &blk))
282             return -1;
283
284         blk *= blksize;
285         for (i = 0; i < blksize; i++) {
286             if (!nsectors)
287                 return 0;
288
289             dprintf("Sector: %10u\n", blk);
290             *sectors++ = blk++;
291             nsectors--;
292         }
293     }
294
295     return 0;
296 }
297
298 /*
299  * Get the size of a block device
300  */
301 uint64_t get_size(int devfd)
302 {
303     uint64_t bytes;
304     uint32_t sects;
305     struct stat st;
306
307 #ifdef BLKGETSIZE64
308     if (!ioctl(devfd, BLKGETSIZE64, &bytes))
309         return bytes;
310 #endif
311     if (!ioctl(devfd, BLKGETSIZE, &sects))
312         return (uint64_t) sects << 9;
313     else if (!fstat(devfd, &st) && st.st_size)
314         return st.st_size;
315     else
316         return 0;
317 }
318
319 /*
320  * Get device geometry and partition offset
321  */
322 struct geometry_table {
323     uint64_t bytes;
324     struct hd_geometry g;
325 };
326
327 /* Standard floppy disk geometries, plus LS-120.  Zipdisk geometry
328    (x/64/32) is the final fallback.  I don't know what LS-240 has
329    as its geometry, since I don't have one and don't know anyone that does,
330    and Google wasn't helpful... */
331 static const struct geometry_table standard_geometries[] = {
332     {360 * 1024, {2, 9, 40, 0}},
333     {720 * 1024, {2, 9, 80, 0}},
334     {1200 * 1024, {2, 15, 80, 0}},
335     {1440 * 1024, {2, 18, 80, 0}},
336     {1680 * 1024, {2, 21, 80, 0}},
337     {1722 * 1024, {2, 21, 80, 0}},
338     {2880 * 1024, {2, 36, 80, 0}},
339     {3840 * 1024, {2, 48, 80, 0}},
340     {123264 * 1024, {8, 32, 963, 0}},   /* LS120 */
341     {0, {0, 0, 0, 0}}
342 };
343
344 int get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
345 {
346     struct floppy_struct fd_str;
347     const struct geometry_table *gp;
348
349     memset(geo, 0, sizeof *geo);
350
351     if (!ioctl(devfd, HDIO_GETGEO, &geo)) {
352         return 0;
353     } else if (!ioctl(devfd, FDGETPRM, &fd_str)) {
354         geo->heads = fd_str.head;
355         geo->sectors = fd_str.sect;
356         geo->cylinders = fd_str.track;
357         geo->start = 0;
358         return 0;
359     }
360
361     /* Didn't work.  Let's see if this is one of the standard geometries */
362     for (gp = standard_geometries; gp->bytes; gp++) {
363         if (gp->bytes == totalbytes) {
364             memcpy(geo, &gp->g, sizeof *geo);
365             return 0;
366         }
367     }
368
369     /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
370        what zipdisks use, so this would help if someone has a USB key that
371        they're booting in USB-ZIP mode. */
372
373     geo->heads = opt.heads ? : 64;
374     geo->sectors = opt.sectors ? : 32;
375     geo->cylinders = totalbytes / (geo->heads * geo->sectors << SECTOR_SHIFT);
376     geo->start = 0;
377
378     if (!opt.sectors && !opt.heads)
379         fprintf(stderr,
380                 "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
381                 "         (on hard disks, this is usually harmless.)\n",
382                 geo->heads, geo->sectors);
383
384     return 1;
385 }
386
387 /*
388  * Query the device geometry and put it into the boot sector.
389  * Map the file and put the map in the boot sector and file.
390  * Stick the "current directory" inode number into the file.
391  */
392 void patch_file_and_bootblock(int fd, int dirfd, int devfd)
393 {
394     struct stat dirst;
395     struct hd_geometry geo;
396     uint32_t *sectp;
397     uint64_t totalbytes, totalsectors;
398     int nsect;
399     unsigned char *p, *patcharea;
400     int i, dw;
401     uint32_t csum;
402
403     if (fstat(dirfd, &dirst)) {
404         perror("fstat dirfd");
405         exit(255);              /* This should never happen */
406     }
407
408     totalbytes = get_size(devfd);
409     get_geometry(devfd, totalbytes, &geo);
410
411     if (opt.heads)
412         geo.heads = opt.heads;
413     if (opt.sectors)
414         geo.sectors = opt.sectors;
415
416     /* Patch this into a fake FAT superblock.  This isn't because
417        FAT is a good format in any way, it's because it lets the
418        early bootstrap share code with the FAT version. */
419     dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
420
421     totalsectors = totalbytes >> SECTOR_SHIFT;
422     if (totalsectors >= 65536) {
423         set_16(boot_block + bsSectors, 0);
424     } else {
425         set_16(boot_block + bsSectors, totalsectors);
426     }
427     set_32(boot_block + bsHugeSectors, totalsectors);
428
429     set_16(boot_block + bsBytesPerSec, SECTOR_SIZE);
430     set_16(boot_block + bsSecPerTrack, geo.sectors);
431     set_16(boot_block + bsHeads, geo.heads);
432     set_32(boot_block + bsHiddenSecs, geo.start);
433
434     /* If we're in RAID mode then patch the appropriate instruction;
435        either way write the proper boot signature */
436     i = get_16(boot_block + 0x1FE);
437     if (opt.raid_mode)
438         set_16(boot_block + i, 0x18CD); /* INT 18h */
439
440     set_16(boot_block + 0x1FE, 0xAA55);
441
442     /* Construct the boot file */
443
444     dprintf("directory inode = %lu\n", (unsigned long)dirst.st_ino);
445     nsect = (boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
446     nsect += 2;                 /* Two sectors for the ADV */
447     sectp = alloca(sizeof(uint32_t) * nsect);
448     if (sectmap(fd, sectp, nsect)) {
449         perror("bmap");
450         exit(1);
451     }
452
453     /* First sector need pointer in boot sector */
454     set_32(boot_block + 0x1F8, *sectp++);
455     nsect--;
456
457     /* Search for LDLINUX_MAGIC to find the patch area */
458     for (p = boot_image; get_32(p) != LDLINUX_MAGIC; p += 4) ;
459     patcharea = p + 8;
460
461     /* Set up the totals */
462     dw = boot_image_len >> 2;   /* COMPLETE dwords, excluding ADV */
463     set_16(patcharea, dw);
464     set_16(patcharea + 2, nsect);       /* Not including the first sector, but
465                                            including the ADV */
466     set_32(patcharea + 8, dirst.st_ino);        /* "Current" directory */
467
468     /* Set the sector pointers */
469     p = patcharea + 12;
470
471     memset(p, 0, 64 * 4);
472     while (nsect--) {
473         set_32(p, *sectp++);
474         p += 4;
475     }
476
477     /* Now produce a checksum */
478     set_32(patcharea + 4, 0);
479
480     csum = LDLINUX_MAGIC;
481     for (i = 0, p = boot_image; i < dw; i++, p += 4)
482         csum -= get_32(p);      /* Negative checksum */
483
484     set_32(patcharea + 4, csum);
485 }
486
487 /*
488  * Read the ADV from an existing instance, or initialize if invalid.
489  * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
490  * ADV was found.
491  */
492 int read_adv(const char *path)
493 {
494     char *file;
495     int fd = -1;
496     struct stat st;
497     int err = 0;
498
499     asprintf(&file, "%s%sextlinux.sys",
500              path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
501
502     if (!file) {
503         perror(program);
504         return -1;
505     }
506
507     fd = open(file, O_RDONLY);
508     if (fd < 0) {
509         if (errno != ENOENT) {
510             err = -1;
511         } else {
512             syslinux_reset_adv(syslinux_adv);
513         }
514     } else if (fstat(fd, &st)) {
515         err = -1;
516     } else if (st.st_size < 2 * ADV_SIZE) {
517         /* Too small to be useful */
518         syslinux_reset_adv(syslinux_adv);
519         err = 0;                /* Nothing to read... */
520     } else if (xpread(fd, syslinux_adv, 2 * ADV_SIZE,
521                       st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
522         err = -1;
523     } else {
524         /* We got it... maybe? */
525         err = syslinux_validate_adv(syslinux_adv) ? 1 : 0;
526     }
527
528     if (err < 0)
529         perror(file);
530
531     if (fd >= 0)
532         close(fd);
533     if (file)
534         free(file);
535
536     return err;
537 }
538
539 /*
540  * Update the ADV in an existing installation.
541  */
542 int write_adv(const char *path)
543 {
544     unsigned char advtmp[2 * ADV_SIZE];
545     char *file;
546     int fd = -1;
547     struct stat st, xst;
548     int err = 0;
549     int flags, nflags;
550
551     asprintf(&file, "%s%sextlinux.sys",
552              path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
553
554     if (!file) {
555         perror(program);
556         return -1;
557     }
558
559     fd = open(file, O_RDONLY);
560     if (fd < 0) {
561         err = -1;
562     } else if (fstat(fd, &st)) {
563         err = -1;
564     } else if (st.st_size < 2 * ADV_SIZE) {
565         /* Too small to be useful */
566         err = -2;
567     } else if (xpread(fd, advtmp, 2 * ADV_SIZE,
568                       st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
569         err = -1;
570     } else {
571         /* We got it... maybe? */
572         err = syslinux_validate_adv(advtmp) ? -2 : 0;
573         if (!err) {
574             /* Got a good one, write our own ADV here */
575             if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
576                 nflags = flags & ~EXT2_IMMUTABLE_FL;
577                 if (nflags != flags)
578                     ioctl(fd, EXT2_IOC_SETFLAGS, &nflags);
579             }
580             if (!(st.st_mode & S_IWUSR))
581                 fchmod(fd, st.st_mode | S_IWUSR);
582
583             /* Need to re-open read-write */
584             close(fd);
585             fd = open(file, O_RDWR | O_SYNC);
586             if (fd < 0) {
587                 err = -1;
588             } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
589                        xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
590                 fprintf(stderr, "%s: race condition on write\n", file);
591                 err = -2;
592             }
593             /* Write our own version ... */
594             if (xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
595                         st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
596                 err = -1;
597             }
598
599             sync();
600
601             if (!(st.st_mode & S_IWUSR))
602                 fchmod(fd, st.st_mode);
603
604             if (nflags != flags)
605                 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
606         }
607     }
608
609     if (err == -2)
610         fprintf(stderr, "%s: cannot write auxilliary data (need --update)?\n",
611                 file);
612     else if (err == -1)
613         perror(file);
614
615     if (fd >= 0)
616         close(fd);
617     if (file)
618         free(file);
619
620     return err;
621 }
622
623 /*
624  * Make any user-specified ADV modifications
625  */
626 int modify_adv(void)
627 {
628     int rv = 0;
629
630     if (opt.set_once) {
631         if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
632             fprintf(stderr, "%s: not enough space for boot-once command\n",
633                     program);
634             rv = -1;
635         }
636     }
637
638     return rv;
639 }
640
641 /*
642  * Install the boot block on the specified device.
643  * Must be run AFTER install_file()!
644  */
645 int install_bootblock(int fd, const char *device)
646 {
647     struct ext2_super_block sb;
648
649     if (xpread(fd, &sb, sizeof sb, EXT2_SUPER_OFFSET) != sizeof sb) {
650         perror("reading superblock");
651         return 1;
652     }
653
654     if (sb.s_magic != EXT2_SUPER_MAGIC) {
655         fprintf(stderr, "no ext2/ext3 superblock found on %s\n", device);
656         return 1;
657     }
658
659     if (xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len) {
660         perror("writing bootblock");
661         return 1;
662     }
663
664     return 0;
665 }
666
667 int install_file(const char *path, int devfd, struct stat *rst)
668 {
669     char *file;
670     int fd = -1, dirfd = -1, flags;
671     struct stat st;
672
673     asprintf(&file, "%s%sextlinux.sys",
674              path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
675     if (!file) {
676         perror(program);
677         return 1;
678     }
679
680     dirfd = open(path, O_RDONLY | O_DIRECTORY);
681     if (dirfd < 0) {
682         perror(path);
683         goto bail;
684     }
685
686     fd = open(file, O_RDONLY);
687     if (fd < 0) {
688         if (errno != ENOENT) {
689             perror(file);
690             goto bail;
691         }
692     } else {
693         /* If file exist, remove the immutable flag and set u+w mode */
694         if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
695             flags &= ~EXT2_IMMUTABLE_FL;
696             ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
697         }
698         if (!fstat(fd, &st)) {
699             fchmod(fd, st.st_mode | S_IWUSR);
700         }
701     }
702     close(fd);
703
704     fd = open(file, O_WRONLY | O_TRUNC | O_CREAT | O_SYNC,
705               S_IRUSR | S_IRGRP | S_IROTH);
706     if (fd < 0) {
707         perror(file);
708         goto bail;
709     }
710
711     /* Write it the first time */
712     if (xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ||
713         xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
714                 boot_image_len) != 2 * ADV_SIZE) {
715         fprintf(stderr, "%s: write failure on %s\n", program, file);
716         goto bail;
717     }
718
719     /* Map the file, and patch the initial sector accordingly */
720     patch_file_and_bootblock(fd, dirfd, devfd);
721
722     /* Write the first sector again - this relies on the file being
723        overwritten in place! */
724     if (xpwrite(fd, boot_image, SECTOR_SIZE, 0) != SECTOR_SIZE) {
725         fprintf(stderr, "%s: write failure on %s\n", program, file);
726         goto bail;
727     }
728
729     /* Attempt to set immutable flag and remove all write access */
730     /* Only set immutable flag if file is owned by root */
731     if (!fstat(fd, &st)) {
732         fchmod(fd, st.st_mode & (S_IRUSR | S_IRGRP | S_IROTH));
733         if (st.st_uid == 0 && !ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
734             flags |= EXT2_IMMUTABLE_FL;
735             ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
736         }
737     }
738
739     if (fstat(fd, rst)) {
740         perror(file);
741         goto bail;
742     }
743
744     close(dirfd);
745     close(fd);
746     return 0;
747
748 bail:
749     if (dirfd >= 0)
750         close(dirfd);
751     if (fd >= 0)
752         close(fd);
753
754     return 1;
755 }
756
757 /* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
758    sector; this is consistent with FAT filesystems. */
759 int already_installed(int devfd)
760 {
761     char buffer[8];
762
763     xpread(devfd, buffer, 8, 3);
764     return !memcmp(buffer, "EXTLINUX", 8);
765 }
766
767 #ifdef __KLIBC__
768 static char devname_buf[64];
769
770 static void device_cleanup(void)
771 {
772     unlink(devname_buf);
773 }
774 #endif
775
776 /* Verify that a device fd and a pathname agree.
777    Return 0 on valid, -1 on error. */
778 static int validate_device(const char *path, int devfd)
779 {
780     struct stat pst, dst;
781
782     if (stat(path, &pst) || fstat(devfd, &dst))
783         return -1;
784
785     return (pst.st_dev == dst.st_rdev) ? 0 : -1;
786 }
787
788 #ifndef __KLIBC__
789 static const char *find_device(const char *mtab_file, dev_t dev)
790 {
791     struct mntent *mnt;
792     struct stat dst;
793     FILE *mtab;
794     const char *devname = NULL;
795
796     mtab = setmntent(mtab_file, "r");
797     if (!mtab)
798         return NULL;
799
800     while ((mnt = getmntent(mtab))) {
801         if ((!strcmp(mnt->mnt_type, "ext2") ||
802              !strcmp(mnt->mnt_type, "ext3")) &&
803             !stat(mnt->mnt_fsname, &dst) && dst.st_rdev == dev) {
804             devname = strdup(mnt->mnt_fsname);
805             break;
806         }
807     }
808     endmntent(mtab);
809
810     return devname;
811 }
812 #endif
813
814 int install_loader(const char *path, int update_only)
815 {
816     struct stat st, fst;
817     int devfd, rv;
818     const char *devname = NULL;
819     struct statfs sfs;
820
821     if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
822         fprintf(stderr, "%s: Not a directory: %s\n", program, path);
823         return 1;
824     }
825
826     if (statfs(path, &sfs)) {
827         fprintf(stderr, "%s: statfs %s: %s\n", program, path, strerror(errno));
828         return 1;
829     }
830
831     if (sfs.f_type != EXT2_SUPER_MAGIC) {
832         fprintf(stderr, "%s: not an ext2/ext3 filesystem: %s\n", program, path);
833         return 1;
834     }
835
836     devfd = -1;
837
838 #ifdef __KLIBC__
839
840     /* klibc doesn't have getmntent and friends; instead, just create
841        a new device with the appropriate device type */
842     snprintf(devname_buf, sizeof devname_buf, "/tmp/dev-%u:%u",
843              major(st.st_dev), minor(st.st_dev));
844
845     if (mknod(devname_buf, S_IFBLK | 0600, st.st_dev)) {
846         fprintf(stderr, "%s: cannot create device %s\n", program, devname);
847         return 1;
848     }
849
850     atexit(device_cleanup);     /* unlink the device node on exit */
851     devname = devname_buf;
852
853 #else
854
855     devname = find_device("/proc/mounts", st.st_dev);
856     if (!devname) {
857         /* Didn't find it in /proc/mounts, try /etc/mtab */
858         devname = find_device("/etc/mtab", st.st_dev);
859     }
860     if (!devname) {
861         fprintf(stderr, "%s: cannot find device for path %s\n", program, path);
862         return 1;
863     }
864
865     fprintf(stderr, "%s is device %s\n", path, devname);
866 #endif
867
868     if ((devfd = open(devname, O_RDWR | O_SYNC)) < 0) {
869         fprintf(stderr, "%s: cannot open device %s\n", program, devname);
870         return 1;
871     }
872
873     /* Verify that the device we opened is the device intended */
874     if (validate_device(path, devfd)) {
875         fprintf(stderr, "%s: path %s doesn't match device %s\n",
876                 program, path, devname);
877         return 1;
878     }
879
880     if (update_only && !already_installed(devfd)) {
881         fprintf(stderr, "%s: no previous extlinux boot sector found\n",
882                 program);
883         return 1;
884     }
885
886     /* Read a pre-existing ADV, if already installed */
887     if (opt.reset_adv)
888         syslinux_reset_adv(syslinux_adv);
889     else if (read_adv(path) < 0)
890         return 1;
891
892     if (modify_adv() < 0)
893         return 1;
894
895     /* Install extlinux.sys */
896     if (install_file(path, devfd, &fst))
897         return 1;
898
899     if (fst.st_dev != st.st_dev) {
900         fprintf(stderr, "%s: file system changed under us - aborting!\n",
901                 program);
902         return 1;
903     }
904
905     sync();
906     rv = install_bootblock(devfd, devname);
907     close(devfd);
908     sync();
909
910     return rv;
911 }
912
913 /*
914  * Modify the ADV of an existing installation
915  */
916 int modify_existing_adv(const char *path)
917 {
918     if (opt.reset_adv)
919         syslinux_reset_adv(syslinux_adv);
920     else if (read_adv(path) < 0)
921         return 1;
922
923     if (modify_adv() < 0)
924         return 1;
925
926     if (write_adv(path) < 0)
927         return 1;
928
929     return 0;
930 }
931
932 int main(int argc, char *argv[])
933 {
934     int o;
935     const char *directory;
936     int update_only = -1;
937
938     program = argv[0];
939
940     while ((o = getopt_long(argc, argv, short_options,
941                             long_options, NULL)) != EOF) {
942         switch (o) {
943         case 'z':
944             opt.heads = 64;
945             opt.sectors = 32;
946             break;
947         case 'S':
948             opt.sectors = strtoul(optarg, NULL, 0);
949             if (opt.sectors < 1 || opt.sectors > 63) {
950                 fprintf(stderr,
951                         "%s: invalid number of sectors: %u (must be 1-63)\n",
952                         program, opt.sectors);
953                 exit(EX_USAGE);
954             }
955             break;
956         case 'H':
957             opt.heads = strtoul(optarg, NULL, 0);
958             if (opt.heads < 1 || opt.heads > 256) {
959                 fprintf(stderr,
960                         "%s: invalid number of heads: %u (must be 1-256)\n",
961                         program, opt.heads);
962                 exit(EX_USAGE);
963             }
964             break;
965         case 'r':
966             opt.raid_mode = 1;
967             break;
968         case 'i':
969             update_only = 0;
970             break;
971         case 'u':
972         case 'U':
973             update_only = 1;
974             break;
975         case 'h':
976             usage(0);
977             break;
978         case 'o':
979             opt.set_once = optarg;
980             break;
981         case 'O':
982             opt.set_once = "";
983             break;
984         case OPT_RESET_ADV:
985             opt.reset_adv = 1;
986             break;
987         case 'v':
988             fputs("extlinux " VERSION_STR
989                   "  Copyright 1994-" YEAR_STR " H. Peter Anvin \n", stderr);
990             exit(0);
991         default:
992             usage(EX_USAGE);
993         }
994     }
995
996     directory = argv[optind];
997
998     if (!directory)
999         usage(EX_USAGE);
1000
1001     if (update_only == -1) {
1002         if (opt.reset_adv || opt.set_once) {
1003             return modify_existing_adv(directory);
1004         } else {
1005             usage(EX_USAGE);
1006         }
1007     }
1008
1009     return install_loader(directory, update_only);
1010 }