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