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