The code to copy file descriptors was duplicated in pidfd_getfd.
Rather than continue to duplicate it, this hoists the code out of
kernel/pid.c and uses the newly added file_receive helper.

Earlier, when this was implemented there was some back-and-forth
about how the semantics should work around copying around file
descriptors [1], and it was decided that the default behaviour
should be to not modify cgroup data. As a matter of least surprise,
this approach follows the default semantics as presented by SCM_RIGHTS.

In the future, a flag can be added to avoid manipulating the cgroup
data on copy.

[1]: https://lore.kernel.org/lkml/[email protected]/

Signed-off-by: Sargun Dhillon <[email protected]>
Suggested-by: Kees Cook <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Christian Brauner <[email protected]>
Cc: Daniel Wagner <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Jann Horn <[email protected]>
Cc: John Fastabend <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Tycho Andersen <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
---
 kernel/pid.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/kernel/pid.c b/kernel/pid.c
index c835b844aca7..1642cf940aa1 100644
--- a/kernel/pid.c
+++ b/kernel/pid.c
@@ -606,7 +606,7 @@ static int pidfd_getfd(struct pid *pid, int fd)
 {
        struct task_struct *task;
        struct file *file;
-       int ret;
+       int ret, err;
 
        task = get_pid_task(pid, PIDTYPE_PID);
        if (!task)
@@ -617,18 +617,16 @@ static int pidfd_getfd(struct pid *pid, int fd)
        if (IS_ERR(file))
                return PTR_ERR(file);
 
-       ret = security_file_receive(file);
-       if (ret) {
-               fput(file);
-               return ret;
-       }
-
        ret = get_unused_fd_flags(O_CLOEXEC);
-       if (ret < 0)
-               fput(file);
-       else
-               fd_install(ret, file);
+       if (ret >= 0) {
+               err = file_receive(ret, file);
+               if (err) {
+                       put_unused_fd(ret);
+                       ret = err;
+               }
+       }
 
+       fput(file);
        return ret;
 }
 
-- 
2.25.1

Reply via email to