virtio-9p: Security model for create/open2

In the mapped security model, VirtFS server intercepts and maps
the file object create and get/set attribute requests. Files on the fileserver
will be created with VirtFS servers (QEMU) user credentials and the
client-users credentials are stored in extended attributes. On the request
to get attributes, server extracts the client-users credentials
from extended attributes and sends them to the client.

On Host/Fileserver:
-rw-------. 2 virfsuid virtfsgid 0 2010-05-11 09:19 afile

On Guest/Client:
-rw-r--r-- 2 guestuser guestuser 0 2010-05-11 12:19 afile

Signed-off-by: Venkateswararao Jujjuri <jvrao@linux.vnet.ibm.com>
Signed-off-by: Anthony Liguori <aliguori@us.ibm.com>
diff --git a/hw/virtio-9p-local.c b/hw/virtio-9p-local.c
index 74c81a6..bb5140e 100644
--- a/hw/virtio-9p-local.c
+++ b/hw/virtio-9p-local.c
@@ -95,6 +95,18 @@
     return 0;
 }
 
+static int local_post_create_passthrough(FsContext *fs_ctx, const char *path,
+        FsCred *credp)
+{
+    if (chmod(rpath(fs_ctx, path), credp->fc_mode & 07777) < 0) {
+        return -1;
+    }
+    if (chown(rpath(fs_ctx, path), credp->fc_uid, credp->fc_gid) < 0) {
+        return -1;
+    }
+    return 0;
+}
+
 static ssize_t local_readlink(FsContext *ctx, const char *path,
                                 char *buf, size_t bufsz)
 {
@@ -230,9 +242,44 @@
     return err;
 }
 
-static int local_open2(FsContext *ctx, const char *path, int flags, mode_t mode)
+static int local_open2(FsContext *fs_ctx, const char *path, int flags,
+        FsCred *credp)
 {
-    return open(rpath(ctx, path), flags, mode);
+    int fd = -1;
+    int err = -1;
+    int serrno = 0;
+
+    /* Determine the security model */
+    if (fs_ctx->fs_sm == SM_MAPPED) {
+        fd = open(rpath(fs_ctx, path), flags, SM_LOCAL_MODE_BITS);
+        if (fd == -1) {
+            return fd;
+        }
+        credp->fc_mode = credp->fc_mode|S_IFREG;
+        /* Set cleint credentials in xattr */
+        err = local_set_xattr(rpath(fs_ctx, path), credp);
+        if (err == -1) {
+            serrno = errno;
+            goto err_end;
+        }
+    } else if (fs_ctx->fs_sm == SM_PASSTHROUGH) {
+        fd = open(rpath(fs_ctx, path), flags, credp->fc_mode);
+        if (fd == -1) {
+            return fd;
+        }
+        err = local_post_create_passthrough(fs_ctx, path, credp);
+        if (err == -1) {
+            serrno = errno;
+            goto err_end;
+        }
+    }
+    return fd;
+
+err_end:
+    close(fd);
+    remove(rpath(fs_ctx, path));
+    errno = serrno;
+    return err;
 }