Set the close-on-exec flag, just to be saf
[oweals/busybox.git] / util-linux / mount.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini mount implementation for busybox
4  *
5  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6  * Copyright (C) 1999-2002 by Erik Andersen <andersee@debian.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21  *
22  * 3/21/1999    Charles P. Wright <cpwright@cpwright.com>
23  *              searches through fstab when -a is passed
24  *              will try mounting stuff with all fses when passed -t auto
25  *
26  * 1999-04-17   Dave Cinege...Rewrote -t auto. Fixed ro mtab.
27  *
28  * 1999-10-07   Erik Andersen <andersee@debian.org>.
29  *              Rewrite of a lot of code. Removed mtab usage (I plan on
30  *              putting it back as a compile-time option some time), 
31  *              major adjustments to option parsing, and some serious 
32  *              dieting all around.
33  *
34  * 1999-11-06   mtab suppport is back - andersee
35  *
36  * 2000-01-12   Ben Collins <bcollins@debian.org>, Borrowed utils-linux's
37  *              mount to add loop support.
38  *
39  * 2000-04-30   Dave Cinege <dcinege@psychosis.com>
40  *              Rewrote fstab while loop and lower mount section. Can now do
41  *              single mounts from fstab. Can override fstab options for single
42  *              mount. Common mount_one call for single mounts and 'all'. Fixed
43  *              mtab updating and stale entries. Removed 'remount' default. 
44  *      
45  */
46
47 #include <limits.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <string.h>
52 #include <stdio.h>
53 #include <mntent.h>
54 #include <ctype.h>
55 #include "busybox.h"
56 #if defined CONFIG_FEATURE_USE_DEVPS_PATCH
57 #       include <linux/devmtab.h>       /* For Erik's nifty devmtab device driver */
58 #endif
59
60 enum {
61         MS_MGC_VAL = 0xc0ed0000,        /* Magic number indicatng "new" flags */
62         MS_RDONLY = 1,          /* Mount read-only */
63         MS_NOSUID = 2,          /* Ignore suid and sgid bits */
64         MS_NODEV = 4,           /* Disallow access to device special files */
65         MS_NOEXEC = 8,          /* Disallow program execution */
66         MS_SYNCHRONOUS = 16,    /* Writes are synced at once */
67         MS_REMOUNT = 32,        /* Alter flags of a mounted FS */
68         MS_MANDLOCK = 64,       /* Allow mandatory locks on an FS */
69         S_QUOTA = 128,          /* Quota initialized for file/directory/symlink */
70         S_APPEND = 256,         /* Append-only file */
71         S_IMMUTABLE = 512,      /* Immutable file */
72         MS_NOATIME = 1024,      /* Do not update access times. */
73         MS_NODIRATIME = 2048,   /* Do not update directory access times */
74         MS_BIND = 4096,         /* Use the new linux 2.4.x "mount --bind" feature */
75 };
76
77
78 #if defined CONFIG_FEATURE_MOUNT_LOOP
79 #include <fcntl.h>
80 #include <sys/ioctl.h>
81 static int use_loop = FALSE;
82 #endif
83
84 extern int mount(__const char *__special_file, __const char *__dir,
85                                  __const char *__fstype, unsigned long int __rwflag,
86                                  __const void *__data);
87 extern int umount(__const char *__special_file);
88 extern int umount2(__const char *__special_file, int __flags);
89
90 extern int sysfs(int option, unsigned int fs_index, char *buf);
91
92 extern const char mtab_file[];  /* Defined in utility.c */
93
94 struct mount_options {
95         const char *name;
96         unsigned long and;
97         unsigned long or;
98 };
99
100 static const struct mount_options mount_options[] = {
101         {"async", ~MS_SYNCHRONOUS, 0},
102         {"atime", ~0, ~MS_NOATIME},
103         {"defaults", ~0, 0},
104         {"noauto", ~0, 0},
105         {"dev", ~MS_NODEV, 0},
106         {"diratime", ~0, ~MS_NODIRATIME},
107         {"exec", ~MS_NOEXEC, 0},
108         {"noatime", ~0, MS_NOATIME},
109         {"nodev", ~0, MS_NODEV},
110         {"nodiratime", ~0, MS_NODIRATIME},
111         {"noexec", ~0, MS_NOEXEC},
112         {"nosuid", ~0, MS_NOSUID},
113         {"remount", ~0, MS_REMOUNT},
114         {"ro", ~0, MS_RDONLY},
115         {"rw", ~MS_RDONLY, 0},
116         {"suid", ~MS_NOSUID, 0},
117         {"sync", ~0, MS_SYNCHRONOUS},
118         {"bind", ~0, MS_BIND},
119         {0, 0, 0}
120 };
121
122 static int
123 do_mount(char *specialfile, char *dir, char *filesystemtype, long flags,
124                  void *string_flags, int useMtab, int fakeIt, char *mtab_opts,
125                  int mount_all)
126 {
127         int status = 0;
128
129 #if defined CONFIG_FEATURE_MOUNT_LOOP
130         char *lofile = NULL;
131 #endif
132
133         if (!fakeIt) {
134 #if defined CONFIG_FEATURE_MOUNT_LOOP
135                 if (use_loop == TRUE) {
136                         int loro = flags & MS_RDONLY;
137
138                         lofile = specialfile;
139
140                         specialfile = find_unused_loop_device();
141                         if (specialfile == NULL) {
142                                 error_msg_and_die("Could not find a spare loop device");
143                         }
144                         if (set_loop(specialfile, lofile, 0, &loro)) {
145                                 error_msg_and_die("Could not setup loop device");
146                         }
147                         if (!(flags & MS_RDONLY) && loro) {     /* loop is ro, but wanted rw */
148                                 error_msg("WARNING: loop device is read-only");
149                                 flags |= MS_RDONLY;
150                         }
151                 }
152 #endif
153                 status = mount(specialfile, dir, filesystemtype, flags, string_flags);
154                 if (status < 0 && errno == EROFS) {
155                         error_msg("%s is write-protected, mounting read-only",
156                                           specialfile);
157                         status = mount(specialfile, dir, filesystemtype, flags |=
158                                                    MS_RDONLY, string_flags);
159                 }
160                 /* Don't whine about already mounted filesystems when mounting all. */
161                 if (status < 0 && errno == EBUSY && mount_all) {
162                         return TRUE;
163                 }
164         }
165
166
167         /* If the mount was sucessful, do anything needed, then return TRUE */
168         if (status == 0 || fakeIt == TRUE) {
169
170 #if defined CONFIG_FEATURE_MTAB_SUPPORT
171                 if (useMtab) {
172                         erase_mtab(specialfile);        /* Clean any stale entries */
173                         write_mtab(specialfile, dir, filesystemtype, flags, mtab_opts);
174                 }
175 #endif
176                 return (TRUE);
177         }
178
179         /* Bummer.  mount failed.  Clean up */
180 #if defined CONFIG_FEATURE_MOUNT_LOOP
181         if (lofile != NULL) {
182                 del_loop(specialfile);
183         }
184 #endif
185
186         if (errno == EPERM) {
187                 error_msg_and_die("permission denied. Are you root?");
188         }
189
190         return (FALSE);
191 }
192
193
194 static void paste_str(char **s1, const char *s2)
195 {
196         *s1 = xrealloc(*s1, strlen(*s1) + strlen(s2) + 1);
197         strcat(*s1, s2);
198 }
199
200 /* Seperate standard mount options from the nonstandard string options */
201 static void parse_mount_options(char *options, int *flags, char **strflags)
202 {
203         while (options) {
204                 int gotone = FALSE;
205                 char *comma = strchr(options, ',');
206                 const struct mount_options *f = mount_options;
207
208                 if (comma) {
209                         *comma = '\0';
210                 }
211
212                 while (f->name != 0) {
213                         if (strcasecmp(f->name, options) == 0) {
214
215                                 *flags &= f->and;
216                                 *flags |= f->or;
217                                 gotone = TRUE;
218                                 break;
219                         }
220                         f++;
221                 }
222 #if defined CONFIG_FEATURE_MOUNT_LOOP
223                 if (!strcasecmp("loop", options)) {     /* loop device support */
224                         use_loop = TRUE;
225                         gotone = TRUE;
226                 }
227 #endif
228                 if (!gotone) {
229                         if (**strflags) {
230                                 /* have previous parsed options */
231                                 paste_str(strflags, ",");
232                         }
233                         paste_str(strflags, options);
234                 }
235                 if (comma) {
236                         *comma = ',';
237                         options = ++comma;
238                 } else {
239                         break;
240                 }
241         }
242 }
243
244 static int mount_one(char *blockDevice, char *directory, char *filesystemType,
245                                          unsigned long flags, char *string_flags, int useMtab,
246                                          int fakeIt, char *mtab_opts, int whineOnErrors,
247                                          int mount_all)
248 {
249         int status = 0;
250
251 #if defined CONFIG_FEATURE_USE_DEVPS_PATCH
252         if (strcmp(filesystemType, "auto") == 0) {
253                 static const char *noauto_array[] =
254                         { "tmpfs", "shm", "proc", "ramfs", "devpts", "devfs", "usbdevfs",
255 0 };
256                 const char **noauto_fstype;
257                 const int num_of_filesystems = sysfs(3, 0, 0);
258                 char buf[255];
259                 int i = 0;
260
261                 filesystemType = buf;
262
263                 while (i < num_of_filesystems) {
264                         sysfs(2, i++, filesystemType);
265                         for (noauto_fstype = noauto_array; *noauto_fstype;
266                                  noauto_fstype++) {
267                                 if (!strcmp(filesystemType, *noauto_fstype)) {
268                                         break;
269                                 }
270                         }
271                         if (!*noauto_fstype) {
272                                 status =
273                                         do_mount(blockDevice, directory, filesystemType,
274                                                          flags | MS_MGC_VAL, string_flags, useMtab,
275                                                          fakeIt, mtab_opts, mount_all);
276                                 if (status) {
277                                         break;
278                                 }
279                         }
280                 }
281         }
282 #else
283         if (strcmp(filesystemType, "auto") == 0) {
284                 char buf[255];
285                 FILE *f;
286                 int read_proc = 0;
287
288                 f = fopen("/etc/filesystems", "r");
289
290                 if (f) {
291                         while (fgets(buf, sizeof(buf), f)) {
292                                 if (*buf == '*') {
293                                         read_proc = 1;
294                                 } else if (*buf == '#') {
295                                         continue;
296                                 } else {
297                                         filesystemType = buf;
298
299                                         /* Add NULL termination to each line */
300                                         while (*filesystemType && !isspace(*filesystemType)) {
301                                                 filesystemType++;
302                                         }
303                                         *filesystemType = '\0';
304
305                                         filesystemType = buf;
306
307                                         if (xstrlen(filesystemType)) {
308                                                 status =
309                                                         do_mount(blockDevice, directory, filesystemType,
310                                                                          flags | MS_MGC_VAL, string_flags,
311                                                                          useMtab, fakeIt, mtab_opts, mount_all);
312                                                 if (status) {
313                                                         break;
314                                                 }
315                                         }
316
317                                 }
318                         }
319                         fclose(f);
320                 }
321
322                 if ((!f || read_proc) && !status) {
323                         f = xfopen("/proc/filesystems", "r");
324
325                         while (fgets(buf, sizeof(buf), f) != NULL) {
326                                 filesystemType = buf;
327                                 if (*filesystemType == '\t') {  /* Not a nodev filesystem */
328
329                                         /* Add NULL termination to each line */
330                                         while (*filesystemType && *filesystemType != '\n') {
331                                                 filesystemType++;
332                                         }
333                                         *filesystemType = '\0';
334
335                                         filesystemType = buf;
336                                         filesystemType++;       /* hop past tab */
337
338                                         status =
339                                                 do_mount(blockDevice, directory, filesystemType,
340                                                                  flags | MS_MGC_VAL, string_flags, useMtab,
341                                                                  fakeIt, mtab_opts, mount_all);
342                                         if (status) {
343                                                 break;
344                                         }
345                                 }
346                         }
347                 }
348                 fclose(f);
349         }
350 #endif
351         else {
352                 status =
353                         do_mount(blockDevice, directory, filesystemType,
354                                          flags | MS_MGC_VAL, string_flags, useMtab, fakeIt,
355                                          mtab_opts, mount_all);
356         }
357
358         if (!status) {
359                 if (whineOnErrors) {
360                         perror_msg("Mounting %s on %s failed", blockDevice, directory);
361                 }
362                 return (FALSE);
363         }
364         return (TRUE);
365 }
366
367 static void show_mounts(char *onlytype)
368 {
369 #if defined CONFIG_FEATURE_USE_DEVPS_PATCH
370         int fd, i, numfilesystems;
371         char device[] = "/dev/mtab";
372         struct k_mntent *mntentlist;
373
374         /* open device */
375         fd = open(device, O_RDONLY);
376         if (fd < 0) {
377                 perror_msg_and_die("open failed for `%s'", device);
378         }
379
380         /* How many mounted filesystems?  We need to know to 
381          * allocate enough space for later... */
382         numfilesystems = ioctl(fd, DEVMTAB_COUNT_MOUNTS);
383         if (numfilesystems < 0) {
384                 perror_msg_and_die("\nDEVMTAB_COUNT_MOUNTS");
385         }
386         mntentlist =
387                 (struct k_mntent *) xcalloc(numfilesystems, sizeof(struct k_mntent));
388
389         /* Grab the list of mounted filesystems */
390         if (ioctl(fd, DEVMTAB_GET_MOUNTS, mntentlist) < 0) {
391                 perror_msg_and_die("\nDEVMTAB_GET_MOUNTS");
392         }
393
394         for (i = 0; i < numfilesystems; i++) {
395                 if (!onlytype || (strcmp(mntentlist[i].mnt_type, onlytype) == 0)) {
396                         printf("%s %s %s %s %d %d\n", mntentlist[i].mnt_fsname,
397                                    mntentlist[i].mnt_dir, mntentlist[i].mnt_type,
398                                    mntentlist[i].mnt_opts, mntentlist[i].mnt_freq,
399                                    mntentlist[i].mnt_passno);
400                 }
401         }
402 #ifdef CONFIG_FEATURE_CLEAN_UP
403         /* Don't bother to close files or free memory.  Exit 
404          * does that automagically, so we can save a few bytes */
405         free(mntentlist);
406         close(fd);
407 #endif
408         exit(EXIT_SUCCESS);
409 #else
410         FILE *mountTable = setmntent(mtab_file, "r");
411
412         if (mountTable) {
413                 struct mntent *m;
414
415                 while ((m = getmntent(mountTable)) != 0) {
416                         char *blockDevice = m->mnt_fsname;
417
418                         if (strcmp(blockDevice, "/dev/root") == 0) {
419                                 blockDevice = find_real_root_device_name(blockDevice);
420                         }
421                         if (!onlytype || (strcmp(m->mnt_type, onlytype) == 0)) {
422                                 printf("%s on %s type %s (%s)\n", blockDevice, m->mnt_dir,
423                                            m->mnt_type, m->mnt_opts);
424                         }
425 #ifdef CONFIG_FEATURE_CLEAN_UP
426                         if (blockDevice != m->mnt_fsname) {
427                                 free(blockDevice);
428                         }
429 #endif
430                 }
431                 endmntent(mountTable);
432         } else {
433                 perror_msg_and_die("%s", mtab_file);
434         }
435         exit(EXIT_SUCCESS);
436 #endif
437 }
438
439 extern int mount_main(int argc, char **argv)
440 {
441         struct stat statbuf;
442         char *string_flags = xstrdup("");
443         char *extra_opts;
444         int flags = 0;
445         char *filesystemType = "auto";
446         int got_filesystemType = 0;
447         char *device = xmalloc(PATH_MAX);
448         char *directory = xmalloc(PATH_MAX);
449         struct mntent *m = NULL;
450         int all = FALSE;
451         int fakeIt = FALSE;
452         int useMtab = TRUE;
453         int rc = EXIT_FAILURE;
454         FILE *f = 0;
455         int opt;
456
457         /* Parse options */
458         while ((opt = getopt(argc, argv, "o:rt:wafnv")) > 0) {
459                 switch (opt) {
460                 case 'o':
461                         parse_mount_options(optarg, &flags, &string_flags);
462                         break;
463                 case 'r':
464                         flags |= MS_RDONLY;
465                         break;
466                 case 't':
467                         filesystemType = optarg;
468                         got_filesystemType = 1;
469                         break;
470                 case 'w':
471                         flags &= ~MS_RDONLY;
472                         break;
473                 case 'a':
474                         all = TRUE;
475                         break;
476                 case 'f':
477                         fakeIt = TRUE;
478                         break;
479 #ifdef CONFIG_FEATURE_MTAB_SUPPORT
480                 case 'n':
481                         useMtab = FALSE;
482                         break;
483 #endif
484                 case 'v':
485                         break;          /* ignore -v */
486                 }
487         }
488
489         if (!all && (optind == argc)) {
490                 show_mounts(got_filesystemType ? filesystemType : NULL);
491         }
492
493         if (optind < argc) {
494                 /* if device is a filename get its real path */
495                 if (stat(argv[optind], &statbuf) == 0) {
496                         char *tmp = simplify_path(argv[optind]);
497
498                         safe_strncpy(device, tmp, PATH_MAX);
499                 } else {
500                         safe_strncpy(device, argv[optind], PATH_MAX);
501                 }
502         }
503
504         if (optind + 1 < argc)
505                 directory = simplify_path(argv[optind + 1]);
506
507         if (all || optind + 1 == argc) {
508                 f = setmntent("/etc/fstab", "r");
509
510                 if (f == NULL)
511                         perror_msg_and_die("\nCannot read /etc/fstab");
512
513                 while ((m = getmntent(f)) != NULL) {
514                         if (!all && (optind + 1 == argc)
515                                 && ((strcmp(device, m->mnt_fsname) != 0)
516                                         && (strcmp(device, m->mnt_dir) != 0))) {
517                                 continue;
518                         }
519
520                         if (all && (    /* If we're mounting 'all' */
521                                                    (strstr(m->mnt_opts, "noauto")) ||   /* and the file system isn't noauto, */
522                                                    (strstr(m->mnt_type, "swap")) ||     /* and isn't swap or nfs, then mount it */
523                                                    (strstr(m->mnt_type, "nfs")))) {
524                                 continue;
525                         }
526
527                         if (all || flags == 0) {        /* Allow single mount to override fstab flags */
528                                 flags = 0;
529                                 string_flags[0] = 0;
530                                 parse_mount_options(m->mnt_opts, &flags, &string_flags);
531                         }
532
533                         strcpy(device, m->mnt_fsname);
534                         strcpy(directory, m->mnt_dir);
535                         filesystemType = xstrdup(m->mnt_type);
536                   singlemount:
537                         extra_opts = string_flags;
538                         rc = EXIT_SUCCESS;
539 #ifdef CONFIG_NFSMOUNT
540                         if (strchr(device, ':') != NULL) {
541                                 filesystemType = "nfs";
542                                 if (nfsmount
543                                         (device, directory, &flags, &extra_opts, &string_flags,
544                                          1)) {
545                                         perror_msg("nfsmount failed");
546                                         rc = EXIT_FAILURE;
547                                 }
548                         }
549 #endif
550                         if (!mount_one
551                                 (device, directory, filesystemType, flags, string_flags,
552                                  useMtab, fakeIt, extra_opts, TRUE, all)) {
553                                 rc = EXIT_FAILURE;
554                         }
555                         if (!all) {
556                                 break;
557                         }
558                 }
559                 if (f) {
560                         endmntent(f);
561                 }
562                 if (!all && f && m == NULL) {
563                         fprintf(stderr, "Can't find %s in /etc/fstab\n", device);
564                 }
565                 return rc;
566         }
567
568         goto singlemount;
569 }