Merge commit 'hpa/master' into for-erwan
[profile/ivi/syslinux.git] / linux / syslinux.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  * syslinux.c - Linux installer program for SYSLINUX
15  *
16  * This is Linux-specific by now.
17  *
18  * This is an alternate version of the installer which doesn't require
19  * mtools, but requires root privilege.
20  */
21
22 /*
23  * If DO_DIRECT_MOUNT is 0, call mount(8)
24  * If DO_DIRECT_MOUNT is 1, call mount(2)
25  */
26 #ifdef __KLIBC__
27 # define DO_DIRECT_MOUNT 1
28 #else
29 # define DO_DIRECT_MOUNT 0      /* glibc has broken losetup ioctls */
30 #endif
31
32 #define _GNU_SOURCE
33 #define _XOPEN_SOURCE 500       /* For pread() pwrite() */
34 #define _FILE_OFFSET_BITS 64
35 #include <alloca.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <paths.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <inttypes.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46 #include <sys/wait.h>
47 #include <sys/mount.h>
48
49 #include <sys/ioctl.h>
50 #include <linux/fs.h>           /* FIGETBSZ, FIBMAP */
51 #include <linux/msdos_fs.h>     /* FAT_IOCTL_SET_ATTRIBUTES, SECTOR_* */
52 #ifndef FAT_IOCTL_SET_ATTRIBUTES
53 # define FAT_IOCTL_SET_ATTRIBUTES _IOW('r', 0x11, uint32_t)
54 #endif
55
56 #include <paths.h>
57 #ifndef _PATH_MOUNT
58 # define _PATH_MOUNT "/bin/mount"
59 #endif
60 #ifndef _PATH_UMOUNT
61 # define _PATH_UMOUNT "/bin/umount"
62 #endif
63 #ifndef _PATH_TMP
64 # define _PATH_TMP "/tmp/"
65 #endif
66
67 #include "syslinux.h"
68
69 #if DO_DIRECT_MOUNT
70 # include <linux/loop.h>
71 #endif
72
73 const char *program;            /* Name of program */
74 const char *device;             /* Device to install to */
75 pid_t mypid;
76 char *mntpath = NULL;           /* Path on which to mount */
77 off_t filesystem_offset = 0;    /* Filesystem offset */
78 #if DO_DIRECT_MOUNT
79 int loop_fd = -1;               /* Loop device */
80 #endif
81
82 void __attribute__ ((noreturn)) usage(void)
83 {
84     fprintf(stderr, "Usage: %s [-sfr][-d directory][-o offset] device\n",
85             program);
86     exit(1);
87 }
88
89 void __attribute__ ((noreturn)) die(const char *msg)
90 {
91     fprintf(stderr, "%s: %s\n", program, msg);
92
93 #if DO_DIRECT_MOUNT
94     if (loop_fd != -1) {
95         ioctl(loop_fd, LOOP_CLR_FD, 0); /* Free loop device */
96         close(loop_fd);
97         loop_fd = -1;
98     }
99 #endif
100
101     if (mntpath)
102         unlink(mntpath);
103
104     exit(1);
105 }
106
107 /*
108  * read/write wrapper functions
109  */
110 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
111 {
112     char *bufp = (char *)buf;
113     ssize_t rv;
114     ssize_t done = 0;
115
116     while (count) {
117         rv = pread(fd, bufp, count, offset);
118         if (rv == 0) {
119             die("short read");
120         } else if (rv == -1) {
121             if (errno == EINTR) {
122                 continue;
123             } else {
124                 die(strerror(errno));
125             }
126         } else {
127             bufp += rv;
128             offset += rv;
129             done += rv;
130             count -= rv;
131         }
132     }
133
134     return done;
135 }
136
137 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
138 {
139     const char *bufp = (const char *)buf;
140     ssize_t rv;
141     ssize_t done = 0;
142
143     while (count) {
144         rv = pwrite(fd, bufp, count, offset);
145         if (rv == 0) {
146             die("short write");
147         } else if (rv == -1) {
148             if (errno == EINTR) {
149                 continue;
150             } else {
151                 die(strerror(errno));
152             }
153         } else {
154             bufp += rv;
155             offset += rv;
156             done += rv;
157             count -= rv;
158         }
159     }
160
161     return done;
162 }
163
164 /*
165  * Create a block map for ldlinux.sys
166  */
167 int make_block_map(uint32_t * sectors, int len, int dev_fd, int fd)
168 {
169     int nsectors = 0;
170     int blocksize, nblock, block;
171     int i;
172
173     (void)dev_fd;
174
175     if (ioctl(fd, FIGETBSZ, &blocksize) < 0)
176         die("ioctl FIGETBSZ failed");
177
178     blocksize >>= SECTOR_BITS;  /* sectors/block */
179
180     nblock = 0;
181     while (len > 0) {
182         block = nblock++;
183         if (ioctl(fd, FIBMAP, &block) < 0)
184             die("ioctl FIBMAP failed");
185
186         for (i = 0; i < blocksize; i++) {
187             if (len <= 0)
188                 break;
189
190             *sectors++ = (block * blocksize) + i;
191             nsectors++;
192             len -= (1 << SECTOR_BITS);
193         }
194     }
195
196     return nsectors;
197 }
198
199 /*
200  * Mount routine
201  */
202 int do_mount(int dev_fd, int *cookie, const char *mntpath, const char *fstype)
203 {
204     struct stat st;
205
206     (void)cookie;
207
208     if (fstat(dev_fd, &st) < 0)
209         return errno;
210
211 #if DO_DIRECT_MOUNT
212     {
213         if (!S_ISBLK(st.st_mode)) {
214             /* It's file, need to mount it loopback */
215             unsigned int n = 0;
216             struct loop_info64 loopinfo;
217             int loop_fd;
218
219             for (n = 0; loop_fd < 0; n++) {
220                 snprintf(devfdname, sizeof devfdname, "/dev/loop%u", n);
221                 loop_fd = open(devfdname, O_RDWR);
222                 if (loop_fd < 0 && errno == ENOENT) {
223                     die("no available loopback device!");
224                 }
225                 if (ioctl(loop_fd, LOOP_SET_FD, (void *)dev_fd)) {
226                     close(loop_fd);
227                     loop_fd = -1;
228                     if (errno != EBUSY)
229                         die("cannot set up loopback device");
230                     else
231                         continue;
232                 }
233
234                 if (ioctl(loop_fd, LOOP_GET_STATUS64, &loopinfo) ||
235                     (loopinfo.lo_offset = filesystem_offset,
236                      ioctl(loop_fd, LOOP_SET_STATUS64, &loopinfo)))
237                     die("cannot set up loopback device");
238             }
239
240             *cookie = loop_fd;
241         } else {
242             snprintf(devfdname, sizeof devfdname, "/proc/%lu/fd/%d",
243                      (unsigned long)mypid, dev_fd);
244             *cookie = -1;
245         }
246
247         return mount(devfdname, mntpath, fstype,
248                      MS_NOEXEC | MS_NOSUID, "umask=077,quiet");
249     }
250 #else
251     {
252         char devfdname[128], mnt_opts[128];
253         pid_t f, w;
254         int status;
255
256         snprintf(devfdname, sizeof devfdname, "/proc/%lu/fd/%d",
257                  (unsigned long)mypid, dev_fd);
258
259         f = fork();
260         if (f < 0) {
261             return -1;
262         } else if (f == 0) {
263             if (!S_ISBLK(st.st_mode)) {
264                 snprintf(mnt_opts, sizeof mnt_opts,
265                          "rw,nodev,noexec,loop,offset=%llu,umask=077,quiet",
266                          (unsigned long long)filesystem_offset);
267             } else {
268                 snprintf(mnt_opts, sizeof mnt_opts,
269                          "rw,nodev,noexec,umask=077,quiet");
270             }
271             execl(_PATH_MOUNT, _PATH_MOUNT, "-t", fstype, "-o", mnt_opts,
272                   devfdname, mntpath, NULL);
273             _exit(255);         /* execl failed */
274         }
275
276         w = waitpid(f, &status, 0);
277         return (w != f || status) ? -1 : 0;
278     }
279 #endif
280 }
281
282 /*
283  * umount routine
284  */
285 void do_umount(const char *mntpath, int cookie)
286 {
287 #if DO_DIRECT_MOUNT
288     int loop_fd = cookie;
289
290     if (umount2(mntpath, 0))
291         die("could not umount path");
292
293     if (loop_fd != -1) {
294         ioctl(loop_fd, LOOP_CLR_FD, 0); /* Free loop device */
295         close(loop_fd);
296         loop_fd = -1;
297     }
298 #else
299     pid_t f = fork();
300     pid_t w;
301     int status;
302     (void)cookie;
303
304     if (f < 0) {
305         perror("fork");
306         exit(1);
307     } else if (f == 0) {
308         execl(_PATH_UMOUNT, _PATH_UMOUNT, mntpath, NULL);
309     }
310
311     w = waitpid(f, &status, 0);
312     if (w != f || status) {
313         exit(1);
314     }
315 #endif
316 }
317
318 int main(int argc, char *argv[])
319 {
320     static unsigned char sectbuf[SECTOR_SIZE];
321     unsigned char *dp;
322     const unsigned char *cdp;
323     int dev_fd, fd;
324     struct stat st;
325     int nb, left;
326     int err = 0;
327     char mntname[128];
328     char *ldlinux_name, **argp, *opt;
329     const char *subdir = NULL;
330     uint32_t sectors[65];       /* 65 is maximum possible */
331     int nsectors = 0;
332     const char *errmsg;
333     int mnt_cookie;
334
335     int force = 0;              /* -f (force) option */
336     int stupid = 0;             /* -s (stupid) option */
337     int raid_mode = 0;          /* -r (RAID) option */
338
339     (void)argc;                 /* Unused */
340
341     program = argv[0];
342     mypid = getpid();
343
344     device = NULL;
345
346     umask(077);
347
348     for (argp = argv + 1; *argp; argp++) {
349         if (**argp == '-') {
350             opt = *argp + 1;
351             if (!*opt)
352                 usage();
353
354             while (*opt) {
355                 if (*opt == 's') {
356                     stupid = 1;
357                 } else if (*opt == 'r') {
358                     raid_mode = 1;
359                 } else if (*opt == 'f') {
360                     force = 1;  /* Force install */
361                 } else if (*opt == 'd' && argp[1]) {
362                     subdir = *++argp;
363                 } else if (*opt == 'o' && argp[1]) {
364                     /* Byte offset */
365                     filesystem_offset = (off_t) strtoull(*++argp, NULL, 0);
366                 } else {
367                     usage();
368                 }
369                 opt++;
370             }
371         } else {
372             if (device)
373                 usage();
374             device = *argp;
375         }
376     }
377
378     if (!device)
379         usage();
380
381     /*
382      * First make sure we can open the device at all, and that we have
383      * read/write permission.
384      */
385     dev_fd = open(device, O_RDWR);
386     if (dev_fd < 0 || fstat(dev_fd, &st) < 0) {
387         perror(device);
388         exit(1);
389     }
390
391     if (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
392         die("not a device or regular file");
393     }
394
395     if (filesystem_offset && S_ISBLK(st.st_mode)) {
396         die("can't combine an offset with a block device");
397     }
398
399     xpread(dev_fd, sectbuf, SECTOR_SIZE, filesystem_offset);
400     fsync(dev_fd);
401
402     /*
403      * Check to see that what we got was indeed an MS-DOS boot sector/superblock
404      */
405     if ((errmsg = syslinux_check_bootsect(sectbuf))) {
406         fprintf(stderr, "%s: %s\n", device, errmsg);
407         exit(1);
408     }
409
410     /*
411      * Now mount the device.
412      */
413     if (geteuid()) {
414         die("This program needs root privilege");
415     } else {
416         int i = 0;
417         struct stat dst;
418         int rv;
419
420         /* We're root or at least setuid.
421            Make a temp dir and pass all the gunky options to mount. */
422
423         if (chdir(_PATH_TMP)) {
424             perror(program);
425             exit(1);
426         }
427 #define TMP_MODE (S_IXUSR|S_IWUSR|S_IXGRP|S_IWGRP|S_IWOTH|S_IXOTH|S_ISVTX)
428
429         if (stat(".", &dst) || !S_ISDIR(dst.st_mode) ||
430             (dst.st_mode & TMP_MODE) != TMP_MODE) {
431             die("possibly unsafe " _PATH_TMP " permissions");
432         }
433
434         for (i = 0;; i++) {
435             snprintf(mntname, sizeof mntname, "syslinux.mnt.%lu.%d",
436                      (unsigned long)mypid, i);
437
438             if (lstat(mntname, &dst) != -1 || errno != ENOENT)
439                 continue;
440
441             rv = mkdir(mntname, 0000);
442
443             if (rv == -1) {
444                 if (errno == EEXIST || errno == EINTR)
445                     continue;
446                 perror(program);
447                 exit(1);
448             }
449
450             if (lstat(mntname, &dst) || dst.st_mode != (S_IFDIR | 0000) ||
451                 dst.st_uid != 0) {
452                 die("someone is trying to symlink race us!");
453             }
454             break;              /* OK, got something... */
455         }
456
457         mntpath = mntname;
458     }
459
460     if (do_mount(dev_fd, &mnt_cookie, mntpath, "vfat") &&
461         do_mount(dev_fd, &mnt_cookie, mntpath, "msdos")) {
462         rmdir(mntpath);
463         die("mount failed");
464     }
465
466     ldlinux_name = alloca(strlen(mntpath) + 14 +
467                           (subdir ? strlen(subdir) + 2 : 0));
468     if (!ldlinux_name) {
469         perror(program);
470         err = 1;
471         goto umount;
472     }
473     sprintf(ldlinux_name, "%s%s%s//ldlinux.sys",
474             mntpath, subdir ? "//" : "", subdir ? subdir : "");
475
476     if ((fd = open(ldlinux_name, O_RDONLY)) >= 0) {
477         uint32_t zero_attr = 0;
478         ioctl(fd, FAT_IOCTL_SET_ATTRIBUTES, &zero_attr);
479         close(fd);
480     }
481
482     unlink(ldlinux_name);
483     fd = open(ldlinux_name, O_WRONLY | O_CREAT | O_TRUNC, 0444);
484     if (fd < 0) {
485         perror(device);
486         err = 1;
487         goto umount;
488     }
489
490     cdp = syslinux_ldlinux;
491     left = syslinux_ldlinux_len;
492     while (left) {
493         nb = write(fd, cdp, left);
494         if (nb == -1 && errno == EINTR)
495             continue;
496         else if (nb <= 0) {
497             perror(device);
498             err = 1;
499             goto umount;
500         }
501
502         dp += nb;
503         left -= nb;
504     }
505
506     fsync(fd);
507     /*
508      * Set the attributes
509      */
510     {
511         uint32_t attr = 0x07;   /* Hidden+System+Readonly */
512         ioctl(fd, FAT_IOCTL_SET_ATTRIBUTES, &attr);
513     }
514
515     /*
516      * Create a block map.
517      */
518     nsectors = make_block_map(sectors, syslinux_ldlinux_len, dev_fd, fd);
519
520     close(fd);
521     sync();
522
523 umount:
524     do_umount(mntpath, mnt_cookie);
525     sync();
526     rmdir(mntpath);
527
528     if (err)
529         exit(err);
530
531     /*
532      * Patch ldlinux.sys and the boot sector
533      */
534     syslinux_patch(sectors, nsectors, stupid, raid_mode);
535
536     /*
537      * Write the now-patched first sector of ldlinux.sys
538      */
539     xpwrite(dev_fd, syslinux_ldlinux, SECTOR_SIZE,
540             filesystem_offset + ((off_t) sectors[0] << SECTOR_BITS));
541
542     /*
543      * To finish up, write the boot sector
544      */
545
546     /* Read the superblock again since it might have changed while mounted */
547     xpread(dev_fd, sectbuf, SECTOR_SIZE, filesystem_offset);
548
549     /* Copy the syslinux code into the boot sector */
550     syslinux_make_bootsect(sectbuf);
551
552     /* Write new boot sector */
553     xpwrite(dev_fd, sectbuf, SECTOR_SIZE, filesystem_offset);
554
555     close(dev_fd);
556     sync();
557
558     /* Done! */
559
560     return 0;
561 }