Introduce old redir program
[lcapit-junk-code.git] / linux-kernel / netlink / tiny-to-user / netlink-tiny-tu.c
blob7822992739caec007f4585368cbaf60551c85edb
1 /*
2 * netlink-tiny-tu: Send a netlink message to user-space after
3 * NETLINK_TINY_DELAY seconds the module has been loaded.
4 *
5 * Luiz Fernando N. Capitulino
6 * <lcapitulino@gmail.com>
7 */
8 #include <linux/kernel.h>
9 #include <linux/module.h>
10 #include <linux/init.h>
11 #include <linux/string.h>
12 #include <linux/mutex.h>
13 #include <linux/net.h>
14 #include <linux/skbuff.h>
15 #include <linux/netlink.h>
16 #include <linux/timer.h>
17 #include <net/sock.h>
19 #define NETLINK_TINY_TU 20 // always check whether this is safe
20 #define TINY_TY_GRP 1
21 #define LOG_PREFIX "KNETLINK_TINY_TU: "
22 #define NETLINK_TINY_DELAY (HZ * 7) // seven seconds
24 #define UNUSED(x) (x = x)
26 static struct sock *nl;
27 static struct timer_list netlink_tiny_timer;
29 static int send_message(const char *message)
31 size_t len;
32 struct sk_buff *skb;
33 struct nlmsghdr *nlh;
35 len = NLMSG_SPACE(strlen(message) + 1);
36 skb = alloc_skb(len, GFP_ATOMIC);
37 if (!skb) {
38 printk(KERN_ERR LOG_PREFIX "cannot allocate memory\n");
39 return -ENOMEM;
42 nlh = NLMSG_PUT(skb, 0, 0, 0, len - sizeof(*nlh));
43 strcpy(NLMSG_DATA(nlh), message);
45 NETLINK_CB(skb).pid = 0; /* from kernel */
46 NETLINK_CB(skb).dst_group = TINY_TY_GRP; /* group */
48 netlink_broadcast(nl, skb, 0, TINY_TY_GRP, GFP_ATOMIC);
50 return 0;
52 nlmsg_failure:
53 kfree_skb(skb);
54 return -EINVAL;
57 static void netlink_tiny_timer_handler(unsigned long data)
59 int err;
61 UNUSED(data);
63 err = send_message("Hello, world!");
64 if (err)
65 printk(KERN_ERR LOG_PREFIX "could not send message\n");
67 printk(LOG_PREFIX "message sent!");
70 static void __init netlink_tiny_timer_init(void)
72 init_timer(&netlink_tiny_timer);
73 netlink_tiny_timer.function = netlink_tiny_timer_handler;
74 netlink_tiny_timer.expires = jiffies + NETLINK_TINY_DELAY;
75 add_timer(&netlink_tiny_timer);
78 static int __init netlink_tiny_tu_init(void)
80 nl = netlink_kernel_create(&init_net, NETLINK_TINY_TU, TINY_TY_GRP,
81 NULL, NULL, THIS_MODULE);
82 if (!nl) {
83 printk(KERN_ERR LOG_PREFIX "cannot create socket\n");
84 return -EINVAL;
87 netlink_tiny_timer_init();
89 return 0;
92 static void __exit netlink_tiny_tu_exit(void)
94 sock_release(nl->sk_socket);
97 module_init(netlink_tiny_tu_init);
98 module_exit(netlink_tiny_tu_exit);
100 MODULE_LICENSE("GPL");
101 MODULE_AUTHOR("Luiz Capitulino <lcapitulino@gmail.com>");
102 MODULE_DESCRIPTION("Netlink (to user-space) example module");