mount: style fixes
[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-2004 by Erik Andersen <andersen@codepoet.org>
7  * Copyright (C) 2005-2006 by Rob Landley <rob@landley.net>
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  */
11
12 /* todo:
13  * bb_getopt_ulflags();
14  */
15
16 /* Design notes: There is no spec for mount.  Remind me to write one.
17
18    mount_main() calls singlemount() which calls mount_it_now().
19
20    mount_main() can loop through /etc/fstab for mount -a
21    singlemount() can loop through /etc/filesystems for fstype detection.
22    mount_it_now() does the actual mount.
23 */
24
25 #include "busybox.h"
26 #include <mntent.h>
27
28 /* Needed for nfs support only... */
29 #include <syslog.h>
30 #include <sys/utsname.h>
31 #undef TRUE
32 #undef FALSE
33 #include <rpc/rpc.h>
34 #include <rpc/pmap_prot.h>
35 #include <rpc/pmap_clnt.h>
36
37
38 // Not real flags, but we want to be able to check for this.
39 #define MOUNT_NOAUTO    (1<<29)
40 #define MOUNT_SWAP      (1<<30)
41
42 /* Standard mount options (from -o options or --options), with corresponding
43  * flags */
44
45 struct {
46         char *name;
47         long flags;
48 } static mount_options[] = {
49         // MS_FLAGS set a bit.  ~MS_FLAGS disable that bit.  0 flags are NOPs.
50
51         USE_FEATURE_MOUNT_LOOP(
52                 {"loop", 0},
53         )
54
55         USE_FEATURE_MOUNT_FSTAB(
56                 {"defaults", 0},
57                 {"quiet", 0},
58                 {"noauto",MOUNT_NOAUTO},
59                 {"swap",MOUNT_SWAP},
60         )
61
62         USE_FEATURE_MOUNT_FLAGS(
63                 // vfs flags
64                 {"nosuid", MS_NOSUID},
65                 {"suid", ~MS_NOSUID},
66                 {"dev", ~MS_NODEV},
67                 {"nodev", MS_NODEV},
68                 {"exec", ~MS_NOEXEC},
69                 {"noexec", MS_NOEXEC},
70                 {"sync", MS_SYNCHRONOUS},
71                 {"async", ~MS_SYNCHRONOUS},
72                 {"atime", ~MS_NOATIME},
73                 {"noatime", MS_NOATIME},
74                 {"diratime", ~MS_NODIRATIME},
75                 {"nodiratime", MS_NODIRATIME},
76                 {"loud", ~MS_SILENT},
77
78                 // action flags
79
80                 {"bind", MS_BIND},
81                 {"move", MS_MOVE},
82                 {"shared", MS_SHARED},
83                 {"slave", MS_SLAVE},
84                 {"private", MS_PRIVATE},
85                 {"unbindable", MS_UNBINDABLE},
86                 {"rshared", MS_SHARED|MS_RECURSIVE},
87                 {"rslave", MS_SLAVE|MS_RECURSIVE},
88                 {"rprivate", MS_SLAVE|MS_RECURSIVE},
89                 {"runbindable", MS_UNBINDABLE|MS_RECURSIVE},
90         )
91
92         // Always understood.
93
94         {"ro", MS_RDONLY},        // vfs flag
95         {"rw", ~MS_RDONLY},       // vfs flag
96         {"remount", MS_REMOUNT},  // action flag
97 };
98
99
100
101 /* Append mount options to string */
102 static void append_mount_options(char **oldopts, char *newopts)
103 {
104         if (*oldopts && **oldopts) {
105                 char *temp = xasprintf("%s,%s",*oldopts,newopts);
106                 free(*oldopts);
107                 *oldopts = temp;
108         } else {
109                 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
110                 *oldopts = xstrdup(newopts);
111         }
112 }
113
114 /* Use the mount_options list to parse options into flags.
115  * Also return list of unrecognized options if unrecognized!=NULL */
116 static int parse_mount_options(char *options, char **unrecognized)
117 {
118         int flags = MS_SILENT;
119
120         // Loop through options
121         for (;;) {
122                 int i;
123                 char *comma = strchr(options, ',');
124
125                 if (comma) *comma = 0;
126
127                 // Find this option in mount_options
128                 for (i = 0; i < (sizeof(mount_options) / sizeof(*mount_options)); i++) {
129                         if (!strcasecmp(mount_options[i].name, options)) {
130                                 long fl = mount_options[i].flags;
131                                 if (fl < 0) flags &= fl;
132                                 else flags |= fl;
133                                 break;
134                         }
135                 }
136                 // If unrecognized not NULL, append unrecognized mount options */
137                 if (unrecognized
138                                 && i == (sizeof(mount_options) / sizeof(*mount_options)))
139                 {
140                         // Add it to strflags, to pass on to kernel
141                         i = *unrecognized ? strlen(*unrecognized) : 0;
142                         *unrecognized = xrealloc(*unrecognized, i+strlen(options)+2);
143
144                         // Comma separated if it's not the first one
145                         if (i) (*unrecognized)[i++] = ',';
146                         strcpy((*unrecognized)+i, options);
147                 }
148
149                 // Advance to next option, or finish
150                 if (comma) {
151                         *comma = ',';
152                         options = ++comma;
153                 } else break;
154         }
155
156         return flags;
157 }
158
159 // Return a list of all block device backed filesystems
160
161 static llist_t *get_block_backed_filesystems(void)
162 {
163         char *fs, *buf,
164                  *filesystems[] = {"/etc/filesystems", "/proc/filesystems", 0};
165         llist_t *list = 0;
166         int i;
167         FILE *f;
168
169         for (i = 0; filesystems[i]; i++) {
170                 f = fopen(filesystems[i], "r");
171                 if (!f) continue;
172
173                 for (fs = buf = 0; (fs = buf = bb_get_chomped_line_from_file(f));
174                         free(buf))
175                 {
176                         if (!strncmp(buf,"nodev",5) && isspace(buf[5])) continue;
177
178                         while (isspace(*fs)) fs++;
179                         if (*fs=='#' || *fs=='*') continue;
180                         if (!*fs) continue;
181
182                         llist_add_to_end(&list,xstrdup(fs));
183                 }
184                 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
185         }
186
187         return list;
188 }
189
190 llist_t *fslist = 0;
191
192 #if ENABLE_FEATURE_CLEAN_UP
193 static void delete_block_backed_filesystems(void)
194 {
195         llist_free(fslist, free);
196 }
197 #else
198 void delete_block_backed_filesystems(void);
199 #endif
200
201 #if ENABLE_FEATURE_MTAB_SUPPORT
202 static int useMtab = 1;
203 static int fakeIt;
204 #else
205 #define useMtab 0
206 #define fakeIt 0
207 #endif
208
209 // Perform actual mount of specific filesystem at specific location.
210 // NB: mp->xxx fields may be trashed on exit
211 static int mount_it_now(struct mntent *mp, int vfsflags, char *filteropts)
212 {
213         int rc;
214
215         if (fakeIt) return 0;
216
217         // Mount, with fallback to read-only if necessary.
218
219         for (;;) {
220                 rc = mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
221                                 vfsflags, filteropts);
222                 if (!rc || (vfsflags&MS_RDONLY) || (errno!=EACCES && errno!=EROFS))
223                         break;
224                 bb_error_msg("%s is write-protected, mounting read-only",
225                                 mp->mnt_fsname);
226                 vfsflags |= MS_RDONLY;
227         }
228
229         // Abort entirely if permission denied.
230
231         if (rc && errno == EPERM)
232                 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
233
234         /* If the mount was successful, and we're maintaining an old-style
235          * mtab file by hand, add the new entry to it now. */
236
237         if(ENABLE_FEATURE_MTAB_SUPPORT && useMtab && !rc && !(vfsflags & MS_REMOUNT)) {
238                 char dirbuf[PATH_MAX];
239                 char srcbuf[PATH_MAX];
240                 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
241                 int i;
242
243                 if(!mountTable)
244                         bb_error_msg("no %s",bb_path_mtab_file);
245
246                 // Add vfs string flags
247
248                 for(i=0; mount_options[i].flags != MS_REMOUNT; i++)
249                         if (mount_options[i].flags > 0 && (mount_options[i].flags & vfsflags))
250                                 append_mount_options(&(mp->mnt_opts), mount_options[i].name);
251
252                 // Remove trailing / (if any) from directory we mounted on
253
254                 i = strlen(mp->mnt_dir) - 1;
255                 if(i > 0 && mp->mnt_dir[i] == '/') mp->mnt_dir[i] = 0;
256
257                 // Add full pathnames as needed
258
259                 if (mp->mnt_dir[0] != '/') {
260                         getcwd(dirbuf, sizeof(dirbuf));
261                         i = strlen(dirbuf);
262                         /* strcat() would be unsafe here */
263                         snprintf(dirbuf+i, sizeof(dirbuf)-i, "/%s", mp->mnt_dir);
264                         mp->mnt_dir = dirbuf;
265                 }
266                 if (!mp->mnt_type || !*mp->mnt_type) { /* bind mount */
267                         if (mp->mnt_fsname[0] != '/') {
268                                 getcwd(srcbuf, sizeof(srcbuf));
269                                 i = strlen(srcbuf);
270                                 snprintf(srcbuf+i, sizeof(srcbuf)-i, "/%s",
271                                                 mp->mnt_fsname);
272                                 mp->mnt_fsname = srcbuf;
273                         }
274                         mp->mnt_type = "none";
275                 }
276                 mp->mnt_freq = mp->mnt_passno = 0;
277
278                 // Write and close.
279
280                 addmntent(mountTable, mp);
281                 endmntent(mountTable);
282         }
283
284         return rc;
285 }
286
287 #if ENABLE_FEATURE_MOUNT_NFS
288
289 /*
290  * Linux NFS mount
291  * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
292  *
293  * Licensed under GPLv2, see file LICENSE in this tarball for details.
294  *
295  * Wed Feb  8 12:51:48 1995, biro@yggdrasil.com (Ross Biro): allow all port
296  * numbers to be specified on the command line.
297  *
298  * Fri, 8 Mar 1996 18:01:39, Swen Thuemmler <swen@uni-paderborn.de>:
299  * Omit the call to connect() for Linux version 1.3.11 or later.
300  *
301  * Wed Oct  1 23:55:28 1997: Dick Streefland <dick_streefland@tasking.com>
302  * Implemented the "bg", "fg" and "retry" mount options for NFS.
303  *
304  * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
305  * - added Native Language Support
306  *
307  * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
308  * plus NFSv3 stuff.
309  */
310
311 /* This is just a warning of a common mistake.  Possibly this should be a
312  * uclibc faq entry rather than in busybox... */
313 #if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
314 #error "You need to build uClibc with UCLIBC_HAS_RPC for NFS support."
315 #endif
316
317 #define MOUNTPORT 635
318 #define MNTPATHLEN 1024
319 #define MNTNAMLEN 255
320 #define FHSIZE 32
321 #define FHSIZE3 64
322
323 typedef char fhandle[FHSIZE];
324
325 typedef struct {
326         unsigned int fhandle3_len;
327         char *fhandle3_val;
328 } fhandle3;
329
330 enum mountstat3 {
331         MNT_OK = 0,
332         MNT3ERR_PERM = 1,
333         MNT3ERR_NOENT = 2,
334         MNT3ERR_IO = 5,
335         MNT3ERR_ACCES = 13,
336         MNT3ERR_NOTDIR = 20,
337         MNT3ERR_INVAL = 22,
338         MNT3ERR_NAMETOOLONG = 63,
339         MNT3ERR_NOTSUPP = 10004,
340         MNT3ERR_SERVERFAULT = 10006,
341 };
342 typedef enum mountstat3 mountstat3;
343
344 struct fhstatus {
345         unsigned int fhs_status;
346         union {
347                 fhandle fhs_fhandle;
348         } fhstatus_u;
349 };
350 typedef struct fhstatus fhstatus;
351
352 struct mountres3_ok {
353         fhandle3 fhandle;
354         struct {
355                 unsigned int auth_flavours_len;
356                 char *auth_flavours_val;
357         } auth_flavours;
358 };
359 typedef struct mountres3_ok mountres3_ok;
360
361 struct mountres3 {
362         mountstat3 fhs_status;
363         union {
364                 mountres3_ok mountinfo;
365         } mountres3_u;
366 };
367 typedef struct mountres3 mountres3;
368
369 typedef char *dirpath;
370
371 typedef char *name;
372
373 typedef struct mountbody *mountlist;
374
375 struct mountbody {
376         name ml_hostname;
377         dirpath ml_directory;
378         mountlist ml_next;
379 };
380 typedef struct mountbody mountbody;
381
382 typedef struct groupnode *groups;
383
384 struct groupnode {
385         name gr_name;
386         groups gr_next;
387 };
388 typedef struct groupnode groupnode;
389
390 typedef struct exportnode *exports;
391
392 struct exportnode {
393         dirpath ex_dir;
394         groups ex_groups;
395         exports ex_next;
396 };
397 typedef struct exportnode exportnode;
398
399 struct ppathcnf {
400         int pc_link_max;
401         short pc_max_canon;
402         short pc_max_input;
403         short pc_name_max;
404         short pc_path_max;
405         short pc_pipe_buf;
406         u_char pc_vdisable;
407         char pc_xxx;
408         short pc_mask[2];
409 };
410 typedef struct ppathcnf ppathcnf;
411
412 #define MOUNTPROG 100005
413 #define MOUNTVERS 1
414
415 #define MOUNTPROC_NULL 0
416 #define MOUNTPROC_MNT 1
417 #define MOUNTPROC_DUMP 2
418 #define MOUNTPROC_UMNT 3
419 #define MOUNTPROC_UMNTALL 4
420 #define MOUNTPROC_EXPORT 5
421 #define MOUNTPROC_EXPORTALL 6
422
423 #define MOUNTVERS_POSIX 2
424
425 #define MOUNTPROC_PATHCONF 7
426
427 #define MOUNT_V3 3
428
429 #define MOUNTPROC3_NULL 0
430 #define MOUNTPROC3_MNT 1
431 #define MOUNTPROC3_DUMP 2
432 #define MOUNTPROC3_UMNT 3
433 #define MOUNTPROC3_UMNTALL 4
434 #define MOUNTPROC3_EXPORT 5
435
436 enum {
437 #ifndef NFS_FHSIZE
438         NFS_FHSIZE = 32,
439 #endif
440 #ifndef NFS_PORT
441         NFS_PORT = 2049
442 #endif
443 };
444
445 /*
446  * We want to be able to compile mount on old kernels in such a way
447  * that the binary will work well on more recent kernels.
448  * Thus, if necessary we teach nfsmount.c the structure of new fields
449  * that will come later.
450  *
451  * Moreover, the new kernel includes conflict with glibc includes
452  * so it is easiest to ignore the kernel altogether (at compile time).
453  */
454
455 struct nfs2_fh {
456         char                    data[32];
457 };
458 struct nfs3_fh {
459         unsigned short          size;
460         unsigned char           data[64];
461 };
462
463 struct nfs_mount_data {
464         int             version;                /* 1 */
465         int             fd;                     /* 1 */
466         struct nfs2_fh  old_root;               /* 1 */
467         int             flags;                  /* 1 */
468         int             rsize;                  /* 1 */
469         int             wsize;                  /* 1 */
470         int             timeo;                  /* 1 */
471         int             retrans;                /* 1 */
472         int             acregmin;               /* 1 */
473         int             acregmax;               /* 1 */
474         int             acdirmin;               /* 1 */
475         int             acdirmax;               /* 1 */
476         struct sockaddr_in addr;                /* 1 */
477         char            hostname[256];          /* 1 */
478         int             namlen;                 /* 2 */
479         unsigned int    bsize;                  /* 3 */
480         struct nfs3_fh  root;                   /* 4 */
481 };
482
483 /* bits in the flags field */
484 enum {
485         NFS_MOUNT_SOFT = 0x0001,        /* 1 */
486         NFS_MOUNT_INTR = 0x0002,        /* 1 */
487         NFS_MOUNT_SECURE = 0x0004,      /* 1 */
488         NFS_MOUNT_POSIX = 0x0008,       /* 1 */
489         NFS_MOUNT_NOCTO = 0x0010,       /* 1 */
490         NFS_MOUNT_NOAC = 0x0020,        /* 1 */
491         NFS_MOUNT_TCP = 0x0040,         /* 2 */
492         NFS_MOUNT_VER3 = 0x0080,        /* 3 */
493         NFS_MOUNT_KERBEROS = 0x0100,    /* 3 */
494         NFS_MOUNT_NONLM = 0x0200        /* 3 */
495 };
496
497
498 /*
499  * We need to translate between nfs status return values and
500  * the local errno values which may not be the same.
501  *
502  * Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>: change errno:
503  * "after #include <errno.h> the symbol errno is reserved for any use,
504  *  it cannot even be used as a struct tag or field name".
505  */
506
507 #ifndef EDQUOT
508 #define EDQUOT  ENOSPC
509 #endif
510
511 // Convert each NFSERR_BLAH into EBLAH
512
513 static const struct {
514         int stat;
515         int errnum;
516 } nfs_errtbl[] = {
517         {0,0}, {1,EPERM}, {2,ENOENT}, {5,EIO}, {6,ENXIO}, {13,EACCES}, {17,EEXIST},
518         {19,ENODEV}, {20,ENOTDIR}, {21,EISDIR}, {22,EINVAL}, {27,EFBIG},
519         {28,ENOSPC}, {30,EROFS}, {63,ENAMETOOLONG}, {66,ENOTEMPTY}, {69,EDQUOT},
520         {70,ESTALE}, {71,EREMOTE}, {-1,EIO}
521 };
522
523 static char *nfs_strerror(int status)
524 {
525         int i;
526         static char buf[256];
527
528         for (i = 0; nfs_errtbl[i].stat != -1; i++) {
529                 if (nfs_errtbl[i].stat == status)
530                         return strerror(nfs_errtbl[i].errnum);
531         }
532         sprintf(buf, "unknown nfs status return value: %d", status);
533         return buf;
534 }
535
536 static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
537 {
538         if (!xdr_opaque(xdrs, objp, FHSIZE))
539                  return FALSE;
540         return TRUE;
541 }
542
543 static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
544 {
545         if (!xdr_u_int(xdrs, &objp->fhs_status))
546                  return FALSE;
547         switch (objp->fhs_status) {
548         case 0:
549                 if (!xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle))
550                          return FALSE;
551                 break;
552         default:
553                 break;
554         }
555         return TRUE;
556 }
557
558 static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
559 {
560         if (!xdr_string(xdrs, objp, MNTPATHLEN))
561                  return FALSE;
562         return TRUE;
563 }
564
565 static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
566 {
567         if (!xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (unsigned int *) &objp->fhandle3_len, FHSIZE3))
568                  return FALSE;
569         return TRUE;
570 }
571
572 static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
573 {
574         if (!xdr_fhandle3(xdrs, &objp->fhandle))
575                 return FALSE;
576         if (!xdr_array(xdrs, &(objp->auth_flavours.auth_flavours_val), &(objp->auth_flavours.auth_flavours_len), ~0,
577                                 sizeof (int), (xdrproc_t) xdr_int))
578                 return FALSE;
579         return TRUE;
580 }
581
582 static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
583 {
584         if (!xdr_enum(xdrs, (enum_t *) objp))
585                  return FALSE;
586         return TRUE;
587 }
588
589 static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
590 {
591         if (!xdr_mountstat3(xdrs, &objp->fhs_status))
592                 return FALSE;
593         switch (objp->fhs_status) {
594         case MNT_OK:
595                 if (!xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo))
596                          return FALSE;
597                 break;
598         default:
599                 break;
600         }
601         return TRUE;
602 }
603
604 #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
605
606 /*
607  * nfs_mount_version according to the sources seen at compile time.
608  */
609 static int nfs_mount_version;
610 static int kernel_version;
611
612 /*
613  * Unfortunately, the kernel prints annoying console messages
614  * in case of an unexpected nfs mount version (instead of
615  * just returning some error).  Therefore we'll have to try
616  * and figure out what version the kernel expects.
617  *
618  * Variables:
619  *      KERNEL_NFS_MOUNT_VERSION: kernel sources at compile time
620  *      NFS_MOUNT_VERSION: these nfsmount sources at compile time
621  *      nfs_mount_version: version this source and running kernel can handle
622  */
623 static void
624 find_kernel_nfs_mount_version(void)
625 {
626         if (kernel_version)
627                 return;
628
629         nfs_mount_version = 4; /* default */
630
631         kernel_version = get_linux_version_code();
632         if (kernel_version) {
633                 if (kernel_version < KERNEL_VERSION(2,1,32))
634                         nfs_mount_version = 1;
635                 else if (kernel_version < KERNEL_VERSION(2,2,18) ||
636                                 (kernel_version >= KERNEL_VERSION(2,3,0) &&
637                                  kernel_version < KERNEL_VERSION(2,3,99)))
638                         nfs_mount_version = 3;
639                 /* else v4 since 2.3.99pre4 */
640         }
641 }
642
643 static struct pmap *
644 get_mountport(struct sockaddr_in *server_addr,
645         long unsigned prog,
646         long unsigned version,
647         long unsigned proto,
648         long unsigned port)
649 {
650         struct pmaplist *pmap;
651         static struct pmap p = {0, 0, 0, 0};
652
653         server_addr->sin_port = PMAPPORT;
654         pmap = pmap_getmaps(server_addr);
655
656         if (version > MAX_NFSPROT)
657                 version = MAX_NFSPROT;
658         if (!prog)
659                 prog = MOUNTPROG;
660         p.pm_prog = prog;
661         p.pm_vers = version;
662         p.pm_prot = proto;
663         p.pm_port = port;
664         
665         while (pmap) {
666                 if (pmap->pml_map.pm_prog != prog)
667                         goto next;
668                 if (!version && p.pm_vers > pmap->pml_map.pm_vers)
669                         goto next;
670                 if (version > 2 && pmap->pml_map.pm_vers != version)
671                         goto next;
672                 if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
673                         goto next;
674                 if (pmap->pml_map.pm_vers > MAX_NFSPROT ||
675                     (proto && p.pm_prot && pmap->pml_map.pm_prot != proto) ||
676                     (port && pmap->pml_map.pm_port != port))
677                         goto next;
678                 memcpy(&p, &pmap->pml_map, sizeof(p));
679 next:
680                 pmap = pmap->pml_next;
681         }
682         if (!p.pm_vers)
683                 p.pm_vers = MOUNTVERS;
684         if (!p.pm_port)
685                 p.pm_port = MOUNTPORT;
686         if (!p.pm_prot)
687                 p.pm_prot = IPPROTO_TCP;
688         return &p;
689 }
690
691 static int daemonize(void)
692 {
693         int fd;
694         int pid = fork();
695         if (pid < 0) /* error */
696                 return -errno;
697         if (pid > 0) /* parent */
698                 return 0;
699         /* child */
700         fd = xopen(bb_dev_null, O_RDWR);
701         dup2(fd, 0);
702         dup2(fd, 1);
703         dup2(fd, 2);
704         if (fd > 2) close(fd);
705         setsid();
706         openlog(bb_applet_name, LOG_PID, LOG_DAEMON);
707         logmode = LOGMODE_SYSLOG;
708         return 1;
709 }
710
711 // TODO
712 static inline int we_saw_this_host_before(const char *hostname)
713 {
714         return 0;
715 }
716
717 /* RPC strerror analogs are terminally idiotic:
718  * *mandatory* prefix and \n at end.
719  * This hopefully helps. Usage:
720  * error_msg_rpc(clnt_*error*(" ")) */
721 static void error_msg_rpc(const char *msg)
722 {
723         size_t len;
724         while (msg[0] == ' ' || msg[0] == ':') msg++;
725         len = strlen(msg);
726         while (len && msg[len-1] == '\n') len--;
727         bb_error_msg("%.*s", len, msg);
728 }
729
730 static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts)
731 {
732         CLIENT *mclient;
733         char *hostname;
734         char *pathname;
735         char *mounthost;
736         struct nfs_mount_data data;
737         char *opt;
738         struct hostent *hp;
739         struct sockaddr_in server_addr;
740         struct sockaddr_in mount_server_addr;
741         int msock, fsock;
742         union {
743                 struct fhstatus nfsv2;
744                 struct mountres3 nfsv3;
745         } status;
746         int daemonized;
747         char *s;
748         int port;
749         int mountport;
750         int proto;
751         int bg;
752         int soft;
753         int intr;
754         int posix;
755         int nocto;
756         int noac;
757         int nolock;
758         int retry;
759         int tcp;
760         int mountprog;
761         int mountvers;
762         int nfsprog;
763         int nfsvers;
764         int retval;
765
766         find_kernel_nfs_mount_version();
767
768         daemonized = 0;
769         mounthost = NULL;
770         retval = ETIMEDOUT;
771         msock = fsock = -1;
772         mclient = NULL;
773
774         /* NB: hostname, mounthost, filteropts must be free()d prior to return */
775
776         filteropts = xstrdup(filteropts); /* going to trash it later... */
777
778         hostname = xstrdup(mp->mnt_fsname);
779         /* mount_main() guarantees that ':' is there */
780         s = strchr(hostname, ':');
781         pathname = s + 1;
782         *s = '\0';
783         /* Ignore all but first hostname in replicated mounts
784            until they can be fully supported. (mack@sgi.com) */
785         s = strchr(hostname, ',');
786         if (s) {
787                 *s = '\0';
788                 bb_error_msg("warning: multiple hostnames not supported");
789         }
790
791         server_addr.sin_family = AF_INET;
792         if (!inet_aton(hostname, &server_addr.sin_addr)) {
793                 hp = gethostbyname(hostname);
794                 if (hp == NULL) {
795                         bb_herror_msg("%s", hostname);
796                         goto fail;
797                 }
798                 if (hp->h_length > sizeof(struct in_addr)) {
799                         bb_error_msg("got bad hp->h_length");
800                         hp->h_length = sizeof(struct in_addr);
801                 }
802                 memcpy(&server_addr.sin_addr,
803                                 hp->h_addr, hp->h_length);
804         }
805
806         memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
807
808         /* add IP address to mtab options for use when unmounting */
809
810         if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
811                 mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
812         } else {
813                 char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
814                                         mp->mnt_opts[0] ? "," : "",
815                                         inet_ntoa(server_addr.sin_addr));
816                 free(mp->mnt_opts);
817                 mp->mnt_opts = tmp;
818         }
819
820         /* Set default options.
821          * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
822          * let the kernel decide.
823          * timeo is filled in after we know whether it'll be TCP or UDP. */
824         memset(&data, 0, sizeof(data));
825         data.retrans    = 3;
826         data.acregmin   = 3;
827         data.acregmax   = 60;
828         data.acdirmin   = 30;
829         data.acdirmax   = 60;
830         data.namlen     = NAME_MAX;
831
832         bg = 0;
833         soft = 0;
834         intr = 0;
835         posix = 0;
836         nocto = 0;
837         nolock = 0;
838         noac = 0;
839         retry = 10000;          /* 10000 minutes ~ 1 week */
840         tcp = 0;
841
842         mountprog = MOUNTPROG;
843         mountvers = 0;
844         port = 0;
845         mountport = 0;
846         nfsprog = 100003;
847         nfsvers = 0;
848
849         /* parse options */
850
851         for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
852                 char *opteq = strchr(opt, '=');
853                 if (opteq) {
854                         int val = atoi(opteq + 1);
855                         *opteq = '\0';
856                         if (!strcmp(opt, "rsize"))
857                                 data.rsize = val;
858                         else if (!strcmp(opt, "wsize"))
859                                 data.wsize = val;
860                         else if (!strcmp(opt, "timeo"))
861                                 data.timeo = val;
862                         else if (!strcmp(opt, "retrans"))
863                                 data.retrans = val;
864                         else if (!strcmp(opt, "acregmin"))
865                                 data.acregmin = val;
866                         else if (!strcmp(opt, "acregmax"))
867                                 data.acregmax = val;
868                         else if (!strcmp(opt, "acdirmin"))
869                                 data.acdirmin = val;
870                         else if (!strcmp(opt, "acdirmax"))
871                                 data.acdirmax = val;
872                         else if (!strcmp(opt, "actimeo")) {
873                                 data.acregmin = val;
874                                 data.acregmax = val;
875                                 data.acdirmin = val;
876                                 data.acdirmax = val;
877                         }
878                         else if (!strcmp(opt, "retry"))
879                                 retry = val;
880                         else if (!strcmp(opt, "port"))
881                                 port = val;
882                         else if (!strcmp(opt, "mountport"))
883                                 mountport = val;
884                         else if (!strcmp(opt, "mounthost"))
885                                 mounthost = xstrndup(opteq+1,
886                                                   strcspn(opteq+1," \t\n\r,"));
887                         else if (!strcmp(opt, "mountprog"))
888                                 mountprog = val;
889                         else if (!strcmp(opt, "mountvers"))
890                                 mountvers = val;
891                         else if (!strcmp(opt, "nfsprog"))
892                                 nfsprog = val;
893                         else if (!strcmp(opt, "nfsvers") ||
894                                  !strcmp(opt, "vers"))
895                                 nfsvers = val;
896                         else if (!strcmp(opt, "proto")) {
897                                 if (!strncmp(opteq+1, "tcp", 3))
898                                         tcp = 1;
899                                 else if (!strncmp(opteq+1, "udp", 3))
900                                         tcp = 0;
901                                 else
902                                         bb_error_msg("warning: unrecognized proto= option");
903                         } else if (!strcmp(opt, "namlen")) {
904                                 if (nfs_mount_version >= 2)
905                                         data.namlen = val;
906                                 else
907                                         bb_error_msg("warning: option namlen is not supported\n");
908                         } else if (!strcmp(opt, "addr"))
909                                 /* ignore */;
910                         else {
911                                 bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
912                                 goto fail;
913                         }
914                 }
915                 else {
916                         int val = 1;
917                         if (!strncmp(opt, "no", 2)) {
918                                 val = 0;
919                                 opt += 2;
920                         }
921                         if (!strcmp(opt, "bg"))
922                                 bg = val;
923                         else if (!strcmp(opt, "fg"))
924                                 bg = !val;
925                         else if (!strcmp(opt, "soft"))
926                                 soft = val;
927                         else if (!strcmp(opt, "hard"))
928                                 soft = !val;
929                         else if (!strcmp(opt, "intr"))
930                                 intr = val;
931                         else if (!strcmp(opt, "posix"))
932                                 posix = val;
933                         else if (!strcmp(opt, "cto"))
934                                 nocto = !val;
935                         else if (!strcmp(opt, "ac"))
936                                 noac = !val;
937                         else if (!strcmp(opt, "tcp"))
938                                 tcp = val;
939                         else if (!strcmp(opt, "udp"))
940                                 tcp = !val;
941                         else if (!strcmp(opt, "lock")) {
942                                 if (nfs_mount_version >= 3)
943                                         nolock = !val;
944                                 else
945                                         bb_error_msg("warning: option nolock is not supported");
946                         } else {
947                                 bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
948                                 goto fail;
949                         }
950                 }
951         }
952         proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
953
954         data.flags = (soft ? NFS_MOUNT_SOFT : 0)
955                 | (intr ? NFS_MOUNT_INTR : 0)
956                 | (posix ? NFS_MOUNT_POSIX : 0)
957                 | (nocto ? NFS_MOUNT_NOCTO : 0)
958                 | (noac ? NFS_MOUNT_NOAC : 0);
959         if (nfs_mount_version >= 2)
960                 data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
961         if (nfs_mount_version >= 3)
962                 data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
963         if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
964                 bb_error_msg("NFSv%d not supported", nfsvers);
965                 goto fail;
966         }
967         if (nfsvers && !mountvers)
968                 mountvers = (nfsvers < 3) ? 1 : nfsvers;
969         if (nfsvers && nfsvers < mountvers) {
970                 mountvers = nfsvers;
971         }
972
973         /* Adjust options if none specified */
974         if (!data.timeo)
975                 data.timeo = tcp ? 70 : 7;
976
977         data.version = nfs_mount_version;
978
979         if (vfsflags & MS_REMOUNT)
980                 goto do_mount;
981
982         /*
983          * If the previous mount operation on the same host was
984          * backgrounded, and the "bg" for this mount is also set,
985          * give up immediately, to avoid the initial timeout.
986          */
987         if (bg && we_saw_this_host_before(hostname)) {
988                 daemonized = daemonize(); /* parent or error */
989                 if (daemonized <= 0) { /* parent or error */
990                         retval = -daemonized;
991                         goto ret;
992                 }
993         }
994
995         /* create mount daemon client */
996         /* See if the nfs host = mount host. */
997         if (mounthost) {
998                 if (mounthost[0] >= '0' && mounthost[0] <= '9') {
999                         mount_server_addr.sin_family = AF_INET;
1000                         mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
1001                 } else {
1002                         hp = gethostbyname(mounthost);
1003                         if (hp == NULL) {
1004                                 bb_herror_msg("%s", mounthost);
1005                                 goto fail;
1006                         } else {
1007                                 if (hp->h_length > sizeof(struct in_addr)) {
1008                                         bb_error_msg("got bad hp->h_length?");
1009                                         hp->h_length = sizeof(struct in_addr);
1010                                 }
1011                                 mount_server_addr.sin_family = AF_INET;
1012                                 memcpy(&mount_server_addr.sin_addr,
1013                                                 hp->h_addr, hp->h_length);
1014                         }
1015                 }
1016         }
1017
1018         /*
1019          * The following loop implements the mount retries. When the mount
1020          * times out, and the "bg" option is set, we background ourself
1021          * and continue trying.
1022          *
1023          * The case where the mount point is not present and the "bg"
1024          * option is set, is treated as a timeout. This is done to
1025          * support nested mounts.
1026          *
1027          * The "retry" count specified by the user is the number of
1028          * minutes to retry before giving up.
1029          */
1030         {
1031                 struct timeval total_timeout;
1032                 struct timeval retry_timeout;
1033                 struct pmap* pm_mnt;
1034                 time_t t;
1035                 time_t prevt;
1036                 time_t timeout;
1037
1038                 retry_timeout.tv_sec = 3;
1039                 retry_timeout.tv_usec = 0;
1040                 total_timeout.tv_sec = 20;
1041                 total_timeout.tv_usec = 0;
1042                 timeout = time(NULL) + 60 * retry;
1043                 prevt = 0;
1044                 t = 30;
1045 retry:
1046                 /* be careful not to use too many CPU cycles */
1047                 if (t - prevt < 30)
1048                         sleep(30);
1049
1050                 pm_mnt = get_mountport(&mount_server_addr,
1051                                 mountprog,
1052                                 mountvers,
1053                                 proto,
1054                                 mountport);
1055                 nfsvers = (pm_mnt->pm_vers < 2) ? 2 : pm_mnt->pm_vers;
1056
1057                 /* contact the mount daemon via TCP */
1058                 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1059                 msock = RPC_ANYSOCK;
1060
1061                 switch (pm_mnt->pm_prot) {
1062                 case IPPROTO_UDP:
1063                         mclient = clntudp_create(&mount_server_addr,
1064                                                  pm_mnt->pm_prog,
1065                                                  pm_mnt->pm_vers,
1066                                                  retry_timeout,
1067                                                  &msock);
1068                         if (mclient)
1069                                 break;
1070                         mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1071                         msock = RPC_ANYSOCK;
1072                 case IPPROTO_TCP:
1073                         mclient = clnttcp_create(&mount_server_addr,
1074                                                  pm_mnt->pm_prog,
1075                                                  pm_mnt->pm_vers,
1076                                                  &msock, 0, 0);
1077                         break;
1078                 default:
1079                         mclient = 0;
1080                 }
1081                 if (!mclient) {
1082                         if (!daemonized && prevt == 0)
1083                                 error_msg_rpc(clnt_spcreateerror(" "));
1084                 } else {
1085                         enum clnt_stat clnt_stat;
1086                         /* try to mount hostname:pathname */
1087                         mclient->cl_auth = authunix_create_default();
1088
1089                         /* make pointers in xdr_mountres3 NULL so
1090                          * that xdr_array allocates memory for us
1091                          */
1092                         memset(&status, 0, sizeof(status));
1093
1094                         if (pm_mnt->pm_vers == 3)
1095                                 clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
1096                                               (xdrproc_t) xdr_dirpath,
1097                                               (caddr_t) &pathname,
1098                                               (xdrproc_t) xdr_mountres3,
1099                                               (caddr_t) &status,
1100                                               total_timeout);
1101                         else
1102                                 clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
1103                                               (xdrproc_t) xdr_dirpath,
1104                                               (caddr_t) &pathname,
1105                                               (xdrproc_t) xdr_fhstatus,
1106                                               (caddr_t) &status,
1107                                               total_timeout);
1108
1109                         if (clnt_stat == RPC_SUCCESS)
1110                                 goto prepare_kernel_data; /* we're done */
1111                         if (errno != ECONNREFUSED) {
1112                                 error_msg_rpc(clnt_sperror(mclient, " "));
1113                                 goto fail;      /* don't retry */
1114                         }
1115                         /* Connection refused */
1116                         if (!daemonized && prevt == 0) /* print just once */
1117                                 error_msg_rpc(clnt_sperror(mclient, " "));
1118                         auth_destroy(mclient->cl_auth);
1119                         clnt_destroy(mclient);
1120                         mclient = 0;
1121                         close(msock);
1122                 }
1123
1124                 /* Timeout. We are going to retry... maybe */
1125
1126                 if (!bg)
1127                         goto fail;
1128                 if (!daemonized) {
1129                         daemonized = daemonize();
1130                         if (daemonized <= 0) { /* parent or error */
1131                                 retval = -daemonized;
1132                                 goto ret;
1133                         }
1134                 }
1135                 prevt = t;
1136                 t = time(NULL);
1137                 if (t >= timeout)
1138                         /* TODO error message */
1139                         goto fail;
1140
1141                 goto retry;
1142         }
1143
1144 prepare_kernel_data:
1145
1146         if (nfsvers == 2) {
1147                 if (status.nfsv2.fhs_status != 0) {
1148                         bb_error_msg("%s:%s failed, reason given by server: %s",
1149                                 hostname, pathname,
1150                                 nfs_strerror(status.nfsv2.fhs_status));
1151                         goto fail;
1152                 }
1153                 memcpy(data.root.data,
1154                                 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1155                                 NFS_FHSIZE);
1156                 data.root.size = NFS_FHSIZE;
1157                 memcpy(data.old_root.data,
1158                                 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1159                                 NFS_FHSIZE);
1160         } else {
1161                 fhandle3 *my_fhandle;
1162                 if (status.nfsv3.fhs_status != 0) {
1163                         bb_error_msg("%s:%s failed, reason given by server: %s",
1164                                 hostname, pathname,
1165                                 nfs_strerror(status.nfsv3.fhs_status));
1166                         goto fail;
1167                 }
1168                 my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
1169                 memset(data.old_root.data, 0, NFS_FHSIZE);
1170                 memset(&data.root, 0, sizeof(data.root));
1171                 data.root.size = my_fhandle->fhandle3_len;
1172                 memcpy(data.root.data,
1173                                 (char *) my_fhandle->fhandle3_val,
1174                                 my_fhandle->fhandle3_len);
1175
1176                 data.flags |= NFS_MOUNT_VER3;
1177         }
1178
1179         /* create nfs socket for kernel */
1180
1181         if (tcp) {
1182                 if (nfs_mount_version < 3) {
1183                         bb_error_msg("NFS over TCP is not supported");
1184                         goto fail;
1185                 }
1186                 fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1187         } else
1188                 fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1189         if (fsock < 0) {
1190                 bb_perror_msg("nfs socket");
1191                 goto fail;
1192         }
1193         if (bindresvport(fsock, 0) < 0) {
1194                 bb_perror_msg("nfs bindresvport");
1195                 goto fail;
1196         }
1197         if (port == 0) {
1198                 server_addr.sin_port = PMAPPORT;
1199                 port = pmap_getport(&server_addr, nfsprog, nfsvers,
1200                                         tcp ? IPPROTO_TCP : IPPROTO_UDP);
1201                 if (port == 0)
1202                         port = NFS_PORT;
1203         }
1204         server_addr.sin_port = htons(port);
1205
1206         /* prepare data structure for kernel */
1207
1208         data.fd = fsock;
1209         memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
1210         strncpy(data.hostname, hostname, sizeof(data.hostname));
1211
1212         /* clean up */
1213
1214         auth_destroy(mclient->cl_auth);
1215         clnt_destroy(mclient);
1216         close(msock);
1217
1218         if (bg) {
1219                 /* We must wait until mount directory is available */
1220                 struct stat statbuf;
1221                 int delay = 1;
1222                 while (stat(mp->mnt_dir, &statbuf) == -1) {
1223                         if (!daemonized) {
1224                                 daemonized = daemonize();
1225                                 if (daemonized <= 0) { /* parent or error */
1226                                         retval = -daemonized;
1227                                         goto ret;
1228                                 }
1229                         }
1230                         sleep(delay);   /* 1, 2, 4, 8, 16, 30, ... */
1231                         delay *= 2;
1232                         if (delay > 30)
1233                                 delay = 30;
1234                 }
1235         }
1236
1237 do_mount: /* perform actual mount */
1238
1239         mp->mnt_type = "nfs";
1240         retval = mount_it_now(mp, vfsflags, (char*)&data);
1241         goto ret;
1242
1243 fail:   /* abort */
1244
1245         if (msock != -1) {
1246                 if (mclient) {
1247                         auth_destroy(mclient->cl_auth);
1248                         clnt_destroy(mclient);
1249                 }
1250                 close(msock);
1251         }
1252         if (fsock != -1)
1253                 close(fsock);
1254
1255 ret:
1256         free(hostname);
1257         free(mounthost);
1258         free(filteropts);
1259         return retval;
1260 }
1261
1262 #else /* !ENABLE_FEATURE_MOUNT_NFS */
1263
1264 /* Never called. Call should be optimized out. */
1265 int nfsmount(struct mntent *mp, int vfsflags, char *filteropts);
1266
1267 #endif /* !ENABLE_FEATURE_MOUNT_NFS */
1268
1269 // Mount one directory.  Handles CIFS, NFS, loopback, autobind, and filesystem
1270 // type detection.  Returns 0 for success, nonzero for failure.
1271
1272 static int singlemount(struct mntent *mp, int ignore_busy)
1273 {
1274         int rc = -1, vfsflags;
1275         char *loopFile = 0, *filteropts = 0;
1276         llist_t *fl = 0;
1277         struct stat st;
1278
1279         vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
1280
1281         // Treat fstype "auto" as unspecified.
1282
1283         if (mp->mnt_type && !strcmp(mp->mnt_type,"auto")) mp->mnt_type = 0;
1284
1285         // Might this be an CIFS filesystem?
1286
1287         if (ENABLE_FEATURE_MOUNT_CIFS &&
1288                 (!mp->mnt_type || !strcmp(mp->mnt_type,"cifs")) &&
1289                 (mp->mnt_fsname[0]==mp->mnt_fsname[1] && (mp->mnt_fsname[0]=='/' || mp->mnt_fsname[0]=='\\')))
1290         {
1291                 struct hostent *he;
1292                 char ip[32], *s;
1293
1294                 rc = 1;
1295                 // Replace '/' with '\' and verify that unc points to "//server/share".
1296
1297                 for (s = mp->mnt_fsname; *s; ++s)
1298                         if (*s == '/') *s = '\\';
1299
1300                 // get server IP
1301
1302                 s = strrchr(mp->mnt_fsname, '\\');
1303                 if (s == mp->mnt_fsname+1) goto report_error;
1304                 *s = 0;
1305                 he = gethostbyname(mp->mnt_fsname+2);
1306                 *s = '\\';
1307                 if (!he) goto report_error;
1308
1309                 // Insert ip=... option into string flags.  (NOTE: Add IPv6 support.)
1310
1311                 sprintf(ip, "ip=%d.%d.%d.%d", he->h_addr[0], he->h_addr[1],
1312                                 he->h_addr[2], he->h_addr[3]);
1313                 parse_mount_options(ip, &filteropts);
1314
1315                 // compose new unc '\\server-ip\share'
1316
1317                 s = xasprintf("\\\\%s%s",ip+3,strchr(mp->mnt_fsname+2,'\\'));
1318                 if (ENABLE_FEATURE_CLEAN_UP) free(mp->mnt_fsname);
1319                 mp->mnt_fsname = s;
1320
1321                 // lock is required
1322                 vfsflags |= MS_MANDLOCK;
1323
1324                 mp->mnt_type = "cifs";
1325                 rc = mount_it_now(mp, vfsflags, filteropts);
1326                 goto report_error;
1327         }
1328
1329         // Might this be an NFS filesystem?
1330
1331         if (ENABLE_FEATURE_MOUNT_NFS &&
1332                 (!mp->mnt_type || !strcmp(mp->mnt_type,"nfs")) &&
1333                 strchr(mp->mnt_fsname, ':') != NULL)
1334         {
1335                 rc = nfsmount(mp, vfsflags, filteropts);
1336                 goto report_error;
1337         }
1338
1339         // Look at the file.  (Not found isn't a failure for remount, or for
1340         // a synthetic filesystem like proc or sysfs.)
1341
1342         if (!lstat(mp->mnt_fsname, &st) && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1343         {
1344                 // Do we need to allocate a loopback device for it?
1345
1346                 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
1347                         loopFile = bb_simplify_path(mp->mnt_fsname);
1348                         mp->mnt_fsname = 0;
1349                         switch (set_loop(&(mp->mnt_fsname), loopFile, 0)) {
1350                                 case 0:
1351                                 case 1:
1352                                         break;
1353                                 default:
1354                                         bb_error_msg( errno == EPERM || errno == EACCES
1355                                                 ? bb_msg_perm_denied_are_you_root
1356                                                 : "cannot setup loop device");
1357                                         return errno;
1358                         }
1359
1360                 // Autodetect bind mounts
1361
1362                 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
1363                         vfsflags |= MS_BIND;
1364         }
1365
1366         /* If we know the fstype (or don't need to), jump straight
1367          * to the actual mount. */
1368
1369         if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1370                 rc = mount_it_now(mp, vfsflags, filteropts);
1371
1372         // Loop through filesystem types until mount succeeds or we run out
1373
1374         else {
1375
1376                 /* Initialize list of block backed filesystems.  This has to be
1377                  * done here so that during "mount -a", mounts after /proc shows up
1378                  * can autodetect. */
1379
1380                 if (!fslist) {
1381                         fslist = get_block_backed_filesystems();
1382                         if (ENABLE_FEATURE_CLEAN_UP && fslist)
1383                                 atexit(delete_block_backed_filesystems);
1384                 }
1385
1386                 for (fl = fslist; fl; fl = fl->link) {
1387                         mp->mnt_type = fl->data;
1388
1389                         rc = mount_it_now(mp,vfsflags, filteropts);
1390                         if (!rc) break;
1391
1392                         mp->mnt_type = 0;
1393                 }
1394         }
1395
1396         // If mount failed, clean up loop file (if any).
1397
1398         if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
1399                 del_loop(mp->mnt_fsname);
1400                 if (ENABLE_FEATURE_CLEAN_UP) {
1401                         free(loopFile);
1402                         free(mp->mnt_fsname);
1403                 }
1404         }
1405
1406 report_error:
1407         if (ENABLE_FEATURE_CLEAN_UP) free(filteropts);
1408
1409         if (rc && errno == EBUSY && ignore_busy) rc = 0;
1410         if (rc < 0)
1411                 /* perror here sometimes says "mounting ... on ... failed: Success" */
1412                 bb_error_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
1413
1414         return rc;
1415 }
1416
1417 // Parse options, if necessary parse fstab/mtab, and call singlemount for
1418 // each directory to be mounted.
1419
1420 int mount_main(int argc, char **argv)
1421 {
1422         char *cmdopts = xstrdup(""), *fstabname, *fstype=0, *storage_path=0;
1423         FILE *fstab;
1424         int i, opt, all = FALSE, rc = 0;
1425         struct mntent mtpair[2], *mtcur = mtpair;
1426
1427         /* parse long options, like --bind and --move.  Note that -o option
1428          * and --option are synonymous.  Yes, this means --remount,rw works. */
1429
1430         for (i = opt = 0; i < argc; i++) {
1431                 if (argv[i][0] == '-' && argv[i][1] == '-') {
1432                         append_mount_options(&cmdopts,argv[i]+2);
1433                 } else argv[opt++] = argv[i];
1434         }
1435         argc = opt;
1436
1437         // Parse remaining options
1438
1439         while ((opt = getopt(argc, argv, "o:t:rwavnf")) > 0) {
1440                 switch (opt) {
1441                         case 'o':
1442                                 append_mount_options(&cmdopts, optarg);
1443                                 break;
1444                         case 't':
1445                                 fstype = optarg;
1446                                 break;
1447                         case 'r':
1448                                 append_mount_options(&cmdopts, "ro");
1449                                 break;
1450                         case 'w':
1451                                 append_mount_options(&cmdopts, "rw");
1452                                 break;
1453                         case 'a':
1454                                 all = TRUE;
1455                                 break;
1456                         case 'n':
1457                                 USE_FEATURE_MTAB_SUPPORT(useMtab = FALSE;)
1458                                 break;
1459                         case 'f':
1460                                 USE_FEATURE_MTAB_SUPPORT(fakeIt = FALSE;)
1461                                 break;
1462                         case 'v':
1463                                 break;          // ignore -v
1464                         default:
1465                                 bb_show_usage();
1466                 }
1467         }
1468
1469         // Three or more non-option arguments?  Die with a usage message.
1470
1471         if (optind-argc>2) bb_show_usage();
1472
1473         // If we have no arguments, show currently mounted filesystems
1474
1475         if (optind == argc) {
1476                 if (!all) {
1477                         FILE *mountTable = setmntent(bb_path_mtab_file, "r");
1478
1479                         if (!mountTable) bb_error_msg_and_die("no %s",bb_path_mtab_file);
1480
1481                         while (getmntent_r(mountTable,mtpair,bb_common_bufsiz1,
1482                                                                 sizeof(bb_common_bufsiz1)))
1483                         {
1484                                 // Don't show rootfs.
1485                                 if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
1486
1487                                 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
1488                                         printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
1489                                                         mtpair->mnt_dir, mtpair->mnt_type,
1490                                                         mtpair->mnt_opts);
1491                         }
1492                         if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
1493                         return EXIT_SUCCESS;
1494                 }
1495         } else storage_path = bb_simplify_path(argv[optind]);
1496
1497         // When we have two arguments, the second is the directory and we can
1498         // skip looking at fstab entirely.  We can always abspath() the directory
1499         // argument when we get it.
1500
1501         if (optind+2 == argc) {
1502                 mtpair->mnt_fsname = argv[optind];
1503                 mtpair->mnt_dir = argv[optind+1];
1504                 mtpair->mnt_type = fstype;
1505                 mtpair->mnt_opts = cmdopts;
1506                 rc = singlemount(mtpair, 0);
1507                 goto clean_up;
1508         }
1509
1510         // If we have a shared subtree flag, don't worry about fstab or mtab.
1511         i = parse_mount_options(cmdopts,0);
1512         if (ENABLE_FEATURE_MOUNT_FLAGS &&
1513                         (i & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE )))
1514         {
1515                 rc = mount("", argv[optind], "", i, "");
1516                 if (rc) bb_perror_msg_and_die("%s", argv[optind]);
1517                 goto clean_up;
1518         }
1519         
1520         // Open either fstab or mtab
1521
1522         if (parse_mount_options(cmdopts,0) & MS_REMOUNT)
1523                 fstabname = bb_path_mtab_file;
1524         else fstabname="/etc/fstab";
1525
1526         fstab = setmntent(fstabname,"r");
1527         if (!fstab)
1528                 bb_perror_msg_and_die("cannot read %s",fstabname);
1529
1530         // Loop through entries until we find what we're looking for.
1531
1532         memset(mtpair,0,sizeof(mtpair));
1533         for (;;) {
1534                 struct mntent *mtnext = (mtcur==mtpair ? mtpair+1 : mtpair);
1535
1536                 // Get next fstab entry
1537
1538                 if (!getmntent_r(fstab, mtcur, bb_common_bufsiz1
1539                                         + (mtcur==mtpair ? sizeof(bb_common_bufsiz1)/2 : 0),
1540                                 sizeof(bb_common_bufsiz1)/2))
1541                 {
1542                         // Were we looking for something specific?
1543
1544                         if (optind != argc) {
1545
1546                                 // If we didn't find anything, complain.
1547
1548                                 if (!mtnext->mnt_fsname)
1549                                         bb_error_msg_and_die("can't find %s in %s",
1550                                                 argv[optind], fstabname);
1551
1552                                 // Mount the last thing we found.
1553
1554                                 mtcur = mtnext;
1555                                 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1556                                 append_mount_options(&(mtcur->mnt_opts),cmdopts);
1557                                 rc = singlemount(mtcur, 0);
1558                                 free(mtcur->mnt_opts);
1559                         }
1560                         goto clean_up;
1561                 }
1562
1563                 /* If we're trying to mount something specific and this isn't it,
1564                  * skip it.  Note we must match both the exact text in fstab (ala
1565                  * "proc") or a full path from root */
1566
1567                 if (optind != argc) {
1568
1569                         // Is this what we're looking for?
1570
1571                         if (strcmp(argv[optind],mtcur->mnt_fsname) &&
1572                            strcmp(storage_path,mtcur->mnt_fsname) &&
1573                            strcmp(argv[optind],mtcur->mnt_dir) &&
1574                            strcmp(storage_path,mtcur->mnt_dir)) continue;
1575
1576                         // Remember this entry.  Something later may have overmounted
1577                         // it, and we want the _last_ match.
1578
1579                         mtcur = mtnext;
1580
1581                 // If we're mounting all.
1582
1583                 } else {
1584
1585                         // Do we need to match a filesystem type?
1586                         if (fstype && strcmp(mtcur->mnt_type,fstype)) continue;
1587
1588                         // Skip noauto and swap anyway.
1589
1590                         if (parse_mount_options(mtcur->mnt_opts,0)
1591                                 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
1592
1593                         // Mount this thing.
1594
1595                         if (singlemount(mtcur, 1)) {
1596                                 /* Count number of failed mounts */
1597                                 rc++;
1598                         }
1599                 }
1600         }
1601         if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
1602
1603 clean_up:
1604
1605         if (ENABLE_FEATURE_CLEAN_UP) {
1606                 free(storage_path);
1607                 free(cmdopts);
1608         }
1609
1610         return rc;
1611 }