如何使用 netlink 套接字与内核模块通信? [英] How to use netlink socket to communicate with a kernel module?

查看:19
本文介绍了如何使用 netlink 套接字与内核模块通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用 netlink 与用户进程通信的 linux 内核模块.我正在使用 netlink,因为我想与之通信的用户程序仅使用套接字进行通信,我无法更改它以添加 ioctl() 或任何东西.

问题是我不知道如何做到这一点.我用谷歌搜索过,但我发现的所有例子都是旧的,比如 this one 并且不再适用于当前内核版本.我也看过this SO question 但是此处的示例使用 libnl 进行套接字操作,但我想坚持使用标准套接字函数(由sys/socket.h).所以有人可以在这里指导我一些教程或指南或一些可以帮助我理解 netlink 的界面和用法的东西.我非常感谢一个工作示例,没什么特别的,只是一个非常基本的示例,说明如何建立从用户程序中的套接字到内核中的套接字的连接,然后将数据从用户进程发送到内核并从内核接收.

另外请不要告诉我看内核代码.我已经在做,但需要很多时间,而且我所剩的不多.

更新:经过大量试验和错误,我有以下代码从用户程序向内核发送消息,但从内核到用户程序的消息,即使用 netlink_unicast() 不起作用.它不仅不工作,呼叫挂起系统,然后我必须重新启动机器.有人可以看看并告诉我我在做什么错.netlink_unicast() 调用在以下代码中进行了注释.内核到用户程序消息应该取消注释.

用户程序

#include #include #define NETLINK_USER 31#define MAX_PAYLOAD 1024/* 最大有效载荷大小*/结构 sockaddr_nl src_addr, dest_addr;结构 nlmsghdr *nlh = NULL;结构 iovec iov;int sock_fd;struct msghdr msg;无效主(){sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);如果(袜子_fd<0)返回-1;memset(&src_addr, 0, sizeof(src_addr));src_addr.nl_family = AF_NETLINK;src_addr.nl_pid = getpid();/* 自 pid *//* 对组 1<<0 感兴趣 */绑定(sock_fd, (struct sockaddr*)&src_addr,sizeof(src_addr));memset(&dest_addr, 0, sizeof(dest_addr));memset(&dest_addr, 0, sizeof(dest_addr));dest_addr.nl_family = AF_NETLINK;dest_addr.nl_pid = 0;/* 对于 Linux 内核 */dest_addr.nl_groups = 0;/* 单播 */nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);nlh->nlmsg_pid = getpid();nlh->nlmsg_flags = 0;strcpy(NLMSG_DATA(nlh),你好");iov.iov_base = (void *)nlh;iov.iov_len = nlh->nlmsg_len;msg.msg_name = (void *)&dest_addr;msg.msg_namelen = sizeof(dest_addr);msg.msg_iov = &iov;msg.msg_iovlen = 1;printf("向内核发送消息
");sendmsg(sock_fd,&msg,0);printf("正在等待来自内核的消息
");/* 从内核读取消息 */recvmsg(sock_fd, &msg, 0);printf("接收到的消息负载:%s
",NLMSG_DATA(nlh));关闭(袜子_fd);}

内核代码

#include #include #include #include #include #include #include #include #include #define NETLINK_USER 31结构袜 *nl_sk = NULL;静态无效 hello_nl_recv_msg(struct sk_buff *skb){结构 nlmsghdr *nlh;int pid;printk(KERN_INFO "输入:%s
", __FUNCTION__);nlh=(struct nlmsghdr*)skb->数据;printk(KERN_INFO "Netlink 收到 msg 负载:%s
",(char*)NLMSG_DATA(nlh));pid = nlh->nlmsg_pid;/*发送进程的pid */NETLINK_CB(skb).dst_group = 0;/* 不在 mcast 组中 */NETLINK_CB(skb).pid = 0;/* 从内核 *///NETLINK_CB(skb).groups = 0;/* 不在 mcast 组中 *///NETLINK_CB(skb).dst_pid = pid;printk("即将发送 msg bak:
");//netlink_unicast(nl_sk,skb,pid,MSG_DONTWAIT);}静态 int __init hello_init(void){printk("输入:%s
",__FUNCTION__);nl_sk=netlink_kernel_create(&init_net, NETLINK_USER, 0,hello_nl_recv_msg, NULL, THIS_MODULE);如果(!nl_sk){printk(KERN_ALERT "创建套接字时出错.
");返回-10;}返回0;}静态无效 __exit hello_exit(void){printk(KERN_INFO "退出 hello 模块
");netlink_kernel_release(nl_sk);}模块初始化(hello_init);模块退出(你好退出);

解决方案

在阅读内核源代码后,我终于设法让 netlink 套接字为我工作.下面是一个 Netlink 套接字基础的例子,即打开一个 netlink 套接字,读取和写入它,然后关闭它.

内核模块

#include #include #include #include #define NETLINK_USER 31结构袜 *nl_sk = NULL;静态无效 hello_nl_recv_msg(struct sk_buff *skb){结构 nlmsghdr *nlh;int pid;结构 sk_buff *skb_out;int msg_size;char *msg = "来自内核的你好";内部资源;printk(KERN_INFO "输入:%s
", __FUNCTION__);msg_size = strlen(msg);nlh = (struct nlmsghdr *)skb->数据;printk(KERN_INFO "Netlink 收到 msg 负载:%s
", (char *)nlmsg_data(nlh));pid = nlh->nlmsg_pid;/*发送进程的pid */skb_out = nlmsg_new(msg_size, 0);如果(!skb_out){printk(KERN_ERR "无法分配新的 skb
");返回;}nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, msg_size, 0);NETLINK_CB(skb_out).dst_group = 0;/* 不在 mcast 组中 */strncpy(nlmsg_data(nlh), msg, msg_size);res = nlmsg_unicast(nl_sk, skb_out, pid);如果 (res <0)printk(KERN_INFO "向用户发送 bak 时出错
");}静态 int __init hello_init(void){printk("输入:%s
", __FUNCTION__);//nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg, NULL, THIS_MODULE);struct netlink_kernel_cfg cfg = {.input = hello_nl_recv_msg,};nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);如果(!nl_sk){printk(KERN_ALERT "创建套接字时出错.
");返回-10;}返回0;}静态无效 __exit hello_exit(void){printk(KERN_INFO "退出 hello 模块
");netlink_kernel_release(nl_sk);}模块初始化(hello_init);模块退出(你好退出);MODULE_LICENSE("GPL");

用户程序

#include #include #include #include #include #include #define NETLINK_USER 31#define MAX_PAYLOAD 1024/* 最大有效载荷大小*/结构 sockaddr_nl src_addr, dest_addr;结构 nlmsghdr *nlh = NULL;结构 iovec iov;int sock_fd;struct msghdr msg;int main(){sock_fd = 套接字(PF_NETLINK,SOCK_RAW,NETLINK_USER);如果 (sock_fd <0)返回-1;memset(&src_addr, 0, sizeof(src_addr));src_addr.nl_family = AF_NETLINK;src_addr.nl_pid = getpid();/* 自 pid */绑定(sock_fd, (struct sockaddr *)&src_addr, sizeof(src_addr));memset(&dest_addr, 0, sizeof(dest_addr));dest_addr.nl_family = AF_NETLINK;dest_addr.nl_pid = 0;/* 对于 Linux 内核 */dest_addr.nl_groups = 0;/* 单播 */nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);nlh->nlmsg_pid = getpid();nlh->nlmsg_flags = 0;strcpy(NLMSG_DATA(nlh),你好");iov.iov_base = (void *)nlh;iov.iov_len = nlh->nlmsg_len;msg.msg_name = (void *)&dest_addr;msg.msg_namelen = sizeof(dest_addr);msg.msg_iov = &iov;msg.msg_iovlen = 1;printf("向内核发送消息
");sendmsg(sock_fd, &msg, 0);printf("正在等待来自内核的消息
");/* 从内核读取消息 */recvmsg(sock_fd, &msg, 0);printf("接收到的消息负载:%s
", NLMSG_DATA(nlh));关闭(袜子_fd);}

关于魔法常量NETLINK_USER 31的相关线程:内核空间中可以有超过 32 个 netlink 套接字吗?

I am trying to write a linux kernel module that communicates with user process using netlink. I am using netlink because the user program I want to communicate to communicates only using sockets and I cant change that to add ioctl() or anything.

Problem is that I cant figure out how to do that. I have googled but all examples I found are for old like this one and no longer valid for current kernel versions. I have also looked at this SO question but the sample here uses libnl for socket operations but I want to stick to standard socket functions (defined by sys/socket.h). So can some one plz guide me here to some tutorial or guide or some thing that can help me understand the interface and usage of netlink. I would highly appreciate a working example, nothing fancy, just a very basic example of how to establish a connection from a socket in user program to a socket in kernel and then send data from user process to kernel and receive back from kernel.

Also please do not tell me to look at kernel code. I am already doing it but it will take a lot of time and I dont have lot of it left.

Update: After lot of trial and error I have following code which sends message from user program to kernel but the message from kernel to user program i.e using netlink_unicast() is not working. Its not only not working, the call hangs the systems and then I have to restart the machine. Can some one plz take a look and tell me what wrong I am doing. The netlink_unicast() call is commented in the following code. It should be uncommented for kernel to user program message.

User Program

#include <sys/socket.h>  
#include <linux/netlink.h>  
#define NETLINK_USER 31  
#define MAX_PAYLOAD 1024  /* maximum payload size*/  

struct sockaddr_nl src_addr, dest_addr;  
struct nlmsghdr *nlh = NULL;  
struct iovec iov;  
int sock_fd;  
struct msghdr msg;  

void main()  
{  
    sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);  
    if(sock_fd<0)  
        return -1;  

    memset(&src_addr, 0, sizeof(src_addr));  
    src_addr.nl_family = AF_NETLINK;  
    src_addr.nl_pid = getpid();  /* self pid */  
    /* interested in group 1<<0 */  
    bind(sock_fd, (struct sockaddr*)&src_addr,  
      sizeof(src_addr));  

    memset(&dest_addr, 0, sizeof(dest_addr));  
    memset(&dest_addr, 0, sizeof(dest_addr));  
    dest_addr.nl_family = AF_NETLINK;  
    dest_addr.nl_pid = 0;   /* For Linux Kernel */  
    dest_addr.nl_groups = 0; /* unicast */  

    nlh = (struct nlmsghdr *)malloc(  
                          NLMSG_SPACE(MAX_PAYLOAD));  
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));  
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);  
    nlh->nlmsg_pid = getpid();  
    nlh->nlmsg_flags = 0;  

    strcpy(NLMSG_DATA(nlh), "Hello");  

    iov.iov_base = (void *)nlh;  
    iov.iov_len = nlh->nlmsg_len;  
    msg.msg_name = (void *)&dest_addr;  
    msg.msg_namelen = sizeof(dest_addr);  
    msg.msg_iov = &iov;  
    msg.msg_iovlen = 1;  

    printf("Sending message to kernel
");  
    sendmsg(sock_fd,&msg,0);  
    printf("Waiting for message from kernel
");  

    /* Read message from kernel */  
    recvmsg(sock_fd, &msg, 0);  
    printf(" Received message payload: %s
",  
        NLMSG_DATA(nlh));  
    close(sock_fd);  
}

Kernel Code

#include <linux/module.h>  
#include <linux/kernel.h>  
#include <linux/init.h>  
#include <net/sock.h>  
#include <linux/socket.h>  
#include <linux/net.h>  
#include <asm/types.h>  
#include <linux/netlink.h>  
#include <linux/skbuff.h>  

#define NETLINK_USER 31  

struct sock *nl_sk = NULL;  

static void hello_nl_recv_msg(struct sk_buff *skb)  
{
        struct nlmsghdr *nlh;  
        int pid;  

        printk(KERN_INFO "Entering: %s
", __FUNCTION__);  

        nlh=(struct nlmsghdr*)skb->data;  
        printk(KERN_INFO "Netlink received msg payload: %s
",
            (char*)NLMSG_DATA(nlh));  
        pid = nlh->nlmsg_pid; /*pid of sending process */  
        NETLINK_CB(skb).dst_group = 0; /* not in mcast group */  
        NETLINK_CB(skb).pid = 0;      /* from kernel */  
        //NETLINK_CB(skb).groups = 0; /* not in mcast group */  
        //NETLINK_CB(skb).dst_pid = pid;  
        printk("About to send msg bak:
");  
        //netlink_unicast(nl_sk,skb,pid,MSG_DONTWAIT);  

}  

static int __init hello_init(void)  
{  

        printk("Entering: %s
",__FUNCTION__);  
        nl_sk=netlink_kernel_create(&init_net, NETLINK_USER, 0,
               hello_nl_recv_msg, NULL, THIS_MODULE);  
        if(!nl_sk)  
        {   
                printk(KERN_ALERT "Error creating socket.
");  
                return -10;  
        }  
        return 0;  
}  

static void __exit hello_exit(void)  
{

        printk(KERN_INFO "exiting hello module
");  
        netlink_kernel_release(nl_sk);  
}  

module_init(hello_init);  
module_exit(hello_exit);  

解决方案

After reading kernel source I finally managed to make netlink sockets work for me. Below is an example of Netlink socket basics i.e opening a netlink socket, reading and writing to it and closing it.

Kernel Module

#include <linux/module.h>
#include <net/sock.h> 
#include <linux/netlink.h>
#include <linux/skbuff.h> 
#define NETLINK_USER 31

struct sock *nl_sk = NULL;

static void hello_nl_recv_msg(struct sk_buff *skb)
{

    struct nlmsghdr *nlh;
    int pid;
    struct sk_buff *skb_out;
    int msg_size;
    char *msg = "Hello from kernel";
    int res;

    printk(KERN_INFO "Entering: %s
", __FUNCTION__);

    msg_size = strlen(msg);

    nlh = (struct nlmsghdr *)skb->data;
    printk(KERN_INFO "Netlink received msg payload:%s
", (char *)nlmsg_data(nlh));
    pid = nlh->nlmsg_pid; /*pid of sending process */

    skb_out = nlmsg_new(msg_size, 0);
    if (!skb_out) {
        printk(KERN_ERR "Failed to allocate new skb
");
        return;
    }

    nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, msg_size, 0);
    NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
    strncpy(nlmsg_data(nlh), msg, msg_size);

    res = nlmsg_unicast(nl_sk, skb_out, pid);
    if (res < 0)
        printk(KERN_INFO "Error while sending bak to user
");
}

static int __init hello_init(void)
{

    printk("Entering: %s
", __FUNCTION__);
    //nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg, NULL, THIS_MODULE);
    struct netlink_kernel_cfg cfg = {
        .input = hello_nl_recv_msg,
    };

    nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
    if (!nl_sk) {
        printk(KERN_ALERT "Error creating socket.
");
        return -10;
    }

    return 0;
}

static void __exit hello_exit(void)
{

    printk(KERN_INFO "exiting hello module
");
    netlink_kernel_release(nl_sk);
}

module_init(hello_init); module_exit(hello_exit);

MODULE_LICENSE("GPL");

User Program

#include <linux/netlink.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define NETLINK_USER 31

#define MAX_PAYLOAD 1024 /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
int sock_fd;
struct msghdr msg;

int main()
{
    sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);
    if (sock_fd < 0)
        return -1;

    memset(&src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid(); /* self pid */

    bind(sock_fd, (struct sockaddr *)&src_addr, sizeof(src_addr));

    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0; /* For Linux Kernel */
    dest_addr.nl_groups = 0; /* unicast */

    nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
    nlh->nlmsg_pid = getpid();
    nlh->nlmsg_flags = 0;

    strcpy(NLMSG_DATA(nlh), "Hello");

    iov.iov_base = (void *)nlh;
    iov.iov_len = nlh->nlmsg_len;
    msg.msg_name = (void *)&dest_addr;
    msg.msg_namelen = sizeof(dest_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    printf("Sending message to kernel
");
    sendmsg(sock_fd, &msg, 0);
    printf("Waiting for message from kernel
");

    /* Read message from kernel */
    recvmsg(sock_fd, &msg, 0);
    printf("Received message payload: %s
", NLMSG_DATA(nlh));
    close(sock_fd);
}

Related thread about the magic constant NETLINK_USER 31: Can I have more than 32 netlink sockets in kernelspace?

这篇关于如何使用 netlink 套接字与内核模块通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆