1 /* vi: set sw=4 ts=4: */
3 * Mini mount implementation for busybox
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>
9 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 /* Design notes: There is no spec for mount. Remind me to write one.
14 mount_main() calls singlemount() which calls mount_it_now().
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.
24 /* Needed for nfs support only... */
26 #include <sys/utsname.h>
30 #include <rpc/pmap_prot.h>
31 #include <rpc/pmap_clnt.h>
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)
40 /* *** XXX FIXME WARNING: This hack is NOT thread safe. --Sampo */
41 struct mntent* ment = getmntent(stream);
42 memcpy(result, ment, sizeof(struct mntent));
48 // Not real flags, but we want to be able to check for this.
50 MOUNT_USERS = (1<<28)*ENABLE_DESKTOP,
51 MOUNT_NOAUTO = (1<<29),
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.
63 /* Standard mount options (from -o options or --options), with corresponding
69 } static mount_options[] = {
70 // MS_FLAGS set a bit. ~MS_FLAGS disable that bit. 0 flags are NOPs.
72 USE_FEATURE_MOUNT_LOOP(
76 USE_FEATURE_MOUNT_FSTAB(
78 /* {"quiet", 0}, - do not filter out, vfat wants to see it */
79 {"noauto", MOUNT_NOAUTO},
81 USE_DESKTOP({"user", MOUNT_USERS},)
82 USE_DESKTOP({"users", MOUNT_USERS},)
85 USE_FEATURE_MOUNT_FLAGS(
87 {"nosuid", MS_NOSUID},
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},
105 {"shared", MS_SHARED},
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},
115 // Always understood.
117 {"ro", MS_RDONLY}, // vfs flag
118 {"rw", ~MS_RDONLY}, // vfs flag
119 {"remount", MS_REMOUNT}, // action flag
122 #define VECTOR_SIZE(v) (sizeof(v) / sizeof((v)[0]))
124 /* Append mount options to string */
125 static void append_mount_options(char **oldopts, char *newopts)
127 if (*oldopts && **oldopts) {
128 /* do not insert options which are already there */
131 int len = strlen(newopts);
132 p = strchr(newopts, ',');
133 if (p) len = p - newopts;
136 if (!strncmp(p, newopts, len)
137 && (p[len]==',' || p[len]==0))
143 p = xasprintf("%s,%.*s", *oldopts, len, newopts);
148 while (newopts[0] == ',') newopts++;
151 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
152 *oldopts = xstrdup(newopts);
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)
160 int flags = MS_SILENT;
162 // Loop through options
165 char *comma = strchr(options, ',');
167 if (comma) *comma = 0;
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;
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);
184 // Comma separated if it's not the first one
185 if (i) (*unrecognized)[i++] = ',';
186 strcpy((*unrecognized)+i, options);
189 // Advance to next option, or finish
199 // Return a list of all block device backed filesystems
201 static llist_t *get_block_backed_filesystems(void)
203 static const char *const filesystems[] = {
213 for (i = 0; filesystems[i]; i++) {
214 f = fopen(filesystems[i], "r");
217 while ((buf = xmalloc_getline(f)) != 0) {
218 if (!strncmp(buf, "nodev", 5) && isspace(buf[5]))
220 fs = skip_whitespace(buf);
221 if (*fs=='#' || *fs=='*' || !*fs) continue;
223 llist_add_to_end(&list, xstrdup(fs));
226 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
234 #if ENABLE_FEATURE_CLEAN_UP
235 static void delete_block_backed_filesystems(void)
237 llist_free(fslist, free);
240 void delete_block_backed_filesystems(void);
243 #if ENABLE_FEATURE_MTAB_SUPPORT
244 static int useMtab = 1;
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)
257 if (fakeIt) goto mtab;
259 // Mount, with fallback to read-only if necessary.
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))
266 bb_error_msg("%s is write-protected, mounting read-only",
268 vfsflags |= MS_RDONLY;
271 // Abort entirely if permission denied.
273 if (rc && errno == EPERM)
274 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
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. */
279 if (ENABLE_FEATURE_MTAB_SUPPORT && useMtab && !rc && !(vfsflags & MS_REMOUNT)) {
281 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
285 bb_error_msg("no %s",bb_path_mtab_file);
289 // Add vfs string flags
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);
295 // Remove trailing / (if any) from directory we mounted on
297 i = strlen(mp->mnt_dir) - 1;
298 if (i > 0 && mp->mnt_dir[i] == '/') mp->mnt_dir[i] = 0;
300 // Convert to canonical pathnames as needed
302 mp->mnt_dir = bb_simplify_path(mp->mnt_dir);
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 = "bind";
308 mp->mnt_freq = mp->mnt_passno = 0;
312 addmntent(mountTable, mp);
313 endmntent(mountTable);
314 if (ENABLE_FEATURE_CLEAN_UP) {
323 #if ENABLE_FEATURE_MOUNT_NFS
327 * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
329 * Licensed under GPLv2, see file LICENSE in this tarball for details.
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.
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.
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.
340 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
341 * - added Native Language Support
343 * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
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."
353 #define MOUNTPORT 635
354 #define MNTPATHLEN 1024
355 #define MNTNAMLEN 255
359 typedef char fhandle[FHSIZE];
362 unsigned int fhandle3_len;
374 MNT3ERR_NAMETOOLONG = 63,
375 MNT3ERR_NOTSUPP = 10004,
376 MNT3ERR_SERVERFAULT = 10006,
378 typedef enum mountstat3 mountstat3;
381 unsigned int fhs_status;
386 typedef struct fhstatus fhstatus;
388 struct mountres3_ok {
391 unsigned int auth_flavours_len;
392 char *auth_flavours_val;
395 typedef struct mountres3_ok mountres3_ok;
398 mountstat3 fhs_status;
400 mountres3_ok mountinfo;
403 typedef struct mountres3 mountres3;
405 typedef char *dirpath;
409 typedef struct mountbody *mountlist;
413 dirpath ml_directory;
416 typedef struct mountbody mountbody;
418 typedef struct groupnode *groups;
424 typedef struct groupnode groupnode;
426 typedef struct exportnode *exports;
433 typedef struct exportnode exportnode;
446 typedef struct ppathcnf ppathcnf;
448 #define MOUNTPROG 100005
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
459 #define MOUNTVERS_POSIX 2
461 #define MOUNTPROC_PATHCONF 7
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
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.
487 * Moreover, the new kernel includes conflict with glibc includes
488 * so it is easiest to ignore the kernel altogether (at compile time).
496 unsigned char data[64];
499 struct nfs_mount_data {
502 struct nfs2_fh old_root; /* 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 */
515 unsigned int bsize; /* 3 */
516 struct nfs3_fh root; /* 4 */
519 /* bits in the flags field */
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 */
535 * We need to translate between nfs status return values and
536 * the local errno values which may not be the same.
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".
544 #define EDQUOT ENOSPC
547 // Convert each NFSERR_BLAH into EBLAH
549 static const struct {
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}
559 static char *nfs_strerror(int status)
562 static char buf[sizeof("unknown nfs status return value: ") + sizeof(int)*3];
564 for (i = 0; nfs_errtbl[i].stat != -1; i++) {
565 if (nfs_errtbl[i].stat == status)
566 return strerror(nfs_errtbl[i].errnum);
568 sprintf(buf, "unknown nfs status return value: %d", status);
572 static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
574 if (!xdr_opaque(xdrs, objp, FHSIZE))
579 static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
581 if (!xdr_u_int(xdrs, &objp->fhs_status))
583 switch (objp->fhs_status) {
585 if (!xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle))
594 static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
596 if (!xdr_string(xdrs, objp, MNTPATHLEN))
601 static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
603 if (!xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (unsigned int *) &objp->fhandle3_len, FHSIZE3))
608 static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
610 if (!xdr_fhandle3(xdrs, &objp->fhandle))
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))
618 static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
620 if (!xdr_enum(xdrs, (enum_t *) objp))
625 static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
627 if (!xdr_mountstat3(xdrs, &objp->fhs_status))
629 switch (objp->fhs_status) {
631 if (!xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo))
640 #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
643 * nfs_mount_version according to the sources seen at compile time.
645 static int nfs_mount_version;
646 static int kernel_version;
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.
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
660 find_kernel_nfs_mount_version(void)
665 nfs_mount_version = 4; /* default */
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 */
680 get_mountport(struct sockaddr_in *server_addr,
682 long unsigned version,
686 struct pmaplist *pmap;
687 static struct pmap p = {0, 0, 0, 0};
689 server_addr->sin_port = PMAPPORT;
690 pmap = pmap_getmaps(server_addr);
692 if (version > MAX_NFSPROT)
693 version = MAX_NFSPROT;
702 if (pmap->pml_map.pm_prog != prog)
704 if (!version && p.pm_vers > pmap->pml_map.pm_vers)
706 if (version > 2 && pmap->pml_map.pm_vers != version)
708 if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
710 if (pmap->pml_map.pm_vers > MAX_NFSPROT ||
711 (proto && p.pm_prot && pmap->pml_map.pm_prot != proto) ||
712 (port && pmap->pml_map.pm_port != port))
714 memcpy(&p, &pmap->pml_map, sizeof(p));
716 pmap = pmap->pml_next;
719 p.pm_vers = MOUNTVERS;
721 p.pm_port = MOUNTPORT;
723 p.pm_prot = IPPROTO_TCP;
727 static int daemonize(void)
731 if (pid < 0) /* error */
733 if (pid > 0) /* parent */
736 fd = xopen(bb_dev_null, O_RDWR);
740 while (fd > 2) close(fd--);
742 openlog(applet_name, LOG_PID, LOG_DAEMON);
743 logmode = LOGMODE_SYSLOG;
748 static inline int we_saw_this_host_before(const char *hostname)
753 /* RPC strerror analogs are terminally idiotic:
754 * *mandatory* prefix and \n at end.
755 * This hopefully helps. Usage:
756 * error_msg_rpc(clnt_*error*(" ")) */
757 static void error_msg_rpc(const char *msg)
760 while (msg[0] == ' ' || msg[0] == ':') msg++;
762 while (len && msg[len-1] == '\n') len--;
763 bb_error_msg("%.*s", len, msg);
766 // NB: mp->xxx fields may be trashed on exit
767 static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts)
773 struct nfs_mount_data data;
776 struct sockaddr_in server_addr;
777 struct sockaddr_in mount_server_addr;
780 struct fhstatus nfsv2;
781 struct mountres3 nfsv3;
803 find_kernel_nfs_mount_version();
811 /* NB: hostname, mounthost, filteropts must be free()d prior to return */
813 filteropts = xstrdup(filteropts); /* going to trash it later... */
815 hostname = xstrdup(mp->mnt_fsname);
816 /* mount_main() guarantees that ':' is there */
817 s = strchr(hostname, ':');
820 /* Ignore all but first hostname in replicated mounts
821 until they can be fully supported. (mack@sgi.com) */
822 s = strchr(hostname, ',');
825 bb_error_msg("warning: multiple hostnames not supported");
828 server_addr.sin_family = AF_INET;
829 if (!inet_aton(hostname, &server_addr.sin_addr)) {
830 hp = gethostbyname(hostname);
832 bb_herror_msg("%s", hostname);
835 if (hp->h_length > sizeof(struct in_addr)) {
836 bb_error_msg("got bad hp->h_length");
837 hp->h_length = sizeof(struct in_addr);
839 memcpy(&server_addr.sin_addr,
840 hp->h_addr, hp->h_length);
843 memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
845 /* add IP address to mtab options for use when unmounting */
847 if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
848 mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
850 char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
851 mp->mnt_opts[0] ? "," : "",
852 inet_ntoa(server_addr.sin_addr));
857 /* Set default options.
858 * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
859 * let the kernel decide.
860 * timeo is filled in after we know whether it'll be TCP or UDP. */
861 memset(&data, 0, sizeof(data));
867 data.namlen = NAME_MAX;
876 retry = 10000; /* 10000 minutes ~ 1 week */
879 mountprog = MOUNTPROG;
888 for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
889 char *opteq = strchr(opt, '=');
891 const char *const options[] = {
903 /* 11 */ "mountport",
904 /* 12 */ "mounthost",
905 /* 13 */ "mountprog",
906 /* 14 */ "mountvers",
915 int val = xatoi_u(opteq + 1);
917 switch (index_in_str_array(options, opt)) {
930 case 4: // "acregmin"
933 case 5: // "acregmax"
936 case 6: // "acdirmin"
939 case 7: // "acdirmax"
954 case 11: // "mountport"
957 case 12: // "mounthost"
958 mounthost = xstrndup(opteq+1,
959 strcspn(opteq+1," \t\n\r,"));
961 case 13: // "mountprog"
964 case 14: // "mountvers"
967 case 15: // "nfsprog"
970 case 16: // "nfsvers"
975 if (!strncmp(opteq+1, "tcp", 3))
977 else if (!strncmp(opteq+1, "udp", 3))
980 bb_error_msg("warning: unrecognized proto= option");
983 if (nfs_mount_version >= 2)
986 bb_error_msg("warning: option namlen is not supported\n");
988 case 20: // "addr" - ignore
991 bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
996 const char *const options[] = {
1011 if (!strncmp(opt, "no", 2)) {
1015 switch (index_in_str_array(options, opt)) {
1047 if (nfs_mount_version >= 3)
1050 bb_error_msg("warning: option nolock is not supported");
1053 bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
1058 proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
1060 data.flags = (soft ? NFS_MOUNT_SOFT : 0)
1061 | (intr ? NFS_MOUNT_INTR : 0)
1062 | (posix ? NFS_MOUNT_POSIX : 0)
1063 | (nocto ? NFS_MOUNT_NOCTO : 0)
1064 | (noac ? NFS_MOUNT_NOAC : 0);
1065 if (nfs_mount_version >= 2)
1066 data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
1067 if (nfs_mount_version >= 3)
1068 data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
1069 if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
1070 bb_error_msg("NFSv%d not supported", nfsvers);
1073 if (nfsvers && !mountvers)
1074 mountvers = (nfsvers < 3) ? 1 : nfsvers;
1075 if (nfsvers && nfsvers < mountvers) {
1076 mountvers = nfsvers;
1079 /* Adjust options if none specified */
1081 data.timeo = tcp ? 70 : 7;
1083 data.version = nfs_mount_version;
1085 if (vfsflags & MS_REMOUNT)
1089 * If the previous mount operation on the same host was
1090 * backgrounded, and the "bg" for this mount is also set,
1091 * give up immediately, to avoid the initial timeout.
1093 if (bg && we_saw_this_host_before(hostname)) {
1094 daemonized = daemonize(); /* parent or error */
1095 if (daemonized <= 0) { /* parent or error */
1096 retval = -daemonized;
1101 /* create mount daemon client */
1102 /* See if the nfs host = mount host. */
1104 if (mounthost[0] >= '0' && mounthost[0] <= '9') {
1105 mount_server_addr.sin_family = AF_INET;
1106 mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
1108 hp = gethostbyname(mounthost);
1110 bb_herror_msg("%s", mounthost);
1113 if (hp->h_length > sizeof(struct in_addr)) {
1114 bb_error_msg("got bad hp->h_length?");
1115 hp->h_length = sizeof(struct in_addr);
1117 mount_server_addr.sin_family = AF_INET;
1118 memcpy(&mount_server_addr.sin_addr,
1119 hp->h_addr, hp->h_length);
1125 * The following loop implements the mount retries. When the mount
1126 * times out, and the "bg" option is set, we background ourself
1127 * and continue trying.
1129 * The case where the mount point is not present and the "bg"
1130 * option is set, is treated as a timeout. This is done to
1131 * support nested mounts.
1133 * The "retry" count specified by the user is the number of
1134 * minutes to retry before giving up.
1137 struct timeval total_timeout;
1138 struct timeval retry_timeout;
1139 struct pmap* pm_mnt;
1144 retry_timeout.tv_sec = 3;
1145 retry_timeout.tv_usec = 0;
1146 total_timeout.tv_sec = 20;
1147 total_timeout.tv_usec = 0;
1148 timeout = time(NULL) + 60 * retry;
1152 /* be careful not to use too many CPU cycles */
1156 pm_mnt = get_mountport(&mount_server_addr,
1161 nfsvers = (pm_mnt->pm_vers < 2) ? 2 : pm_mnt->pm_vers;
1163 /* contact the mount daemon via TCP */
1164 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1165 msock = RPC_ANYSOCK;
1167 switch (pm_mnt->pm_prot) {
1169 mclient = clntudp_create(&mount_server_addr,
1176 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1177 msock = RPC_ANYSOCK;
1179 mclient = clnttcp_create(&mount_server_addr,
1188 if (!daemonized && prevt == 0)
1189 error_msg_rpc(clnt_spcreateerror(" "));
1191 enum clnt_stat clnt_stat;
1192 /* try to mount hostname:pathname */
1193 mclient->cl_auth = authunix_create_default();
1195 /* make pointers in xdr_mountres3 NULL so
1196 * that xdr_array allocates memory for us
1198 memset(&status, 0, sizeof(status));
1200 if (pm_mnt->pm_vers == 3)
1201 clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
1202 (xdrproc_t) xdr_dirpath,
1203 (caddr_t) &pathname,
1204 (xdrproc_t) xdr_mountres3,
1208 clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
1209 (xdrproc_t) xdr_dirpath,
1210 (caddr_t) &pathname,
1211 (xdrproc_t) xdr_fhstatus,
1215 if (clnt_stat == RPC_SUCCESS)
1216 goto prepare_kernel_data; /* we're done */
1217 if (errno != ECONNREFUSED) {
1218 error_msg_rpc(clnt_sperror(mclient, " "));
1219 goto fail; /* don't retry */
1221 /* Connection refused */
1222 if (!daemonized && prevt == 0) /* print just once */
1223 error_msg_rpc(clnt_sperror(mclient, " "));
1224 auth_destroy(mclient->cl_auth);
1225 clnt_destroy(mclient);
1230 /* Timeout. We are going to retry... maybe */
1235 daemonized = daemonize();
1236 if (daemonized <= 0) { /* parent or error */
1237 retval = -daemonized;
1244 /* TODO error message */
1250 prepare_kernel_data:
1253 if (status.nfsv2.fhs_status != 0) {
1254 bb_error_msg("%s:%s failed, reason given by server: %s",
1256 nfs_strerror(status.nfsv2.fhs_status));
1259 memcpy(data.root.data,
1260 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1262 data.root.size = NFS_FHSIZE;
1263 memcpy(data.old_root.data,
1264 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1267 fhandle3 *my_fhandle;
1268 if (status.nfsv3.fhs_status != 0) {
1269 bb_error_msg("%s:%s failed, reason given by server: %s",
1271 nfs_strerror(status.nfsv3.fhs_status));
1274 my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
1275 memset(data.old_root.data, 0, NFS_FHSIZE);
1276 memset(&data.root, 0, sizeof(data.root));
1277 data.root.size = my_fhandle->fhandle3_len;
1278 memcpy(data.root.data,
1279 (char *) my_fhandle->fhandle3_val,
1280 my_fhandle->fhandle3_len);
1282 data.flags |= NFS_MOUNT_VER3;
1285 /* create nfs socket for kernel */
1288 if (nfs_mount_version < 3) {
1289 bb_error_msg("NFS over TCP is not supported");
1292 fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1294 fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1296 bb_perror_msg("nfs socket");
1299 if (bindresvport(fsock, 0) < 0) {
1300 bb_perror_msg("nfs bindresvport");
1304 server_addr.sin_port = PMAPPORT;
1305 port = pmap_getport(&server_addr, nfsprog, nfsvers,
1306 tcp ? IPPROTO_TCP : IPPROTO_UDP);
1310 server_addr.sin_port = htons(port);
1312 /* prepare data structure for kernel */
1315 memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
1316 strncpy(data.hostname, hostname, sizeof(data.hostname));
1320 auth_destroy(mclient->cl_auth);
1321 clnt_destroy(mclient);
1325 /* We must wait until mount directory is available */
1326 struct stat statbuf;
1328 while (stat(mp->mnt_dir, &statbuf) == -1) {
1330 daemonized = daemonize();
1331 if (daemonized <= 0) { /* parent or error */
1332 retval = -daemonized;
1336 sleep(delay); /* 1, 2, 4, 8, 16, 30, ... */
1343 do_mount: /* perform actual mount */
1345 mp->mnt_type = "nfs";
1346 retval = mount_it_now(mp, vfsflags, (char*)&data);
1353 auth_destroy(mclient->cl_auth);
1354 clnt_destroy(mclient);
1368 #else /* !ENABLE_FEATURE_MOUNT_NFS */
1370 /* Never called. Call should be optimized out. */
1371 int nfsmount(struct mntent *mp, int vfsflags, char *filteropts);
1373 #endif /* !ENABLE_FEATURE_MOUNT_NFS */
1375 // Mount one directory. Handles CIFS, NFS, loopback, autobind, and filesystem
1376 // type detection. Returns 0 for success, nonzero for failure.
1377 // NB: mp->xxx fields may be trashed on exit
1378 static int singlemount(struct mntent *mp, int ignore_busy)
1380 int rc = -1, vfsflags;
1381 char *loopFile = 0, *filteropts = 0;
1385 vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
1387 // Treat fstype "auto" as unspecified.
1389 if (mp->mnt_type && !strcmp(mp->mnt_type,"auto")) mp->mnt_type = 0;
1391 // Might this be an CIFS filesystem?
1393 if (ENABLE_FEATURE_MOUNT_CIFS &&
1394 (!mp->mnt_type || !strcmp(mp->mnt_type,"cifs")) &&
1395 (mp->mnt_fsname[0]==mp->mnt_fsname[1] && (mp->mnt_fsname[0]=='/' || mp->mnt_fsname[0]=='\\')))
1401 // Replace '/' with '\' and verify that unc points to "//server/share".
1403 for (s = mp->mnt_fsname; *s; ++s)
1404 if (*s == '/') *s = '\\';
1408 s = strrchr(mp->mnt_fsname, '\\');
1409 if (s == mp->mnt_fsname+1) goto report_error;
1411 he = gethostbyname(mp->mnt_fsname+2);
1413 if (!he) goto report_error;
1415 // Insert ip=... option into string flags. (NOTE: Add IPv6 support.)
1417 sprintf(ip, "ip=%d.%d.%d.%d", he->h_addr[0], he->h_addr[1],
1418 he->h_addr[2], he->h_addr[3]);
1419 parse_mount_options(ip, &filteropts);
1421 // compose new unc '\\server-ip\share'
1423 mp->mnt_fsname = xasprintf("\\\\%s%s", ip+3,
1424 strchr(mp->mnt_fsname+2,'\\'));
1427 vfsflags |= MS_MANDLOCK;
1429 mp->mnt_type = "cifs";
1430 rc = mount_it_now(mp, vfsflags, filteropts);
1431 if (ENABLE_FEATURE_CLEAN_UP) free(mp->mnt_fsname);
1435 // Might this be an NFS filesystem?
1437 if (ENABLE_FEATURE_MOUNT_NFS &&
1438 (!mp->mnt_type || !strcmp(mp->mnt_type,"nfs")) &&
1439 strchr(mp->mnt_fsname, ':') != NULL)
1441 rc = nfsmount(mp, vfsflags, filteropts);
1445 // Look at the file. (Not found isn't a failure for remount, or for
1446 // a synthetic filesystem like proc or sysfs.)
1448 if (!lstat(mp->mnt_fsname, &st) && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1450 // Do we need to allocate a loopback device for it?
1452 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
1453 loopFile = bb_simplify_path(mp->mnt_fsname);
1455 switch (set_loop(&(mp->mnt_fsname), loopFile, 0)) {
1460 bb_error_msg( errno == EPERM || errno == EACCES
1461 ? bb_msg_perm_denied_are_you_root
1462 : "cannot setup loop device");
1466 // Autodetect bind mounts
1468 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
1469 vfsflags |= MS_BIND;
1472 /* If we know the fstype (or don't need to), jump straight
1473 * to the actual mount. */
1475 if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1476 rc = mount_it_now(mp, vfsflags, filteropts);
1478 // Loop through filesystem types until mount succeeds or we run out
1482 /* Initialize list of block backed filesystems. This has to be
1483 * done here so that during "mount -a", mounts after /proc shows up
1484 * can autodetect. */
1487 fslist = get_block_backed_filesystems();
1488 if (ENABLE_FEATURE_CLEAN_UP && fslist)
1489 atexit(delete_block_backed_filesystems);
1492 for (fl = fslist; fl; fl = fl->link) {
1493 mp->mnt_type = fl->data;
1494 rc = mount_it_now(mp, vfsflags, filteropts);
1499 // If mount failed, clean up loop file (if any).
1501 if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
1502 del_loop(mp->mnt_fsname);
1503 if (ENABLE_FEATURE_CLEAN_UP) {
1505 free(mp->mnt_fsname);
1510 if (ENABLE_FEATURE_CLEAN_UP) free(filteropts);
1512 if (rc && errno == EBUSY && ignore_busy) rc = 0;
1514 /* perror here sometimes says "mounting ... on ... failed: Success" */
1515 bb_error_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
1520 // Parse options, if necessary parse fstab/mtab, and call singlemount for
1521 // each directory to be mounted.
1523 const char must_be_root[] = "you must be root";
1525 int mount_main(int argc, char **argv)
1527 enum { OPT_ALL = 0x10 };
1529 char *cmdopts = xstrdup(""), *fstype=0, *storage_path=0;
1531 const char *fstabname;
1535 struct mntent mtpair[2], *mtcur = mtpair;
1536 SKIP_DESKTOP(const int nonroot = 0;)
1537 USE_DESKTOP( int nonroot = (getuid() != 0);)
1539 /* parse long options, like --bind and --move. Note that -o option
1540 * and --option are synonymous. Yes, this means --remount,rw works. */
1542 for (i = j = 0; i < argc; i++) {
1543 if (argv[i][0] == '-' && argv[i][1] == '-') {
1544 append_mount_options(&cmdopts, argv[i]+2);
1545 } else argv[j++] = argv[i];
1550 // Parse remaining options
1552 opt = getopt32(argc, argv, "o:t:rwanfvs", &opt_o, &fstype);
1553 if (opt & 0x1) append_mount_options(&cmdopts, opt_o); // -o
1554 //if (opt & 0x2) // -t
1555 if (opt & 0x4) append_mount_options(&cmdopts, "ro"); // -r
1556 if (opt & 0x8) append_mount_options(&cmdopts, "rw"); // -w
1557 //if (opt & 0x10) // -a
1558 if (opt & 0x20) USE_FEATURE_MTAB_SUPPORT(useMtab = 0); // -n
1559 if (opt & 0x40) USE_FEATURE_MTAB_SUPPORT(fakeIt = 1); // -f
1560 //if (opt & 0x80) // -v: verbose (ignore)
1561 //if (opt & 0x100) // -s: sloppy (ignore)
1565 // Three or more non-option arguments? Die with a usage message.
1567 if (argc > 2) bb_show_usage();
1569 // If we have no arguments, show currently mounted filesystems
1572 if (!(opt & OPT_ALL)) {
1573 FILE *mountTable = setmntent(bb_path_mtab_file, "r");
1575 if (!mountTable) bb_error_msg_and_die("no %s", bb_path_mtab_file);
1577 while (getmntent_r(mountTable, mtpair, bb_common_bufsiz1,
1578 sizeof(bb_common_bufsiz1)))
1580 // Don't show rootfs. FIXME: why??
1581 // util-linux 2.12a happily shows rootfs...
1582 //if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
1584 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
1585 printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
1586 mtpair->mnt_dir, mtpair->mnt_type,
1589 if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
1590 return EXIT_SUCCESS;
1592 } else storage_path = bb_simplify_path(argv[0]);
1594 // When we have two arguments, the second is the directory and we can
1595 // skip looking at fstab entirely. We can always abspath() the directory
1596 // argument when we get it.
1600 bb_error_msg_and_die(must_be_root);
1601 mtpair->mnt_fsname = argv[0];
1602 mtpair->mnt_dir = argv[1];
1603 mtpair->mnt_type = fstype;
1604 mtpair->mnt_opts = cmdopts;
1605 rc = singlemount(mtpair, 0);
1609 i = parse_mount_options(cmdopts, 0);
1610 if (nonroot && (i & ~MS_SILENT)) // Non-root users cannot specify flags
1611 bb_error_msg_and_die(must_be_root);
1613 // If we have a shared subtree flag, don't worry about fstab or mtab.
1615 if (ENABLE_FEATURE_MOUNT_FLAGS &&
1616 (i & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)))
1618 rc = mount("", argv[0], "", i, "");
1619 if (rc) bb_perror_msg_and_die("%s", argv[0]);
1623 // Open either fstab or mtab
1625 fstabname = "/etc/fstab";
1626 if (i & MS_REMOUNT) {
1627 fstabname = bb_path_mtab_file;
1629 fstab = setmntent(fstabname, "r");
1631 bb_perror_msg_and_die("cannot read %s", fstabname);
1633 // Loop through entries until we find what we're looking for.
1635 memset(mtpair, 0, sizeof(mtpair));
1637 struct mntent *mtnext = (mtcur==mtpair ? mtpair+1 : mtpair);
1639 // Get next fstab entry
1641 if (!getmntent_r(fstab, mtcur, bb_common_bufsiz1
1642 + (mtcur==mtpair ? sizeof(bb_common_bufsiz1)/2 : 0),
1643 sizeof(bb_common_bufsiz1)/2))
1645 // Were we looking for something specific?
1649 // If we didn't find anything, complain.
1651 if (!mtnext->mnt_fsname)
1652 bb_error_msg_and_die("can't find %s in %s",
1653 argv[0], fstabname);
1657 // fstab must have "users" or "user"
1658 if (!(parse_mount_options(mtcur->mnt_opts, 0) & MOUNT_USERS))
1659 bb_error_msg_and_die(must_be_root);
1662 // Mount the last thing we found.
1664 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1665 append_mount_options(&(mtcur->mnt_opts), cmdopts);
1666 rc = singlemount(mtcur, 0);
1667 free(mtcur->mnt_opts);
1672 /* If we're trying to mount something specific and this isn't it,
1673 * skip it. Note we must match both the exact text in fstab (ala
1674 * "proc") or a full path from root */
1678 // Is this what we're looking for?
1680 if (strcmp(argv[0], mtcur->mnt_fsname) &&
1681 strcmp(storage_path, mtcur->mnt_fsname) &&
1682 strcmp(argv[0], mtcur->mnt_dir) &&
1683 strcmp(storage_path, mtcur->mnt_dir)) continue;
1685 // Remember this entry. Something later may have overmounted
1686 // it, and we want the _last_ match.
1690 // If we're mounting all.
1693 // Do we need to match a filesystem type?
1694 // TODO: support "-t type1,type2"; "-t notype1,type2"
1696 if (fstype && strcmp(mtcur->mnt_type, fstype)) continue;
1698 // Skip noauto and swap anyway.
1700 if (parse_mount_options(mtcur->mnt_opts, 0)
1701 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
1703 // No, mount -a won't mount anything,
1704 // even user mounts, for mere humans.
1707 bb_error_msg_and_die(must_be_root);
1709 // Mount this thing.
1711 // NFS mounts want this to be xrealloc-able
1712 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1713 if (singlemount(mtcur, 1)) {
1714 /* Count number of failed mounts */
1717 free(mtcur->mnt_opts);
1720 if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
1724 if (ENABLE_FEATURE_CLEAN_UP) {