fscrypt: new helper function - fscrypt_require_key()
authorEric Biggers <ebiggers@google.com>
Mon, 9 Oct 2017 19:15:39 +0000 (12:15 -0700)
committerTheodore Ts'o <tytso@mit.edu>
Wed, 18 Oct 2017 23:52:37 +0000 (19:52 -0400)
Add a helper function which checks if an inode is encrypted, and if so,
tries to set up its encryption key.  This is a pattern which is
duplicated in multiple places in each of ext4, f2fs, and ubifs --- for
example, when a regular file is asked to be opened or truncated.

Acked-by: Dave Chinner <dchinner@redhat.com>
Signed-off-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
include/linux/fscrypt.h

index d58e6a90cfe4e67d474b889f7c00203577ba4e0f..b3e2a5f93415ab47424e3b7daca38737a6e67459 100644 (file)
@@ -151,5 +151,30 @@ static inline bool fscrypt_has_encryption_key(const struct inode *inode)
 #include <linux/fscrypt_notsupp.h>
 #endif /* __FS_HAS_ENCRYPTION */
 
+/**
+ * fscrypt_require_key - require an inode's encryption key
+ * @inode: the inode we need the key for
+ *
+ * If the inode is encrypted, set up its encryption key if not already done.
+ * Then require that the key be present and return -ENOKEY otherwise.
+ *
+ * No locks are needed, and the key will live as long as the struct inode --- so
+ * it won't go away from under you.
+ *
+ * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
+ * if a problem occurred while setting up the encryption key.
+ */
+static inline int fscrypt_require_key(struct inode *inode)
+{
+       if (IS_ENCRYPTED(inode)) {
+               int err = fscrypt_get_encryption_info(inode);
+
+               if (err)
+                       return err;
+               if (!fscrypt_has_encryption_key(inode))
+                       return -ENOKEY;
+       }
+       return 0;
+}
 
 #endif /* _LINUX_FSCRYPT_H */