Linux 4.19.133
[linux/fpc-iii.git] / net / bpfilter / bpfilter_kern.c
blob450b257afa84d22fc52333f1e6aee56455d80f64
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3 #include <linux/init.h>
4 #include <linux/module.h>
5 #include <linux/umh.h>
6 #include <linux/bpfilter.h>
7 #include <linux/sched.h>
8 #include <linux/sched/signal.h>
9 #include <linux/fs.h>
10 #include <linux/file.h>
11 #include "msgfmt.h"
13 extern char bpfilter_umh_start;
14 extern char bpfilter_umh_end;
16 static struct umh_info info;
17 /* since ip_getsockopt() can run in parallel, serialize access to umh */
18 static DEFINE_MUTEX(bpfilter_lock);
20 static void shutdown_umh(struct umh_info *info)
22 struct task_struct *tsk;
24 if (!info->pid)
25 return;
26 tsk = get_pid_task(find_vpid(info->pid), PIDTYPE_PID);
27 if (tsk) {
28 send_sig(SIGKILL, tsk, 1);
29 put_task_struct(tsk);
31 fput(info->pipe_to_umh);
32 fput(info->pipe_from_umh);
33 info->pid = 0;
36 static void __stop_umh(void)
38 if (IS_ENABLED(CONFIG_INET)) {
39 bpfilter_process_sockopt = NULL;
40 shutdown_umh(&info);
44 static void stop_umh(void)
46 mutex_lock(&bpfilter_lock);
47 __stop_umh();
48 mutex_unlock(&bpfilter_lock);
51 static int __bpfilter_process_sockopt(struct sock *sk, int optname,
52 char __user *optval,
53 unsigned int optlen, bool is_set)
55 struct mbox_request req;
56 struct mbox_reply reply;
57 loff_t pos;
58 ssize_t n;
59 int ret = -EFAULT;
61 req.is_set = is_set;
62 req.pid = current->pid;
63 req.cmd = optname;
64 req.addr = (long __force __user)optval;
65 req.len = optlen;
66 mutex_lock(&bpfilter_lock);
67 if (!info.pid)
68 goto out;
69 n = __kernel_write(info.pipe_to_umh, &req, sizeof(req), &pos);
70 if (n != sizeof(req)) {
71 pr_err("write fail %zd\n", n);
72 __stop_umh();
73 ret = -EFAULT;
74 goto out;
76 pos = 0;
77 n = kernel_read(info.pipe_from_umh, &reply, sizeof(reply), &pos);
78 if (n != sizeof(reply)) {
79 pr_err("read fail %zd\n", n);
80 __stop_umh();
81 ret = -EFAULT;
82 goto out;
84 ret = reply.status;
85 out:
86 mutex_unlock(&bpfilter_lock);
87 return ret;
90 static int __init load_umh(void)
92 int err;
94 /* fork usermode process */
95 err = fork_usermode_blob(&bpfilter_umh_start,
96 &bpfilter_umh_end - &bpfilter_umh_start,
97 &info);
98 if (err)
99 return err;
100 pr_info("Loaded bpfilter_umh pid %d\n", info.pid);
102 /* health check that usermode process started correctly */
103 if (__bpfilter_process_sockopt(NULL, 0, NULL, 0, 0) != 0) {
104 stop_umh();
105 return -EFAULT;
107 if (IS_ENABLED(CONFIG_INET))
108 bpfilter_process_sockopt = &__bpfilter_process_sockopt;
110 return 0;
113 static void __exit fini_umh(void)
115 stop_umh();
117 module_init(load_umh);
118 module_exit(fini_umh);
119 MODULE_LICENSE("GPL");