netlink.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. https://en.wikipedia.org/wiki/Netlink
  3. https://stackoverflow.com/questions/3299386/how-to-use-netlink-socket-to-communicate-with-a-kernel-module
  4. */
  5. #include <linux/delay.h> /* usleep_range */
  6. #include <linux/jiffies.h>
  7. #include <linux/module.h>
  8. #include <linux/netlink.h>
  9. #include <linux/skbuff.h>
  10. #include <net/sock.h>
  11. /* Socket identifier, matches userland. TODO can be anything?
  12. * Is there a more scalable way to do it? E.g. ioctl device,
  13. * kernel generates one on the fly, then give it back and connect?
  14. * https://stackoverflow.com/questions/32898173/can-i-have-more-than-32-netlink-sockets-in-kernelspace */
  15. #define NETLINK_USER 31
  16. struct sock *nl_sk = NULL;
  17. static void callback(struct sk_buff *skb)
  18. {
  19. char readbuf[1024];
  20. size_t readbuflen;
  21. int pid;
  22. int res;
  23. struct nlmsghdr *nlh;
  24. struct sk_buff *skb_out;
  25. /* Read user message. */
  26. nlh = (struct nlmsghdr *)skb->data;
  27. pr_info("kernel received: %s\n", (char *)nlmsg_data(nlh));
  28. /* Add an artificial sleep to see what happens when
  29. * multiple requests come in at the same time.
  30. *
  31. * Try this out (it works):
  32. * for i in `seq 16`; do /netlink.out & done */
  33. usleep_range(1000000, 1000001);
  34. /* Reply with jiffies. */
  35. readbuflen = snprintf(readbuf, sizeof(readbuf), "%llu", (unsigned long long)jiffies);
  36. pid = nlh->nlmsg_pid;
  37. skb_out = nlmsg_new(readbuflen, 0);
  38. if (!skb_out) {
  39. pr_err("nlmsg_new\n");
  40. return;
  41. }
  42. nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, readbuflen, 0);
  43. NETLINK_CB(skb_out).dst_group = 0;
  44. strncpy(nlmsg_data(nlh), readbuf, readbuflen);
  45. res = nlmsg_unicast(nl_sk, skb_out, pid);
  46. if (res < 0)
  47. pr_info("nlmsg_unicast\n");
  48. }
  49. static int myinit(void)
  50. {
  51. struct netlink_kernel_cfg cfg = {
  52. .input = callback,
  53. };
  54. nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
  55. if (!nl_sk) {
  56. pr_err("netlink_kernel_create\n");
  57. return -10;
  58. }
  59. return 0;
  60. }
  61. static void myexit(void)
  62. {
  63. netlink_kernel_release(nl_sk);
  64. }
  65. module_init(myinit);
  66. module_exit(myexit);
  67. MODULE_LICENSE("GPL");