Introduce old redir program
[lcapit-junk-code.git] / linux-kernel / netlink / echo / netlink-echo.c
blobdee44ff1bb3f471a950c03311234d30df2bd3839
1 /*
2 * netlink-echo: Receives a string from user-space and echoes it back.
3 * It's just yet another netlink usage example.
4 *
5 * FIXME: I don't whether it's ok to call netlink_unicast() from
6 * netlink_echo_input().
7 *
8 * Luiz Fernando N. Capitulino
9 * <lcapitulino@gmail.com>
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/string.h>
15 #include <linux/mutex.h>
16 #include <linux/net.h>
17 #include <linux/skbuff.h>
18 #include <linux/netlink.h>
19 #include <net/sock.h>
21 #define NETLINK_ECHO 20 // always check whether this is safe
23 static struct sock *nl;
24 static DEFINE_MUTEX(netlink_echo_mutex);
26 static void send_packet(int pid, const char *message)
28 size_t len;
29 struct sk_buff *skb;
30 struct nlmsghdr *nlh;
32 len = NLMSG_SPACE(strlen(message) + 1);
33 skb = alloc_skb(len, GFP_ATOMIC);
34 if (!skb) {
35 printk(KERN_ERR "[netlink_echo]: cannot allocate memory\n");
36 return;
39 nlh = NLMSG_PUT(skb, 0, 0, 0, len - sizeof(*nlh));
40 strcpy(NLMSG_DATA(nlh), message);
42 NETLINK_CB(skb).pid = 0; /* from kernel */
43 NETLINK_CB(skb).dst_group = 0; /* unicast */
44 netlink_unicast(nl, skb, pid, GFP_ATOMIC);
46 return;
48 nlmsg_failure:
49 kfree_skb(skb);
52 static void netlink_echo_input(struct sk_buff *skb)
54 char *msg;
55 struct nlmsghdr *nlh;
57 mutex_lock(&netlink_echo_mutex);
59 if (skb->len < sizeof(*nlh))
60 return;
62 nlh = nlmsg_hdr(skb);
63 msg = NLMSG_DATA(nlh);
64 send_packet(nlh->nlmsg_pid, msg);
66 mutex_unlock(&netlink_echo_mutex);
69 static int __init netlink_echo_init(void)
71 nl = netlink_kernel_create(&init_net, NETLINK_ECHO, 0,
72 netlink_echo_input, NULL, THIS_MODULE);
73 if (!nl) {
74 printk(KERN_ERR "[netlink_echo]: cannot create socket\n");
75 return -EINVAL;
78 return 0;
81 static void __exit netlink_echo_exit(void)
83 sock_release(nl->sk_socket);
86 module_init(netlink_echo_init);
87 module_exit(netlink_echo_exit);
89 MODULE_LICENSE("GPL");
90 MODULE_AUTHOR("Luiz Capitulino <lcapitulino@gmail.com>");
91 MODULE_DESCRIPTION("Netlink example module");