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