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