源码:bluez_4.66.orig.tar.gz
编译
编译bluez-4.66时,在configure时,遇到如下dbus错误:
configure: error: D-Bus library is required
解决方法:
sudo apt-get install libdbus-1-dev libdbus-glib-1-dev
make -j4
最终产生bluetoothd,在src/.libs/目录下。
运行
在ubuntu下,系统启动时默认已经启动里了bluetoothd,只是这个bluetoothd位于/usr/sbin/下。我们可以用killall -9 bluetoothd将默认启动的bluetoothd干掉,然后手动
启动我们自己编译的bluetoothd,经检验,自己编译的bluetoothd也是可以配合运行的,基本配对传文件功能也正常。
我们用./bluetoothd -h查看bluetoothd运行命令,结果如下:
Usage:
bluetoothd [OPTION...]
Help Options:
-h, --help Show help options
Application Options:
-n, --nodaemon Don't run as daemon in background
-d, --debug=DEBUG Enable debug information output
-u, --udev Run from udev mode of operation
最简单的情况下,我们用sudo ./bluetoothd去启动bluetoothd程序。用sudo的原因就不需要讲了,因为程序本身用到里很多root权限。我们用这个命令启动后,发现程序马上
就进入后台运行了。在看上面help出来的结果,在后面加上-n参数,这时候发现程序在控制台运行,并且可以用ctrl+c终止程序。这里我主要是为了调试蓝牙模块,所以用
控制台跑程序,以便打印一些我要的信息。其他两个参数后面在研究。
代码解析
代码解析之:start_sdp_server(mtu, main_opts.deviceid, SDP_SERVER_COMPAT);
此部分代码在sdpd-server.c文件中,函数如下:
int start_sdp_server(uint16_t mtu, const char *did, uint32_t flags)
{
int compat = flags & SDP_SERVER_COMPAT;
int master = flags & SDP_SERVER_MASTER;
info("Starting SDP server");
if (init_server(mtu, master, compat) < 0) {
error("Server initialization failed");
return -1;
}
if (did && strlen(did) > 0) {
const char *ptr = did;
uint16_t vid = 0x0000, pid = 0x0000, ver = 0x0000;
vid = (uint16_t) strtol(ptr, NULL, 16);
ptr = strchr(ptr, ':');
if (ptr) {
pid = (uint16_t) strtol(ptr + 1, NULL, 16);
ptr = strchr(ptr + 1, ':');
if (ptr)
ver = (uint16_t) strtol(ptr + 1, NULL, 16);
register_device_id(vid, pid, ver);
}
}
//create a channel according to socket, just like create a port according to the socket
//then add io_accept_event func listen to the channel if there are someone connect to
//the channel, just like we create a port on linux, then we will listen to the port because
//there maybe someone connect to the port, here we act as a server.
l2cap_io = g_io_channel_unix_new(l2cap_sock);
g_io_channel_set_close_on_unref(l2cap_io, TRUE);
g_io_add_watch(l2cap_io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
io_accept_event, &l2cap_sock);
if (compat && unix_sock > fileno(stderr)) {
unix_io = g_io_channel_unix_new(unix_sock);
g_io_channel_set_close_on_unref(unix_io, TRUE);
g_io_add_watch(unix_io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
io_accept_event, &unix_sock);
}
return 0;
}
这个函数在最后创建里l2cap_io,并用io_accept_event接口侦听此channel。这里我的理解就类似于linux下我们创建端口port后,会用listen接口去侦听创建的端口,这样
一旦有client连接上来,我们就可以用accept接口去接受连接。这里我觉得应该原理相同,这里无非是用glib库实现而已。
接下来看io_accept_event这个接口:
static gboolean io_accept_event(GIOChannel *chan, GIOCondition cond, gpointer data)
{
GIOChannel *io;
int nsk;
if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
g_io_channel_unref(chan);
return FALSE;
}
if (data == &l2cap_sock) {
struct sockaddr_l2 addr;
socklen_t len = sizeof(addr);
nsk = accept(l2cap_sock, (struct sockaddr *) &addr, &len);
} else if (data == &unix_sock) {
struct sockaddr_un addr;
socklen_t len = sizeof(addr);
nsk = accept(unix_sock, (struct sockaddr *) &addr, &len);
} else
return FALSE;
if (nsk < 0) {
error("Can't accept connection: %s", strerror(errno));
return TRUE;
}
//here we accept the connect from client, and then generate a new socket, the new socket
//is for really data transfer, and here we can see we use io_session_event func to deal with
//the new socket for processing the coming data.
io = g_io_channel_unix_new(nsk);
g_io_channel_set_close_on_unref(io, TRUE);
g_io_add_watch(io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
io_session_event, data);
g_io_channel_unref(io);
return TRUE;
}
这个接口实现接受client过来的连接,并且为这个连接创建新的socket,这个新创建的socket就是用来为这次连接传输数据的。对这次连接数据的处理函数
为其中注册的io_session_event接口。下面看io_session_event数据处理接口:
static gboolean io_session_event(GIOChannel *chan, GIOCondition cond, gpointer data)
{
sdp_pdu_hdr_t hdr;
uint8_t *buf;
int sk, len, size;
if (cond & G_IO_NVAL)
return FALSE;
sk = g_io_channel_unix_get_fd(chan);
if (cond & (G_IO_HUP | G_IO_ERR)) {
sdp_svcdb_collect_all(sk);
return FALSE;
}
//first receive the sdp pdu hdr, connecting msg i guess
len = recv(sk, &hdr, sizeof(sdp_pdu_hdr_t), MSG_PEEK);
if (len <= 0) {
sdp_svcdb_collect_all(sk);
return FALSE;
}
size = sizeof(sdp_pdu_hdr_t) + ntohs(hdr.plen);
buf = malloc(size);
if (!buf)
return TRUE;
//then receive the real data
len = recv(sk, buf, size, 0);
if (len <= 0) {
sdp_svcdb_collect_all(sk);
free(buf);
return FALSE;
}
//here we will process the data
handle_request(sk, buf, len);
return TRUE;
}
这里首先recv了sdp头结构数据,然后再recv其他数据。我们看到他真正处理的是第二次接收的数据。把数据传送给接口handle_request处理。handle_request接口将上面recv到的数据转化为
typedef struct request {
bdaddr_t device;
bdaddr_t bdaddr;
int local;
int sock;
int mtu;
int flags;
uint8_t *buf;
int len;
} sdp_req_t;
下面看一下process_request这个函数:
static void process_request(sdp_req_t *req)
{
sdp_pdu_hdr_t *reqhdr = (sdp_pdu_hdr_t *)req->buf;
sdp_pdu_hdr_t *rsphdr;
sdp_buf_t rsp;
uint8_t *buf = malloc(USHRT_MAX);
int sent = 0;
int status = SDP_INVALID_SYNTAX;
//prepare the response struct, init the response data
memset(buf, 0, USHRT_MAX);
rsp.data = buf + sizeof(sdp_pdu_hdr_t);
rsp.data_size = 0;
rsp.buf_size = USHRT_MAX - sizeof(sdp_pdu_hdr_t);
rsphdr = (sdp_pdu_hdr_t *)buf;
if (ntohs(reqhdr->plen) != req->len - sizeof(sdp_pdu_hdr_t)) {
status = SDP_INVALID_PDU_SIZE;
goto send_rsp;
}
//here do all kinds of process according to the pdu id
switch (reqhdr->pdu_id) {
case SDP_SVC_SEARCH_REQ:
SDPDBG("Got a svc srch req");
status = service_search_req(req, &rsp);
rsphdr->pdu_id = SDP_SVC_SEARCH_RSP;
break;
case SDP_SVC_ATTR_REQ:
SDPDBG("Got a svc attr req");
status = service_attr_req(req, &rsp);
rsphdr->pdu_id = SDP_SVC_ATTR_RSP;
break;
case SDP_SVC_SEARCH_ATTR_REQ:
SDPDBG("Got a svc srch attr req");
status = service_search_attr_req(req, &rsp);
rsphdr->pdu_id = SDP_SVC_SEARCH_ATTR_RSP;
break;
/* Following requests are allowed only for local connections */
case SDP_SVC_REGISTER_REQ:
SDPDBG("Service register request");
if (req->local) {
status = service_register_req(req, &rsp);
rsphdr->pdu_id = SDP_SVC_REGISTER_RSP;
}
break;
case SDP_SVC_UPDATE_REQ:
SDPDBG("Service update request");
if (req->local) {
status = service_update_req(req, &rsp);
rsphdr->pdu_id = SDP_SVC_UPDATE_RSP;
}
break;
case SDP_SVC_REMOVE_REQ:
SDPDBG("Service removal request");
if (req->local) {
status = service_remove_req(req, &rsp);
rsphdr->pdu_id = SDP_SVC_REMOVE_RSP;
}
break;
default:
error("Unknown PDU ID : 0x%x received", reqhdr->pdu_id);
status = SDP_INVALID_SYNTAX;
break;
}
send_rsp:
//fill in the response data and then send rsp the the client
if (status) {
rsphdr->pdu_id = SDP_ERROR_RSP;
bt_put_unaligned(htons(status), (uint16_t *)rsp.data);
rsp.data_size = sizeof(uint16_t);
}
SDPDBG("Sending rsp. status %d", status);
rsphdr->tid = reqhdr->tid;
rsphdr->plen = htons(rsp.data_size);
/* point back to the real buffer start and set the real rsp length */
rsp.data_size += sizeof(sdp_pdu_hdr_t);
rsp.data = buf;
/* stream the rsp PDU */
sent = send(req->sock, rsp.data, rsp.data_size, 0);
SDPDBG("Bytes Sent : %d", sent);
free(rsp.data);
free(req->buf);
}
这个函数简单明了,首先初始化要返回的数据结构体,然后根据请求做出相应的动作,最后填充完rsp数据并发送给client。这里涉及到的客户端处理请求有以下几种:
/*
* The PDU identifiers of SDP packets between client and server
*/
#define SDP_ERROR_RSP 0x01
#define SDP_SVC_SEARCH_REQ 0x02
#define SDP_SVC_SEARCH_RSP 0x03
#define SDP_SVC_ATTR_REQ 0x04
#define SDP_SVC_ATTR_RSP 0x05
#define SDP_SVC_SEARCH_ATTR_REQ 0x06
#define SDP_SVC_SEARCH_ATTR_RSP 0x07
有搜索请求,属性请求,搜索属性请求。怎么请求会回应在一起定义?今天到这里。。。
代码解析之:plugin_init(config);
此函数定义在当前目录下plugin.c文件里面,主要的工作是将提供的plugins添加到plugins全局链表中,并初始化每个plugins:
gboolean plugin_init(GKeyFile *config)
{
GSList *list;
GDir *dir;
const gchar *file;
gchar **disabled;
unsigned int i;
/* Make a call to BtIO API so its symbols got resolved before the
* plugins are loaded. */
bt_io_error_quark();
if (config)
disabled = g_key_file_get_string_list(config, "General",
"DisablePlugins",
NULL, NULL);
else
disabled = NULL;
DBG("Loading builtin plugins");
//add default plugins, those plugins always need for bluetoothd runing
//those plugins will add to the global link named plugins
for (i = 0; __bluetooth_builtin[i]; i++) {
if (is_disabled(__bluetooth_builtin[i]->name, disabled))
continue;
add_plugin(NULL, __bluetooth_builtin[i]);
}
if (strlen(PLUGINDIR) == 0) {
g_strfreev(disabled);
goto start;
}
DBG("Loading plugins %s", PLUGINDIR);
dir = g_dir_open(PLUGINDIR, 0, NULL);
if (!dir) {
g_strfreev(disabled);
goto start;
}
//add user plugins, those plugins stored in PLUGINDIR path, and the
//PLUGINDIR = /usr/local/lib/bluetooth/plugins. The bluetoothd will
//find all those plugins which name *.so, and open them, get the method
//named bluetooth_plugin_desc, it will also add those plugins to the
//plugins links.
while ((file = g_dir_read_name(dir)) != NULL) {
struct bluetooth_plugin_desc *desc;
void *handle;
gchar *filename;
if (g_str_has_prefix(file, "lib") == TRUE ||
g_str_has_suffix(file, ".so") == FALSE)
continue;
if (is_disabled(file, disabled))
continue;
filename = g_build_filename(PLUGINDIR, file, NULL);
handle = dlopen(filename, RTLD_NOW);
if (handle == NULL) {
error("Can't load plugin %s: %s", filename,
dlerror());
g_free(filename);
continue;
}
g_free(filename);
desc = dlsym(handle, "bluetooth_plugin_desc");
if (desc == NULL) {
error("Can't load plugin description: %s", dlerror());
dlclose(handle);
continue;
}
if (add_plugin(handle, desc) == FALSE)
dlclose(handle);
}
g_dir_close(dir);
g_strfreev(disabled);
start:
//init all of the plugins by calling the plugins init function
for (list = plugins; list; list = list->next) {
struct bluetooth_plugin *plugin = list->data;
if (plugin->desc->init() < 0) {
error("Failed to init %s plugin", plugin->desc->name);
continue;
}
plugin->active = TRUE;
}
return TRUE;
}
可以看到,这个函数执行的最终结果会生成plugins全局链表。从函数中可以看到,它是通过add_plugin()函数将__bluetooth_builtin[]数组中的成员添加到plugins全局变量中的。__bluetooth_builtin具体是什么东西呢?看它的定义,这个数组定义在builtin.h文件中,如下:
extern struct bluetooth_plugin_desc __bluetooth_builtin_audio;
extern struct bluetooth_plugin_desc __bluetooth_builtin_input;
extern struct bluetooth_plugin_desc __bluetooth_builtin_serial;
extern struct bluetooth_plugin_desc __bluetooth_builtin_network;
extern struct bluetooth_plugin_desc __bluetooth_builtin_service;
extern struct bluetooth_plugin_desc __bluetooth_builtin_hciops;
extern struct bluetooth_plugin_desc __bluetooth_builtin_hal;
extern struct bluetooth_plugin_desc __bluetooth_builtin_storage;
static struct bluetooth_plugin_desc *__bluetooth_builtin[] = {
&__bluetooth_builtin_audio,
&__bluetooth_builtin_input,
&__bluetooth_builtin_serial,
&__bluetooth_builtin_network,
&__bluetooth_builtin_service,
&__bluetooth_builtin_hciops,
&__bluetooth_builtin_hal,
&__bluetooth_builtin_storage,
NULL
};
搜索整个代码工程,都无法找到__bluetooth_builtin_audio等等变量的定义。看这些成员都是extern应用,定义肯定在外部。要看看它们具体是怎么定义的,首先要知道如下#define定义: #define中的##使用。在了解里这个定义后,看下其中一个(其他类似)如__bluetooth_builtin_audio,来看一下以下这个文件:audio/main.c。这个文件中最下面有个宏定义:
BLUETOOTH_PLUGIN_DEFINE(audio, VERSION,
BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, audio_init, audio_exit)
这个宏定义在src/plugin.h文件中,如下:
#ifdef BLUETOOTH_PLUGIN_BUILTIN
#define BLUETOOTH_PLUGIN_DEFINE(name, version, priority, init, exit) \
struct bluetooth_plugin_desc __bluetooth_builtin_ ## name = { \
#name, version, priority, init, exit \
};
#else
#define BLUETOOTH_PLUGIN_DEFINE(name, version, priority, init, exit) \
extern struct bluetooth_plugin_desc bluetooth_plugin_desc \
__attribute__ ((visibility("default"))); \
struct bluetooth_plugin_desc bluetooth_plugin_desc = { \
#name, version, priority, init, exit \
};
#endif
根据 #define中的##使用这个语法,可以知道__bluetooth_builtin_audio结构体变量定义就是audio/main.c中这个宏,并且已经为这个结构体变量附好了初值(见audio/main.c宏定义中对应的参数值)。
代码解析之:adapter_ops_setup()
首先看函数定义:
int adapter_ops_setup(void)
{
if (!adapter_ops)
return -EINVAL;
return adapter_ops->setup();
}
函数很简单,执行了setup函数指针。这里主要看adapter_ops这个全局变量何时被赋值。从上一个函数plugin_init介绍,提到在将全局__bluetooth_builtin[]数组加载到plugins后,最后会依次执行各个plugins的init函数。看下加载__bluetooth_builtin_hciops时,调用的init函数,这个函数定义在plugins/hciops.c中,即hciops_init函数。这个函数将传入的静态全局变量hci_ops赋值给了adapter_ops,所以变量adapter_ops即变量hci_ops。所以此处调用adapter_ops->setup(),即调用hciops.c中的hciops_setup函数。看hciops_setup函数定义如下:
static int hciops_setup(void)
{
struct sockaddr_hci addr;
struct hci_filter flt;
GIOChannel *ctl_io, *child_io;
int sock, err;
info("hciops_setup\n");
if (child_pipe[0] != -1)
return -EALREADY;
if (pipe(child_pipe) < 0) {
err = errno;
error("pipe(): %s (%d)", strerror(err), err);
return -err;
}
child_io = g_io_channel_unix_new(child_pipe[0]);
g_io_channel_set_close_on_unref(child_io, TRUE);
child_io_id = g_io_add_watch(child_io,
G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
child_exit, NULL);
g_io_channel_unref(child_io);
/* Create and bind HCI socket */
sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
if (sock < 0) {
err = errno;
error("Can't open HCI socket: %s (%d)", strerror(err),
err);
return -err;
}
/* Set filter */
hci_filter_clear(&flt);
hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
hci_filter_set_event(EVT_STACK_INTERNAL, &flt);
if (setsockopt(sock, SOL_HCI, HCI_FILTER, &flt,
sizeof(flt)) < 0) {
err = errno;
error("Can't set filter: %s (%d)", strerror(err), err);
return -err;
}
memset(&addr, 0, sizeof(addr));
addr.hci_family = AF_BLUETOOTH;
addr.hci_dev = HCI_DEV_NONE;
if (bind(sock, (struct sockaddr *) &addr,
sizeof(addr)) < 0) {
err = errno;
error("Can't bind HCI socket: %s (%d)",
strerror(err), err);
return -err;
}
ctl_io = g_io_channel_unix_new(sock);
g_io_channel_set_close_on_unref(ctl_io, TRUE);
ctl_io_id = g_io_add_watch(ctl_io, G_IO_IN, io_stack_event, NULL);
g_io_channel_unref(ctl_io);
/* Initialize already connected devices */
return init_known_adapters(sock);
}
这个函数首先创建里一个管道,这个管道通向哪里目前尚未知。然后为HCI层创建里一个sock,绑定一个channel:ctl_io,并用io_stack_event事件处理来处理从这个channel获取的数据。最后初始化HCI适配器,init_known_adapters。下面看以下初始化HCI适配器的函数:
static int init_known_adapters(int ctl)
{
struct hci_dev_list_req *dl;
struct hci_dev_req *dr;
int i, err;
info("init_known_adapters\n");
dl = g_try_malloc0(HCI_MAX_DEV * sizeof(struct hci_dev_req) + sizeof(uint16_t));
if (!dl) {
err = errno;
error("Can't allocate devlist buffer: %s (%d)",
strerror(err), err);
return -err;
}
dl->dev_num = HCI_MAX_DEV;
dr = dl->dev_req;
if (ioctl(ctl, HCIGETDEVLIST, (void *) dl) < 0) {
err = errno;
error("Can't get device list: %s (%d)",
strerror(err), err);
g_free(dl);
return -err;
}
for (i = 0; i < dl->dev_num; i++, dr++) {
device_event(HCI_DEV_REG, dr->dev_id);
if (hci_test_bit(HCI_UP, &dr->dev_opt))
device_event(HCI_DEV_UP, dr->dev_id);
}
g_free(dl);
return 0;
}
从函数中可以看出,这里支持最大HCI设备个数为16个,即HCI_MAX_DEV的值。这里用ioctl从驱动部分取得真正HCI适配器,获取的HCI设备列表是hci_dev_req链表。然后循环链表,用device_event函数依次注册并启动HCI设备。
代码解析之:rfkill_init()
void rfkill_init(void)
{
int fd;
if (!main_opts.remember_powered)
return;
fd = open("/dev/rfkill", O_RDWR);
if (fd < 0) {
error("Failed to open RFKILL control device");
return;
}
channel = g_io_channel_unix_new(fd);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_add_watch(channel, G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR,
rfkill_event, NULL);
}
这个函数打开了/dev/rfkill文件,该文件主要用来暂未知(猜测是控制上电吧)。对文件操作用rfkill_event事件处理函数来处理。要看rfkill_event事件处理函数,先看下如下结构体:
struct rfkill_event {
uint32_t idx;
uint8_t type;
uint8_t op;
uint8_t soft;
uint8_t hard;
};