概述
hostapd的ctrl i/f(control interface,控制接口)模块主要作用是为外部程序(如命令行工具hostapd_cli、GUI等)提供与hostapd守护进程进行交互的机制,实现运行时控制和状态查询
对应源代码
ctrl if模块对应源代码是./hostapd/ctrl_iface.c和./hostapd/ctrl_iface.h
hostapd主进程
配置句柄
hostapd通信时采用的方法是通过文件句柄来进行通信,句柄会存储在hostapd.conf中的ctrl_interface配置选项中,在读取配置文件时会将这个字段存入struct hostapd_bss_config中的ctrl_interface字段中用于后续的使用
在./hostapd/hostapd.conf中可以找到相关的注释
# Interface for separate control program. If this is specified, hostapd
# will create this directory and a UNIX domain socket for listening to requests
# from external programs (CLI/GUI, etc.) for status information and
# configuration. The socket file will be named based on the interface name, so
# multiple hostapd processes/interfaces can be run at the same time if more
# than one interface is used.
# /var/run/hostapd is the recommended directory for sockets and by default,
# hostapd_cli will use it when trying to connect with hostapd.
ctrl_interface=/var/run/hostapd
通信使用的句柄会在hostapd_ctrl_iface_path函数中拼接而成
static char * hostapd_ctrl_iface_path(struct hostapd_data *hapd)
{
char *buf;
size_t len;
if (hapd->conf->ctrl_interface == NULL)
return NULL;
len = os_strlen(hapd->conf->ctrl_interface) +
os_strlen(hapd->conf->iface) + 2;
buf = os_malloc(len);
if (buf == NULL)
return NULL;
os_snprintf(buf, len, "%s/%s",
hapd->conf->ctrl_interface, hapd->conf->iface);
buf[len - 1] = '\0';
return buf;
}
这里的hapd->conf->ctrl_interface是对应配置文件中的ctrl_interface,hapd->conf->iface是对应配置文件中的interface选项
在配置句柄之后会通过eloop_register_read_sock函数来对其进行监听,同时配置对应回调hostapd_ctrl_iface_receive用来处理socket中的消息
使用命令
在启动hostapd主进程之后,输入
sudo ./hostapd_cli -i wlan0 help
-i指定端口,help查看使用帮助
hostapd_cli侧
在hostapd_cli的中会使用一个全局变量static struct wpa_ctrl *ctrl_conn来存储待使用的socket
初始化句柄
hostapd_cli在与hostapd的主进程进行通信时是作为client端,在创建与主进程通信的socket时。
- 使用
bind函数将socket绑定本地的一个随机文件 - 使用
connet将socket的目标句柄,这个目标是全局变量CONFIG_CTRL_IFACE_DIR中存储与主进程通信使用的句柄的路径,传入端口比如wlan0,然后将两者进行拼接 - 目标句柄在主进程中也会使用,区别是主进程是读取配置文件获取文件路径

处理用户命令
hostapd_cli内部维护了一个全局的结构体数组,存储支持的命令和对应的回调函数。在接收到命令后会首先在数组中找到对应的回调然后调用,最后使用wpa_ctrl_command接口来发送和接收数据

发送和接收数据
数据的发送和接收使用的时之前创建的socket句柄,发送后使用select监听句柄,并对需要主动处理的事件调用注册好的hostapd_cli_msg_cb进行处理

整体流程
