[PATCH] mount.cifs: attempt to lock the mtab before updating it

Jeff Layton jlayton at redhat.com
Sun Oct 5 00:41:39 GMT 2008


Have mount.cifs lock the mtab using the same scheme as umount.cifs.
Currently, we just append to the mtab, but that's subject to races with
programs that build a new mtab and rename it to /etc/mtab.

Signed-off-by: Jeff Layton <jlayton at redhat.com>
---
 source3/client/mount.cifs.c |   44 ++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 43 insertions(+), 1 deletions(-)

diff --git a/source3/client/mount.cifs.c b/source3/client/mount.cifs.c
index b7a76c6..325f1ec 100644
--- a/source3/client/mount.cifs.c
+++ b/source3/client/mount.cifs.c
@@ -79,6 +79,8 @@
 #define MOUNT_PASSWD_SIZE 64
 #define DOMAIN_SIZE 64
 
+#define MOUNTED_LOCK "/etc/mtab~"
+
 const char *thisprogram;
 int verboseflag = 0;
 static int got_password = 0;
@@ -1014,6 +1016,40 @@ uppercase_string(char *string)
 	return 1;
 }
 
+/*
+ * BB: Duplicate the locking scheme that util-linux-ng mount command uses.
+ *     This can leave a MOUNTED_LOCK in place if the process is signalled.
+ */
+static int
+lock_mtab(void)
+{
+	int rc, numsleeps = 0;
+
+	rc = open(MOUNTED_LOCK, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
+	while (rc < 0 && numsleeps < 300) {
+		if (errno != EEXIST)
+			return 0;
+
+		/* sleep .1s */
+		usleep(100000);
+		numsleeps++;
+		rc = open(MOUNTED_LOCK, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
+	}
+
+	if (rc >= 0) {
+		close(rc);
+		return 1;
+	} else {
+		return 0;
+	}
+}
+
+static void
+unlock_mtab(void)
+{
+	unlink(MOUNTED_LOCK);
+}
+
 int main(int argc, char ** argv)
 {
 	int c;
@@ -1403,6 +1439,11 @@ mount_retry:
 		rc = -1;
 		goto mount_exit;
 	} else {
+		if (!lock_mtab()) {
+			printf("Mount table locked\n");
+			rc = 0;
+			goto mount_exit;
+		}
 		pmntfile = setmntent(MOUNTED, "a+");
 		if(pmntfile) {
 			mountent.mnt_fsname = dev_name;
@@ -1440,8 +1481,9 @@ mount_retry:
 			endmntent(pmntfile);
 			SAFE_FREE(mountent.mnt_opts);
 		} else {
-		    printf("could not update mount table\n");
+			printf("could not update mount table\n");
 		}
+		unlock_mtab();
 	}
 	rc = 0;
 mount_exit:
-- 
1.5.5.1



More information about the samba-technical mailing list