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.
25 /* Needed for nfs support only... */
26 #include <sys/utsname.h>
30 #include <rpc/pmap_prot.h>
31 #include <rpc/pmap_clnt.h>
34 #define MS_SILENT (1 << 15)
37 #if defined(__dietlibc__)
38 /* 16.12.2006, Sampo Kellomaki (sampo@iki.fi)
39 * dietlibc-0.30 does not have implementation of getmntent_r() */
40 static struct mntent *getmntent_r(FILE* stream, struct mntent* result, char* buffer, int bufsize)
42 struct mntent* ment = getmntent(stream);
43 memcpy(result, ment, sizeof(struct mntent));
48 #define getmntent_buf bb_common_bufsiz1
51 // Not real flags, but we want to be able to check for this.
53 MOUNT_USERS = (1<<28)*ENABLE_DESKTOP,
54 MOUNT_NOAUTO = (1<<29),
57 // TODO: more "user" flag compatibility.
58 // "user" option (from mount manpage):
59 // Only the user that mounted a filesystem can unmount it again.
60 // If any user should be able to unmount, then use users instead of user
61 // in the fstab line. The owner option is similar to the user option,
62 // with the restriction that the user must be the owner of the special file.
63 // This may be useful e.g. for /dev/fd if a login script makes
64 // the console user owner of this device.
66 /* Standard mount options (from -o options or --options), with corresponding
69 static const int32_t 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,
80 /* "sw" */ MOUNT_SWAP,
81 /* "swap" */ MOUNT_SWAP,
82 USE_DESKTOP(/* "user" */ MOUNT_USERS,)
83 USE_DESKTOP(/* "users" */ MOUNT_USERS,)
86 USE_FEATURE_MOUNT_FLAGS(
88 /* "nosuid" */ MS_NOSUID,
89 /* "suid" */ ~MS_NOSUID,
90 /* "dev" */ ~MS_NODEV,
91 /* "nodev" */ MS_NODEV,
92 /* "exec" */ ~MS_NOEXEC,
93 /* "noexec" */ MS_NOEXEC,
94 /* "sync" */ MS_SYNCHRONOUS,
95 /* "async" */ ~MS_SYNCHRONOUS,
96 /* "atime" */ ~MS_NOATIME,
97 /* "noatime" */ MS_NOATIME,
98 /* "diratime" */ ~MS_NODIRATIME,
99 /* "nodiratime" */ MS_NODIRATIME,
100 /* "loud" */ ~MS_SILENT,
103 /* "bind" */ MS_BIND,
104 /* "move" */ MS_MOVE,
105 /* "shared" */ MS_SHARED,
106 /* "slave" */ MS_SLAVE,
107 /* "private" */ MS_PRIVATE,
108 /* "unbindable" */ MS_UNBINDABLE,
109 /* "rshared" */ MS_SHARED|MS_RECURSIVE,
110 /* "rslave" */ MS_SLAVE|MS_RECURSIVE,
111 /* "rprivate" */ MS_SLAVE|MS_RECURSIVE,
112 /* "runbindable" */ MS_UNBINDABLE|MS_RECURSIVE,
115 // Always understood.
116 /* "ro" */ MS_RDONLY, // vfs flag
117 /* "rw" */ ~MS_RDONLY, // vfs flag
118 /* "remount" */ MS_REMOUNT // action flag
121 static const char mount_option_str[] =
122 USE_FEATURE_MOUNT_LOOP(
125 USE_FEATURE_MOUNT_FSTAB(
127 /* "quiet" "\0" - do not filter out, vfat wants to see it */
131 USE_DESKTOP("user" "\0")
132 USE_DESKTOP("users" "\0")
134 USE_FEATURE_MOUNT_FLAGS(
163 // Always understood.
164 "ro" "\0" // vfs flag
165 "rw" "\0" // vfs flag
166 "remount" "\0" // action flag
169 /* Append mount options to string */
170 static void append_mount_options(char **oldopts, const char *newopts)
172 if (*oldopts && **oldopts) {
173 /* do not insert options which are already there */
176 int len = strlen(newopts);
177 p = strchr(newopts, ',');
178 if (p) len = p - newopts;
181 if (!strncmp(p, newopts, len)
182 && (p[len] == ',' || p[len] == '\0'))
188 p = xasprintf("%s,%.*s", *oldopts, len, newopts);
193 while (newopts[0] == ',') newopts++;
196 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
197 *oldopts = xstrdup(newopts);
201 /* Use the mount_options list to parse options into flags.
202 * Also return list of unrecognized options if unrecognized!=NULL */
203 static int parse_mount_options(char *options, char **unrecognized)
205 int flags = MS_SILENT;
207 // Loop through options
210 char *comma = strchr(options, ',');
211 const char *option_str = mount_option_str;
213 if (comma) *comma = '\0';
215 // Find this option in mount_options
216 for (i = 0; i < ARRAY_SIZE(mount_options); i++) {
217 if (!strcasecmp(option_str, options)) {
218 long fl = mount_options[i];
219 if (fl < 0) flags &= fl;
223 option_str += strlen(option_str) + 1;
225 // If unrecognized not NULL, append unrecognized mount options */
226 if (unrecognized && i == ARRAY_SIZE(mount_options)) {
227 // Add it to strflags, to pass on to kernel
228 i = *unrecognized ? strlen(*unrecognized) : 0;
229 *unrecognized = xrealloc(*unrecognized, i+strlen(options)+2);
231 // Comma separated if it's not the first one
232 if (i) (*unrecognized)[i++] = ',';
233 strcpy((*unrecognized)+i, options);
238 // Advance to next option
246 // Return a list of all block device backed filesystems
248 static llist_t *get_block_backed_filesystems(void)
250 static const char filesystems[2][sizeof("/proc/filesystems")] = {
259 for (i = 0; i < 2; i++) {
260 f = fopen(filesystems[i], "r");
263 while ((buf = xmalloc_getline(f)) != 0) {
264 if (!strncmp(buf, "nodev", 5) && isspace(buf[5]))
266 fs = skip_whitespace(buf);
267 if (*fs=='#' || *fs=='*' || !*fs) continue;
269 llist_add_to_end(&list, xstrdup(fs));
272 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
278 static llist_t *fslist;
280 #if ENABLE_FEATURE_CLEAN_UP
281 static void delete_block_backed_filesystems(void)
283 llist_free(fslist, free);
286 void delete_block_backed_filesystems(void);
289 #if ENABLE_FEATURE_MTAB_SUPPORT
290 static int useMtab = 1;
297 // Perform actual mount of specific filesystem at specific location.
298 // NB: mp->xxx fields may be trashed on exit
299 static int mount_it_now(struct mntent *mp, int vfsflags, char *filteropts)
303 if (fakeIt) goto mtab;
305 // Mount, with fallback to read-only if necessary.
308 rc = mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
309 vfsflags, filteropts);
310 if (!rc || (vfsflags & MS_RDONLY) || (errno != EACCES && errno != EROFS))
312 if (!(vfsflags & MS_SILENT))
313 bb_error_msg("%s is write-protected, mounting read-only",
315 vfsflags |= MS_RDONLY;
318 // Abort entirely if permission denied.
320 if (rc && errno == EPERM)
321 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
323 /* If the mount was successful, and we're maintaining an old-style
324 * mtab file by hand, add the new entry to it now. */
326 if (ENABLE_FEATURE_MTAB_SUPPORT && useMtab && !rc && !(vfsflags & MS_REMOUNT)) {
328 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
329 const char *option_str = mount_option_str;
333 bb_error_msg("no %s", bb_path_mtab_file);
337 // Add vfs string flags
339 for (i = 0; mount_options[i] != MS_REMOUNT; i++) {
340 if (mount_options[i] > 0 && (mount_options[i] & vfsflags))
341 append_mount_options(&(mp->mnt_opts), option_str);
342 option_str += strlen(option_str) + 1;
345 // Remove trailing / (if any) from directory we mounted on
347 i = strlen(mp->mnt_dir) - 1;
348 if (i > 0 && mp->mnt_dir[i] == '/') mp->mnt_dir[i] = '\0';
350 // Convert to canonical pathnames as needed
352 mp->mnt_dir = bb_simplify_path(mp->mnt_dir);
354 if (!mp->mnt_type || !*mp->mnt_type) { /* bind mount */
355 mp->mnt_fsname = fsname = bb_simplify_path(mp->mnt_fsname);
356 mp->mnt_type = (char*)"bind";
358 mp->mnt_freq = mp->mnt_passno = 0;
362 addmntent(mountTable, mp);
363 endmntent(mountTable);
364 if (ENABLE_FEATURE_CLEAN_UP) {
373 #if ENABLE_FEATURE_MOUNT_NFS
377 * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
379 * Licensed under GPLv2, see file LICENSE in this tarball for details.
381 * Wed Feb 8 12:51:48 1995, biro@yggdrasil.com (Ross Biro): allow all port
382 * numbers to be specified on the command line.
384 * Fri, 8 Mar 1996 18:01:39, Swen Thuemmler <swen@uni-paderborn.de>:
385 * Omit the call to connect() for Linux version 1.3.11 or later.
387 * Wed Oct 1 23:55:28 1997: Dick Streefland <dick_streefland@tasking.com>
388 * Implemented the "bg", "fg" and "retry" mount options for NFS.
390 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
391 * - added Native Language Support
393 * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
397 /* This is just a warning of a common mistake. Possibly this should be a
398 * uclibc faq entry rather than in busybox... */
399 #if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
400 #error "You need to build uClibc with UCLIBC_HAS_RPC for NFS support."
403 #define MOUNTPORT 635
404 #define MNTPATHLEN 1024
405 #define MNTNAMLEN 255
409 typedef char fhandle[FHSIZE];
412 unsigned int fhandle3_len;
424 MNT3ERR_NAMETOOLONG = 63,
425 MNT3ERR_NOTSUPP = 10004,
426 MNT3ERR_SERVERFAULT = 10006,
428 typedef enum mountstat3 mountstat3;
431 unsigned int fhs_status;
436 typedef struct fhstatus fhstatus;
438 struct mountres3_ok {
441 unsigned int auth_flavours_len;
442 char *auth_flavours_val;
445 typedef struct mountres3_ok mountres3_ok;
448 mountstat3 fhs_status;
450 mountres3_ok mountinfo;
453 typedef struct mountres3 mountres3;
455 typedef char *dirpath;
459 typedef struct mountbody *mountlist;
463 dirpath ml_directory;
466 typedef struct mountbody mountbody;
468 typedef struct groupnode *groups;
474 typedef struct groupnode groupnode;
476 typedef struct exportnode *exports;
483 typedef struct exportnode exportnode;
496 typedef struct ppathcnf ppathcnf;
498 #define MOUNTPROG 100005
501 #define MOUNTPROC_NULL 0
502 #define MOUNTPROC_MNT 1
503 #define MOUNTPROC_DUMP 2
504 #define MOUNTPROC_UMNT 3
505 #define MOUNTPROC_UMNTALL 4
506 #define MOUNTPROC_EXPORT 5
507 #define MOUNTPROC_EXPORTALL 6
509 #define MOUNTVERS_POSIX 2
511 #define MOUNTPROC_PATHCONF 7
515 #define MOUNTPROC3_NULL 0
516 #define MOUNTPROC3_MNT 1
517 #define MOUNTPROC3_DUMP 2
518 #define MOUNTPROC3_UMNT 3
519 #define MOUNTPROC3_UMNTALL 4
520 #define MOUNTPROC3_EXPORT 5
532 * We want to be able to compile mount on old kernels in such a way
533 * that the binary will work well on more recent kernels.
534 * Thus, if necessary we teach nfsmount.c the structure of new fields
535 * that will come later.
537 * Moreover, the new kernel includes conflict with glibc includes
538 * so it is easiest to ignore the kernel altogether (at compile time).
546 unsigned char data[64];
549 struct nfs_mount_data {
552 struct nfs2_fh old_root; /* 1 */
558 int acregmin; /* 1 */
559 int acregmax; /* 1 */
560 int acdirmin; /* 1 */
561 int acdirmax; /* 1 */
562 struct sockaddr_in addr; /* 1 */
563 char hostname[256]; /* 1 */
565 unsigned int bsize; /* 3 */
566 struct nfs3_fh root; /* 4 */
569 /* bits in the flags field */
571 NFS_MOUNT_SOFT = 0x0001, /* 1 */
572 NFS_MOUNT_INTR = 0x0002, /* 1 */
573 NFS_MOUNT_SECURE = 0x0004, /* 1 */
574 NFS_MOUNT_POSIX = 0x0008, /* 1 */
575 NFS_MOUNT_NOCTO = 0x0010, /* 1 */
576 NFS_MOUNT_NOAC = 0x0020, /* 1 */
577 NFS_MOUNT_TCP = 0x0040, /* 2 */
578 NFS_MOUNT_VER3 = 0x0080, /* 3 */
579 NFS_MOUNT_KERBEROS = 0x0100, /* 3 */
580 NFS_MOUNT_NONLM = 0x0200 /* 3 */
585 * We need to translate between nfs status return values and
586 * the local errno values which may not be the same.
588 * Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>: change errno:
589 * "after #include <errno.h> the symbol errno is reserved for any use,
590 * it cannot even be used as a struct tag or field name".
594 #define EDQUOT ENOSPC
597 // Convert each NFSERR_BLAH into EBLAH
599 static const struct {
603 {0,0}, {1,EPERM}, {2,ENOENT}, {5,EIO}, {6,ENXIO}, {13,EACCES}, {17,EEXIST},
604 {19,ENODEV}, {20,ENOTDIR}, {21,EISDIR}, {22,EINVAL}, {27,EFBIG},
605 {28,ENOSPC}, {30,EROFS}, {63,ENAMETOOLONG}, {66,ENOTEMPTY}, {69,EDQUOT},
606 {70,ESTALE}, {71,EREMOTE}, {-1,EIO}
609 static char *nfs_strerror(int status)
613 for (i = 0; nfs_errtbl[i].stat != -1; i++) {
614 if (nfs_errtbl[i].stat == status)
615 return strerror(nfs_errtbl[i].errnum);
617 return xasprintf("unknown nfs status return value: %d", status);
620 static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
622 if (!xdr_opaque(xdrs, objp, FHSIZE))
627 static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
629 if (!xdr_u_int(xdrs, &objp->fhs_status))
631 switch (objp->fhs_status) {
633 if (!xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle))
642 static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
644 if (!xdr_string(xdrs, objp, MNTPATHLEN))
649 static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
651 if (!xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (unsigned int *) &objp->fhandle3_len, FHSIZE3))
656 static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
658 if (!xdr_fhandle3(xdrs, &objp->fhandle))
660 if (!xdr_array(xdrs, &(objp->auth_flavours.auth_flavours_val), &(objp->auth_flavours.auth_flavours_len), ~0,
661 sizeof (int), (xdrproc_t) xdr_int))
666 static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
668 if (!xdr_enum(xdrs, (enum_t *) objp))
673 static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
675 if (!xdr_mountstat3(xdrs, &objp->fhs_status))
677 switch (objp->fhs_status) {
679 if (!xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo))
688 #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
690 static smalluint nfs_mount_version;
693 * Unfortunately, the kernel prints annoying console messages
694 * in case of an unexpected nfs mount version (instead of
695 * just returning some error). Therefore we'll have to try
696 * and figure out what version the kernel expects.
699 * KERNEL_NFS_MOUNT_VERSION: kernel sources at compile time
700 * NFS_MOUNT_VERSION: these nfsmount sources at compile time
701 * nfs_mount_version: version this source and running kernel can handle
704 find_kernel_nfs_mount_version(void)
708 if (nfs_mount_version)
711 nfs_mount_version = 4; /* default */
713 kernel_version = get_linux_version_code();
714 if (kernel_version) {
715 if (kernel_version < KERNEL_VERSION(2,1,32))
716 nfs_mount_version = 1;
717 else if (kernel_version < KERNEL_VERSION(2,2,18) ||
718 (kernel_version >= KERNEL_VERSION(2,3,0) &&
719 kernel_version < KERNEL_VERSION(2,3,99)))
720 nfs_mount_version = 3;
721 /* else v4 since 2.3.99pre4 */
726 get_mountport(struct pmap *pm_mnt,
727 struct sockaddr_in *server_addr,
729 long unsigned version,
733 struct pmaplist *pmap;
735 server_addr->sin_port = PMAPPORT;
736 /* glibc 2.4 (still) has pmap_getmaps(struct sockaddr_in *).
737 * I understand it like "IPv6 for this is not 100% ready" */
738 pmap = pmap_getmaps(server_addr);
740 if (version > MAX_NFSPROT)
741 version = MAX_NFSPROT;
744 pm_mnt->pm_prog = prog;
745 pm_mnt->pm_vers = version;
746 pm_mnt->pm_prot = proto;
747 pm_mnt->pm_port = port;
750 if (pmap->pml_map.pm_prog != prog)
752 if (!version && pm_mnt->pm_vers > pmap->pml_map.pm_vers)
754 if (version > 2 && pmap->pml_map.pm_vers != version)
756 if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
758 if (pmap->pml_map.pm_vers > MAX_NFSPROT ||
759 (proto && pm_mnt->pm_prot && pmap->pml_map.pm_prot != proto) ||
760 (port && pmap->pml_map.pm_port != port))
762 memcpy(pm_mnt, &pmap->pml_map, sizeof(*pm_mnt));
764 pmap = pmap->pml_next;
766 if (!pm_mnt->pm_vers)
767 pm_mnt->pm_vers = MOUNTVERS;
768 if (!pm_mnt->pm_port)
769 pm_mnt->pm_port = MOUNTPORT;
770 if (!pm_mnt->pm_prot)
771 pm_mnt->pm_prot = IPPROTO_TCP;
775 static int daemonize(void)
779 if (pid < 0) /* error */
781 if (pid > 0) /* parent */
784 fd = xopen(bb_dev_null, O_RDWR);
788 while (fd > 2) close(fd--);
790 openlog(applet_name, LOG_PID, LOG_DAEMON);
791 logmode = LOGMODE_SYSLOG;
795 static inline int daemonize(void) { return -ENOSYS; }
799 static inline int we_saw_this_host_before(const char *hostname)
804 /* RPC strerror analogs are terminally idiotic:
805 * *mandatory* prefix and \n at end.
806 * This hopefully helps. Usage:
807 * error_msg_rpc(clnt_*error*(" ")) */
808 static void error_msg_rpc(const char *msg)
811 while (msg[0] == ' ' || msg[0] == ':') msg++;
813 while (len && msg[len-1] == '\n') len--;
814 bb_error_msg("%.*s", len, msg);
817 // NB: mp->xxx fields may be trashed on exit
818 static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts)
824 struct nfs_mount_data data;
827 struct sockaddr_in server_addr;
828 struct sockaddr_in mount_server_addr;
831 struct fhstatus nfsv2;
832 struct mountres3 nfsv3;
858 find_kernel_nfs_mount_version();
866 /* NB: hostname, mounthost, filteropts must be free()d prior to return */
868 filteropts = xstrdup(filteropts); /* going to trash it later... */
870 hostname = xstrdup(mp->mnt_fsname);
871 /* mount_main() guarantees that ':' is there */
872 s = strchr(hostname, ':');
875 /* Ignore all but first hostname in replicated mounts
876 until they can be fully supported. (mack@sgi.com) */
877 s = strchr(hostname, ',');
880 bb_error_msg("warning: multiple hostnames not supported");
883 server_addr.sin_family = AF_INET;
884 if (!inet_aton(hostname, &server_addr.sin_addr)) {
885 hp = gethostbyname(hostname);
887 bb_herror_msg("%s", hostname);
890 if (hp->h_length > sizeof(struct in_addr)) {
891 bb_error_msg("got bad hp->h_length");
892 hp->h_length = sizeof(struct in_addr);
894 memcpy(&server_addr.sin_addr,
895 hp->h_addr, hp->h_length);
898 memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
900 /* add IP address to mtab options for use when unmounting */
902 if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
903 mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
905 char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
906 mp->mnt_opts[0] ? "," : "",
907 inet_ntoa(server_addr.sin_addr));
912 /* Set default options.
913 * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
914 * let the kernel decide.
915 * timeo is filled in after we know whether it'll be TCP or UDP. */
916 memset(&data, 0, sizeof(data));
922 data.namlen = NAME_MAX;
930 retry = 10000; /* 10000 minutes ~ 1 week */
933 mountprog = MOUNTPROG;
941 if (filteropts) for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
942 char *opteq = strchr(opt, '=');
944 static const char options[] ALIGN1 =
956 /* 11 */ "mountport\0"
957 /* 12 */ "mounthost\0"
958 /* 13 */ "mountprog\0"
959 /* 14 */ "mountvers\0"
966 int val = xatoi_u(opteq + 1);
968 switch (index_in_strings(options, opt)) {
981 case 4: // "acregmin"
984 case 5: // "acregmax"
987 case 6: // "acdirmin"
990 case 7: // "acdirmax"
1005 case 11: // "mountport"
1008 case 12: // "mounthost"
1009 mounthost = xstrndup(opteq+1,
1010 strcspn(opteq+1," \t\n\r,"));
1012 case 13: // "mountprog"
1015 case 14: // "mountvers"
1018 case 15: // "nfsprog"
1021 case 16: // "nfsvers"
1026 if (!strncmp(opteq+1, "tcp", 3))
1028 else if (!strncmp(opteq+1, "udp", 3))
1031 bb_error_msg("warning: unrecognized proto= option");
1033 case 19: // "namlen"
1034 if (nfs_mount_version >= 2)
1037 bb_error_msg("warning: option namlen is not supported\n");
1039 case 20: // "addr" - ignore
1042 bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
1047 static const char options[] ALIGN1 =
1060 if (!strncmp(opt, "no", 2)) {
1064 switch (index_in_strings(options, opt)) {
1100 if (nfs_mount_version >= 3)
1103 bb_error_msg("warning: option nolock is not supported");
1106 bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
1111 proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
1113 data.flags = (soft ? NFS_MOUNT_SOFT : 0)
1114 | (intr ? NFS_MOUNT_INTR : 0)
1115 | (posix ? NFS_MOUNT_POSIX : 0)
1116 | (nocto ? NFS_MOUNT_NOCTO : 0)
1117 | (noac ? NFS_MOUNT_NOAC : 0);
1118 if (nfs_mount_version >= 2)
1119 data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
1120 if (nfs_mount_version >= 3)
1121 data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
1122 if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
1123 bb_error_msg("NFSv%d not supported", nfsvers);
1126 if (nfsvers && !mountvers)
1127 mountvers = (nfsvers < 3) ? 1 : nfsvers;
1128 if (nfsvers && nfsvers < mountvers) {
1129 mountvers = nfsvers;
1132 /* Adjust options if none specified */
1134 data.timeo = tcp ? 70 : 7;
1136 data.version = nfs_mount_version;
1138 if (vfsflags & MS_REMOUNT)
1142 * If the previous mount operation on the same host was
1143 * backgrounded, and the "bg" for this mount is also set,
1144 * give up immediately, to avoid the initial timeout.
1146 if (bg && we_saw_this_host_before(hostname)) {
1147 daemonized = daemonize();
1148 if (daemonized <= 0) { /* parent or error */
1149 retval = -daemonized;
1154 /* create mount daemon client */
1155 /* See if the nfs host = mount host. */
1157 if (mounthost[0] >= '0' && mounthost[0] <= '9') {
1158 mount_server_addr.sin_family = AF_INET;
1159 mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
1161 hp = gethostbyname(mounthost);
1163 bb_herror_msg("%s", mounthost);
1166 if (hp->h_length > sizeof(struct in_addr)) {
1167 bb_error_msg("got bad hp->h_length?");
1168 hp->h_length = sizeof(struct in_addr);
1170 mount_server_addr.sin_family = AF_INET;
1171 memcpy(&mount_server_addr.sin_addr,
1172 hp->h_addr, hp->h_length);
1178 * The following loop implements the mount retries. When the mount
1179 * times out, and the "bg" option is set, we background ourself
1180 * and continue trying.
1182 * The case where the mount point is not present and the "bg"
1183 * option is set, is treated as a timeout. This is done to
1184 * support nested mounts.
1186 * The "retry" count specified by the user is the number of
1187 * minutes to retry before giving up.
1190 struct timeval total_timeout;
1191 struct timeval retry_timeout;
1197 retry_timeout.tv_sec = 3;
1198 retry_timeout.tv_usec = 0;
1199 total_timeout.tv_sec = 20;
1200 total_timeout.tv_usec = 0;
1201 timeout = time(NULL) + 60 * retry;
1205 /* be careful not to use too many CPU cycles */
1209 get_mountport(&pm_mnt, &mount_server_addr,
1214 nfsvers = (pm_mnt.pm_vers < 2) ? 2 : pm_mnt.pm_vers;
1216 /* contact the mount daemon via TCP */
1217 mount_server_addr.sin_port = htons(pm_mnt.pm_port);
1218 msock = RPC_ANYSOCK;
1220 switch (pm_mnt.pm_prot) {
1222 mclient = clntudp_create(&mount_server_addr,
1229 mount_server_addr.sin_port = htons(pm_mnt.pm_port);
1230 msock = RPC_ANYSOCK;
1232 mclient = clnttcp_create(&mount_server_addr,
1241 if (!daemonized && prevt == 0)
1242 error_msg_rpc(clnt_spcreateerror(" "));
1244 enum clnt_stat clnt_stat;
1245 /* try to mount hostname:pathname */
1246 mclient->cl_auth = authunix_create_default();
1248 /* make pointers in xdr_mountres3 NULL so
1249 * that xdr_array allocates memory for us
1251 memset(&status, 0, sizeof(status));
1253 if (pm_mnt.pm_vers == 3)
1254 clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
1255 (xdrproc_t) xdr_dirpath,
1256 (caddr_t) &pathname,
1257 (xdrproc_t) xdr_mountres3,
1261 clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
1262 (xdrproc_t) xdr_dirpath,
1263 (caddr_t) &pathname,
1264 (xdrproc_t) xdr_fhstatus,
1268 if (clnt_stat == RPC_SUCCESS)
1269 goto prepare_kernel_data; /* we're done */
1270 if (errno != ECONNREFUSED) {
1271 error_msg_rpc(clnt_sperror(mclient, " "));
1272 goto fail; /* don't retry */
1274 /* Connection refused */
1275 if (!daemonized && prevt == 0) /* print just once */
1276 error_msg_rpc(clnt_sperror(mclient, " "));
1277 auth_destroy(mclient->cl_auth);
1278 clnt_destroy(mclient);
1284 /* Timeout. We are going to retry... maybe */
1289 daemonized = daemonize();
1290 if (daemonized <= 0) { /* parent or error */
1291 retval = -daemonized;
1298 /* TODO error message */
1304 prepare_kernel_data:
1307 if (status.nfsv2.fhs_status != 0) {
1308 bb_error_msg("%s:%s failed, reason given by server: %s",
1310 nfs_strerror(status.nfsv2.fhs_status));
1313 memcpy(data.root.data,
1314 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1316 data.root.size = NFS_FHSIZE;
1317 memcpy(data.old_root.data,
1318 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1321 fhandle3 *my_fhandle;
1322 if (status.nfsv3.fhs_status != 0) {
1323 bb_error_msg("%s:%s failed, reason given by server: %s",
1325 nfs_strerror(status.nfsv3.fhs_status));
1328 my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
1329 memset(data.old_root.data, 0, NFS_FHSIZE);
1330 memset(&data.root, 0, sizeof(data.root));
1331 data.root.size = my_fhandle->fhandle3_len;
1332 memcpy(data.root.data,
1333 (char *) my_fhandle->fhandle3_val,
1334 my_fhandle->fhandle3_len);
1336 data.flags |= NFS_MOUNT_VER3;
1339 /* create nfs socket for kernel */
1342 if (nfs_mount_version < 3) {
1343 bb_error_msg("NFS over TCP is not supported");
1346 fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1348 fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1350 bb_perror_msg("nfs socket");
1353 if (bindresvport(fsock, 0) < 0) {
1354 bb_perror_msg("nfs bindresvport");
1358 server_addr.sin_port = PMAPPORT;
1359 port = pmap_getport(&server_addr, nfsprog, nfsvers,
1360 tcp ? IPPROTO_TCP : IPPROTO_UDP);
1364 server_addr.sin_port = htons(port);
1366 /* prepare data structure for kernel */
1369 memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
1370 strncpy(data.hostname, hostname, sizeof(data.hostname));
1374 auth_destroy(mclient->cl_auth);
1375 clnt_destroy(mclient);
1380 /* We must wait until mount directory is available */
1381 struct stat statbuf;
1383 while (stat(mp->mnt_dir, &statbuf) == -1) {
1385 daemonized = daemonize();
1386 if (daemonized <= 0) { /* parent or error */
1387 // FIXME: parent doesn't close fsock - ??!
1388 retval = -daemonized;
1392 sleep(delay); /* 1, 2, 4, 8, 16, 30, ... */
1399 do_mount: /* perform actual mount */
1401 mp->mnt_type = (char*)"nfs";
1402 retval = mount_it_now(mp, vfsflags, (char*)&data);
1409 auth_destroy(mclient->cl_auth);
1410 clnt_destroy(mclient);
1424 #else /* !ENABLE_FEATURE_MOUNT_NFS */
1426 /* Never called. Call should be optimized out. */
1427 int nfsmount(struct mntent *mp, int vfsflags, char *filteropts);
1429 #endif /* !ENABLE_FEATURE_MOUNT_NFS */
1431 // Mount one directory. Handles CIFS, NFS, loopback, autobind, and filesystem
1432 // type detection. Returns 0 for success, nonzero for failure.
1433 // NB: mp->xxx fields may be trashed on exit
1434 static int singlemount(struct mntent *mp, int ignore_busy)
1436 int rc = -1, vfsflags;
1437 char *loopFile = 0, *filteropts = 0;
1441 vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
1443 // Treat fstype "auto" as unspecified.
1445 if (mp->mnt_type && strcmp(mp->mnt_type,"auto") == 0)
1448 // Might this be a virtual filesystem?
1450 if (ENABLE_FEATURE_MOUNT_HELPERS
1451 && (strchr(mp->mnt_fsname, '#'))
1453 char *s, *p, *args[35];
1455 for (s = p = mp->mnt_fsname; *s && n < 35-3; ++s) {
1456 if (s[0] == '#' && s[1] != '#') {
1463 args[n++] = mp->mnt_dir;
1465 rc = wait4pid(xspawn(args));
1469 // Might this be an CIFS filesystem?
1471 if (ENABLE_FEATURE_MOUNT_CIFS
1472 && (!mp->mnt_type || strcmp(mp->mnt_type,"cifs") == 0)
1473 && (mp->mnt_fsname[0]=='/' || mp->mnt_fsname[0]=='\\')
1474 && mp->mnt_fsname[0]==mp->mnt_fsname[1]
1476 len_and_sockaddr *lsa;
1481 // Replace '/' with '\' and verify that unc points to "//server/share".
1483 for (s = mp->mnt_fsname; *s; ++s)
1484 if (*s == '/') *s = '\\';
1488 s = strrchr(mp->mnt_fsname, '\\');
1489 if (s <= mp->mnt_fsname+1) goto report_error;
1491 lsa = host2sockaddr(mp->mnt_fsname+2, 0);
1493 if (!lsa) goto report_error;
1495 // insert ip=... option into string flags.
1497 dotted = xmalloc_sockaddr2dotted_noport(&lsa->sa);
1498 ip = xasprintf("ip=%s", dotted);
1499 parse_mount_options(ip, &filteropts);
1501 // compose new unc '\\server-ip\share'
1502 // (s => slash after hostname)
1504 mp->mnt_fsname = xasprintf("\\\\%s%s", dotted, s);
1507 vfsflags |= MS_MANDLOCK;
1509 mp->mnt_type = (char*)"cifs";
1510 rc = mount_it_now(mp, vfsflags, filteropts);
1511 if (ENABLE_FEATURE_CLEAN_UP) {
1512 free(mp->mnt_fsname);
1520 // Might this be an NFS filesystem?
1522 if (ENABLE_FEATURE_MOUNT_NFS
1523 && (!mp->mnt_type || !strcmp(mp->mnt_type, "nfs"))
1524 && strchr(mp->mnt_fsname, ':') != NULL
1526 rc = nfsmount(mp, vfsflags, filteropts);
1530 // Look at the file. (Not found isn't a failure for remount, or for
1531 // a synthetic filesystem like proc or sysfs.)
1532 // (We use stat, not lstat, in order to allow
1533 // mount symlink_to_file_or_blkdev dir)
1535 if (!stat(mp->mnt_fsname, &st)
1536 && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE))
1538 // Do we need to allocate a loopback device for it?
1540 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
1541 loopFile = bb_simplify_path(mp->mnt_fsname);
1542 mp->mnt_fsname = NULL; /* will receive malloced loop dev name */
1543 if (set_loop(&(mp->mnt_fsname), loopFile, 0) < 0) {
1544 if (errno == EPERM || errno == EACCES)
1545 bb_error_msg(bb_msg_perm_denied_are_you_root);
1547 bb_perror_msg("cannot setup loop device");
1551 // Autodetect bind mounts
1553 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
1554 vfsflags |= MS_BIND;
1557 /* If we know the fstype (or don't need to), jump straight
1558 * to the actual mount. */
1560 if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1561 rc = mount_it_now(mp, vfsflags, filteropts);
1563 // Loop through filesystem types until mount succeeds
1566 /* Initialize list of block backed filesystems. This has to be
1567 * done here so that during "mount -a", mounts after /proc shows up
1568 * can autodetect. */
1571 fslist = get_block_backed_filesystems();
1572 if (ENABLE_FEATURE_CLEAN_UP && fslist)
1573 atexit(delete_block_backed_filesystems);
1576 for (fl = fslist; fl; fl = fl->link) {
1577 mp->mnt_type = fl->data;
1578 rc = mount_it_now(mp, vfsflags, filteropts);
1583 // If mount failed, clean up loop file (if any).
1585 if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
1586 del_loop(mp->mnt_fsname);
1587 if (ENABLE_FEATURE_CLEAN_UP) {
1589 free(mp->mnt_fsname);
1594 if (ENABLE_FEATURE_CLEAN_UP)
1597 if (errno == EBUSY && ignore_busy)
1600 bb_perror_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
1604 // Parse options, if necessary parse fstab/mtab, and call singlemount for
1605 // each directory to be mounted.
1607 static const char must_be_root[] ALIGN1 = "you must be root";
1609 int mount_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1610 int mount_main(int argc, char **argv)
1612 enum { OPT_ALL = 0x10 };
1614 char *cmdopts = xstrdup(""), *fstype=0, *storage_path=0;
1616 const char *fstabname;
1620 struct mntent mtpair[2], *mtcur = mtpair;
1621 SKIP_DESKTOP(const int nonroot = 0;)
1622 USE_DESKTOP( int nonroot = (getuid() != 0);)
1624 /* parse long options, like --bind and --move. Note that -o option
1625 * and --option are synonymous. Yes, this means --remount,rw works. */
1627 for (i = j = 0; i < argc; i++) {
1628 if (argv[i][0] == '-' && argv[i][1] == '-') {
1629 append_mount_options(&cmdopts, argv[i]+2);
1630 } else argv[j++] = argv[i];
1635 // Parse remaining options
1637 opt = getopt32(argv, "o:t:rwanfvsi", &opt_o, &fstype);
1638 if (opt & 0x1) append_mount_options(&cmdopts, opt_o); // -o
1639 //if (opt & 0x2) // -t
1640 if (opt & 0x4) append_mount_options(&cmdopts, "ro"); // -r
1641 if (opt & 0x8) append_mount_options(&cmdopts, "rw"); // -w
1642 //if (opt & 0x10) // -a
1643 if (opt & 0x20) USE_FEATURE_MTAB_SUPPORT(useMtab = 0); // -n
1644 if (opt & 0x40) USE_FEATURE_MTAB_SUPPORT(fakeIt = 1); // -f
1645 //if (opt & 0x80) // -v: verbose (ignore)
1646 //if (opt & 0x100) // -s: sloppy (ignore)
1647 //if (opt & 0x200) // -i: don't call mount.<fstype> (ignore)
1651 // Three or more non-option arguments? Die with a usage message.
1653 if (argc > 2) bb_show_usage();
1655 // If we have no arguments, show currently mounted filesystems
1658 if (!(opt & OPT_ALL)) {
1659 FILE *mountTable = setmntent(bb_path_mtab_file, "r");
1661 if (!mountTable) bb_error_msg_and_die("no %s", bb_path_mtab_file);
1663 while (getmntent_r(mountTable, &mtpair[0], getmntent_buf,
1664 sizeof(getmntent_buf)))
1666 // Don't show rootfs. FIXME: why??
1667 // util-linux 2.12a happily shows rootfs...
1668 //if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
1670 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
1671 printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
1672 mtpair->mnt_dir, mtpair->mnt_type,
1675 if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
1676 return EXIT_SUCCESS;
1678 } else storage_path = bb_simplify_path(argv[0]);
1680 // When we have two arguments, the second is the directory and we can
1681 // skip looking at fstab entirely. We can always abspath() the directory
1682 // argument when we get it.
1686 bb_error_msg_and_die(must_be_root);
1687 mtpair->mnt_fsname = argv[0];
1688 mtpair->mnt_dir = argv[1];
1689 mtpair->mnt_type = fstype;
1690 mtpair->mnt_opts = cmdopts;
1691 rc = singlemount(mtpair, 0);
1695 i = parse_mount_options(cmdopts, 0);
1696 if (nonroot && (i & ~MS_SILENT)) // Non-root users cannot specify flags
1697 bb_error_msg_and_die(must_be_root);
1699 // If we have a shared subtree flag, don't worry about fstab or mtab.
1701 if (ENABLE_FEATURE_MOUNT_FLAGS
1702 && (i & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
1704 rc = mount("", argv[0], "", i, "");
1705 if (rc) bb_simple_perror_msg_and_die(argv[0]);
1709 // Open either fstab or mtab
1711 fstabname = "/etc/fstab";
1712 if (i & MS_REMOUNT) {
1713 fstabname = bb_path_mtab_file;
1715 fstab = setmntent(fstabname, "r");
1717 bb_perror_msg_and_die("cannot read %s", fstabname);
1719 // Loop through entries until we find what we're looking for.
1721 memset(mtpair, 0, sizeof(mtpair));
1723 struct mntent *mtnext = (mtcur==mtpair ? mtpair+1 : mtpair);
1725 // Get next fstab entry
1727 if (!getmntent_r(fstab, mtcur, getmntent_buf
1728 + (mtcur==mtpair ? sizeof(getmntent_buf)/2 : 0),
1729 sizeof(getmntent_buf)/2))
1731 // Were we looking for something specific?
1735 // If we didn't find anything, complain.
1737 if (!mtnext->mnt_fsname)
1738 bb_error_msg_and_die("can't find %s in %s",
1739 argv[0], fstabname);
1743 // fstab must have "users" or "user"
1744 if (!(parse_mount_options(mtcur->mnt_opts, 0) & MOUNT_USERS))
1745 bb_error_msg_and_die(must_be_root);
1748 // Mount the last thing we found.
1750 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1751 append_mount_options(&(mtcur->mnt_opts), cmdopts);
1752 rc = singlemount(mtcur, 0);
1753 free(mtcur->mnt_opts);
1758 /* If we're trying to mount something specific and this isn't it,
1759 * skip it. Note we must match both the exact text in fstab (ala
1760 * "proc") or a full path from root */
1764 // Is this what we're looking for?
1766 if (strcmp(argv[0], mtcur->mnt_fsname) &&
1767 strcmp(storage_path, mtcur->mnt_fsname) &&
1768 strcmp(argv[0], mtcur->mnt_dir) &&
1769 strcmp(storage_path, mtcur->mnt_dir)) continue;
1771 // Remember this entry. Something later may have overmounted
1772 // it, and we want the _last_ match.
1776 // If we're mounting all.
1779 // Do we need to match a filesystem type?
1780 if (fstype && match_fstype(mtcur, fstype)) continue;
1782 // Skip noauto and swap anyway.
1784 if (parse_mount_options(mtcur->mnt_opts, 0)
1785 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
1787 // No, mount -a won't mount anything,
1788 // even user mounts, for mere humans.
1791 bb_error_msg_and_die(must_be_root);
1793 // Mount this thing.
1795 // NFS mounts want this to be xrealloc-able
1796 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1797 if (singlemount(mtcur, 1)) {
1798 /* Count number of failed mounts */
1801 free(mtcur->mnt_opts);
1804 if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
1808 if (ENABLE_FEATURE_CLEAN_UP) {