code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* att.c - Attribute protocol handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <bt_errno.h> #include <stdbool.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/uuid.h> #include <bluetooth/gatt.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_ATT) #define LOG_MODULE_NAME bt_att #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "smp.h" #include "att_internal.h" #include "gatt_internal.h" #include "hci_api.h" #define ATT_CHAN(_ch) CONTAINER_OF(_ch, struct bt_att_chan, chan.chan) #define ATT_REQ(_node) CONTAINER_OF(_node, struct bt_att_req, node) #define ATT_CMD_MASK 0x40 #if defined(CONFIG_BT_EATT) #define ATT_CHAN_MAX (CONFIG_BT_EATT_MAX + 1) #else #define ATT_CHAN_MAX 1 #endif /* CONFIG_BT_EATT */ #ifndef ENOTSUP #define ENOTSUP 134 /*unsupported*/ #endif typedef enum __packed { ATT_COMMAND, ATT_REQUEST, ATT_RESPONSE, ATT_NOTIFICATION, ATT_CONFIRMATION, ATT_INDICATION, ATT_UNKNOWN, } att_type_t; static att_type_t att_op_get_type(u8_t op); #if CONFIG_BT_ATT_PREPARE_COUNT > 0 struct bt_attr_data { u16_t handle; u16_t offset; }; /* Pool for incoming ATT packets */ NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, sizeof(struct bt_attr_data), NULL); #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ // K_MEM_SLAB_DEFINE(req_slab, sizeof(struct bt_att_req), // CONFIG_BT_ATT_TX_MAX, 16); struct bt_att_req req_slab[CONFIG_BT_ATT_TX_MAX]; #define k_mem_slab_alloc(slab, ptr, max_num) \ { \ for (int i = 0; i < max_num; ++i) { \ if (!slab[i].used) { \ ptr = &slab[i]; \ memset(ptr, 0, sizeof(*ptr)); \ ptr->used = 1; \ break; \ } \ } \ } #define k_mem_slab_alloc_req(ptr) k_mem_slab_alloc(req_slab, ptr, CONFIG_BT_ATT_TX_MAX) enum { ATT_PENDING_RSP, ATT_PENDING_CFM, ATT_DISCONNECTED, ATT_ENHANCED, /* Total number of flags - must be at the end of the enum */ ATT_NUM_FLAGS, }; /* ATT channel specific data */ struct bt_att_chan { /* Connection this channel is associated with */ struct bt_att *att; struct bt_l2cap_le_chan chan; ATOMIC_DEFINE(flags, ATT_NUM_FLAGS); struct bt_att_req *req; struct k_delayed_work timeout_work; struct k_sem tx_sem; void (*sent)(struct bt_att_chan *chan); sys_snode_t node; bool used; }; /* ATT connection specific data */ struct bt_att { struct bt_conn *conn; /* Shared request queue */ sys_slist_t reqs; struct kfifo tx_queue; #if CONFIG_BT_ATT_PREPARE_COUNT > 0 struct kfifo prep_queue; #endif /* Contains bt_att_chan instance(s) */ sys_slist_t chans; bool used; }; // K_MEM_SLAB_DEFINE(att_slab, sizeof(struct bt_att), // CONFIG_BT_MAX_CONN, 16); // K_MEM_SLAB_DEFINE(chan_slab, sizeof(struct bt_att_chan), // CONFIG_BT_MAX_CONN * ATT_CHAN_MAX, 16); struct bt_att att_slab[CONFIG_BT_MAX_CONN]; #define k_mem_slab_alloc_att(att) k_mem_slab_alloc(att_slab, att, CONFIG_BT_MAX_CONN) struct bt_att_chan chan_slab[CONFIG_BT_MAX_CONN * ATT_CHAN_MAX]; #define k_mem_slab_alloc_chan(chan) k_mem_slab_alloc(chan_slab, chan, CONFIG_BT_MAX_CONN * ATT_CHAN_MAX) static struct bt_att_req cancel; static void att_req_destroy(struct bt_att_req *req) { BT_DBG("req %p", req); if (req->buf) { net_buf_unref(req->buf); } if (req->destroy) { req->destroy(req); } bt_att_req_free(req); } typedef void (*bt_att_chan_sent_t)(struct bt_att_chan *chan); static bt_att_chan_sent_t chan_cb(struct net_buf *buf); void att_sent(struct bt_conn *conn, void *user_data) { struct bt_l2cap_chan *chan = user_data; BT_DBG("conn %p chan %p", conn, chan); if (chan->ops->sent) { chan->ops->sent(chan); } } static int chan_send(struct bt_att_chan *chan, struct net_buf *buf, bt_att_chan_sent_t cb) { struct bt_att_hdr *hdr; hdr = (void *)buf->data; BT_DBG("code 0x%02x", hdr->code); chan->sent = cb ? cb : chan_cb(buf); if (IS_ENABLED(CONFIG_BT_EATT) && atomic_test_bit(chan->flags, ATT_ENHANCED)) { if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) { return -ENOTSUP; } /* Check if the channel is ready to send in case of a request */ if (att_op_get_type(hdr->code) == ATT_REQUEST && !atomic_test_bit(chan->chan.chan.status, BT_L2CAP_STATUS_OUT)) { return -EAGAIN; } return bt_l2cap_chan_send(&chan->chan.chan, buf); } if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) { int err; err = bt_smp_sign(chan->att->conn, buf); if (err) { BT_ERR("Error signing data"); net_buf_unref(buf); return err; } } return bt_l2cap_send_cb(chan->att->conn, BT_L2CAP_CID_ATT, buf, att_sent, &chan->chan.chan); } static void bt_att_sent(struct bt_l2cap_chan *ch) { struct bt_att_chan *chan = ATT_CHAN(ch); struct bt_att *att = chan->att; struct net_buf *buf; BT_DBG("chan %p", chan); if (chan->sent) { chan->sent(chan); } while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) { /* Check if the queued buf is a request */ if (chan->req && chan->req->buf == buf) { /* Save request state so it can be resent */ net_buf_simple_save(&chan->req->buf->b, &chan->req->state); } if (chan_send(chan, buf, NULL) < 0) { /* Push it back if it could not be send */ k_queue_prepend(&att->tx_queue._queue, buf); break; } return; } k_sem_give(&chan->tx_sem); } static void chan_cfm_sent(struct bt_att_chan *chan) { BT_DBG("chan %p", chan); if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { atomic_clear_bit(chan->flags, ATT_PENDING_CFM); } } static void chan_rsp_sent(struct bt_att_chan *chan) { BT_DBG("chan %p", chan); if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { atomic_clear_bit(chan->flags, ATT_PENDING_RSP); } } static void chan_req_sent(struct bt_att_chan *chan) { BT_DBG("chan %p chan->req %p", chan, chan->req); /* Start timeout work */ if (chan->req) { k_delayed_work_submit(&chan->timeout_work, BT_ATT_TIMEOUT); } } static bt_att_chan_sent_t chan_cb(struct net_buf *buf) { switch (att_op_get_type(buf->data[0])) { case ATT_RESPONSE: return chan_rsp_sent; case ATT_CONFIRMATION: return chan_cfm_sent; case ATT_REQUEST: case ATT_INDICATION: return chan_req_sent; default: return NULL; } } struct net_buf *bt_att_chan_create_pdu(struct bt_att_chan *chan, u8_t op, size_t len) { struct bt_att_hdr *hdr; struct net_buf *buf; if (len + sizeof(op) > chan->chan.tx.mtu) { BT_WARN("ATT MTU exceeded, max %u, wanted %zu", chan->chan.tx.mtu, len + sizeof(op)); return NULL; } switch (att_op_get_type(op)) { case ATT_RESPONSE: case ATT_CONFIRMATION: /* Use a timeout only when responding/confirming */ buf = bt_l2cap_create_pdu_timeout(NULL, 0, BT_ATT_TIMEOUT); break; default: buf = bt_l2cap_create_pdu(NULL, 0); } if (!buf) { BT_ERR("Unable to allocate buffer for op 0x%02x", op); return NULL; } hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = op; return buf; } static inline bool att_chan_is_connected(struct bt_att_chan *chan) { return (chan->att->conn->state != BT_CONN_CONNECTED || !atomic_test_bit(chan->flags, ATT_DISCONNECTED)); } static int bt_att_chan_send(struct bt_att_chan *chan, struct net_buf *buf, bt_att_chan_sent_t cb) { struct bt_att_hdr *hdr; hdr = (void *)buf->data; BT_DBG("chan %p flags %u code 0x%02x", chan, atomic_get(chan->flags), hdr->code); (void)hdr; /* Don't use tx_sem if caller has set it own callback */ if (!cb) { if (k_sem_take(&chan->tx_sem, K_NO_WAIT) < 0) { return -EAGAIN; } } return chan_send(chan, buf, cb); } static void send_err_rsp(struct bt_att_chan *chan, u8_t req, u16_t handle, u8_t err) { struct bt_att_error_rsp *rsp; struct net_buf *buf; /* Ignore opcode 0x00 */ if (!req) { return; } buf = bt_att_chan_create_pdu(chan, BT_ATT_OP_ERROR_RSP, sizeof(*rsp)); if (!buf) { return; } rsp = net_buf_add(buf, sizeof(*rsp)); rsp->request = req; rsp->handle = sys_cpu_to_le16(handle); rsp->error = err; (void)bt_att_chan_send(chan, buf, chan_rsp_sent); } __attribute__((weak)) void mtu_exchange_cb(struct bt_conn *conn, u8_t err, struct bt_gatt_exchange_params *params) { } static u8_t att_mtu_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_conn *conn = chan->att->conn; struct bt_att_exchange_mtu_req *req; struct bt_att_exchange_mtu_rsp *rsp; struct net_buf *pdu; u16_t mtu_client, mtu_server; /* Exchange MTU sub-procedure shall only be supported on the * LE Fixed Channel Unenhanced ATT bearer. */ if (atomic_test_bit(chan->flags, ATT_ENHANCED)) { return BT_ATT_ERR_NOT_SUPPORTED; } req = (void *)buf->data; mtu_client = sys_le16_to_cpu(req->mtu); BT_DBG("Client MTU %u", mtu_client); /* Check if MTU is valid */ if (mtu_client < BT_ATT_DEFAULT_LE_MTU) { return BT_ATT_ERR_INVALID_PDU; } pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp)); if (!pdu) { return BT_ATT_ERR_UNLIKELY; } mtu_server = BT_ATT_MTU; BT_DBG("Server MTU %u", mtu_server); rsp = net_buf_add(pdu, sizeof(*rsp)); rsp->mtu = sys_cpu_to_le16(mtu_server); (void)bt_att_chan_send(chan, pdu, chan_rsp_sent); /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484: * * A device's Exchange MTU Request shall contain the same MTU as the * device's Exchange MTU Response (i.e. the MTU shall be symmetric). */ chan->chan.rx.mtu = MIN(mtu_client, mtu_server); chan->chan.tx.mtu = chan->chan.rx.mtu; BT_DBG("Negotiated MTU %u", chan->chan.rx.mtu); mtu_exchange_cb(conn, 0, NULL); return 0; } static int bt_att_chan_req_send(struct bt_att_chan *chan, struct bt_att_req *req) { int err; __ASSERT_NO_MSG(chan); __ASSERT_NO_MSG(req); __ASSERT_NO_MSG(req->func); __ASSERT_NO_MSG(!chan->req); BT_DBG("req %p", req); if (chan->chan.tx.mtu < net_buf_frags_len(req->buf)) { return -EMSGSIZE; } if (k_sem_take(&chan->tx_sem, K_NO_WAIT) < 0) { return -EAGAIN; } BT_DBG("chan %p req %p len %zu", chan, req, net_buf_frags_len(req->buf)); chan->req = req; /* Save request state so it can be resent */ net_buf_simple_save(&req->buf->b, &req->state); /* Keep a reference for resending in case of an error */ err = chan_send(chan, net_buf_ref(req->buf), NULL); if (err < 0) { net_buf_unref(req->buf); req->buf = NULL; k_sem_give(&chan->tx_sem); chan->req = NULL; } return err; } static void att_process(struct bt_att *att) { sys_snode_t *node; struct bt_att_chan *chan, *tmp; /* Pull next request from the list */ node = sys_slist_get(&att->reqs); if (!node) { return; } BT_DBG("req %p", ATT_REQ(node)); SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->chans, chan, tmp, node) { /* If there is nothing pending use the channel */ if (!chan->req) { if (bt_att_chan_req_send(chan, ATT_REQ(node)) >= 0) { return; } } } /* Prepend back to the list as it could not be sent */ sys_slist_prepend(&att->reqs, node); } static u8_t att_handle_rsp(struct bt_att_chan *chan, void *pdu, u16_t len, u8_t err) { bt_att_func_t func = NULL; void *params; BT_DBG("chan %p err 0x%02x len %u: %s", chan, err, len, bt_hex(pdu, len)); /* Cancel timeout if ongoing */ k_delayed_work_cancel(&chan->timeout_work); if (!chan->req) { BT_WARN("No pending ATT request"); goto process; } /* Check if request has been cancelled */ if (chan->req == &cancel) { chan->req = NULL; goto process; } /* Release original buffer */ if (chan->req->buf) { net_buf_unref(chan->req->buf); chan->req->buf = NULL; } /* Reset func so it can be reused by the callback */ func = chan->req->func; chan->req->func = NULL; params = chan->req->user_data; /* free allocated request so its memory can be reused */ att_req_destroy(chan->req); chan->req = NULL; process: /* Process pending requests */ att_process(chan->att); if (func) { func(chan->att->conn, err, pdu, len, params); } return 0; } #if defined(CONFIG_BT_GATT_CLIENT) static u8_t att_mtu_rsp(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_exchange_mtu_rsp *rsp; u16_t mtu; rsp = (void *)buf->data; mtu = sys_le16_to_cpu(rsp->mtu); BT_DBG("Server MTU %u", mtu); /* Check if MTU is valid */ if (mtu < BT_ATT_DEFAULT_LE_MTU) { return att_handle_rsp(chan, NULL, 0, BT_ATT_ERR_INVALID_PDU); } chan->chan.rx.mtu = MIN(mtu, BT_ATT_MTU); /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484: * * A device's Exchange MTU Request shall contain the same MTU as the * device's Exchange MTU Response (i.e. the MTU shall be symmetric). */ chan->chan.tx.mtu = chan->chan.rx.mtu; BT_DBG("Negotiated MTU %u", chan->chan.rx.mtu); return att_handle_rsp(chan, rsp, buf->len, 0); } #endif /* CONFIG_BT_GATT_CLIENT */ static bool range_is_valid(u16_t start, u16_t end, u16_t *err) { /* Handle 0 is invalid */ if (!start || !end) { if (err) { *err = 0U; } return false; } /* Check if range is valid */ if (start > end) { if (err) { *err = start; } return false; } return true; } struct find_info_data { struct bt_att_chan *chan; struct net_buf *buf; struct bt_att_find_info_rsp *rsp; union { struct bt_att_info_16 *info16; struct bt_att_info_128 *info128; }; }; static u8_t find_info_cb(const struct bt_gatt_attr *attr, void *user_data) { struct find_info_data *data = user_data; struct bt_att_chan *chan = data->chan; BT_DBG("handle 0x%04x", attr->handle); /* Initialize rsp at first entry */ if (!data->rsp) { data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ? BT_ATT_INFO_16 : BT_ATT_INFO_128; } switch (data->rsp->format) { case BT_ATT_INFO_16: if (attr->uuid->type != BT_UUID_TYPE_16) { return BT_GATT_ITER_STOP; } /* Fast forward to next item position */ data->info16 = net_buf_add(data->buf, sizeof(*data->info16)); data->info16->handle = sys_cpu_to_le16(attr->handle); data->info16->uuid = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val); if (chan->chan.tx.mtu - data->buf->len > sizeof(*data->info16)) { return BT_GATT_ITER_CONTINUE; } break; case BT_ATT_INFO_128: if (attr->uuid->type != BT_UUID_TYPE_128) { return BT_GATT_ITER_STOP; } /* Fast forward to next item position */ data->info128 = net_buf_add(data->buf, sizeof(*data->info128)); data->info128->handle = sys_cpu_to_le16(attr->handle); memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val, sizeof(data->info128->uuid)); if (chan->chan.tx.mtu - data->buf->len > sizeof(*data->info128)) { return BT_GATT_ITER_CONTINUE; } } return BT_GATT_ITER_STOP; } static u8_t att_find_info_rsp(struct bt_att_chan *chan, u16_t start_handle, u16_t end_handle) { struct bt_conn *conn = chan->chan.chan.conn; struct find_info_data data; (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data); if (!data.rsp) { net_buf_unref(data.buf); /* Respond since handle is set */ send_err_rsp(chan, BT_ATT_OP_FIND_INFO_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); return 0; } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } static u8_t att_find_info_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_find_info_req *req; u16_t start_handle, end_handle, err_handle; req = (void *)buf->data; start_handle = sys_le16_to_cpu(req->start_handle); end_handle = sys_le16_to_cpu(req->end_handle); BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle); if (!range_is_valid(start_handle, end_handle, &err_handle)) { send_err_rsp(chan, BT_ATT_OP_FIND_INFO_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE); return 0; } return att_find_info_rsp(chan, start_handle, end_handle); } struct find_type_data { struct bt_att_chan *chan; struct net_buf *buf; struct bt_att_handle_group *group; const void *value; u8_t value_len; u8_t err; }; static u8_t find_type_cb(const struct bt_gatt_attr *attr, void *user_data) { struct find_type_data *data = user_data; struct bt_att_chan *chan = data->chan; struct bt_conn *conn = chan->chan.chan.conn; int read; u8_t uuid[16]; struct net_buf *frag; size_t len; /* Skip secondary services */ if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { goto skip; } /* Update group end_handle if not a primary service */ if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) { if (data->group && attr->handle > sys_le16_to_cpu(data->group->end_handle)) { data->group->end_handle = sys_cpu_to_le16(attr->handle); } return BT_GATT_ITER_CONTINUE; } BT_DBG("handle 0x%04x", attr->handle); /* stop if there is no space left */ if (chan->chan.tx.mtu - net_buf_frags_len(data->buf) < sizeof(*data->group)) { return BT_GATT_ITER_STOP; } frag = net_buf_frag_last(data->buf); len = MIN(chan->chan.tx.mtu - net_buf_frags_len(data->buf), net_buf_tailroom(frag)); if (!len) { frag = net_buf_alloc(net_buf_pool_get(data->buf->pool_id), K_NO_WAIT); /* If not buffer can be allocated immediately stop */ if (!frag) { return BT_GATT_ITER_STOP; } net_buf_frag_add(data->buf, frag); } /* Read attribute value and store in the buffer */ read = attr->read(conn, attr, uuid, sizeof(uuid), 0); if (read < 0) { /* * Since we don't know if it is the service with requested UUID, * we cannot respond with an error to this request. */ goto skip; } /* Check if data matches */ if (read != data->value_len) { /* Use bt_uuid_cmp() to compare UUIDs of different form. */ struct bt_uuid_128 ref_uuid; struct bt_uuid_128 recvd_uuid; if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) { BT_WARN("Unable to create UUID: size %u", data->value_len); goto skip; } if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) { BT_WARN("Unable to create UUID: size %d", read); goto skip; } if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) { goto skip; } } else if (memcmp(data->value, uuid, read)) { goto skip; } /* If service has been found, error should be cleared */ data->err = 0x00; /* Fast forward to next item position */ data->group = net_buf_add(frag, sizeof(*data->group)); data->group->start_handle = sys_cpu_to_le16(attr->handle); data->group->end_handle = sys_cpu_to_le16(attr->handle); /* continue to find the end_handle */ return BT_GATT_ITER_CONTINUE; skip: data->group = NULL; return BT_GATT_ITER_CONTINUE; } static u8_t att_find_type_rsp(struct bt_att_chan *chan, u16_t start_handle, u16_t end_handle, const void *value, u8_t value_len) { struct bt_conn *conn = chan->chan.chan.conn; struct find_type_data data; (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; data.group = NULL; data.value = value; data.value_len = value_len; /* Pre-set error in case no service will be found */ data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND; bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data); /* If error has not been cleared, no service has been found */ if (data.err) { net_buf_unref(data.buf); /* Respond since handle is set */ send_err_rsp(chan, BT_ATT_OP_FIND_TYPE_REQ, start_handle, data.err); return 0; } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } static u8_t att_find_type_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_find_type_req *req; u16_t start_handle, end_handle, err_handle, type; u8_t *value; req = net_buf_pull_mem(buf, sizeof(*req)); start_handle = sys_le16_to_cpu(req->start_handle); end_handle = sys_le16_to_cpu(req->end_handle); type = sys_le16_to_cpu(req->type); value = buf->data; BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle, end_handle, type); if (!range_is_valid(start_handle, end_handle, &err_handle)) { send_err_rsp(chan, BT_ATT_OP_FIND_TYPE_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE); return 0; } /* The Attribute Protocol Find By Type Value Request shall be used with * the Attribute Type parameter set to the UUID for "Primary Service" * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit * UUID for the specific primary service. */ if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) { send_err_rsp(chan, BT_ATT_OP_FIND_TYPE_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); return 0; } return att_find_type_rsp(chan, start_handle, end_handle, value, buf->len); } static u8_t err_to_att(int err) { BT_DBG("%d", err); if (err < 0 && err >= -0xff) { return -err; } return BT_ATT_ERR_UNLIKELY; } struct read_type_data { struct bt_att_chan *chan; struct bt_uuid *uuid; struct net_buf *buf; struct bt_att_read_type_rsp *rsp; struct bt_att_data *item; u8_t err; }; typedef bool (*attr_read_cb)(struct net_buf *buf, ssize_t read, void *user_data); static bool attr_read_type_cb(struct net_buf *frag, ssize_t read, void *user_data) { struct read_type_data *data = user_data; if (!data->rsp->len) { /* Set len to be the first item found */ data->rsp->len = read + sizeof(*data->item); } else if (data->rsp->len != read + sizeof(*data->item)) { /* All items should have the same size */ frag->len -= sizeof(*data->item); data->item = NULL; return false; } return true; } static ssize_t att_chan_read(struct bt_att_chan *chan, const struct bt_gatt_attr *attr, struct net_buf *buf, u16_t offset, attr_read_cb cb, void *user_data) { struct bt_conn *conn = chan->chan.chan.conn; ssize_t read; struct net_buf *frag; size_t len, total = 0; if (chan->chan.tx.mtu <= net_buf_frags_len(buf)) { return 0; } frag = net_buf_frag_last(buf); /* Create necessary fragments if MTU is bigger than what a buffer can * hold. */ do { len = MIN(chan->chan.tx.mtu - net_buf_frags_len(buf), net_buf_tailroom(frag)); if (!len) { frag = net_buf_alloc(net_buf_pool_get(buf->pool_id), K_NO_WAIT); /* If not buffer can be allocated immediately return */ if (!frag) { return total; } net_buf_frag_add(buf, frag); len = MIN(chan->chan.tx.mtu - net_buf_frags_len(buf), net_buf_tailroom(frag)); } read = attr->read(conn, attr, frag->data + frag->len, len, offset); if (read < 0) { if (total) { return total; } return read; } if (cb && !cb(frag, read, user_data)) { break; } net_buf_add(frag, read); total += read; offset += read; } while (chan->chan.tx.mtu > net_buf_frags_len(buf) && read == len); return total; } static u8_t read_type_cb(const struct bt_gatt_attr *attr, void *user_data) { struct read_type_data *data = user_data; struct bt_att_chan *chan = data->chan; struct bt_conn *conn = chan->chan.chan.conn; ssize_t read; /* Skip if doesn't match */ if (bt_uuid_cmp(attr->uuid, data->uuid)) { return BT_GATT_ITER_CONTINUE; } BT_DBG("handle 0x%04x", attr->handle); /* * If an attribute in the set of requested attributes would cause an * Error Response then this attribute cannot be included in a * Read By Type Response and the attributes before this attribute * shall be returned * * If the first attribute in the set of requested attributes would * cause an Error Response then no other attributes in the requested * attributes can be considered. */ data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); if (data->err) { if (data->rsp->len) { data->err = 0x00; } return BT_GATT_ITER_STOP; } /* * If any attribute is founded in handle range it means that error * should be changed from pre-set: attr not found error to no error. */ data->err = 0x00; /* Fast foward to next item position */ data->item = net_buf_add(net_buf_frag_last(data->buf), sizeof(*data->item)); data->item->handle = sys_cpu_to_le16(attr->handle); read = att_chan_read(chan, attr, data->buf, 0, attr_read_type_cb, data); if (read < 0) { data->err = err_to_att(read); return BT_GATT_ITER_STOP; } if (!data->item) { return BT_GATT_ITER_STOP; } /* continue only if there are still space for more items */ return chan->chan.tx.mtu - net_buf_frags_len(data->buf) > data->rsp->len ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP; } static u8_t att_read_type_rsp(struct bt_att_chan *chan, struct bt_uuid *uuid, u16_t start_handle, u16_t end_handle) { struct bt_conn *conn = chan->chan.chan.conn; struct read_type_data data; (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP, sizeof(*data.rsp)); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; data.uuid = uuid; data.rsp = net_buf_add(data.buf, sizeof(*data.rsp)); data.rsp->len = 0U; /* Pre-set error if no attr will be found in handle */ data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND; bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data); if (data.err) { net_buf_unref(data.buf); /* Response here since handle is set */ send_err_rsp(chan, BT_ATT_OP_READ_TYPE_REQ, start_handle, data.err); return 0; } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } static u8_t att_read_type_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_read_type_req *req; u16_t start_handle, end_handle, err_handle; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_128 u128; } u; u8_t uuid_len = buf->len - sizeof(*req); /* Type can only be UUID16 or UUID128 */ if (uuid_len != 2 && uuid_len != 16) { return BT_ATT_ERR_INVALID_PDU; } req = net_buf_pull_mem(buf, sizeof(*req)); start_handle = sys_le16_to_cpu(req->start_handle); end_handle = sys_le16_to_cpu(req->end_handle); if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) { return BT_ATT_ERR_UNLIKELY; } BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid)); if (!range_is_valid(start_handle, end_handle, &err_handle)) { send_err_rsp(chan, BT_ATT_OP_READ_TYPE_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE); return 0; } return att_read_type_rsp(chan, &u.uuid, start_handle, end_handle); } struct read_data { struct bt_att_chan *chan; u16_t offset; struct net_buf *buf; struct bt_att_read_rsp *rsp; u8_t err; }; static u8_t read_cb(const struct bt_gatt_attr *attr, void *user_data) { struct read_data *data = user_data; struct bt_att_chan *chan = data->chan; struct bt_conn *conn = chan->chan.chan.conn; int ret; BT_DBG("handle 0x%04x", attr->handle); data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); /* * If any attribute is founded in handle range it means that error * should be changed from pre-set: invalid handle error to no error. */ data->err = 0x00; /* Check attribute permissions */ data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); if (data->err) { return BT_GATT_ITER_STOP; } /* Read attribute value and store in the buffer */ ret = att_chan_read(chan, attr, data->buf, data->offset, NULL, NULL); if (ret < 0) { data->err = err_to_att(ret); return BT_GATT_ITER_STOP; } return BT_GATT_ITER_CONTINUE; } static u8_t att_read_rsp(struct bt_att_chan *chan, u8_t op, u8_t rsp, u16_t handle, u16_t offset) { struct bt_conn *conn = chan->chan.chan.conn; struct read_data data; if (!bt_gatt_change_aware(conn, true)) { return BT_ATT_ERR_DB_OUT_OF_SYNC; } if (!handle) { return BT_ATT_ERR_INVALID_HANDLE; } (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, rsp, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; data.offset = offset; /* Pre-set error if no attr will be found in handle */ data.err = BT_ATT_ERR_INVALID_HANDLE; bt_gatt_foreach_attr(handle, handle, read_cb, &data); /* In case of error discard data and respond with an error */ if (data.err) { net_buf_unref(data.buf); /* Respond here since handle is set */ send_err_rsp(chan, op, handle, data.err); return 0; } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } static u8_t att_read_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_read_req *req; u16_t handle; req = (void *)buf->data; handle = sys_le16_to_cpu(req->handle); BT_DBG("handle 0x%04x", handle); return att_read_rsp(chan, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP, handle, 0); } static u8_t att_read_blob_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_read_blob_req *req; u16_t handle, offset; req = (void *)buf->data; handle = sys_le16_to_cpu(req->handle); offset = sys_le16_to_cpu(req->offset); BT_DBG("handle 0x%04x offset %u", handle, offset); return att_read_rsp(chan, BT_ATT_OP_READ_BLOB_REQ, BT_ATT_OP_READ_BLOB_RSP, handle, offset); } #if defined(CONFIG_BT_GATT_READ_MULTIPLE) static u8_t att_read_mult_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_conn *conn = chan->chan.chan.conn; struct read_data data; u16_t handle; (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; while (buf->len >= sizeof(u16_t)) { handle = net_buf_pull_le16(buf); BT_DBG("handle 0x%04x ", handle); /* An Error Response shall be sent by the server in response to * the Read Multiple Request [....] if a read operation is not * permitted on any of the Characteristic Values. * * If handle is not valid then return invalid handle error. * If handle is found error will be cleared by read_cb. */ data.err = BT_ATT_ERR_INVALID_HANDLE; bt_gatt_foreach_attr(handle, handle, read_cb, &data); /* Stop reading in case of error */ if (data.err) { net_buf_unref(data.buf); /* Respond here since handle is set */ send_err_rsp(chan, BT_ATT_OP_READ_MULT_REQ, handle, data.err); return 0; } } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } #if defined(CONFIG_BT_EATT) static u8_t read_vl_cb(const struct bt_gatt_attr *attr, void *user_data) { struct read_data *data = user_data; struct bt_att_chan *chan = data->chan; struct bt_conn *conn = chan->chan.chan.conn; struct bt_att_read_mult_vl_rsp *rsp; int read; BT_DBG("handle 0x%04x", attr->handle); data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); /* * If any attribute is founded in handle range it means that error * should be changed from pre-set: invalid handle error to no error. */ data->err = 0x00; /* Check attribute permissions */ data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); if (data->err) { return BT_GATT_ITER_STOP; } /* The Length Value Tuple List may be truncated within the first two * octets of a tuple due to the size limits of the current ATT_MTU. */ if (chan->chan.tx.mtu - data->buf->len < 2) { return BT_GATT_ITER_STOP; } rsp = net_buf_add(data->buf, sizeof(*rsp)); read = att_chan_read(chan, attr, data->buf, data->offset, NULL, NULL); if (read < 0) { data->err = err_to_att(read); return BT_GATT_ITER_STOP; } rsp->len = read; return BT_GATT_ITER_CONTINUE; } static u8_t att_read_mult_vl_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_conn *conn = chan->chan.chan.conn; struct read_data data; u16_t handle; (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_VL_RSP, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; while (buf->len >= sizeof(u16_t)) { handle = net_buf_pull_le16(buf); BT_DBG("handle 0x%04x ", handle); /* If handle is not valid then return invalid handle error. * If handle is found error will be cleared by read_cb. */ data.err = BT_ATT_ERR_INVALID_HANDLE; bt_gatt_foreach_attr(handle, handle, read_vl_cb, &data); /* Stop reading in case of error */ if (data.err) { net_buf_unref(data.buf); /* Respond here since handle is set */ send_err_rsp(chan, BT_ATT_OP_READ_MULT_VL_REQ, handle, data.err); return 0; } } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } #endif /* CONFIG_BT_EATT */ #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ struct read_group_data { struct bt_att_chan *chan; struct bt_uuid *uuid; struct net_buf *buf; struct bt_att_read_group_rsp *rsp; struct bt_att_group_data *group; }; static bool attr_read_group_cb(struct net_buf *frag, ssize_t read, void *user_data) { struct read_group_data *data = user_data; if (!data->rsp->len) { /* Set len to be the first group found */ data->rsp->len = read + sizeof(*data->group); } else if (data->rsp->len != read + sizeof(*data->group)) { /* All groups entries should have the same size */ data->buf->len -= sizeof(*data->group); data->group = NULL; return false; } return true; } static u8_t read_group_cb(const struct bt_gatt_attr *attr, void *user_data) { struct read_group_data *data = user_data; struct bt_att_chan *chan = data->chan; int read; /* Update group end_handle if attribute is not a service */ if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) && bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { if (data->group && attr->handle > sys_le16_to_cpu(data->group->end_handle)) { data->group->end_handle = sys_cpu_to_le16(attr->handle); } return BT_GATT_ITER_CONTINUE; } /* If Group Type don't match skip */ if (bt_uuid_cmp(attr->uuid, data->uuid)) { data->group = NULL; return BT_GATT_ITER_CONTINUE; } BT_DBG("handle 0x%04x", attr->handle); /* Stop if there is no space left */ if (data->rsp->len && chan->chan.tx.mtu - data->buf->len < data->rsp->len) { return BT_GATT_ITER_STOP; } /* Fast forward to next group position */ data->group = net_buf_add(data->buf, sizeof(*data->group)); /* Initialize group handle range */ data->group->start_handle = sys_cpu_to_le16(attr->handle); data->group->end_handle = sys_cpu_to_le16(attr->handle); /* Read attribute value and store in the buffer */ read = att_chan_read(chan, attr, data->buf, 0, attr_read_group_cb, data); if (read < 0) { /* TODO: Handle read errors */ return BT_GATT_ITER_STOP; } if (!data->group) { return BT_GATT_ITER_STOP; } /* continue only if there are still space for more items */ return BT_GATT_ITER_CONTINUE; } static u8_t att_read_group_rsp(struct bt_att_chan *chan, struct bt_uuid *uuid, u16_t start_handle, u16_t end_handle) { struct bt_conn *conn = chan->chan.chan.conn; struct read_group_data data; (void)memset(&data, 0, sizeof(data)); data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP, sizeof(*data.rsp)); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } data.chan = chan; data.uuid = uuid; data.rsp = net_buf_add(data.buf, sizeof(*data.rsp)); data.rsp->len = 0U; data.group = NULL; bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data); if (!data.rsp->len) { net_buf_unref(data.buf); /* Respond here since handle is set */ send_err_rsp(chan, BT_ATT_OP_READ_GROUP_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); return 0; } (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } static u8_t att_read_group_req(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_read_group_req *req; u16_t start_handle, end_handle, err_handle; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_128 u128; } u; u8_t uuid_len = buf->len - sizeof(*req); /* Type can only be UUID16 or UUID128 */ if (uuid_len != 2 && uuid_len != 16) { return BT_ATT_ERR_INVALID_PDU; } req = net_buf_pull_mem(buf, sizeof(*req)); start_handle = sys_le16_to_cpu(req->start_handle); end_handle = sys_le16_to_cpu(req->end_handle); if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) { return BT_ATT_ERR_UNLIKELY; } BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid)); if (!range_is_valid(start_handle, end_handle, &err_handle)) { send_err_rsp(chan, BT_ATT_OP_READ_GROUP_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE); return 0; } /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping: * Not all of the grouping attributes can be used in the ATT * Read By Group Type Request. The "Primary Service" and "Secondary * Service" grouping types may be used in the Read By Group Type * Request. The "Characteristic" grouping type shall not be used in * the ATT Read By Group Type Request. */ if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) && bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) { send_err_rsp(chan, BT_ATT_OP_READ_GROUP_REQ, start_handle, BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE); return 0; } return att_read_group_rsp(chan, &u.uuid, start_handle, end_handle); } struct write_data { struct bt_conn *conn; struct net_buf *buf; u8_t req; const void *value; u16_t len; u16_t offset; u8_t err; }; static u8_t write_cb(const struct bt_gatt_attr *attr, void *user_data) { struct write_data *data = user_data; int write; u8_t flags = 0U; BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset); /* Check attribute permissions */ data->err = bt_gatt_check_perm(data->conn, attr, BT_GATT_PERM_WRITE_MASK); if (data->err) { return BT_GATT_ITER_STOP; } /* Set command flag if not a request */ if (!data->req) { flags |= BT_GATT_WRITE_FLAG_CMD; } /* Write attribute value */ write = attr->write(data->conn, attr, data->value, data->len, data->offset, flags); if (write < 0 || write != data->len) { data->err = err_to_att(write); return BT_GATT_ITER_STOP; } data->err = 0U; return BT_GATT_ITER_CONTINUE; } static u8_t att_write_rsp(struct bt_att_chan *chan, u8_t req, u8_t rsp, u16_t handle, u16_t offset, const void *value, u16_t len) { struct write_data data; if (!bt_gatt_change_aware(chan->att->conn, req ? true : false)) { return BT_ATT_ERR_DB_OUT_OF_SYNC; } if (!handle) { return BT_ATT_ERR_INVALID_HANDLE; } (void)memset(&data, 0, sizeof(data)); /* Only allocate buf if required to respond */ if (rsp) { data.buf = bt_att_chan_create_pdu(chan, rsp, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } } data.conn = chan->att->conn; data.req = req; data.offset = offset; data.value = value; data.len = len; data.err = BT_ATT_ERR_INVALID_HANDLE; bt_gatt_foreach_attr(handle, handle, write_cb, &data); if (data.err) { /* In case of error discard data and respond with an error */ if (rsp) { net_buf_unref(data.buf); /* Respond here since handle is set */ send_err_rsp(chan, req, handle, data.err); } return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0; } if (data.buf) { (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); } return 0; } static u8_t att_write_req(struct bt_att_chan *chan, struct net_buf *buf) { u16_t handle; handle = net_buf_pull_le16(buf); BT_DBG("handle 0x%04x", handle); return att_write_rsp(chan, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP, handle, 0, buf->data, buf->len); } #if CONFIG_BT_ATT_PREPARE_COUNT > 0 struct prep_data { struct bt_conn *conn; struct net_buf *buf; const void *value; u16_t len; u16_t offset; u8_t err; }; static u8_t prep_write_cb(const struct bt_gatt_attr *attr, void *user_data) { struct prep_data *data = user_data; struct bt_attr_data *attr_data; int write; BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset); /* Check attribute permissions */ data->err = bt_gatt_check_perm(data->conn, attr, BT_GATT_PERM_WRITE_MASK); if (data->err) { return BT_GATT_ITER_STOP; } /* Check if attribute requires handler to accept the data */ if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) { goto append; } /* Write attribute value to check if device is authorized */ write = attr->write(data->conn, attr, data->value, data->len, data->offset, BT_GATT_WRITE_FLAG_PREPARE); if (write != 0) { data->err = err_to_att(write); return BT_GATT_ITER_STOP; } append: /* Copy data into the outstanding queue */ data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT); if (!data->buf) { data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL; return BT_GATT_ITER_STOP; } attr_data = net_buf_user_data(data->buf); attr_data->handle = attr->handle; attr_data->offset = data->offset; net_buf_add_mem(data->buf, data->value, data->len); data->err = 0U; return BT_GATT_ITER_CONTINUE; } static u8_t att_prep_write_rsp(struct bt_att_chan *chan, u16_t handle, u16_t offset, const void *value, u8_t len) { struct bt_conn *conn = chan->chan.chan.conn; struct prep_data data; struct bt_att_prepare_write_rsp *rsp; if (!bt_gatt_change_aware(conn, true)) { return BT_ATT_ERR_DB_OUT_OF_SYNC; } if (!handle) { return BT_ATT_ERR_INVALID_HANDLE; } (void)memset(&data, 0, sizeof(data)); data.conn = conn; data.offset = offset; data.value = value; data.len = len; data.err = BT_ATT_ERR_INVALID_HANDLE; bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data); if (data.err) { /* Respond here since handle is set */ send_err_rsp(chan, BT_ATT_OP_PREPARE_WRITE_REQ, handle, data.err); return 0; } BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset); /* Store buffer in the outstanding queue */ net_buf_put(&chan->att->prep_queue, data.buf); /* Generate response */ data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0); if (!data.buf) { return BT_ATT_ERR_UNLIKELY; } rsp = net_buf_add(data.buf, sizeof(*rsp)); rsp->handle = sys_cpu_to_le16(handle); rsp->offset = sys_cpu_to_le16(offset); net_buf_add(data.buf, len); memcpy(rsp->value, value, len); (void)bt_att_chan_send(chan, data.buf, chan_rsp_sent); return 0; } #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ static u8_t att_prepare_write_req(struct bt_att_chan *chan, struct net_buf *buf) { #if CONFIG_BT_ATT_PREPARE_COUNT == 0 return BT_ATT_ERR_NOT_SUPPORTED; #else struct bt_att_prepare_write_req *req; u16_t handle, offset; req = net_buf_pull_mem(buf, sizeof(*req)); handle = sys_le16_to_cpu(req->handle); offset = sys_le16_to_cpu(req->offset); BT_DBG("handle 0x%04x offset %u", handle, offset); return att_prep_write_rsp(chan, handle, offset, buf->data, buf->len); #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ } #if CONFIG_BT_ATT_PREPARE_COUNT > 0 static u8_t att_exec_write_rsp(struct bt_att_chan *chan, u8_t flags) { struct bt_conn *conn = chan->chan.chan.conn; struct net_buf *buf; u8_t err = 0U; while ((buf = net_buf_get(&chan->att->prep_queue, K_NO_WAIT))) { struct bt_attr_data *data = net_buf_user_data(buf); BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle, data->offset); /* Just discard the data if an error was set */ if (!err && flags == BT_ATT_FLAG_EXEC) { err = att_write_rsp(chan, BT_ATT_OP_EXEC_WRITE_REQ, 0, data->handle, data->offset, buf->data, buf->len); if (err) { /* Respond here since handle is set */ send_err_rsp(chan, BT_ATT_OP_EXEC_WRITE_REQ, data->handle, err); } } net_buf_unref(buf); } if (err) { return 0; } /* Generate response */ buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0); if (!buf) { return BT_ATT_ERR_UNLIKELY; } (void)bt_att_chan_send(chan, buf, chan_rsp_sent); return 0; } #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ static u8_t att_exec_write_req(struct bt_att_chan *chan, struct net_buf *buf) { #if CONFIG_BT_ATT_PREPARE_COUNT == 0 return BT_ATT_ERR_NOT_SUPPORTED; #else struct bt_att_exec_write_req *req; req = (void *)buf->data; BT_DBG("flags 0x%02x", req->flags); return att_exec_write_rsp(chan, req->flags); #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ } static u8_t att_write_cmd(struct bt_att_chan *chan, struct net_buf *buf) { u16_t handle; handle = net_buf_pull_le16(buf); BT_DBG("handle 0x%04x", handle); return att_write_rsp(chan, 0, 0, handle, 0, buf->data, buf->len); } #if defined(CONFIG_BT_SIGNING) static u8_t att_signed_write_cmd(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_conn *conn = chan->chan.chan.conn; struct bt_att_signed_write_cmd *req; u16_t handle; int err; req = (void *)buf->data; handle = sys_le16_to_cpu(req->handle); BT_DBG("handle 0x%04x", handle); /* Verifying data requires full buffer including attribute header */ net_buf_push(buf, sizeof(struct bt_att_hdr)); err = bt_smp_sign_verify(conn, buf); if (err) { BT_ERR("Error verifying data"); /* No response for this command */ return 0; } net_buf_pull(buf, sizeof(struct bt_att_hdr)); net_buf_pull(buf, sizeof(*req)); return att_write_rsp(chan, 0, 0, handle, 0, buf->data, buf->len - sizeof(struct bt_att_signature)); } #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_GATT_CLIENT) #if defined(CONFIG_BT_SMP) static int att_change_security(struct bt_conn *conn, u8_t err) { bt_security_t sec; switch (err) { case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION: if (conn->sec_level >= BT_SECURITY_L2) return -EALREADY; sec = BT_SECURITY_L2; break; case BT_ATT_ERR_AUTHENTICATION: if (conn->sec_level < BT_SECURITY_L2) { /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] * page 375: * * If an LTK is not available, the service request * shall be rejected with the error code 'Insufficient * Authentication'. * Note: When the link is not encrypted, the error code * "Insufficient Authentication" does not indicate that * MITM protection is required. */ sec = BT_SECURITY_L2; } else if (conn->sec_level < BT_SECURITY_L3) { /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] * page 375: * * If an authenticated pairing is required but only an * unauthenticated pairing has occurred and the link is * currently encrypted, the service request shall be * rejected with the error code 'Insufficient * Authentication'. * Note: When unauthenticated pairing has occurred and * the link is currently encrypted, the error code * 'Insufficient Authentication' indicates that MITM * protection is required. */ sec = BT_SECURITY_L3; } else if (conn->sec_level < BT_SECURITY_L4) { /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] * page 375: * * If LE Secure Connections authenticated pairing is * required but LE legacy pairing has occurred and the * link is currently encrypted, the service request * shall be rejected with the error code ''Insufficient * Authentication'. */ sec = BT_SECURITY_L4; } else { return -EALREADY; } break; default: return -EINVAL; } return bt_conn_set_security(conn, sec); } #endif /* CONFIG_BT_SMP */ static u8_t att_error_rsp(struct bt_att_chan *chan, struct net_buf *buf) { struct bt_att_error_rsp *rsp; u8_t err; rsp = (void *)buf->data; BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request, sys_le16_to_cpu(rsp->handle), rsp->error); /* Don't retry if there is no req pending or it has been cancelled */ if (!chan->req || chan->req == &cancel) { err = BT_ATT_ERR_UNLIKELY; goto done; } if (chan->req->buf) { /* Restore state to be resent */ net_buf_simple_restore(&chan->req->buf->b, &chan->req->state); } err = rsp->error; #if defined(CONFIG_BT_SMP) if (chan->req->retrying) { goto done; } /* Check if security needs to be changed */ if (!att_change_security(chan->chan.chan.conn, err)) { chan->req->retrying = true; /* Wait security_changed: TODO: Handle fail case */ return 0; } #endif /* CONFIG_BT_SMP */ done: return att_handle_rsp(chan, NULL, 0, err); } static u8_t att_handle_find_info_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_find_type_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_read_type_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_read_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_read_blob_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } #if defined(CONFIG_BT_GATT_READ_MULTIPLE) static u8_t att_handle_read_mult_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } #if defined(CONFIG_BT_EATT) static u8_t att_handle_read_mult_vl_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } #endif /* CONFIG_BT_EATT */ #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ static u8_t att_handle_read_group_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_write_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_prepare_write_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_handle_exec_write_rsp(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static u8_t att_notify(struct bt_att_chan *chan, struct net_buf *buf) { u16_t handle; handle = net_buf_pull_le16(buf); BT_DBG("chan %p handle 0x%04x", chan, handle); bt_gatt_notification(chan->att->conn, handle, buf->data, buf->len); return 0; } static u8_t att_indicate(struct bt_att_chan *chan, struct net_buf *buf) { u16_t handle; handle = net_buf_pull_le16(buf); BT_DBG("chan %p handle 0x%04x", chan, handle); bt_gatt_notification(chan->att->conn, handle, buf->data, buf->len); buf = bt_att_chan_create_pdu(chan, BT_ATT_OP_CONFIRM, 0); if (!buf) { return 0; } (void)bt_att_chan_send(chan, buf, chan_cfm_sent); return 0; } static u8_t att_notify_mult(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG("chan %p", chan); bt_gatt_mult_notification(chan->att->conn, buf->data, buf->len); return 0; } #endif /* CONFIG_BT_GATT_CLIENT */ static u8_t att_confirm(struct bt_att_chan *chan, struct net_buf *buf) { BT_DBG(""); return att_handle_rsp(chan, buf->data, buf->len, 0); } static const struct att_handler { u8_t op; u8_t expect_len; att_type_t type; u8_t (*func)(struct bt_att_chan *chan, struct net_buf *buf); } handlers[] = { { BT_ATT_OP_MTU_REQ, sizeof(struct bt_att_exchange_mtu_req), ATT_REQUEST, att_mtu_req }, { BT_ATT_OP_FIND_INFO_REQ, sizeof(struct bt_att_find_info_req), ATT_REQUEST, att_find_info_req }, { BT_ATT_OP_FIND_TYPE_REQ, sizeof(struct bt_att_find_type_req), ATT_REQUEST, att_find_type_req }, { BT_ATT_OP_READ_TYPE_REQ, sizeof(struct bt_att_read_type_req), ATT_REQUEST, att_read_type_req }, { BT_ATT_OP_READ_REQ, sizeof(struct bt_att_read_req), ATT_REQUEST, att_read_req }, { BT_ATT_OP_READ_BLOB_REQ, sizeof(struct bt_att_read_blob_req), ATT_REQUEST, att_read_blob_req }, #if defined(CONFIG_BT_GATT_READ_MULTIPLE) { BT_ATT_OP_READ_MULT_REQ, BT_ATT_READ_MULT_MIN_LEN_REQ, ATT_REQUEST, att_read_mult_req }, #if defined(CONFIG_BT_EATT) { BT_ATT_OP_READ_MULT_VL_REQ, BT_ATT_READ_MULT_MIN_LEN_REQ, ATT_REQUEST, att_read_mult_vl_req }, #endif /* CONFIG_BT_EATT */ #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ { BT_ATT_OP_READ_GROUP_REQ, sizeof(struct bt_att_read_group_req), ATT_REQUEST, att_read_group_req }, { BT_ATT_OP_WRITE_REQ, sizeof(struct bt_att_write_req), ATT_REQUEST, att_write_req }, { BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(struct bt_att_prepare_write_req), ATT_REQUEST, att_prepare_write_req }, { BT_ATT_OP_EXEC_WRITE_REQ, sizeof(struct bt_att_exec_write_req), ATT_REQUEST, att_exec_write_req }, { BT_ATT_OP_CONFIRM, 0, ATT_CONFIRMATION, att_confirm }, { BT_ATT_OP_WRITE_CMD, sizeof(struct bt_att_write_cmd), ATT_COMMAND, att_write_cmd }, #if defined(CONFIG_BT_SIGNING) { BT_ATT_OP_SIGNED_WRITE_CMD, (sizeof(struct bt_att_write_cmd) + sizeof(struct bt_att_signature)), ATT_COMMAND, att_signed_write_cmd }, #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_GATT_CLIENT) { BT_ATT_OP_ERROR_RSP, sizeof(struct bt_att_error_rsp), ATT_RESPONSE, att_error_rsp }, { BT_ATT_OP_MTU_RSP, sizeof(struct bt_att_exchange_mtu_rsp), ATT_RESPONSE, att_mtu_rsp }, { BT_ATT_OP_FIND_INFO_RSP, sizeof(struct bt_att_find_info_rsp), ATT_RESPONSE, att_handle_find_info_rsp }, { BT_ATT_OP_FIND_TYPE_RSP, sizeof(struct bt_att_find_type_rsp), ATT_RESPONSE, att_handle_find_type_rsp }, { BT_ATT_OP_READ_TYPE_RSP, sizeof(struct bt_att_read_type_rsp), ATT_RESPONSE, att_handle_read_type_rsp }, { BT_ATT_OP_READ_RSP, sizeof(struct bt_att_read_rsp), ATT_RESPONSE, att_handle_read_rsp }, { BT_ATT_OP_READ_BLOB_RSP, sizeof(struct bt_att_read_blob_rsp), ATT_RESPONSE, att_handle_read_blob_rsp }, #if defined(CONFIG_BT_GATT_READ_MULTIPLE) { BT_ATT_OP_READ_MULT_RSP, sizeof(struct bt_att_read_mult_rsp), ATT_RESPONSE, att_handle_read_mult_rsp }, #if defined(CONFIG_BT_EATT) { BT_ATT_OP_READ_MULT_VL_RSP, sizeof(struct bt_att_read_mult_vl_rsp), ATT_RESPONSE, att_handle_read_mult_vl_rsp }, #endif /* CONFIG_BT_EATT */ #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ { BT_ATT_OP_READ_GROUP_RSP, sizeof(struct bt_att_read_group_rsp), ATT_RESPONSE, att_handle_read_group_rsp }, { BT_ATT_OP_WRITE_RSP, 0, ATT_RESPONSE, att_handle_write_rsp }, { BT_ATT_OP_PREPARE_WRITE_RSP, sizeof(struct bt_att_prepare_write_rsp), ATT_RESPONSE, att_handle_prepare_write_rsp }, { BT_ATT_OP_EXEC_WRITE_RSP, 0, ATT_RESPONSE, att_handle_exec_write_rsp }, { BT_ATT_OP_NOTIFY, sizeof(struct bt_att_notify), ATT_NOTIFICATION, att_notify }, { BT_ATT_OP_INDICATE, sizeof(struct bt_att_indicate), ATT_INDICATION, att_indicate }, { BT_ATT_OP_NOTIFY_MULT, sizeof(struct bt_att_notify_mult), ATT_NOTIFICATION, att_notify_mult }, #endif /* CONFIG_BT_GATT_CLIENT */ }; static att_type_t att_op_get_type(u8_t op) { switch (op) { case BT_ATT_OP_MTU_REQ: case BT_ATT_OP_FIND_INFO_REQ: case BT_ATT_OP_FIND_TYPE_REQ: case BT_ATT_OP_READ_TYPE_REQ: case BT_ATT_OP_READ_REQ: case BT_ATT_OP_READ_BLOB_REQ: case BT_ATT_OP_READ_MULT_REQ: case BT_ATT_OP_READ_GROUP_REQ: case BT_ATT_OP_WRITE_REQ: case BT_ATT_OP_PREPARE_WRITE_REQ: case BT_ATT_OP_EXEC_WRITE_REQ: return ATT_REQUEST; case BT_ATT_OP_CONFIRM: return ATT_CONFIRMATION; case BT_ATT_OP_WRITE_CMD: case BT_ATT_OP_SIGNED_WRITE_CMD: return ATT_COMMAND; case BT_ATT_OP_ERROR_RSP: case BT_ATT_OP_MTU_RSP: case BT_ATT_OP_FIND_INFO_RSP: case BT_ATT_OP_FIND_TYPE_RSP: case BT_ATT_OP_READ_TYPE_RSP: case BT_ATT_OP_READ_RSP: case BT_ATT_OP_READ_BLOB_RSP: case BT_ATT_OP_READ_MULT_RSP: case BT_ATT_OP_READ_GROUP_RSP: case BT_ATT_OP_WRITE_RSP: case BT_ATT_OP_PREPARE_WRITE_RSP: case BT_ATT_OP_EXEC_WRITE_RSP: return ATT_RESPONSE; case BT_ATT_OP_NOTIFY: return ATT_NOTIFICATION; case BT_ATT_OP_INDICATE: return ATT_INDICATION; } if (op & ATT_CMD_MASK) { return ATT_COMMAND; } return ATT_UNKNOWN; } static int bt_att_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_att_chan *att_chan = ATT_CHAN(chan); struct bt_att_hdr *hdr; const struct att_handler *handler; u8_t err; size_t i; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small ATT PDU received"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_DBG("Received ATT chan %p code 0x%02x len %u", att_chan, hdr->code, net_buf_frags_len(buf)); for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) { if (hdr->code == handlers[i].op) { handler = &handlers[i]; break; } } if (!handler) { BT_WARN("Unhandled ATT code 0x%02x", hdr->code); if (att_op_get_type(hdr->code) != ATT_COMMAND) { send_err_rsp(att_chan, hdr->code, 0, BT_ATT_ERR_NOT_SUPPORTED); } return 0; } if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { if (handler->type == ATT_REQUEST && atomic_test_and_set_bit(att_chan->flags, ATT_PENDING_RSP)) { BT_WARN("Ignoring unexpected request"); return 0; } else if (handler->type == ATT_INDICATION && atomic_test_and_set_bit(att_chan->flags, ATT_PENDING_CFM)) { BT_WARN("Ignoring unexpected indication"); return 0; } } if (buf->len < handler->expect_len) { BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); err = BT_ATT_ERR_INVALID_PDU; } else { err = handler->func(att_chan, buf); } if (handler->type == ATT_REQUEST && err) { BT_DBG("ATT error 0x%02x", err); send_err_rsp(att_chan, hdr->code, 0, err); } return 0; } static struct bt_att *att_get(struct bt_conn *conn) { struct bt_l2cap_chan *chan; struct bt_att_chan *att_chan; if (conn->state != BT_CONN_CONNECTED) { BT_WARN("Not connected"); return NULL; } chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT); if (!chan) { BT_ERR("Unable to find ATT channel"); return NULL; } att_chan = ATT_CHAN(chan); if (atomic_test_bit(att_chan->flags, ATT_DISCONNECTED)) { BT_WARN("ATT channel flagged as disconnected"); return NULL; } return att_chan->att; } struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len) { struct bt_att *att; struct bt_att_chan *chan, *tmp; att = att_get(conn); if (!att) { return NULL; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->chans, chan, tmp, node) { if (len + sizeof(op) > chan->chan.tx.mtu) { continue; } return bt_att_chan_create_pdu(chan, op, len); } BT_WARN("No ATT channel for MTU %zu", len + sizeof(op)); return NULL; } static void att_reset(struct bt_att *att) { struct bt_att_req *req, *tmp; struct net_buf *buf; #if CONFIG_BT_ATT_PREPARE_COUNT > 0 /* Discard queued buffers */ while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) { net_buf_unref(buf); } #endif /* CONFIG_BT_ATT_PREPARE_COUNT > 0 */ while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) { net_buf_unref(buf); } att->conn = NULL; /* Notify pending requests */ SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node) { if (req->func) { req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req->user_data); } att_req_destroy(req); } // k_mem_slab_free(&att_slab, (void **)&att); att->used = 0; att = NULL; } static void att_chan_detach(struct bt_att_chan *chan) { int i; BT_DBG("chan %p", chan); sys_slist_find_and_remove(&chan->att->chans, &chan->node); /* Ensure that any waiters are woken up */ for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) { k_sem_give(&chan->tx_sem); } if (chan->req) { /* Notify outstanding request */ att_handle_rsp(chan, NULL, 0, BT_ATT_ERR_UNLIKELY); } chan->att = NULL; } static void att_timeout(struct k_work *work) { struct bt_att_chan *chan = CONTAINER_OF(work, struct bt_att_chan, timeout_work); struct bt_att *att = chan->att; struct bt_l2cap_le_chan *ch = &chan->chan; BT_ERR("ATT Timeout"); /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480: * * A transaction not completed within 30 seconds shall time out. Such a * transaction shall be considered to have failed and the local higher * layers shall be informed of this failure. No more attribute protocol * requests, commands, indications or notifications shall be sent to the * target device on this ATT Bearer. */ att_chan_detach(chan); /* Don't notify if there are still channels to be used */ if (!sys_slist_is_empty(&att->chans)) { return; } att_reset(att); /* Consider the channel disconnected */ bt_gatt_disconnected(ch->chan.conn); ch->chan.conn = NULL; } static struct bt_att_chan *att_get_fixed_chan(struct bt_conn *conn) { struct bt_l2cap_chan *chan; chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT); __ASSERT(chan, "No ATT channel found"); return ATT_CHAN(chan); } static void att_chan_attach(struct bt_att *att, struct bt_att_chan *chan) { BT_DBG("att %p chan %p flags %u", att, chan, atomic_get(chan->flags)); if (sys_slist_is_empty(&att->chans)) { /* Init general queues when attaching the first channel */ k_fifo_init(&att->tx_queue); #if CONFIG_BT_ATT_PREPARE_COUNT > 0 k_fifo_init(&att->prep_queue); #endif } sys_slist_prepend(&att->chans, &chan->node); } static void bt_att_connected(struct bt_l2cap_chan *chan) { struct bt_att_chan *att_chan = att_get_fixed_chan(chan->conn); struct bt_att *att = att_chan->att; struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); att_chan = ATT_CHAN(chan); att_chan_attach(att, att_chan); if (!atomic_test_bit(att_chan->flags, ATT_ENHANCED)) { ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU; ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU; } k_delayed_work_init(&att_chan->timeout_work, att_timeout); } static void bt_att_disconnected(struct bt_l2cap_chan *chan) { struct bt_att_chan *att_chan = ATT_CHAN(chan); struct bt_att *att = att_chan->att; struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); att_chan_detach(att_chan); /* Don't reset if there are still channels to be used */ if (!sys_slist_is_empty(&att->chans)) { return; } att_reset(att); bt_gatt_disconnected(ch->chan.conn); } #if defined(CONFIG_BT_SMP) static void bt_att_encrypt_change(struct bt_l2cap_chan *chan, u8_t hci_status) { struct bt_att_chan *att_chan = ATT_CHAN(chan); struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct bt_conn *conn = ch->chan.conn; BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch, conn, conn->handle, conn->sec_level, hci_status); /* * If status (HCI status of security procedure) is non-zero, notify * outstanding request about security failure. */ if (hci_status) { att_handle_rsp(att_chan, NULL, 0, BT_ATT_ERR_AUTHENTICATION); return; } bt_gatt_encrypt_change(conn); if (conn->sec_level == BT_SECURITY_L1) { return; } if (!att_chan->req || !att_chan->req->retrying) { return; } BT_DBG("Retrying"); /* Resend buffer */ (void)bt_att_chan_send(att_chan, att_chan->req->buf, chan_cb(att_chan->req->buf)); att_chan->req->buf = NULL; } #endif /* CONFIG_BT_SMP */ static void bt_att_status(struct bt_l2cap_chan *ch, atomic_t *status) { struct bt_att_chan *chan = ATT_CHAN(ch); sys_snode_t *node; BT_DBG("chan %p status %p", ch, status); if (!atomic_test_bit(status, BT_L2CAP_STATUS_OUT)) { return; } /* If there is a request pending don't attempt to send */ if (chan->req) { return; } /* Pull next request from the list */ node = sys_slist_get(&chan->att->reqs); if (!node) { return; } if (bt_att_chan_req_send(chan, ATT_REQ(node)) >= 0) { return; } /* Prepend back to the list as it could not be sent */ sys_slist_prepend(&chan->att->reqs, node); } static void bt_att_released(struct bt_l2cap_chan *ch) { struct bt_att_chan *chan = ATT_CHAN(ch); BT_DBG("chan %p", chan); // k_mem_slab_free(&chan_slab, (void **)&chan); k_sem_delete(&chan->tx_sem); chan->used = 0; chan = NULL; } static struct bt_att_chan *att_chan_new(struct bt_att *att, atomic_val_t flags) { int quota = 0; static struct bt_l2cap_chan_ops ops = { .connected = bt_att_connected, .disconnected = bt_att_disconnected, .recv = bt_att_recv, .sent = bt_att_sent, .status = bt_att_status, #if defined(CONFIG_BT_SMP) .encrypt_change = bt_att_encrypt_change, #endif /* CONFIG_BT_SMP */ .released = bt_att_released, }; struct bt_att_chan *chan = NULL; SYS_SLIST_FOR_EACH_CONTAINER(&att->chans, chan, node) { if (chan->att == att) { quota++; } if (quota == ATT_CHAN_MAX) { BT_ERR("Maximum number of channels reached: %d", quota); return NULL; } } // if (k_mem_slab_alloc(&chan_slab, (void **)&chan, K_NO_WAIT)) { // BT_ERR("No available ATT channel for conn %p", att->conn); // return NULL; // } k_mem_slab_alloc_chan(chan); if (!chan) { BT_ERR("No available ATT channel for conn %p", att->conn); return NULL; } // (void)memset(chan, 0, sizeof(*chan)); chan->chan.chan.ops = &ops; k_sem_init(&chan->tx_sem, CONFIG_BT_ATT_TX_MAX, CONFIG_BT_ATT_TX_MAX); atomic_set(chan->flags, flags); chan->att = att; return chan; } static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **ch) { struct bt_att *att = NULL; struct bt_att_chan *chan = NULL; BT_DBG("conn %p handle %u", conn, conn->handle); // if (k_mem_slab_alloc(&att_slab, (void **)&att, K_NO_WAIT)) { // BT_ERR("No available ATT context for conn %p", conn); // return -ENOMEM; // } // (void)memset(att, 0, sizeof(*att)); k_mem_slab_alloc_att(att); if (!att) { BT_ERR("No available ATT context for conn %p", conn); return -ENOMEM; } att->conn = conn; sys_slist_init(&att->reqs); sys_slist_init(&att->chans); chan = att_chan_new(att, 0); if (!chan) { return -ENOMEM; } *ch = &chan->chan.chan; return 0; } BT_L2CAP_CHANNEL_DEFINE(att_fixed_chan, BT_L2CAP_CID_ATT, bt_att_accept, NULL); #if defined(CONFIG_BT_EATT) int bt_eatt_connect(struct bt_conn *conn, u8_t num_channels) { struct bt_att_chan *att_chan = att_get_fixed_chan(conn); struct bt_att *att = att_chan->att; struct bt_l2cap_chan *chan[CONFIG_BT_EATT_MAX] = {}; int i = 0; if (num_channels > CONFIG_BT_EATT_MAX) { return -EINVAL; } while (num_channels--) { att_chan = att_chan_new(att, BIT(ATT_ENHANCED)); if (!att_chan) { break; } chan[i] = &att_chan->chan.chan; i++; } if (!i) { return -ENOMEM; } return bt_l2cap_ecred_chan_connect(conn, chan, BT_EATT_PSM); } int bt_eatt_disconnect(struct bt_conn *conn) { struct bt_att_chan *chan = att_get_fixed_chan(conn); struct bt_att *att = chan->att; int err = -ENOTCONN; if (!conn) { return -EINVAL; } SYS_SLIST_FOR_EACH_CONTAINER(&att->chans, chan, node) { if (atomic_test_bit(chan->flags, ATT_ENHANCED)) { err = bt_l2cap_chan_disconnect(&chan->chan.chan); } } return err; } #endif /* CONFIG_BT_EATT */ static int bt_eatt_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { struct bt_att_chan *att_chan = att_get_fixed_chan(conn); struct bt_att *att = att_chan->att; BT_DBG("conn %p handle %u", conn, conn->handle); att_chan = att_chan_new(att, BIT(ATT_ENHANCED)); if (att_chan) { *chan = &att_chan->chan.chan; return 0; } return -ENOMEM; } static void bt_eatt_init(void) { int err; static struct bt_l2cap_server eatt_l2cap = { .psm = BT_EATT_PSM, #if defined(CONFIG_BT_EATT_SEC_LEVEL) .sec_level = CONFIG_BT_EATT_SEC_LEVEL, #endif .accept = bt_eatt_accept, }; BT_DBG(""); err = bt_l2cap_server_register(&eatt_l2cap); if (err < 0) { BT_ERR("EATT Server registration failed %d", err); } } void bt_att_init(void) { bt_l2cap_le_fixed_chan_register(&att_fixed_chan); bt_gatt_init(); #if CONFIG_BT_ATT_PREPARE_COUNT > 0 NET_BUF_POOL_INIT(prep_pool); #endif if (IS_ENABLED(CONFIG_BT_EATT)) { bt_eatt_init(); } } u16_t bt_att_get_mtu(struct bt_conn *conn) { struct bt_att_chan *chan, *tmp; struct bt_att *att; u16_t mtu = 0; att = att_get(conn); if (!att) { return 0; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->chans, chan, tmp, node) { if (chan->chan.tx.mtu > mtu) { mtu = chan->chan.tx.mtu; } } return mtu; } struct bt_att_req *bt_att_req_alloc(k_timeout_t timeout) { struct bt_att_req *req = NULL; k_mem_slab_alloc_req(req); BT_DBG("req %p", req); return req; } void bt_att_req_free(struct bt_att_req *req) { BT_DBG("req %p", req); // k_mem_slab_free(&req_slab, (void **)&req); req->used = 0; req = NULL; } int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) { struct bt_att_chan *chan, *tmp; struct bt_att *att; int ret; __ASSERT_NO_MSG(conn); __ASSERT_NO_MSG(buf); att = att_get(conn); if (!att) { net_buf_unref(buf); return -ENOTCONN; } /* If callback is set use the fixed channel since bt_l2cap_chan_send * cannot be used with a custom user_data. */ if (cb) { bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, cb, user_data); return 0; } ret = 0; SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->chans, chan, tmp, node) { ret = bt_att_chan_send(chan, buf, NULL); if (ret >= 0) { break; } } if (ret < 0) { /* Queue buffer to be send later */ BT_DBG("Queueing buffer %p", buf); k_fifo_put(&att->tx_queue, buf); } return 0; } int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req) { struct bt_att *att; struct bt_att_chan *chan, *tmp; BT_DBG("conn %p req %p", conn, req); __ASSERT_NO_MSG(conn); __ASSERT_NO_MSG(req); att = att_get(conn); if (!att) { net_buf_unref(req->buf); req->buf = NULL; return -ENOTCONN; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->chans, chan, tmp, node) { /* If there is nothing pending use the channel */ if (!chan->req) { int ret; ret = bt_att_chan_req_send(chan, req); if (ret >= 0) { return ret; } } } /* Queue the request to be send later */ sys_slist_append(&att->reqs, &req->node); BT_DBG("req %p queued", req); return 0; } static bool bt_att_chan_req_cancel(struct bt_att_chan *chan, struct bt_att_req *req) { if (chan->req != req) { return false; } chan->req = &cancel; att_req_destroy(req); return true; } void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req) { struct bt_att *att; struct bt_att_chan *chan, *tmp; BT_DBG("req %p", req); if (!conn || !req) { return; } att = att_get(conn); if (!att) { return; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->chans, chan, tmp, node) { /* Check if request is outstanding */ if (bt_att_chan_req_cancel(chan, req)) { return; } } /* Remove request from the list */ sys_slist_find_and_remove(&att->reqs, &req->node); att_req_destroy(req); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/att.c
C
apache-2.0
70,795
/* att_internal.h - Attribute protocol handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #define BT_EATT_PSM 0x27 #define BT_ATT_DEFAULT_LE_MTU 23 #define BT_ATT_TIMEOUT K_SECONDS(30) #if BT_L2CAP_RX_MTU < CONFIG_BT_L2CAP_TX_MTU #define BT_ATT_MTU BT_L2CAP_RX_MTU #else #define BT_ATT_MTU CONFIG_BT_L2CAP_TX_MTU #endif struct bt_att_hdr { u8_t code; } __packed; #define BT_ATT_OP_ERROR_RSP 0x01 struct bt_att_error_rsp { u8_t request; u16_t handle; u8_t error; } __packed; #define BT_ATT_OP_MTU_REQ 0x02 struct bt_att_exchange_mtu_req { u16_t mtu; } __packed; #define BT_ATT_OP_MTU_RSP 0x03 struct bt_att_exchange_mtu_rsp { u16_t mtu; } __packed; /* Find Information Request */ #define BT_ATT_OP_FIND_INFO_REQ 0x04 struct bt_att_find_info_req { u16_t start_handle; u16_t end_handle; } __packed; /* Format field values for BT_ATT_OP_FIND_INFO_RSP */ #define BT_ATT_INFO_16 0x01 #define BT_ATT_INFO_128 0x02 struct bt_att_info_16 { u16_t handle; u16_t uuid; } __packed; struct bt_att_info_128 { u16_t handle; u8_t uuid[16]; } __packed; /* Find Information Response */ #define BT_ATT_OP_FIND_INFO_RSP 0x05 struct bt_att_find_info_rsp { u8_t format; u8_t info[0]; } __packed; /* Find By Type Value Request */ #define BT_ATT_OP_FIND_TYPE_REQ 0x06 struct bt_att_find_type_req { u16_t start_handle; u16_t end_handle; u16_t type; u8_t value[0]; } __packed; struct bt_att_handle_group { u16_t start_handle; u16_t end_handle; } __packed; /* Find By Type Value Response */ #define BT_ATT_OP_FIND_TYPE_RSP 0x07 struct bt_att_find_type_rsp { struct bt_att_handle_group list[0]; } __packed; /* Read By Type Request */ #define BT_ATT_OP_READ_TYPE_REQ 0x08 struct bt_att_read_type_req { u16_t start_handle; u16_t end_handle; u8_t uuid[0]; } __packed; struct bt_att_data { u16_t handle; u8_t value[0]; } __packed; /* Read By Type Response */ #define BT_ATT_OP_READ_TYPE_RSP 0x09 struct bt_att_read_type_rsp { u8_t len; struct bt_att_data data[0]; } __packed; /* Read Request */ #define BT_ATT_OP_READ_REQ 0x0a struct bt_att_read_req { u16_t handle; } __packed; /* Read Response */ #define BT_ATT_OP_READ_RSP 0x0b struct bt_att_read_rsp { u8_t value[0]; } __packed; /* Read Blob Request */ #define BT_ATT_OP_READ_BLOB_REQ 0x0c struct bt_att_read_blob_req { u16_t handle; u16_t offset; } __packed; /* Read Blob Response */ #define BT_ATT_OP_READ_BLOB_RSP 0x0d struct bt_att_read_blob_rsp { u8_t value[0]; } __packed; /* Read Multiple Request */ #define BT_ATT_READ_MULT_MIN_LEN_REQ 0x04 #define BT_ATT_OP_READ_MULT_REQ 0x0e struct bt_att_read_mult_req { u16_t handles[0]; } __packed; /* Read Multiple Respose */ #define BT_ATT_OP_READ_MULT_RSP 0x0f struct bt_att_read_mult_rsp { u8_t value[0]; } __packed; /* Read by Group Type Request */ #define BT_ATT_OP_READ_GROUP_REQ 0x10 struct bt_att_read_group_req { u16_t start_handle; u16_t end_handle; u8_t uuid[0]; } __packed; struct bt_att_group_data { u16_t start_handle; u16_t end_handle; u8_t value[0]; } __packed; /* Read by Group Type Response */ #define BT_ATT_OP_READ_GROUP_RSP 0x11 struct bt_att_read_group_rsp { u8_t len; struct bt_att_group_data data[0]; } __packed; /* Write Request */ #define BT_ATT_OP_WRITE_REQ 0x12 struct bt_att_write_req { u16_t handle; u8_t value[0]; } __packed; /* Write Response */ #define BT_ATT_OP_WRITE_RSP 0x13 /* Prepare Write Request */ #define BT_ATT_OP_PREPARE_WRITE_REQ 0x16 struct bt_att_prepare_write_req { u16_t handle; u16_t offset; u8_t value[0]; } __packed; /* Prepare Write Respond */ #define BT_ATT_OP_PREPARE_WRITE_RSP 0x17 struct bt_att_prepare_write_rsp { u16_t handle; u16_t offset; u8_t value[0]; } __packed; /* Execute Write Request */ #define BT_ATT_FLAG_CANCEL 0x00 #define BT_ATT_FLAG_EXEC 0x01 #define BT_ATT_OP_EXEC_WRITE_REQ 0x18 struct bt_att_exec_write_req { u8_t flags; } __packed; /* Execute Write Response */ #define BT_ATT_OP_EXEC_WRITE_RSP 0x19 /* Handle Value Notification */ #define BT_ATT_OP_NOTIFY 0x1b struct bt_att_notify { u16_t handle; u8_t value[0]; } __packed; /* Handle Value Indication */ #define BT_ATT_OP_INDICATE 0x1d struct bt_att_indicate { u16_t handle; u8_t value[0]; } __packed; /* Handle Value Confirm */ #define BT_ATT_OP_CONFIRM 0x1e struct bt_att_signature { u8_t value[12]; } __packed; #define BT_ATT_OP_READ_MULT_VL_REQ 0x20 struct bt_att_read_mult_vl_req { u16_t handles[0]; } __packed; /* Read Multiple Respose */ #define BT_ATT_OP_READ_MULT_VL_RSP 0x21 struct bt_att_read_mult_vl_rsp { u16_t len; u8_t value[0]; } __packed; /* Handle Multiple Value Notification */ #define BT_ATT_OP_NOTIFY_MULT 0x23 struct bt_att_notify_mult { u16_t handle; u16_t len; u8_t value[0]; } __packed; /* Write Command */ #define BT_ATT_OP_WRITE_CMD 0x52 struct bt_att_write_cmd { u16_t handle; u8_t value[0]; } __packed; /* Signed Write Command */ #define BT_ATT_OP_SIGNED_WRITE_CMD 0xd2 struct bt_att_signed_write_cmd { u16_t handle; u8_t value[0]; } __packed; typedef void (*bt_att_func_t)(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data); typedef void (*bt_att_destroy_t)(void *user_data); /* ATT request context */ struct bt_att_req { sys_snode_t node; bt_att_func_t func; bt_att_destroy_t destroy; struct net_buf_simple_state state; struct net_buf *buf; #if defined(CONFIG_BT_SMP) bool retrying; #endif /* CONFIG_BT_SMP */ void *user_data; bool used; }; void att_sent(struct bt_conn *conn, void *user_data); void bt_att_init(void); u16_t bt_att_get_mtu(struct bt_conn *conn); struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len); /* Allocate a new request */ struct bt_att_req *bt_att_req_alloc(k_timeout_t timeout); /* Free a request */ void bt_att_req_free(struct bt_att_req *req); /* Send ATT PDU over a connection */ int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data); /* Send ATT Request over a connection */ int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req); /* Cancel ATT request */ void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req); /* Connect EATT channels */ int bt_eatt_connect(struct bt_conn *conn, u8_t num_channels); /* Disconnect EATT channels */ int bt_eatt_disconnect(struct bt_conn *conn);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/att_internal.h
C
apache-2.0
6,460
/* * Audio Video Distribution Protocol * * SPDX-License-Identifier: Apache-2.0 * */ #include <ble_os.h> #include <string.h> // #include <strings.h> #include <bt_errno.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/l2cap.h> #include <bluetooth/avdtp.h> #ifdef CONFIG_BT_AVDTP #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_AVDTP) #define LOG_MODULE_NAME bt_avdtp #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "avdtp_internal.h" #define AVDTP_MSG_POISTION 0x00 #define AVDTP_PKT_POSITION 0x02 #define AVDTP_TID_POSITION 0x04 #define AVDTP_SIGID_MASK 0x3f #define AVDTP_GET_TR_ID(hdr) ((hdr & 0xf0) >> AVDTP_TID_POSITION) #define AVDTP_GET_MSG_TYPE(hdr) (hdr & 0x03) #define AVDTP_GET_PKT_TYPE(hdr) ((hdr & 0x0c) >> AVDTP_PKT_POSITION) #define AVDTP_GET_SIG_ID(s) (s & AVDTP_SIGID_MASK) static struct bt_avdtp_event_cb *event_cb; static struct bt_avdtp_seid_lsep *lseps; #define AVDTP_CHAN(_ch) CONTAINER_OF(_ch, struct bt_avdtp, br_chan.chan) #define AVDTP_KWORK(_work) CONTAINER_OF(_work, struct bt_avdtp_req,\ timeout_work) #define AVDTP_TIMEOUT K_SECONDS(6) static const struct { u8_t sig_id; void (*func)(struct bt_avdtp *session, struct net_buf *buf, u8_t msg_type); } handler[] = { }; static int avdtp_send(struct bt_avdtp *session, struct net_buf *buf, struct bt_avdtp_req *req) { int result; struct bt_avdtp_single_sig_hdr *hdr; hdr = (struct bt_avdtp_single_sig_hdr *)buf->data; result = bt_l2cap_chan_send(&session->br_chan.chan, buf); if (result < 0) { BT_ERR("Error:L2CAP send fail - result = %d", result); return result; } /*Save the sent request*/ req->sig = AVDTP_GET_SIG_ID(hdr->signal_id); req->tid = AVDTP_GET_TR_ID(hdr->hdr); BT_DBG("sig 0x%02X, tid 0x%02X", req->sig, req->tid); session->req = req; /* Start timeout work */ k_delayed_work_submit(&session->req->timeout_work, AVDTP_TIMEOUT); return result; } static struct net_buf *avdtp_create_pdu(u8_t msg_type, u8_t pkt_type, u8_t sig_id) { struct net_buf *buf; static u8_t tid; struct bt_avdtp_single_sig_hdr *hdr; BT_DBG(""); buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->hdr = (msg_type | pkt_type << AVDTP_PKT_POSITION | tid++ << AVDTP_TID_POSITION); tid %= 16; /* Loop for 16*/ hdr->signal_id = sig_id & AVDTP_SIGID_MASK; BT_DBG("hdr = 0x%02X, Signal_ID = 0x%02X", hdr->hdr, hdr->signal_id); return buf; } /* Timeout handler */ static void avdtp_timeout(struct k_work *work) { BT_DBG("Failed Signal_id = %d", (AVDTP_KWORK(work))->sig); /* Gracefully Disconnect the Signalling and streaming L2cap chann*/ } /* L2CAP Interface callbacks */ void bt_avdtp_l2cap_connected(struct bt_l2cap_chan *chan) { struct bt_avdtp *session; if (!chan) { BT_ERR("Invalid AVDTP chan"); return; } session = AVDTP_CHAN(chan); BT_DBG("chan %p session %p", chan, session); /* Init the timer */ k_delayed_work_init(&session->req->timeout_work, avdtp_timeout); } void bt_avdtp_l2cap_disconnected(struct bt_l2cap_chan *chan) { struct bt_avdtp *session = AVDTP_CHAN(chan); BT_DBG("chan %p session %p", chan, session); session->br_chan.chan.conn = NULL; /* Clear the Pending req if set*/ } void bt_avdtp_l2cap_encrypt_changed(struct bt_l2cap_chan *chan, u8_t status) { BT_DBG(""); } int bt_avdtp_l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_avdtp_single_sig_hdr *hdr; struct bt_avdtp *session = AVDTP_CHAN(chan); u8_t i, msgtype, sigid, tid; if (buf->len < sizeof(*hdr)) { BT_ERR("Recvd Wrong AVDTP Header"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); msgtype = AVDTP_GET_MSG_TYPE(hdr->hdr); sigid = AVDTP_GET_SIG_ID(hdr->signal_id); tid = AVDTP_GET_TR_ID(hdr->hdr); BT_DBG("msg_type[0x%02x] sig_id[0x%02x] tid[0x%02x]", msgtype, sigid, tid); /* validate if there is an outstanding resp expected*/ if (msgtype != BT_AVDTP_CMD) { if (session->req == NULL) { BT_DBG("Unexpected peer response"); return 0; } if (session->req->sig != sigid || session->req->tid != tid) { BT_DBG("Peer mismatch resp, expected sig[0x%02x]" "tid[0x%02x]", session->req->sig, session->req->tid); return 0; } } for (i = 0U; i < ARRAY_SIZE(handler); i++) { if (sigid == handler[i].sig_id) { handler[i].func(session, buf, msgtype); return 0; } } return 0; } /*A2DP Layer interface */ int bt_avdtp_connect(struct bt_conn *conn, struct bt_avdtp *session) { static const struct bt_l2cap_chan_ops ops = { .connected = bt_avdtp_l2cap_connected, .disconnected = bt_avdtp_l2cap_disconnected, .encrypt_change = bt_avdtp_l2cap_encrypt_changed, .recv = bt_avdtp_l2cap_recv }; if (!session) { return -EINVAL; } session->br_chan.chan.ops = &ops; session->br_chan.chan.required_sec_level = BT_SECURITY_L2; return bt_l2cap_chan_connect(conn, &session->br_chan.chan, BT_L2CAP_PSM_AVDTP); } int bt_avdtp_disconnect(struct bt_avdtp *session) { if (!session) { return -EINVAL; } BT_DBG("session %p", session); return bt_l2cap_chan_disconnect(&session->br_chan.chan); } int bt_avdtp_l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { struct bt_avdtp *session = NULL; int result; static const struct bt_l2cap_chan_ops ops = { .connected = bt_avdtp_l2cap_connected, .disconnected = bt_avdtp_l2cap_disconnected, .recv = bt_avdtp_l2cap_recv, }; BT_DBG("conn %p", conn); /* Get the AVDTP session from upper layer */ result = event_cb->accept(conn, &session); if (result < 0) { return result; } session->br_chan.chan.ops = &ops; session->br_chan.rx.mtu = BT_AVDTP_MAX_MTU; *chan = &session->br_chan.chan; return 0; } /* Application will register its callback */ int bt_avdtp_register(struct bt_avdtp_event_cb *cb) { BT_DBG(""); if (event_cb) { return -EALREADY; } event_cb = cb; return 0; } int bt_avdtp_register_sep(u8_t media_type, u8_t role, struct bt_avdtp_seid_lsep *lsep) { BT_DBG(""); static u8_t bt_avdtp_seid = BT_AVDTP_MIN_SEID; if (!lsep) { return -EIO; } if (bt_avdtp_seid == BT_AVDTP_MAX_SEID) { return -EIO; } lsep->sep.id = bt_avdtp_seid++; lsep->sep.inuse = 0U; lsep->sep.media_type = media_type; lsep->sep.tsep = role; lsep->next = lseps; lseps = lsep; return 0; } /* init function */ int bt_avdtp_init(void) { int err; static struct bt_l2cap_server avdtp_l2cap = { .psm = BT_L2CAP_PSM_AVDTP, .sec_level = BT_SECURITY_L2, .accept = bt_avdtp_l2cap_accept, }; BT_DBG(""); /* Register AVDTP PSM with L2CAP */ err = bt_l2cap_br_server_register(&avdtp_l2cap); if (err < 0) { BT_ERR("AVDTP L2CAP Registration failed %d", err); } return err; } /* AVDTP Discover Request */ int bt_avdtp_discover(struct bt_avdtp *session, struct bt_avdtp_discover_params *param) { struct net_buf *buf; BT_DBG(""); if (!param || !session) { BT_DBG("Error: Callback/Session not valid"); return -EINVAL; } buf = avdtp_create_pdu(BT_AVDTP_CMD, BT_AVDTP_PACKET_TYPE_SINGLE, BT_AVDTP_DISCOVER); if (!buf) { BT_ERR("Error: No Buff available"); return -ENOMEM; } /* Body of the message */ return avdtp_send(session, buf, &param->req); } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/avdtp.c
C
apache-2.0
7,353
/* * avdtp_internal.h - avdtp handling * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bluetooth/avdtp.h> /* @brief A2DP ROLE's */ #define A2DP_SRC_ROLE 0x00 #define A2DP_SNK_ROLE 0x01 /* @brief AVDTP Role */ #define BT_AVDTP_INT 0x00 #define BT_AVDTP_ACP 0x01 #define BT_L2CAP_PSM_AVDTP 0x0019 /* AVDTP SIGNAL HEADER - Packet Type*/ #define BT_AVDTP_PACKET_TYPE_SINGLE 0x00 #define BT_AVDTP_PACKET_TYPE_START 0x01 #define BT_AVDTP_PACKET_TYPE_CONTINUE 0x02 #define BT_AVDTP_PACKET_TYPE_END 0x03 /* AVDTP SIGNAL HEADER - MESSAGE TYPE */ #define BT_AVDTP_CMD 0x00 #define BT_AVDTP_GEN_REJECT 0x01 #define BT_AVDTP_ACCEPT 0x02 #define BT_AVDTP_REJECT 0x03 /* @brief AVDTP SIGNAL HEADER - Signal Identifier */ #define BT_AVDTP_DISCOVER 0x01 #define BT_AVDTP_GET_CAPABILITIES 0x02 #define BT_AVDTP_SET_CONFIGURATION 0x03 #define BT_AVDTP_GET_CONFIGURATION 0x04 #define BT_AVDTP_RECONFIGURE 0x05 #define BT_AVDTP_OPEN 0x06 #define BT_AVDTP_START 0x07 #define BT_AVDTP_CLOSE 0x08 #define BT_AVDTP_SUSPEND 0x09 #define BT_AVDTP_ABORT 0x0a #define BT_AVDTP_SECURITY_CONTROL 0x0b #define BT_AVDTP_GET_ALL_CAPABILITIES 0x0c #define BT_AVDTP_DELAYREPORT 0x0d /* @brief AVDTP STREAM STATE */ #define BT_AVDTP_STREAM_STATE_IDLE 0x01 #define BT_AVDTP_STREAM_STATE_CONFIGURED 0x02 #define BT_AVDTP_STREAM_STATE_OPEN 0x03 #define BT_AVDTP_STREAM_STATE_STREAMING 0x04 #define BT_AVDTP_STREAM_STATE_CLOSING 0x05 /* @brief AVDTP Media TYPE */ #define BT_AVDTP_SERVICE_CAT_MEDIA_TRANSPORT 0x01 #define BT_AVDTP_SERVICE_CAT_REPORTING 0x02 #define BT_AVDTP_SERVICE_CAT_RECOVERY 0x03 #define BT_AVDTP_SERVICE_CAT_CONTENT_PROTECTION 0x04 #define BT_AVDTP_SERVICE_CAT_HDR_COMPRESSION 0x05 #define BT_AVDTP_SERVICE_CAT_MULTIPLEXING 0x06 #define BT_AVDTP_SERVICE_CAT_MEDIA_CODEC 0x07 #define BT_AVDTP_SERVICE_CAT_DELAYREPORTING 0x08 /* AVDTP Error Codes */ #define BT_AVDTP_SUCCESS 0x00 #define BT_AVDTP_ERR_BAD_HDR_FORMAT 0x01 #define BT_AVDTP_ERR_BAD_LENGTH 0x11 #define BT_AVDTP_ERR_BAD_ACP_SEID 0x12 #define BT_AVDTP_ERR_SEP_IN_USE 0x13 #define BT_AVDTP_ERR_SEP_NOT_IN_USE 0x14 #define BT_AVDTP_ERR_BAD_SERV_CATEGORY 0x17 #define BT_AVDTP_ERR_BAD_PAYLOAD_FORMAT 0x18 #define BT_AVDTP_ERR_NOT_SUPPORTED_COMMAND 0x19 #define BT_AVDTP_ERR_INVALID_CAPABILITIES 0x1a #define BT_AVDTP_ERR_BAD_RECOVERY_TYPE 0x22 #define BT_AVDTP_ERR_BAD_MEDIA_TRANSPORT_FORMAT 0x23 #define BT_AVDTP_ERR_BAD_RECOVERY_FORMAT 0x25 #define BT_AVDTP_ERR_BAD_ROHC_FORMAT 0x26 #define BT_AVDTP_ERR_BAD_CP_FORMAT 0x27 #define BT_AVDTP_ERR_BAD_MULTIPLEXING_FORMAT 0x28 #define BT_AVDTP_ERR_UNSUPPORTED_CONFIGURAION 0x29 #define BT_AVDTP_ERR_BAD_STATE 0x31 #define BT_AVDTP_MAX_MTU BT_L2CAP_RX_MTU #define BT_AVDTP_MIN_SEID 0x01 #define BT_AVDTP_MAX_SEID 0x3E struct bt_avdtp; struct bt_avdtp_req; typedef int (*bt_avdtp_func_t)(struct bt_avdtp *session, struct bt_avdtp_req *req); struct bt_avdtp_req { u8_t sig; u8_t tid; bt_avdtp_func_t func; struct k_delayed_work timeout_work; }; struct bt_avdtp_single_sig_hdr { u8_t hdr; u8_t signal_id; } __packed; #define BT_AVDTP_SIG_HDR_LEN sizeof(struct bt_avdtp_single_sig_hdr) struct bt_avdtp_ind_cb { /* * discovery_ind; * get_capabilities_ind; * set_configuration_ind; * open_ind; * start_ind; * suspend_ind; * close_ind; */ }; struct bt_avdtp_cap { u8_t cat; u8_t len; u8_t data[0]; }; struct bt_avdtp_sep { u8_t seid; u8_t len; struct bt_avdtp_cap caps[0]; }; struct bt_avdtp_discover_params { struct bt_avdtp_req req; u8_t status; struct bt_avdtp_sep *caps; }; /** @brief Global AVDTP session structure. */ struct bt_avdtp { struct bt_l2cap_br_chan br_chan; struct bt_avdtp_stream *streams; /* List of AV streams */ struct bt_avdtp_req *req; }; struct bt_avdtp_event_cb { struct bt_avdtp_ind_cb *ind; int (*accept)(struct bt_conn *conn, struct bt_avdtp **session); }; /* Initialize AVDTP layer*/ int bt_avdtp_init(void); /* Application register with AVDTP layer */ int bt_avdtp_register(struct bt_avdtp_event_cb *cb); /* AVDTP connect */ int bt_avdtp_connect(struct bt_conn *conn, struct bt_avdtp *session); /* AVDTP disconnect */ int bt_avdtp_disconnect(struct bt_avdtp *session); /* AVDTP SEP register function */ int bt_avdtp_register_sep(u8_t media_type, u8_t role, struct bt_avdtp_seid_lsep *sep); /* AVDTP Discover Request */ int bt_avdtp_discover(struct bt_avdtp *session, struct bt_avdtp_discover_params *param);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/avdtp_internal.h
C
apache-2.0
4,849
/* conn.c - Bluetooth connection handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <bt_errno.h> #include <stdbool.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <misc/slist.h> #include <misc/stack.h> #include <misc/__assert.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci_driver.h> #include <bluetooth/att.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_CONN) #define LOG_MODULE_NAME bt_conn #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "keys.h" #include "smp.h" #include "att_internal.h" #include "gatt_internal.h" #include <hci_api.h> struct tx_meta { struct bt_conn_tx *tx; }; #define tx_data(buf) ((struct tx_meta *)net_buf_user_data(buf)) NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), sizeof(struct tx_meta), NULL); #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 #if defined(CONFIG_BT_CTLR_TX_BUFFER_SIZE) #define FRAG_SIZE BT_L2CAP_BUF_SIZE(CONFIG_BT_CTLR_TX_BUFFER_SIZE - 4) #else #define FRAG_SIZE BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU) #endif /* Dedicated pool for fragment buffers in case queued up TX buffers don't * fit the controllers buffer size. We can't use the acl_tx_pool for the * fragmentation, since it's possible that pool is empty and all buffers * are queued up in the TX queue. In such a situation, trying to allocate * another buffer from the acl_tx_pool would result in a deadlock. */ NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL); #endif /* CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) const struct bt_conn_auth_cb *bt_auth; #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ static struct bt_conn conns[CONFIG_BT_MAX_CONN]; static struct bt_conn_cb *callback_list; static struct bt_conn_tx conn_tx[CONFIG_BT_CONN_TX_MAX]; struct kfifo free_tx; #if defined(CONFIG_BT_BREDR) static struct bt_conn sco_conns[CONFIG_BT_MAX_SCO_CONN]; enum pairing_method { LEGACY, /* Legacy (pre-SSP) pairing */ JUST_WORKS, /* JustWorks pairing */ PASSKEY_INPUT, /* Passkey Entry input */ PASSKEY_DISPLAY, /* Passkey Entry display */ PASSKEY_CONFIRM, /* Passkey confirm */ }; /* based on table 5.7, Core Spec 4.2, Vol.3 Part C, 5.2.2.6 */ static const u8_t ssp_method[4 /* remote */][4 /* local */] = { { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS }, { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS }, { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS }, { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, }; #endif /* CONFIG_BT_BREDR */ void bt_conn_del(struct bt_conn *conn); struct k_sem *bt_conn_get_pkts(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) { return &bt_dev.br.pkts; } #endif /* CONFIG_BT_BREDR */ return &bt_dev.le.pkts; } static inline const char *state2str(bt_conn_state_t state) { switch (state) { case BT_CONN_DISCONNECTED: return "disconnected"; case BT_CONN_CONNECT_SCAN: return "connect-scan"; case BT_CONN_CONNECT_DIR_ADV: return "connect-dir-adv"; case BT_CONN_CONNECT_ADV: return "connect-adv"; case BT_CONN_CONNECT_AUTO: return "connect-auto"; case BT_CONN_CONNECT: return "connect"; case BT_CONN_CONNECTED: return "connected"; case BT_CONN_DISCONNECT: return "disconnect"; default: return "(unknown)"; } } static void notify_connected(struct bt_conn *conn) { struct bt_conn_cb *cb; for (cb = callback_list; cb; cb = cb->_next) { if (cb->connected) { cb->connected(conn, conn->err); } } if (!conn->err) { bt_gatt_connected(conn); } } static void notify_disconnected(struct bt_conn *conn) { struct bt_conn_cb *cb; for (cb = callback_list; cb; cb = cb->_next) { if (cb->disconnected) { cb->disconnected(conn, conn->err); } } } #if defined(CONFIG_BT_REMOTE_INFO) void notify_remote_info(struct bt_conn *conn) { struct bt_conn_remote_info remote_info; struct bt_conn_cb *cb; int err; err = bt_conn_get_remote_info(conn, &remote_info); if (err) { BT_DBG("Notify remote info failed %d", err); return; } for (cb = callback_list; cb; cb = cb->_next) { if (cb->remote_info_available) { cb->remote_info_available(conn, &remote_info); } } } #endif /* defined(CONFIG_BT_REMOTE_INFO) */ void notify_le_param_updated(struct bt_conn *conn) { struct bt_conn_cb *cb; /* If new connection parameters meet requirement of pending * parameters don't send slave conn param request anymore on timeout */ if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && conn->le.interval >= conn->le.interval_min && conn->le.interval <= conn->le.interval_max && conn->le.latency == conn->le.pending_latency && conn->le.timeout == conn->le.pending_timeout) { atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); } for (cb = callback_list; cb; cb = cb->_next) { if (cb->le_param_updated) { cb->le_param_updated(conn, conn->le.interval, conn->le.latency, conn->le.timeout); } } } #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) void notify_le_data_len_updated(struct bt_conn *conn) { struct bt_conn_cb *cb; for (cb = callback_list; cb; cb = cb->_next) { if (cb->le_data_len_updated) { cb->le_data_len_updated(conn, &conn->le.data_len); } } } #endif #if defined(CONFIG_BT_USER_PHY_UPDATE) void notify_le_phy_updated(struct bt_conn *conn) { struct bt_conn_cb *cb; for (cb = callback_list; cb; cb = cb->_next) { if (cb->le_phy_updated) { cb->le_phy_updated(conn, &conn->le.phy); } } } #endif bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param) { struct bt_conn_cb *cb; if (!bt_le_conn_params_valid(param)) { return false; } for (cb = callback_list; cb; cb = cb->_next) { if (!cb->le_param_req) { continue; } if (!cb->le_param_req(conn, param)) { return false; } /* The callback may modify the parameters so we need to * double-check that it returned valid parameters. */ if (!bt_le_conn_params_valid(param)) { return false; } } /* Default to accepting if there's no app callback */ return true; } static int send_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) { BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout); /* Proceed only if connection parameters contains valid values*/ if (!bt_le_conn_params_valid(param)) { return -EINVAL; } /* Use LE connection parameter request if both local and remote support * it; or if local role is master then use LE connection update. */ if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) || (conn->role == BT_HCI_ROLE_MASTER)) { int rc; rc = bt_conn_le_conn_update(conn, param); /* store those in case of fallback to L2CAP */ if (rc == 0) { conn->le.pending_latency = param->latency; conn->le.pending_timeout = param->timeout; } return rc; } /* If remote master does not support LL Connection Parameters Request * Procedure */ return bt_l2cap_update_conn_param(conn, param); } static void tx_free(struct bt_conn_tx *tx) { tx->cb = NULL; tx->user_data = NULL; tx->pending_no_cb = 0U; k_fifo_put(&free_tx, tx); } static void tx_notify(struct bt_conn *conn) { BT_DBG("conn %p", conn); while (1) { struct bt_conn_tx *tx; unsigned int key; bt_conn_tx_cb_t cb; void *user_data; key = irq_lock(); if (sys_slist_is_empty(&conn->tx_complete)) { irq_unlock(key); break; } tx = (void *)sys_slist_get_not_empty(&conn->tx_complete); irq_unlock(key); BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data); /* Copy over the params */ cb = tx->cb; user_data = tx->user_data; /* Free up TX notify since there may be user waiting */ tx_free(tx); /* Run the callback, at this point it should be safe to * allocate new buffers since the TX should have been * unblocked by tx_free. */ cb(conn, user_data); } } static void tx_complete_work(struct k_work *work) { struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, tx_complete_work); BT_DBG("conn %p", conn); tx_notify(conn); } static void conn_update_timeout(struct k_work *work) { struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, update_work); const struct bt_le_conn_param *param; BT_DBG("conn %p", conn); if (conn->state == BT_CONN_DISCONNECTED) { bt_l2cap_disconnected(conn); // notify_disconnected(conn); /* Release the reference we took for the very first * state transition. */ bt_conn_unref(conn); /* A new reference likely to have been released here, * Resume advertising. */ if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { bt_le_adv_resume(); } return; } if (conn->type != BT_CONN_TYPE_LE) { return; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) { /* we don't call bt_conn_disconnect as it would also clear * auto connect flag if it was set, instead just cancel * connection directly */ bt_le_create_conn_cancel(); return; } if (IS_ENABLED(CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS)) { /* if application set own params use those, otherwise * use defaults. */ if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) { param = BT_LE_CONN_PARAM(conn->le.interval_min, conn->le.interval_max, conn->le.pending_latency, conn->le.pending_timeout); send_conn_le_param_update(conn, param); } else { #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS) param = BT_LE_CONN_PARAM( CONFIG_BT_PERIPHERAL_PREF_MIN_INT, CONFIG_BT_PERIPHERAL_PREF_MAX_INT, CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY, CONFIG_BT_PERIPHERAL_PREF_TIMEOUT); send_conn_le_param_update(conn, param); #endif } } atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE); } static struct bt_conn *conn_new(void) { struct bt_conn *conn = NULL; int i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { conn = &conns[i]; (void)memset(conn, 0, sizeof(*conn)); conn->handle = i; break; } } if (!conn) { return NULL; } k_delayed_work_init(&conn->update_work, conn_update_timeout); k_work_init(&conn->tx_complete_work, tx_complete_work); atomic_set(&conn->ref, 1); return conn; } #if defined(CONFIG_BT_BREDR) void bt_sco_cleanup(struct bt_conn *sco_conn) { bt_conn_unref(sco_conn->sco.acl); sco_conn->sco.acl = NULL; bt_conn_unref(sco_conn); } static struct bt_conn *sco_conn_new(void) { struct bt_conn *sco_conn = NULL; int i; for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { if (!atomic_get(&sco_conns[i].ref)) { sco_conn = &sco_conns[i]; break; } } if (!sco_conn) { return NULL; } (void)memset(sco_conn, 0, sizeof(*sco_conn)); atomic_set(&sco_conn->ref, 1); return sco_conn; } struct bt_conn *bt_conn_create_br(const bt_addr_t *peer, const struct bt_br_conn_param *param) { struct bt_hci_cp_connect *cp; struct bt_conn *conn; struct net_buf *buf; conn = bt_conn_lookup_addr_br(peer); if (conn) { switch (conn->state) { case BT_CONN_CONNECT: case BT_CONN_CONNECTED: return conn; default: bt_conn_unref(conn); return NULL; } } conn = bt_conn_add_br(peer); if (!conn) { return NULL; } buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp)); if (!buf) { bt_conn_unref(conn); return NULL; } cp = net_buf_add(buf, sizeof(*cp)); (void)memset(cp, 0, sizeof(*cp)); memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr)); cp->packet_type = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */ cp->pscan_rep_mode = 0x02; /* R2 */ cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00; cp->clock_offset = 0x0000; /* TODO used cached clock offset */ if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) { bt_conn_unref(conn); return NULL; } bt_conn_set_state(conn, BT_CONN_CONNECT); conn->role = BT_CONN_ROLE_MASTER; return conn; } struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer) { struct bt_hci_cp_setup_sync_conn *cp; struct bt_conn *sco_conn; struct net_buf *buf; int link_type; sco_conn = bt_conn_lookup_addr_sco(peer); if (sco_conn) { switch (sco_conn->state) { case BT_CONN_CONNECT: case BT_CONN_CONNECTED: return sco_conn; default: bt_conn_unref(sco_conn); return NULL; } } if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { link_type = BT_HCI_ESCO; } else { link_type = BT_HCI_SCO; } sco_conn = bt_conn_add_sco(peer, link_type); if (!sco_conn) { return NULL; } buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp)); if (!buf) { bt_sco_cleanup(sco_conn); return NULL; } cp = net_buf_add(buf, sizeof(*cp)); (void)memset(cp, 0, sizeof(*cp)); BT_ERR("handle : %x", sco_conn->sco.acl->handle); cp->handle = sco_conn->sco.acl->handle; cp->pkt_type = sco_conn->sco.pkt_type; cp->tx_bandwidth = 0x00001f40; cp->rx_bandwidth = 0x00001f40; cp->max_latency = 0x0007; cp->retrans_effort = 0x01; cp->content_format = BT_VOICE_CVSD_16BIT; if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf, NULL) < 0) { bt_sco_cleanup(sco_conn); return NULL; } bt_conn_set_state(sco_conn, BT_CONN_CONNECT); return sco_conn; } struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) { int i; for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { if (!atomic_get(&sco_conns[i].ref)) { continue; } if (sco_conns[i].type != BT_CONN_TYPE_SCO) { continue; } if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) { return bt_conn_ref(&sco_conns[i]); } } return NULL; } struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer) { int i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { continue; } if (conns[i].type != BT_CONN_TYPE_BR) { continue; } if (!bt_addr_cmp(peer, &conns[i].br.dst)) { return bt_conn_ref(&conns[i]); } } return NULL; } struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type) { struct bt_conn *sco_conn = sco_conn_new(); if (!sco_conn) { return NULL; } sco_conn->sco.acl = bt_conn_lookup_addr_br(peer); sco_conn->type = BT_CONN_TYPE_SCO; if (link_type == BT_HCI_SCO) { if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ESCO_PKT_MASK); } else { sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & SCO_PKT_MASK); } } else if (link_type == BT_HCI_ESCO) { sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ~EDR_ESCO_PKT_MASK); } return sco_conn; } struct bt_conn *bt_conn_add_br(const bt_addr_t *peer) { struct bt_conn *conn = conn_new(); if (!conn) { return NULL; } bt_addr_copy(&conn->br.dst, peer); conn->type = BT_CONN_TYPE_BR; return conn; } static int pin_code_neg_reply(const bt_addr_t *bdaddr) { struct bt_hci_cp_pin_code_neg_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL); } static int pin_code_reply(struct bt_conn *conn, const char *pin, u8_t len) { struct bt_hci_cp_pin_code_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &conn->br.dst); cp->pin_len = len; strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code)); return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL); } int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin) { size_t len; if (!bt_auth) { return -EINVAL; } if (conn->type != BT_CONN_TYPE_BR) { return -EINVAL; } len = strlen(pin); if (len > 16) { return -EINVAL; } if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) { BT_WARN("PIN code for %s is not 16 bytes wide", bt_addr_str(&conn->br.dst)); return -EPERM; } /* Allow user send entered PIN to remote, then reset user state. */ if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { return -EPERM; } if (len == 16) { atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE); } return pin_code_reply(conn, pin, len); } void bt_conn_pin_code_req(struct bt_conn *conn) { if (bt_auth && bt_auth->pincode_entry) { bool secure = false; if (conn->required_sec_level == BT_SECURITY_L3) { secure = true; } atomic_set_bit(conn->flags, BT_CONN_USER); atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING); bt_auth->pincode_entry(conn, secure); } else { pin_code_neg_reply(&conn->br.dst); } } u8_t bt_conn_get_io_capa(void) { if (!bt_auth) { return BT_IO_NO_INPUT_OUTPUT; } if (bt_auth->passkey_confirm && bt_auth->passkey_display) { return BT_IO_DISPLAY_YESNO; } if (bt_auth->passkey_entry) { return BT_IO_KEYBOARD_ONLY; } if (bt_auth->passkey_display) { return BT_IO_DISPLAY_ONLY; } return BT_IO_NO_INPUT_OUTPUT; } static u8_t ssp_pair_method(const struct bt_conn *conn) { return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()]; } u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn) { /* Validate no bond auth request, and if valid use it. */ if ((conn->br.remote_auth == BT_HCI_NO_BONDING) || ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) && (ssp_pair_method(conn) > JUST_WORKS))) { return conn->br.remote_auth; } /* Local & remote have enough IO capabilities to get MITM protection. */ if (ssp_pair_method(conn) > JUST_WORKS) { return conn->br.remote_auth | BT_MITM; } /* No MITM protection possible so ignore remote MITM requirement. */ return (conn->br.remote_auth & ~BT_MITM); } static int ssp_confirm_reply(struct bt_conn *conn) { struct bt_hci_cp_user_confirm_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &conn->br.dst); return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL); } static int ssp_confirm_neg_reply(struct bt_conn *conn) { struct bt_hci_cp_user_confirm_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &conn->br.dst); return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf, NULL); } void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status) { if (!status) { bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND); if (bt_auth && bt_auth->pairing_complete) { bt_auth->pairing_complete(conn, bond); } } else { if (bt_auth && bt_auth->pairing_failed) { bt_auth->pairing_failed(conn, status); } } } void bt_conn_ssp_auth(struct bt_conn *conn, bt_u32_t passkey) { conn->br.pairing_method = ssp_pair_method(conn); /* * If local required security is HIGH then MITM is mandatory. * MITM protection is no achievable when SSP 'justworks' is applied. */ if (conn->required_sec_level > BT_SECURITY_L2 && conn->br.pairing_method == JUST_WORKS) { BT_DBG("MITM protection infeasible for required security"); ssp_confirm_neg_reply(conn); return; } switch (conn->br.pairing_method) { case PASSKEY_CONFIRM: atomic_set_bit(conn->flags, BT_CONN_USER); bt_auth->passkey_confirm(conn, passkey); break; case PASSKEY_DISPLAY: atomic_set_bit(conn->flags, BT_CONN_USER); bt_auth->passkey_display(conn, passkey); break; case PASSKEY_INPUT: atomic_set_bit(conn->flags, BT_CONN_USER); bt_auth->passkey_entry(conn); break; case JUST_WORKS: /* * When local host works as pairing acceptor and 'justworks' * model is applied then notify user about such pairing request. * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6] */ if (bt_auth && bt_auth->pairing_confirm && !atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) { atomic_set_bit(conn->flags, BT_CONN_USER); bt_auth->pairing_confirm(conn); break; } ssp_confirm_reply(conn); break; default: break; } } static int ssp_passkey_reply(struct bt_conn *conn, unsigned int passkey) { struct bt_hci_cp_user_passkey_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &conn->br.dst); cp->passkey = sys_cpu_to_le32(passkey); return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL); } static int ssp_passkey_neg_reply(struct bt_conn *conn) { struct bt_hci_cp_user_passkey_neg_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &conn->br.dst); return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf, NULL); } static int bt_hci_connect_br_cancel(struct bt_conn *conn) { struct bt_hci_cp_connect_cancel *cp; struct bt_hci_rp_connect_cancel *rp; struct net_buf *buf, *rsp; int err; buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr)); err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp); if (err) { return err; } rp = (void *)rsp->data; err = rp->status ? -EIO : 0; net_buf_unref(rsp); return err; } static int conn_auth(struct bt_conn *conn) { struct bt_hci_cp_auth_requested *auth; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth)); if (!buf) { return -ENOBUFS; } auth = net_buf_add(buf, sizeof(*auth)); auth->handle = sys_cpu_to_le16(conn->handle); atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR); return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL); } #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_SMP) void bt_conn_identity_resolved(struct bt_conn *conn) { const bt_addr_le_t *rpa; struct bt_conn_cb *cb; if (conn->role == BT_HCI_ROLE_MASTER) { rpa = &conn->le.resp_addr; } else { rpa = &conn->le.init_addr; } for (cb = callback_list; cb; cb = cb->_next) { if (cb->identity_resolved) { cb->identity_resolved(conn, rpa, &conn->le.dst); } } } int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], u8_t ediv[2], const u8_t *ltk, size_t len) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_start_encryption *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); memcpy(&cp->rand, rand, sizeof(cp->rand)); memcpy(&cp->ediv, ediv, sizeof(cp->ediv)); memcpy(cp->ltk, ltk, len); if (len < sizeof(cp->ltk)) { (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len); } return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL); #else u8_t ltk_buf[16]; memcpy(ltk_buf, ltk, len); if (len < sizeof(ltk_buf)) { memset(ltk_buf + len, 0, sizeof(ltk_buf) - len); } return hci_api_le_start_encrypt(conn->handle, rand, ediv, ltk_buf); #endif } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) u8_t bt_conn_enc_key_size(struct bt_conn *conn) { if (!conn->encrypt) { return 0; } if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { struct bt_hci_cp_read_encryption_key_size *cp; struct bt_hci_rp_read_encryption_key_size *rp; struct net_buf *buf; struct net_buf *rsp; u8_t key_size; buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, sizeof(*cp)); if (!buf) { return 0; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, buf, &rsp)) { return 0; } rp = (void *)rsp->data; key_size = rp->status ? 0 : rp->key_size; net_buf_unref(rsp); return key_size; } if (IS_ENABLED(CONFIG_BT_SMP)) { return conn->le.keys ? conn->le.keys->enc_size : 0; } return 0; } void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err) { struct bt_conn_cb *cb; for (cb = callback_list; cb; cb = cb->_next) { if (cb->security_changed) { cb->security_changed(conn, conn->sec_level, err); } } #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) if (!err && conn->sec_level >= BT_SECURITY_L2) { bt_keys_update_usage(conn->id, bt_conn_get_dst(conn)); } #endif } static int start_security(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) { return -EBUSY; } if (conn->required_sec_level > BT_SECURITY_L3) { return -ENOTSUP; } if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT && conn->required_sec_level > BT_SECURITY_L2) { return -EINVAL; } return conn_auth(conn); } #endif /* CONFIG_BT_BREDR */ if (IS_ENABLED(CONFIG_BT_SMP)) { return bt_smp_start_security(conn); } return -EINVAL; } int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec) { int err; if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) && sec < BT_SECURITY_L4) { return -EOPNOTSUPP; } if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) && sec > BT_SECURITY_L3) { return -EOPNOTSUPP; } /* nothing to do */ if (conn->sec_level >= sec || conn->required_sec_level >= sec) { return 0; } atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR, sec & BT_SECURITY_FORCE_PAIR); conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR; err = start_security(conn); /* reset required security level in case of error */ if (err) { conn->required_sec_level = conn->sec_level; } return err; } bt_security_t bt_conn_get_security(struct bt_conn *conn) { return conn->sec_level; } #else bt_security_t bt_conn_get_security(struct bt_conn *conn) { return BT_SECURITY_L1; } #endif /* CONFIG_BT_SMP */ void bt_conn_cb_register(struct bt_conn_cb *cb) { cb->_next = callback_list; callback_list = cb; } static void bt_conn_reset_rx_state(struct bt_conn *conn) { if (!conn->rx_len) { return; } net_buf_unref(conn->rx); conn->rx = NULL; conn->rx_len = 0U; } void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags) { struct bt_l2cap_hdr *hdr; u16_t len; /* Make sure we notify any pending TX callbacks before processing * new data for this connection. */ tx_notify(conn); BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags); /* Check packet boundary flags */ switch (flags) { case BT_ACL_START: hdr = (void *)buf->data; len = sys_le16_to_cpu(hdr->len); BT_DBG("First, len %u final %u", buf->len, len); if (conn->rx_len) { BT_ERR("Unexpected first L2CAP frame"); bt_conn_reset_rx_state(conn); } conn->rx_len = (sizeof(*hdr) + len) - buf->len; BT_DBG("rx_len %u", conn->rx_len); if (conn->rx_len) { conn->rx = buf; return; } break; case BT_ACL_CONT: if (!conn->rx_len) { BT_ERR("Unexpected L2CAP continuation"); bt_conn_reset_rx_state(conn); net_buf_unref(buf); return; } if (buf->len > conn->rx_len) { BT_ERR("L2CAP data overflow"); bt_conn_reset_rx_state(conn); net_buf_unref(buf); return; } BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len); if (buf->len > net_buf_tailroom(conn->rx)) { BT_ERR("Not enough buffer space for L2CAP data"); bt_conn_reset_rx_state(conn); net_buf_unref(buf); return; } net_buf_add_mem(conn->rx, buf->data, buf->len); conn->rx_len -= buf->len; net_buf_unref(buf); if (conn->rx_len) { return; } buf = conn->rx; conn->rx = NULL; conn->rx_len = 0U; break; default: /* BT_ACL_START_NO_FLUSH and BT_ACL_COMPLETE are not allowed on * LE-U from Controller to Host. * Only BT_ACL_POINT_TO_POINT is supported. */ BT_ERR("Unexpected ACL flags (0x%02x)", flags); bt_conn_reset_rx_state(conn); net_buf_unref(buf); return; } hdr = (void *)buf->data; len = sys_le16_to_cpu(hdr->len); if (sizeof(*hdr) + len != buf->len) { BT_ERR("ACL len mismatch (%u != %u)", len, buf->len); net_buf_unref(buf); return; } BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len); bt_l2cap_recv(conn, buf); } static struct bt_conn_tx *conn_tx_alloc(void) { //sys_snode_t *node; /* The TX context always get freed in the system workqueue, * so if we're in the same workqueue but there are no immediate * contexts available, there's no chance we'll get one by waiting. */ //if (k_current_get() == &k_sys_work_q.thread) { // return k_fifo_get(&free_tx, K_NO_WAIT); //} if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) { struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT); if (tx) { return tx; } BT_WARN("Unable to get an immediate free conn_tx"); } return k_fifo_get(&free_tx, K_FOREVER); } int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) { struct bt_conn_tx *tx; BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle, buf->len, cb, user_data); if (conn->state != BT_CONN_CONNECTED) { BT_ERR("not connected!"); net_buf_unref(buf); return -ENOTCONN; } if (cb) { tx = conn_tx_alloc(); if (!tx) { BT_ERR("Unable to allocate TX context"); net_buf_unref(buf); return -ENOBUFS; } /* Verify that we're still connected after blocking */ if (conn->state != BT_CONN_CONNECTED) { BT_WARN("Disconnected while allocating context"); net_buf_unref(buf); tx_free(tx); return -ENOTCONN; } tx->cb = cb; tx->user_data = user_data; tx->pending_no_cb = 0U; tx_data(buf)->tx = tx; } else { tx_data(buf)->tx = NULL; } net_buf_put(&conn->tx_queue, buf); return 0; } static bool send_frag(struct bt_conn *conn, struct net_buf *buf, u8_t flags, bool always_consume) { struct bt_conn_tx *tx = tx_data(buf)->tx; struct bt_hci_acl_hdr *hdr; bt_u32_t *pending_no_cb; unsigned int key; int err; BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len, flags); /* Wait until the controller can accept ACL packets */ k_sem_take(bt_conn_get_pkts(conn), K_FOREVER); /* Check for disconnection while waiting for pkts_sem */ if (conn->state != BT_CONN_CONNECTED) { goto fail; } hdr = net_buf_push(buf, sizeof(*hdr)); hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags)); hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); /* Add to pending, it must be done before bt_buf_set_type */ key = irq_lock(); if (tx) { sys_slist_append(&conn->tx_pending, &tx->node); } else { struct bt_conn_tx *tail_tx; tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending); if (tail_tx) { pending_no_cb = &tail_tx->pending_no_cb; } else { pending_no_cb = &conn->pending_no_cb; } (*pending_no_cb)++; } irq_unlock(key); bt_buf_set_type(buf, BT_BUF_ACL_OUT); err = bt_send(buf); if (err) { BT_ERR("Unable to send to driver (err %d)", err); key = irq_lock(); /* Roll back the pending TX info */ if (tx) { sys_slist_find_and_remove(&conn->tx_pending, &tx->node); } else { __ASSERT_NO_MSG(*pending_no_cb > 0); (*pending_no_cb)--; } irq_unlock(key); goto fail; } return true; fail: k_sem_give(bt_conn_get_pkts(conn)); if (tx) { tx_free(tx); } if (always_consume) { net_buf_unref(buf); } return false; } static inline u16_t conn_mtu(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) { return bt_dev.br.mtu; } #endif /* CONFIG_BT_BREDR */ return bt_dev.le.mtu; } static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf) { struct net_buf *frag; u16_t frag_len; frag = bt_conn_create_frag(0); if (conn->state != BT_CONN_CONNECTED) { net_buf_unref(frag); return NULL; } /* Fragments never have a TX completion callback */ tx_data(frag)->tx = NULL; frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag)); net_buf_add_mem(frag, buf->data, frag_len); net_buf_pull(buf, frag_len); return frag; } static bool send_buf(struct bt_conn *conn, struct net_buf *buf) { struct net_buf *frag; BT_DBG("conn %p buf %p len %u", conn, buf, buf->len); /* Send directly if the packet fits the ACL MTU */ if (buf->len <= conn_mtu(conn)) { return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false); } /* Create & enqueue first fragment */ frag = create_frag(conn, buf); if (!frag) { return false; } if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) { return false; } /* * Send the fragments. For the last one simply use the original * buffer (which works since we've used net_buf_pull on it. */ while (buf->len > conn_mtu(conn)) { frag = create_frag(conn, buf); if (!frag) { return false; } if (!send_frag(conn, frag, BT_ACL_CONT, true)) { return false; } } return send_frag(conn, buf, BT_ACL_CONT, false); } static struct k_poll_signal conn_change = K_POLL_SIGNAL_INITIALIZER(conn_change); static void conn_cleanup(struct bt_conn *conn) { struct net_buf *buf; /* Give back any allocated buffers */ while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) { if (tx_data(buf)->tx) { tx_free(tx_data(buf)->tx); } net_buf_unref(buf); } __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets"); __ASSERT_NO_MSG(conn->pending_no_cb == 0); bt_conn_reset_rx_state(conn); k_delayed_work_submit(&conn->update_work, K_NO_WAIT); } int bt_conn_prepare_events(struct k_poll_event events[]) { int i, ev_count = 0; // BT_DBG(""); conn_change.signaled = 0U; k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &conn_change); for (i = 0; i < ARRAY_SIZE(conns); i++) { struct bt_conn *conn = &conns[i]; if (!atomic_get(&conn->ref)) { continue; } if (conn->state == BT_CONN_DISCONNECTED && atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) { conn_cleanup(conn); continue; } if (conn->state != BT_CONN_CONNECTED) { continue; } BT_DBG("Adding conn %p to poll list", conn); k_poll_event_init(&events[ev_count], K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &conn->tx_queue); events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE; } return ev_count; } void bt_conn_process_tx(struct bt_conn *conn) { struct net_buf *buf; BT_DBG("conn %p", conn); if (conn->state == BT_CONN_DISCONNECTED && atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) { BT_DBG("handle %u disconnected - cleaning up", conn->handle); conn_cleanup(conn); return; } /* Get next ACL packet for connection */ buf = net_buf_get(&conn->tx_queue, K_NO_WAIT); BT_ASSERT(buf); if (!send_buf(conn, buf)) { net_buf_unref(buf); } } bool bt_conn_exists_le(u8_t id, const bt_addr_le_t *peer) { struct bt_conn *conn = bt_conn_lookup_addr_le(id, peer); if (conn) { /* Connection object already exists. * If the connection state is not "disconnected",then the * connection was created but has not yet been disconnected. * If the connection state is "disconnected" then the connection * still has valid references. The last reference of the stack * is released after the disconnected callback. */ BT_WARN("Found valid connection in %s state", state2str(conn->state)); bt_conn_unref(conn); return true; } return false; } struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer) { struct bt_conn *conn = conn_new(); if (!conn) { return NULL; } conn->id = id; bt_addr_le_copy(&conn->le.dst, peer); #if defined(CONFIG_BT_SMP) conn->sec_level = BT_SECURITY_L1; conn->required_sec_level = BT_SECURITY_L1; #endif /* CONFIG_BT_SMP */ conn->type = BT_CONN_TYPE_LE; conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN; conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX; return conn; } static void process_unack_tx(struct bt_conn *conn) { /* Return any unacknowledged packets */ while (1) { struct bt_conn_tx *tx; sys_snode_t *node; unsigned int key; key = irq_lock(); if (conn->pending_no_cb) { conn->pending_no_cb--; irq_unlock(key); k_sem_give(bt_conn_get_pkts(conn)); continue; } node = sys_slist_get(&conn->tx_pending); irq_unlock(key); if (!node) { break; } tx = CONTAINER_OF(node, struct bt_conn_tx, node); key = irq_lock(); conn->pending_no_cb = tx->pending_no_cb; tx->pending_no_cb = 0U; irq_unlock(key); tx_free(tx); k_sem_give(bt_conn_get_pkts(conn)); } } void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state) { bt_conn_state_t old_state; BT_DBG("%s -> %s", state2str(conn->state), state2str(state)); if (conn->state == state) { BT_WARN("no transition %s", state2str(state)); return; } old_state = conn->state; conn->state = state; /* Actions needed for exiting the old state */ switch (old_state) { case BT_CONN_DISCONNECTED: /* Take a reference for the first state transition after * bt_conn_add_le() and keep it until reaching DISCONNECTED * again. */ bt_conn_ref(conn); break; case BT_CONN_CONNECT: if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) { BT_DBG("k_delayed_work_cancel(&conn->update_work)"); k_delayed_work_cancel(&conn->update_work); } break; default: break; } /* Actions needed for entering the new state */ switch (conn->state) { case BT_CONN_CONNECTED: if (conn->type == BT_CONN_TYPE_SCO) { /* TODO: Notify sco connected */ break; } bt_dev.le.mtu = bt_dev.le.mtu_init; k_fifo_init(&conn->tx_queue); k_poll_signal_raise(&conn_change, 0); sys_slist_init(&conn->channels); bt_l2cap_connected(conn); notify_connected(conn); break; case BT_CONN_DISCONNECTED: if (conn->type == BT_CONN_TYPE_SCO) { /* TODO: Notify sco disconnected */ bt_conn_unref(conn); break; } /* Notify disconnection and queue a dummy buffer to wake * up and stop the tx thread for states where it was * running. */ switch (old_state) { case BT_CONN_CONNECTED: case BT_CONN_DISCONNECT: process_unack_tx(conn); tx_notify(conn); bt_conn_del(conn); bt_l2cap_disconnected(conn); notify_disconnected(conn); /* Cancel Connection Update if it is pending */ if (conn->type == BT_CONN_TYPE_LE) { BT_DBG("k_delayed_work_cancel(&conn->update_work)"); k_delayed_work_cancel(&conn->update_work); } atomic_set_bit(conn->flags, BT_CONN_CLEANUP); k_poll_signal_raise(&conn_change, 0); /* The last ref will be dropped during cleanup */ break; case BT_CONN_CONNECT: /* LE Create Connection command failed. This might be * directly from the API, don't notify application in * this case. */ if (conn->err) { notify_connected(conn); } bt_conn_unref(conn); break; case BT_CONN_CONNECT_SCAN: /* this indicate LE Create Connection with peer address * has been stopped. This could either be triggered by * the application through bt_conn_disconnect or by * timeout set by bt_conn_le_create_param.timeout. */ if (conn->err) { notify_connected(conn); } bt_conn_unref(conn); break; case BT_CONN_CONNECT_DIR_ADV: /* this indicate Directed advertising stopped */ if (conn->err) { notify_connected(conn); } bt_conn_unref(conn); break; case BT_CONN_CONNECT_AUTO: /* this indicates LE Create Connection with filter * policy has been stopped. This can only be triggered * by the application, so don't notify. */ bt_conn_unref(conn); break; case BT_CONN_CONNECT_ADV: /* This can only happen when application stops the * advertiser, conn->err is never set in this case. */ bt_conn_unref(conn); break; case BT_CONN_DISCONNECTED: /* Cannot happen, no transition. */ break; } break; case BT_CONN_CONNECT_AUTO: break; case BT_CONN_CONNECT_ADV: break; case BT_CONN_CONNECT_SCAN: break; case BT_CONN_CONNECT_DIR_ADV: break; case BT_CONN_CONNECT: if (conn->type == BT_CONN_TYPE_SCO) { break; } /* * Timer is needed only for LE. For other link types controller * will handle connection timeout. */ if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) { k_delayed_work_submit(&conn->update_work, K_MSEC(10 * bt_dev.create_param.timeout)); } break; case BT_CONN_DISCONNECT: break; default: BT_WARN("no valid (%u) state was set", state); break; } } struct bt_conn *bt_conn_lookup_handle(u16_t handle) { int i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { continue; } /* We only care about connections with a valid handle */ if (conns[i].state != BT_CONN_CONNECTED && conns[i].state != BT_CONN_DISCONNECT) { continue; } if (conns[i].handle == handle) { return bt_conn_ref(&conns[i]); } } #if defined(CONFIG_BT_BREDR) for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { if (!atomic_get(&sco_conns[i].ref)) { continue; } /* We only care about connections with a valid handle */ if (sco_conns[i].state != BT_CONN_CONNECTED && sco_conns[i].state != BT_CONN_DISCONNECT) { continue; } if (sco_conns[i].handle == handle) { return bt_conn_ref(&sco_conns[i]); } } #endif return NULL; } bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, u8_t id, const bt_addr_le_t *peer) { if (id != conn->id) { return false; } /* Check against conn dst address as it may be the identity address */ if (!bt_addr_le_cmp(peer, &conn->le.dst)) { return true; } /* Check against initial connection address */ if (conn->role == BT_HCI_ROLE_MASTER) { return bt_addr_le_cmp(peer, &conn->le.resp_addr) == 0; } return bt_addr_le_cmp(peer, &conn->le.init_addr) == 0; } struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer) { int i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { continue; } if (conns[i].type != BT_CONN_TYPE_LE) { continue; } if (bt_conn_is_peer_addr_le(&conns[i], id, peer)) { return bt_conn_ref(&conns[i]); } } return NULL; } struct bt_conn *bt_conn_lookup_state_le(u8_t id, const bt_addr_le_t *peer, const bt_conn_state_t state) { int i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { continue; } if (conns[i].type != BT_CONN_TYPE_LE) { continue; } if (peer && !bt_conn_is_peer_addr_le(&conns[i], id, peer)) { continue; } if (conns[i].state == state && conns[i].id == id) { return bt_conn_ref(&conns[i]); } } return NULL; } void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), void *data) { int i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { continue; } if (!(conns[i].type & type)) { continue; } func(&conns[i], data); } #if defined(CONFIG_BT_BREDR) if (type & BT_CONN_TYPE_SCO) { for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { if (!atomic_get(&sco_conns[i].ref)) { continue; } func(&sco_conns[i], data); } } #endif /* defined(CONFIG_BT_BREDR) */ } struct bt_conn *bt_conn_ref(struct bt_conn *conn) { atomic_val_t old = atomic_inc(&conn->ref); BT_DBG("%s: handle %u ref %u -> %u", __func__, conn->handle, old, atomic_get(&conn->ref)); (void)old; return conn; } void bt_conn_unref(struct bt_conn *conn) { if (atomic_get(&conn->ref) == 0) return; atomic_val_t old = atomic_dec(&conn->ref); (void)old; BT_DBG("%s: handle %u ref %u -> %u", __func__, conn->handle, old, atomic_get(&conn->ref)); } void bt_conn_del(struct bt_conn *conn) { atomic_val_t old = atomic_set(&conn->ref, 0); (void)old; BT_DBG("%s: handle %u ref %u -> %u", __func__, conn->handle, old, atomic_get(&conn->ref)); } const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn) { return &conn->le.dst; } int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info) { info->type = conn->type; info->role = conn->role; info->id = conn->id; switch (conn->type) { case BT_CONN_TYPE_LE: info->le.dst = &conn->le.dst; info->le.src = &bt_dev.id_addr[conn->id]; if (conn->role == BT_HCI_ROLE_MASTER) { info->le.local = &conn->le.init_addr; info->le.remote = &conn->le.resp_addr; } else { info->le.local = &conn->le.resp_addr; info->le.remote = &conn->le.init_addr; } info->le.interval = conn->le.interval; info->le.latency = conn->le.latency; info->le.timeout = conn->le.timeout; #if defined(CONFIG_BT_USER_PHY_UPDATE) info->le.phy = &conn->le.phy; #endif #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) info->le.data_len = &conn->le.data_len; #endif return 0; #if defined(CONFIG_BT_BREDR) case BT_CONN_TYPE_BR: info->br.dst = &conn->br.dst; return 0; #endif } return -EINVAL; } int bt_conn_get_remote_info(struct bt_conn *conn, struct bt_conn_remote_info *remote_info) { if (!atomic_test_bit(conn->flags, BT_CONN_AUTO_FEATURE_EXCH) || (IS_ENABLED(CONFIG_BT_REMOTE_VERSION) && !atomic_test_bit(conn->flags, BT_CONN_AUTO_VERSION_INFO))) { return -EBUSY; } remote_info->type = conn->type; #if defined(CONFIG_BT_REMOTE_VERSION) /* The conn->rv values will be just zeroes if the operation failed */ remote_info->version = conn->rv.version; remote_info->manufacturer = conn->rv.manufacturer; remote_info->subversion = conn->rv.subversion; #else remote_info->version = 0; remote_info->manufacturer = 0; remote_info->subversion = 0; #endif switch (conn->type) { case BT_CONN_TYPE_LE: remote_info->le.features = conn->le.features; return 0; #if defined(CONFIG_BT_BREDR) case BT_CONN_TYPE_BR: /* TODO: Make sure the HCI commands to read br features and * extended features has finished. */ return -ENOTSUP; #endif default: return -EINVAL; } } static int conn_disconnect(struct bt_conn *conn, u8_t reason) { int err; err = bt_hci_disconnect(conn->handle, reason); if (err) { return err; } bt_conn_set_state(conn, BT_CONN_DISCONNECT); return 0; } int bt_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) { BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout); /* Check if there's a need to update conn params */ if (conn->le.interval >= param->interval_min && conn->le.interval <= param->interval_max && conn->le.latency == param->latency && conn->le.timeout == param->timeout) { atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); return -EALREADY; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) { return send_conn_le_param_update(conn, param); } if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { /* if slave conn param update timer expired just send request */ if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) { return send_conn_le_param_update(conn, param); } /* store new conn params to be used by update timer */ conn->le.interval_min = param->interval_min; conn->le.interval_max = param->interval_max; conn->le.pending_latency = param->latency; conn->le.pending_timeout = param->timeout; atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); } return 0; } #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) int bt_conn_le_data_len_update(struct bt_conn *conn, const struct bt_conn_le_data_len_param *param) { if (conn->le.data_len.tx_max_len == param->tx_max_len && conn->le.data_len.tx_max_time == param->tx_max_time) { return -EALREADY; } if (IS_ENABLED(CONFIG_BT_AUTO_DATA_LEN_UPDATE) && !atomic_test_bit(conn->flags, BT_CONN_AUTO_DATA_LEN_COMPLETE)) { return -EAGAIN; } return bt_le_set_data_len(conn, param->tx_max_len, param->tx_max_time); } #endif #if defined(CONFIG_BT_USER_PHY_UPDATE) int bt_conn_le_phy_update(struct bt_conn *conn, const struct bt_conn_le_phy_param *param) { if (conn->le.phy.tx_phy == param->pref_tx_phy && conn->le.phy.rx_phy == param->pref_rx_phy) { return -EALREADY; } if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && !atomic_test_bit(conn->flags, BT_CONN_AUTO_PHY_COMPLETE)) { return -EAGAIN; } return bt_le_set_phy(conn, param->pref_tx_phy, param->pref_rx_phy); } #endif int bt_conn_disconnect(struct bt_conn *conn, u8_t reason) { /* Disconnection is initiated by us, so auto connection shall * be disabled. Otherwise the passive scan would be enabled * and we could send LE Create Connection as soon as the remote * starts advertising. */ #if !defined(CONFIG_BT_WHITELIST) if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) { bt_le_set_auto_conn(&conn->le.dst, NULL); } #endif /* !defined(CONFIG_BT_WHITELIST) */ switch (conn->state) { case BT_CONN_CONNECT_SCAN: conn->err = reason; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); if (IS_ENABLED(CONFIG_BT_CENTRAL)) { bt_le_scan_update(false); } return 0; case BT_CONN_CONNECT_DIR_ADV: BT_WARN("Deprecated: Use bt_le_adv_stop instead"); conn->err = reason; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { /* User should unref connection object when receiving * error in connection callback. */ return bt_le_adv_stop(); } return 0; case BT_CONN_CONNECT: #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { return bt_hci_connect_br_cancel(conn); } #endif /* CONFIG_BT_BREDR */ if (IS_ENABLED(CONFIG_BT_CENTRAL)) { k_delayed_work_cancel(&conn->update_work); return bt_le_create_conn_cancel(); } return 0; case BT_CONN_CONNECTED: return conn_disconnect(conn, reason); case BT_CONN_DISCONNECT: return 0; case BT_CONN_DISCONNECTED: default: return -ENOTCONN; } } #if defined(CONFIG_BT_CENTRAL) static void bt_conn_set_param_le(struct bt_conn *conn, const struct bt_le_conn_param *param) { conn->le.interval_min = param->interval_min; conn->le.interval_max = param->interval_max; conn->le.latency = param->latency; conn->le.timeout = param->timeout; } static bool create_param_validate(const struct bt_conn_le_create_param *param) { #if defined(CONFIG_BT_PRIVACY) /* Initiation timeout cannot be greater than the RPA timeout */ const bt_u32_t timeout_max = (MSEC_PER_SEC / 10) * CONFIG_BT_RPA_TIMEOUT; if (param->timeout > timeout_max) { return false; } #endif return true; } static void create_param_setup(const struct bt_conn_le_create_param *param) { bt_dev.create_param = *param; bt_dev.create_param.timeout = (bt_dev.create_param.timeout != 0) ? bt_dev.create_param.timeout : (MSEC_PER_SEC / 10) * CONFIG_BT_CREATE_CONN_TIMEOUT; bt_dev.create_param.interval_coded = (bt_dev.create_param.interval_coded != 0) ? bt_dev.create_param.interval_coded : bt_dev.create_param.interval; bt_dev.create_param.window_coded = (bt_dev.create_param.window_coded != 0) ? bt_dev.create_param.window_coded : bt_dev.create_param.window; } #if defined(CONFIG_BT_WHITELIST) int bt_conn_le_create_auto(const struct bt_conn_le_create_param *create_param, const struct bt_le_conn_param *param) { struct bt_conn *conn; int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (!bt_le_conn_params_valid(param)) { return -EINVAL; } conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE, BT_CONN_CONNECT_AUTO); if (conn) { bt_conn_unref(conn); return -EALREADY; } /* Scanning either to connect or explicit scan, either case scanner was * started by application and should not be stopped. */ if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { return -EINVAL; } if (atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) { return -EINVAL; } if (!bt_le_scan_random_addr_check()) { return -EINVAL; } conn = bt_conn_add_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE); if (!conn) { return -ENOMEM; } bt_conn_set_param_le(conn, param); create_param_setup(create_param); atomic_set_bit(conn->flags, BT_CONN_AUTO_CONNECT); bt_conn_set_state(conn, BT_CONN_CONNECT_AUTO); err = bt_le_create_conn(conn); if (err) { BT_ERR("Failed to start whitelist scan"); conn->err = 0; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); return err; } /* Since we don't give the application a reference to manage in * this case, we need to release this reference here. */ bt_conn_unref(conn); return 0; } int bt_conn_create_auto_stop(void) { struct bt_conn *conn; int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EINVAL; } conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE, BT_CONN_CONNECT_AUTO); if (!conn) { return -EINVAL; } if (!atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) { return -EINVAL; } bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); err = bt_le_create_conn_cancel(); if (err) { BT_ERR("Failed to stop initiator"); return err; } return 0; } #endif /* defined(CONFIG_BT_WHITELIST) */ int bt_conn_le_create(const bt_addr_le_t *peer, const struct bt_conn_le_create_param *create_param, const struct bt_le_conn_param *conn_param, struct bt_conn **ret_conn) { struct bt_conn *conn; bt_addr_le_t dst; int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (!bt_le_conn_params_valid(conn_param)) { return -EINVAL; } if (!create_param_validate(create_param)) { return -EINVAL; } if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { return -EINVAL; } if (atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) { return -EALREADY; } if (!bt_le_scan_random_addr_check()) { return -EINVAL; } if (bt_conn_exists_le(BT_ID_DEFAULT, peer)) { return -EINVAL; } if (peer->type == BT_ADDR_LE_PUBLIC_ID || peer->type == BT_ADDR_LE_RANDOM_ID) { bt_addr_le_copy(&dst, peer); dst.type -= BT_ADDR_LE_PUBLIC_ID; } else { bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer)); } /* Only default identity supported for now */ conn = bt_conn_add_le(BT_ID_DEFAULT, &dst); if (!conn) { return -ENOMEM; } bt_conn_set_param_le(conn, conn_param); create_param_setup(create_param); #if defined(CONFIG_BT_SMP) if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); err = bt_le_scan_update(true); if (err) { bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); return err; } *ret_conn = conn; return 0; } #endif bt_conn_set_state(conn, BT_CONN_CONNECT); err = bt_le_create_conn(conn); if (err) { conn->err = 0; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); bt_le_scan_update(false); return err; } *ret_conn = conn; return 0; } #if !defined(CONFIG_BT_WHITELIST) int bt_le_set_auto_conn(const bt_addr_le_t *addr, const struct bt_le_conn_param *param) { struct bt_conn *conn; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (param && !bt_le_conn_params_valid(param)) { return -EINVAL; } if (!bt_le_scan_random_addr_check()) { return -EINVAL; } /* Only default identity is supported */ conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr); if (!conn) { conn = bt_conn_add_le(BT_ID_DEFAULT, addr); if (!conn) { return -ENOMEM; } } if (param) { bt_conn_set_param_le(conn, param); if (!atomic_test_and_set_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { bt_conn_ref(conn); } } else { if (atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { bt_conn_unref(conn); if (conn->state == BT_CONN_CONNECT_SCAN) { bt_conn_set_state(conn, BT_CONN_DISCONNECTED); } } } if (conn->state == BT_CONN_DISCONNECTED && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { if (param) { bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); } bt_le_scan_update(false); } bt_conn_unref(conn); return 0; } #endif /* !defined(CONFIG_BT_WHITELIST) */ #endif /* CONFIG_BT_CENTRAL */ int bt_conn_le_conn_update(struct bt_conn *conn, const struct bt_le_conn_param *param) { #if !defined(CONFIG_BT_USE_HCI_API) struct hci_cp_le_conn_update *conn_update; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE, sizeof(*conn_update)); if (!buf) { return -ENOBUFS; } conn_update = net_buf_add(buf, sizeof(*conn_update)); (void)memset(conn_update, 0, sizeof(*conn_update)); conn_update->handle = sys_cpu_to_le16(conn->handle); conn_update->conn_interval_min = sys_cpu_to_le16(param->interval_min); conn_update->conn_interval_max = sys_cpu_to_le16(param->interval_max); conn_update->conn_latency = sys_cpu_to_le16(param->latency); conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL); #else return hci_api_le_conn_updata(conn->handle, param->interval_min, param->interval_max, param->latency, param->timeout, 0, 0); #endif } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve, k_timeout_t timeout, const char *func, int line) #else struct net_buf *bt_conn_create_frag_timeout(size_t reserve, k_timeout_t timeout) #endif { struct net_buf_pool *pool = NULL; #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 pool = &frag_pool; #endif #if defined(CONFIG_NET_BUF_LOG) return bt_conn_create_pdu_timeout_debug(pool, reserve, timeout, func, line); #else return bt_conn_create_pdu_timeout(pool, reserve, timeout); #endif /* CONFIG_NET_BUF_LOG */ } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout, const char *func, int line) #else struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout) #endif { struct net_buf *buf; /* * PDU must not be allocated from ISR as we block with 'K_FOREVER' * during the allocation */ __ASSERT_NO_MSG(!k_is_in_isr()); if (!pool) { pool = &acl_tx_pool; } if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) { #if defined(CONFIG_NET_BUF_LOG) buf = net_buf_alloc_fixed_debug(pool, K_NO_WAIT, func, line); #else buf = net_buf_alloc(pool, K_NO_WAIT); #endif if (!buf) { BT_WARN("Unable to allocate buffer with K_NO_WAIT"); #if defined(CONFIG_NET_BUF_LOG) buf = net_buf_alloc_fixed_debug(pool, timeout, func, line); #else buf = net_buf_alloc(pool, timeout); #endif } } else { #if defined(CONFIG_NET_BUF_LOG) buf = net_buf_alloc_fixed_debug(pool, timeout, func, line); #else buf = net_buf_alloc(pool, timeout); #endif } if (!buf) { BT_WARN("Unable to allocate buffer within timeout"); return NULL; } reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE; net_buf_reserve(buf, reserve); return buf; } #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb) { if (!cb) { bt_auth = NULL; return 0; } if (bt_auth) { return -EALREADY; } /* The cancel callback must always be provided if the app provides * interactive callbacks. */ if (!cb->cancel && (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm || #if defined(CONFIG_BT_BREDR) cb->pincode_entry || #endif cb->pairing_confirm)) { return -EINVAL; } bt_auth = cb; return 0; } int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey) { if (!bt_auth) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { bt_smp_auth_passkey_entry(conn, passkey); return 0; } #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { /* User entered passkey, reset user state. */ if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { return -EPERM; } if (conn->br.pairing_method == PASSKEY_INPUT) { return ssp_passkey_reply(conn, passkey); } } #endif /* CONFIG_BT_BREDR */ return -EINVAL; } int bt_conn_auth_passkey_confirm(struct bt_conn *conn) { if (!bt_auth) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { return bt_smp_auth_passkey_confirm(conn); } #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { /* Allow user confirm passkey value, then reset user state. */ if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { return -EPERM; } return ssp_confirm_reply(conn); } #endif /* CONFIG_BT_BREDR */ return -EINVAL; } int bt_conn_auth_cancel(struct bt_conn *conn) { if (!bt_auth) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { return bt_smp_auth_cancel(conn); } #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { /* Allow user cancel authentication, then reset user state. */ if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { return -EPERM; } switch (conn->br.pairing_method) { case JUST_WORKS: case PASSKEY_CONFIRM: return ssp_confirm_neg_reply(conn); case PASSKEY_INPUT: return ssp_passkey_neg_reply(conn); case PASSKEY_DISPLAY: return bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); case LEGACY: return pin_code_neg_reply(&conn->br.dst); default: break; } } #endif /* CONFIG_BT_BREDR */ return -EINVAL; } int bt_conn_auth_pairing_confirm(struct bt_conn *conn) { if (!bt_auth) { return -EINVAL; } switch (conn->type) { #if defined(CONFIG_BT_SMP) case BT_CONN_TYPE_LE: return bt_smp_auth_pairing_confirm(conn); #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_BREDR) case BT_CONN_TYPE_BR: return ssp_confirm_reply(conn); #endif /* CONFIG_BT_BREDR */ default: return -EINVAL; } } #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ u8_t bt_conn_index(struct bt_conn *conn) { u8_t index = conn - conns; __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer"); return index; } struct bt_conn *bt_conn_lookup_index(u8_t index) { struct bt_conn *conn; if (index >= ARRAY_SIZE(conns)) { return NULL; } conn = &conns[index]; if (!atomic_get(&conn->ref)) { return NULL; } return bt_conn_ref(conn); } int bt_conn_init(void) { int err, i; k_fifo_init(&free_tx); for (i = 0; i < ARRAY_SIZE(conn_tx); i++) { k_fifo_put(&free_tx, &conn_tx[i]); } bt_att_init(); err = bt_smp_init(); if (err) { return err; } bt_l2cap_init(); NET_BUF_POOL_INIT(acl_tx_pool); NET_BUF_POOL_INIT(frag_pool); /* Initialize background scan */ if (IS_ENABLED(CONFIG_BT_CENTRAL)) { for (i = 0; i < ARRAY_SIZE(conns); i++) { struct bt_conn *conn = &conns[i]; if (!atomic_get(&conn->ref)) { continue; } #if !defined(CONFIG_BT_WHITELIST) if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { /* Only the default identity is supported */ conn->id = BT_ID_DEFAULT; bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); } #endif /* !defined(CONFIG_BT_WHITELIST) */ } } return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/conn.c
C
apache-2.0
64,056
/** @file * @brief Internal APIs for Bluetooth connection handling. */ /* * Copyright (c) 2015 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ typedef enum __packed { BT_CONN_DISCONNECTED, BT_CONN_CONNECT_SCAN, BT_CONN_CONNECT_AUTO, BT_CONN_CONNECT_ADV, BT_CONN_CONNECT_DIR_ADV, BT_CONN_CONNECT, BT_CONN_CONNECTED, BT_CONN_DISCONNECT, } bt_conn_state_t; /* bt_conn flags: the flags defined here represent connection parameters */ enum { BT_CONN_AUTO_CONNECT, BT_CONN_BR_LEGACY_SECURE, /* 16 digits legacy PIN tracker */ BT_CONN_USER, /* user I/O when pairing */ BT_CONN_BR_PAIRING, /* BR connection in pairing context */ BT_CONN_BR_NOBOND, /* SSP no bond pairing tracker */ BT_CONN_BR_PAIRING_INITIATOR, /* local host starts authentication */ BT_CONN_CLEANUP, /* Disconnected, pending cleanup */ BT_CONN_AUTO_PHY_UPDATE, /* Auto-update PHY */ BT_CONN_SLAVE_PARAM_UPDATE, /* If slave param update timer fired */ BT_CONN_SLAVE_PARAM_SET, /* If slave param were set from app */ BT_CONN_SLAVE_PARAM_L2CAP, /* If should force L2CAP for CPUP */ BT_CONN_FORCE_PAIR, /* Pairing even with existing keys. */ BT_CONN_AUTO_PHY_COMPLETE, /* Auto-initiated PHY procedure done */ BT_CONN_AUTO_FEATURE_EXCH, /* Auto-initiated LE Feat done */ BT_CONN_AUTO_VERSION_INFO, /* Auto-initiated LE version done */ BT_CONN_AUTO_DATA_LEN_COMPLETE, /* Auto-initiated Data Length done */ /* Total number of flags - must be at the end of the enum */ BT_CONN_NUM_FLAGS, }; struct bt_conn_le { bt_addr_le_t dst; bt_addr_le_t init_addr; bt_addr_le_t resp_addr; u16_t interval; u16_t interval_min; u16_t interval_max; u16_t latency; u16_t timeout; u16_t pending_latency; u16_t pending_timeout; u8_t features[8]; struct bt_keys *keys; #if defined(CONFIG_BT_USER_PHY_UPDATE) struct bt_conn_le_phy_info phy; #endif #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) struct bt_conn_le_data_len_info data_len; #endif }; #if defined(CONFIG_BT_BREDR) /* For now reserve space for 2 pages of LMP remote features */ #define LMP_MAX_PAGES 2 struct bt_conn_br { bt_addr_t dst; u8_t remote_io_capa; u8_t remote_auth; u8_t pairing_method; /* remote LMP features pages per 8 bytes each */ u8_t features[LMP_MAX_PAGES][8]; struct bt_keys_link_key *link_key; }; struct bt_conn_sco { /* Reference to ACL Connection */ struct bt_conn *acl; u16_t pkt_type; }; #endif typedef void (*bt_conn_tx_cb_t)(struct bt_conn *conn, void *user_data); struct bt_conn_tx { sys_snode_t node; bt_conn_tx_cb_t cb; void *user_data; /* Number of pending packets without a callback after this one */ bt_u32_t pending_no_cb; }; struct bt_conn { u16_t handle; u8_t type; u8_t role; ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS); /* Which local identity address this connection uses */ u8_t id; #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) bt_security_t sec_level; bt_security_t required_sec_level; u8_t encrypt; #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ /* Connection error or reason for disconnect */ u8_t err; bt_conn_state_t state; u16_t rx_len; struct net_buf *rx; /* Sent but not acknowledged TX packets with a callback */ sys_slist_t tx_pending; /* Sent but not acknowledged TX packets without a callback before * the next packet (if any) in tx_pending. */ bt_u32_t pending_no_cb; /* Completed TX for which we need to call the callback */ sys_slist_t tx_complete; struct k_work tx_complete_work; /* Queue for outgoing ACL data */ struct kfifo tx_queue; /* Active L2CAP channels */ sys_slist_t channels; atomic_t ref; /* Delayed work for connection update and other deferred tasks */ struct k_delayed_work update_work; union { struct bt_conn_le le; #if defined(CONFIG_BT_BREDR) struct bt_conn_br br; struct bt_conn_sco sco; #endif }; #if defined(CONFIG_BT_REMOTE_VERSION) struct bt_conn_rv { u8_t version; u16_t manufacturer; u16_t subversion; } rv; #endif }; /* Process incoming data for a connection */ void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags); /* Send data over a connection */ int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data); static inline int bt_conn_send(struct bt_conn *conn, struct net_buf *buf) { return bt_conn_send_cb(conn, buf, NULL, NULL); } /* Check if a connection object with the peer already exists */ bool bt_conn_exists_le(u8_t id, const bt_addr_le_t *peer); /* Add a new LE connection */ struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer); /* Add a new BR/EDR connection */ struct bt_conn *bt_conn_add_br(const bt_addr_t *peer); /* Add a new SCO connection */ struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type); /* Cleanup SCO references */ void bt_sco_cleanup(struct bt_conn *sco_conn); /* Look up an existing sco connection by BT address */ struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer); /* Look up an existing connection by BT address */ struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer); void bt_conn_pin_code_req(struct bt_conn *conn); u8_t bt_conn_get_io_capa(void); u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn); void bt_conn_ssp_auth(struct bt_conn *conn, bt_u32_t passkey); void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status); void bt_conn_disconnect_all(u8_t id); /* Look up an existing connection */ struct bt_conn *bt_conn_lookup_handle(u16_t handle); /* Check if the connection is with the given peer. */ bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, u8_t id, const bt_addr_le_t *peer); /* Helpers for identifying & looking up connections based on the the index to * the connection list. This is useful for O(1) lookups, but can't be used * e.g. as the handle since that's assigned to us by the controller. */ #define BT_CONN_INDEX_INVALID 0xff struct bt_conn *bt_conn_lookup_index(u8_t index); /* Look up a connection state. For BT_ADDR_LE_ANY, returns the first connection * with the specific state */ struct bt_conn *bt_conn_lookup_state_le(u8_t id, const bt_addr_le_t *peer, const bt_conn_state_t state); /* Set connection object in certain state and perform action related to state */ void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state); int bt_conn_le_conn_update(struct bt_conn *conn, const struct bt_le_conn_param *param); void notify_remote_info(struct bt_conn *conn); void notify_le_param_updated(struct bt_conn *conn); void notify_le_data_len_updated(struct bt_conn *conn); void notify_le_phy_updated(struct bt_conn *conn); bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param); #if defined(CONFIG_BT_SMP) /* rand and ediv should be in BT order */ int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], u8_t ediv[2], const u8_t *ltk, size_t len); /* Notify higher layers that RPA was resolved */ void bt_conn_identity_resolved(struct bt_conn *conn); #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) /* Notify higher layers that connection security changed */ void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err); #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ /* Prepare a PDU to be sent over a connection */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout, const char *func, int line); #define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) \ bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \ __func__, __LINE__) #define bt_conn_create_pdu(_pool, _reserve) \ bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \ __func__, __line__) #else struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout); #define bt_conn_create_pdu(_pool, _reserve) \ bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER) #endif /* Prepare a PDU to be sent over a connection */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve, k_timeout_t timeout, const char *func, int line); #define bt_conn_create_frag_timeout(_reserve, _timeout) \ bt_conn_create_frag_timeout_debug(_reserve, _timeout, \ __func__, __LINE__) #define bt_conn_create_frag(_reserve) \ bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \ __func__, __LINE__) #else struct net_buf *bt_conn_create_frag_timeout(size_t reserve, k_timeout_t timeout); #define bt_conn_create_frag(_reserve) \ bt_conn_create_frag_timeout(_reserve, K_FOREVER) #endif /* Initialize connection management */ int bt_conn_init(void); /* Selects based on connecton type right semaphore for ACL packets */ struct k_sem *bt_conn_get_pkts(struct bt_conn *conn); /* k_poll related helpers for the TX thread */ int bt_conn_prepare_events(struct k_poll_event events[]); void bt_conn_process_tx(struct bt_conn *conn);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/conn_internal.h
C
apache-2.0
9,209
/* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <bt_errno.h> #include <ble_os.h> #include "bt_crypto.h" int bt_rand(void *buf, size_t len) { return bt_crypto_rand(buf, len); } int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) { return bt_crypto_encrypt_le(key, plaintext, enc_data); } int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) { return bt_crypto_encrypt_be(key, plaintext, enc_data); } int bt_decrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) { return bt_crypto_decrypt_be(key, plaintext, enc_data); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/crypto.c
C
apache-2.0
747
/* ecc.h - ECDH helpers */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /* @brief Container for public key callback */ struct bt_pub_key_cb { /** @brief Callback type for Public Key generation. * * Used to notify of the local public key or that the local key is not * available (either because of a failure to read it or because it is * being regenerated). * * @param key The local public key, or NULL in case of no key. */ void (*func)(const u8_t key[64]); struct bt_pub_key_cb *_next; }; /* @brief Generate a new Public Key. * * Generate a new ECC Public Key. The callback will persist even after the * key has been generated, and will be used to notify of new generation * processes (NULL as key). * * @param cb Callback to notify the new key, or NULL to request an update * without registering any new callback. * * @return Zero on success or negative error code otherwise */ int bt_pub_key_gen(struct bt_pub_key_cb *cb); /* @brief Get the current Public Key. * * Get the current ECC Public Key. * * @return Current key, or NULL if not available. */ const u8_t *bt_pub_key_get(void); /* @typedef bt_dh_key_cb_t * @brief Callback type for DH Key calculation. * * Used to notify of the calculated DH Key. * * @param key The DH Key, or NULL in case of failure. */ typedef void (*bt_dh_key_cb_t)(const u8_t key[32]); /* @brief Calculate a DH Key from a remote Public Key. * * Calculate a DH Key from the remote Public Key. * * @param remote_pk Remote Public Key. * @param cb Callback to notify the calculated key. * * @return Zero on success or negative error code otherwise */ int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/ecc.h
C
apache-2.0
1,773
/* gatt.c - Generic Attribute Profile handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <bt_errno.h> #include <stdbool.h> #include <stdlib.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <settings/settings.h> #if defined(CONFIG_BT_GATT_CACHING) #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> #include <tinycrypt/aes.h> #include <tinycrypt/cmac_mode.h> #include <tinycrypt/ccm_mode.h> #endif /* CONFIG_BT_GATT_CACHING */ #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/uuid.h> #include <bluetooth/gatt.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_GATT) #define LOG_MODULE_NAME bt_gatt #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "keys.h" #include "l2cap_internal.h" #include "att_internal.h" #include "smp.h" #include "settings.h" #include "gatt_internal.h" #include <bt_crypto.h> #define SC_TIMEOUT K_MSEC(10) #define CCC_STORE_DELAY K_SECONDS(1) #define DB_HASH_TIMEOUT K_MSEC(10) #define SC_TIMEOUT K_MSEC(10) #define CCC_STORE_DELAY K_SECONDS(1) #define DB_HASH_TIMEOUT K_MSEC(10) static u16_t last_static_handle = 0; /* Persistent storage format for GATT CCC */ struct ccc_store { u16_t handle; u16_t value; }; struct gatt_sub { u8_t id; bt_addr_le_t peer; sys_slist_t list; }; #if defined(CONFIG_BT_GATT_CLIENT) #define SUB_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) #else #define SUB_MAX 0 #endif /* CONFIG_BT_GATT_CLIENT */ static struct gatt_sub subscriptions[SUB_MAX]; static const u16_t gap_appearance = CONFIG_BT_DEVICE_APPEARANCE; #if defined(CONFIG_BT_GATT_DYNAMIC_DB) static sys_slist_t db; #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ static atomic_t init; #if defined(CONFIG_BT_SETTINGS) int bt_gatt_settings_init(); #endif static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { const char *name = bt_get_name(); return bt_gatt_attr_read(conn, attr, buf, len, offset, name, strlen(name)); } #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE) static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) { char value[CONFIG_BT_DEVICE_NAME_MAX] = {}; if (offset) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); } if (len >= sizeof(value)) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); } memcpy(value, buf, len); bt_set_name(value); return len; } #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */ static ssize_t read_appearance(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { u16_t appearance = sys_cpu_to_le16(gap_appearance); return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance, sizeof(appearance)); } #if defined (CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS) /* This checks if the range entered is valid */ BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 && CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff)); BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 && CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff)); BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 && CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff)); BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) || (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <= CONFIG_BT_PERIPHERAL_PREF_MAX_INT)); static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { struct __packed { u16_t min_int; u16_t max_int; u16_t latency; u16_t timeout; } ppcp; ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT); ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT); ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY); ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT); return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp, sizeof(ppcp)); } #endif #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY) static ssize_t read_central_addr_res(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP; return bt_gatt_attr_read(conn, attr, buf, len, offset, &central_addr_res, sizeof(central_addr_res)); } #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */ BT_GATT_SERVICE_DEFINE(_2_gap_svc, BT_GATT_PRIMARY_SERVICE(BT_UUID_GAP), #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE) /* Require pairing for writes to device name */ BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_ENCRYPT, read_name, write_name, bt_dev.name), #else BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_name, NULL, NULL), #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */ BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_appearance, NULL, NULL), #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY) BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_central_addr_res, NULL, NULL), #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS) BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_ppcp, NULL, NULL), #endif ); struct sc_data { u16_t start; u16_t end; } __packed; struct gatt_sc_cfg { u8_t id; bt_addr_le_t peer; struct { u16_t start; u16_t end; } data; }; #define SC_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) static struct gatt_sc_cfg sc_cfg[SC_CFG_MAX]; BUILD_ASSERT(sizeof(struct sc_data) == sizeof(sc_cfg[0].data)); static struct gatt_sc_cfg *find_sc_cfg(u8_t id, bt_addr_le_t *addr) { BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr)); for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) { if (id == sc_cfg[i].id && !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) { return &sc_cfg[i]; } } return NULL; } static void sc_store(struct gatt_sc_cfg *cfg) { char key[BT_SETTINGS_KEY_MAX]; int err; if (cfg->id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), cfg->id); bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, id_str); } else { bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, NULL); } err = settings_save_one(key, (char *)&cfg->data, sizeof(cfg->data)); if (err) { BT_ERR("failed to store SC (err %d)", err); return; } BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)", bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start, cfg->data.end); } static void clear_sc_cfg(struct gatt_sc_cfg *cfg) { memset(cfg, 0, sizeof(*cfg)); } static int bt_gatt_clear_sc(u8_t id, const bt_addr_le_t *addr) { struct gatt_sc_cfg *cfg; cfg = find_sc_cfg(id, (bt_addr_le_t *)addr); if (!cfg) { return 0; } if (IS_ENABLED(CONFIG_BT_SETTINGS)) { char key[BT_SETTINGS_KEY_MAX]; int err; if (cfg->id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), cfg->id); bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, id_str); } else { bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, NULL); } err = settings_delete(key); if (err) { BT_ERR("failed to delete SC (err %d)", err); } else { BT_DBG("deleted SC for %s (%s)", bt_addr_le_str(&cfg->peer), log_strdup(key)); } } clear_sc_cfg(cfg); return 0; } static void sc_clear(struct bt_conn *conn) { if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { int err; err = bt_gatt_clear_sc(conn->id, &conn->le.dst); if (err) { BT_ERR("Failed to clear SC %d", err); } } else { struct gatt_sc_cfg *cfg; cfg = find_sc_cfg(conn->id, &conn->le.dst); if (cfg) { clear_sc_cfg(cfg); } } } static void sc_reset(struct gatt_sc_cfg *cfg) { BT_DBG("peer %s", bt_addr_le_str(&cfg->peer)); memset(&cfg->data, 0, sizeof(cfg->data)); if (IS_ENABLED(CONFIG_BT_SETTINGS)) { sc_store(cfg); } } static bool update_range(u16_t *start, u16_t *end, u16_t new_start, u16_t new_end) { BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x", *start, *end, new_start, new_end); /* Check if inside existing range */ if (new_start >= *start && new_end <= *end) { return false; } /* Update range */ if (*start > new_start) { *start = new_start; } if (*end < new_end) { *end = new_end; } return true; } static void sc_save(u8_t id, bt_addr_le_t *peer, u16_t start, u16_t end) { struct gatt_sc_cfg *cfg; bool modified = false; BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, end); cfg = find_sc_cfg(id, peer); if (!cfg) { /* Find and initialize a free sc_cfg entry */ cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); if (!cfg) { BT_ERR("unable to save SC: no cfg left"); return; } cfg->id = id; bt_addr_le_copy(&cfg->peer, peer); } /* Check if there is any change stored */ if (!(cfg->data.start || cfg->data.end)) { cfg->data.start = start; cfg->data.end = end; modified = true; goto done; } modified = update_range(&cfg->data.start, &cfg->data.end, start, end); done: if (IS_ENABLED(CONFIG_BT_SETTINGS) && modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) { sc_store(cfg); } } static ssize_t sc_ccc_cfg_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t value) { BT_DBG("value 0x%04x", value); if (value == BT_GATT_CCC_INDICATE) { /* Create a new SC configuration entry if subscribed */ sc_save(conn->id, &conn->le.dst, 0, 0); } else { sc_clear(conn); } return sizeof(value); } static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL, sc_ccc_cfg_write, NULL); enum { CF_CHANGE_AWARE, /* Client is changed aware */ CF_OUT_OF_SYNC, /* Client is out of sync */ /* Total number of flags - must be at the end of the enum */ CF_NUM_FLAGS, }; #define CF_BIT_ROBUST_CACHING 0 #define CF_BIT_EATT 1 #define CF_BIT_NOTIFY_MULTI 2 #define CF_BIT_LAST CF_BIT_NOTIFY_MULTI #define CF_BYTE_LAST (CF_BIT_LAST % 8) #define CF_ROBUST_CACHING(_cfg) (_cfg->data[0] & BIT(CF_BIT_ROBUST_CACHING)) #define CF_EATT(_cfg) (_cfg->data[0] & BIT(CF_BIT_EATT)) #define CF_NOTIFY_MULTI(_cfg) (_cfg->data[0] & BIT(CF_BIT_NOTIFY_MULTI)) struct gatt_cf_cfg { u8_t id; bt_addr_le_t peer; u8_t data[1]; ATOMIC_DEFINE(flags, CF_NUM_FLAGS); }; #if defined(CONFIG_BT_GATT_CACHING) #define CF_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) #else #define CF_CFG_MAX 0 #endif /* CONFIG_BT_GATT_CACHING */ static struct gatt_cf_cfg cf_cfg[CF_CFG_MAX] = {}; static void clear_cf_cfg(struct gatt_cf_cfg *cfg) { bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY); memset(cfg->data, 0, sizeof(cfg->data)); atomic_set(cfg->flags, 0); } #if defined(CONFIG_BT_GATT_CACHING) static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn) { int i; for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { struct gatt_cf_cfg *cfg = &cf_cfg[i]; if (!conn) { if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { return cfg; } } else if (bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) { return cfg; } } return NULL; } static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { struct gatt_cf_cfg *cfg; u8_t data[1] = {}; cfg = find_cf_cfg(conn); if (cfg) { memcpy(data, cfg->data, sizeof(data)); } return bt_gatt_attr_read(conn, attr, buf, len, offset, data, sizeof(data)); } static bool cf_set_value(struct gatt_cf_cfg *cfg, const u8_t *value, u16_t len) { u16_t i; u8_t last_byte = CF_BYTE_LAST; u8_t last_bit = CF_BIT_LAST; /* Validate the bits */ for (i = 0U; i < len && i <= last_byte; i++) { u8_t chg_bits = value[i] ^ cfg->data[i]; u8_t bit; for (bit = 0U; bit <= last_bit; bit++) { /* A client shall never clear a bit it has set */ if ((BIT(bit) & chg_bits) && (BIT(bit) & cfg->data[i])) { return false; } } } /* Set the bits for each octect */ for (i = 0U; i < len && i < last_byte; i++) { cfg->data[i] |= value[i] & (BIT(last_bit + 1) - 1); BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i], value[i]); } return true; } static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) { struct gatt_cf_cfg *cfg; const u8_t *value = buf; if (offset > sizeof(cfg->data)) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); } if (offset + len > sizeof(cfg->data)) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); } cfg = find_cf_cfg(conn); if (!cfg) { cfg = find_cf_cfg(NULL); } if (!cfg) { BT_WARN("No space to store Client Supported Features"); return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES); } BT_DBG("handle 0x%04x len %u", attr->handle, len); if (!cf_set_value(cfg, value, len)) { return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED); } bt_addr_le_copy(&cfg->peer, &conn->le.dst); cfg->id = conn->id; atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); return len; } static u8_t db_hash[16]; struct k_delayed_work db_hash_work; struct gen_hash_state { struct tc_cmac_struct state; int err; }; static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data) { struct gen_hash_state *state = user_data; struct bt_uuid_16 *u16; u8_t data[16]; ssize_t len; u16_t value; if (attr->uuid->type != BT_UUID_TYPE_16) return BT_GATT_ITER_CONTINUE; u16 = (struct bt_uuid_16 *)attr->uuid; switch (u16->val) { /* Attributes to hash: handle + UUID + value */ case 0x2800: /* GATT Primary Service */ case 0x2801: /* GATT Secondary Service */ case 0x2802: /* GATT Include Service */ case 0x2803: /* GATT Characteristic */ case 0x2900: /* GATT Characteristic Extended Properties */ value = sys_cpu_to_le16(attr->handle); if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(attr->handle)) == TC_CRYPTO_FAIL) { state->err = -EINVAL; return BT_GATT_ITER_STOP; } value = sys_cpu_to_le16(u16->val); if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(u16->val)) == TC_CRYPTO_FAIL) { state->err = -EINVAL; return BT_GATT_ITER_STOP; } len = attr->read(NULL, attr, data, sizeof(data), 0); if (len < 0) { state->err = len; return BT_GATT_ITER_STOP; } if (tc_cmac_update(&state->state, data, len) == TC_CRYPTO_FAIL) { state->err = -EINVAL; return BT_GATT_ITER_STOP; } break; /* Attributes to hash: handle + UUID */ case 0x2901: /* GATT Characteristic User Descriptor */ case 0x2902: /* GATT Client Characteristic Configuration */ case 0x2903: /* GATT Server Characteristic Configuration */ case 0x2904: /* GATT Characteristic Presentation Format */ case 0x2905: /* GATT Characteristic Aggregated Format */ value = sys_cpu_to_le16(attr->handle); if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(attr->handle)) == TC_CRYPTO_FAIL) { state->err = -EINVAL; return BT_GATT_ITER_STOP; } value = sys_cpu_to_le16(u16->val); if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(u16->val)) == TC_CRYPTO_FAIL) { state->err = -EINVAL; return BT_GATT_ITER_STOP; } break; default: return BT_GATT_ITER_CONTINUE; } return BT_GATT_ITER_CONTINUE; } static void db_hash_store(void) { int err; err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash)); if (err) { BT_ERR("Failed to save Database Hash (err %d)", err); } BT_DBG("Database Hash stored"); } /* Once the db_hash work has started we cannot cancel it anymore, so the * assumption is made that the in-progress work cannot be pre-empted. * This assumption should hold as long as calculation does not make any calls * that would make it unready. * If this assumption is no longer true we will have to solve the case where * k_delayed_work_cancel failed because the work was in-progress but pre-empted. */ static void db_hash_gen(bool store) { u8_t key[16] = {}; struct tc_aes_key_sched_struct sched; struct gen_hash_state state; if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) { BT_ERR("Unable to setup AES CMAC"); return; } bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state); if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) { BT_ERR("Unable to calculate hash"); return; } /** * Core 5.1 does not state the endianess of the hash. * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic * Values shall be LE unless otherwise defined. PTS expects hash to be * in little endianess as well. bt_smp_aes_cmac calculates the hash in * big endianess so we have to swap. */ sys_mem_swap(db_hash, sizeof(db_hash)); BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: "); if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { db_hash_store(); } } static void db_hash_process(struct k_work *work) { db_hash_gen(true); } static ssize_t db_hash_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { int err; /* Check if db_hash is already pending in which case it shall be * generated immediately instead of waiting for the work to complete. */ err = k_delayed_work_cancel(&db_hash_work); if (!err) { db_hash_gen(true); } /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: * 2.5.2.1 Robust Caching * A connected client becomes change-aware when... * The client reads the Database Hash characteristic and then the server * receives another ATT request from the client. */ bt_gatt_change_aware(conn, true); return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash, sizeof(db_hash)); } static void remove_cf_cfg(struct bt_conn *conn) { struct gatt_cf_cfg *cfg; cfg = find_cf_cfg(conn); if (!cfg) { return; } /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405: * For clients with a trusted relationship, the characteristic value * shall be persistent across connections. For clients without a * trusted relationship the characteristic value shall be set to the * default value at each connection. */ if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { clear_cf_cfg(cfg); } else { /* Update address in case it has changed */ bt_addr_le_copy(&cfg->peer, &conn->le.dst); atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); } } #if defined(CONFIG_BT_EATT) #define SF_BIT_EATT 0 #define SF_BIT_LAST SF_BIT_EATT static ssize_t sf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { u8_t value = BIT(SF_BIT_EATT); return bt_gatt_attr_read(conn, attr, buf, len, offset, &value, sizeof(value)); } #endif /* CONFIG_BT_EATT */ #endif /* CONFIG_BT_GATT_CACHING */ BT_GATT_SERVICE_DEFINE(_1_gatt_svc, BT_GATT_PRIMARY_SERVICE(BT_UUID_GATT), #if defined(CONFIG_BT_GATT_SERVICE_CHANGED) /* Bluetooth 5.0, Vol3 Part G: * The Service Changed characteristic Attribute Handle on the server * shall not change if the server has a trusted relationship with any * client. */ BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE, BT_GATT_PERM_NONE, NULL, NULL, NULL), BT_GATT_CCC_MANAGED(&sc_ccc, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), #if defined(CONFIG_BT_GATT_CACHING) BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, cf_read, cf_write, NULL), BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, db_hash_read, NULL, NULL), #if defined(CONFIG_BT_EATT) BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SERVER_FEATURES, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, sf_read, NULL, NULL), #endif /* CONFIG_BT_EATT */ #endif /* CONFIG_BT_GATT_CACHING */ #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */ ); #if defined(CONFIG_BT_GATT_DYNAMIC_DB) static u8_t found_attr(const struct bt_gatt_attr *attr, void *user_data) { const struct bt_gatt_attr **found = user_data; *found = attr; return BT_GATT_ITER_STOP; } static const struct bt_gatt_attr *find_attr(uint16_t handle) { const struct bt_gatt_attr *attr = NULL; bt_gatt_foreach_attr(handle, handle, found_attr, &attr); return attr; } static void gatt_insert(struct bt_gatt_service *svc, u16_t last_handle) { struct bt_gatt_service *tmp, *prev = NULL; if (last_handle == 0 || svc->attrs[0].handle > last_handle) { sys_slist_append(&db, &svc->node); return; } /* DB shall always have its service in ascending order */ SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) { if (tmp->attrs[0].handle > svc->attrs[0].handle) { if (prev) { sys_slist_insert(&db, &prev->node, &svc->node); } else { sys_slist_prepend(&db, &svc->node); } return; } prev = tmp; } } static int gatt_register(struct bt_gatt_service *svc) { struct bt_gatt_service *last; u16_t handle, last_handle; struct bt_gatt_attr *attrs = svc->attrs; u16_t count = svc->attr_count; if (sys_slist_is_empty(&db)) { handle = last_static_handle; last_handle = 0; goto populate; } last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node); handle = last->attrs[last->attr_count - 1].handle; last_handle = handle; populate: /* Populate the handles and append them to the list */ for (; attrs && count; attrs++, count--) { if (!attrs->handle) { /* Allocate handle if not set already */ attrs->handle = ++handle; } else if (attrs->handle > handle) { /* Use existing handle if valid */ handle = attrs->handle; } else if (find_attr(attrs->handle)) { /* Service has conflicting handles */ BT_ERR("Unable to register handle 0x%04x", attrs->handle); return -EINVAL; } BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x", attrs, attrs->handle, bt_uuid_str(attrs->uuid), attrs->perm); } gatt_insert(svc, last_handle); return 0; } #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ enum { SC_RANGE_CHANGED, /* SC range changed */ SC_INDICATE_PENDING, /* SC indicate pending */ /* Total number of flags - must be at the end of the enum */ SC_NUM_FLAGS, }; static struct gatt_sc { struct bt_gatt_indicate_params params; u16_t start; u16_t end; struct k_delayed_work work; ATOMIC_DEFINE(flags, SC_NUM_FLAGS); } gatt_sc; static void sc_indicate_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) { #if defined(CONFIG_BT_GATT_CACHING) struct gatt_cf_cfg *cfg; #endif BT_DBG("err 0x%02x", err); atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING); /* Check if there is new change in the meantime */ if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { /* Reschedule without any delay since it is waiting already */ k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT); } #if defined(CONFIG_BT_GATT_CACHING) /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: * 2.5.2.1 Robust Caching * A connected client becomes change-aware when... * The client receives and confirms a Service Changed indication. */ cfg = find_cf_cfg(conn); if (cfg && CF_ROBUST_CACHING(cfg)) { atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); } #endif } static void sc_process(struct k_work *work) { struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work); u16_t sc_range[2]; __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING), "Indicate already pending"); BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end); sc_range[0] = sys_cpu_to_le16(sc->start); sc_range[1] = sys_cpu_to_le16(sc->end); atomic_clear_bit(sc->flags, SC_RANGE_CHANGED); sc->start = 0U; sc->end = 0U; sc->params.attr = &_1_gatt_svc.attrs[2]; sc->params.func = sc_indicate_rsp; sc->params.data = &sc_range[0]; sc->params.len = sizeof(sc_range); if (bt_gatt_indicate(NULL, &sc->params)) { /* No connections to indicate */ return; } atomic_set_bit(sc->flags, SC_INDICATE_PENDING); } #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) static struct gatt_ccc_store { struct bt_conn *conn_list[CONFIG_BT_MAX_CONN]; struct k_delayed_work work; } gatt_ccc_store; static bool gatt_ccc_conn_is_queued(struct bt_conn *conn) { return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]); } static void gatt_ccc_conn_unqueue(struct bt_conn *conn) { u8_t index = bt_conn_index(conn); if (gatt_ccc_store.conn_list[index] != NULL) { bt_conn_unref(gatt_ccc_store.conn_list[index]); gatt_ccc_store.conn_list[index] = NULL; } } static bool gatt_ccc_conn_queue_is_empty(void) { for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) { if (gatt_ccc_store.conn_list[i]) { return false; } } return true; } static void ccc_delayed_store(struct k_work *work) { struct gatt_ccc_store *ccc_store = CONTAINER_OF(work, struct gatt_ccc_store, work); for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) { struct bt_conn *conn = ccc_store->conn_list[i]; if (!conn) { continue; } if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { bt_gatt_store_ccc(conn->id, &conn->le.dst); bt_conn_unref(conn); ccc_store->conn_list[i] = NULL; } } } #endif static const struct bt_gatt_service_static *_bt_gatt_service_static[] = { &_2_gap_svc, &_1_gatt_svc, }; void bt_gatt_init(void) { if (!atomic_cas(&init, 0, 1)) { return; } /* Register mandatory services */ //gatt_register(&_2_gap_svc); //gatt_register(&_1_gatt_svc); last_static_handle += _2_gap_svc.attr_count; last_static_handle += _1_gatt_svc.attr_count; // Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc) { #if defined(CONFIG_BT_GATT_CACHING) k_delayed_work_init(&db_hash_work, db_hash_process); /* Submit work to Generate initial hash as there could be static * services already in the database. */ k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT); #endif /* CONFIG_BT_GATT_CACHING */ if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) { k_delayed_work_init(&gatt_sc.work, sc_process); if (IS_ENABLED(CONFIG_BT_SETTINGS)) { /* Make sure to not send SC indications until SC * settings are loaded */ atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING); } } #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store); #endif #if defined(CONFIG_BT_SETTINGS) bt_gatt_settings_init(); #endif } #if defined(CONFIG_BT_GATT_DYNAMIC_DB) || \ (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS)) static void sc_indicate(u16_t start, u16_t end) { BT_DBG("start 0x%04x end 0x%04x", start, end); if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { gatt_sc.start = start; gatt_sc.end = end; goto submit; } if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) { return; } submit: if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) { BT_DBG("indicate pending, waiting until complete..."); return; } /* Reschedule since the range has changed */ k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT); } #endif /* BT_GATT_DYNAMIC_DB || (BT_GATT_CACHING && BT_SETTINGS) */ #if defined(CONFIG_BT_GATT_DYNAMIC_DB) static void db_changed(void) { #if defined(CONFIG_BT_GATT_CACHING) int i; k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT); for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { struct gatt_cf_cfg *cfg = &cf_cfg[i]; if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { continue; } if (CF_ROBUST_CACHING(cfg)) { /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching *... the database changes again before the client * becomes change-aware in which case the error response * shall be sent again. */ atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); if (atomic_test_and_clear_bit(cfg->flags, CF_CHANGE_AWARE)) { BT_DBG("%s change-unaware", bt_addr_le_str(&cfg->peer)); } } } #endif } int bt_gatt_service_register(struct bt_gatt_service *svc) { int err; __ASSERT(svc, "invalid parameters\n"); __ASSERT(svc->attrs, "invalid parameters\n"); __ASSERT(svc->attr_count, "invalid parameters\n"); /* Init GATT core services */ bt_gatt_init(); /* Do no allow to register mandatory services twice */ if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) || !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) { return -EALREADY; } err = gatt_register(svc); if (err < 0) { return err; } sc_indicate(svc->attrs[0].handle, svc->attrs[svc->attr_count - 1].handle); db_changed(); return 0; } int bt_gatt_service_unregister(struct bt_gatt_service *svc) { __ASSERT(svc, "invalid parameters\n"); if (!sys_slist_find_and_remove(&db, &svc->node)) { return -ENOENT; } sc_indicate(svc->attrs[0].handle, svc->attrs[svc->attr_count - 1].handle); db_changed(); return 0; } #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t buf_len, u16_t offset, const void *value, u16_t value_len) { u16_t len; if (offset > value_len) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); } len = MIN(buf_len, value_len - offset); BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset, len); memcpy(buf, (u8_t *)value + offset, len); return len; } ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { struct bt_uuid *uuid = attr->user_data; if (uuid->type == BT_UUID_TYPE_16) { u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val); return bt_gatt_attr_read(conn, attr, buf, len, offset, &uuid16, 2); } return bt_gatt_attr_read(conn, attr, buf, len, offset, BT_UUID_128(uuid)->val, 16); } struct gatt_incl { u16_t start_handle; u16_t end_handle; u16_t uuid16; } __packed; static u8_t get_service_handles(const struct bt_gatt_attr *attr, void *user_data) { struct gatt_incl *include = user_data; /* Stop if attribute is a service */ if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { return BT_GATT_ITER_STOP; } include->end_handle = attr->handle; return BT_GATT_ITER_CONTINUE; } static u16_t find_static_attr(const struct bt_gatt_attr *attr) { u16_t handle = 1; // Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) { for (const struct bt_gatt_service_static *static_svc = _bt_gatt_service_static[0]; (uint32_t)static_svc < (uint32_t)_bt_gatt_service_static[ARRAY_SIZE(_bt_gatt_service_static)]; ++static_svc) { for (size_t i = 0; i < static_svc->attr_count; i++, handle++) { if (attr == &static_svc->attrs[i]) { return handle; } } } return 0; } ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { struct bt_gatt_attr *incl = attr->user_data; u16_t handle = incl->handle ? : find_static_attr(incl); struct bt_uuid *uuid = incl->user_data; struct gatt_incl pdu; u8_t value_len; /* first attr points to the start handle */ pdu.start_handle = sys_cpu_to_le16(handle); value_len = sizeof(pdu.start_handle) + sizeof(pdu.end_handle); /* * Core 4.2, Vol 3, Part G, 3.2, * The Service UUID shall only be present when the UUID is a * 16-bit Bluetooth UUID. */ if (uuid->type == BT_UUID_TYPE_16) { pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val); value_len += sizeof(pdu.uuid16); } /* Lookup for service end handle */ bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu); return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len); } struct gatt_chrc { u8_t properties; u16_t value_handle; union { u16_t uuid16; u8_t uuid[16]; }; } __packed; uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr) { u16_t handle = 0; if ((attr != NULL) && (attr->read == bt_gatt_attr_read_chrc)) { struct bt_gatt_chrc *chrc = attr->user_data; handle = chrc->value_handle; if (handle == 0) { /* Fall back to Zephyr value handle policy */ handle = (attr->handle ? : find_static_attr(attr)) + 1U; } } return handle; } ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { struct bt_gatt_chrc *chrc = attr->user_data; struct gatt_chrc pdu; u8_t value_len; pdu.properties = chrc->properties; /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534: * 3.3.2 Characteristic Value Declaration * The Characteristic Value declaration contains the value of the * characteristic. It is the first Attribute after the characteristic * declaration. All characteristic definitions shall have a * Characteristic Value declaration. */ pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr)); value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle); if (chrc->uuid->type == BT_UUID_TYPE_16) { pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val); value_len += 2U; } else { memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16); value_len += 16U; } return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len); } static u8_t gatt_foreach_iter(const struct bt_gatt_attr *attr, u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t *num_matches, bt_gatt_attr_func_t func, void *user_data) { u8_t result; /* Stop if over the requested range */ if (attr->handle > end_handle) { return BT_GATT_ITER_STOP; } /* Check if attribute handle is within range */ if (attr->handle < start_handle) { return BT_GATT_ITER_CONTINUE; } /* Match attribute UUID if set */ if (uuid && bt_uuid_cmp(uuid, attr->uuid)) { return BT_GATT_ITER_CONTINUE; } /* Match attribute user_data if set */ if (attr_data && attr_data != attr->user_data) { return BT_GATT_ITER_CONTINUE; } *num_matches -= 1; result = func(attr, user_data); if (!*num_matches) { return BT_GATT_ITER_STOP; } return result; } static void foreach_attr_type_dyndb(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data) { #if defined(CONFIG_BT_GATT_DYNAMIC_DB) size_t i; struct bt_gatt_service *svc; SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node) { struct bt_gatt_service *next; next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node); if (next) { /* Skip ahead if start is not within service handles */ if (next->attrs[0].handle <= start_handle) { continue; } } for (i = 0; i < svc->attr_count; i++) { struct bt_gatt_attr *attr = &svc->attrs[i]; if (gatt_foreach_iter(attr, start_handle, end_handle, uuid, attr_data, &num_matches, func, user_data) == BT_GATT_ITER_STOP) { return; } } } #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ } void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data) { size_t i; if (!num_matches) { num_matches = UINT16_MAX; } if (start_handle <= last_static_handle) { u16_t handle = 1; // Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) { const struct bt_gatt_service_static *static_svc = NULL; //SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) { //SYS_SLIST_ITERATE_FROM_NODE(&db, static_svc) { int ii; for (ii = 0; ii < 2; ii++) { static_svc = _bt_gatt_service_static[ii]; /* Skip ahead if start is not within service handles */ if (handle + static_svc->attr_count < start_handle) { handle += static_svc->attr_count; continue; } for (i = 0; i < static_svc->attr_count; i++, handle++) { struct bt_gatt_attr attr; memcpy(&attr, &static_svc->attrs[i], sizeof(attr)); attr.handle = handle; if (gatt_foreach_iter(&attr, start_handle, end_handle, uuid, attr_data, &num_matches, func, user_data) == BT_GATT_ITER_STOP) { return; } } } } /* Iterate over dynamic db */ foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data, num_matches, func, user_data); } static u8_t find_next(const struct bt_gatt_attr *attr, void *user_data) { struct bt_gatt_attr **next = user_data; *next = (struct bt_gatt_attr *)attr; return BT_GATT_ITER_STOP; } struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr) { struct bt_gatt_attr *next = NULL; u16_t handle = attr->handle ? : find_static_attr(attr); bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next); return next; } static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg) { bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY); cfg->id = 0U; cfg->value = 0U; } static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn, struct _bt_gatt_ccc *ccc) { for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; if (conn) { if (bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) { return cfg; } } else if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { return cfg; } } return NULL; } ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { struct _bt_gatt_ccc *ccc = attr->user_data; const struct bt_gatt_ccc_cfg *cfg; u16_t value; cfg = find_ccc_cfg(conn, ccc); if (cfg) { value = sys_cpu_to_le16(cfg->value); } else { /* Default to disable if there is no cfg for the peer */ value = 0x0000; } return bt_gatt_attr_read(conn, attr, buf, len, offset, &value, sizeof(value)); } static void gatt_ccc_changed(const struct bt_gatt_attr *attr, struct _bt_gatt_ccc *ccc) { int i; u16_t value = 0x0000; for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { if (ccc->cfg[i].value > value) { value = ccc->cfg[i].value; } } BT_DBG("ccc %p value 0x%04x", ccc, value); if (value != ccc->value) { ccc->value = value; if (ccc->cfg_changed) { ccc->cfg_changed(attr, value); } } } ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) { struct _bt_gatt_ccc *ccc = attr->user_data; struct bt_gatt_ccc_cfg *cfg; u16_t value; if (offset) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); } if (!len || len > sizeof(u16_t)) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); } if (len < sizeof(u16_t)) { value = *(u8_t *)buf; } else { value = sys_get_le16(buf); } cfg = find_ccc_cfg(conn, ccc); if (!cfg) { /* If there's no existing entry, but the new value is zero, * we don't need to do anything, since a disabled CCC is * behavioraly the same as no written CCC. */ if (!value) { return len; } cfg = find_ccc_cfg(NULL, ccc); if (!cfg) { BT_WARN("No space to store CCC cfg"); return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES); } bt_addr_le_copy(&cfg->peer, &conn->le.dst); cfg->id = conn->id; } /* Confirm write if cfg is managed by application */ if (ccc->cfg_write) { ssize_t write = ccc->cfg_write(conn, attr, value); if (write < 0) { return write; } /* Accept size=1 for backwards compatibility */ if (write != sizeof(value) && write != 1) { return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY); } } cfg->value = value; BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value); /* Update cfg if don't match */ if (cfg->value != ccc->value) { gatt_ccc_changed(attr, ccc); #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) if ((!gatt_ccc_conn_is_queued(conn)) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { /* Store the connection with the same index it has in * the conns array */ gatt_ccc_store.conn_list[bt_conn_index(conn)] = bt_conn_ref(conn); k_delayed_work_submit(&gatt_ccc_store.work, CCC_STORE_DELAY); } #endif } /* Disabled CCC is the same as no configured CCC, so clear the entry */ if (!value) { clear_ccc_cfg(cfg); } return len; } ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { const struct bt_gatt_cep *value = attr->user_data; u16_t props = sys_cpu_to_le16(value->properties); return bt_gatt_attr_read(conn, attr, buf, len, offset, &props, sizeof(props)); } ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { const char *value = attr->user_data; return bt_gatt_attr_read(conn, attr, buf, len, offset, value, strlen(value)); } ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { const struct bt_gatt_cpf *value = attr->user_data; return bt_gatt_attr_read(conn, attr, buf, len, offset, value, sizeof(*value)); } struct notify_data { int err; u16_t type; union { struct bt_gatt_notify_params *nfy_params; struct bt_gatt_indicate_params *ind_params; }; }; #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE) struct nfy_mult_data { bt_gatt_complete_func_t func; void *user_data; }; #define nfy_mult_user_data(buf) \ ((struct nfy_mult_data *)net_buf_user_data(buf)) #define nfy_mult_data_match(buf, _func, _user_data) \ ((nfy_mult_user_data(buf)->func == _func) && \ (nfy_mult_user_data(buf)->user_data == _user_data)) static struct net_buf *nfy_mult[CONFIG_BT_MAX_CONN]; static int gatt_notify_mult_send(struct bt_conn *conn, struct net_buf **buf) { struct nfy_mult_data *data = nfy_mult_user_data(*buf); int ret; ret = bt_att_send(conn, *buf, data->func, data->user_data); if (ret < 0) { net_buf_unref(*buf); } *buf = NULL; return ret; } static void notify_mult_process(struct k_work *work) { int i; /* Send to any connection with an allocated buffer */ for (i = 0; i < ARRAY_SIZE(nfy_mult); i++) { struct net_buf **buf = &nfy_mult[i]; if (*buf) { struct bt_conn *conn = bt_conn_lookup_index(i); gatt_notify_mult_send(conn, buf); bt_conn_unref(conn); } } } K_WORK_DEFINE(nfy_mult_work, notify_mult_process); static bool gatt_cf_notify_multi(struct bt_conn *conn) { struct gatt_cf_cfg *cfg; cfg = find_cf_cfg(conn); if (!cfg) { return false; } return CF_NOTIFY_MULTI(cfg); } static int gatt_notify_mult(struct bt_conn *conn, u16_t handle, struct bt_gatt_notify_params *params) { struct net_buf **buf = &nfy_mult[bt_conn_index(conn)]; struct bt_att_notify_mult *nfy; /* Check if we can fit more data into it, in case it doesn't fit send * the existing buffer and proceed to create a new one */ if (*buf && ((net_buf_tailroom(*buf) < sizeof(*nfy) + params->len) || !nfy_mult_data_match(*buf, params->func, params->user_data))) { int ret; ret = gatt_notify_mult_send(conn, buf); if (ret < 0) { return ret; } } if (!*buf) { *buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY_MULT, sizeof(*nfy) + params->len); if (!*buf) { BT_WARN("No buffer available to send notification"); return -ENOMEM; } /* Set user_data so it can be restored when sending */ nfy_mult_user_data(*buf)->func = params->func; nfy_mult_user_data(*buf)->user_data = params->user_data; } BT_DBG("handle 0x%04x len %u", handle, params->len); nfy = net_buf_add(*buf, sizeof(*nfy)); nfy->handle = sys_cpu_to_le16(handle); nfy->len = sys_cpu_to_le16(params->len); net_buf_add(*buf, params->len); memcpy(nfy->value, params->data, params->len); k_work_submit(&nfy_mult_work); return 0; } #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */ static int gatt_notify(struct bt_conn *conn, u16_t handle, struct bt_gatt_notify_params *params) { struct net_buf *buf; struct bt_att_notify *nfy; #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE) /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: * Except for the Handle Value indication, the server shall not send * notifications and indications to such a client until it becomes * change-aware. */ if (!bt_gatt_change_aware(conn, false)) { return -EAGAIN; } #endif #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE) if (gatt_cf_notify_multi(conn)) { return gatt_notify_mult(conn, handle, params); } #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */ buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY, sizeof(*nfy) + params->len); if (!buf) { BT_WARN("No buffer available to send notification"); return -ENOMEM; } BT_DBG("conn %p handle 0x%04x", conn, handle); nfy = net_buf_add(buf, sizeof(*nfy)); nfy->handle = sys_cpu_to_le16(handle); net_buf_add(buf, params->len); memcpy(nfy->value, params->data, params->len); return bt_att_send(conn, buf, params->func, params->user_data); } static void gatt_indicate_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_indicate_params *params = user_data; params->func(conn, params->attr, err); } static int gatt_send(struct bt_conn *conn, struct net_buf *buf, bt_att_func_t func, void *params, bt_att_destroy_t destroy) { int err; if (params) { struct bt_att_req *req; /* Allocate new request */ req = bt_att_req_alloc(BT_ATT_TIMEOUT); if (!req) { return -ENOMEM; } req->buf = buf; req->func = func; req->destroy = destroy; req->user_data = params; err = bt_att_req_send(conn, req); if (err) { bt_att_req_free(req); } } else { err = bt_att_send(conn, buf, NULL, NULL); } if (err) { BT_ERR("Error sending ATT PDU: %d", err); } return err; } static int gatt_indicate(struct bt_conn *conn, u16_t handle, struct bt_gatt_indicate_params *params) { struct net_buf *buf; struct bt_att_indicate *ind; #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE) /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: * Except for the Handle Value indication, the server shall not send * notifications and indications to such a client until it becomes * change-aware. */ if (!(params->func && (params->func == sc_indicate_rsp || params->func == sc_restore_rsp)) && !bt_gatt_change_aware(conn, false)) { return -EAGAIN; } #endif buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE, sizeof(*ind) + params->len); if (!buf) { BT_WARN("No buffer available to send indication"); return -ENOMEM; } BT_DBG("conn %p handle 0x%04x", conn, handle); ind = net_buf_add(buf, sizeof(*ind)); ind->handle = sys_cpu_to_le16(handle); net_buf_add(buf, params->len); memcpy(ind->value, params->data, params->len); if (!params->func) { return gatt_send(conn, buf, NULL, NULL, NULL); } return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL); } static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data) { struct notify_data *data = user_data; struct _bt_gatt_ccc *ccc; size_t i; /* Check attribute user_data must be of type struct _bt_gatt_ccc */ if (attr->write != bt_gatt_attr_write_ccc) { return BT_GATT_ITER_CONTINUE; } ccc = attr->user_data; /* Save Service Changed data if peer is not connected */ if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) { for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) { struct gatt_sc_cfg *cfg = &sc_cfg[i]; struct bt_conn *conn; if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { continue; } conn = bt_conn_lookup_state_le(cfg->id, &cfg->peer, BT_CONN_CONNECTED); if (!conn) { struct sc_data *sc; sc = (struct sc_data *)data->ind_params->data; sc_save(cfg->id, &cfg->peer, sys_le16_to_cpu(sc->start), sys_le16_to_cpu(sc->end)); continue; } bt_conn_unref(conn); } } /* Notify all peers configured */ for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; struct bt_conn *conn; int err; /* Check if config value matches data type since consolidated * value may be for a different peer. */ if (cfg->value != data->type) { continue; } conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer); if (!conn) { continue; } if (conn->state != BT_CONN_CONNECTED) { bt_conn_unref(conn); continue; } /* Confirm match if cfg is managed by application */ if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) { bt_conn_unref(conn); continue; } if (data->type == BT_GATT_CCC_INDICATE) { err = gatt_indicate(conn, attr->handle - 1, data->ind_params); } else { err = gatt_notify(conn, attr->handle - 1, data->nfy_params); } bt_conn_unref(conn); if (err < 0) { return BT_GATT_ITER_STOP; } data->err = 0; } return BT_GATT_ITER_CONTINUE; } static u8_t match_uuid(const struct bt_gatt_attr *attr, void *user_data) { const struct bt_gatt_attr **found = user_data; *found = attr; return BT_GATT_ITER_STOP; } int bt_gatt_notify_cb(struct bt_conn *conn, struct bt_gatt_notify_params *params) { struct notify_data data; const struct bt_gatt_attr *attr; u16_t handle; __ASSERT(params, "invalid parameters\n"); __ASSERT(params->attr, "invalid parameters\n"); if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } attr = params->attr; if (conn && conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } handle = attr->handle ? : find_static_attr(attr); if (!handle) { return -ENOENT; } /* Lookup UUID if it was given */ if (params->uuid) { attr = NULL; bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, NULL, 1, match_uuid, &attr); if (!attr) { return -ENOENT; } handle = attr->handle ? : find_static_attr(attr); if (!handle) { return -ENOENT; } } /* Check if attribute is a characteristic then adjust the handle */ if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { struct bt_gatt_chrc *chrc = attr->user_data; if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) { return -EINVAL; } handle = bt_gatt_attr_value_handle(attr); } if (conn) { return gatt_notify(conn, handle, params); } data.err = -ENOTCONN; data.type = BT_GATT_CCC_NOTIFY; data.nfy_params = params; bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data); return data.err; } #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE) int bt_gatt_notify_multiple(struct bt_conn *conn, u16_t num_params, struct bt_gatt_notify_params *params) { int i, ret; __ASSERT(params, "invalid parameters\n"); __ASSERT(num_params, "invalid parameters\n"); __ASSERT(params->attr, "invalid parameters\n"); for (i = 0; i < num_params; i++) { ret = bt_gatt_notify_cb(conn, &params[i]); if (ret < 0) { return ret; } } return 0; } #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */ int bt_gatt_indicate(struct bt_conn *conn, struct bt_gatt_indicate_params *params) { struct notify_data data; const struct bt_gatt_attr *attr; u16_t handle; __ASSERT(params, "invalid parameters\n"); __ASSERT(params->attr, "invalid parameters\n"); if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } attr = params->attr; if (conn && conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } handle = attr->handle ? : find_static_attr(attr); if (!handle) { return -ENOENT; } /* Lookup UUID if it was given */ if (params->uuid) { attr = NULL; bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, NULL, 1, match_uuid, &attr); if (!attr) { return -ENOENT; } handle = attr->handle ? : find_static_attr(attr); if (!handle) { return -ENOENT; } } /* Check if attribute is a characteristic then adjust the handle */ if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { struct bt_gatt_chrc *chrc = attr->user_data; if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) { return -EINVAL; } handle = bt_gatt_attr_value_handle(attr); } if (conn) { return gatt_indicate(conn, handle, params); } data.err = -ENOTCONN; data.type = BT_GATT_CCC_INDICATE; data.ind_params = params; bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data); return data.err; } u16_t bt_gatt_get_mtu(struct bt_conn *conn) { return bt_att_get_mtu(conn); } u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t mask) { if ((mask & BT_GATT_PERM_READ) && (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) { return BT_ATT_ERR_READ_NOT_PERMITTED; } if ((mask & BT_GATT_PERM_WRITE) && (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) { return BT_ATT_ERR_WRITE_NOT_PERMITTED; } mask &= attr->perm; if (mask & BT_GATT_PERM_AUTHEN_MASK) { if (bt_conn_get_security(conn) < BT_SECURITY_L3) { return BT_ATT_ERR_AUTHENTICATION; } } if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) { #if defined(CONFIG_BT_SMP) if (!conn->encrypt) { return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION; } #else return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION; #endif /* CONFIG_BT_SMP */ } return 0; } static void sc_restore_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) { #if defined(CONFIG_BT_GATT_CACHING) struct gatt_cf_cfg *cfg; #endif BT_DBG("err 0x%02x", err); #if defined(CONFIG_BT_GATT_CACHING) /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: * 2.5.2.1 Robust Caching * A connected client becomes change-aware when... * The client receives and confirms a Service Changed indication. */ cfg = find_cf_cfg(conn); if (cfg && CF_ROBUST_CACHING(cfg)) { atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); } #endif } static struct bt_gatt_indicate_params sc_restore_params[CONFIG_BT_MAX_CONN]; static void sc_restore(struct bt_conn *conn) { struct gatt_sc_cfg *cfg; u16_t sc_range[2]; u8_t index; cfg = find_sc_cfg(conn->id, &conn->le.dst); if (!cfg) { BT_DBG("no SC data found"); return; } if (!(cfg->data.start || cfg->data.end)) { return; } BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer), cfg->data.start, cfg->data.end); sc_range[0] = sys_cpu_to_le16(cfg->data.start); sc_range[1] = sys_cpu_to_le16(cfg->data.end); index = bt_conn_index(conn); sc_restore_params[index].attr = &_1_gatt_svc.attrs[2]; sc_restore_params[index].func = sc_restore_rsp; sc_restore_params[index].data = &sc_range[0]; sc_restore_params[index].len = sizeof(sc_range); if (bt_gatt_indicate(conn, &sc_restore_params[index])) { BT_ERR("SC restore indication failed"); } /* Reset config data */ sc_reset(cfg); } struct conn_data { struct bt_conn *conn; bt_security_t sec; }; static u8_t update_ccc(const struct bt_gatt_attr *attr, void *user_data) { struct conn_data *data = user_data; struct bt_conn *conn = data->conn; struct _bt_gatt_ccc *ccc; size_t i; u8_t err; /* Check attribute user_data must be of type struct _bt_gatt_ccc */ if (attr->write != bt_gatt_attr_write_ccc) { return BT_GATT_ITER_CONTINUE; } ccc = attr->user_data; for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; /* Ignore configuration for different peer or not active */ if (!cfg->value || !bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) { continue; } /* Check if attribute requires encryption/authentication */ err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK); if (err) { bt_security_t sec; if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) { BT_WARN("CCC %p not writable", attr); continue; } sec = BT_SECURITY_L2; if (err == BT_ATT_ERR_AUTHENTICATION) { sec = BT_SECURITY_L3; } /* Check if current security is enough */ if (IS_ENABLED(CONFIG_BT_SMP) && bt_conn_get_security(conn) < sec) { if (data->sec < sec) { data->sec = sec; } continue; } } gatt_ccc_changed(attr, ccc); if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) { sc_restore(conn); } return BT_GATT_ITER_CONTINUE; } return BT_GATT_ITER_CONTINUE; } static u8_t disconnected_cb(const struct bt_gatt_attr *attr, void *user_data) { struct bt_conn *conn = user_data; struct _bt_gatt_ccc *ccc; bool value_used; size_t i; /* Check attribute user_data must be of type struct _bt_gatt_ccc */ if (attr->write != bt_gatt_attr_write_ccc) { return BT_GATT_ITER_CONTINUE; } ccc = attr->user_data; /* If already disabled skip */ if (!ccc->value) { return BT_GATT_ITER_CONTINUE; } /* Checking if all values are disabled */ value_used = false; for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; /* Ignore configurations with disabled value */ if (!cfg->value) { continue; } if (!bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) { struct bt_conn *tmp; /* Skip if there is another peer connected */ tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer); if (tmp) { if (tmp->state == BT_CONN_CONNECTED) { value_used = true; } bt_conn_unref(tmp); } } else { /* Clear value if not paired */ if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { if (ccc == &sc_ccc) { sc_clear(conn); } clear_ccc_cfg(cfg); } else { /* Update address in case it has changed */ bt_addr_le_copy(&cfg->peer, &conn->le.dst); } } } /* If all values are now disabled, reset value while disconnected */ if (!value_used) { ccc->value = 0U; if (ccc->cfg_changed) { ccc->cfg_changed(attr, ccc->value); } BT_DBG("ccc %p reseted", ccc); } return BT_GATT_ITER_CONTINUE; } bool bt_gatt_is_subscribed(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t ccc_value) { const struct _bt_gatt_ccc *ccc; __ASSERT(conn, "invalid parameter\n"); __ASSERT(attr, "invalid parameter\n"); if (conn->state != BT_CONN_CONNECTED) { return false; } /* Check if attribute is a characteristic declaration */ if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { struct bt_gatt_chrc *chrc = attr->user_data; if (!(chrc->properties & (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) { /* Characteristic doesn't support subscription */ return false; } attr = bt_gatt_attr_next(attr); } /* Check if attribute is a characteristic value */ if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) { attr = bt_gatt_attr_next(attr); } /* Check if the attribute is the CCC Descriptor */ if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) { return false; } ccc = attr->user_data; /* Check if the connection is subscribed */ for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) { const struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; if (bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer) && (ccc_value & ccc->cfg[i].value)) { return true; } } return false; } static void gatt_sub_remove(struct bt_conn *conn, struct gatt_sub *sub, sys_snode_t *prev, struct bt_gatt_subscribe_params *params) { if (params) { /* Remove subscription from the list*/ sys_slist_remove(&sub->list, prev, &params->node); /* Notify removal */ params->notify(conn, params, NULL, 0); } if (sys_slist_is_empty(&sub->list)) { /* Reset address if there are no subscription left */ bt_addr_le_copy(&sub->peer, BT_ADDR_LE_ANY); } } #if defined(CONFIG_BT_GATT_CLIENT) static struct gatt_sub *gatt_sub_find_free(struct bt_conn *conn, struct gatt_sub **free_sub) { int i; if (free_sub) { *free_sub = NULL; } for (i = 0; i < ARRAY_SIZE(subscriptions); i++) { struct gatt_sub *sub = &subscriptions[i]; if (bt_conn_is_peer_addr_le(conn, sub->id, &sub->peer)) { return sub; } else if (free_sub && !bt_addr_le_cmp(BT_ADDR_LE_ANY, &sub->peer)) { *free_sub = sub; } } return NULL; } #define gatt_sub_find(_conn) \ gatt_sub_find_free(_conn, NULL) static struct gatt_sub *gatt_sub_add(struct bt_conn *conn) { struct gatt_sub *sub, *free_sub; sub = gatt_sub_find_free(conn, &free_sub); if (sub) { return sub; } if (free_sub) { bt_addr_le_copy(&free_sub->peer, &conn->le.dst); free_sub->id = conn->id; return free_sub; } return NULL; } __attribute__((weak)) void ble_stack_gatt_notify_cb(int16_t conn_handle, uint16_t attr_handle, const uint8_t *data, uint16_t len) { } void bt_gatt_notification(struct bt_conn *conn, u16_t handle, const void *data, u16_t length) { struct bt_gatt_subscribe_params *params, *tmp; struct gatt_sub *sub; BT_DBG("handle 0x%04x length %u", handle, length); ble_stack_gatt_notify_cb(bt_conn_index(conn), handle, data, length); sub = gatt_sub_find(conn); if (!sub) { return; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp, node) { if (handle != params->value_handle) { continue; } if (params->notify(conn, params, data, length) == BT_GATT_ITER_STOP) { bt_gatt_unsubscribe(conn, params); } } } void bt_gatt_mult_notification(struct bt_conn *conn, const void *data, u16_t length) { struct bt_gatt_subscribe_params *params, *tmp; const struct bt_att_notify_mult *nfy; struct net_buf_simple buf; struct gatt_sub *sub; BT_DBG("length %u", length); sub = gatt_sub_find(conn); if (!sub) { return; } /* This is fine since there no write operation to the buffer. */ net_buf_simple_init_with_data(&buf, (void *)data, length); while (buf.len > sizeof(*nfy)) { u16_t handle; u16_t len; nfy = net_buf_simple_pull_mem(&buf, sizeof(*nfy)); handle = sys_cpu_to_le16(nfy->handle); len = sys_cpu_to_le16(nfy->len); BT_DBG("handle 0x%02x len %u", handle, len); if (len > buf.len) { BT_ERR("Invalid data len %u > %u", len, length); return; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp, node) { if (handle != params->value_handle) { continue; } if (params->notify(conn, params, nfy->value, len) == BT_GATT_ITER_STOP) { bt_gatt_unsubscribe(conn, params); } } net_buf_simple_pull_mem(&buf, len); } } static void gatt_sub_update(struct bt_conn *conn, struct gatt_sub *sub) { if (sub->peer.type == BT_ADDR_LE_PUBLIC) { return; } /* Update address */ bt_addr_le_copy(&sub->peer, &conn->le.dst); } static void remove_subscriptions(struct bt_conn *conn) { struct gatt_sub *sub; struct bt_gatt_subscribe_params *params, *tmp; sys_snode_t *prev = NULL; sub = gatt_sub_find(conn); if (!sub) { return; } /* Lookup existing subscriptions */ SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp, node) { if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) || (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) { /* Remove subscription */ params->value = 0U; gatt_sub_remove(conn, sub, prev, params); } else { gatt_sub_update(conn, sub); prev = &params->node; } } } static void gatt_mtu_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_exchange_params *params = user_data; params->func(conn, err, params); } int bt_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params) { struct bt_att_exchange_mtu_req *req; struct net_buf *buf; u16_t mtu; __ASSERT(conn, "invalid parameter\n"); __ASSERT(params && params->func, "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } mtu = BT_ATT_MTU; BT_DBG("Client MTU %u", mtu); req = net_buf_add(buf, sizeof(*req)); req->mtu = sys_cpu_to_le16(mtu); return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL); } static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle, struct bt_gatt_discover_params *params) { /* Skip if last_handle is not set */ if (!last_handle) goto discover; /* Continue from the last found handle */ params->start_handle = last_handle; if (params->start_handle < UINT16_MAX) { params->start_handle++; } else { goto done; } /* Stop if over the range or the requests */ if (params->start_handle > params->end_handle) { goto done; } discover: /* Discover next range */ if (!bt_gatt_discover(conn, params)) { return; } done: params->func(conn, NULL, params); } static void gatt_find_type_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { const struct bt_att_find_type_rsp *rsp = pdu; struct bt_gatt_discover_params *params = user_data; u8_t i; u16_t end_handle = 0U, start_handle; BT_DBG("err 0x%02x", err); if (err) { goto done; } /* Parse attributes found */ for (i = 0U; length >= sizeof(rsp->list[i]); i++, length -= sizeof(rsp->list[i])) { struct bt_uuid_16 uuid_svc; struct bt_gatt_attr attr = {}; struct bt_gatt_service_val value; start_handle = sys_le16_to_cpu(rsp->list[i].start_handle); end_handle = sys_le16_to_cpu(rsp->list[i].end_handle); BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle); uuid_svc.uuid.type = BT_UUID_TYPE_16; if (params->type == BT_GATT_DISCOVER_PRIMARY) { uuid_svc.val = BT_UUID_16(BT_UUID_GATT_PRIMARY)->val; } else { uuid_svc.val = BT_UUID_16(BT_UUID_GATT_SECONDARY)->val; } value.end_handle = end_handle; value.uuid = params->uuid; attr.uuid = &uuid_svc.uuid; attr.handle = start_handle; attr.user_data = &value; if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) { return; } } /* Stop if could not parse the whole PDU */ if (length > 0) { goto done; } gatt_discover_next(conn, end_handle, params); return; done: params->func(conn, NULL, params); } static int gatt_find_type(struct bt_conn *conn, struct bt_gatt_discover_params *params) { u16_t uuid_val; struct net_buf *buf; struct bt_att_find_type_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->start_handle = sys_cpu_to_le16(params->start_handle); req->end_handle = sys_cpu_to_le16(params->end_handle); if (params->type == BT_GATT_DISCOVER_PRIMARY) { uuid_val = BT_UUID_16(BT_UUID_GATT_PRIMARY)->val; } else { uuid_val = BT_UUID_16(BT_UUID_GATT_SECONDARY)->val; } req->type = sys_cpu_to_le16(uuid_val); BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x", bt_uuid_str(params->uuid), params->start_handle, params->end_handle); switch (params->uuid->type) { case BT_UUID_TYPE_16: net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val); break; case BT_UUID_TYPE_128: net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16); break; default: BT_ERR("Unknown UUID type %u", params->uuid->type); net_buf_unref(buf); return -EINVAL; } return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL); } static void read_included_uuid_cb(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_discover_params *params = user_data; struct bt_gatt_include value; struct bt_gatt_attr *attr; union { struct bt_uuid uuid; struct bt_uuid_128 u128; } u; if (length != 16U) { BT_ERR("Invalid data len %u", length); params->func(conn, NULL, params); return; } value.start_handle = params->_included.start_handle; value.end_handle = params->_included.end_handle; value.uuid = &u.uuid; u.uuid.type = BT_UUID_TYPE_128; memcpy(u.u128.val, pdu, length); BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x " "end_handle 0x%04x\n", params->_included.attr_handle, bt_uuid_str(&u.uuid), value.start_handle, value.end_handle); /* Skip if UUID is set but doesn't match */ if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { goto next; } attr = (&(struct bt_gatt_attr) { .uuid = BT_UUID_GATT_INCLUDE, .user_data = &value, }); attr->handle = params->_included.attr_handle; if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { return; } next: gatt_discover_next(conn, params->start_handle, params); return; } static int read_included_uuid(struct bt_conn *conn, struct bt_gatt_discover_params *params) { struct net_buf *buf; struct bt_att_read_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->handle = sys_cpu_to_le16(params->_included.start_handle); BT_DBG("handle 0x%04x", params->_included.start_handle); return gatt_send(conn, buf, read_included_uuid_cb, params, NULL); } static u16_t parse_include(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) { const struct bt_att_read_type_rsp *rsp = pdu; u16_t handle = 0U; struct bt_gatt_include value; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_128 u128; } u; /* Data can be either in UUID16 or UUID128 */ switch (rsp->len) { case 8: /* UUID16 */ u.uuid.type = BT_UUID_TYPE_16; break; case 6: /* UUID128 */ /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550 * To get the included service UUID when the included service * uses a 128-bit UUID, the Read Request is used. */ u.uuid.type = BT_UUID_TYPE_128; break; default: BT_ERR("Invalid data len %u", rsp->len); goto done; } /* Parse include found */ for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { struct bt_gatt_attr *attr; const struct bt_att_data *data = pdu; struct gatt_incl *incl = (void *)data->value; handle = sys_le16_to_cpu(data->handle); /* Handle 0 is invalid */ if (!handle) { goto done; } /* Convert include data, bt_gatt_incl and gatt_incl * have different formats so the conversion have to be done * field by field. */ value.start_handle = sys_le16_to_cpu(incl->start_handle); value.end_handle = sys_le16_to_cpu(incl->end_handle); switch (u.uuid.type) { case BT_UUID_TYPE_16: value.uuid = &u.uuid; u.u16.val = sys_le16_to_cpu(incl->uuid16); break; case BT_UUID_TYPE_128: params->_included.attr_handle = handle; params->_included.start_handle = value.start_handle; params->_included.end_handle = value.end_handle; return read_included_uuid(conn, params); } BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x " "end_handle 0x%04x\n", handle, bt_uuid_str(&u.uuid), value.start_handle, value.end_handle); /* Skip if UUID is set but doesn't match */ if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { continue; } attr = (&(struct bt_gatt_attr) { .uuid = BT_UUID_GATT_INCLUDE, .user_data = &value, }); attr->handle = handle; if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { return 0; } } /* Whole PDU read without error */ if (length == 0U && handle) { return handle; } done: params->func(conn, NULL, params); return 0; } #define BT_GATT_CHRC(_uuid, _handle, _props) \ BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \ bt_gatt_attr_read_chrc, NULL, \ (&(struct bt_gatt_chrc) { .uuid = _uuid, \ .value_handle = _handle, \ .properties = _props, })) static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) { const struct bt_att_read_type_rsp *rsp = pdu; u16_t handle = 0U; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_128 u128; } u; /* Data can be either in UUID16 or UUID128 */ switch (rsp->len) { case 7: /* UUID16 */ u.uuid.type = BT_UUID_TYPE_16; break; case 21: /* UUID128 */ u.uuid.type = BT_UUID_TYPE_128; break; default: BT_ERR("Invalid data len %u", rsp->len); goto done; } /* Parse characteristics found */ for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { struct bt_gatt_attr *attr; const struct bt_att_data *data = pdu; struct gatt_chrc *chrc = (void *)data->value; handle = sys_le16_to_cpu(data->handle); /* Handle 0 is invalid */ if (!handle) { goto done; } switch (u.uuid.type) { case BT_UUID_TYPE_16: u.u16.val = sys_le16_to_cpu(chrc->uuid16); break; case BT_UUID_TYPE_128: memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid)); break; } BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle, bt_uuid_str(&u.uuid), chrc->properties); /* Skip if UUID is set but doesn't match */ if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { continue; } attr = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid, chrc->value_handle, chrc->properties)); attr->handle = handle; if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { return 0; } } /* Whole PDU read without error */ if (length == 0U && handle) { return handle; } done: params->func(conn, NULL, params); return 0; } static void gatt_read_type_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_discover_params *params = user_data; u16_t handle; BT_DBG("err 0x%02x", err); if (err) { params->func(conn, NULL, params); return; } if (params->type == BT_GATT_DISCOVER_INCLUDE) { handle = parse_include(conn, pdu, params, length); } else { handle = parse_characteristic(conn, pdu, params, length); } if (!handle) { return; } gatt_discover_next(conn, handle, params); } static int gatt_read_type(struct bt_conn *conn, struct bt_gatt_discover_params *params) { struct net_buf *buf; struct bt_att_read_type_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->start_handle = sys_cpu_to_le16(params->start_handle); req->end_handle = sys_cpu_to_le16(params->end_handle); if (params->type == BT_GATT_DISCOVER_INCLUDE) { net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val); } else { net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val); } BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle); return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL); } static u16_t parse_service(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) { const struct bt_att_read_group_rsp *rsp = pdu; u16_t start_handle, end_handle = 0U; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_128 u128; } u; /* Data can be either in UUID16 or UUID128 */ switch (rsp->len) { case 6: /* UUID16 */ u.uuid.type = BT_UUID_TYPE_16; break; case 20: /* UUID128 */ u.uuid.type = BT_UUID_TYPE_128; break; default: BT_ERR("Invalid data len %u", rsp->len); goto done; } /* Parse services found */ for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { struct bt_uuid_16 uuid_svc; struct bt_gatt_attr attr = {}; struct bt_gatt_service_val value; const struct bt_att_group_data *data = pdu; start_handle = sys_le16_to_cpu(data->start_handle); if (!start_handle) { goto done; } end_handle = sys_le16_to_cpu(data->end_handle); if (!end_handle || end_handle < start_handle) { goto done; } switch (u.uuid.type) { case BT_UUID_TYPE_16: memcpy(&u.u16.val, data->value, sizeof(u.u16.val)); u.u16.val = sys_le16_to_cpu(u.u16.val); break; case BT_UUID_TYPE_128: memcpy(u.u128.val, data->value, sizeof(u.u128.val)); break; } BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", start_handle, end_handle, bt_uuid_str(&u.uuid)); uuid_svc.uuid.type = BT_UUID_TYPE_16; if (params->type == BT_GATT_DISCOVER_PRIMARY) { uuid_svc.val = BT_UUID_16(BT_UUID_GATT_PRIMARY)->val; } else { uuid_svc.val = BT_UUID_16(BT_UUID_GATT_SECONDARY)->val; } value.end_handle = end_handle; value.uuid = &u.uuid; attr.uuid = &uuid_svc.uuid; attr.handle = start_handle; attr.user_data = &value; if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) { return 0; } } /* Whole PDU read without error */ if (length == 0U && end_handle) { return end_handle; } done: params->func(conn, NULL, params); return 0; } static void gatt_read_group_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_discover_params *params = user_data; u16_t handle; BT_DBG("err 0x%02x", err); if (err) { params->func(conn, NULL, params); return; } handle = parse_service(conn, pdu, params, length); if (!handle) { return; } gatt_discover_next(conn, handle, params); } static int gatt_read_group(struct bt_conn *conn, struct bt_gatt_discover_params *params) { struct net_buf *buf; struct bt_att_read_group_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->start_handle = sys_cpu_to_le16(params->start_handle); req->end_handle = sys_cpu_to_le16(params->end_handle); if (params->type == BT_GATT_DISCOVER_PRIMARY) { net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val); } else { net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val); } BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle); return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL); } static void gatt_find_info_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { const struct bt_att_find_info_rsp *rsp = pdu; struct bt_gatt_discover_params *params = user_data; u16_t handle = 0U; u16_t len; union { const struct bt_att_info_16 *i16; const struct bt_att_info_128 *i128; } info; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_128 u128; } u; int i; bool skip = false; BT_DBG("err 0x%02x", err); if (err) { goto done; } /* Data can be either in UUID16 or UUID128 */ switch (rsp->format) { case BT_ATT_INFO_16: u.uuid.type = BT_UUID_TYPE_16; len = sizeof(*info.i16); break; case BT_ATT_INFO_128: u.uuid.type = BT_UUID_TYPE_128; len = sizeof(*info.i128); break; default: BT_ERR("Invalid format %u", rsp->format); goto done; } length--; /* Check if there is a least one descriptor in the response */ if (length < len) { goto done; } /* Parse descriptors found */ for (i = length / len, pdu = rsp->info; i != 0; i--, pdu = (const u8_t *)pdu + len) { struct bt_gatt_attr *attr; info.i16 = pdu; handle = sys_le16_to_cpu(info.i16->handle); if (skip) { skip = false; continue; } switch (u.uuid.type) { case BT_UUID_TYPE_16: u.u16.val = sys_le16_to_cpu(info.i16->uuid); break; case BT_UUID_TYPE_128: memcpy(u.u128.val, info.i128->uuid, 16); break; } BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid)); /* Skip if UUID is set but doesn't match */ if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { continue; } if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) { /* Skip attributes that are not considered * descriptors. */ if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) { continue; } /* If Characteristic Declaration skip ahead as the next * entry must be its value. */ if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) { skip = true; continue; } } attr = (&(struct bt_gatt_attr) BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL)); attr->handle = handle; if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { return; } } gatt_discover_next(conn, handle, params); return; done: params->func(conn, NULL, params); } static int gatt_find_info(struct bt_conn *conn, struct bt_gatt_discover_params *params) { struct net_buf *buf; struct bt_att_find_info_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->start_handle = sys_cpu_to_le16(params->start_handle); req->end_handle = sys_cpu_to_le16(params->end_handle); BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle); return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL); } int bt_gatt_discover(struct bt_conn *conn, struct bt_gatt_discover_params *params) { __ASSERT(conn, "invalid parameters\n"); __ASSERT(params && params->func, "invalid parameters\n"); __ASSERT((params->start_handle && params->end_handle), "invalid parameters\n"); __ASSERT((params->start_handle <= params->end_handle), "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } switch (params->type) { case BT_GATT_DISCOVER_PRIMARY: case BT_GATT_DISCOVER_SECONDARY: if (params->uuid) { return gatt_find_type(conn, params); } return gatt_read_group(conn, params); case BT_GATT_DISCOVER_INCLUDE: case BT_GATT_DISCOVER_CHARACTERISTIC: return gatt_read_type(conn, params); case BT_GATT_DISCOVER_DESCRIPTOR: /* Only descriptors can be filtered */ if (params->uuid && (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) { return -EINVAL; } /* Fallthrough. */ case BT_GATT_DISCOVER_ATTRIBUTE: return gatt_find_info(conn, params); default: BT_ERR("Invalid discovery type: %u", params->type); } return -EINVAL; } static void parse_read_by_uuid(struct bt_conn *conn, struct bt_gatt_read_params *params, const void *pdu, u16_t length) { const struct bt_att_read_type_rsp *rsp = pdu; /* Parse values found */ for (length--, pdu = rsp->data; length >= 2 && length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { const struct bt_att_data *data = pdu; u16_t handle; u16_t len; handle = sys_le16_to_cpu(data->handle); /* Handle 0 is invalid */ if (!handle) { BT_ERR("Invalid handle"); return; } len = rsp->len > length ? length - 2 : rsp->len - 2; BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len); /* Update start_handle */ params->by_uuid.start_handle = handle; if (params->func(conn, 0, params, data->value, len) == BT_GATT_ITER_STOP) { return; } /* Check if long attribute */ if (rsp->len > length) { break; } /* Stop if it's the last handle to be read */ if (params->by_uuid.start_handle == params->by_uuid.end_handle) { params->func(conn, 0, params, NULL, 0); return; } params->by_uuid.start_handle++; } /* Continue reading the attributes */ if (bt_gatt_read(conn, params) < 0) { params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0); } } static void gatt_read_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_read_params *params = user_data; BT_DBG("err 0x%02x", err); if (err || !length) { params->func(conn, err, params, NULL, 0); return; } if (!params->handle_count) { parse_read_by_uuid(conn, params, pdu, length); return; } if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) { return; } /* * Core Spec 4.2, Vol. 3, Part G, 4.8.1 * If the Characteristic Value is greater than (ATT_MTU - 1) octets * in length, the Read Long Characteristic Value procedure may be used * if the rest of the Characteristic Value is required. */ if (length < (bt_att_get_mtu(conn) - 1)) { params->func(conn, 0, params, NULL, 0); return; } params->single.offset += length; /* Continue reading the attribute */ if (bt_gatt_read(conn, params) < 0) { params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0); } } static int gatt_read_blob(struct bt_conn *conn, struct bt_gatt_read_params *params) { struct net_buf *buf; struct bt_att_read_blob_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->handle = sys_cpu_to_le16(params->single.handle); req->offset = sys_cpu_to_le16(params->single.offset); BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle, params->single.offset); return gatt_send(conn, buf, gatt_read_rsp, params, NULL); } static int gatt_read_uuid(struct bt_conn *conn, struct bt_gatt_read_params *params) { struct net_buf *buf; struct bt_att_read_type_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle); req->end_handle = sys_cpu_to_le16(params->by_uuid.end_handle); if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) { net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val); } else { net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16); } BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", params->by_uuid.start_handle, params->by_uuid.end_handle, bt_uuid_str(params->by_uuid.uuid)); return gatt_send(conn, buf, gatt_read_rsp, params, NULL); } #if defined(CONFIG_BT_GATT_READ_MULTIPLE) static void gatt_read_mult_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_read_params *params = user_data; BT_DBG("err 0x%02x", err); if (err || !length) { params->func(conn, err, params, NULL, 0); return; } params->func(conn, 0, params, pdu, length); /* mark read as complete since read multiple is single response */ params->func(conn, 0, params, NULL, 0); } static int gatt_read_mult(struct bt_conn *conn, struct bt_gatt_read_params *params) { struct net_buf *buf; u8_t i; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ, params->handle_count * sizeof(u16_t)); if (!buf) { return -ENOMEM; } for (i = 0U; i < params->handle_count; i++) { net_buf_add_le16(buf, params->handles[i]); } return gatt_send(conn, buf, gatt_read_mult_rsp, params, NULL); } #if defined(CONFIG_BT_EATT) static void gatt_read_mult_vl_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_read_params *params = user_data; const struct bt_att_read_mult_vl_rsp *rsp; struct net_buf_simple buf; BT_DBG("err 0x%02x", err); if (err || !length) { if (err == BT_ATT_ERR_NOT_SUPPORTED) { gatt_read_mult(conn, params); } params->func(conn, err, params, NULL, 0); return; } net_buf_simple_init_with_data(&buf, (void *)pdu, length); while (buf.len >= sizeof(*rsp)) { u16_t len; rsp = net_buf_simple_pull_mem(&buf, sizeof(*rsp)); len = sys_le16_to_cpu(rsp->len); /* If a Length Value Tuple is truncated, then the amount of * Attribute Value will be less than the value of the Value * Length field. */ if (len > buf.len) { len = buf.len; } params->func(conn, 0, params, rsp->value, len); net_buf_simple_pull_mem(&buf, len); } /* mark read as complete since read multiple is single response */ params->func(conn, 0, params, NULL, 0); } static int gatt_read_mult_vl(struct bt_conn *conn, struct bt_gatt_read_params *params) { struct net_buf *buf; u8_t i; buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_VL_REQ, params->handle_count * sizeof(u16_t)); if (!buf) { return -ENOMEM; } for (i = 0U; i < params->handle_count; i++) { net_buf_add_le16(buf, params->handles[i]); } return gatt_send(conn, buf, gatt_read_mult_vl_rsp, params, NULL); } #endif /* CONFIG_BT_EATT */ #else static int gatt_read_mult(struct bt_conn *conn, struct bt_gatt_read_params *params) { return -ENOTSUP; } static int gatt_read_mult_vl(struct bt_conn *conn, struct bt_gatt_read_params *params) { return -ENOTSUP; } #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params) { struct net_buf *buf; struct bt_att_read_req *req; __ASSERT(conn, "invalid parameters\n"); __ASSERT(params && params->func, "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (params->handle_count == 0) { return gatt_read_uuid(conn, params); } if (params->handle_count > 1) { #if defined(CONFIG_BT_EATT) return gatt_read_mult_vl(conn, params); #else return gatt_read_mult(conn, params); #endif /* CONFIG_BT_EATT */ } if (params->single.offset) { return gatt_read_blob(conn, params); } buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->handle = sys_cpu_to_le16(params->single.handle); BT_DBG("handle 0x%04x", params->single.handle); return gatt_send(conn, buf, gatt_read_rsp, params, NULL); } static void gatt_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_write_params *params = user_data; BT_DBG("err 0x%02x", err); params->func(conn, err, params); } int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, const void *data, u16_t length, bool sign, bt_gatt_complete_func_t func, void *user_data) { struct net_buf *buf; struct bt_att_write_cmd *cmd; size_t write; __ASSERT(conn, "invalid parameters\n"); __ASSERT(handle, "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } #if defined(CONFIG_BT_SMP) if (conn->encrypt) { /* Don't need to sign if already encrypted */ sign = false; } #endif if (sign) { buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD, sizeof(*cmd) + length + 12); } else { buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD, sizeof(*cmd) + length); } if (!buf) { return -ENOMEM; } cmd = net_buf_add(buf, sizeof(*cmd)); cmd->handle = sys_cpu_to_le16(handle); write = net_buf_append_bytes(buf, length, data, K_NO_WAIT, NULL, NULL); if (write != length) { BT_WARN("Unable to allocate length %u: only %zu written", length, write); net_buf_unref(buf); return -ENOMEM; } BT_DBG("handle 0x%04x length %u", handle, length); return bt_att_send(conn, buf, func, user_data); } static int gatt_exec_write(struct bt_conn *conn, struct bt_gatt_write_params *params) { struct net_buf *buf; struct bt_att_exec_write_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->flags = BT_ATT_FLAG_EXEC; BT_DBG(""); return gatt_send(conn, buf, gatt_write_rsp, params, NULL); } static void gatt_prepare_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_write_params *params = user_data; BT_DBG("err 0x%02x", err); /* Don't continue in case of error */ if (err) { params->func(conn, err, params); return; } /* If there is no more data execute */ if (!params->length) { gatt_exec_write(conn, params); return; } /* Write next chunk */ bt_gatt_write(conn, params); } static int gatt_prepare_write(struct bt_conn *conn, struct bt_gatt_write_params *params) { struct net_buf *buf; struct bt_att_prepare_write_req *req; u16_t len; size_t write; len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1); buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(*req) + len); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->handle = sys_cpu_to_le16(params->handle); req->offset = sys_cpu_to_le16(params->offset); /* Append as much as possible */ write = net_buf_append_bytes(buf, len, params->data, K_NO_WAIT, NULL, NULL); /* Update params */ params->offset += write; params->data = (const u8_t *)params->data + len; params->length -= write; BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset, params->length); return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL); } int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params) { struct net_buf *buf; struct bt_att_write_req *req; size_t write; __ASSERT(conn, "invalid parameters\n"); __ASSERT(params && params->func, "invalid parameters\n"); __ASSERT(params->handle, "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } /* Use Prepare Write if offset is set or Long Write is required */ if (params->offset || params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) { return gatt_prepare_write(conn, params); } buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + params->length); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->handle = sys_cpu_to_le16(params->handle); write = net_buf_append_bytes(buf, params->length, params->data, K_NO_WAIT, NULL, NULL); if (write != params->length) { net_buf_unref(buf); return -ENOMEM; } BT_DBG("handle 0x%04x length %u", params->handle, params->length); return gatt_send(conn, buf, gatt_write_rsp, params, NULL); } static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) { struct bt_gatt_subscribe_params *params = user_data; BT_DBG("err 0x%02x", err); atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING); /* if write to CCC failed we remove subscription and notify app */ if (err) { struct gatt_sub *sub; sys_snode_t *node, *tmp, *prev = NULL; sub = gatt_sub_find(conn); if (!sub) { return; } SYS_SLIST_FOR_EACH_NODE_SAFE(&sub->list, node, tmp) { if (node == &params->node) { gatt_sub_remove(conn, sub, tmp, params); break; } prev = node; } (void)prev; } else if (!params->value) { /* Notify with NULL data to complete unsubscribe */ params->notify(conn, params, NULL, 0); } } static int gatt_write_ccc(struct bt_conn *conn, u16_t handle, u16_t value, bt_att_func_t func, struct bt_gatt_subscribe_params *params) { struct net_buf *buf; struct bt_att_write_req *req; buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + sizeof(u16_t)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->handle = sys_cpu_to_le16(handle); net_buf_add_le16(buf, value); BT_DBG("handle 0x%04x value 0x%04x", handle, value); atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING); return gatt_send(conn, buf, func, params, NULL); } int bt_gatt_subscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) { struct gatt_sub *sub; struct bt_gatt_subscribe_params *tmp; bool has_subscription = false; __ASSERT(conn, "invalid parameters\n"); __ASSERT(params && params->notify, "invalid parameters\n"); __ASSERT(params->value, "invalid parameters\n"); __ASSERT(params->ccc_handle, "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } sub = gatt_sub_add(conn); if (!sub) { return -ENOMEM; } /* Lookup existing subscriptions */ SYS_SLIST_FOR_EACH_CONTAINER(&sub->list, tmp, node) { /* Fail if entry already exists */ if (tmp == params) { gatt_sub_remove(conn, sub, NULL, NULL); return -EALREADY; } /* Check if another subscription exists */ if (tmp->value_handle == params->value_handle && tmp->value >= params->value) { has_subscription = true; } } /* Skip write if already subscribed */ if (!has_subscription) { int err; err = gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params); if (err) { gatt_sub_remove(conn, sub, NULL, NULL); return err; } } /* * Add subscription before write complete as some implementation were * reported to send notification before reply to CCC write. */ sys_slist_prepend(&sub->list, &params->node); return 0; } int bt_gatt_unsubscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) { struct gatt_sub *sub; struct bt_gatt_subscribe_params *tmp, *next; bool has_subscription = false, found = false; sys_snode_t *prev = NULL; __ASSERT(conn, "invalid parameters\n"); __ASSERT(params, "invalid parameters\n"); if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } sub = gatt_sub_find(conn); if (!sub) { return -EINVAL; } /* Lookup existing subscriptions */ SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, tmp, next, node) { /* Remove subscription */ if (params == tmp) { found = true; sys_slist_remove(&sub->list, prev, &tmp->node); /* Attempt to cancel if write is pending */ if (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) { bt_gatt_cancel(conn, params); } continue; } else { prev = &tmp->node; } /* Check if there still remains any other subscription */ if (tmp->value_handle == params->value_handle) { has_subscription = true; } } if (!found) { return -EINVAL; } if (has_subscription) { /* Notify with NULL data to complete unsubscribe */ params->notify(conn, params, NULL, 0); return 0; } params->value = 0x0000; return gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params); } void bt_gatt_cancel(struct bt_conn *conn, void *params) { bt_att_req_cancel(conn, params); } static void add_subscriptions(struct bt_conn *conn) { struct gatt_sub *sub; struct bt_gatt_subscribe_params *params; sub = gatt_sub_find(conn); if (!sub) { return; } /* Lookup existing subscriptions */ SYS_SLIST_FOR_EACH_CONTAINER(&sub->list, params, node) { if (bt_addr_le_is_bonded(conn->id, &conn->le.dst) && !atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_NO_RESUB)) { /* Force write to CCC to workaround devices that don't * track it properly. */ gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params); } } } #endif /* CONFIG_BT_GATT_CLIENT */ #define CCC_STORE_MAX 48 static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc, const bt_addr_le_t *addr, u8_t id) { for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { if (id == ccc->cfg[i].id && !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) { return &ccc->cfg[i]; } } return NULL; } struct addr_with_id { const bt_addr_le_t *addr; u8_t id; }; struct ccc_load { struct addr_with_id addr_with_id; struct ccc_store *entry; size_t count; }; static void ccc_clear(struct _bt_gatt_ccc *ccc, const bt_addr_le_t *addr, u8_t id) { struct bt_gatt_ccc_cfg *cfg; cfg = ccc_find_cfg(ccc, addr, id); if (!cfg) { BT_DBG("Unable to clear CCC: cfg not found"); return; } clear_ccc_cfg(cfg); } static u8_t ccc_load(const struct bt_gatt_attr *attr, void *user_data) { struct ccc_load *load = user_data; struct _bt_gatt_ccc *ccc; struct bt_gatt_ccc_cfg *cfg; /* Check if attribute is a CCC */ if (attr->write != bt_gatt_attr_write_ccc) { return BT_GATT_ITER_CONTINUE; } ccc = attr->user_data; /* Clear if value was invalidated */ if (!load->entry) { ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id); return BT_GATT_ITER_CONTINUE; } else if (!load->count) { return BT_GATT_ITER_STOP; } /* Skip if value is not for the given attribute */ if (load->entry->handle != attr->handle) { /* If attribute handle is bigger then it means * the attribute no longer exists and cannot * be restored. */ if (load->entry->handle < attr->handle) { BT_DBG("Unable to restore CCC: handle 0x%04x cannot be" " found", load->entry->handle); goto next; } return BT_GATT_ITER_CONTINUE; } BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle, load->entry->value); cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id); if (!cfg) { cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0); if (!cfg) { BT_DBG("Unable to restore CCC: no cfg left"); goto next; } bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr); cfg->id = load->addr_with_id.id; } cfg->value = load->entry->value; next: load->entry++; load->count--; return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP; } static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) { if (IS_ENABLED(CONFIG_BT_SETTINGS)) { struct ccc_store ccc_store[CCC_STORE_MAX]; struct ccc_load load; bt_addr_le_t addr; ssize_t len; int err; const char *next; settings_name_next(name, &next); if (!name) { BT_ERR("Insufficient number of arguments"); return -EINVAL; } else if (!next) { load.addr_with_id.id = BT_ID_DEFAULT; } else { load.addr_with_id.id = strtol(next, NULL, 10); } err = bt_settings_decode_key(name, &addr); if (err) { BT_ERR("Unable to decode address %s", log_strdup(name)); return -EINVAL; } load.addr_with_id.addr = &addr; if (len_rd) { len = read_cb(cb_arg, ccc_store, sizeof(ccc_store)); if (len < 0) { BT_ERR("Failed to decode value (err %zd)", len); return len; } load.entry = ccc_store; load.count = len / sizeof(*ccc_store); for (size_t i = 0; i < load.count; i++) { BT_DBG("Read CCC: handle 0x%04x value 0x%04x", ccc_store[i].handle, ccc_store[i].value); } } else { load.entry = NULL; load.count = 0; } bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load); BT_DBG("Restored CCC for id:%d addr:%s", load.addr_with_id.id, bt_addr_le_str(load.addr_with_id.addr)); } return 0; } #if !IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) /* Only register the ccc_set settings handler when not loading on-demand */ //SETTINGS_STATIC_HANDLER_DEFINE(bt_ccc, "bt/ccc", NULL, ccc_set, NULL, NULL); #endif /* CONFIG_BT_SETTINGS_CCC_LAZY_LOADING */ static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb, void *cb_arg, void *param) { if (IS_ENABLED(CONFIG_BT_SETTINGS)) { const char *name; BT_DBG("key: %s", log_strdup((const char *)param)); /* Only "bt/ccc" settings should ever come here */ if (!settings_name_steq((const char *)param, "bt/ccc", &name)) { BT_ERR("Invalid key"); return -EINVAL; } return ccc_set(name, len, read_cb, cb_arg); } return 0; } void bt_gatt_connected(struct bt_conn *conn) { struct conn_data data; BT_DBG("conn %p", conn); data.conn = conn; data.sec = BT_SECURITY_L1; /* Load CCC settings from backend if bonded */ if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { char key[BT_SETTINGS_KEY_MAX]; if (conn->id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), conn->id); bt_settings_encode_key(key, sizeof(key), "ccc", &conn->le.dst, id_str); } else { bt_settings_encode_key(key, sizeof(key), "ccc", &conn->le.dst, NULL); } settings_load_subtree_direct(key, ccc_set_direct, (void *)key); } bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data); /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192: * * 10.3.1.1 Handling of GATT indications and notifications * * A client "requests" a server to send indications and notifications * by appropriately configuring the server via a Client Characteristic * Configuration Descriptor. Since the configuration is persistent * across a disconnection and reconnection, security requirements must * be checked against the configuration upon a reconnection before * sending indications or notifications. When a server reconnects to a * client to send an indication or notification for which security is * required, the server shall initiate or request encryption with the * client prior to sending an indication or notification. If the client * does not have an LTK indicating that the client has lost the bond, * enabling encryption will fail. */ if (IS_ENABLED(CONFIG_BT_SMP) && bt_conn_get_security(conn) < data.sec) { bt_conn_set_security(conn, data.sec); } #if defined(CONFIG_BT_GATT_CLIENT) add_subscriptions(conn); #endif /* CONFIG_BT_GATT_CLIENT */ } void bt_gatt_encrypt_change(struct bt_conn *conn) { struct conn_data data; BT_DBG("conn %p", conn); data.conn = conn; data.sec = BT_SECURITY_L1; bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data); } bool bt_gatt_change_aware(struct bt_conn *conn, bool req) { #if defined(CONFIG_BT_GATT_CACHING) struct gatt_cf_cfg *cfg; cfg = find_cf_cfg(conn); if (!cfg || !CF_ROBUST_CACHING(cfg)) { return true; } if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) { return true; } /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: * If a change-unaware client sends an ATT command, the server shall * ignore it. */ if (!req) { return false; } /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: * 2.5.2.1 Robust Caching * A connected client becomes change-aware when... * The server sends the client a response with the error code set to * Database Out Of Sync and then the server receives another ATT * request from the client. */ if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) { atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); return true; } atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC); return false; #else return true; #endif } static int bt_gatt_store_cf(struct bt_conn *conn) { #if defined(CONFIG_BT_GATT_CACHING) struct gatt_cf_cfg *cfg; char key[BT_SETTINGS_KEY_MAX]; char *str; size_t len; int err; cfg = find_cf_cfg(conn); if (!cfg) { /* No cfg found, just clear it */ BT_DBG("No config for CF"); str = NULL; len = 0; } else { str = (char *)cfg->data; len = sizeof(cfg->data); if (conn->id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), conn->id); bt_settings_encode_key(key, sizeof(key), "cf", &conn->le.dst, id_str); } } if (!cfg || !conn->id) { bt_settings_encode_key(key, sizeof(key), "cf", &conn->le.dst, NULL); } err = settings_save_one(key, str, len); if (err) { BT_ERR("Failed to store Client Features (err %d)", err); return err; } BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key)); #endif /* CONFIG_BT_GATT_CACHING */ return 0; } void bt_gatt_disconnected(struct bt_conn *conn) { BT_DBG("conn %p", conn); bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn); #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) gatt_ccc_conn_unqueue(conn); if (gatt_ccc_conn_queue_is_empty()) { k_delayed_work_cancel(&gatt_ccc_store.work); } #endif if (IS_ENABLED(CONFIG_BT_SETTINGS) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { bt_gatt_store_ccc(conn->id, &conn->le.dst); bt_gatt_store_cf(conn); } #if defined(CONFIG_BT_GATT_CLIENT) remove_subscriptions(conn); #endif /* CONFIG_BT_GATT_CLIENT */ #if defined(CONFIG_BT_GATT_CACHING) remove_cf_cfg(conn); #endif } static struct gatt_cf_cfg *find_cf_cfg_by_addr(u8_t id, const bt_addr_le_t *addr) { if (IS_ENABLED(CONFIG_BT_GATT_CACHING)) { int i; for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { if (id == cf_cfg[i].id && !bt_addr_le_cmp(addr, &cf_cfg[i].peer)) { return &cf_cfg[i]; } } } return NULL; } #if defined(CONFIG_BT_SETTINGS) struct ccc_save { struct addr_with_id addr_with_id; struct ccc_store store[CCC_STORE_MAX]; size_t count; }; static u8_t ccc_save(const struct bt_gatt_attr *attr, void *user_data) { struct ccc_save *save = user_data; struct _bt_gatt_ccc *ccc; struct bt_gatt_ccc_cfg *cfg; /* Check if attribute is a CCC */ if (attr->write != bt_gatt_attr_write_ccc) { return BT_GATT_ITER_CONTINUE; } ccc = attr->user_data; /* Check if there is a cfg for the peer */ cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id); if (!cfg) { return BT_GATT_ITER_CONTINUE; } BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle, cfg->value); save->store[save->count].handle = attr->handle; save->store[save->count].value = cfg->value; save->count++; return BT_GATT_ITER_CONTINUE; } int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr) { struct ccc_save save; char key[BT_SETTINGS_KEY_MAX]; size_t len; char *str; int err; save.addr_with_id.addr = addr; save.addr_with_id.id = id; save.count = 0; bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save); if (id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), id); bt_settings_encode_key(key, sizeof(key), "ccc", addr, id_str); } else { bt_settings_encode_key(key, sizeof(key), "ccc", addr, NULL); } if (save.count) { str = (char *)save.store; len = save.count * sizeof(*save.store); } else { /* No entries to encode, just clear */ str = NULL; len = 0; } err = settings_save_one(key, str, len); if (err) { BT_ERR("Failed to store CCCs (err %d)", err); return err; } BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr), log_strdup(key)); if (len) { for (size_t i = 0; i < save.count; i++) { BT_DBG(" CCC: handle 0x%04x value 0x%04x", save.store[i].handle, save.store[i].value); } } else { BT_DBG(" CCC: NULL"); } return 0; } #if defined(CONFIG_BT_GATT_SERVICE_CHANGED) static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) { struct gatt_sc_cfg *cfg; u8_t id; bt_addr_le_t addr; ssize_t len; int err; const char *next; if (!name) { BT_ERR("Insufficient number of arguments"); return -EINVAL; } err = bt_settings_decode_key(name, &addr); if (err) { BT_ERR("Unable to decode address %s", log_strdup(name)); return -EINVAL; } settings_name_next(name, &next); if (!next) { id = BT_ID_DEFAULT; } else { id = strtol(next, NULL, 10); } cfg = find_sc_cfg(id, &addr); if (!cfg && len_rd) { /* Find and initialize a free sc_cfg entry */ cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); if (!cfg) { BT_ERR("Unable to restore SC: no cfg left"); return -ENOMEM; } cfg->id = id; bt_addr_le_copy(&cfg->peer, &addr); } if (len_rd) { len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data)); if (len < 0) { BT_ERR("Failed to decode value (err %zd)", len); return len; } BT_DBG("Read SC: len %zd", len); BT_DBG("Restored SC for %s", bt_addr_le_str(&addr)); } else if (cfg) { /* Clear configuration */ memset(cfg, 0, sizeof(*cfg)); BT_DBG("Removed SC for %s", bt_addr_le_str(&addr)); } return 0; } static int sc_commit(void) { atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING); if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { /* Schedule SC indication since the range has changed */ k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT); } return 0; } //SETTINGS_STATIC_HANDLER_DEFINE(bt_sc, "bt/sc", NULL, sc_set, sc_commit, NULL); #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */ #if defined(CONFIG_BT_GATT_CACHING) static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) { struct gatt_cf_cfg *cfg; bt_addr_le_t addr; const char *next; ssize_t len; int err; u8_t id; if (!name) { BT_ERR("Insufficient number of arguments"); return -EINVAL; } err = bt_settings_decode_key(name, &addr); if (err) { BT_ERR("Unable to decode address %s", log_strdup(name)); return -EINVAL; } settings_name_next(name, &next); if (!next) { id = BT_ID_DEFAULT; } else { id = strtol(next, NULL, 10); } cfg = find_cf_cfg_by_addr(id, &addr); if (!cfg) { cfg = find_cf_cfg(NULL); if (!cfg) { BT_ERR("Unable to restore CF: no cfg left"); return -ENOMEM; } cfg->id = id; bt_addr_le_copy(&cfg->peer, &addr); } if (len_rd) { len = read_cb(cb_arg, cfg->data, sizeof(cfg->data)); if (len < 0) { BT_ERR("Failed to decode value (err %zd)", len); return len; } BT_DBG("Read CF: len %zd", len); } else { clear_cf_cfg(cfg); } BT_DBG("Restored CF for %s", bt_addr_le_str(&addr)); return 0; } //SETTINGS_STATIC_HANDLER_DEFINE(bt_cf, "bt/cf", NULL, cf_set, NULL, NULL); static u8_t stored_hash[16]; static int db_hash_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) { ssize_t len; len = read_cb(cb_arg, stored_hash, sizeof(stored_hash)); if (len < 0) { BT_ERR("Failed to decode value (err %zd)", len); return len; } BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: "); return 0; } static int db_hash_commit(void) { int err; /* Stop work and generate the hash */ err = k_delayed_work_cancel(&db_hash_work); if (!err) { db_hash_gen(false); } /* Check if hash matches then skip SC update */ if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) { BT_DBG("Database Hash matches"); k_delayed_work_cancel(&gatt_sc.work); atomic_clear_bit(gatt_sc.flags, SC_RANGE_CHANGED); return 0; } BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: "); /** * GATT database has been modified since last boot, likely due to * a firmware update or a dynamic service that was not re-registered on * boot. Indicate Service Changed to all bonded devices for the full * database range to invalidate client-side cache and force discovery on * reconnect. */ sc_indicate(0x0001, 0xffff); /* Hash did not match overwrite with current hash */ db_hash_store(); return 0; } //SETTINGS_STATIC_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set, /// db_hash_commit, NULL); #endif /*CONFIG_BT_GATT_CACHING */ int bt_gatt_settings_init() { #if !IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) /* Only register the ccc_set settings handler when not loading on-demand */ SETTINGS_HANDLER_DEFINE(bt_ccc, "bt/ccc", NULL, ccc_set, NULL, NULL); #endif /* CONFIG_BT_SETTINGS_CCC_LAZY_LOADING */ #if defined(CONFIG_BT_GATT_SERVICE_CHANGED) SETTINGS_HANDLER_DEFINE(bt_sc, "bt/sc", NULL, sc_set, sc_commit, NULL); #endif #if defined(CONFIG_BT_GATT_CACHING) SETTINGS_HANDLER_DEFINE(bt_cf, "bt/cf", NULL, cf_set, NULL, NULL); SETTINGS_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set, db_hash_commit, NULL); #endif return 0; } #endif /* CONFIG_BT_SETTINGS */ static u8_t remove_peer_from_attr(const struct bt_gatt_attr *attr, void *user_data) { const struct addr_with_id *addr_with_id = user_data; struct _bt_gatt_ccc *ccc; struct bt_gatt_ccc_cfg *cfg; /* Check if attribute is a CCC */ if (attr->write != bt_gatt_attr_write_ccc) { return BT_GATT_ITER_CONTINUE; } ccc = attr->user_data; /* Check if there is a cfg for the peer */ cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id); if (cfg) { memset(cfg, 0, sizeof(*cfg)); } return BT_GATT_ITER_CONTINUE; } static int bt_gatt_clear_ccc(u8_t id, const bt_addr_le_t *addr) { struct addr_with_id addr_with_id = { .addr = addr, .id = id, }; bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr, &addr_with_id); if (IS_ENABLED(CONFIG_BT_SETTINGS)) { char key[BT_SETTINGS_KEY_MAX]; if (id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), id); bt_settings_encode_key(key, sizeof(key), "ccc", addr, id_str); } else { bt_settings_encode_key(key, sizeof(key), "ccc", addr, NULL); } return settings_delete(key); } return 0; } static int bt_gatt_clear_cf(u8_t id, const bt_addr_le_t *addr) { struct gatt_cf_cfg *cfg; cfg = find_cf_cfg_by_addr(id, addr); if (cfg) { clear_cf_cfg(cfg); } if (IS_ENABLED(CONFIG_BT_SETTINGS)) { char key[BT_SETTINGS_KEY_MAX]; if (id) { char id_str[4]; u8_to_dec(id_str, sizeof(id_str), id); bt_settings_encode_key(key, sizeof(key), "cf", addr, id_str); } else { bt_settings_encode_key(key, sizeof(key), "cf", addr, NULL); } return settings_delete(key); } return 0; } static struct gatt_sub *find_gatt_sub(u8_t id, const bt_addr_le_t *addr) { for (int i = 0; i < ARRAY_SIZE(subscriptions); i++) { struct gatt_sub *sub = &subscriptions[i]; if (id == sub->id && !bt_addr_le_cmp(addr, &sub->peer)) { return sub; } } return NULL; } static void bt_gatt_clear_subscriptions(u8_t id, const bt_addr_le_t *addr) { struct gatt_sub *sub; struct bt_gatt_subscribe_params *params, *tmp; sys_snode_t *prev = NULL; sub = find_gatt_sub(id, addr); if (!sub) { return; } SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp, node) { params->value = 0U; gatt_sub_remove(NULL, sub, prev, params); } } int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr) { int err; err = bt_gatt_clear_ccc(id, addr); if (err < 0) { return err; } if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) { err = bt_gatt_clear_sc(id, addr); if (err < 0) { return err; } } if (IS_ENABLED(CONFIG_BT_GATT_CACHING)) { err = bt_gatt_clear_cf(id, addr); if (err < 0) { return err; } } if (IS_ENABLED(CONFIG_BT_GATT_CLIENT)) { bt_gatt_clear_subscriptions(id, addr); } return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/gatt.c
C
apache-2.0
118,161
/** @file * @brief Internal API for Generic Attribute Profile handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #define BT_GATT_CENTRAL_ADDR_RES_NOT_SUPP 0 #define BT_GATT_CENTRAL_ADDR_RES_SUPP 1 #define BT_GATT_PERM_READ_MASK (BT_GATT_PERM_READ | \ BT_GATT_PERM_READ_ENCRYPT | \ BT_GATT_PERM_READ_AUTHEN) #define BT_GATT_PERM_WRITE_MASK (BT_GATT_PERM_WRITE | \ BT_GATT_PERM_WRITE_ENCRYPT | \ BT_GATT_PERM_WRITE_AUTHEN) #define BT_GATT_PERM_ENCRYPT_MASK (BT_GATT_PERM_READ_ENCRYPT | \ BT_GATT_PERM_WRITE_ENCRYPT) #define BT_GATT_PERM_AUTHEN_MASK (BT_GATT_PERM_READ_AUTHEN | \ BT_GATT_PERM_WRITE_AUTHEN) void bt_gatt_init(void); void bt_gatt_connected(struct bt_conn *conn); void bt_gatt_encrypt_change(struct bt_conn *conn); void bt_gatt_disconnected(struct bt_conn *conn); bool bt_gatt_change_aware(struct bt_conn *conn, bool req); int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr); int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr); #if defined(CONFIG_BT_GATT_CLIENT) void bt_gatt_notification(struct bt_conn *conn, u16_t handle, const void *data, u16_t length); void bt_gatt_mult_notification(struct bt_conn *conn, const void *data, u16_t length); #else static inline void bt_gatt_notification(struct bt_conn *conn, u16_t handle, const void *data, u16_t length) { } static inline void bt_gatt_mult_notification(struct bt_conn *conn, const void *data, u16_t length) { } #endif /* CONFIG_BT_GATT_CLIENT */ struct bt_gatt_attr; /* Check attribute permission */ u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t mask);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/gatt_internal.h
C
apache-2.0
1,710
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ble_os.h> #include <string.h> #include <stdio.h> #include <bt_errno.h> #include <atomic.h> #include <misc/util.h> #include <misc/slist.h> #include <misc/byteorder.h> #include <misc/stack.h> #include <misc/__assert.h> #include <settings/settings.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/l2cap.h> #include <bluetooth/hci.h> #include <bluetooth/hci_vs.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE) #include "common/log.h" #include "common/rpa.h" #include "keys.h" #include "monitor.h" #include "hci_core.h" #include "hci_ecc.h" #include "ecc.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "gatt_internal.h" #include "smp.h" #include "bluetooth/crypto.h" #include "settings.h" //#include "soc.h" //only for phy6220 #include "hci_api.h" #if defined(CONFIG_BT_USE_HCI_API) #define __hci_api_weak__ __attribute__((weak)) struct hci_debug_counter_t g_hci_debug_counter = {0}; struct cmd_state_set { atomic_t *target; int bit; bool val; }; struct cmd_data { /** HCI status of the command completion */ u8_t status; /** The command OpCode that the buffer contains */ u16_t opcode; /** The state to update when command completes with success. */ struct cmd_state_set *state; /** Used by bt_hci_cmd_send_sync. */ struct k_sem *sync; }; extern void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit, bool val); static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT]; #define cmd(buf) (&cmd_data[net_buf_id(buf)]) #define HCI_CMD_TIMEOUT K_SECONDS(10) /* HCI command buffers. Derive the needed size from BT_BUF_RX_SIZE since * the same buffer is also used for the response. */ #define CMD_BUF_SIZE BT_BUF_RX_SIZE NET_BUF_POOL_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, BT_BUF_USER_DATA_MIN, NULL); /* Number of commands controller can accept */ static struct k_sem ncmd_sem; /* Last sent HCI command */ static struct net_buf *sent_cmd; /* Queue for outgoing HCI commands */ static struct kfifo cmd_tx_queue; static inline void handle_event(u8_t event, struct net_buf *buf, const struct event_handler *handlers, size_t num_handlers) { size_t i; for (i = 0; i < num_handlers; i++) { const struct event_handler *handler = &handlers[i]; if (handler->event != event) { continue; } if (buf->len < handler->min_len) { BT_ERR("Too small (%u bytes) event 0x%02x", buf->len, event); return; } handler->handler(buf); return; } BT_WARN("Unhandled event 0x%02x len %u: %s", event, buf->len, bt_hex(buf->data, buf->len)); } void hci_num_completed_packets(struct net_buf *buf) { struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data; int i; BT_DBG("num_handles %u", evt->num_handles); for (i = 0; i < evt->num_handles; i++) { u16_t handle, count; handle = sys_le16_to_cpu(evt->h[i].handle); count = sys_le16_to_cpu(evt->h[i].count); hci_api_num_complete_packets(1, &handle, &count); } } struct net_buf *bt_buf_get_cmd_complete(k_timeout_t timeout) { struct net_buf *buf; unsigned int key; key = irq_lock(); buf = sent_cmd; sent_cmd = NULL; irq_unlock(key); BT_DBG("sent_cmd %p", buf); if (buf) { bt_buf_set_type(buf, BT_BUF_EVT); buf->len = 0U; net_buf_reserve(buf, BT_BUF_RESERVE); return buf; } return bt_buf_get_rx(BT_BUF_EVT, timeout); } static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf) { BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf); if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) { BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p", opcode, buf->pool_id, net_buf_pool_get(buf->pool_id), &hci_cmd_pool); return; } if (cmd(buf)->opcode != opcode) { BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x", opcode, cmd(buf)->opcode); } if (cmd(buf)->state && !status) { struct cmd_state_set *update = cmd(buf)->state; atomic_set_bit_to(update->target, update->bit, update->val); } /* If the command was synchronous wake up bt_hci_cmd_send_sync() */ if (cmd(buf)->sync) { cmd(buf)->status = status; k_sem_give(cmd(buf)->sync); } } void hci_cmd_complete(struct net_buf *buf) { struct bt_hci_evt_cmd_complete *evt; u8_t status, ncmd; u16_t opcode; evt = net_buf_pull_mem(buf, sizeof(*evt)); ncmd = evt->ncmd; opcode = sys_le16_to_cpu(evt->opcode); BT_DBG("opcode 0x%04x", opcode); /* All command return parameters have a 1-byte status in the * beginning, so we can safely make this generalization. */ status = buf->data[0]; hci_cmd_done(opcode, status, buf); /* Allow next command to be sent */ if (ncmd) { k_sem_give(&ncmd_sem); } } void hci_cmd_status(struct net_buf *buf) { struct bt_hci_evt_cmd_status *evt; u16_t opcode; u8_t ncmd; evt = net_buf_pull_mem(buf, sizeof(*evt)); opcode = sys_le16_to_cpu(evt->opcode); ncmd = evt->ncmd; BT_DBG("opcode 0x%04x", opcode); hci_cmd_done(opcode, evt->status, buf); /* Allow next command to be sent */ if (ncmd) { k_sem_give(&ncmd_sem); } } void send_cmd(void) { struct net_buf *buf; int err; /* Get next command */ BT_DBG("calling net_buf_get"); buf = net_buf_get(&cmd_tx_queue, K_NO_WAIT); BT_ASSERT(buf); /* Wait until ncmd > 0 */ BT_DBG("calling sem_take_wait"); k_sem_take(&ncmd_sem, K_FOREVER); /* Clear out any existing sent command */ if (sent_cmd) { BT_ERR("Uncleared pending sent_cmd"); net_buf_unref(sent_cmd); sent_cmd = NULL; } sent_cmd = net_buf_ref(buf); BT_DBG("Sending command 0x%04x (buf %p) to driver", cmd(buf)->opcode, buf); err = bt_send(buf); if (err) { BT_ERR("Unable to send to driver (err %d)", err); k_sem_give(&ncmd_sem); hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, buf); net_buf_unref(sent_cmd); sent_cmd = NULL; net_buf_unref(buf); } } u16_t bt_hci_get_cmd_opcode(struct net_buf *buf) { return cmd(buf)->opcode; } struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len) { struct bt_hci_cmd_hdr *hdr; struct net_buf *buf; BT_DBG("opcode 0x%04x param_len %u", opcode, param_len); buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER); __ASSERT_NO_MSG(buf); BT_DBG("buf %p", buf); net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, BT_BUF_CMD); cmd(buf)->opcode = opcode; cmd(buf)->sync = NULL; cmd(buf)->state = NULL; hdr = net_buf_add(buf, sizeof(*hdr)); hdr->opcode = sys_cpu_to_le16(opcode); hdr->param_len = param_len; return buf; } int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf) { if (!buf) { buf = bt_hci_cmd_create(opcode, 0); if (!buf) { return -ENOBUFS; } } BT_DBG("opcode 0x%04x len %u", opcode, buf->len); /* Host Number of Completed Packets can ignore the ncmd value * and does not generate any cmd complete/status events. */ if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) { int err; err = bt_send(buf); if (err) { BT_ERR("Unable to send to driver (err %d)", err); net_buf_unref(buf); } return err; } net_buf_put(&cmd_tx_queue, buf); return 0; } int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, struct net_buf **rsp) { struct k_sem sync_sem; u8_t status; int err; if (!buf) { buf = bt_hci_cmd_create(opcode, 0); if (!buf) { return -ENOBUFS; } } BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len); k_sem_init(&sync_sem, 0, 1); cmd(buf)->sync = &sync_sem; /* Make sure the buffer stays around until the command completes */ net_buf_ref(buf); net_buf_put(&cmd_tx_queue, buf); err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT); BT_ASSERT_MSG(err == 0, "k_sem_take failed with err %d", err); k_sem_delete(&sync_sem); status = cmd(buf)->status; if (status) { BT_WARN("opcode 0x%04x status 0x%02x", opcode, status); net_buf_unref(buf); switch (status) { case BT_HCI_ERR_CONN_LIMIT_EXCEEDED: return -ECONNREFUSED; default: return -EIO; } } BT_DBG("rsp %p opcode 0x%04x len %u", buf, opcode, buf->len); if (rsp) { *rsp = buf; } else { net_buf_unref(buf); } return 0; } __hci_api_weak__ int hci_api_le_scan_enable(u8_t enable, u8_t filter_dup) { struct bt_hci_cp_le_set_scan_enable *cp; struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); if (enable == BT_HCI_LE_SCAN_ENABLE) { cp->filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); } else { cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; } cp->enable = enable; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL); return err; } __hci_api_weak__ int hci_api_le_scan_param_set(u8_t scan_type, u16_t interval, u16_t window, u8_t addr_type, u8_t filter_policy) { struct bt_hci_cp_le_set_scan_param set_param; struct net_buf *buf; memset(&set_param, 0, sizeof(set_param)); set_param.scan_type = scan_type; set_param.addr_type = addr_type; /* for the rest parameters apply default values according to * spec 4.2, vol2, part E, 7.8.10 */ set_param.interval = sys_cpu_to_le16(interval); set_param.window = sys_cpu_to_le16(window); set_param.filter_policy = filter_policy; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, &set_param, sizeof(set_param)); bt_hci_cmd_send(BT_HCI_OP_LE_SET_SCAN_PARAM, buf); return 0; } __hci_api_weak__ int hci_api_le_get_max_data_len(uint16_t *tx_octets, uint16_t *tx_time) { struct bt_hci_rp_le_read_max_data_len *rp; struct net_buf *rsp; int err; if (tx_octets == NULL || tx_time == NULL) { return -EINVAL; } err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp); if (err) { return err; } rp = (void *)rsp->data; *tx_octets = sys_le16_to_cpu(rp->max_tx_octets); *tx_time = sys_le16_to_cpu(rp->max_tx_time); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_get_default_data_len(uint16_t *tx_octets, uint16_t *tx_time) { struct bt_hci_rp_le_read_default_data_len *rp; struct net_buf *rsp; int err; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_DEFAULT_DATA_LEN, NULL, &rsp); if (err) { return err; } rp = (void *)rsp->data; *tx_octets = sys_le16_to_cpu(rp->max_tx_octets); *tx_time = sys_le16_to_cpu(rp->max_tx_time); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_set_default_data_len(uint16_t tx_octets, uint16_t tx_time) { struct bt_hci_cp_le_write_default_data_len *cp; struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->max_tx_octets = sys_cpu_to_le16(tx_octets); cp->max_tx_time = sys_cpu_to_le16(tx_time); err = bt_hci_cmd_send(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, buf); if (err) { return err; } return 0; } __hci_api_weak__ int hci_api_le_set_data_len(int16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) { struct bt_hci_cp_le_set_data_len *cp; struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn_handle); cp->tx_octets = sys_cpu_to_le16(tx_octets); cp->tx_time = sys_cpu_to_le16(tx_time); err = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf); if (err) { return err; } return 0; } static int hci_vs_set_bd_add(uint8_t addr[6]) { #if defined(CONFIG_BT_HCI_VS_EXT) struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_VS_WRITE_BD_ADDR, sizeof(*addr)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, addr, sizeof(*addr)); err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_WRITE_BD_ADDR, buf, NULL); if (err) { return err; } return 0; #else return -ENOTSUP; #endif } __hci_api_weak__ int hci_api_le_set_bdaddr(uint8_t bdaddr[6]) { return hci_vs_set_bd_add(bdaddr); } __hci_api_weak__ int hci_api_reset() { int err; struct net_buf *rsp; u8_t status; /* Send HCI_RESET */ err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp); if (err) { return err; } status = rsp->data[0]; net_buf_unref(rsp); return status; } __hci_api_weak__ int hci_api_read_local_feature(uint8_t feature[8]) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_read_local_features *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } memcpy(feature, rp->features, 8); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_read_local_version_info(uint8_t *hci_version, uint8_t *lmp_version, uint16_t *hci_revision, uint16_t *lmp_subversion, uint16_t *manufacturer) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_read_local_version_info *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *hci_version = rp->hci_version; *lmp_version = rp->lmp_version; *hci_revision = rp->hci_revision; *lmp_subversion = rp->lmp_subversion; *manufacturer = rp->manufacturer; net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_read_bdaddr(u8_t bdaddr[6]) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_read_bd_addr *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) || !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) { net_buf_unref(rsp); return -ENODATA; } memcpy(bdaddr, &rp->bdaddr, 6); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_read_local_support_command(uint8_t supported_commands[64]) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_read_supported_commands *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } memcpy(supported_commands, rp->commands, 64); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_set_host_buffer_size(uint16_t acl_mtu, uint8_t sco_mtu, uint16_t acl_pkts, uint16_t sco_pkts) { struct bt_hci_cp_host_buffer_size *hbs; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE, sizeof(*hbs)); if (!buf) { return -ENOBUFS; } hbs = net_buf_add(buf, sizeof(*hbs)); memset(hbs, 0, sizeof(*hbs)); hbs->acl_mtu = sys_cpu_to_le16(acl_mtu); hbs->acl_pkts = sys_cpu_to_le16(acl_pkts); return bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL); } __hci_api_weak__ int hci_api_set_host_flow_enable(uint8_t enable) { struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, enable); return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL); } __hci_api_weak__ int hci_api_le_read_local_feature(uint8_t feature[8]) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_le_read_local_features *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } memcpy(feature, rp->features, 8); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_read_buffer_size_complete(uint16_t *le_max_len, uint8_t *le_max_num) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_le_read_buffer_size *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *le_max_len = sys_le16_to_cpu(rp->le_max_len); *le_max_num = rp->le_max_num; net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_read_support_states(uint64_t *states) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_le_read_supp_states *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *states = sys_get_le64(rp->le_states); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_read_rl_size(uint8_t *rl_size) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_le_read_rl_size *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *rl_size = rp->rl_size; net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_set_event_mask(uint64_t mask) { struct bt_hci_cp_le_set_event_mask *cp_mask; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask)); if (!buf) { return -ENOBUFS; } cp_mask = net_buf_add(buf, sizeof(*cp_mask)); sys_put_le64(mask, cp_mask->events); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL); } __hci_api_weak__ int hci_api_set_event_mask(uint64_t mask) { struct bt_hci_cp_set_event_mask *ev; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev)); if (!buf) { return -ENOBUFS; } ev = net_buf_add(buf, sizeof(*ev)); sys_put_le64(mask, ev->events); return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL); } __hci_api_weak__ int hci_api_num_complete_packets(u8_t num_handles, u16_t *handles, u16_t *counts) { int i; for (i = 0; i < num_handles; i++) { u16_t handle, count; handle = handles[i]; count = counts[i]; BT_DBG("handle %u count %u", handle, count); extern void bt_hci_num_complete_packets(u16_t handle, u16_t count); bt_hci_num_complete_packets(handle, count); } return 0; } __hci_api_weak__ int hci_api_white_list_size(uint8_t *size) { int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_le_read_wl_size *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *size = rp->wl_size; net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_white_list_add(uint8_t peer_addr_type, uint8_t peer_addr[6]) { struct bt_hci_cp_le_add_dev_to_wl *wl_addr; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*wl_addr)); if(!buf) { return -ENOBUFS; } wl_addr = net_buf_add(buf, sizeof(*wl_addr)); wl_addr->addr.type = peer_addr_type; memcpy(wl_addr->addr.a.val,peer_addr,sizeof(wl_addr->addr.a.val)); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL); } __hci_api_weak__ int hci_api_white_list_remove(uint8_t peer_addr_type, uint8_t peer_addr[6]) { struct bt_hci_cp_le_add_dev_to_wl *wl_addr; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*wl_addr)); if(!buf) { return -ENOBUFS; } wl_addr = net_buf_add(buf, sizeof(*wl_addr)); wl_addr->addr.type = peer_addr_type; memcpy(wl_addr->addr.a.val,peer_addr,sizeof(wl_addr->addr.a.val)); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL); } __hci_api_weak__ int hci_api_white_list_clear() { return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL); } #if defined(CONFIG_BT_HCI_VS_EXT) #if defined(CONFIG_BT_DEBUG) static const char *vs_hw_platform(u16_t platform) { static const char *const plat_str[] = { "reserved", "Intel Corporation", "Nordic Semiconductor", "NXP Semiconductors" }; if (platform < ARRAY_SIZE(plat_str)) { return plat_str[platform]; } return "unknown"; } static const char *vs_hw_variant(u16_t platform, u16_t variant) { static const char *const nordic_str[] = { "reserved", "nRF51x", "nRF52x" }; if (platform != BT_HCI_VS_HW_PLAT_NORDIC) { return "unknown"; } if (variant < ARRAY_SIZE(nordic_str)) { return nordic_str[variant]; } return "unknown"; } static const char *vs_fw_variant(u8_t variant) { static const char *const var_str[] = { "Standard Bluetooth controller", "Vendor specific controller", "Firmware loader", "Rescue image", }; if (variant < ARRAY_SIZE(var_str)) { return var_str[variant]; } return "unknown"; } #endif /* CONFIG_BT_DEBUG */ static void hci_vs_init(void) { union { struct bt_hci_rp_vs_read_version_info *info; struct bt_hci_rp_vs_read_supported_commands *cmds; struct bt_hci_rp_vs_read_supported_features *feat; } rp; struct net_buf *rsp; int err; /* If heuristics is enabled, try to guess HCI VS support by looking * at the HCI version and identity address. We haven't tried to set * a static random address yet at this point, so the identity will * either be zeroes or a valid public address. */ if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && (bt_dev.hci_version < BT_HCI_VERSION_5_0 || (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) { BT_WARN("Controller doesn't seem to support Zephyr vendor HCI"); return; } err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp); if (err) { BT_WARN("Vendor HCI extensions not available"); return; } #if defined(CONFIG_BT_DEBUG) rp.info = (void *)rsp->data; BT_INFO("HW Platform: %s (0x%04x)", vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)), sys_le16_to_cpu(rp.info->hw_platform)); BT_INFO("HW Variant: %s (0x%04x)", vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform), sys_le16_to_cpu(rp.info->hw_variant)), sys_le16_to_cpu(rp.info->hw_variant)); BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u", vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant, rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision), sys_le32_to_cpu(rp.info->fw_build)); #endif /* CONFIG_BT_DEBUG */ net_buf_unref(rsp); err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS, NULL, &rsp); if (err) { BT_WARN("Failed to read supported vendor features"); return; } rp.cmds = (void *)rsp->data; memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX); net_buf_unref(rsp); err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES, NULL, &rsp); if (err) { BT_WARN("Failed to read supported vendor commands"); return; } rp.feat = (void *)rsp->data; memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX); net_buf_unref(rsp); } #endif /* CONFIG_BT_HCI_VS_EXT */ __hci_api_weak__ int hci_api_vs_init() { #if defined(CONFIG_BT_HCI_VS_EXT) hci_vs_init(); return 0; #else return 0; #endif } __hci_api_weak__ int hci_api_le_adv_enable(uint8_t enable) { struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, enable); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL); } __hci_api_weak__ int hci_api_le_adv_param(uint16_t min_interval, uint16_t max_interval, uint8_t type, uint8_t own_addr_type, uint8_t direct_addr_type, uint8_t direct_addr[6], uint8_t channel_map, uint8_t filter_policy) { struct bt_hci_cp_le_set_adv_param set_param; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param)); if (!buf) { return -ENOBUFS; } set_param.min_interval = min_interval; set_param.max_interval = max_interval; set_param.type = type; set_param.own_addr_type = own_addr_type; set_param.direct_addr.type = direct_addr_type; memcpy(set_param.direct_addr.a.val, direct_addr, 6); set_param.channel_map = channel_map; set_param.filter_policy = filter_policy; net_buf_add_mem(buf, &set_param, sizeof(set_param)); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL); } __hci_api_weak__ int hci_api_le_set_random_addr(const uint8_t addr[6]) { struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, 6); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, addr, 6); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL); } __hci_api_weak__ int hci_api_le_set_ad_data(uint8_t len, uint8_t data[31]) { struct bt_hci_cp_le_set_adv_data *set_data; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_DATA, sizeof(*set_data)); if (!buf) { return -ENOBUFS; } set_data = net_buf_add(buf, sizeof(*set_data)); set_data->len = len; memcpy(set_data->data, data, 31); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_DATA, buf, NULL); } __hci_api_weak__ int hci_api_le_set_sd_data(uint8_t len, uint8_t data[31]) { struct bt_hci_cp_le_set_adv_data *set_data; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sizeof(*set_data)); if (!buf) { return -ENOBUFS; } set_data = net_buf_add(buf, sizeof(*set_data)); set_data->len = len; memcpy(set_data->data, data, 31); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, buf, NULL); } __hci_api_weak__ int hci_api_le_create_conn(uint16_t scan_interval, uint16_t scan_window, uint8_t filter_policy, uint8_t peer_addr_type, const uint8_t peer_addr[6], uint8_t own_addr_type, uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout, uint16_t min_ce_len, uint16_t max_ce_len) { struct net_buf *buf; struct bt_hci_cp_le_create_conn *cp; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memset(cp, 0, sizeof(*cp)); /* Interval == window for continuous scanning */ cp->scan_interval = sys_cpu_to_le16(scan_interval); cp->scan_window = cp->scan_interval; cp->peer_addr.type = peer_addr_type; memcpy(cp->peer_addr.a.val, peer_addr, 6); cp->own_addr_type = own_addr_type; cp->conn_interval_min = sys_cpu_to_le16(conn_interval_min); cp->conn_interval_max = sys_cpu_to_le16(conn_interval_max); cp->conn_latency = sys_cpu_to_le16(conn_latency); cp->supervision_timeout = sys_cpu_to_le16(supervision_timeout); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL); } __hci_api_weak__ int hci_api_le_create_conn_cancel() { return bt_hci_cmd_send(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL); } __hci_api_weak__ int hci_api_le_disconnect(uint16_t conn_hanlde, uint8_t reason) { struct net_buf *buf; struct bt_hci_cp_disconnect *disconn; buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn)); if (!buf) { return -ENOBUFS; } disconn = net_buf_add(buf, sizeof(*disconn)); disconn->handle = sys_cpu_to_le16(conn_hanlde); disconn->reason = reason; return bt_hci_cmd_send(BT_HCI_OP_DISCONNECT, buf); } __hci_api_weak__ int hci_api_le_read_remote_features(uint16_t conn_handle) { struct bt_hci_cp_le_read_remote_features *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn_handle); return bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf); } __hci_api_weak__ int hci_api_le_read_remote_version(uint16_t conn_handle) { struct bt_hci_cp_read_remote_version_info *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_VERSION_INFO, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn_handle); return bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_VERSION_INFO, buf, NULL); } __hci_api_weak__ int hci_api_host_num_complete_packets(uint8_t num_handles, struct handle_count *phc) { struct net_buf *buf; struct bt_hci_cp_host_num_completed_packets *cp; struct bt_hci_handle_count *hc; buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, sizeof(*cp) + sizeof(*hc)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->num_handles = sys_cpu_to_le16(num_handles); hc = net_buf_add(buf, sizeof(*hc)); hc->handle = sys_cpu_to_le16(phc[0].handle); hc->count = sys_cpu_to_le16(phc[0].count); return bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf); } __hci_api_weak__ int hci_api_le_conn_updata(uint16_t conn_handle, uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout, uint16_t min_ce_len, uint16_t max_ce_len) { struct hci_cp_le_conn_update *conn_update; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE, sizeof(*conn_update)); if (!buf) { return -ENOBUFS; } conn_update = net_buf_add(buf, sizeof(*conn_update)); memset(conn_update, 0, sizeof(*conn_update)); conn_update->handle = sys_cpu_to_le16(conn_handle); conn_update->conn_interval_min = sys_cpu_to_le16(conn_interval_min); conn_update->conn_interval_max = sys_cpu_to_le16(conn_interval_max); conn_update->conn_latency = sys_cpu_to_le16(conn_latency); conn_update->supervision_timeout = sys_cpu_to_le16(supervision_timeout); return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_UPDATE, buf); } __hci_api_weak__ int hci_api_le_start_encrypt(uint16_t conn_handle, u8_t rand[8], u8_t ediv[2], uint8_t ltk[16]) { struct bt_hci_cp_le_start_encryption *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn_handle); memcpy(&cp->rand, rand, sizeof(cp->rand)); memcpy(&cp->ediv, ediv, sizeof(cp->ediv)); memcpy(cp->ltk, ltk, sizeof(cp->ltk)); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL); } __hci_api_weak__ int hci_api_le_enctypt_ltk_req_reply(uint16_t conn_handle, uint8_t ltk[16]) { struct net_buf *buf; struct bt_hci_cp_le_ltk_req_reply *cp; buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = conn_handle; memcpy(cp->ltk, ltk, 16); return bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf); } __hci_api_weak__ int hci_api_le_enctypt_ltk_req_neg_reply(uint16_t conn_handle) { struct bt_hci_cp_le_ltk_req_neg_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = conn_handle; return bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf); } __hci_api_weak__ int hci_api_le_rand(uint8_t random_data[8]) { struct bt_hci_rp_le_rand *rp; struct net_buf *rsp; int err; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); if (err) { return err; } rp = (void *)rsp->data; memcpy(random_data, rp->rand, sizeof(rp->rand)); return 0; } __hci_api_weak__ int hci_api_le_enc(uint8_t key[16], uint8_t plaintext[16], uint8_t ciphertext[16]) { struct bt_hci_cp_le_encrypt *cp; struct bt_hci_rp_le_encrypt *rp; int err; struct net_buf *buf; struct net_buf *rsp; buf = bt_hci_cmd_create(BT_HCI_OP_LE_ENCRYPT, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memcpy(cp->key, key, sizeof(cp->key)); memcpy(cp->plaintext, plaintext, sizeof(cp->plaintext)); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ENCRYPT, buf, &rsp); if (err) { return err; } rp = (void *)rsp->data; memcpy(ciphertext, rp->enc_data, sizeof(rp->enc_data)); return 0; } __hci_api_weak__ int hci_api_le_set_phy(u16_t handle, u8_t all_phys, u8_t tx_phys, u8_t rx_phys, u16_t phy_opts) { struct bt_hci_cp_le_set_phy *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); cp->all_phys = all_phys; cp->tx_phys = tx_phys; cp->rx_phys = rx_phys; cp->phy_opts = phy_opts; return bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf); } __hci_api_weak__ int hci_api_le_conn_param_req_reply(uint16_t handle, uint16_t interval_min, uint16_t interval_max, uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { struct bt_hci_cp_le_conn_param_req_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memset(cp, 0, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); cp->interval_min = sys_cpu_to_le16(interval_min); cp->interval_max = sys_cpu_to_le16(interval_max); cp->latency = sys_cpu_to_le16(latency); cp->timeout = sys_cpu_to_le16(timeout); return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf); } __hci_api_weak__ int hci_api_le_conn_param_neg_reply(uint16_t handle, uint8_t reason) { struct bt_hci_cp_le_conn_param_req_neg_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); cp->reason = sys_cpu_to_le16(reason); return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf); } __hci_api_weak__ int hci_api_le_add_dev_to_rl(uint8_t type, uint8_t peer_id_addr[6], uint8_t peer_irk[16], uint8_t local_irk[16]) { struct bt_hci_cp_le_add_dev_to_rl *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memset(cp, 0, sizeof(*cp)); cp->peer_id_addr.type = type; memcpy(cp->peer_id_addr.a.val, peer_id_addr, 6); if (peer_irk) { memcpy(cp->peer_irk, peer_irk, 16); } if (local_irk) { memcpy(cp->local_irk, local_irk, 16); } return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL); } __hci_api_weak__ int hci_api_le_remove_dev_from_rl(uint8_t type, const uint8_t peer_id_addr[6]) { struct bt_hci_cp_le_rem_dev_from_rl *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memset(cp, 0, sizeof(*cp)); cp->peer_id_addr.type = type; memcpy(cp->peer_id_addr.a.val, peer_id_addr, 6); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL); } __hci_api_weak__ int hci_api_le_clear_rl() { return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL); } __hci_api_weak__ int hci_api_le_set_addr_res_enable(uint8_t enable) { struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, enable); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, buf, NULL); } __hci_api_weak__ int hci_api_le_set_privacy_mode(uint8_t type, uint8_t id_addr[6], uint8_t mode) { struct bt_hci_cp_le_set_privacy_mode cp; struct net_buf *buf; cp.id_addr.type = type; memcpy(cp.id_addr.a.val, id_addr, 6); cp.mode = mode; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, &cp, sizeof(cp)); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL); } __hci_api_weak__ int hci_api_le_gen_p256_pubkey() { return bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL); } __hci_api_weak__ int hci_api_le_gen_dhkey(uint8_t remote_pk[64]) { struct bt_hci_cp_le_generate_dhkey *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memcpy(cp->key, remote_pk, sizeof(cp->key)); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL); } __hci_api_weak__ int hci_api_read_buffer_size(uint16_t *acl_max_len, uint8_t *sco_max_len, uint16_t *acl_max_num, uint16_t *sco_max_num) { struct bt_hci_rp_read_buffer_size *rp; struct net_buf *rsp; int err; /* Use BR/EDR buffer size if LE reports zero buffers */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp); if (err) { return err; } rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *acl_max_len = sys_le16_to_cpu(rp->acl_max_len); *sco_max_len = rp->sco_max_len; *acl_max_num = sys_le16_to_cpu(rp->acl_max_num); *sco_max_num = sys_le16_to_cpu(rp->sco_max_num); net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_write_host_supp(uint8_t le, uint8_t simul) { struct bt_hci_cp_write_le_host_supp *cp_le; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, sizeof(*cp_le)); if (!buf) { return -ENOBUFS; } cp_le = net_buf_add(buf, sizeof(*cp_le)); /* Explicitly enable LE for dual-mode controllers */ cp_le->le = le; cp_le->simul = simul; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf, NULL); } static void process_events(struct k_poll_event *ev, int count) { BT_DBG("count %d", count); for (; count; ev++, count--) { BT_DBG("ev->state %u", ev->state); switch (ev->state) { case K_POLL_STATE_SIGNALED: break; case K_POLL_STATE_FIFO_DATA_AVAILABLE: if (ev->tag == BT_EVENT_CMD_TX) { send_cmd(); } else if (IS_ENABLED(CONFIG_BT_CONN)) { struct bt_conn *conn; if (ev->tag == BT_EVENT_CONN_TX_QUEUE) { conn = CONTAINER_OF(ev->fifo, struct bt_conn, tx_queue); bt_conn_process_tx(conn); } } break; case K_POLL_STATE_NOT_READY: break; default: BT_WARN("Unexpected k_poll event state %u", ev->state); break; } } } static void hci_data_buf_overflow(struct net_buf *buf) { struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data; BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type); (void)evt; } static const struct event_handler prio_events[] = { EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete, sizeof(struct bt_hci_evt_cmd_complete)), EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status, sizeof(struct bt_hci_evt_cmd_status)), #if defined(CONFIG_BT_CONN) EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW, hci_data_buf_overflow, sizeof(struct bt_hci_evt_data_buf_overflow)), EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS, hci_num_completed_packets, sizeof(struct bt_hci_evt_num_completed_packets)), #endif /* CONFIG_BT_CONN */ }; __hci_api_weak__ int bt_recv_prio(struct net_buf *buf) { struct bt_hci_evt_hdr *hdr; bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT); BT_ASSERT(buf->len >= sizeof(*hdr)); hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_ASSERT(bt_hci_evt_is_prio(hdr->evt)); handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events)); net_buf_unref(buf); return 0; } #if defined(CONFIG_BT_CONN) /* command FIFO + conn_change signal + MAX_CONN * 2 (tx & tx_notify) */ #define EV_COUNT (2 + (CONFIG_BT_MAX_CONN * 2)) #else /* command FIFO */ #define EV_COUNT 1 #endif static void hci_tx_thread(void *p1) { static struct k_poll_event events[EV_COUNT] = { K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &cmd_tx_queue, BT_EVENT_CMD_TX), }; BT_DBG("Started"); while (1) { int ev_count, err; events[0].state = K_POLL_STATE_NOT_READY; ev_count = 1; if (IS_ENABLED(CONFIG_BT_CONN)) { ev_count += bt_conn_prepare_events(&events[1]); } BT_DBG("Calling k_poll with %d events", ev_count); #ifndef YULONG_HCI err = k_poll(events, ev_count, K_FOREVER); #endif BT_ASSERT(err == 0); process_events(events, ev_count); /* Make sure we don't hog the CPU if there's all the time * some ready events. */ k_yield(); } } __hci_api_weak__ int hci_api_init() { #if !defined(CONFIG_BT_WAIT_NOP) k_sem_init(&ncmd_sem,1,1); #else k_sem_init(&ncmd_sem,0,1); #endif NET_BUF_POOL_INIT(hci_cmd_pool); k_fifo_init(&cmd_tx_queue); #ifdef CONFIG_BT_TINYCRYPT_ECC bt_hci_ecc_init(); #endif return 0; } __hci_api_weak__ int hci_api_le_ext_adv_enable(uint8_t enable, uint16_t set_num, struct ext_adv_set_t adv_sets[]) { struct net_buf *buf; struct cmd_state_set state; int i; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_ADV_ENABLE, 2 + 4 * set_num); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, enable); net_buf_add_u8(buf, set_num); for (i = 0; i < set_num; i++) { net_buf_add_u8(buf, adv_sets[i].adv_handle); net_buf_add_le16(buf,sys_cpu_to_le16(adv_sets[i].duration)); net_buf_add_u8(buf, adv_sets[i].max_ext_adv_evts); } //cmd_state_set_init(&state, adv->flags, BT_ADV_ENABLED, enable); cmd(buf)->state = &state; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_ADV_ENABLE, buf, NULL); } __hci_api_weak__ int hci_api_le_set_adv_random_addr(uint8_t handle, const uint8_t addr[6]) { struct bt_hci_cp_le_set_adv_set_random_addr *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = handle; memcpy(&cp->bdaddr, addr, 6); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR, buf, NULL); } __hci_api_weak__ int hci_api_le_ext_scan_enable(uint8_t enable,uint8_t filter_dup,uint16_t duration, uint16_t period) { struct bt_hci_cp_le_set_ext_scan_enable *cp; struct cmd_state_set state; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->enable = enable; cp->filter_dup = filter_dup; cp->duration = sys_cpu_to_le16(duration); cp->period = 0; cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE); cmd(buf)->state = &state; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE, buf, NULL); } __hci_api_weak__ int hci_api_le_ext_scan_param_set(uint8_t own_addr_type,uint8_t filter_policy,uint8_t scan_phys, struct ext_scan_param_t params[]) { struct bt_hci_cp_le_set_ext_scan_param *set_param; struct net_buf *buf; u8_t phys_num = (scan_phys & BT_HCI_LE_EXT_SCAN_PHY_1M)? 1 : 0 + (scan_phys & BT_HCI_LE_EXT_SCAN_PHY_CODED)? 1 : 0; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_SCAN_PARAM, sizeof(*set_param) + phys_num * sizeof(struct bt_hci_ext_scan_phy)); if (!buf) { return -ENOBUFS; } set_param = net_buf_add(buf, sizeof(*set_param)); set_param->own_addr_type = own_addr_type; set_param->phys = scan_phys; set_param->filter_policy = filter_policy; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_SCAN_PARAM, buf, NULL); } __hci_api_weak__ int hci_api_le_read_phy(uint16_t conn_handle, uint8_t *tx_phy , uint8_t *rx_phy) { struct bt_hci_cp_le_read_phy *cp; struct bt_hci_rp_le_read_phy *rp; struct net_buf *buf, *rsp; int err; buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_PHY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn_handle); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_PHY, buf, &rsp); if (err) { return err; } rp = (void *)rsp->data; *tx_phy = rp->tx_phy; *rx_phy = rp->rx_phy; net_buf_unref(rsp); return 0; } __hci_api_weak__ int hci_api_le_create_conn_ext(uint8_t filter_policy, uint8_t own_addr_type, uint8_t peer_addr_type, uint8_t peer_addr[6], uint8_t init_phys, struct ext_conn_phy_params_t params[]) { struct bt_hci_cp_le_ext_create_conn *cp; struct bt_hci_ext_conn_phy *phy; struct cmd_state_set state; struct net_buf *buf; u8_t num_phys; struct ext_conn_phy_params_t *pparams = params; num_phys = (init_phys & BT_HCI_LE_EXT_SCAN_PHY_1M) ? 1:0 + (init_phys & BT_HCI_LE_EXT_SCAN_PHY_CODED) ? 1:0; buf = bt_hci_cmd_create(BT_HCI_OP_LE_EXT_CREATE_CONN, sizeof(*cp) + num_phys * sizeof(*phy)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); (void)memset(cp, 0, sizeof(*cp)); cp->filter_policy = filter_policy; cp->peer_addr.type = peer_addr_type; memcpy(cp->peer_addr.a.val, peer_addr, 6); cp->own_addr_type = own_addr_type; cp->phys = init_phys; if (init_phys & BT_HCI_LE_EXT_SCAN_PHY_1M) { phy = net_buf_add(buf, sizeof(*phy)); phy->scan_interval = sys_cpu_to_le16(pparams->scan_interval); phy->scan_window = sys_cpu_to_le16(pparams->scan_window); phy->conn_interval_min = sys_cpu_to_le16(pparams->conn_interval_min); phy->conn_interval_max = sys_cpu_to_le16(pparams->conn_interval_max); phy->conn_latency = sys_cpu_to_le16(pparams->conn_latency); phy->supervision_timeout = sys_cpu_to_le16(pparams->supervision_timeout); phy->min_ce_len = 0; phy->max_ce_len = 0; pparams++; } if (init_phys & BT_HCI_LE_EXT_SCAN_PHY_CODED) { phy = net_buf_add(buf, sizeof(*phy)); phy->scan_interval = sys_cpu_to_le16(pparams->scan_interval); phy->scan_window = sys_cpu_to_le16(pparams->scan_window); phy->conn_interval_min = sys_cpu_to_le16(pparams->conn_interval_min); phy->conn_interval_max = sys_cpu_to_le16(pparams->conn_interval_max); phy->conn_latency = sys_cpu_to_le16(pparams->conn_latency); phy->supervision_timeout = sys_cpu_to_le16(pparams->supervision_timeout); phy->min_ce_len = 0; phy->max_ce_len = 0; } cmd_state_set_init(&state, bt_dev.flags, BT_DEV_INITIATING, true); cmd(buf)->state = &state; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_EXT_CREATE_CONN, buf, NULL); } __hci_api_weak__ int hci_api_le_rpa_timeout_set(uint16_t timeout) { struct net_buf *buf; struct bt_hci_cp_le_set_rpa_timeout *cp; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->rpa_timeout = sys_cpu_to_le16(timeout); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, NULL); } __hci_api_weak__ int hci_api_le_set_ext_ad_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[251]) { struct bt_hci_cp_le_set_ext_adv_data *set_data; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_ADV_DATA, sizeof(*set_data)); if (!buf) { return -ENOBUFS; } set_data = net_buf_add(buf, sizeof(*set_data)); (void)memset(set_data, 0, sizeof(*set_data)); set_data->handle = handle; set_data->op = op; set_data->frag_pref = frag_pref; set_data->len = len; memcpy(set_data->data, data, len); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_ADV_DATA, buf, NULL); } __hci_api_weak__ int hci_api_le_set_ext_sd_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[251]) { struct bt_hci_cp_le_set_ext_scan_rsp_data *set_data; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA, sizeof(*set_data)); if (!buf) { return -ENOBUFS; } set_data = net_buf_add(buf, sizeof(*set_data)); (void)memset(set_data, 0, sizeof(*set_data)); set_data->handle = handle; set_data->op = op; set_data->frag_pref = frag_pref; set_data->len = len; memcpy(set_data->data, data, len); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA, buf, NULL); } __hci_api_weak__ int hci_api_le_remove_adv_set(uint8_t handle) { struct bt_hci_cp_le_remove_adv_set *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_REMOVE_ADV_SET, sizeof(*cp)); if (!buf) { BT_WARN("No HCI buffers"); return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = handle; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REMOVE_ADV_SET, buf, NULL); } __hci_api_weak__ int hci_api_le_set_host_chan_classif(u8_t ch_map[5]) { struct bt_hci_cp_le_set_host_chan_classif *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memcpy(&cp->ch_map[0], &ch_map[0], 5); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, buf, NULL); } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_api.c
C
apache-2.0
52,747
/* hci_core.c - HCI core Bluetooth handling */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <stdio.h> #include <bt_errno.h> #include <atomic.h> #include <misc/util.h> #include <misc/slist.h> #include <misc/byteorder.h> #include <misc/stack.h> #include <misc/__assert.h> #include <settings/settings.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/l2cap.h> #include <bluetooth/hci.h> #include <bluetooth/hci_vs.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE) #define LOG_MODULE_NAME bt_hci_core #include "common/log.h" #include "common/rpa.h" #include "keys.h" #include "monitor.h" #include "hci_core.h" #include "hci_ecc.h" #include "ecc.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "gatt_internal.h" #include "smp.h" #include "bluetooth/crypto.h" #include "settings.h" #include <hci_api.h> #ifndef ENOTSUP #define ENOTSUP 134 /* unsupported*/ #endif #if !defined(CONFIG_BT_EXT_ADV_LEGACY_SUPPORT) #undef BT_FEAT_LE_EXT_ADV #define BT_FEAT_LE_EXT_ADV(feat) 1 #endif #ifndef __WEAK #define __WEAK __attribute__((weak)) #endif /* Peripheral timeout to initialize Connection Parameter Update procedure */ #define CONN_UPDATE_TIMEOUT K_MSEC(CONFIG_BT_CONN_PARAM_UPDATE_TIMEOUT) #define RPA_TIMEOUT_MS (CONFIG_BT_RPA_TIMEOUT * MSEC_PER_SEC) #define RPA_TIMEOUT K_MSEC(RPA_TIMEOUT_MS) #if !defined(CONFIG_BT_USE_HCI_API) #define HCI_CMD_TIMEOUT K_SECONDS(10) #endif /* Stacks for the threads */ #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) static struct k_thread rx_thread_data; static BT_STACK_NOINIT(rx_thread_stack, CONFIG_BT_RX_STACK_SIZE); #endif static struct k_thread tx_thread_data; static BT_STACK_NOINIT(tx_thread_stack, CONFIG_BT_HCI_TX_STACK_SIZE); static void init_work(struct k_work *work); struct bt_dev bt_dev; static bt_ready_cb_t ready_cb; static bt_le_scan_cb_t *scan_dev_found_cb; #if defined(CONFIG_BT_OBSERVER) static int set_le_scan_enable(u8_t enable); static sys_slist_t scan_cbs = SYS_SLIST_STATIC_INIT(&scan_cbs); #endif /* defined(CONFIG_BT_OBSERVER) */ #if defined(CONFIG_BT_EXT_ADV) static struct bt_le_ext_adv adv_pool[CONFIG_BT_EXT_ADV_MAX_ADV_SET]; #endif #if defined(CONFIG_BT_HCI_VS_EVT_USER) static bt_hci_vnd_evt_cb_t *hci_vnd_evt_cb; #endif /* CONFIG_BT_HCI_VS_EVT_USER */ #if defined(CONFIG_BT_ECC) static u8_t pub_key[64]; static struct bt_pub_key_cb *pub_key_cb; static bt_dh_key_cb_t dh_key_cb; #endif /* CONFIG_BT_ECC */ #if defined(CONFIG_BT_BREDR) static bt_br_discovery_cb_t *discovery_cb; struct bt_br_discovery_result *discovery_results; static size_t discovery_results_size; static size_t discovery_results_count; #endif /* CONFIG_BT_BREDR */ struct cmd_state_set { atomic_t *target; int bit; bool val; }; void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit, bool val) { state->target = target; state->bit = bit; state->val = val; } struct cmd_data { /** HCI status of the command completion */ u8_t status; /** The command OpCode that the buffer contains */ u16_t opcode; /** The state to update when command completes with success. */ struct cmd_state_set *state; /** Used by bt_hci_cmd_send_sync. */ struct k_sem *sync; }; struct acl_data { /** BT_BUF_ACL_IN */ u8_t type; /* Index into the bt_conn storage array */ u8_t index; /** ACL connection handle */ u16_t handle; }; #define acl(buf) ((struct acl_data *)net_buf_user_data(buf)) #if !defined(CONFIG_BT_USE_HCI_API) static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT]; #define cmd(buf) (&cmd_data[net_buf_id(buf)]) /* HCI command buffers. Derive the needed size from BT_BUF_RX_SIZE since * the same buffer is also used for the response. */ #define CMD_BUF_SIZE BT_BUF_RX_SIZE NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL); #endif NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL); #if defined(CONFIG_BT_CONN) #define NUM_COMLETE_EVENT_SIZE BT_BUF_SIZE( \ sizeof(struct bt_hci_evt_hdr) + \ sizeof(struct bt_hci_cp_host_num_completed_packets) + \ CONFIG_BT_MAX_CONN * sizeof(struct bt_hci_handle_count)) /* Dedicated pool for HCI_Number_of_Completed_Packets. This event is always * consumed synchronously by bt_recv_prio() so a single buffer is enough. * Having a dedicated pool for it ensures that exhaustion of the RX pool * cannot block the delivery of this priority event. */ NET_BUF_POOL_FIXED_DEFINE(num_complete_pool, 1, NUM_COMLETE_EVENT_SIZE, NULL); #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT) #define DISCARDABLE_EVENT_SIZE BT_BUF_SIZE(CONFIG_BT_DISCARDABLE_BUF_SIZE) NET_BUF_POOL_FIXED_DEFINE(discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, DISCARDABLE_EVENT_SIZE, NULL); #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */ #if !defined(CONFIG_BT_USE_HCI_API) struct event_handler { u8_t event; u8_t min_len; void (*handler)(struct net_buf *buf); }; #define EVENT_HANDLER(_evt, _handler, _min_len) \ { \ .event = _evt, \ .handler = _handler, \ .min_len = _min_len, \ } #endif void handle_event(u8_t event, struct net_buf *buf, const struct event_handler *handlers, size_t num_handlers) { size_t i; for (i = 0; i < num_handlers; i++) { const struct event_handler *handler = &handlers[i]; if (handler->event != event) { continue; } if (buf->len < handler->min_len) { BT_ERR("Too small (%u bytes) event 0x%02x", buf->len, event); return; } handler->handler(buf); return; } BT_WARN("Unhandled event 0x%02x len %u: %s", event, buf->len, bt_hex(buf->data, buf->len)); } #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) static void report_completed_packet(struct net_buf *buf) { u16_t handle = acl(buf)->handle; struct bt_conn *conn; net_buf_destroy(buf); /* Do nothing if controller to host flow control is not supported */ if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { return; } conn = bt_conn_lookup_index(acl(buf)->index); if (!conn) { BT_WARN("Unable to look up conn with index 0x%02x", acl(buf)->index); return; } if (conn->state != BT_CONN_CONNECTED && conn->state != BT_CONN_DISCONNECT) { BT_WARN("Not reporting packet for non-connected conn"); bt_conn_unref(conn); return; } bt_conn_unref(conn); BT_DBG("Reporting completed packet for handle %u", handle); #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_host_num_completed_packets *cp; struct bt_hci_handle_count *hc; buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, sizeof(*cp) + sizeof(*hc)); if (!buf) { BT_ERR("Unable to allocate new HCI command"); return; } cp = net_buf_add(buf, sizeof(*cp)); cp->num_handles = sys_cpu_to_le16(1); hc = net_buf_add(buf, sizeof(*hc)); hc->handle = sys_cpu_to_le16(handle); hc->count = sys_cpu_to_le16(1); bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf); #else struct handle_count hc; hc.handle = handle; hc.count = 1; hci_api_host_num_complete_packets(1, &hc); #endif } #define ACL_IN_SIZE BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_RX_MTU) NET_BUF_POOL_DEFINE(acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, sizeof(struct acl_data), report_completed_packet); #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */ #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len) { struct bt_hci_cmd_hdr *hdr; struct net_buf *buf; BT_DBG("opcode 0x%04x param_len %u", opcode, param_len); buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER); __ASSERT_NO_MSG(buf); BT_DBG("buf %p", buf); net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, BT_BUF_CMD); cmd(buf)->opcode = opcode; cmd(buf)->sync = NULL; cmd(buf)->state = NULL; hdr = net_buf_add(buf, sizeof(*hdr)); hdr->opcode = sys_cpu_to_le16(opcode); hdr->param_len = param_len; return buf; } int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf) { if (!buf) { buf = bt_hci_cmd_create(opcode, 0); if (!buf) { return -ENOBUFS; } } BT_DBG("opcode 0x%04x len %u", opcode, buf->len); /* Host Number of Completed Packets can ignore the ncmd value * and does not generate any cmd complete/status events. */ if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) { int err; err = bt_send(buf); if (err) { BT_ERR("Unable to send to driver (err %d)", err); net_buf_unref(buf); } return err; } net_buf_put(&bt_dev.cmd_tx_queue, buf); return 0; } int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, struct net_buf **rsp) { struct k_sem sync_sem; u8_t status; int err; if (!buf) { buf = bt_hci_cmd_create(opcode, 0); if (!buf) { return -ENOBUFS; } } BT_INFO("buf %p opcode 0x%04x len %u", buf, opcode, buf->len); k_sem_init(&sync_sem, 0, 1); cmd(buf)->sync = &sync_sem; /* Make sure the buffer stays around until the command completes */ net_buf_ref(buf); net_buf_put(&bt_dev.cmd_tx_queue, buf); err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT); BT_ASSERT_MSG(err == 0, "k_sem_take failed with err %d", err); k_sem_delete(&sync_sem); status = cmd(buf)->status; if (status) { BT_WARN("opcode 0x%04x status 0x%02x", opcode, status); net_buf_unref(buf); switch (status) { case BT_HCI_ERR_CONN_LIMIT_EXCEEDED: return -ECONNREFUSED; default: return -EIO; } } BT_DBG("rsp %p opcode 0x%04x len %u", buf, opcode, buf->len); if (rsp) { *rsp = buf; } else { net_buf_unref(buf); } return 0; } #endif #if defined(CONFIG_BT_OBSERVER) || defined(CONFIG_BT_BROADCASTER) const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr) { if (IS_ENABLED(CONFIG_BT_SMP)) { struct bt_keys *keys; keys = bt_keys_find_irk(id, addr); if (keys) { BT_DBG("Identity %s matched RPA %s", bt_addr_le_str(&keys->addr), bt_addr_le_str(addr)); return &keys->addr; } } return addr; } #endif /* CONFIG_BT_OBSERVER || CONFIG_BT_CONN */ #if defined(CONFIG_BT_EXT_ADV) u8_t bt_le_ext_adv_get_index(struct bt_le_ext_adv *adv) { u8_t index = adv - adv_pool; __ASSERT(index < ARRAY_SIZE(adv_pool), "Invalid bt_adv pointer"); return index; } static struct bt_le_ext_adv *adv_new(void) { struct bt_le_ext_adv *adv = NULL; int i; for (i = 0; i < ARRAY_SIZE(adv_pool); i++) { if (!atomic_test_bit(adv_pool[i].flags, BT_ADV_CREATED)) { adv = &adv_pool[i]; break; } } if (!adv) { return NULL; } (void)memset(adv, 0, sizeof(*adv)); atomic_set_bit(adv_pool[i].flags, BT_ADV_CREATED); adv->handle = i; return adv; } static void adv_delete(struct bt_le_ext_adv *adv) { atomic_clear_bit(adv->flags, BT_ADV_CREATED); } #if defined(CONFIG_BT_BROADCASTER) static struct bt_le_ext_adv *bt_adv_lookup_handle(u8_t handle) { if (handle < ARRAY_SIZE(adv_pool) && atomic_test_bit(adv_pool[handle].flags, BT_ADV_CREATED)) { return &adv_pool[handle]; } return NULL; } #endif /* CONFIG_BT_BROADCASTER */ #endif /* defined(CONFIG_BT_EXT_ADV) */ static void bt_adv_foreach(void (*func)(struct bt_le_ext_adv *adv, void *data), void *data) { #if defined(CONFIG_BT_EXT_ADV) for (size_t i = 0; i < ARRAY_SIZE(adv_pool); i++) { if (atomic_test_bit(adv_pool[i].flags, BT_ADV_CREATED)) { func(&adv_pool[i], data); } } #else func(&bt_dev.adv, data); #endif /* defined(CONFIG_BT_EXT_ADV) */ } static struct bt_le_ext_adv *adv_new_legacy(void) { #if defined(CONFIG_BT_EXT_ADV) if (bt_dev.adv) { return NULL; } bt_dev.adv = adv_new(); return bt_dev.adv; #else return &bt_dev.adv; #endif } static void adv_delete_legacy(void) { #if defined(CONFIG_BT_EXT_ADV) if (bt_dev.adv) { atomic_clear_bit(bt_dev.adv->flags, BT_ADV_CREATED); bt_dev.adv = NULL; } #endif } struct bt_le_ext_adv *bt_adv_lookup_legacy(void) { #if defined(CONFIG_BT_EXT_ADV) return bt_dev.adv; #else return &bt_dev.adv; #endif } static int set_le_adv_enable_legacy(struct bt_le_ext_adv *adv, bool enable) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *buf; struct cmd_state_set state; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1); if (!buf) { return -ENOBUFS; } if (enable) { net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE); } else { net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE); } cmd_state_set_init(&state, adv->flags, BT_ADV_ENABLED, enable); cmd(buf)->state = &state; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL); #else u8_t adv_enable; if (enable) { adv_enable = BT_HCI_LE_ADV_ENABLE; } else { adv_enable = BT_HCI_LE_ADV_DISABLE; } err = hci_api_le_adv_enable(adv_enable); if (!err) { atomic_set_bit_to(adv->flags, BT_ADV_ENABLED, enable); } #endif if (err) { return err; } return 0; } static int set_random_address(const bt_addr_t *addr) { int err; BT_DBG("%s", bt_addr_str(addr)); /* Do nothing if we already have the right address */ if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) { return 0; } #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, addr, sizeof(*addr)); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL); #else err = hci_api_le_set_random_addr(addr->val); #endif if (err) { return err; } bt_addr_copy(&bt_dev.random_addr.a, addr); bt_dev.random_addr.type = BT_ADDR_LE_RANDOM; return 0; } static int set_le_adv_enable_ext(struct bt_le_ext_adv *adv, bool enable, const struct bt_le_ext_adv_start_param *param) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *buf; struct cmd_state_set state; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_ADV_ENABLE, 6); if (!buf) { return -ENOBUFS; } if (enable) { net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE); } else { net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE); } net_buf_add_u8(buf, 1); net_buf_add_u8(buf, adv->handle); net_buf_add_le16(buf, param ? sys_cpu_to_le16(param->timeout) : 0); net_buf_add_u8(buf, param ? param->num_events : 0); cmd_state_set_init(&state, adv->flags, BT_ADV_ENABLED, enable); cmd(buf)->state = &state; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_ADV_ENABLE, buf, NULL); #else struct ext_adv_set_t adv_sets[1]; u8_t adv_enable; if (enable) { adv_enable = BT_HCI_LE_ADV_ENABLE; } else { adv_enable = BT_HCI_LE_ADV_DISABLE; } adv_sets[0].adv_handle = adv->handle; adv_sets[0].duration = param ? param->timeout : 0; adv_sets[0].max_ext_adv_evts = param ? param->num_events : 0; err = hci_api_le_ext_adv_enable(adv_enable, 1, adv_sets); if (!err) { atomic_set_bit_to(adv->flags, BT_ADV_ENABLED, enable); } #endif if (err) { return err; } return 0; } static int set_le_adv_enable(struct bt_le_ext_adv *adv, bool enable) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { return set_le_adv_enable_ext(adv, enable, NULL); } return set_le_adv_enable_legacy(adv, enable); } static int set_adv_random_address(struct bt_le_ext_adv *adv, const bt_addr_t *addr) { int err; if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { return set_random_address(addr); } BT_DBG("%s", bt_addr_str(addr)); if (!atomic_test_bit(adv->flags, BT_ADV_PARAMS_SET)) { bt_addr_copy(&adv->random_addr.a, addr); adv->random_addr.type = BT_ADDR_LE_RANDOM; atomic_set_bit(adv->flags, BT_ADV_RANDOM_ADDR_PENDING); return 0; } #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_adv_set_random_addr *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = adv->handle; bt_addr_copy(&cp->bdaddr, addr); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR, buf, NULL); #else err = hci_api_le_set_adv_random_addr(adv->handle, addr->val); #endif if (err) { return err; } bt_addr_copy(&adv->random_addr.a, addr); adv->random_addr.type = BT_ADDR_LE_RANDOM; return 0; } int bt_addr_from_str(const char *str, bt_addr_t *addr) { int i, j; u8_t tmp; if (strlen(str) != 17U) { return -EINVAL; } for (i = 5, j = 1; *str != '\0'; str++, j++) { if (!(j % 3) && (*str != ':')) { return -EINVAL; } else if (*str == ':') { i--; continue; } addr->val[i] = addr->val[i] << 4; if (char2hex(*str, &tmp) < 0) { return -EINVAL; } addr->val[i] |= tmp; } return 0; } int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr) { int err; err = bt_addr_from_str(str, &addr->a); if (err < 0) { return err; } if (!strcmp(type, "public") || !strcmp(type, "(public)")) { addr->type = BT_ADDR_LE_PUBLIC; } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) { addr->type = BT_ADDR_LE_RANDOM; } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) { addr->type = BT_ADDR_LE_PUBLIC_ID; } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) { addr->type = BT_ADDR_LE_RANDOM_ID; } else { return -EINVAL; } return 0; } static void adv_rpa_invalidate(struct bt_le_ext_adv *adv, void *data) { if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED)) { atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID); } } static void le_rpa_invalidate(void) { /* RPA must be submitted */ atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_TIMEOUT_SET); /* Invalidate RPA */ if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED))) { atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); } bt_adv_foreach(adv_rpa_invalidate, NULL); } #if defined(CONFIG_BT_PRIVACY) static void le_rpa_timeout_submit(void) { /* Check if RPA timer is running. */ if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_RPA_TIMEOUT_SET)) { return; } k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT); } /* this function sets new RPA only if current one is no longer valid */ static int le_set_private_addr(u8_t id) { bt_addr_t rpa; int err; /* check if RPA is valid */ if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) { return 0; } err = bt_rpa_create(bt_dev.irk[id], &rpa); if (!err) { err = set_random_address(&rpa); if (!err) { atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID); } } le_rpa_timeout_submit(); return err; } static int le_adv_set_private_addr(struct bt_le_ext_adv *adv) { bt_addr_t rpa; int err; if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { return le_set_private_addr(adv->id); } /* check if RPA is valid */ if (atomic_test_bit(adv->flags, BT_ADV_RPA_VALID)) { return 0; } if (adv == bt_adv_lookup_legacy() && adv->id == BT_ID_DEFAULT) { /* Make sure that a Legacy advertiser using default ID has same * RPA address as scanner roles. */ err = le_set_private_addr(BT_ID_DEFAULT); if (err) { return err; } err = set_adv_random_address(adv, &bt_dev.random_addr.a); if (!err) { atomic_set_bit(adv->flags, BT_ADV_RPA_VALID); } return 0; } err = bt_rpa_create(bt_dev.irk[adv->id], &rpa); if (!err) { err = set_adv_random_address(adv, &rpa); if (!err) { atomic_set_bit(adv->flags, BT_ADV_RPA_VALID); } } if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED)) { le_rpa_timeout_submit(); } return err; } #else static int le_set_private_addr(u8_t id) { bt_addr_t nrpa; int err; err = bt_rand(nrpa.val, sizeof(nrpa.val)); if (err) { return err; } nrpa.val[5] &= 0x3f; return set_random_address(&nrpa); } static int le_adv_set_private_addr(struct bt_le_ext_adv *adv) { bt_addr_t nrpa; int err; err = bt_rand(nrpa.val, sizeof(nrpa.val)); if (err) { return err; } nrpa.val[5] &= 0x3f; return set_adv_random_address(adv, &nrpa); } #endif /* defined(CONFIG_BT_PRIVACY) */ static void adv_update_rpa(struct bt_le_ext_adv *adv, void *data) { if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) && !atomic_test_bit(adv->flags, BT_ADV_LIMITED) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { int err; set_le_adv_enable_ext(adv, false, NULL); err = le_adv_set_private_addr(adv); if (err) { BT_WARN("Failed to update advertiser RPA address (%d)", err); } set_le_adv_enable_ext(adv, true, NULL); } } static void le_update_private_addr(void) { struct bt_le_ext_adv *adv; bool adv_enabled = false; u8_t id = BT_ID_DEFAULT; int err; if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { bt_adv_foreach(adv_update_rpa, NULL); } #if defined(CONFIG_BT_OBSERVER) bool scan_enabled = false; if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN) && !(IS_ENABLED(CONFIG_BT_EXT_ADV) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED))) { set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); scan_enabled = true; } #endif if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) { /* Canceled initiating procedure will be restarted by * connection complete event. */ bt_le_create_conn_cancel(); } if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { adv = bt_adv_lookup_legacy(); if (adv && atomic_test_bit(adv->flags, BT_ADV_ENABLED) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { adv_enabled = true; id = adv->id; set_le_adv_enable_legacy(adv, false); } } /* If both advertiser and scanner is running then the advertiser * ID must be BT_ID_DEFAULT, this will update the RPA address * for both roles. */ err = le_set_private_addr(id); if (err) { BT_WARN("Failed to update RPA address (%d)", err); return; } if (adv_enabled) { set_le_adv_enable_legacy(adv, true); } #if defined(CONFIG_BT_OBSERVER) if (scan_enabled) { set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); } #endif } struct adv_id_check_data { u8_t id; bool adv_enabled; }; static void adv_id_check_func(struct bt_le_ext_adv *adv, void *data) { struct adv_id_check_data *check_data = data; if (IS_ENABLED(CONFIG_BT_EXT_ADV)) { /* Only check if the ID is in use, as the advertiser can be * started and stopped without reconfiguring parameters. */ if (check_data->id == adv->id) { check_data->adv_enabled = true; } } else { if (check_data->id == adv->id && atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { check_data->adv_enabled = true; } } } static void adv_id_check_connectable_func(struct bt_le_ext_adv *adv, void *data) { struct adv_id_check_data *check_data = data; if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) && atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE) && check_data->id != adv->id) { check_data->adv_enabled = true; } } #if defined(CONFIG_BT_SMP) static void adv_is_limited_enabled(struct bt_le_ext_adv *adv, void *data) { bool *adv_enabled = data; if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) && atomic_test_bit(adv->flags, BT_ADV_LIMITED)) { *adv_enabled = true; } } static void adv_pause_enabled(struct bt_le_ext_adv *adv, void *data) { if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { atomic_set_bit(adv->flags, BT_ADV_PAUSED); set_le_adv_enable(adv, false); } } static void adv_unpause_enabled(struct bt_le_ext_adv *adv, void *data) { if (atomic_test_and_clear_bit(adv->flags, BT_ADV_PAUSED)) { set_le_adv_enable(adv, true); } } #endif /* defined(CONFIG_BT_SMP) */ #if defined(CONFIG_BT_PRIVACY) static void adv_is_private_enabled(struct bt_le_ext_adv *adv, void *data) { bool *adv_enabled = data; if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { *adv_enabled = true; } } static void rpa_timeout(struct k_work *work) { bool adv_enabled = false; BT_DBG(""); if (IS_ENABLED(CONFIG_BT_CENTRAL)) { struct bt_conn *conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_CONNECT_SCAN); if (conn) { bt_conn_unref(conn); bt_le_create_conn_cancel(); } } le_rpa_invalidate(); bt_adv_foreach(adv_is_private_enabled, &adv_enabled); /* IF no roles using the RPA is running we can stop the RPA timer */ if (!(adv_enabled || atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING) || (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)))) { return; } le_update_private_addr(); } #endif /* CONFIG_BT_PRIVACY */ bool bt_le_scan_random_addr_check(void) { struct bt_le_ext_adv *adv; if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { /* Advertiser and scanner using different random address */ return true; } adv = bt_adv_lookup_legacy(); if (!adv) { return true; } /* If the advertiser is not enabled or not active there is no issue */ if (!IS_ENABLED(CONFIG_BT_BROADCASTER) || !atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return true; } /* When privacy is enabled the random address will not be set * immediately before starting the role, because the RPA might still be * valid and only updated on RPA timeout. */ if (IS_ENABLED(CONFIG_BT_PRIVACY)) { /* Cannot start scannor or initiator if the random address is * used by the advertiser for an RPA with a different identity * or for a random static identity address. */ if ((atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) && bt_dev.id_addr[adv->id].type == BT_ADDR_LE_RANDOM) || adv->id != BT_ID_DEFAULT) { return false; } } /* If privacy is not enabled then the random address will be attempted * to be set before enabling the role. If another role is already using * the random address then this command will fail, and should return * the error code to the application. */ return true; } static bool bt_le_adv_random_addr_check(const struct bt_le_adv_param *param) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { /* Advertiser and scanner using different random address */ return true; } /* If scanner roles are not enabled or not active there is no issue. */ if (!IS_ENABLED(CONFIG_BT_OBSERVER) || !(atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING) || atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING))) { return true; } /* When privacy is enabled the random address will not be set * immediately before starting the role, because the RPA might still be * valid and only updated on RPA timeout. */ if (IS_ENABLED(CONFIG_BT_PRIVACY)) { /* Cannot start an advertiser with random static identity or * using an RPA generated for a different identity than scanner * roles. */ if (((param->options & BT_LE_ADV_OPT_USE_IDENTITY) && bt_dev.id_addr[param->id].type == BT_ADDR_LE_RANDOM) || param->id != BT_ID_DEFAULT) { return false; } } else if (IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_RANDOM) { /* Scanning with random static identity. Stop the advertiser * from overwriting the passive scanner identity address. * In this case the LE Set Random Address command does not * protect us in the case of a passive scanner. * Explicitly stop it here. */ if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE) && (param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { /* Attempt to set non-connectable NRPA */ return false; } else if (bt_dev.id_addr[param->id].type == BT_ADDR_LE_RANDOM && param->id != BT_ID_DEFAULT) { /* Attempt to set connectable, or non-connectable with * identity different than scanner. */ return false; } } /* If privacy is not enabled then the random address will be attempted * to be set before enabling the role. If another role is already using * the random address then this command will fail, and should return * the error code to the application. */ return true; } #if defined(CONFIG_BT_OBSERVER) static int set_le_ext_scan_enable(u8_t enable, u16_t duration) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_ext_scan_enable *cp; struct cmd_state_set state; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); if (enable == BT_HCI_LE_SCAN_ENABLE) { cp->filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); } else { cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; } cp->enable = enable; cp->duration = sys_cpu_to_le16(duration); cp->period = 0; cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE); cmd(buf)->state = &state; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE, buf, NULL); #else u8_t filter_dup; if (enable == BT_HCI_LE_SCAN_ENABLE) { filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); } else { filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; } err = hci_api_le_ext_scan_enable(enable, filter_dup, sys_cpu_to_le16(duration), 0); if (!err) { atomic_set_bit_to(bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE); } #endif if (err) { return err; } return 0; } static int set_le_scan_enable_legacy(u8_t enable) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_scan_enable *cp; struct cmd_state_set state; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); if (enable == BT_HCI_LE_SCAN_ENABLE) { cp->filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); } else { cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; } cp->enable = enable; cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE); cmd(buf)->state = &state; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL); #else u8_t filter_dup; if (enable == BT_HCI_LE_SCAN_ENABLE) { filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); } else { filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; } err = hci_api_le_scan_enable(enable, filter_dup); if (!err) { atomic_set_bit_to(bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE); } #endif if (err) { return err; } return 0; } static int set_le_scan_enable(u8_t enable) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { return set_le_ext_scan_enable(enable, 0); } return set_le_scan_enable_legacy(enable); } #endif /* CONFIG_BT_OBSERVER */ static inline bool rpa_is_new(void) { #if defined(CONFIG_BT_PRIVACY) /* RPA is considered new if there is less than half a second since the * timeout was started. */ return k_delayed_work_remaining_get(&bt_dev.rpa_update) > (RPA_TIMEOUT_MS - 500); #else return false; #endif } static int hci_le_read_max_data_len(u16_t *tx_octets, u16_t *tx_time) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_rp_le_read_max_data_len *rp; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp); if (err) { BT_ERR("Failed to read DLE max data len"); return err; } rp = (void *)rsp->data; *tx_octets = sys_le16_to_cpu(rp->max_tx_octets); *tx_time = sys_le16_to_cpu(rp->max_tx_time); net_buf_unref(rsp); #else err = hci_api_le_get_max_data_len(tx_octets, tx_time); if (err) { BT_ERR("Failed to read DLE max data len"); return err; } #endif return 0; } #if (defined(CONFIG_BT_OBSERVER) && defined(CONFIG_BT_EXT_ADV)) \ || defined(CONFIG_BT_USER_PHY_UPDATE) static u8_t get_phy(u8_t hci_phy) { switch (hci_phy) { case BT_HCI_LE_PHY_1M: return BT_GAP_LE_PHY_1M; case BT_HCI_LE_PHY_2M: return BT_GAP_LE_PHY_2M; case BT_HCI_LE_PHY_CODED: return BT_GAP_LE_PHY_CODED; default: return 0; } } #endif /* (BT_OBSERVER && BT_EXT_ADV) || USER_PHY_UPDATE */ #if defined(CONFIG_BT_CONN) static void hci_acl(struct net_buf *buf) { struct bt_hci_acl_hdr *hdr; u16_t handle, len; struct bt_conn *conn; u8_t flags; BT_DBG("buf %p", buf); BT_ASSERT(buf->len >= sizeof(*hdr)); hdr = net_buf_pull_mem(buf, sizeof(*hdr)); len = sys_le16_to_cpu(hdr->len); handle = sys_le16_to_cpu(hdr->handle); flags = bt_acl_flags(handle); acl(buf)->handle = bt_acl_handle(handle); acl(buf)->index = BT_CONN_INDEX_INVALID; BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags); if (buf->len != len) { BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len); net_buf_unref(buf); return; } conn = bt_conn_lookup_handle(acl(buf)->handle); if (!conn) { BT_ERR("Unable to find conn for handle %u", acl(buf)->handle); net_buf_unref(buf); return; } acl(buf)->index = bt_conn_index(conn); bt_conn_recv(conn, buf, flags); bt_conn_unref(conn); } #if !defined(CONFIG_BT_USE_HCI_API) static void hci_data_buf_overflow(struct net_buf *buf) { struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data; BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type); } #endif void bt_hci_num_complete_packets(u16_t handle, u16_t count) { struct bt_conn *conn; unsigned int key; BT_DBG("handle %u count %u\n", handle, count); key = irq_lock(); conn = bt_conn_lookup_handle(handle); if (!conn) { irq_unlock(key); BT_ERR("No connection for handle %u", handle); return; } irq_unlock(key); while (count--) { struct bt_conn_tx *tx; sys_snode_t *node; key = irq_lock(); if (conn->pending_no_cb) { conn->pending_no_cb--; irq_unlock(key); k_sem_give(bt_conn_get_pkts(conn)); continue; } node = sys_slist_get(&conn->tx_pending); irq_unlock(key); if (!node) { BT_ERR("packets count mismatch"); break; } tx = CONTAINER_OF(node, struct bt_conn_tx, node); key = irq_lock(); conn->pending_no_cb = tx->pending_no_cb; tx->pending_no_cb = 0U; sys_slist_append(&conn->tx_complete, &tx->node); irq_unlock(key); k_work_submit(&conn->tx_complete_work); k_sem_give(bt_conn_get_pkts(conn)); } bt_conn_unref(conn); return; } static void hci_num_completed_packets(struct net_buf *buf) { struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data; int i; BT_DBG("num_handles %u", evt->num_handles); for (i = 0; i < evt->num_handles; i++) { u16_t handle, count; struct bt_conn *conn; unsigned int key; handle = sys_le16_to_cpu(evt->h[i].handle); count = sys_le16_to_cpu(evt->h[i].count); BT_DBG("handle %u count %u", handle, count); key = irq_lock(); conn = bt_conn_lookup_handle(handle); if (!conn) { irq_unlock(key); BT_ERR("No connection for handle %u", handle); continue; } irq_unlock(key); while (count--) { struct bt_conn_tx *tx; sys_snode_t *node; key = irq_lock(); if (conn->pending_no_cb) { conn->pending_no_cb--; irq_unlock(key); k_sem_give(bt_conn_get_pkts(conn)); continue; } node = sys_slist_get(&conn->tx_pending); irq_unlock(key); if (!node) { BT_ERR("packets count mismatch"); break; } tx = CONTAINER_OF(node, struct bt_conn_tx, node); key = irq_lock(); conn->pending_no_cb = tx->pending_no_cb; tx->pending_no_cb = 0U; sys_slist_append(&conn->tx_complete, &tx->node); irq_unlock(key); k_work_submit(&conn->tx_complete_work); k_sem_give(bt_conn_get_pkts(conn)); } bt_conn_unref(conn); } } static inline bool rpa_timeout_valid_check(void) { #if defined(CONFIG_BT_PRIVACY) /* Check if create conn timeout will happen before RPA timeout. */ return k_delayed_work_remaining_get(&bt_dev.rpa_update) > (10 * bt_dev.create_param.timeout); #else return true; #endif } #if defined(CONFIG_BT_CENTRAL) static int le_create_conn_set_random_addr(bool use_filter, u8_t *own_addr_type) { int err; if (IS_ENABLED(CONFIG_BT_PRIVACY)) { if (use_filter || rpa_timeout_valid_check()) { err = le_set_private_addr(BT_ID_DEFAULT); if (err) { return err; } } else { /* Force new RPA timeout so that RPA timeout is not * triggered while direct initiator is active. */ le_rpa_invalidate(); le_update_private_addr(); } if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { *own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; } else { *own_addr_type = BT_ADDR_LE_RANDOM; } } else { const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT]; /* If Static Random address is used as Identity address we * need to restore it before creating connection. Otherwise * NRPA used for active scan could be used for connection. */ if (addr->type == BT_ADDR_LE_RANDOM) { err = set_random_address(&addr->a); if (err) { return err; } } *own_addr_type = addr->type; } return 0; } static void set_phy_conn_param(const struct bt_conn *conn, struct bt_hci_ext_conn_phy *phy) { phy->conn_interval_min = sys_cpu_to_le16(conn->le.interval_min); phy->conn_interval_max = sys_cpu_to_le16(conn->le.interval_max); phy->conn_latency = sys_cpu_to_le16(conn->le.latency); phy->supervision_timeout = sys_cpu_to_le16(conn->le.timeout); phy->min_ce_len = 0; phy->max_ce_len = 0; } int bt_le_create_conn_ext(const struct bt_conn *conn) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_ext_create_conn *cp; struct bt_hci_ext_conn_phy *phy; struct cmd_state_set state; bool use_filter = false; struct net_buf *buf; u8_t own_addr_type; u8_t num_phys; int err; if (IS_ENABLED(CONFIG_BT_WHITELIST)) { use_filter = atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT); } err = le_create_conn_set_random_addr(use_filter, &own_addr_type); if (err) { return err; } num_phys = (!(bt_dev.create_param.options & BT_CONN_LE_OPT_NO_1M) ? 1 : 0) + ((bt_dev.create_param.options & BT_CONN_LE_OPT_CODED) ? 1 : 0); buf = bt_hci_cmd_create(BT_HCI_OP_LE_EXT_CREATE_CONN, sizeof(*cp) + num_phys * sizeof(*phy)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); (void)memset(cp, 0, sizeof(*cp)); if (use_filter) { /* User Initiated procedure use fast scan parameters. */ bt_addr_le_copy(&cp->peer_addr, BT_ADDR_LE_ANY); cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST; } else { const bt_addr_le_t *peer_addr = &conn->le.dst; #if defined(CONFIG_BT_SMP) if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { /* Host resolving is used, use the RPA directly. */ peer_addr = &conn->le.resp_addr; } #endif bt_addr_le_copy(&cp->peer_addr, peer_addr); cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_DIRECT; } cp->own_addr_type = own_addr_type; cp->phys = 0; if (!(bt_dev.create_param.options & BT_CONN_LE_OPT_NO_1M)) { cp->phys |= BT_HCI_LE_EXT_SCAN_PHY_1M; phy = net_buf_add(buf, sizeof(*phy)); phy->scan_interval = sys_cpu_to_le16( bt_dev.create_param.interval); phy->scan_window = sys_cpu_to_le16( bt_dev.create_param.window); set_phy_conn_param(conn, phy); } if (bt_dev.create_param.options & BT_CONN_LE_OPT_CODED) { cp->phys |= BT_HCI_LE_EXT_SCAN_PHY_CODED; phy = net_buf_add(buf, sizeof(*phy)); phy->scan_interval = sys_cpu_to_le16( bt_dev.create_param.interval_coded); phy->scan_window = sys_cpu_to_le16( bt_dev.create_param.window_coded); set_phy_conn_param(conn, phy); } cmd_state_set_init(&state, bt_dev.flags, BT_DEV_INITIATING, true); cmd(buf)->state = &state; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_EXT_CREATE_CONN, buf, NULL); #else bool use_filter = false; u8_t own_addr_type; u8_t num_phys; u8_t filter_policy; u8_t init_phys; int err; bt_addr_le_t peer_addr; if (IS_ENABLED(CONFIG_BT_WHITELIST)) { use_filter = atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT); } err = le_create_conn_set_random_addr(use_filter, &own_addr_type); if (err) { return err; } num_phys = (!(bt_dev.create_param.options & BT_CONN_LE_OPT_NO_1M) ? 1 : 0) + ((bt_dev.create_param.options & BT_CONN_LE_OPT_CODED) ? 1 : 0); struct ext_conn_phy_params_t phys[num_phys]; struct ext_conn_phy_params_t *phy = phys; memset(phy, 0, sizeof(struct ext_conn_phy_params_t) * num_phys); if (use_filter) { /* User Initiated procedure use fast scan parameters. */ bt_addr_le_copy(&peer_addr, BT_ADDR_LE_ANY); filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST; } else { const bt_addr_le_t *ppeer_addr = &conn->le.dst; #if defined(CONFIG_BT_SMP) if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { /* Host resolving is used, use the RPA directly. */ ppeer_addr = &conn->le.resp_addr; } #endif bt_addr_le_copy(&peer_addr, ppeer_addr); filter_policy = BT_HCI_LE_CREATE_CONN_FP_DIRECT; } init_phys = 0; if (!(bt_dev.create_param.options & BT_CONN_LE_OPT_NO_1M)) { init_phys |= BT_HCI_LE_EXT_SCAN_PHY_1M; phy->scan_interval = bt_dev.create_param.interval; phy->scan_window = bt_dev.create_param.window; phy->conn_interval_min = conn->le.interval_min; phy->conn_interval_max = conn->le.interval_max; phy->conn_latency = conn->le.latency; phy->supervision_timeout = conn->le.timeout; phy->min_ce_len = 0; phy->max_ce_len = 0; phy++; } if (bt_dev.create_param.options & BT_CONN_LE_OPT_CODED) { init_phys |= BT_HCI_LE_EXT_SCAN_PHY_CODED; phy->scan_interval = bt_dev.create_param.interval_coded; phy->scan_window = bt_dev.create_param.window_coded; phy->conn_interval_min = conn->le.interval_min; phy->conn_interval_max = conn->le.interval_max; phy->conn_latency = conn->le.latency; phy->supervision_timeout = conn->le.timeout; phy->min_ce_len = 0; phy->max_ce_len = 0; } err = hci_api_le_create_conn_ext(filter_policy, own_addr_type, peer_addr.type, peer_addr.a.val, init_phys, phys); if (!err) { atomic_set_bit_to(bt_dev.flags, BT_DEV_INITIATING, true); } return err; #endif } int bt_le_create_conn_legacy(const struct bt_conn *conn) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_create_conn *cp; struct cmd_state_set state; bool use_filter = false; struct net_buf *buf; u8_t own_addr_type; int err; if (IS_ENABLED(CONFIG_BT_WHITELIST)) { use_filter = atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT); } err = le_create_conn_set_random_addr(use_filter, &own_addr_type); if (err) { return err; } buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memset(cp, 0, sizeof(*cp)); cp->own_addr_type = own_addr_type; if (use_filter) { /* User Initiated procedure use fast scan parameters. */ bt_addr_le_copy(&cp->peer_addr, BT_ADDR_LE_ANY); cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST; } else { const bt_addr_le_t *peer_addr = &conn->le.dst; #if defined(CONFIG_BT_SMP) if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { /* Host resolving is used, use the RPA directly. */ peer_addr = &conn->le.resp_addr; } #endif bt_addr_le_copy(&cp->peer_addr, peer_addr); cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_DIRECT; } cp->scan_interval = sys_cpu_to_le16(bt_dev.create_param.interval); cp->scan_window = sys_cpu_to_le16(bt_dev.create_param.window); cp->conn_interval_min = sys_cpu_to_le16(conn->le.interval_min); cp->conn_interval_max = sys_cpu_to_le16(conn->le.interval_max); cp->conn_latency = sys_cpu_to_le16(conn->le.latency); cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout); cmd_state_set_init(&state, bt_dev.flags, BT_DEV_INITIATING, true); cmd(buf)->state = &state; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL); #else bool use_filter = false; u8_t own_addr_type; u8_t filter_policy; bt_addr_le_t peer_addr; int err; if (IS_ENABLED(CONFIG_BT_WHITELIST)) { use_filter = atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT); } err = le_create_conn_set_random_addr(use_filter, &own_addr_type); if (err) { return err; } if (use_filter) { /* User Initiated procedure use fast scan parameters. */ bt_addr_le_copy(&peer_addr, BT_ADDR_LE_ANY); filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST; } else { const bt_addr_le_t *ppeer_addr = &conn->le.dst; #if defined(CONFIG_BT_SMP) if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { /* Host resolving is used, use the RPA directly. */ ppeer_addr = &conn->le.resp_addr; } #endif bt_addr_le_copy(&peer_addr, ppeer_addr); filter_policy = BT_HCI_LE_CREATE_CONN_FP_DIRECT; } err = hci_api_le_create_conn(bt_dev.create_param.interval, bt_dev.create_param.window, filter_policy, peer_addr.type, peer_addr.a.val, own_addr_type, conn->le.interval_min, conn->le.interval_max, conn->le.latency, conn->le.timeout, 0, 0); if (!err) { atomic_set_bit_to(bt_dev.flags, BT_DEV_INITIATING, true); } return err; #endif } int bt_le_create_conn(const struct bt_conn *conn) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { return bt_le_create_conn_ext(conn); } return bt_le_create_conn_legacy(conn); } int bt_le_create_conn_cancel(void) { #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *buf; struct cmd_state_set state; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0); cmd_state_set_init(&state, bt_dev.flags, BT_DEV_INITIATING, false); cmd(buf)->state = &state; return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL); #else int err; err = hci_api_le_create_conn_cancel(); if (!err) { atomic_set_bit_to(bt_dev.flags, BT_DEV_INITIATING, false); } return err; #endif } #endif /* CONFIG_BT_CENTRAL */ int bt_hci_disconnect(u16_t handle, u8_t reason) { #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *buf; struct bt_hci_cp_disconnect *disconn; buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn)); if (!buf) { return -ENOBUFS; } disconn = net_buf_add(buf, sizeof(*disconn)); disconn->handle = sys_cpu_to_le16(handle); disconn->reason = reason; return bt_hci_cmd_send(BT_HCI_OP_DISCONNECT, buf); #else return hci_api_le_disconnect(handle, reason); #endif } static void hci_disconn_complete(struct net_buf *buf) { struct bt_hci_evt_disconn_complete *evt = (void *)buf->data; u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_conn *conn; BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle, evt->reason); if (evt->status) { return; } conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to look up conn with handle %u", handle); goto advertise; } conn->err = evt->reason; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); conn->handle = 0U; if (conn->type != BT_CONN_TYPE_LE) { #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_SCO) { bt_sco_cleanup(conn); return; } /* * If only for one connection session bond was set, clear keys * database row for this connection. */ if (conn->type == BT_CONN_TYPE_BR && atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) { bt_keys_link_key_clear(conn->br.link_key); } #endif bt_conn_unref(conn); return; } #if defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST) if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); bt_le_scan_update(false); } #endif /* defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST) */ //bt_conn_unref(conn); advertise: if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { bt_le_adv_resume(); } } static int hci_le_read_remote_features(struct bt_conn *conn) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_read_remote_features *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf); #else hci_api_le_read_remote_features(conn->handle); #endif return 0; } static int hci_read_remote_version(struct bt_conn *conn) { if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } /* Remote version cannot change. */ if (atomic_test_bit(conn->flags, BT_CONN_AUTO_VERSION_INFO)) { return 0; } #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_read_remote_version_info *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_VERSION_INFO, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); return bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_VERSION_INFO, buf, NULL); #else return hci_api_le_read_remote_version(conn->handle); #endif } /* LE Data Length Change Event is optional so this function just ignore * error and stack will continue to use default values. */ int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_data_len *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); cp->tx_octets = sys_cpu_to_le16(tx_octets); cp->tx_time = sys_cpu_to_le16(tx_time); return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf); #else return hci_api_le_set_data_len(conn->handle, tx_octets, tx_time); #endif } #if defined(CONFIG_BT_USER_PHY_UPDATE) static int hci_le_read_phy(struct bt_conn *conn) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_read_phy *cp; struct bt_hci_rp_le_read_phy *rp; struct net_buf *buf, *rsp; int err; buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_PHY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_PHY, buf, &rsp); if (err) { return err; } rp = (void *)rsp->data; conn->le.phy.tx_phy = get_phy(rp->tx_phy); conn->le.phy.rx_phy = get_phy(rp->rx_phy); net_buf_unref(rsp); #else u8_t tx_phy; u8_t rx_phy; err = hci_api_le_read_phy(conn->handle, &tx_phy, &rx_phy); if (err) { return err; } conn->le.phy.tx_phy = get_phy(tx_phy); conn->le.phy.rx_phy = get_phy(rx_phy); #endif return 0; } #endif /* defined(CONFIG_BT_USER_PHY_UPDATE) */ int bt_le_set_phy(struct bt_conn *conn, u8_t pref_tx_phy, u8_t pref_rx_phy) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_phy *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); cp->all_phys = 0U; cp->tx_phys = pref_tx_phy; cp->rx_phys = pref_rx_phy; cp->phy_opts = BT_HCI_LE_PHY_CODED_ANY; return bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf); #else return hci_api_le_set_phy(conn->handle, 0U, pref_tx_phy, pref_rx_phy, BT_HCI_LE_PHY_CODED_ANY); #endif } static void slave_update_conn_param(struct bt_conn *conn) { if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) { return; } /* don't start timer again on PHY update etc */ if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) { return; } /* * Core 4.2 Vol 3, Part C, 9.3.12.2 * The Peripheral device should not perform a Connection Parameter * Update procedure within 5 s after establishing a connection. */ k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT); } #if defined(CONFIG_BT_SMP) static void pending_id_update(struct bt_keys *keys, void *data) { if (keys->state & BT_KEYS_ID_PENDING_ADD) { keys->state &= ~BT_KEYS_ID_PENDING_ADD; bt_id_add(keys); return; } if (keys->state & BT_KEYS_ID_PENDING_DEL) { keys->state &= ~BT_KEYS_ID_PENDING_DEL; bt_id_del(keys); return; } } static void pending_id_keys_update_set(struct bt_keys *keys, u8_t flag) { atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING); keys->state |= flag; } static void pending_id_keys_update(void) { if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) { if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_PRIVACY)) { bt_keys_foreach(BT_KEYS_ALL, pending_id_update, NULL); } else { bt_keys_foreach(BT_KEYS_IRK, pending_id_update, NULL); } } } #endif /* defined(CONFIG_BT_SMP) */ static struct bt_conn *find_pending_connect(u8_t role, bt_addr_le_t *peer_addr) { struct bt_conn *conn; /* * Make lookup to check if there's a connection object in * CONNECT or CONNECT_AUTO state associated with passed peer LE address. */ if (IS_ENABLED(CONFIG_BT_CENTRAL) && role == BT_HCI_ROLE_MASTER) { conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, peer_addr, BT_CONN_CONNECT); if (IS_ENABLED(CONFIG_BT_WHITELIST) && !conn) { conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE, BT_CONN_CONNECT_AUTO); } return conn; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && role == BT_HCI_ROLE_SLAVE) { conn = bt_conn_lookup_state_le(bt_dev.adv_conn_id, peer_addr, BT_CONN_CONNECT_DIR_ADV); if (!conn) { conn = bt_conn_lookup_state_le(bt_dev.adv_conn_id, BT_ADDR_LE_NONE, BT_CONN_CONNECT_ADV); } return conn; } return NULL; } static void conn_auto_initiate(struct bt_conn *conn) { int err; if (conn->state != BT_CONN_CONNECTED) { /* It is possible that connection was disconnected directly from * connected callback so we must check state before doing * connection parameters update. */ return; } if (!atomic_test_bit(conn->flags, BT_CONN_AUTO_FEATURE_EXCH) && ((conn->role == BT_HCI_ROLE_MASTER) || BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features))) { err = hci_le_read_remote_features(conn); if (!err) { return; } } if (IS_ENABLED(CONFIG_BT_REMOTE_VERSION) && !atomic_test_bit(conn->flags, BT_CONN_AUTO_VERSION_INFO)) { err = hci_read_remote_version(conn); if (!err) { return; } } if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && !atomic_test_bit(conn->flags, BT_CONN_AUTO_PHY_COMPLETE) && BT_FEAT_LE_PHY_2M(bt_dev.le.features)) { err = bt_le_set_phy(conn, BT_HCI_LE_PHY_PREFER_2M, BT_HCI_LE_PHY_PREFER_2M); if (!err) { atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE); return; } BT_ERR("Failed to set LE PHY (%d)", err); } if (IS_ENABLED(CONFIG_BT_AUTO_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) { u16_t tx_octets, tx_time; err = hci_le_read_max_data_len(&tx_octets, &tx_time); if (!err) { err = bt_le_set_data_len(conn, tx_octets, tx_time); if (err) { BT_ERR("Failed to set data len (%d)", err); } } } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) { slave_update_conn_param(conn); } } static void le_conn_complete_cancel(void) { struct bt_conn *conn; /* Handle create connection cancel. * * There is no need to check ID address as only one * connection in master role can be in pending state. */ conn = find_pending_connect(BT_HCI_ROLE_MASTER, NULL); if (!conn) { BT_ERR("No pending master connection"); return; } conn->err = BT_HCI_ERR_UNKNOWN_CONN_ID; /* Handle cancellation of outgoing connection attempt. */ if (!IS_ENABLED(CONFIG_BT_WHITELIST)) { /* We notify before checking autoconnect flag * as application may choose to change it from * callback. */ bt_conn_set_state(conn, BT_CONN_DISCONNECTED); /* Check if device is marked for autoconnect. */ if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { /* Restart passive scanner for device */ bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); } } else { if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { /* Restart whitelist initiator after RPA timeout. */ bt_le_create_conn(conn); } else { /* Create connection canceled by timeout */ bt_conn_set_state(conn, BT_CONN_DISCONNECTED); } } bt_conn_unref(conn); } static void le_conn_complete_adv_timeout(void) { if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); struct bt_conn *conn; /* Handle advertising timeout after high duty cycle directed * advertising. */ atomic_clear_bit(adv->flags, BT_ADV_ENABLED); /* There is no need to check ID address as only one * connection in slave role can be in pending state. */ conn = find_pending_connect(BT_HCI_ROLE_SLAVE, NULL); if (!conn) { BT_ERR("No pending slave connection"); return; } conn->err = BT_HCI_ERR_ADV_TIMEOUT; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); } } static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt) { u16_t handle = sys_le16_to_cpu(evt->handle); bt_addr_le_t peer_addr, id_addr; struct bt_conn *conn; BT_DBG("status 0x%02x handle %u role %u peer %s peer RPA %s", evt->status, handle, evt->role, bt_addr_le_str(&evt->peer_addr), bt_addr_str(&evt->peer_rpa)); BT_DBG("local RPA %s", bt_addr_str(&evt->local_rpa)); #if defined(CONFIG_BT_SMP) pending_id_keys_update(); #endif if (evt->status) { if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && evt->status == BT_HCI_ERR_ADV_TIMEOUT) { le_conn_complete_adv_timeout(); return; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && evt->status == BT_HCI_ERR_UNKNOWN_CONN_ID) { le_conn_complete_cancel(); bt_le_scan_update(false); return; } BT_WARN("Unexpected status 0x%02x", evt->status); return; } /* Translate "enhanced" identity address type to normal one */ if (evt->peer_addr.type == BT_ADDR_LE_PUBLIC_ID || evt->peer_addr.type == BT_ADDR_LE_RANDOM_ID) { bt_addr_le_copy(&id_addr, &evt->peer_addr); id_addr.type -= BT_ADDR_LE_PUBLIC_ID; bt_addr_copy(&peer_addr.a, &evt->peer_rpa); peer_addr.type = BT_ADDR_LE_RANDOM; } else { u8_t id = evt->role == BT_HCI_ROLE_SLAVE ? bt_dev.adv_conn_id : BT_ID_DEFAULT; bt_addr_le_copy(&id_addr, bt_lookup_id_addr(id, &evt->peer_addr)); bt_addr_le_copy(&peer_addr, &evt->peer_addr); } conn = find_pending_connect(evt->role, &id_addr); if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && evt->role == BT_HCI_ROLE_SLAVE && !(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); /* Clear advertising even if we are not able to add connection * object to keep host in sync with controller state. */ atomic_clear_bit(adv->flags, BT_ADV_ENABLED); } if (IS_ENABLED(CONFIG_BT_CENTRAL) && evt->role == BT_HCI_ROLE_MASTER) { /* Clear initiating even if we are not able to add connection * object to keep the host in sync with controller state. */ atomic_clear_bit(bt_dev.flags, BT_DEV_INITIATING); } if (!conn) { BT_ERR("Unable to add new conn for handle %u", handle); bt_hci_disconnect(handle, BT_HCI_ERR_MEM_CAPACITY_EXCEEDED); return; } conn->handle = handle; bt_addr_le_copy(&conn->le.dst, &id_addr); conn->le.interval = sys_le16_to_cpu(evt->interval); conn->le.latency = sys_le16_to_cpu(evt->latency); conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout); conn->role = evt->role; conn->err = 0U; #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) conn->le.data_len.tx_max_len = BT_GAP_DATA_LEN_DEFAULT; conn->le.data_len.tx_max_time = BT_GAP_DATA_TIME_DEFAULT; conn->le.data_len.rx_max_len = BT_GAP_DATA_LEN_DEFAULT; conn->le.data_len.rx_max_time = BT_GAP_DATA_TIME_DEFAULT; #endif #if defined(CONFIG_BT_USER_PHY_UPDATE) conn->le.phy.tx_phy = BT_GAP_LE_PHY_1M; conn->le.phy.rx_phy = BT_GAP_LE_PHY_1M; #endif /* * Use connection address (instead of identity address) as initiator * or responder address. Only slave needs to be updated. For master all * was set during outgoing connection creation. */ if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_HCI_ROLE_SLAVE) { bt_addr_le_copy(&conn->le.init_addr, &peer_addr); if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); if (IS_ENABLED(CONFIG_BT_PRIVACY) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { conn->le.resp_addr.type = BT_ADDR_LE_RANDOM; if (bt_addr_cmp(&evt->local_rpa, BT_ADDR_ANY) != 0) { bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); } else { bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a); } } else { bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]); } } else { /* Copy the local RPA and handle this in advertising set * terminated event. */ bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); } /* if the controller supports, lets advertise for another * slave connection. * check for connectable advertising state is sufficient as * this is how this le connection complete for slave occurred. */ if (BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) { bt_le_adv_resume(); } if (IS_ENABLED(CONFIG_BT_EXT_ADV) && !BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); /* No advertising set terminated event, must be a * legacy advertiser set. */ if (!atomic_test_bit(adv->flags, BT_ADV_PERSIST)) { adv_delete_legacy(); } } } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER) { bt_addr_le_copy(&conn->le.resp_addr, &peer_addr); if (IS_ENABLED(CONFIG_BT_PRIVACY)) { conn->le.init_addr.type = BT_ADDR_LE_RANDOM; if (bt_addr_cmp(&evt->local_rpa, BT_ADDR_ANY) != 0) { bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa); } else { bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a); } } else { bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]); } } #if defined(CONFIG_BT_USER_PHY_UPDATE) if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { int err; err = hci_le_read_phy(conn); if (err) { BT_WARN("Failed to read PHY (%d)", err); } else { if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && conn->le.phy.tx_phy == BT_HCI_LE_PHY_PREFER_2M && conn->le.phy.rx_phy == BT_HCI_LE_PHY_PREFER_2M) { /* Already on 2M, skip auto-phy update. */ atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_COMPLETE); } } } #endif /* defined(CONFIG_BT_USER_PHY_UPDATE) */ bt_conn_set_state(conn, BT_CONN_CONNECTED); /* Start auto-initiated procedures */ conn_auto_initiate(conn); bt_conn_unref(conn); if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER) { bt_le_scan_update(false); } } static void le_enh_conn_complete(struct net_buf *buf) { enh_conn_complete((void *)buf->data); } static void le_legacy_conn_complete(struct net_buf *buf) { struct bt_hci_evt_le_conn_complete *evt = (void *)buf->data; struct bt_hci_evt_le_enh_conn_complete enh; BT_DBG("status 0x%02x role %u %s", evt->status, evt->role, bt_addr_le_str(&evt->peer_addr)); enh.status = evt->status; enh.handle = evt->handle; enh.role = evt->role; enh.interval = evt->interval; enh.latency = evt->latency; enh.supv_timeout = evt->supv_timeout; enh.clock_accuracy = evt->clock_accuracy; bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr); if (IS_ENABLED(CONFIG_BT_PRIVACY)) { bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a); } else { bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY); } bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY); enh_conn_complete(&enh); } static void le_remote_feat_complete(struct net_buf *buf) { struct bt_hci_evt_le_remote_feat_complete *evt = (void *)buf->data; u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_conn *conn; conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to lookup conn for handle %u", handle); return; } if (!evt->status) { memcpy(conn->le.features, evt->features, sizeof(conn->le.features)); } atomic_set_bit(conn->flags, BT_CONN_AUTO_FEATURE_EXCH); if (IS_ENABLED(CONFIG_BT_REMOTE_INFO) && !IS_ENABLED(CONFIG_BT_REMOTE_VERSION)) { notify_remote_info(conn); } /* Continue with auto-initiated procedures */ conn_auto_initiate(conn); bt_conn_unref(conn); } #if defined(CONFIG_BT_DATA_LEN_UPDATE) static void le_data_len_change(struct net_buf *buf) { struct bt_hci_evt_le_data_len_change *evt = (void *)buf->data; u16_t max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets); u16_t max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets); u16_t max_tx_time = sys_le16_to_cpu(evt->max_tx_time); u16_t max_rx_time = sys_le16_to_cpu(evt->max_rx_time); u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_conn *conn; conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to lookup conn for handle %u", handle); return; } BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets, max_tx_time, max_rx_octets, max_rx_time); bt_dev.le.mtu = max_tx_octets; #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) if (IS_ENABLED(CONFIG_BT_AUTO_DATA_LEN_UPDATE)) { atomic_set_bit(conn->flags, BT_CONN_AUTO_DATA_LEN_COMPLETE); } conn->le.data_len.tx_max_len = max_tx_octets; conn->le.data_len.tx_max_time = max_tx_time; conn->le.data_len.rx_max_len = max_rx_octets; conn->le.data_len.rx_max_time = max_rx_time; notify_le_data_len_updated(conn); #endif (void)max_tx_octets; (void)max_rx_octets; (void)max_tx_time; (void)max_rx_time; bt_conn_unref(conn); } #endif /* CONFIG_BT_DATA_LEN_UPDATE */ #if defined(CONFIG_BT_PHY_UPDATE) static void le_phy_update_complete(struct net_buf *buf) { struct bt_hci_evt_le_phy_update_complete *evt = (void *)buf->data; u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_conn *conn; conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to lookup conn for handle %u", handle); return; } BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u", evt->status, evt->tx_phy, evt->rx_phy); if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) { atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_COMPLETE); /* Continue with auto-initiated procedures */ conn_auto_initiate(conn); } #if defined(CONFIG_BT_USER_PHY_UPDATE) conn->le.phy.tx_phy = get_phy(evt->tx_phy); conn->le.phy.rx_phy = get_phy(evt->rx_phy); notify_le_phy_updated(conn); #endif bt_conn_unref(conn); } #endif /* CONFIG_BT_PHY_UPDATE */ bool bt_le_conn_params_valid(const struct bt_le_conn_param *param) { /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */ if (param->interval_min > param->interval_max || param->interval_min < 6 || param->interval_max > 3200) { return false; } if (param->latency > 499) { return false; } if (param->timeout < 10 || param->timeout > 3200 || ((param->timeout * 4U) <= ((1U + param->latency) * param->interval_max))) { return false; } return true; } static void le_conn_param_neg_reply(u16_t handle, u8_t reason) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_conn_param_req_neg_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, sizeof(*cp)); if (!buf) { BT_ERR("Unable to allocate buffer"); return; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); cp->reason = sys_cpu_to_le16(reason); bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf); #else hci_api_le_conn_param_neg_reply(handle, reason); #endif } static int le_conn_param_req_reply(u16_t handle, const struct bt_le_conn_param *param) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_conn_param_req_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); (void)memset(cp, 0, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); cp->interval_min = sys_cpu_to_le16(param->interval_min); cp->interval_max = sys_cpu_to_le16(param->interval_max); cp->latency = sys_cpu_to_le16(param->latency); cp->timeout = sys_cpu_to_le16(param->timeout); return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf); #else return hci_api_le_conn_param_req_reply(handle, param->interval_min,param->interval_max, param->latency,param->timeout, 0, 0 ); #endif } static void le_conn_param_req(struct net_buf *buf) { struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data; struct bt_le_conn_param param; struct bt_conn *conn; u16_t handle; handle = sys_le16_to_cpu(evt->handle); param.interval_min = sys_le16_to_cpu(evt->interval_min); param.interval_max = sys_le16_to_cpu(evt->interval_max); param.latency = sys_le16_to_cpu(evt->latency); param.timeout = sys_le16_to_cpu(evt->timeout); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to lookup conn for handle %u", handle); le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID); return; } if (!le_param_req(conn, &param)) { le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM); } else { le_conn_param_req_reply(handle, &param); } bt_conn_unref(conn); } static void le_conn_update_complete(struct net_buf *buf) { struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data; struct bt_conn *conn; u16_t handle; handle = sys_le16_to_cpu(evt->handle); BT_DBG("status 0x%02x, handle %u", evt->status, handle); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to lookup conn for handle %u", handle); return; } if (!evt->status) { conn->le.interval = sys_le16_to_cpu(evt->interval); conn->le.latency = sys_le16_to_cpu(evt->latency); conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout); notify_le_param_updated(conn); } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE && conn->role == BT_HCI_ROLE_SLAVE && !atomic_test_and_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) { /* CPR not supported, let's try L2CAP CPUP instead */ struct bt_le_conn_param param; param.interval_min = conn->le.interval_min; param.interval_max = conn->le.interval_max; param.latency = conn->le.pending_latency; param.timeout = conn->le.pending_timeout; bt_l2cap_update_conn_param(conn, &param); } bt_conn_unref(conn); } #if defined(CONFIG_BT_CENTRAL) static void check_pending_conn(const bt_addr_le_t *id_addr, const bt_addr_le_t *addr, u8_t adv_props) { struct bt_conn *conn; /* No connections are allowed during explicit scanning */ if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { return; } /* Return if event is not connectable */ if (!(adv_props & BT_HCI_LE_ADV_EVT_TYPE_CONN)) { return; } conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, id_addr, BT_CONN_CONNECT_SCAN); if (!conn) { return; } if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) { goto failed; } bt_addr_le_copy(&conn->le.resp_addr, addr); if (bt_le_create_conn(conn)) { goto failed; } bt_conn_set_state(conn, BT_CONN_CONNECT); bt_conn_unref(conn); return; failed: conn->err = BT_HCI_ERR_UNSPECIFIED; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); bt_le_scan_update(false); } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) static int set_flow_control(void) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_host_buffer_size *hbs; struct net_buf *buf; int err; /* Check if host flow control is actually supported */ if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { BT_WARN("Controller to host flow control not supported"); return 0; } buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE, sizeof(*hbs)); if (!buf) { return -ENOBUFS; } hbs = net_buf_add(buf, sizeof(*hbs)); (void)memset(hbs, 0, sizeof(*hbs)); hbs->acl_mtu = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU + sizeof(struct bt_l2cap_hdr)); hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT); err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL); if (err) { return err; } buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE); return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL); #else int err; /* Check if host flow control is actually supported */ if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { BT_WARN("Controller to host flow control not supported"); return 0; } err = hci_api_set_host_buffer_size(CONFIG_BT_L2CAP_RX_MTU+sizeof(struct bt_l2cap_hdr), 0, CONFIG_BT_ACL_RX_COUNT, 0); if (err) { return err; } return hci_api_set_host_flow_enable(BT_HCI_CTL_TO_HOST_FLOW_ENABLE); #endif } #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */ static void unpair(u8_t id, const bt_addr_le_t *addr) { struct bt_keys *keys = NULL; struct bt_conn *conn = bt_conn_lookup_addr_le(id, addr); if (conn) { /* Clear the conn->le.keys pointer since we'll invalidate it, * and don't want any subsequent code (like disconnected * callbacks) accessing it. */ if (conn->type == BT_CONN_TYPE_LE) { keys = conn->le.keys; conn->le.keys = NULL; } bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); bt_conn_unref(conn); } if (IS_ENABLED(CONFIG_BT_BREDR)) { /* LE Public may indicate BR/EDR as well */ if (addr->type == BT_ADDR_LE_PUBLIC) { bt_keys_link_key_clear_addr(&addr->a); } } if (IS_ENABLED(CONFIG_BT_SMP)) { if (!keys) { keys = bt_keys_find_addr(id, addr); } if (keys) { bt_keys_clear(keys); } } bt_gatt_clear(id, addr); } static void unpair_remote(const struct bt_bond_info *info, void *data) { u8_t *id = (u8_t *) data; unpair(*id, &info->addr); } int bt_unpair(u8_t id, const bt_addr_le_t *addr) { if (id >= CONFIG_BT_ID_MAX) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_SMP) && (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY))) { bt_foreach_bond(id, unpair_remote, &id); return 0; } unpair(id, addr); return 0; } #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) static enum bt_security_err security_err_get(u8_t hci_err) { switch (hci_err) { case BT_HCI_ERR_SUCCESS: return BT_SECURITY_ERR_SUCCESS; case BT_HCI_ERR_AUTH_FAIL: return BT_SECURITY_ERR_AUTH_FAIL; case BT_HCI_ERR_PIN_OR_KEY_MISSING: return BT_SECURITY_ERR_PIN_OR_KEY_MISSING; case BT_HCI_ERR_PAIRING_NOT_SUPPORTED: return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED; case BT_HCI_ERR_PAIRING_NOT_ALLOWED: return BT_SECURITY_ERR_PAIR_NOT_ALLOWED; case BT_HCI_ERR_INVALID_PARAM: return BT_SECURITY_ERR_INVALID_PARAM; default: return BT_SECURITY_ERR_UNSPECIFIED; } } static void reset_pairing(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING); atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR); atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE); } #endif /* CONFIG_BT_BREDR */ /* Reset required security level to current operational */ conn->required_sec_level = conn->sec_level; } #endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */ #if defined(CONFIG_BT_BREDR) static int reject_conn(const bt_addr_t *bdaddr, u8_t reason) { struct bt_hci_cp_reject_conn_req *cp; struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); cp->reason = reason; err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL); if (err) { return err; } return 0; } static int accept_sco_conn(const bt_addr_t *bdaddr, struct bt_conn *sco_conn) { struct bt_hci_cp_accept_sync_conn_req *cp; struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); cp->pkt_type = sco_conn->sco.pkt_type; cp->tx_bandwidth = 0x00001f40; cp->rx_bandwidth = 0x00001f40; cp->max_latency = 0x0007; cp->retrans_effort = 0x01; cp->content_format = BT_VOICE_CVSD_16BIT; err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL); if (err) { return err; } return 0; } static int accept_conn(const bt_addr_t *bdaddr) { struct bt_hci_cp_accept_conn_req *cp; struct net_buf *buf; int err; buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); cp->role = BT_HCI_ROLE_SLAVE; err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL); if (err) { return err; } return 0; } static void bt_esco_conn_req(struct bt_hci_evt_conn_request *evt) { struct bt_conn *sco_conn; sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type); if (!sco_conn) { reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES); return; } if (accept_sco_conn(&evt->bdaddr, sco_conn)) { BT_ERR("Error accepting connection from %s", bt_addr_str(&evt->bdaddr)); reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED); bt_sco_cleanup(sco_conn); return; } sco_conn->role = BT_HCI_ROLE_SLAVE; bt_conn_set_state(sco_conn, BT_CONN_CONNECT); bt_conn_unref(sco_conn); } static void conn_req(struct net_buf *buf) { struct bt_hci_evt_conn_request *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr), evt->link_type); if (evt->link_type != BT_HCI_ACL) { bt_esco_conn_req(evt); return; } conn = bt_conn_add_br(&evt->bdaddr); if (!conn) { reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES); return; } accept_conn(&evt->bdaddr); conn->role = BT_HCI_ROLE_SLAVE; bt_conn_set_state(conn, BT_CONN_CONNECT); bt_conn_unref(conn); } static bool br_sufficient_key_size(struct bt_conn *conn) { struct bt_hci_cp_read_encryption_key_size *cp; struct bt_hci_rp_read_encryption_key_size *rp; struct net_buf *buf, *rsp; u8_t key_size; int err; buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, sizeof(*cp)); if (!buf) { BT_ERR("Failed to allocate command buffer"); return false; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(conn->handle); err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, buf, &rsp); if (err) { BT_ERR("Failed to read encryption key size (err %d)", err); return false; } if (rsp->len < sizeof(*rp)) { BT_ERR("Too small command complete for encryption key size"); net_buf_unref(rsp); return false; } rp = (void *)rsp->data; key_size = rp->key_size; net_buf_unref(rsp); BT_DBG("Encryption key size is %u", key_size); if (conn->sec_level == BT_SECURITY_L4) { return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX; } return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN; } static bool update_sec_level_br(struct bt_conn *conn) { if (!conn->encrypt) { conn->sec_level = BT_SECURITY_L1; return true; } if (conn->br.link_key) { if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) { if (conn->encrypt == 0x02) { conn->sec_level = BT_SECURITY_L4; } else { conn->sec_level = BT_SECURITY_L3; } } else { conn->sec_level = BT_SECURITY_L2; } } else { BT_WARN("No BR/EDR link key found"); conn->sec_level = BT_SECURITY_L2; } if (!br_sufficient_key_size(conn)) { BT_ERR("Encryption key size is not sufficient"); bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); return false; } if (conn->required_sec_level > conn->sec_level) { BT_ERR("Failed to set required security level"); bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); return false; } return true; } static void synchronous_conn_complete(struct net_buf *buf) { struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data; struct bt_conn *sco_conn; u16_t handle = sys_le16_to_cpu(evt->handle); BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, evt->link_type); sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr); if (!sco_conn) { BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); return; } if (evt->status) { sco_conn->err = evt->status; bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED); bt_conn_unref(sco_conn); return; } sco_conn->handle = handle; bt_conn_set_state(sco_conn, BT_CONN_CONNECTED); bt_conn_unref(sco_conn); } static void conn_complete(struct net_buf *buf) { struct bt_hci_evt_conn_complete *evt = (void *)buf->data; struct bt_conn *conn; struct bt_hci_cp_read_remote_features *cp; u16_t handle = sys_le16_to_cpu(evt->handle); BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, evt->link_type); conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); return; } if (evt->status) { conn->err = evt->status; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); return; } conn->handle = handle; conn->err = 0U; conn->encrypt = evt->encr_enabled; if (!update_sec_level_br(conn)) { bt_conn_unref(conn); return; } bt_conn_set_state(conn, BT_CONN_CONNECTED); bt_conn_unref(conn); buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp)); if (!buf) { return; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = evt->handle; bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL); } static void pin_code_req(struct net_buf *buf) { struct bt_hci_evt_pin_code_req *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG(""); conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } bt_conn_pin_code_req(conn); bt_conn_unref(conn); } static void link_key_notify(struct net_buf *buf) { struct bt_hci_evt_link_key_notify *evt = (void *)buf->data; struct bt_conn *conn; conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type); if (!conn->br.link_key) { conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr); } if (!conn->br.link_key) { BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr)); bt_conn_unref(conn); return; } /* clear any old Link Key flags */ conn->br.link_key->flags = 0U; switch (evt->key_type) { case BT_LK_COMBINATION: /* * Setting Combination Link Key as AUTHENTICATED means it was * successfully generated by 16 digits wide PIN code. */ if (atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE)) { conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; } memcpy(conn->br.link_key->val, evt->link_key, 16); break; case BT_LK_AUTH_COMBINATION_P192: conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; /* fall through */ case BT_LK_UNAUTH_COMBINATION_P192: /* Mark no-bond so that link-key is removed on disconnection */ if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) { atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND); } memcpy(conn->br.link_key->val, evt->link_key, 16); break; case BT_LK_AUTH_COMBINATION_P256: conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; /* fall through */ case BT_LK_UNAUTH_COMBINATION_P256: conn->br.link_key->flags |= BT_LINK_KEY_SC; /* Mark no-bond so that link-key is removed on disconnection */ if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) { atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND); } memcpy(conn->br.link_key->val, evt->link_key, 16); break; default: BT_WARN("Unsupported Link Key type %u", evt->key_type); (void)memset(conn->br.link_key->val, 0, sizeof(conn->br.link_key->val)); break; } bt_conn_unref(conn); } static void link_key_neg_reply(const bt_addr_t *bdaddr) { struct bt_hci_cp_link_key_neg_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp)); if (!buf) { BT_ERR("Out of command buffers"); return; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL); } static void link_key_reply(const bt_addr_t *bdaddr, const u8_t *lk) { struct bt_hci_cp_link_key_reply *cp; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp)); if (!buf) { BT_ERR("Out of command buffers"); return; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); memcpy(cp->link_key, lk, 16); bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL); } static void link_key_req(struct net_buf *buf) { struct bt_hci_evt_link_key_req *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG("%s", bt_addr_str(&evt->bdaddr)); conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); link_key_neg_reply(&evt->bdaddr); return; } if (!conn->br.link_key) { conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr); } if (!conn->br.link_key) { link_key_neg_reply(&evt->bdaddr); bt_conn_unref(conn); return; } /* * Enforce regenerate by controller stronger link key since found one * in database not covers requested security level. */ if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) && conn->required_sec_level > BT_SECURITY_L2) { link_key_neg_reply(&evt->bdaddr); bt_conn_unref(conn); return; } link_key_reply(&evt->bdaddr, conn->br.link_key->val); bt_conn_unref(conn); } static void io_capa_neg_reply(const bt_addr_t *bdaddr, const u8_t reason) { struct bt_hci_cp_io_capability_neg_reply *cp; struct net_buf *resp_buf; resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, sizeof(*cp)); if (!resp_buf) { BT_ERR("Out of command buffers"); return; } cp = net_buf_add(resp_buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, bdaddr); cp->reason = reason; bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL); } static void io_capa_resp(struct net_buf *buf) { struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x", bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication); if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) { BT_ERR("Invalid remote authentication requirements"); io_capa_neg_reply(&evt->bdaddr, BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL); return; } if (evt->capability > BT_IO_NO_INPUT_OUTPUT) { BT_ERR("Invalid remote io capability requirements"); io_capa_neg_reply(&evt->bdaddr, BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL); return; } conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); return; } conn->br.remote_io_capa = evt->capability; conn->br.remote_auth = evt->authentication; atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING); bt_conn_unref(conn); } static void io_capa_req(struct net_buf *buf) { struct bt_hci_evt_io_capa_req *evt = (void *)buf->data; struct net_buf *resp_buf; struct bt_conn *conn; struct bt_hci_cp_io_capability_reply *cp; u8_t auth; BT_DBG(""); conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY, sizeof(*cp)); if (!resp_buf) { BT_ERR("Out of command buffers"); bt_conn_unref(conn); return; } /* * Set authentication requirements when acting as pairing initiator to * 'dedicated bond' with MITM protection set if local IO capa * potentially allows it, and for acceptor, based on local IO capa and * remote's authentication set. */ if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) { if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) { auth = BT_HCI_DEDICATED_BONDING_MITM; } else { auth = BT_HCI_DEDICATED_BONDING; } } else { auth = bt_conn_ssp_get_auth(conn); } cp = net_buf_add(resp_buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &evt->bdaddr); cp->capability = bt_conn_get_io_capa(); cp->authentication = auth; cp->oob_data = 0U; bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL); bt_conn_unref(conn); } static void ssp_complete(struct net_buf *buf) { struct bt_hci_evt_ssp_complete *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG("status 0x%02x", evt->status); conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } bt_conn_ssp_auth_complete(conn, security_err_get(evt->status)); if (evt->status) { bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); } bt_conn_unref(conn); } static void user_confirm_req(struct net_buf *buf) { struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data; struct bt_conn *conn; conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey)); bt_conn_unref(conn); } static void user_passkey_notify(struct net_buf *buf) { struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG(""); conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey)); bt_conn_unref(conn); } static void user_passkey_req(struct net_buf *buf) { struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data; struct bt_conn *conn; conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } bt_conn_ssp_auth(conn, 0); bt_conn_unref(conn); } struct discovery_priv { u16_t clock_offset; u8_t pscan_rep_mode; u8_t resolving; } __packed; static int request_name(const bt_addr_t *addr, u8_t pscan, u16_t offset) { struct bt_hci_cp_remote_name_request *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, addr); cp->pscan_rep_mode = pscan; cp->reserved = 0x00; /* reserver, should be set to 0x00 */ cp->clock_offset = offset; return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL); } #define EIR_SHORT_NAME 0x08 #define EIR_COMPLETE_NAME 0x09 static bool eir_has_name(const u8_t *eir) { int len = 240; while (len) { if (len < 2) { break; }; /* Look for early termination */ if (!eir[0]) { break; } /* Check if field length is correct */ if (eir[0] > len - 1) { break; } switch (eir[1]) { case EIR_SHORT_NAME: case EIR_COMPLETE_NAME: if (eir[0] > 1) { return true; } break; default: break; } /* Parse next AD Structure */ len -= eir[0] + 1; eir += eir[0] + 1; } return false; } static void report_discovery_results(void) { bool resolving_names = false; int i; for (i = 0; i < discovery_results_count; i++) { struct discovery_priv *priv; priv = (struct discovery_priv *)&discovery_results[i]._priv; if (eir_has_name(discovery_results[i].eir)) { continue; } if (request_name(&discovery_results[i].addr, priv->pscan_rep_mode, priv->clock_offset)) { continue; } priv->resolving = 1U; resolving_names = true; } if (resolving_names) { return; } atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); discovery_cb(discovery_results, discovery_results_count); discovery_cb = NULL; discovery_results = NULL; discovery_results_size = 0; discovery_results_count = 0; } static void inquiry_complete(struct net_buf *buf) { struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data; if (evt->status) { BT_ERR("Failed to complete inquiry"); } report_discovery_results(); } static struct bt_br_discovery_result *get_result_slot(const bt_addr_t *addr, s8_t rssi) { struct bt_br_discovery_result *result = NULL; size_t i; /* check if already present in results */ for (i = 0; i < discovery_results_count; i++) { if (!bt_addr_cmp(addr, &discovery_results[i].addr)) { return &discovery_results[i]; } } /* Pick a new slot (if available) */ if (discovery_results_count < discovery_results_size) { bt_addr_copy(&discovery_results[discovery_results_count].addr, addr); return &discovery_results[discovery_results_count++]; } /* ignore if invalid RSSI */ if (rssi == 0xff) { return NULL; } /* * Pick slot with smallest RSSI that is smaller then passed RSSI * TODO handle TX if present */ for (i = 0; i < discovery_results_size; i++) { if (discovery_results[i].rssi > rssi) { continue; } if (!result || result->rssi > discovery_results[i].rssi) { result = &discovery_results[i]; } } if (result) { BT_DBG("Reusing slot (old %s rssi %d dBm)", bt_addr_str(&result->addr), result->rssi); bt_addr_copy(&result->addr, addr); } return result; } static void inquiry_result_with_rssi(struct net_buf *buf) { u8_t num_reports = net_buf_pull_u8(buf); if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { return; } BT_DBG("number of results: %u", num_reports); while (num_reports--) { struct bt_hci_evt_inquiry_result_with_rssi *evt; struct bt_br_discovery_result *result; struct discovery_priv *priv; if (buf->len < sizeof(*evt)) { BT_ERR("Unexpected end to buffer"); return; } evt = net_buf_pull_mem(buf, sizeof(*evt)); BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi); result = get_result_slot(&evt->addr, evt->rssi); if (!result) { return; } priv = (struct discovery_priv *)&result->_priv; priv->pscan_rep_mode = evt->pscan_rep_mode; priv->clock_offset = evt->clock_offset; memcpy(result->cod, evt->cod, 3); result->rssi = evt->rssi; /* we could reuse slot so make sure EIR is cleared */ (void)memset(result->eir, 0, sizeof(result->eir)); } } static void extended_inquiry_result(struct net_buf *buf) { struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data; struct bt_br_discovery_result *result; struct discovery_priv *priv; if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { return; } BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi); result = get_result_slot(&evt->addr, evt->rssi); if (!result) { return; } priv = (struct discovery_priv *)&result->_priv; priv->pscan_rep_mode = evt->pscan_rep_mode; priv->clock_offset = evt->clock_offset; result->rssi = evt->rssi; memcpy(result->cod, evt->cod, 3); memcpy(result->eir, evt->eir, sizeof(result->eir)); } static void remote_name_request_complete(struct net_buf *buf) { struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data; struct bt_br_discovery_result *result; struct discovery_priv *priv; int eir_len = 240; u8_t *eir; int i; result = get_result_slot(&evt->bdaddr, 0xff); if (!result) { return; } priv = (struct discovery_priv *)&result->_priv; priv->resolving = 0U; if (evt->status) { goto check_names; } eir = result->eir; while (eir_len) { if (eir_len < 2) { break; }; /* Look for early termination */ if (!eir[0]) { size_t name_len; eir_len -= 2; /* name is null terminated */ name_len = strlen((const char *)evt->name); if (name_len > eir_len) { eir[0] = eir_len + 1; eir[1] = EIR_SHORT_NAME; } else { eir[0] = name_len + 1; eir[1] = EIR_SHORT_NAME; } memcpy(&eir[2], evt->name, eir[0] - 1); break; } /* Check if field length is correct */ if (eir[0] > eir_len - 1) { break; } /* next EIR Structure */ eir_len -= eir[0] + 1; eir += eir[0] + 1; } check_names: /* if still waiting for names */ for (i = 0; i < discovery_results_count; i++) { struct discovery_priv *priv; priv = (struct discovery_priv *)&discovery_results[i]._priv; if (priv->resolving) { return; } } /* all names resolved, report discovery results */ atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); discovery_cb(discovery_results, discovery_results_count); discovery_cb = NULL; discovery_results = NULL; discovery_results_size = 0; discovery_results_count = 0; } static void link_encr(const u16_t handle) { struct bt_hci_cp_set_conn_encrypt *encr; struct net_buf *buf; BT_DBG(""); buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr)); if (!buf) { BT_ERR("Out of command buffers"); return; } encr = net_buf_add(buf, sizeof(*encr)); encr->handle = sys_cpu_to_le16(handle); encr->encrypt = 0x01; bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL); } static void auth_complete(struct net_buf *buf) { struct bt_hci_evt_auth_complete *evt = (void *)buf->data; struct bt_conn *conn; u16_t handle = sys_le16_to_cpu(evt->handle); BT_DBG("status 0x%02x, handle %u", evt->status, handle); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Can't find conn for handle %u", handle); return; } if (evt->status) { if (conn->state == BT_CONN_CONNECTED) { /* * Inform layers above HCI about non-zero authentication * status to make them able cleanup pending jobs. */ bt_l2cap_encrypt_change(conn, evt->status); } reset_pairing(conn); } else { link_encr(handle); } bt_conn_unref(conn); } static void read_remote_features_complete(struct net_buf *buf) { struct bt_hci_evt_remote_features *evt = (void *)buf->data; u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_hci_cp_read_remote_ext_features *cp; struct bt_conn *conn; BT_DBG("status 0x%02x handle %u", evt->status, handle); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Can't find conn for handle %u", handle); return; } if (evt->status) { goto done; } memcpy(conn->br.features[0], evt->features, sizeof(evt->features)); if (!BT_FEAT_EXT_FEATURES(conn->br.features)) { goto done; } buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, sizeof(*cp)); if (!buf) { goto done; } /* Read remote host features (page 1) */ cp = net_buf_add(buf, sizeof(*cp)); cp->handle = evt->handle; cp->page = 0x01; bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL); done: bt_conn_unref(conn); } static void read_remote_ext_features_complete(struct net_buf *buf) { struct bt_hci_evt_remote_ext_features *evt = (void *)buf->data; u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_conn *conn; BT_DBG("status 0x%02x handle %u", evt->status, handle); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Can't find conn for handle %u", handle); return; } if (!evt->status && evt->page == 0x01) { memcpy(conn->br.features[1], evt->features, sizeof(conn->br.features[1])); } bt_conn_unref(conn); } static void role_change(struct net_buf *buf) { struct bt_hci_evt_role_change *evt = (void *)buf->data; struct bt_conn *conn; BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role, bt_addr_str(&evt->bdaddr)); if (evt->status) { return; } conn = bt_conn_lookup_addr_br(&evt->bdaddr); if (!conn) { BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); return; } if (evt->role) { conn->role = BT_CONN_ROLE_SLAVE; } else { conn->role = BT_CONN_ROLE_MASTER; } bt_conn_unref(conn); } #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_SMP) static int le_set_privacy_mode(const bt_addr_le_t *addr, u8_t mode) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_privacy_mode cp; struct net_buf *buf; int err; /* Check if set privacy mode command is supported */ if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) { BT_WARN("Set privacy mode command is not supported"); return 0; } BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode); bt_addr_le_copy(&cp.id_addr, addr); cp.mode = mode; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, &cp, sizeof(cp)); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL); if (err) { return err; } return 0; #else /* Check if set privacy mode command is supported */ if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) { BT_WARN("Set privacy mode command is not supported"); return 0; } BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode); return hci_api_le_set_privacy_mode(addr->type, (uint8_t *)addr->a.val, mode); #endif } static int addr_res_enable(u8_t enable) { #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *buf; BT_DBG("%s", enable ? "enabled" : "disabled"); buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, enable); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, buf, NULL); #else BT_DBG("%s", enable ? "enabled" : "disabled"); return hci_api_le_set_addr_res_enable(enable); #endif } static int hci_id_add(u8_t id, const bt_addr_le_t *addr, u8_t peer_irk[16]) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_add_dev_to_rl *cp; struct net_buf *buf; BT_DBG("addr %s", bt_addr_le_str(addr)); buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_le_copy(&cp->peer_id_addr, addr); memcpy(cp->peer_irk, peer_irk, 16); #if defined(CONFIG_BT_PRIVACY) memcpy(cp->local_irk, bt_dev.irk[id], 16); #else (void)memset(cp->local_irk, 0, 16); #endif return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL); #else u8_t local_irk[16] = {0}; BT_DBG("addr %s", bt_addr_le_str(addr)); #if defined(CONFIG_BT_PRIVACY) memcpy(local_irk, bt_dev.irk[id], 16); #else (void)memset(local_irk, 0, 16); #endif return hci_api_le_add_dev_to_rl(addr->type, (uint8_t *)addr->a.val, peer_irk, local_irk); #endif } void bt_id_add(struct bt_keys *keys) { struct bt_conn *conn; int err; BT_DBG("addr %s", bt_addr_le_str(&keys->addr)); /* Nothing to be done if host-side resolving is used */ if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { bt_dev.le.rl_entries++; keys->state |= BT_KEYS_ID_ADDED; return; } conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_CONNECT); if (conn) { pending_id_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD); bt_conn_unref(conn); return; } if (IS_ENABLED(CONFIG_BT_EXT_ADV)) { bool adv_enabled = false; bt_adv_foreach(adv_is_limited_enabled, &adv_enabled); if (adv_enabled) { pending_id_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD); return; } } #if defined(CONFIG_BT_OBSERVER) bool scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING); if (IS_ENABLED(CONFIG_BT_EXT_ADV) && scan_enabled && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) { pending_id_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD); } #endif bt_adv_foreach(adv_pause_enabled, NULL); #if defined(CONFIG_BT_OBSERVER) if (scan_enabled) { set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); } #endif /* CONFIG_BT_OBSERVER */ /* If there are any existing entries address resolution will be on */ if (bt_dev.le.rl_entries) { err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE); if (err) { BT_WARN("Failed to disable address resolution"); goto done; } } if (bt_dev.le.rl_entries == bt_dev.le.rl_size) { BT_WARN("Resolving list size exceeded. Switching to host."); #if !defined(CONFIG_BT_USE_HCI_API) err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL); #else err = hci_api_le_clear_rl(); #endif if (err) { BT_ERR("Failed to clear resolution list"); goto done; } bt_dev.le.rl_entries++; keys->state |= BT_KEYS_ID_ADDED; goto done; } err = hci_id_add(keys->id, &keys->addr, keys->irk.val); if (err) { BT_ERR("Failed to add IRK to controller"); goto done; } bt_dev.le.rl_entries++; keys->state |= BT_KEYS_ID_ADDED; /* * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature * * By default, network privacy mode is used when private addresses are * resolved and generated by the Controller, so advertising packets from * peer devices that contain private addresses will only be accepted. * By changing to the device privacy mode device is only concerned about * its privacy and will accept advertising packets from peer devices * that contain their identity address as well as ones that contain * a private address, even if the peer device has distributed its IRK in * the past. */ err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE); if (err) { BT_ERR("Failed to set privacy mode"); goto done; } done: addr_res_enable(BT_HCI_ADDR_RES_ENABLE); #if defined(CONFIG_BT_OBSERVER) if (scan_enabled) { set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); } #endif /* CONFIG_BT_OBSERVER */ bt_adv_foreach(adv_unpause_enabled, NULL); } static void keys_add_id(struct bt_keys *keys, void *data) { if (keys->state & BT_KEYS_ID_ADDED) { hci_id_add(keys->id, &keys->addr, keys->irk.val); } } static int hci_id_del(const bt_addr_le_t *addr) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_rem_dev_from_rl *cp; struct net_buf *buf; BT_DBG("addr %s", bt_addr_le_str(addr)); buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_le_copy(&cp->peer_id_addr, addr); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL); #else return hci_api_le_remove_dev_from_rl(addr->type, addr->a.val); #endif } void bt_id_del(struct bt_keys *keys) { struct bt_conn *conn; int err; BT_DBG("addr %s", bt_addr_le_str(&keys->addr)); if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) { bt_dev.le.rl_entries--; keys->state &= ~BT_KEYS_ID_ADDED; return; } conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_CONNECT); if (conn) { pending_id_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL); bt_conn_unref(conn); return; } if (IS_ENABLED(CONFIG_BT_EXT_ADV)) { bool adv_enabled = false; bt_adv_foreach(adv_is_limited_enabled, &adv_enabled); if (adv_enabled) { pending_id_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD); return; } } #if defined(CONFIG_BT_OBSERVER) bool scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING); if (IS_ENABLED(CONFIG_BT_EXT_ADV) && scan_enabled && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) { pending_id_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL); } #endif /* CONFIG_BT_OBSERVER */ bt_adv_foreach(adv_pause_enabled, NULL); #if defined(CONFIG_BT_OBSERVER) if (scan_enabled) { set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); } #endif /* CONFIG_BT_OBSERVER */ err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE); if (err) { BT_ERR("Disabling address resolution failed (err %d)", err); goto done; } /* We checked size + 1 earlier, so here we know we can fit again */ if (bt_dev.le.rl_entries > bt_dev.le.rl_size) { bt_dev.le.rl_entries--; keys->state &= ~BT_KEYS_ID_ADDED; if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_PRIVACY)) { bt_keys_foreach(BT_KEYS_ALL, keys_add_id, NULL); } else { bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL); } goto done; } err = hci_id_del(&keys->addr); if (err) { BT_ERR("Failed to remove IRK from controller"); goto done; } bt_dev.le.rl_entries--; keys->state &= ~BT_KEYS_ID_ADDED; done: /* Only re-enable if there are entries to do resolving with */ if (bt_dev.le.rl_entries) { addr_res_enable(BT_HCI_ADDR_RES_ENABLE); } #if defined(CONFIG_BT_OBSERVER) if (scan_enabled) { set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); } #endif /* CONFIG_BT_OBSERVER */ bt_adv_foreach(adv_unpause_enabled, NULL); } static void update_sec_level(struct bt_conn *conn) { if (!conn->encrypt) { conn->sec_level = BT_SECURITY_L1; return; } if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { if (conn->le.keys->flags & BT_KEYS_SC && conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) { conn->sec_level = BT_SECURITY_L4; } else { conn->sec_level = BT_SECURITY_L3; } } else { conn->sec_level = BT_SECURITY_L2; } if (conn->required_sec_level > conn->sec_level) { BT_ERR("Failed to set required security level"); bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); } } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) static void hci_encrypt_change(struct net_buf *buf) { struct bt_hci_evt_encrypt_change *evt = (void *)buf->data; u16_t handle = sys_le16_to_cpu(evt->handle); struct bt_conn *conn; BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle, evt->encrypt); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to look up conn with handle %u", handle); return; } if (evt->status) { reset_pairing(conn); bt_l2cap_encrypt_change(conn, evt->status); bt_conn_security_changed(conn, security_err_get(evt->status)); bt_conn_unref(conn); return; } conn->encrypt = evt->encrypt; #if defined(CONFIG_BT_SMP) if (conn->type == BT_CONN_TYPE_LE) { /* * we update keys properties only on successful encryption to * avoid losing valid keys if encryption was not successful. * * Update keys with last pairing info for proper sec level * update. This is done only for LE transport, for BR/EDR keys * are updated on HCI 'Link Key Notification Event' */ if (conn->encrypt) { bt_smp_update_keys(conn); } update_sec_level(conn); } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { if (!update_sec_level_br(conn)) { bt_conn_unref(conn); return; } if (IS_ENABLED(CONFIG_BT_SMP)) { /* * Start SMP over BR/EDR if we are pairing and are * master on the link */ if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) && conn->role == BT_CONN_ROLE_MASTER) { bt_smp_br_send_pairing_req(conn); } } } #endif /* CONFIG_BT_BREDR */ reset_pairing(conn); bt_l2cap_encrypt_change(conn, evt->status); bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS); bt_conn_unref(conn); } static void hci_encrypt_key_refresh_complete(struct net_buf *buf) { struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data; struct bt_conn *conn; u16_t handle; handle = sys_le16_to_cpu(evt->handle); BT_DBG("status 0x%02x handle %u", evt->status, handle); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to look up conn with handle %u", handle); return; } if (evt->status) { reset_pairing(conn); bt_l2cap_encrypt_change(conn, evt->status); bt_conn_security_changed(conn, security_err_get(evt->status)); bt_conn_unref(conn); return; } /* * Update keys with last pairing info for proper sec level update. * This is done only for LE transport. For BR/EDR transport keys are * updated on HCI 'Link Key Notification Event', therefore update here * only security level based on available keys and encryption state. */ #if defined(CONFIG_BT_SMP) if (conn->type == BT_CONN_TYPE_LE) { bt_smp_update_keys(conn); update_sec_level(conn); } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { if (!update_sec_level_br(conn)) { bt_conn_unref(conn); return; } } #endif /* CONFIG_BT_BREDR */ reset_pairing(conn); bt_l2cap_encrypt_change(conn, evt->status); bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS); bt_conn_unref(conn); } #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ #if defined(CONFIG_BT_REMOTE_VERSION) static void bt_hci_evt_read_remote_version_complete(struct net_buf *buf) { struct bt_hci_evt_remote_version_info *evt; struct bt_conn *conn; evt = net_buf_pull_mem(buf, sizeof(*evt)); conn = bt_conn_lookup_handle(evt->handle); if (!conn) { BT_ERR("No connection for handle %u", evt->handle); return; } if (!evt->status) { conn->rv.version = evt->version; conn->rv.manufacturer = sys_le16_to_cpu(evt->manufacturer); conn->rv.subversion = sys_le16_to_cpu(evt->subversion); } atomic_set_bit(conn->flags, BT_CONN_AUTO_VERSION_INFO); if (IS_ENABLED(CONFIG_BT_REMOTE_INFO)) { /* Remote features is already present */ notify_remote_info(conn); } /* Continue with auto-initiated procedures */ conn_auto_initiate(conn); bt_conn_unref(conn); } #endif /* CONFIG_BT_REMOTE_VERSION */ #if defined(CONFIG_BT_SMP) static void le_ltk_neg_reply(u16_t handle) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_ltk_req_neg_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp)); if (!buf) { BT_ERR("Out of command buffers"); return; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf); #else hci_api_le_enctypt_ltk_req_neg_reply(handle); #endif } static void le_ltk_reply(u16_t handle, u8_t *ltk) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_ltk_req_reply *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY, sizeof(*cp)); if (!buf) { BT_ERR("Out of command buffers"); return; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = sys_cpu_to_le16(handle); memcpy(cp->ltk, ltk, sizeof(cp->ltk)); bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf); #else hci_api_le_enctypt_ltk_req_reply(handle, ltk); #endif } static void le_ltk_request(struct net_buf *buf) { struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data; struct bt_conn *conn; u16_t handle; u8_t ltk[16]; handle = sys_le16_to_cpu(evt->handle); BT_DBG("handle %u", handle); conn = bt_conn_lookup_handle(handle); if (!conn) { BT_ERR("Unable to lookup conn for handle %u", handle); return; } if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) { le_ltk_reply(handle, ltk); } else { le_ltk_neg_reply(handle); } bt_conn_unref(conn); } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_ECC) #if !defined(CONFIG_BT_USE_HCI_API) static void le_pkey_complete(struct net_buf *buf) { struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data; struct bt_pub_key_cb *cb; BT_DBG("status: 0x%02x", evt->status); atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); if (!evt->status) { memcpy(pub_key, evt->key, 64); atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); } for (cb = pub_key_cb; cb; cb = cb->_next) { cb->func(evt->status ? NULL : pub_key); } pub_key_cb = NULL; } static void le_dhkey_complete(struct net_buf *buf) { struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data; BT_DBG("status: 0x%02x", evt->status); if (dh_key_cb) { dh_key_cb(evt->status ? NULL : evt->dhkey); dh_key_cb = NULL; } } #else int hci_api_le_event_pkey_complete(u8_t status, u8_t key[64]) { struct bt_pub_key_cb *cb; BT_DBG("status: 0x%02x", status); atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); if (!status) { memcpy(pub_key, key, 64); atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); } for (cb = pub_key_cb; cb; cb = cb->_next) { cb->func(status ? NULL : key); } pub_key_cb = NULL; return 0; } static void le_pkey_complete(struct net_buf *buf) { struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data; hci_api_le_event_pkey_complete(evt->status, evt->key); } int hci_api_le_event_dhkey_complete(u8_t status, u8_t dhkey[32]) { BT_DBG("status: 0x%x", status); if (dh_key_cb) { dh_key_cb(status ? NULL : dhkey); dh_key_cb = NULL; } return 0; } static void le_dhkey_complete(struct net_buf *buf) { struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data; hci_api_le_event_dhkey_complete(evt->status, evt->dhkey); } #endif #endif /* CONFIG_BT_ECC */ #if !defined(CONFIG_BT_USE_HCI_API) static void hci_reset_complete(struct net_buf *buf) { u8_t status = buf->data[0]; atomic_t flags; BT_DBG("status 0x%02x", status); if (status) { return; } scan_dev_found_cb = NULL; #if defined(CONFIG_BT_BREDR) discovery_cb = NULL; discovery_results = NULL; discovery_results_size = 0; discovery_results_count = 0; #endif /* CONFIG_BT_BREDR */ flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS); atomic_set(bt_dev.flags, flags); } #else static void hci_reset_complete() { atomic_t flags; scan_dev_found_cb = NULL; #if defined(CONFIG_BT_BREDR) discovery_cb = NULL; discovery_results = NULL; discovery_results_size = 0; discovery_results_count = 0; #endif /* CONFIG_BT_BREDR */ flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS); atomic_set(bt_dev.flags, flags); } #endif #if !defined(CONFIG_BT_USE_HCI_API) static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf) { BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf); if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) { BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p", opcode, buf->pool_id, net_buf_pool_get(buf->pool_id), &hci_cmd_pool); return; } if (cmd(buf)->opcode != opcode) { BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x", opcode, cmd(buf)->opcode); } if (cmd(buf)->state && !status) { struct cmd_state_set *update = cmd(buf)->state; atomic_set_bit_to(update->target, update->bit, update->val); } /* If the command was synchronous wake up bt_hci_cmd_send_sync() */ if (cmd(buf)->sync) { cmd(buf)->status = status; k_sem_give(cmd(buf)->sync); } } static void hci_cmd_complete(struct net_buf *buf) { struct bt_hci_evt_cmd_complete *evt; u8_t status, ncmd; u16_t opcode; evt = net_buf_pull_mem(buf, sizeof(*evt)); ncmd = evt->ncmd; opcode = sys_le16_to_cpu(evt->opcode); BT_DBG("opcode 0x%04x", opcode); /* All command return parameters have a 1-byte status in the * beginning, so we can safely make this generalization. */ status = buf->data[0]; hci_cmd_done(opcode, status, buf); /* Allow next command to be sent */ if (ncmd) { k_sem_give(&bt_dev.ncmd_sem); } } static void hci_cmd_status(struct net_buf *buf) { struct bt_hci_evt_cmd_status *evt; u16_t opcode; u8_t ncmd; evt = net_buf_pull_mem(buf, sizeof(*evt)); opcode = sys_le16_to_cpu(evt->opcode); ncmd = evt->ncmd; BT_DBG("opcode 0x%04x", opcode); hci_cmd_done(opcode, evt->status, buf); /* Allow next command to be sent */ if (ncmd) { k_sem_give(&bt_dev.ncmd_sem); } } #endif #if defined(CONFIG_BT_OBSERVER) static int le_scan_set_random_addr(bool active_scan, u8_t *own_addr_type) { int err; if (IS_ENABLED(CONFIG_BT_PRIVACY)) { err = le_set_private_addr(BT_ID_DEFAULT); if (err) { return err; } if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { *own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; } else { *own_addr_type = BT_ADDR_LE_RANDOM; } } else { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); *own_addr_type = bt_dev.id_addr[0].type; /* Use NRPA unless identity has been explicitly requested * (through Kconfig). * Use same RPA as legacy advertiser if advertising. */ if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && !(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) && adv && !atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { err = le_set_private_addr(BT_ID_DEFAULT); if (err) { return err; } *own_addr_type = BT_ADDR_LE_RANDOM; } else if (IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && *own_addr_type == BT_ADDR_LE_RANDOM) { /* If scanning with Identity Address we must set the * random identity address for both active and passive * scanner in order to receive adv reports that are * directed towards this identity. */ err = set_random_address(&bt_dev.id_addr[0].a); if (err) { return err; } } } return 0; } static int start_le_scan_ext(struct bt_hci_ext_scan_phy *phy_1m, struct bt_hci_ext_scan_phy *phy_coded, u16_t duration) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_ext_scan_param *set_param; struct net_buf *buf; u8_t own_addr_type; bool active_scan; int err; active_scan = (phy_1m && phy_1m->type == BT_HCI_LE_SCAN_ACTIVE) || (phy_coded && phy_coded->type == BT_HCI_LE_SCAN_ACTIVE); if (duration > 0) { atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED); /* Allow bt_le_oob_get_local to be called directly before * starting a scan limited by timeout. */ if (IS_ENABLED(CONFIG_BT_PRIVACY) && !rpa_is_new()) { atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); } } err = le_scan_set_random_addr(active_scan, &own_addr_type); if (err) { return err; } buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_SCAN_PARAM, sizeof(*set_param) + (phy_1m ? sizeof(*phy_1m) : 0) + (phy_coded ? sizeof(*phy_coded) : 0)); if (!buf) { return -ENOBUFS; } set_param = net_buf_add(buf, sizeof(*set_param)); set_param->own_addr_type = own_addr_type; set_param->phys = 0; if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) { set_param->filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST; } else { set_param->filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST; } if (phy_1m) { set_param->phys |= BT_HCI_LE_EXT_SCAN_PHY_1M; net_buf_add_mem(buf, phy_1m, sizeof(*phy_1m)); } if (phy_coded) { set_param->phys |= BT_HCI_LE_EXT_SCAN_PHY_CODED; net_buf_add_mem(buf, phy_coded, sizeof(*phy_coded)); } err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_SCAN_PARAM, buf, NULL); if (err) { return err; } #else u8_t own_addr_type; bool active_scan; int err; u8_t scan_phys = 0; u8_t filter_policy; active_scan = (phy_1m && phy_1m->type == BT_HCI_LE_SCAN_ACTIVE) || (phy_coded && phy_coded->type == BT_HCI_LE_SCAN_ACTIVE); if (duration > 0) { atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED); /* Allow bt_le_oob_get_local to be called directly before * starting a scan limited by timeout. */ if (IS_ENABLED(CONFIG_BT_PRIVACY) && !rpa_is_new()) { atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); } } err = le_scan_set_random_addr(active_scan, &own_addr_type); if (err) { return err; } struct ext_scan_param_t phys[(phy_1m ? sizeof(*phy_1m) : 0) + (phy_coded ? sizeof(*phy_coded) : 0)]; struct ext_scan_param_t *phy = phys; if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) { filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST; } else { filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST; } if (phy_1m) { scan_phys |= BT_HCI_LE_EXT_SCAN_PHY_1M; phy->type = phy_1m->type; phy->interval = phy_1m->interval; phy->window = phy_1m->window; phy++; } if (phy_coded) { scan_phys |= BT_HCI_LE_EXT_SCAN_PHY_CODED; phy->type = phy_coded->type; phy->interval = phy_coded->interval; phy->window = phy_coded->window; } err = hci_api_le_ext_scan_param_set(own_addr_type, filter_policy, scan_phys, phys); if (err) { return err; } #endif err = set_le_ext_scan_enable(BT_HCI_LE_SCAN_ENABLE, duration); if (err) { return err; } atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, active_scan); return 0; } static int start_le_scan_legacy(u8_t scan_type, u16_t interval, u16_t window) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_scan_param set_param; struct net_buf *buf; int err; bool active_scan; (void)memset(&set_param, 0, sizeof(set_param)); set_param.scan_type = scan_type; /* for the rest parameters apply default values according to * spec 4.2, vol2, part E, 7.8.10 */ set_param.interval = sys_cpu_to_le16(interval); set_param.window = sys_cpu_to_le16(window); if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) { set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST; } else { set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST; } active_scan = scan_type == BT_HCI_LE_SCAN_ACTIVE; err = le_scan_set_random_addr(active_scan, &set_param.addr_type); if (err) { return err; } buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, &set_param, sizeof(set_param)); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL); if (err) { return err; } #else int err; bool active_scan; u8_t filter_policy; u8_t addr_type; if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) { filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST; } else { filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST; } active_scan = scan_type == BT_HCI_LE_SCAN_ACTIVE; err = le_scan_set_random_addr(active_scan, &addr_type); if (err) { return err; } err = hci_api_le_scan_param_set(scan_type, sys_cpu_to_le16(interval), sys_cpu_to_le16(window), addr_type, filter_policy); if (err) { return err; } #endif err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); if (err) { return err; } atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, active_scan); return 0; } static int start_passive_scan(bool fast_scan) { u16_t interval, window; if (fast_scan) { interval = BT_GAP_SCAN_FAST_INTERVAL; window = BT_GAP_SCAN_FAST_WINDOW; } else { interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL; window = CONFIG_BT_BACKGROUND_SCAN_WINDOW; } if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { struct bt_hci_ext_scan_phy scan; scan.type = BT_HCI_LE_SCAN_PASSIVE; scan.interval = sys_cpu_to_le16(interval); scan.window = sys_cpu_to_le16(window); return start_le_scan_ext(&scan, NULL, 0); } return start_le_scan_legacy(BT_HCI_LE_SCAN_PASSIVE, interval, window); } int bt_le_scan_update(bool fast_scan) { if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { return 0; } if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { int err; err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); if (err) { return err; } } if (IS_ENABLED(CONFIG_BT_CENTRAL)) { struct bt_conn *conn; /* don't restart scan if we have pending connection */ conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_CONNECT); if (conn) { bt_conn_unref(conn); return 0; } conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_CONNECT_SCAN); if (!conn) { return 0; } atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); bt_conn_unref(conn); return start_passive_scan(fast_scan); } return 0; } void bt_data_parse(struct net_buf_simple *ad, bool (*func)(struct bt_data *data, void *user_data), void *user_data) { while (ad->len > 1) { struct bt_data data; u8_t len; len = net_buf_simple_pull_u8(ad); if (len == 0U) { /* Early termination */ return; } if (len > ad->len) { BT_WARN("Malformed data"); return; } data.type = net_buf_simple_pull_u8(ad); data.data_len = len - 1; data.data = ad->data; if (!func(&data, user_data)) { return; } net_buf_simple_pull(ad, len - 1); } } /* Convert Legacy adv report evt_type field to adv props */ static u8_t get_adv_props(u8_t evt_type) { switch (evt_type) { case BT_GAP_ADV_TYPE_ADV_IND: return BT_GAP_ADV_PROP_CONNECTABLE | BT_GAP_ADV_PROP_SCANNABLE; case BT_GAP_ADV_TYPE_ADV_DIRECT_IND: return BT_GAP_ADV_PROP_CONNECTABLE | BT_GAP_ADV_PROP_DIRECTED; case BT_GAP_ADV_TYPE_ADV_SCAN_IND: return BT_GAP_ADV_PROP_SCANNABLE; case BT_GAP_ADV_TYPE_ADV_NONCONN_IND: return 0; /* In legacy advertising report, we don't know if the scan * response come from a connectable advertiser, so don't * set connectable property bit. */ case BT_GAP_ADV_TYPE_SCAN_RSP: return BT_GAP_ADV_PROP_SCAN_RESPONSE | BT_GAP_ADV_PROP_SCANNABLE; default: return 0; } } static void le_adv_recv(bt_addr_le_t *addr, struct bt_le_scan_recv_info *info, struct net_buf *buf, u8_t len) { struct bt_le_scan_cb *listener; struct net_buf_simple_state state; bt_addr_le_t id_addr; BT_DBG("%s event %u, len %u, rssi %d dBm", bt_addr_le_str(addr), info->adv_type, len, info->rssi); if (!IS_ENABLED(CONFIG_BT_PRIVACY) && !IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) && (info->adv_props & BT_HCI_LE_ADV_PROP_DIRECT)) { BT_DBG("Dropped direct adv report"); return; } if (addr->type == BT_ADDR_LE_PUBLIC_ID || addr->type == BT_ADDR_LE_RANDOM_ID) { bt_addr_le_copy(&id_addr, addr); id_addr.type -= BT_ADDR_LE_PUBLIC_ID; } else if (addr->type == BT_HCI_PEER_ADDR_ANONYMOUS) { bt_addr_le_copy(&id_addr, BT_ADDR_LE_ANY); } else { bt_addr_le_copy(&id_addr, bt_lookup_id_addr(BT_ID_DEFAULT, addr)); } info->addr = &id_addr; bt_le_scan_cb_t *scan_dev_found_cb_tmp; scan_dev_found_cb_tmp = scan_dev_found_cb; if (scan_dev_found_cb_tmp) { net_buf_simple_save(&buf->b, &state); buf->len = len; scan_dev_found_cb_tmp(&id_addr, info->rssi, info->adv_type, &buf->b); net_buf_simple_restore(&buf->b, &state); } SYS_SLIST_FOR_EACH_CONTAINER(&scan_cbs, listener, node) { net_buf_simple_save(&buf->b, &state); buf->len = len; listener->recv(info, &buf->b); net_buf_simple_restore(&buf->b, &state); } #if defined(CONFIG_BT_CENTRAL) check_pending_conn(&id_addr, addr, info->adv_props); #endif /* CONFIG_BT_CENTRAL */ } #if defined(CONFIG_BT_EXT_ADV) static void le_scan_timeout(struct net_buf *buf) { struct bt_le_scan_cb *listener; atomic_clear_bit(bt_dev.flags, BT_DEV_SCANNING); atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED); atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); #if defined(CONFIG_BT_SMP) pending_id_keys_update(); #endif SYS_SLIST_FOR_EACH_CONTAINER(&scan_cbs, listener, node) { listener->timeout(); } } /* Convert Extended adv report evt_type field into adv type */ static u8_t get_adv_type(u8_t evt_type) { switch (evt_type) { case (BT_HCI_LE_ADV_EVT_TYPE_CONN | BT_HCI_LE_ADV_EVT_TYPE_SCAN | BT_HCI_LE_ADV_EVT_TYPE_LEGACY): return BT_GAP_ADV_TYPE_ADV_IND; case (BT_HCI_LE_ADV_EVT_TYPE_CONN | BT_HCI_LE_ADV_EVT_TYPE_DIRECT | BT_HCI_LE_ADV_EVT_TYPE_LEGACY): return BT_GAP_ADV_TYPE_ADV_DIRECT_IND; case (BT_HCI_LE_ADV_EVT_TYPE_SCAN | BT_HCI_LE_ADV_EVT_TYPE_LEGACY): return BT_GAP_ADV_TYPE_ADV_SCAN_IND; case BT_HCI_LE_ADV_EVT_TYPE_LEGACY: return BT_GAP_ADV_TYPE_ADV_NONCONN_IND; case (BT_HCI_LE_ADV_EVT_TYPE_SCAN_RSP | BT_HCI_LE_ADV_EVT_TYPE_CONN | BT_HCI_LE_ADV_EVT_TYPE_SCAN | BT_HCI_LE_ADV_EVT_TYPE_LEGACY): case (BT_HCI_LE_ADV_EVT_TYPE_SCAN_RSP | BT_HCI_LE_ADV_EVT_TYPE_SCAN | BT_HCI_LE_ADV_EVT_TYPE_LEGACY): /* Scan response from connectable or non-connectable advertiser. */ return BT_GAP_ADV_TYPE_SCAN_RSP; default: return BT_GAP_ADV_TYPE_EXT_ADV; } } static void le_adv_ext_report(struct net_buf *buf) { u8_t num_reports = net_buf_pull_u8(buf); BT_DBG("Adv number of reports %u", num_reports); while (num_reports--) { struct bt_hci_evt_le_ext_advertising_info *evt; struct bt_le_scan_recv_info adv_info; if (buf->len < sizeof(*evt)) { BT_ERR("Unexpected end of buffer"); break; } evt = net_buf_pull_mem(buf, sizeof(*evt)); adv_info.primary_phy = get_phy(evt->prim_phy); adv_info.secondary_phy = get_phy(evt->sec_phy); adv_info.tx_power = evt->tx_power; adv_info.rssi = evt->rssi; adv_info.sid = evt->sid; adv_info.adv_type = get_adv_type(evt->evt_type); /* Convert "Legacy" property to Extended property. */ adv_info.adv_props = evt->evt_type ^ BT_HCI_LE_ADV_PROP_LEGACY; le_adv_recv(&evt->addr, &adv_info, buf, evt->length); net_buf_pull(buf, evt->length); } } #endif /* defined(CONFIG_BT_EXT_ADV) */ static void le_adv_report(struct net_buf *buf) { u8_t num_reports = net_buf_pull_u8(buf); struct bt_hci_evt_le_advertising_info *evt; BT_DBG("Adv number of reports %u", num_reports); while (num_reports--) { struct bt_le_scan_recv_info adv_info; if (buf->len < sizeof(*evt)) { BT_ERR("Unexpected end of buffer"); break; } evt = net_buf_pull_mem(buf, sizeof(*evt)); adv_info.rssi = evt->data[evt->length]; adv_info.primary_phy = BT_GAP_LE_PHY_1M; adv_info.secondary_phy = 0; adv_info.tx_power = BT_GAP_TX_POWER_INVALID; adv_info.sid = BT_GAP_SID_INVALID; adv_info.adv_type = evt->evt_type; adv_info.adv_props = get_adv_props(evt->evt_type); le_adv_recv(&evt->addr, &adv_info, buf, evt->length); net_buf_pull(buf, evt->length + sizeof(adv_info.rssi)); } } #endif /* CONFIG_BT_OBSERVER */ static void le_adv_stop_free_conn(const struct bt_le_ext_adv *adv, u8_t status) { struct bt_conn *conn; if (!bt_addr_le_cmp(&adv->target_addr, BT_ADDR_LE_ANY)) { conn = bt_conn_lookup_state_le(adv->id, BT_ADDR_LE_NONE, BT_CONN_CONNECT_ADV); } else { conn = bt_conn_lookup_state_le(adv->id, &adv->target_addr, BT_CONN_CONNECT_DIR_ADV); } if (conn) { conn->err = status; bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); } } #if defined(CONFIG_BT_EXT_ADV) #if defined(CONFIG_BT_BROADCASTER) static void le_adv_set_terminated(struct net_buf *buf) { struct bt_hci_evt_le_adv_set_terminated *evt; struct bt_le_ext_adv *adv; evt = (void *)buf->data; adv = bt_adv_lookup_handle(evt->adv_handle); BT_DBG("status 0x%02x adv_handle %u conn_handle 0x%02x num %u", evt->status, evt->adv_handle, evt->conn_handle, evt->num_completed_ext_adv_evts); if (!adv) { BT_ERR("No valid adv"); return; } atomic_clear_bit(adv->flags, BT_ADV_ENABLED); if (evt->status && IS_ENABLED(CONFIG_BT_PERIPHERAL) && atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) { /* Only set status for legacy advertising API. * This will call connected callback for high duty cycle * directed advertiser timeout. */ le_adv_stop_free_conn(adv, adv == bt_dev.adv ? evt->status : 0); } if (IS_ENABLED(CONFIG_BT_CONN) && !evt->status) { struct bt_conn *conn = bt_conn_lookup_handle(evt->conn_handle); if (conn) { if (IS_ENABLED(CONFIG_BT_PRIVACY) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { /* Set Responder address unless already set */ conn->le.resp_addr.type = BT_ADDR_LE_RANDOM; if (bt_addr_cmp(&conn->le.resp_addr.a, BT_ADDR_ANY) == 0) { bt_addr_copy(&conn->le.resp_addr.a, &adv->random_addr.a); } } else { bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]); } if (adv->cb && adv->cb->connected) { struct bt_le_ext_adv_connected_info info = { .conn = conn, }; adv->cb->connected(adv, &info); } bt_conn_unref(conn); } } if (atomic_test_and_clear_bit(adv->flags, BT_ADV_LIMITED)) { atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID); #if defined(CONFIG_BT_SMP) pending_id_keys_update(); #endif if (adv->cb && adv->cb->sent) { struct bt_le_ext_adv_sent_info info = { .num_sent = evt->num_completed_ext_adv_evts, }; adv->cb->sent(adv, &info); } } if (!atomic_test_bit(adv->flags, BT_ADV_PERSIST) && adv == bt_dev.adv) { adv_delete_legacy(); } } static void le_scan_req_received(struct net_buf *buf) { struct bt_hci_evt_le_scan_req_received *evt; struct bt_le_ext_adv *adv; evt = (void *)buf->data; adv = bt_adv_lookup_handle(evt->handle); BT_DBG("handle %u peer %s", evt->handle, bt_addr_le_str(&evt->addr)); if (!adv) { BT_ERR("No valid adv"); return; } if (adv->cb && adv->cb->scanned) { struct bt_le_ext_adv_scanned_info info; bt_addr_le_t id_addr; if (evt->addr.type == BT_ADDR_LE_PUBLIC_ID || evt->addr.type == BT_ADDR_LE_RANDOM_ID) { bt_addr_le_copy(&id_addr, &evt->addr); id_addr.type -= BT_ADDR_LE_PUBLIC_ID; } else { bt_addr_le_copy(&id_addr, bt_lookup_id_addr(adv->id, &evt->addr)); } info.addr = &id_addr; adv->cb->scanned(adv, &info); } } #endif /* defined(CONFIG_BT_BROADCASTER) */ #endif /* defined(CONFIG_BT_EXT_ADV) */ int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle) { if (conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } *conn_handle = conn->handle; return 0; } #if defined(CONFIG_BT_HCI_VS_EVT_USER) int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb) { hci_vnd_evt_cb = cb; return 0; } #endif /* CONFIG_BT_HCI_VS_EVT_USER */ static void hci_vendor_event(struct net_buf *buf) { bool handled = false; #if defined(CONFIG_BT_HCI_VS_EVT_USER) if (hci_vnd_evt_cb) { struct net_buf_simple_state state; net_buf_simple_save(&buf->b, &state); handled = hci_vnd_evt_cb(&buf->b); net_buf_simple_restore(&buf->b, &state); } #endif /* CONFIG_BT_HCI_VS_EVT_USER */ if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) { /* do nothing at present time */ BT_WARN("Unhandled vendor-specific event: %s", bt_hex(buf->data, buf->len)); } } static const struct event_handler meta_events[] = { #if defined(CONFIG_BT_OBSERVER) EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report, sizeof(struct bt_hci_evt_le_advertising_report)), #endif /* CONFIG_BT_OBSERVER */ #if defined(CONFIG_BT_CONN) EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete, sizeof(struct bt_hci_evt_le_conn_complete)), EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete, sizeof(struct bt_hci_evt_le_enh_conn_complete)), EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE, le_conn_update_complete, sizeof(struct bt_hci_evt_le_conn_update_complete)), EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE, le_remote_feat_complete, sizeof(struct bt_hci_evt_le_remote_feat_complete)), EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req, sizeof(struct bt_hci_evt_le_conn_param_req)), #if defined(CONFIG_BT_DATA_LEN_UPDATE) EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change, sizeof(struct bt_hci_evt_le_data_len_change)), #endif /* CONFIG_BT_DATA_LEN_UPDATE */ #if defined(CONFIG_BT_PHY_UPDATE) EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE, le_phy_update_complete, sizeof(struct bt_hci_evt_le_phy_update_complete)), #endif /* CONFIG_BT_PHY_UPDATE */ #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request, sizeof(struct bt_hci_evt_le_ltk_request)), #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_ECC) EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete, sizeof(struct bt_hci_evt_le_p256_public_key_complete)), EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete, sizeof(struct bt_hci_evt_le_generate_dhkey_complete)), #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_EXT_ADV) #if defined(CONFIG_BT_BROADCASTER) EVENT_HANDLER(BT_HCI_EVT_LE_ADV_SET_TERMINATED, le_adv_set_terminated, sizeof(struct bt_hci_evt_le_adv_set_terminated)), EVENT_HANDLER(BT_HCI_EVT_LE_SCAN_REQ_RECEIVED, le_scan_req_received, sizeof(struct bt_hci_evt_le_scan_req_received)), #endif #if defined(CONFIG_BT_OBSERVER) EVENT_HANDLER(BT_HCI_EVT_LE_SCAN_TIMEOUT, le_scan_timeout, 0), EVENT_HANDLER(BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT, le_adv_ext_report, sizeof(struct bt_hci_evt_le_ext_advertising_report)), #endif /* defined(CONFIG_BT_OBSERVER) */ #endif /* defined(CONFIG_BT_EXT_ADV) */ }; static void hci_le_meta_event(struct net_buf *buf) { struct bt_hci_evt_le_meta_event *evt; evt = net_buf_pull_mem(buf, sizeof(*evt)); BT_DBG("subevent 0x%02x", evt->subevent); handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events)); } static const struct event_handler normal_events[] = { EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event, sizeof(struct bt_hci_evt_vs)), EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event, sizeof(struct bt_hci_evt_le_meta_event)), #if defined(CONFIG_BT_BREDR) EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req, sizeof(struct bt_hci_evt_conn_request)), EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete, sizeof(struct bt_hci_evt_conn_complete)), EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req, sizeof(struct bt_hci_evt_pin_code_req)), EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify, sizeof(struct bt_hci_evt_link_key_notify)), EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req, sizeof(struct bt_hci_evt_link_key_req)), EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp, sizeof(struct bt_hci_evt_io_capa_resp)), EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req, sizeof(struct bt_hci_evt_io_capa_req)), EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete, sizeof(struct bt_hci_evt_ssp_complete)), EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req, sizeof(struct bt_hci_evt_user_confirm_req)), EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify, sizeof(struct bt_hci_evt_user_passkey_notify)), EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req, sizeof(struct bt_hci_evt_user_passkey_req)), EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete, sizeof(struct bt_hci_evt_inquiry_complete)), EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI, inquiry_result_with_rssi, sizeof(struct bt_hci_evt_inquiry_result_with_rssi)), EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT, extended_inquiry_result, sizeof(struct bt_hci_evt_extended_inquiry_result)), EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE, remote_name_request_complete, sizeof(struct bt_hci_evt_remote_name_req_complete)), EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete, sizeof(struct bt_hci_evt_auth_complete)), EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES, read_remote_features_complete, sizeof(struct bt_hci_evt_remote_features)), EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES, read_remote_ext_features_complete, sizeof(struct bt_hci_evt_remote_ext_features)), EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change, sizeof(struct bt_hci_evt_role_change)), EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete, sizeof(struct bt_hci_evt_sync_conn_complete)), #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_CONN) EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete, sizeof(struct bt_hci_evt_disconn_complete)), #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change, sizeof(struct bt_hci_evt_encrypt_change)), EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE, hci_encrypt_key_refresh_complete, sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)), #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ #if defined(CONFIG_BT_REMOTE_VERSION) EVENT_HANDLER(BT_HCI_EVT_REMOTE_VERSION_INFO, bt_hci_evt_read_remote_version_complete, sizeof(struct bt_hci_evt_remote_version_info)), #endif /* CONFIG_BT_REMOTE_VERSION */ }; static void hci_event(struct net_buf *buf) { struct bt_hci_evt_hdr *hdr; BT_ASSERT(buf->len >= sizeof(*hdr)); hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_DBG("event 0x%02x", hdr->evt); BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt)); handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events)); net_buf_unref(buf); } extern struct k_sem * bt_conn_get_pkts(struct bt_conn *conn); int has_tx_sem(struct k_poll_event *event) { struct bt_conn *conn = NULL; if (IS_ENABLED(CONFIG_BT_CONN)) { if (event->tag == BT_EVENT_CONN_TX_QUEUE) { conn = CONTAINER_OF(event->fifo, struct bt_conn, tx_queue); } if (conn && (k_sem_count_get(bt_conn_get_pkts(conn)) == 0)) { return 0; } } return 1; } #if !defined(CONFIG_BT_USE_HCI_API) static void send_cmd(void) { struct net_buf *buf; int err; /* Get next command */ BT_DBG("calling net_buf_get"); buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT); BT_ASSERT(buf); /* Wait until ncmd > 0 */ BT_DBG("calling sem_take_wait"); k_sem_take(&bt_dev.ncmd_sem, K_FOREVER); /* Clear out any existing sent command */ if (bt_dev.sent_cmd) { BT_ERR("Uncleared pending sent_cmd"); net_buf_unref(bt_dev.sent_cmd); bt_dev.sent_cmd = NULL; } bt_dev.sent_cmd = net_buf_ref(buf); BT_DBG("Sending command 0x%04x (buf %p) to driver", cmd(buf)->opcode, buf); err = bt_send(buf); if (err) { BT_ERR("Unable to send to driver (err %d)", err); k_sem_give(&bt_dev.ncmd_sem); hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, buf); net_buf_unref(bt_dev.sent_cmd); bt_dev.sent_cmd = NULL; net_buf_unref(buf); } } void process_events(struct k_poll_event *ev, int count) { // BT_DBG("count %d", count); for (; count; ev++, count--) { // BT_DBG("ev->state %u", ev->state); switch (ev->state) { case K_POLL_STATE_SIGNALED: break; case K_POLL_STATE_FIFO_DATA_AVAILABLE: if (ev->tag == BT_EVENT_CMD_TX) { send_cmd(); } else if (IS_ENABLED(CONFIG_BT_CONN)) { struct bt_conn *conn; if (ev->tag == BT_EVENT_CONN_TX_QUEUE) { conn = CONTAINER_OF(ev->fifo, struct bt_conn, tx_queue); bt_conn_process_tx(conn); } } break; case K_POLL_STATE_NOT_READY: break; default: BT_WARN("Unexpected k_poll event state %u", ev->state); break; } } k_sleep(10); } static void read_local_ver_complete(struct net_buf *buf) { struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data; BT_DBG("status 0x%02x", rp->status); bt_dev.hci_version = rp->hci_version; bt_dev.hci_revision = sys_le16_to_cpu(rp->hci_revision); bt_dev.lmp_version = rp->lmp_version; bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion); bt_dev.manufacturer = sys_le16_to_cpu(rp->manufacturer); } static void read_le_features_complete(struct net_buf *buf) { struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data; BT_DBG("status 0x%02x", rp->status); memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features)); } #if defined(CONFIG_BT_BREDR) static void read_buffer_size_complete(struct net_buf *buf) { struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data; u16_t pkts; BT_DBG("status 0x%02x", rp->status); bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len); pkts = sys_le16_to_cpu(rp->acl_max_num); BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu); k_sem_init(&bt_dev.br.pkts, pkts, pkts); } #elif defined(CONFIG_BT_CONN) static void read_buffer_size_complete(struct net_buf *buf) { struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data; u16_t pkts; BT_DBG("status 0x%02x", rp->status); /* If LE-side has buffers we can ignore the BR/EDR values */ if (bt_dev.le.mtu) { return; } bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len); pkts = sys_le16_to_cpu(rp->acl_max_num); BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu); k_sem_init(&bt_dev.le.pkts, pkts, pkts); } #endif #if defined(CONFIG_BT_CONN) static void le_read_buffer_size_complete(struct net_buf *buf) { struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data; BT_DBG("status 0x%02x", rp->status); bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len); if (!bt_dev.le.mtu) { return; } BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu); bt_dev.le.mtu_init = bt_dev.le.mtu; k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num); } #endif static void read_supported_commands_complete(struct net_buf *buf) { struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data; BT_DBG("status 0x%02x", rp->status); memcpy(bt_dev.supported_commands, rp->commands, sizeof(bt_dev.supported_commands)); #if !defined(CONFIG_BT_USE_HCI_API) /* * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as * supported if TinyCrypt ECC is used for emulation. */ if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { bt_dev.supported_commands[34] |= 0x02; bt_dev.supported_commands[34] |= 0x04; } #endif } static void read_local_features_complete(struct net_buf *buf) { struct bt_hci_rp_read_local_features *rp = (void *)buf->data; BT_DBG("status 0x%02x", rp->status); memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0])); } static void le_read_supp_states_complete(struct net_buf *buf) { struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data; BT_DBG("status 0x%02x", rp->status); bt_dev.le.states = sys_get_le64(rp->le_states); } #if defined(CONFIG_BT_SMP) static void le_read_resolving_list_size_complete(struct net_buf *buf) { struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data; BT_DBG("Resolving List size %u", rp->rl_size); bt_dev.le.rl_size = rp->rl_size; } #endif /* defined(CONFIG_BT_SMP) */ #else /* !defined(CONFIG_BT_USE_HCI_API) */ void process_events(struct k_poll_event *ev, int count) { BT_DBG("count %d", count); for (; count; ev++, count--) { BT_DBG("ev->state %u", ev->state); switch (ev->state) { case K_POLL_STATE_SIGNALED: break; case K_POLL_STATE_FIFO_DATA_AVAILABLE: if (ev->tag == BT_EVENT_CMD_TX) { //send_cmd(); } else if (IS_ENABLED(CONFIG_BT_CONN)) { struct bt_conn *conn; if (ev->tag == BT_EVENT_CONN_TX_QUEUE) { conn = CONTAINER_OF(ev->fifo, struct bt_conn, tx_queue); bt_conn_process_tx(conn); } } break; case K_POLL_STATE_NOT_READY: break; default: BT_WARN("Unexpected k_poll event state %u", ev->state); break; } } } static void read_buffer_size_complete(u16_t acl_max_len, uint8_t sco_max_len, u16_t acl_max_num, u16_t sco_max_num) { u16_t pkts; /* If LE-side has buffers we can ignore the BR/EDR values */ if (bt_dev.le.mtu) { return; } bt_dev.le.mtu = acl_max_len; pkts = acl_max_num; BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu); k_sem_init(&bt_dev.le.pkts, pkts, pkts); } #endif /* !defined(CONFIG_BT_USE_HCI_API) */ #if defined(CONFIG_BT_CONN) /* command FIFO + conn_change signal + MAX_CONN */ #define EV_COUNT (2 + CONFIG_BT_MAX_CONN) #else /* command FIFO */ #define EV_COUNT 1 #endif static void hci_tx_thread(void *p1) { static struct k_poll_event events[EV_COUNT] = { K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &bt_dev.cmd_tx_queue, BT_EVENT_CMD_TX), }; extern void scheduler_loop(struct k_poll_event *events); scheduler_loop(events); } static int common_init(void) { #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *rsp; int err; if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) { /* Send HCI_RESET */ err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp); if (err) { // BT_ERR("BT_HCI_OP_RESET, err = %d\n"); return err; } hci_reset_complete(rsp); net_buf_unref(rsp); } /* Read Local Supported Features */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp); if (err) { // BT_ERR("BT_HCI_OP_READ_LOCAL_FEATURES, err = %d\n"); return err; } read_local_features_complete(rsp); net_buf_unref(rsp); /* Read Local Version Information */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL, &rsp); if (err) { // BT_ERR("BT_HCI_OP_READ_LOCAL_VERSION_INFO, err = %d\n"); return err; } read_local_ver_complete(rsp); net_buf_unref(rsp); /* Read Local Supported Commands */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL, &rsp); if (err) { // BT_ERR("BT_HCI_OP_READ_SUPPORTED_COMMANDS, err = %d\n"); return err; } read_supported_commands_complete(rsp); net_buf_unref(rsp); #else int err; if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) { err = hci_api_reset(); if (err) { return err; } hci_reset_complete(); } /* Read Local Supported Features */ err = hci_api_read_local_feature(bt_dev.features[0]); if (err) { return err; } /* Read Local Version Information */ err = hci_api_read_local_version_info(&bt_dev.hci_version, &bt_dev.lmp_version, &bt_dev.hci_revision, &bt_dev.lmp_subversion, &bt_dev.manufacturer); if (err) { return err; } /* Read Local Supported Commands */ err = hci_api_read_local_support_command(bt_dev.supported_commands); if (err) { return err; } #endif if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) { /* Initialize the PRNG so that it is safe to use it later * on in the initialization process. */ extern int prng_init(void); err = prng_init(); if (err) { return err; } } #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) err = set_flow_control(); if (err) { return err; } #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */ return 0; } static int le_set_event_mask(void) { u64_t mask = 0U; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_event_mask *cp_mask; struct net_buf *buf; /* Set LE event mask */ buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask)); if (!buf) { return -ENOBUFS; } cp_mask = net_buf_add(buf, sizeof(*cp_mask)); #endif mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT; if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { mask |= BT_EVT_MASK_LE_ADV_SET_TERMINATED; mask |= BT_EVT_MASK_LE_SCAN_REQ_RECEIVED; mask |= BT_EVT_MASK_LE_EXT_ADVERTISING_REPORT; mask |= BT_EVT_MASK_LE_SCAN_TIMEOUT; } if (IS_ENABLED(CONFIG_BT_CONN)) { if ((IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_PRIVACY(bt_dev.le.features)) || (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { /* C24: * Mandatory if the LE Controller supports Connection * State and either LE Feature (LL Privacy) or * LE Feature (Extended Advertising) is supported, ... */ mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE; } else { mask |= BT_EVT_MASK_LE_CONN_COMPLETE; } mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE; mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE; if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) { mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ; } if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) { mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE; } if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) && (BT_FEAT_LE_PHY_2M(bt_dev.le.features) || BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) { mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE; } } if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_ENCR(bt_dev.le.features)) { mask |= BT_EVT_MASK_LE_LTK_REQUEST; } /* * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are * supported we need to enable events generated by those commands. */ if (IS_ENABLED(CONFIG_BT_ECC) && (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) && (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) { mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE; mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE; } #if !defined(CONFIG_BT_USE_HCI_API) sys_put_le64(mask, cp_mask->events); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL); #else return hci_api_le_set_event_mask(mask); #endif } static int le_init(void) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_write_le_host_supp *cp_le; struct net_buf *buf, *rsp; int err; /* For now we only support LE capable controllers */ if (!BT_FEAT_LE(bt_dev.features)) { BT_ERR("Non-LE capable controller detected!"); return -ENODEV; } /* Read Low Energy Supported Features */ err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL, &rsp); if (err) { return err; } read_le_features_complete(rsp); net_buf_unref(rsp); #if defined(CONFIG_BT_CONN) /* Read LE Buffer Size */ err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE, NULL, &rsp); if (err) { return err; } le_read_buffer_size_complete(rsp); net_buf_unref(rsp); #endif if (BT_FEAT_BREDR(bt_dev.features)) { buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, sizeof(*cp_le)); if (!buf) { return -ENOBUFS; } cp_le = net_buf_add(buf, sizeof(*cp_le)); /* Explicitly enable LE for dual-mode controllers */ cp_le->le = 0x01; cp_le->simul = 0x00; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf, NULL); if (err) { return err; } } /* Read LE Supported States */ if (BT_CMD_LE_STATES(bt_dev.supported_commands)) { err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL, &rsp); if (err) { return err; } le_read_supp_states_complete(rsp); net_buf_unref(rsp); } if (IS_ENABLED(CONFIG_BT_CONN) && IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) { struct bt_hci_cp_le_write_default_data_len *cp; u16_t tx_octets, tx_time; err = hci_le_read_max_data_len(&tx_octets, &tx_time); if (err) { return err; } buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->max_tx_octets = sys_cpu_to_le16(tx_octets); cp->max_tx_time = sys_cpu_to_le16(tx_time); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, buf, NULL); if (err) { return err; } } #if defined(CONFIG_BT_SMP) if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { #if defined(CONFIG_BT_PRIVACY) struct bt_hci_cp_le_set_rpa_timeout *cp; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, NULL); if (err) { return err; } #endif /* defined(CONFIG_BT_PRIVACY) */ err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL, &rsp); if (err) { return err; } le_read_resolving_list_size_complete(rsp); net_buf_unref(rsp); } #endif #else int err; /* For now we only support LE capable controllers */ if (!BT_FEAT_LE(bt_dev.features)) { BT_ERR("Non-LE capable controller detected!"); return -ENODEV; } /* Read Low Energy Supported Features */ err = hci_api_le_read_local_feature(bt_dev.le.features); if (err) { return err; } #if defined(CONFIG_BT_CONN) bt_dev.le.mtu_init = 27; bt_dev.le.mtu = 27; u8_t le_max_num; u16_t le_max_mtu; /* Read LE Buffer Size */ err = hci_api_le_read_buffer_size_complete(&le_max_mtu, &le_max_num); (void)le_max_mtu; if (err) { return err; } if (bt_dev.le.mtu) { bt_dev.le.mtu_init = bt_dev.le.mtu; k_sem_init(&bt_dev.le.pkts, le_max_num, le_max_num); } #endif if (BT_FEAT_BREDR(bt_dev.features)) { /* Explicitly enable LE for dual-mode controllers */ err = hci_api_le_write_host_supp(0x01, 0x00); if (err) { return err; } } /* Read LE Supported States */ if (BT_CMD_LE_STATES(bt_dev.supported_commands)) { err = hci_api_le_read_support_states(&bt_dev.le.states); if (err) { return err; } } if (IS_ENABLED(CONFIG_BT_CONN) && IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) { u16_t tx_octets, tx_time; err = hci_le_read_max_data_len(&tx_octets, &tx_time); if (err) { return err; } err = hci_api_le_set_default_data_len(tx_octets, tx_time); if (err) { return err; } } #if defined(CONFIG_BT_SMP) if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { #if defined(CONFIG_BT_PRIVACY) err = hci_api_le_rpa_timeout_set(CONFIG_BT_RPA_TIMEOUT); if (err) { return err; } #endif /* defined(CONFIG_BT_PRIVACY) */ err = hci_api_le_read_rl_size(&bt_dev.le.rl_size); if (err) { return err; } BT_DBG("Resolving List size %u", bt_dev.le.rl_size); } #endif /* defined(CONFIG_BT_SMP) */ #endif /* defined(CONFIG_BT_USE_HCI_API) */ return le_set_event_mask(); } #if defined(CONFIG_BT_BREDR) static int read_ext_features(void) { int i; /* Read Local Supported Extended Features */ for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) { struct bt_hci_cp_read_local_ext_features *cp; struct bt_hci_rp_read_local_ext_features *rp; struct net_buf *buf, *rsp; int err; buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->page = i; err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, buf, &rsp); if (err) { return err; } rp = (void *)rsp->data; memcpy(&bt_dev.features[i], rp->ext_features, sizeof(bt_dev.features[i])); if (rp->max_page <= i) { net_buf_unref(rsp); break; } net_buf_unref(rsp); } return 0; } void device_supported_pkt_type(void) { /* Device supported features and sco packet types */ if (BT_FEAT_HV2_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2); } if (BT_FEAT_HV3_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3); } if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3); } if (BT_FEAT_EV4_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4); } if (BT_FEAT_EV5_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5); } if (BT_FEAT_2EV3_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3); } if (BT_FEAT_3EV3_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3); } if (BT_FEAT_3SLOT_PKT(bt_dev.features)) { bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 | HCI_PKT_TYPE_ESCO_3EV5); } } static int br_init(void) { struct net_buf *buf; struct bt_hci_cp_write_ssp_mode *ssp_cp; struct bt_hci_cp_write_inquiry_mode *inq_cp; struct bt_hci_write_local_name *name_cp; int err; /* Read extended local features */ if (BT_FEAT_EXT_FEATURES(bt_dev.features)) { err = read_ext_features(); if (err) { return err; } } /* Add local supported packet types to bt_dev */ device_supported_pkt_type(); /* Get BR/EDR buffer size */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf); if (err) { return err; } read_buffer_size_complete(buf); net_buf_unref(buf); /* Set SSP mode */ buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp)); if (!buf) { return -ENOBUFS; } ssp_cp = net_buf_add(buf, sizeof(*ssp_cp)); ssp_cp->mode = 0x01; err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL); if (err) { return err; } /* Enable Inquiry results with RSSI or extended Inquiry */ buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp)); if (!buf) { return -ENOBUFS; } inq_cp = net_buf_add(buf, sizeof(*inq_cp)); inq_cp->mode = 0x02; err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL); if (err) { return err; } /* Set local name */ buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp)); if (!buf) { return -ENOBUFS; } name_cp = net_buf_add(buf, sizeof(*name_cp)); strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME, sizeof(name_cp->local_name)); err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL); if (err) { return err; } /* Set page timeout*/ buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t)); if (!buf) { return -ENOBUFS; } net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT); err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL); if (err) { return err; } /* Enable BR/EDR SC if supported */ if (BT_FEAT_SC(bt_dev.features)) { struct bt_hci_cp_write_sc_host_supp *sc_cp; buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP, sizeof(*sc_cp)); if (!buf) { return -ENOBUFS; } sc_cp = net_buf_add(buf, sizeof(*sc_cp)); sc_cp->sc_support = 0x01; err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf, NULL); if (err) { return err; } } return 0; } #else static int br_init(void) { #if defined(CONFIG_BT_CONN) #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *rsp; int err; if (bt_dev.le.mtu) { return 0; } /* Use BR/EDR buffer size if LE reports zero buffers */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp); if (err) { return err; } read_buffer_size_complete(rsp); net_buf_unref(rsp); #else int err; u16_t acl_max_len = 0; u8_t sco_max_len = 0; u16_t acl_max_num = 0; u16_t sco_max_num = 0; if (bt_dev.le.mtu) { return 0; } /* Use BR/EDR buffer size if LE reports zero buffers */ err = hci_api_read_buffer_size(&acl_max_len, &sco_max_len, &acl_max_num, &sco_max_num); if (err) { return err; } read_buffer_size_complete(acl_max_len, sco_max_len, acl_max_num, sco_max_num); #endif #endif /* CONFIG_BT_CONN */ return 0; } #endif static int set_event_mask(void) { u64_t mask = 0U; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_set_event_mask *ev; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev)); if (!buf) { return -ENOBUFS; } ev = net_buf_add(buf, sizeof(*ev)); #endif if (IS_ENABLED(CONFIG_BT_BREDR)) { /* Since we require LE support, we can count on a * Bluetooth 4.0 feature set */ mask |= BT_EVT_MASK_INQUIRY_COMPLETE; mask |= BT_EVT_MASK_CONN_COMPLETE; mask |= BT_EVT_MASK_CONN_REQUEST; mask |= BT_EVT_MASK_AUTH_COMPLETE; mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE; mask |= BT_EVT_MASK_REMOTE_FEATURES; mask |= BT_EVT_MASK_ROLE_CHANGE; mask |= BT_EVT_MASK_PIN_CODE_REQ; mask |= BT_EVT_MASK_LINK_KEY_REQ; mask |= BT_EVT_MASK_LINK_KEY_NOTIFY; mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI; mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES; mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE; mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT; mask |= BT_EVT_MASK_IO_CAPA_REQ; mask |= BT_EVT_MASK_IO_CAPA_RESP; mask |= BT_EVT_MASK_USER_CONFIRM_REQ; mask |= BT_EVT_MASK_USER_PASSKEY_REQ; mask |= BT_EVT_MASK_SSP_COMPLETE; mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY; } mask |= BT_EVT_MASK_HARDWARE_ERROR; mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW; mask |= BT_EVT_MASK_LE_META_EVENT; if (IS_ENABLED(CONFIG_BT_CONN)) { mask |= BT_EVT_MASK_DISCONN_COMPLETE; mask |= BT_EVT_MASK_REMOTE_VERSION_INFO; } if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_ENCR(bt_dev.le.features)) { mask |= BT_EVT_MASK_ENCRYPT_CHANGE; mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE; } #if !defined(CONFIG_BT_USE_HCI_API) sys_put_le64(mask, ev->events); return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL); #else return hci_api_set_event_mask(mask); #endif } static inline int create_random_addr(bt_addr_le_t *addr) { addr->type = BT_ADDR_LE_RANDOM; return bt_rand(addr->a.val, 6); } int bt_addr_le_create_nrpa(bt_addr_le_t *addr) { int err; err = create_random_addr(addr); if (err) { return err; } BT_ADDR_SET_NRPA(&addr->a); return 0; } int bt_addr_le_create_static(bt_addr_le_t *addr) { int err; err = create_random_addr(addr); if (err) { return err; } BT_ADDR_SET_STATIC(&addr->a); return 0; } static u8_t bt_read_public_addr(bt_addr_le_t *addr) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_rp_read_bd_addr *rp; struct net_buf *rsp; int err; /* Read Bluetooth Address */ err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp); if (err) { BT_WARN("Failed to read public address"); return 0U; } rp = (void *)rsp->data; if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) || !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) { BT_DBG("Controller has no public address"); net_buf_unref(rsp); return 0U; } bt_addr_copy(&addr->a, &rp->bdaddr); addr->type = BT_ADDR_LE_PUBLIC; net_buf_unref(rsp); #else int err = hci_api_read_bdaddr(addr->a.val); if (err) { BT_WARN("Failed to read public address"); return 0U; } addr->type = BT_ADDR_LE_PUBLIC; #endif return 1U; } #if defined(CONFIG_BT_DEBUG) static const char *ver_str(u8_t ver) { const char * const str[] = { "1.0b", "1.1", "1.2", "2.0", "2.1", "3.0", "4.0", "4.1", "4.2", "5.0", "5.1", "5.2" }; if (ver < ARRAY_SIZE(str)) { return str[ver]; } return "unknown"; } static void bt_dev_show_info(void) { int i; BT_INFO("Identity%s: %s", bt_dev.id_count > 1 ? "[0]" : "", bt_addr_le_str(&bt_dev.id_addr[0])); for (i = 1; i < bt_dev.id_count; i++) { BT_INFO("Identity[%d]: %s", i, bt_addr_le_str(&bt_dev.id_addr[i])); } BT_INFO("HCI: version %s (0x%02x) revision 0x%04x, manufacturer 0x%04x", ver_str(bt_dev.hci_version), bt_dev.hci_version, bt_dev.hci_revision, bt_dev.manufacturer); BT_INFO("LMP: version %s (0x%02x) subver 0x%04x", ver_str(bt_dev.lmp_version), bt_dev.lmp_version, bt_dev.lmp_subversion); } #else static inline void bt_dev_show_info(void) { } #endif /* CONFIG_BT_DEBUG */ #if defined(CONFIG_BT_HCI_VS_EXT) #if defined(CONFIG_BT_DEBUG) static const char *vs_hw_platform(u16_t platform) { static const char * const plat_str[] = { "reserved", "Intel Corporation", "Nordic Semiconductor", "NXP Semiconductors" }; if (platform < ARRAY_SIZE(plat_str)) { return plat_str[platform]; } return "unknown"; } static const char *vs_hw_variant(u16_t platform, u16_t variant) { static const char * const nordic_str[] = { "reserved", "nRF51x", "nRF52x", "nRF53x" }; if (platform != BT_HCI_VS_HW_PLAT_NORDIC) { return "unknown"; } if (variant < ARRAY_SIZE(nordic_str)) { return nordic_str[variant]; } return "unknown"; } static const char *vs_fw_variant(u8_t variant) { static const char * const var_str[] = { "Standard Bluetooth controller", "Vendor specific controller", "Firmware loader", "Rescue image", }; if (variant < ARRAY_SIZE(var_str)) { return var_str[variant]; } return "unknown"; } #endif /* CONFIG_BT_DEBUG */ static void hci_vs_init(void) { union { struct bt_hci_rp_vs_read_version_info *info; struct bt_hci_rp_vs_read_supported_commands *cmds; struct bt_hci_rp_vs_read_supported_features *feat; } rp; struct net_buf *rsp; int err; /* If heuristics is enabled, try to guess HCI VS support by looking * at the HCI version and identity address. We haven't set any addresses * at this point. So we need to read the public address. */ if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT)) { bt_addr_le_t addr; if ((bt_dev.hci_version < BT_HCI_VERSION_5_0) || bt_read_public_addr(&addr)) { BT_WARN("Controller doesn't seem to support " "Zephyr vendor HCI"); return; } } err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp); if (err) { BT_WARN("Vendor HCI extensions not available"); return; } if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && rsp->len != sizeof(struct bt_hci_rp_vs_read_version_info)) { BT_WARN("Invalid Vendor HCI extensions"); net_buf_unref(rsp); return; } #if defined(CONFIG_BT_DEBUG) rp.info = (void *)rsp->data; BT_INFO("HW Platform: %s (0x%04x)", vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)), sys_le16_to_cpu(rp.info->hw_platform)); BT_INFO("HW Variant: %s (0x%04x)", vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform), sys_le16_to_cpu(rp.info->hw_variant)), sys_le16_to_cpu(rp.info->hw_variant)); BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u", vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant, rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision), sys_le32_to_cpu(rp.info->fw_build)); #endif /* CONFIG_BT_DEBUG */ net_buf_unref(rsp); err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS, NULL, &rsp); if (err) { BT_WARN("Failed to read supported vendor commands"); return; } if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && rsp->len != sizeof(struct bt_hci_rp_vs_read_supported_commands)) { BT_WARN("Invalid Vendor HCI extensions"); net_buf_unref(rsp); return; } rp.cmds = (void *)rsp->data; memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX); net_buf_unref(rsp); if (BT_VS_CMD_SUP_FEAT(bt_dev.vs_commands)) { err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES, NULL, &rsp); if (err) { BT_WARN("Failed to read supported vendor features"); return; } if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && rsp->len != sizeof(struct bt_hci_rp_vs_read_supported_features)) { BT_WARN("Invalid Vendor HCI extensions"); net_buf_unref(rsp); return; } rp.feat = (void *)rsp->data; memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX); net_buf_unref(rsp); } } #endif /* CONFIG_BT_HCI_VS_EXT */ static int hci_init(void) { int err; err = common_init(); if (err) { return err; } err = le_init(); if (err) { return err; } if (BT_FEAT_BREDR(bt_dev.features)) { err = br_init(); if (err) { return err; } } else if (IS_ENABLED(CONFIG_BT_BREDR)) { BT_ERR("Non-BR/EDR controller detected"); return -EIO; } err = set_event_mask(); if (err) { return err; } #if defined(CONFIG_BT_HCI_VS_EXT) hci_api_vs_init(); #endif if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) { BT_DBG("No user identity. Trying to set public."); bt_setup_public_id_addr(); } if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) { BT_DBG("No public address. Trying to set static random."); err = bt_setup_random_id_addr(); if (err) { BT_ERR("Unable to set identity address"); return err; } /* The passive scanner just sends a dummy address type in the * command. If the first activity does this, and the dummy type * is a random address, it needs a valid value, even though it's * not actually used. */ err = set_random_address(&bt_dev.id_addr[0].a); if (err) { BT_ERR("Unable to set random address"); return err; } } return 0; } int bt_send(struct net_buf *buf) { BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf)); bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); #if !defined(CONFIG_BT_USE_HCI_API) if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { return bt_hci_ecc_send(buf); } #endif return bt_dev.drv->send(buf); } int bt_recv(struct net_buf *buf) { bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); BT_DBG("buf %p len %u", buf, buf->len); switch (bt_buf_get_type(buf)) { #if defined(CONFIG_BT_CONN) case BT_BUF_ACL_IN: #if defined(CONFIG_BT_RECV_IS_RX_THREAD) hci_acl(buf); #else net_buf_put(&bt_dev.rx_queue, buf); #endif return 0; #endif /* BT_CONN */ case BT_BUF_EVT: #if defined(CONFIG_BT_RECV_IS_RX_THREAD) hci_event(buf); #else net_buf_put(&bt_dev.rx_queue, buf); #endif return 0; default: BT_ERR("Invalid buf type %u", bt_buf_get_type(buf)); net_buf_unref(buf); return -EINVAL; } } #if !defined(CONFIG_BT_USE_HCI_API) static const struct event_handler prio_events[] = { EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete, sizeof(struct bt_hci_evt_cmd_complete)), EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status, sizeof(struct bt_hci_evt_cmd_status)), #if defined(CONFIG_BT_CONN) EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW, hci_data_buf_overflow, sizeof(struct bt_hci_evt_data_buf_overflow)), EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS, hci_num_completed_packets, sizeof(struct bt_hci_evt_num_completed_packets)), #endif /* CONFIG_BT_CONN */ }; int bt_recv_prio(struct net_buf *buf) { struct bt_hci_evt_hdr *hdr; bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT); BT_ASSERT(buf->len >= sizeof(*hdr)); hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_ASSERT(bt_hci_evt_is_prio(hdr->evt)); handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events)); net_buf_unref(buf); return 0; } #endif int bt_hci_driver_register(const struct bt_hci_driver *drv) { if (bt_dev.drv) { return -EALREADY; } if (!drv->open || !drv->send) { return -EINVAL; } bt_dev.drv = drv; BT_DBG("Registered %s", drv->name ? drv->name : ""); bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus, BT_ADDR_ANY, drv->name ? drv->name : "bt0"); return 0; } void bt_finalize_init(void) { atomic_set_bit(bt_dev.flags, BT_DEV_READY); if (IS_ENABLED(CONFIG_BT_OBSERVER)) { bt_le_scan_update(false); } bt_dev_show_info(); } static int bt_init(void) { int err; err = hci_init(); if (err) { return err; } if (IS_ENABLED(CONFIG_BT_CONN)) { err = bt_conn_init(); if (err) { return err; } } #if defined(CONFIG_BT_PRIVACY) k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout); #endif if (IS_ENABLED(CONFIG_BT_SETTINGS)) { if (!bt_dev.id_count) { BT_INFO("No ID address. App must call settings_load()"); return 0; } atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID); } bt_finalize_init(); return 0; } static void init_work(struct k_work *work) { int err; err = bt_init(); if (ready_cb) { ready_cb(err); } } #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) static void hci_rx_thread(void * arg) { struct net_buf *buf = NULL; BT_DBG("started"); while (1) { BT_DBG("calling fifo_get_wait"); buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER); BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len); switch (bt_buf_get_type(buf)) { #if defined(CONFIG_BT_CONN) case BT_BUF_ACL_IN: hci_acl(buf); break; #endif /* CONFIG_BT_CONN */ case BT_BUF_EVT: hci_event(buf); break; default: BT_ERR("Unknown buf type %u", bt_buf_get_type(buf)); net_buf_unref(buf); break; } /* Make sure we don't hog the CPU if the rx_queue never * gets empty. */ k_yield(); } } #endif /* !CONFIG_BT_RECV_IS_RX_THREAD */ #if !defined(CONFIG_BT_USE_HCI_API) u16_t bt_hci_get_cmd_opcode(struct net_buf *buf) { return cmd(buf)->opcode; } #endif int bt_enable(bt_ready_cb_t cb) { int err; BT_INFO("enter %s\n", __func__); if (!bt_dev.drv) { BT_ERR("No HCI driver registered"); return -ENODEV; } if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) { return -EALREADY; } if (IS_ENABLED(CONFIG_BT_SETTINGS)) { err = bt_settings_init(); if (err) { return err; } } else { bt_set_name(CONFIG_BT_DEVICE_NAME); } NET_BUF_POOL_INIT(hci_rx_pool); #if defined(CONFIG_BT_CONN) NET_BUF_POOL_INIT(num_complete_pool); #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT) NET_BUF_POOL_INIT(discardable_pool); #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */ #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) NET_BUF_POOL_INIT(acl_in_pool); #endif k_work_q_start(); k_work_init(&bt_dev.init, init_work); #if defined(CONFIG_BT_USE_HCI_API) err = hci_api_init(); if (err) { return err; } #endif #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) k_fifo_init(&bt_dev.rx_queue); #endif ready_cb = cb; #if !defined(CONFIG_BT_USE_HCI_API) #if !defined(CONFIG_BT_WAIT_NOP) k_sem_init(&bt_dev.ncmd_sem,1,1); #else k_sem_init(&bt_dev.ncmd_sem,0,1); #endif NET_BUF_POOL_INIT(hci_cmd_pool); #endif k_fifo_init(&bt_dev.cmd_tx_queue); /* TX thread */ k_thread_spawn(&tx_thread_data, "hci tx", tx_thread_stack, K_THREAD_STACK_SIZEOF(tx_thread_stack), hci_tx_thread, NULL, CONFIG_BT_HCI_TX_PRIO); #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) /* RX thread */ k_thread_spawn(&rx_thread_data, "hci rx", rx_thread_stack, K_THREAD_STACK_SIZEOF(rx_thread_stack),\ hci_rx_thread, NULL, CONFIG_BT_RX_PRIO); #endif #if !defined(CONFIG_BT_USE_HCI_API) if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { bt_hci_ecc_init(); } #endif err = bt_dev.drv->open(); if (err) { BT_ERR("HCI driver open failed (%d)", err); return err; } bt_monitor_send(BT_MONITOR_OPEN_INDEX, NULL, 0); if (!cb) { return bt_init(); } k_work_submit(&bt_dev.init); return 0; } struct bt_ad { const struct bt_data *data; size_t len; }; static int set_data_add(u8_t *set_data, u8_t set_data_len_max, const struct bt_ad *ad, size_t ad_len, u8_t *data_len) { u8_t set_data_len = 0; for (size_t i = 0; i < ad_len; i++) { const struct bt_data *data = ad[i].data; for (size_t j = 0; j < ad[i].len; j++) { size_t len = data[j].data_len; u8_t type = data[j].type; /* Check if ad fit in the remaining buffer */ if ((set_data_len + len + 2) > set_data_len_max) { len = set_data_len_max - (set_data_len + 2); if (type != BT_DATA_NAME_COMPLETE || !len) { BT_ERR("Too big advertising data"); return -EINVAL; } type = BT_DATA_NAME_SHORTENED; } set_data[set_data_len++] = len + 1; set_data[set_data_len++] = type; memcpy(&set_data[set_data_len], data[j].data, len); set_data_len += len; } } *data_len = set_data_len; return 0; } static int hci_set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_adv_data *set_data; struct net_buf *buf; buf = bt_hci_cmd_create(hci_op, sizeof(*set_data)); if (!buf) { return -ENOBUFS; } set_data = net_buf_add(buf, sizeof(*set_data)); (void)memset(set_data, 0, sizeof(*set_data)); err = set_data_add(set_data->data, BT_GAP_ADV_MAX_ADV_DATA_LEN, ad, ad_len, &set_data->len); if (err) { net_buf_unref(buf); return err; } return bt_hci_cmd_send_sync(hci_op, buf, NULL); #else u8_t data[31] = {0}; u8_t len; err = set_data_add(data, BT_GAP_ADV_MAX_ADV_DATA_LEN, ad, ad_len, &len); if (err) { return err; } if (hci_op == BT_HCI_OP_LE_SET_ADV_DATA) { return hci_api_le_set_ad_data(len, data); } else if (hci_op == BT_HCI_OP_LE_SET_SCAN_RSP_DATA) { return hci_api_le_set_sd_data(len, data); } return 0; #endif } /* Set legacy data using Extended Advertising HCI commands */ static int hci_set_ad_ext(struct bt_le_ext_adv *adv, u16_t hci_op, const struct bt_ad *ad, size_t ad_len) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_ext_adv_data *set_data; struct net_buf *buf; buf = bt_hci_cmd_create(hci_op, sizeof(*set_data)); if (!buf) { return -ENOBUFS; } set_data = net_buf_add(buf, sizeof(*set_data)); (void)memset(set_data, 0, sizeof(*set_data)); err = set_data_add(set_data->data, BT_HCI_LE_EXT_ADV_FRAG_MAX_LEN, ad, ad_len, &set_data->len); if (err) { net_buf_unref(buf); return err; } set_data->handle = adv->handle; set_data->op = BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA; set_data->frag_pref = BT_HCI_LE_EXT_ADV_FRAG_DISABLED; return bt_hci_cmd_send_sync(hci_op, buf, NULL); #else u8_t data[251] = {0}; u8_t len; err = set_data_add(data, BT_HCI_LE_EXT_ADV_FRAG_MAX_LEN, ad, ad_len, &len); if (err) { return err; } if (hci_op == BT_HCI_OP_LE_SET_EXT_ADV_DATA) { return hci_api_le_set_ext_ad_data(adv->handle, BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA, BT_HCI_LE_EXT_ADV_FRAG_DISABLED, len, data); } else if (hci_op == BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA) { return hci_api_le_set_ext_sd_data(adv->handle, BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA, BT_HCI_LE_EXT_ADV_FRAG_DISABLED, len, data); } #endif } static int set_ad(struct bt_le_ext_adv *adv, const struct bt_ad *ad, size_t ad_len) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { return hci_set_ad_ext(adv, BT_HCI_OP_LE_SET_EXT_ADV_DATA, ad, ad_len); } return hci_set_ad(BT_HCI_OP_LE_SET_ADV_DATA, ad, ad_len); } static int set_sd(struct bt_le_ext_adv *adv, const struct bt_ad *sd, size_t sd_len) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { return hci_set_ad_ext(adv, BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA, sd, sd_len); } return hci_set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sd, sd_len); } int bt_set_name(const char *name) { #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); size_t len = strlen(name); int err; if (len >= sizeof(bt_dev.name)) { return -ENOMEM; } if (!strcmp(bt_dev.name, name)) { return 0; } strncpy(bt_dev.name, name, sizeof(bt_dev.name)); /* Update advertising name if in use */ if (adv && atomic_test_bit(adv->flags, BT_ADV_INCLUDE_NAME)) { struct bt_data data[] = { BT_DATA(BT_DATA_NAME_COMPLETE, name, strlen(name)) }; struct bt_ad sd = { data, ARRAY_SIZE(data) }; set_sd(adv, &sd, 1); } if (IS_ENABLED(CONFIG_BT_SETTINGS)) { err = settings_save_one("bt/name", bt_dev.name, len); if (err) { BT_WARN("Unable to store name"); } } return 0; #else return -ENOMEM; #endif } const char *bt_get_name(void) { #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) return bt_dev.name; #else return CONFIG_BT_DEVICE_NAME; #endif } int bt_set_id_addr(const bt_addr_le_t *addr) { bt_addr_le_t non_const_addr; if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { BT_ERR("Setting identity not allowed after bt_enable()"); return -EBUSY; } bt_addr_le_copy(&non_const_addr, addr); return bt_id_create(&non_const_addr, NULL); } __WEAK int bt_set_bdaddr(const bt_addr_le_t *addr) { return -ENOTSUP; } void bt_id_get(bt_addr_le_t *addrs, size_t *count) { size_t to_copy = MIN(*count, bt_dev.id_count); memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t)); *count = to_copy; } static int id_find(const bt_addr_le_t *addr) { u8_t id; for (id = 0U; id < bt_dev.id_count; id++) { if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) { return id; } } return -ENOENT; } static void id_create(u8_t id, bt_addr_le_t *addr, u8_t *irk) { if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { bt_addr_le_copy(&bt_dev.id_addr[id], addr); } else { bt_addr_le_t new_addr; do { bt_addr_le_create_static(&new_addr); /* Make sure we didn't generate a duplicate */ } while (id_find(&new_addr) >= 0); bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr); if (addr) { bt_addr_le_copy(addr, &bt_dev.id_addr[id]); } } #if defined(CONFIG_BT_PRIVACY) { u8_t zero_irk[16] = { 0 }; if (irk && memcmp(irk, zero_irk, 16)) { memcpy(&bt_dev.irk[id], irk, 16); } else { bt_rand(&bt_dev.irk[id], 16); if (irk) { memcpy(irk, &bt_dev.irk[id], 16); } } } #endif /* Only store if stack was already initialized. Before initialization * we don't know the flash content, so it's potentially harmful to * try to write anything there. */ if (IS_ENABLED(CONFIG_BT_SETTINGS) && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { bt_settings_save_id(); } } int bt_id_create(bt_addr_le_t *addr, u8_t *irk) { int new_id; if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) { BT_ERR("Only static random identity address supported"); return -EINVAL; } if (id_find(addr) >= 0) { return -EALREADY; } } if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) { return -EINVAL; } if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) { return -ENOMEM; } new_id = bt_dev.id_count++; id_create(new_id, addr, irk); return new_id; } int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk) { struct adv_id_check_data check_data = { .id = id, .adv_enabled = false, }; if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) { BT_ERR("Only static random identity address supported"); return -EINVAL; } if (id_find(addr) >= 0) { return -EALREADY; } } if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) { return -EINVAL; } if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) { return -EINVAL; } bt_adv_foreach(adv_id_check_func, &check_data); if (check_data.adv_enabled) { return -EBUSY; } if (IS_ENABLED(CONFIG_BT_CONN) && bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) { int err; err = bt_unpair(id, NULL); if (err) { return err; } } id_create(id, addr, irk); return id; } int bt_id_delete(u8_t id) { struct adv_id_check_data check_data = { .id = id, .adv_enabled = false, }; if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) { return -EINVAL; } if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) { return -EALREADY; } bt_adv_foreach(adv_id_check_func, &check_data); if (check_data.adv_enabled) { return -EBUSY; } if (IS_ENABLED(CONFIG_BT_CONN)) { int err; err = bt_unpair(id, NULL); if (err) { return err; } } #if defined(CONFIG_BT_PRIVACY) (void)memset(bt_dev.irk[id], 0, 16); #endif bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY); if (id == bt_dev.id_count - 1) { bt_dev.id_count--; } if (IS_ENABLED(CONFIG_BT_SETTINGS) && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { bt_settings_save_id(); } return 0; } #if defined(CONFIG_BT_PRIVACY) static void bt_read_identity_root(u8_t *ir) { /* Invalid IR */ memset(ir, 0, 16); #if defined(CONFIG_BT_HCI_VS_EXT) struct bt_hci_rp_vs_read_key_hierarchy_roots *rp; struct net_buf *rsp; int err; if (!BT_VS_CMD_READ_KEY_ROOTS(bt_dev.vs_commands)) { return; } err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_KEY_HIERARCHY_ROOTS, NULL, &rsp); if (err) { BT_WARN("Failed to read identity root"); return; } if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && rsp->len != sizeof(struct bt_hci_rp_vs_read_key_hierarchy_roots)) { BT_WARN("Invalid Vendor HCI extensions"); net_buf_unref(rsp); return; } rp = (void *)rsp->data; memcpy(ir, rp->ir, 16); net_buf_unref(rsp); #endif /* defined(CONFIG_BT_HCI_VS_EXT) */ } #endif /* defined(CONFIG_BT_PRIVACY) */ void bt_setup_public_id_addr(void) { bt_addr_le_t addr; u8_t *irk = NULL; bt_dev.id_count = bt_read_public_addr(&addr); if (!bt_dev.id_count) { return; } #if defined(CONFIG_BT_PRIVACY) u8_t ir_irk[16]; u8_t ir[16]; bt_read_identity_root(ir); if (!bt_smp_irk_get(ir, ir_irk)) { irk = ir_irk; } else if (IS_ENABLED(CONFIG_BT_SETTINGS)) { atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID); } #endif /* defined(CONFIG_BT_PRIVACY) */ id_create(BT_ID_DEFAULT, &addr, irk); } #if defined(CONFIG_BT_HCI_VS_EXT) u8_t bt_read_static_addr(struct bt_hci_vs_static_addr addrs[], u8_t size) { struct bt_hci_rp_vs_read_static_addrs *rp; struct net_buf *rsp; int err, i; u8_t cnt; if (!BT_VS_CMD_READ_STATIC_ADDRS(bt_dev.vs_commands)) { BT_WARN("Read Static Addresses command not available"); return 0; } err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp); if (err) { BT_WARN("Failed to read static addresses"); return 0; } if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && rsp->len < sizeof(struct bt_hci_rp_vs_read_static_addrs)) { BT_WARN("Invalid Vendor HCI extensions"); net_buf_unref(rsp); return 0; } rp = (void *)rsp->data; cnt = MIN(rp->num_addrs, size); if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && rsp->len != (sizeof(struct bt_hci_rp_vs_read_static_addrs) + rp->num_addrs * sizeof(struct bt_hci_vs_static_addr))) { BT_WARN("Invalid Vendor HCI extensions"); net_buf_unref(rsp); return 0; } for (i = 0; i < cnt; i++) { memcpy(&addrs[i], rp->a, sizeof(struct bt_hci_vs_static_addr)); } net_buf_unref(rsp); if (!cnt) { BT_WARN("No static addresses stored in controller"); } return cnt; } #endif /* CONFIG_BT_HCI_VS_EXT */ int bt_setup_random_id_addr(void) { #if defined(CONFIG_BT_HCI_VS_EXT) || defined(CONFIG_BT_CTLR) /* Only read the addresses if the user has not already configured one or * more identities (!bt_dev.id_count). */ if (!bt_dev.id_count) { struct bt_hci_vs_static_addr addrs[CONFIG_BT_ID_MAX]; bt_dev.id_count = bt_read_static_addr(addrs, CONFIG_BT_ID_MAX); if (bt_dev.id_count) { for (u8_t i = 0; i < bt_dev.id_count; i++) { bt_addr_le_t addr; u8_t *irk = NULL; #if defined(CONFIG_BT_PRIVACY) u8_t ir_irk[16]; if (!bt_smp_irk_get(addrs[i].ir, ir_irk)) { irk = ir_irk; } else if (IS_ENABLED(CONFIG_BT_SETTINGS)) { atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID); } #endif /* CONFIG_BT_PRIVACY */ bt_addr_copy(&addr.a, &addrs[i].bdaddr); addr.type = BT_ADDR_LE_RANDOM; id_create(i, &addr, irk); } return 0; } } #endif /* defined(CONFIG_BT_HCI_VS_EXT) || defined(CONFIG_BT_CTLR) */ if (IS_ENABLED(CONFIG_BT_PRIVACY) && IS_ENABLED(CONFIG_BT_SETTINGS)) { atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID); } return bt_id_create(NULL, NULL); } bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr) { if (IS_ENABLED(CONFIG_BT_SMP)) { struct bt_keys *keys = bt_keys_find_addr(id, addr); /* if there are any keys stored then device is bonded */ return keys && keys->keys; } else { return false; } } static bool valid_adv_ext_param(const struct bt_le_adv_param *param) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { if (param->peer && !(param->options & BT_LE_ADV_OPT_EXT_ADV) && !(param->options & BT_LE_ADV_OPT_CONNECTABLE)) { /* Cannot do directed non-connectable advertising * without extended advertising. */ return false; } if (!(param->options & BT_LE_ADV_OPT_EXT_ADV) && param->options & (BT_LE_ADV_OPT_EXT_ADV | BT_LE_ADV_OPT_NO_2M | BT_LE_ADV_OPT_CODED | BT_LE_ADV_OPT_ANONYMOUS | BT_LE_ADV_OPT_USE_TX_POWER)) { /* Extended options require extended advertising. */ return false; } } if (param->id >= bt_dev.id_count || !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) { return false; } if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) { /* * BT Core 4.2 [Vol 2, Part E, 7.8.5] * The Advertising_Interval_Min and Advertising_Interval_Max * shall not be set to less than 0x00A0 (100 ms) if the * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND. */ if (bt_dev.hci_version < BT_HCI_VERSION_5_0 && param->interval_min < 0x00a0) { return false; } } if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !param->peer) { if (param->interval_min > param->interval_max || param->interval_min < 0x0020 || param->interval_max > 0x4000) { return false; } } return true; } static bool valid_adv_param(const struct bt_le_adv_param *param) { if (param->options & BT_LE_ADV_OPT_EXT_ADV) { return false; } if (param->peer && !(param->options & BT_LE_ADV_OPT_CONNECTABLE)) { return false; } return valid_adv_ext_param(param); } static inline bool ad_has_name(const struct bt_data *ad, size_t ad_len) { size_t i; for (i = 0; i < ad_len; i++) { if (ad[i].type == BT_DATA_NAME_COMPLETE || ad[i].type == BT_DATA_NAME_SHORTENED) { return true; } } return false; } static int le_adv_update(struct bt_le_ext_adv *adv, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, bool scannable, bool use_name) { struct bt_ad d[2] = {}; struct bt_data data; size_t d_len; int err; if (use_name) { const char *name = bt_get_name(); if ((ad && ad_has_name(ad, ad_len)) || (sd && ad_has_name(sd, sd_len))) { /* Cannot use name if name is already set */ return -EINVAL; } data = (struct bt_data)BT_DATA( BT_DATA_NAME_COMPLETE, name, strlen(name)); } d_len = 1; d[0].data = ad; d[0].len = ad_len; if (use_name && !scannable) { d[1].data = &data; d[1].len = 1; d_len = 2; } err = set_ad(adv, d, d_len); if (err) { return err; } if (scannable) { d_len = 1; d[0].data = sd; d[0].len = sd_len; if (use_name) { d[1].data = &data; d[1].len = 1; d_len = 2; } err = set_sd(adv, d, d_len); if (err) { return err; } } atomic_set_bit(adv->flags, BT_ADV_DATA_SET); return 0; } int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); bool scannable, use_name; if (!adv) { return -EINVAL; } if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return -EAGAIN; } scannable = atomic_test_bit(adv->flags, BT_ADV_SCANNABLE); use_name = atomic_test_bit(adv->flags, BT_ADV_INCLUDE_NAME); return le_adv_update(adv, ad, ad_len, sd, sd_len, scannable, use_name); } static u8_t get_filter_policy(u8_t options) { if (!IS_ENABLED(CONFIG_BT_WHITELIST)) { return BT_LE_ADV_FP_NO_WHITELIST; } else if ((options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && (options & BT_LE_ADV_OPT_FILTER_CONN)) { return BT_LE_ADV_FP_WHITELIST_BOTH; } else if (options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) { return BT_LE_ADV_FP_WHITELIST_SCAN_REQ; } else if (options & BT_LE_ADV_OPT_FILTER_CONN) { return BT_LE_ADV_FP_WHITELIST_CONN_IND; } else { return BT_LE_ADV_FP_NO_WHITELIST; } } static int le_adv_set_random_addr(struct bt_le_ext_adv *adv, bt_u32_t options, bool dir_adv, u8_t *own_addr_type) { const bt_addr_le_t *id_addr; int err = 0; /* Set which local identity address we're advertising with */ id_addr = &bt_dev.id_addr[adv->id]; if (options & BT_LE_ADV_OPT_CONNECTABLE) { if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(options & BT_LE_ADV_OPT_USE_IDENTITY)) { err = le_adv_set_private_addr(adv); if (err) { return err; } if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { *own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; } else { *own_addr_type = BT_ADDR_LE_RANDOM; } } else { /* * If Static Random address is used as Identity * address we need to restore it before advertising * is enabled. Otherwise NRPA used for active scan * could be used for advertising. */ if (id_addr->type == BT_ADDR_LE_RANDOM) { err = set_adv_random_address(adv, &id_addr->a); if (err) { return err; } } *own_addr_type = id_addr->type; } if (dir_adv) { if (IS_ENABLED(CONFIG_BT_SMP) && !IS_ENABLED(CONFIG_BT_PRIVACY) && BT_FEAT_LE_PRIVACY(bt_dev.le.features) && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) { /* This will not use RPA for our own address * since we have set zeroed out the local IRK. */ *own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK; } } } else { if (options & BT_LE_ADV_OPT_USE_IDENTITY) { if (id_addr->type == BT_ADDR_LE_RANDOM) { err = set_adv_random_address(adv, &id_addr->a); } *own_addr_type = id_addr->type; } else if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features))) { /* In case advertising set random address is not * available we must handle the shared random address * problem. */ #if defined(CONFIG_BT_OBSERVER) bool scan_enabled = false; /* If active scan with NRPA is ongoing refresh NRPA */ if (!IS_ENABLED(CONFIG_BT_PRIVACY) && !IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) { scan_enabled = true; set_le_scan_enable(false); } #endif /* defined(CONFIG_BT_OBSERVER) */ err = le_adv_set_private_addr(adv); *own_addr_type = BT_ADDR_LE_RANDOM; #if defined(CONFIG_BT_OBSERVER) if (scan_enabled) { set_le_scan_enable(true); } #endif /* defined(CONFIG_BT_OBSERVER) */ } else { err = le_adv_set_private_addr(adv); *own_addr_type = BT_ADDR_LE_RANDOM; } if (err) { return err; } } return 0; } static int le_adv_start_add_conn(const struct bt_le_ext_adv *adv, struct bt_conn **out_conn) { struct adv_id_check_data check_data = { .id = adv->id, .adv_enabled = false }; struct bt_conn *conn; bt_adv_foreach(adv_id_check_connectable_func, &check_data); if (check_data.adv_enabled) { return -ENOTSUP; } bt_dev.adv_conn_id = adv->id; if (!bt_addr_le_cmp(&adv->target_addr, BT_ADDR_LE_ANY)) { /* Undirected advertising */ conn = bt_conn_add_le(adv->id, BT_ADDR_LE_NONE); if (!conn) { return -ENOMEM; } bt_conn_set_state(conn, BT_CONN_CONNECT_ADV); *out_conn = conn; return 0; } if (bt_conn_exists_le(adv->id, &adv->target_addr)) { return -EINVAL; } conn = bt_conn_add_le(adv->id, &adv->target_addr); if (!conn) { return -ENOMEM; } bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV); *out_conn = conn; return 0; } int bt_le_adv_start_legacy(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) { struct bt_conn *conn = NULL; bool dir_adv = (param->peer != NULL), scannable; int err; struct bt_le_ext_adv *adv; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_adv_param set_param; struct net_buf *buf; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (!valid_adv_param(param)) { return -EINVAL; } if (!bt_le_adv_random_addr_check(param)) { return -EINVAL; } (void)memset(&set_param, 0, sizeof(set_param)); set_param.min_interval = sys_cpu_to_le16(param->interval_min); set_param.max_interval = sys_cpu_to_le16(param->interval_max); set_param.channel_map = param->channel_map ? param->channel_map : 0x07; set_param.filter_policy = get_filter_policy(param->options); adv = adv_new_legacy(); if (!adv || atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return -EALREADY; } if (adv->id != param->id) { atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); } adv->id = param->id; bt_dev.adv_conn_id = adv->id; err = le_adv_set_random_addr(adv, param->options, dir_adv, &set_param.own_addr_type); if (err) { return err; } if (dir_adv) { bt_addr_le_copy(&adv->target_addr, param->peer); } else { bt_addr_le_copy(&adv->target_addr, BT_ADDR_LE_ANY); } if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { scannable = true; if (dir_adv) { if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) { set_param.type = BT_HCI_ADV_DIRECT_IND_LOW_DUTY; } else { set_param.type = BT_HCI_ADV_DIRECT_IND; } bt_addr_le_copy(&set_param.direct_addr, param->peer); } else { set_param.type = BT_HCI_ADV_IND; } } else { scannable = sd || (param->options & BT_LE_ADV_OPT_USE_NAME); set_param.type = scannable ? BT_HCI_ADV_SCAN_IND : BT_HCI_ADV_NONCONN_IND; } buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param)); if (!buf) { return -ENOBUFS; } net_buf_add_mem(buf, &set_param, sizeof(set_param)); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL); #else u8_t type; u8_t own_addr_type; u8_t peer_addr_type = 0; u8_t peer_addr[6] = {0}; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (!valid_adv_param(param)) { return -EINVAL; } if (!bt_le_adv_random_addr_check(param)) { return -EINVAL; } adv = adv_new_legacy(); if (!adv || atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return -EALREADY; } if (adv->id != param->id) { atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); } adv->id = param->id; bt_dev.adv_conn_id = adv->id; err = le_adv_set_random_addr(adv, param->options, dir_adv, &own_addr_type); if (err) { return err; } if (dir_adv) { bt_addr_le_copy(&adv->target_addr, param->peer); } else { bt_addr_le_copy(&adv->target_addr, BT_ADDR_LE_ANY); } if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { scannable = true; if (dir_adv) { if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) { type = BT_HCI_ADV_DIRECT_IND_LOW_DUTY; } else { type = BT_HCI_ADV_DIRECT_IND; } peer_addr_type = param->peer->type; memcpy(peer_addr, param->peer->a.val, 6); } else { type = BT_HCI_ADV_IND; } } else { scannable = sd || (param->options & BT_LE_ADV_OPT_USE_NAME); type = scannable ? BT_HCI_ADV_SCAN_IND : BT_HCI_ADV_NONCONN_IND; } err = hci_api_le_adv_param(param->interval_min, param->interval_max, type, own_addr_type, peer_addr_type, peer_addr, param->channel_map ? param->channel_map : 0x07, get_filter_policy(param->options)); #endif if (err) { BT_ERR("hci adv param err = %d", err); return err; } if (!dir_adv) { err = le_adv_update(adv, ad, ad_len, sd, sd_len, scannable, param->options & BT_LE_ADV_OPT_USE_NAME); if (err) { BT_ERR("le_adv_update err = %d", err); return err; } } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && (param->options & BT_LE_ADV_OPT_CONNECTABLE)) { err = le_adv_start_add_conn(adv, &conn); if (err) { BT_ERR("le adv add conn err = %d", err); return err; } } err = set_le_adv_enable(adv, true); if (err) { BT_ERR("Failed to start advertiser"); if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) { bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); } return err; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) { /* If undirected connectable advertiser we have created a * connection object that we don't yet give to the application. * Since we don't give the application a reference to manage in * this case, we need to release this reference here */ bt_conn_unref(conn); } atomic_set_bit_to(adv->flags, BT_ADV_PERSIST, !dir_adv && !(param->options & BT_LE_ADV_OPT_ONE_TIME)); atomic_set_bit_to(adv->flags, BT_ADV_INCLUDE_NAME, param->options & BT_LE_ADV_OPT_USE_NAME); atomic_set_bit_to(adv->flags, BT_ADV_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE); atomic_set_bit_to(adv->flags, BT_ADV_SCANNABLE, scannable); atomic_set_bit_to(adv->flags, BT_ADV_USE_IDENTITY, param->options & BT_LE_ADV_OPT_USE_IDENTITY); return 0; } static int le_ext_adv_param_set(struct bt_le_ext_adv *adv, const struct bt_le_adv_param *param, bool has_scan_data) { bool dir_adv = param->peer != NULL, scannable; int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_ext_adv_param *cp; struct net_buf *buf, *rsp; buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EXT_ADV_PARAM, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); (void)memset(cp, 0, sizeof(*cp)); err = le_adv_set_random_addr(adv, param->options, dir_adv, &cp->own_addr_type); if (err) { return err; } if (dir_adv) { bt_addr_le_copy(&adv->target_addr, param->peer); } else { bt_addr_le_copy(&adv->target_addr, BT_ADDR_LE_ANY); } cp->handle = adv->handle; sys_put_le24(param->interval_min, cp->prim_min_interval); sys_put_le24(param->interval_max, cp->prim_max_interval); cp->prim_channel_map = 0x07; cp->filter_policy = get_filter_policy(param->options); cp->tx_power = BT_HCI_LE_ADV_TX_POWER_NO_PREF; cp->prim_adv_phy = BT_HCI_LE_PHY_1M; if (param->options & BT_LE_ADV_OPT_EXT_ADV) { if (param->options & BT_LE_ADV_OPT_NO_2M) { cp->sec_adv_phy = BT_HCI_LE_PHY_1M; } else { cp->sec_adv_phy = BT_HCI_LE_PHY_2M; } } if (param->options & BT_LE_ADV_OPT_CODED) { cp->prim_adv_phy = BT_HCI_LE_PHY_CODED; cp->sec_adv_phy = BT_HCI_LE_PHY_CODED; } if (!(param->options & BT_LE_ADV_OPT_EXT_ADV)) { cp->props |= BT_HCI_LE_ADV_PROP_LEGACY; } if (param->options & BT_LE_ADV_OPT_USE_TX_POWER) { cp->props |= BT_HCI_LE_ADV_PROP_TX_POWER; } if (param->options & BT_LE_ADV_OPT_ANONYMOUS) { cp->props |= BT_HCI_LE_ADV_PROP_ANON; } if (param->options & BT_LE_ADV_OPT_NOTIFY_SCAN_REQ) { cp->scan_req_notify_enable = BT_HCI_LE_ADV_SCAN_REQ_ENABLE; } if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { cp->props |= BT_HCI_LE_ADV_PROP_CONN; if (!dir_adv && !(param->options & BT_LE_ADV_OPT_EXT_ADV)) { /* When using non-extended adv packets then undirected * advertising has to be scannable as well. * We didn't require this option to be set before, so * it is implicitly set instead in this case. */ cp->props |= BT_HCI_LE_ADV_PROP_SCAN; } } if ((param->options & BT_LE_ADV_OPT_SCANNABLE) || has_scan_data) { cp->props |= BT_HCI_LE_ADV_PROP_SCAN; } scannable = !!(cp->props & BT_HCI_LE_ADV_PROP_SCAN); if (dir_adv) { cp->props |= BT_HCI_LE_ADV_PROP_DIRECT; if (!(param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY)) { cp->props |= BT_HCI_LE_ADV_PROP_HI_DC_CONN; } bt_addr_le_copy(&cp->peer_addr, param->peer); } cp->sid = param->sid; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_ADV_PARAM, buf, &rsp); if (err) { return err; } #if defined(CONFIG_BT_EXT_ADV) struct bt_hci_rp_le_set_ext_adv_param *rp = (void *)rsp->data; adv->tx_power = rp->tx_power; #endif /* defined(CONFIG_BT_EXT_ADV) */ net_buf_unref(rsp); #else u8_t own_addr_type; u8_t peer_addr_type = 0; u8_t peer_addr[6] = {0}; u8_t prim_adv_phy = 0; u8_t sec_adv_phy = 0; u16_t props = 0; u8_t scan_req_notify_enable = 0; err = le_adv_set_random_addr(adv, param->options, dir_adv, &own_addr_type); if (err) { return err; } if (dir_adv) { bt_addr_le_copy(&adv->target_addr, param->peer); } else { bt_addr_le_copy(&adv->target_addr, BT_ADDR_LE_ANY); } if (param->options & BT_LE_ADV_OPT_EXT_ADV) { if (param->options & BT_LE_ADV_OPT_NO_2M) { sec_adv_phy = BT_HCI_LE_PHY_1M; } else { sec_adv_phy = BT_HCI_LE_PHY_2M; } } prim_adv_phy = BT_HCI_LE_PHY_1M; if (param->options & BT_LE_ADV_OPT_CODED) { prim_adv_phy = BT_HCI_LE_PHY_CODED; sec_adv_phy = BT_HCI_LE_PHY_CODED; } if (!(param->options & BT_LE_ADV_OPT_EXT_ADV)) { props |= BT_HCI_LE_ADV_PROP_LEGACY; } if (param->options & BT_LE_ADV_OPT_USE_TX_POWER) { props |= BT_HCI_LE_ADV_PROP_TX_POWER; } if (param->options & BT_LE_ADV_OPT_ANONYMOUS) { props |= BT_HCI_LE_ADV_PROP_ANON; } if (param->options & BT_LE_ADV_OPT_NOTIFY_SCAN_REQ) { scan_req_notify_enable = BT_HCI_LE_ADV_SCAN_REQ_ENABLE; } if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { props |= BT_HCI_LE_ADV_PROP_CONN; if (!dir_adv && !(param->options & BT_LE_ADV_OPT_EXT_ADV)) { /* When using non-extended adv packets then undirected * advertising has to be scannable as well. * We didn't require this option to be set before, so * it is implicitly set instead in this case. */ props |= BT_HCI_LE_ADV_PROP_SCAN; } } if ((param->options & BT_LE_ADV_OPT_SCANNABLE) || has_scan_data) { props |= BT_HCI_LE_ADV_PROP_SCAN; } scannable = !!(props & BT_HCI_LE_ADV_PROP_SCAN); if (dir_adv) { props |= BT_HCI_LE_ADV_PROP_DIRECT; if (!(param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY)) { props |= BT_HCI_LE_ADV_PROP_HI_DC_CONN; } peer_addr_type = param->peer->type; memcpy(peer_addr, param->peer->a.val, 6); } int8_t tx_power = 0; err = hci_api_le_ext_adv_param_set (adv->handle, props, param->interval_min, param->interval_max, 0x07, own_addr_type, peer_addr_type, peer_addr, get_filter_policy(param->options), BT_HCI_LE_ADV_TX_POWER_NO_PREF, prim_adv_phy, 0, sec_adv_phy, param->sid, scan_req_notify_enable, &tx_power); if (err) { return err; } #if defined(CONFIG_BT_EXT_ADV) adv->tx_power = tx_power; #endif /* defined(CONFIG_BT_EXT_ADV) */ #endif atomic_set_bit(adv->flags, BT_ADV_PARAMS_SET); if (atomic_test_and_clear_bit(adv->flags, BT_ADV_RANDOM_ADDR_PENDING)) { err = set_adv_random_address(adv, &adv->random_addr.a); if (err) { return err; } } /* Flag only used by bt_le_adv_start API. */ atomic_set_bit_to(adv->flags, BT_ADV_PERSIST, false); atomic_set_bit_to(adv->flags, BT_ADV_INCLUDE_NAME, param->options & BT_LE_ADV_OPT_USE_NAME); atomic_set_bit_to(adv->flags, BT_ADV_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE); atomic_set_bit_to(adv->flags, BT_ADV_SCANNABLE, scannable); atomic_set_bit_to(adv->flags, BT_ADV_USE_IDENTITY, param->options & BT_LE_ADV_OPT_USE_IDENTITY); return 0; } int bt_le_adv_start_ext(struct bt_le_ext_adv *adv, const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) { struct bt_le_ext_adv_start_param start_param = { .timeout = 0, .num_events = 0, }; bool dir_adv = (param->peer != NULL); struct bt_conn *conn = NULL; int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (!valid_adv_param(param)) { return -EINVAL; } if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return -EALREADY; } adv->id = param->id; err = le_ext_adv_param_set(adv, param, sd || (param->options & BT_LE_ADV_OPT_USE_NAME)); if (err) { return err; } if (!dir_adv) { err = bt_le_ext_adv_set_data(adv, ad, ad_len, sd, sd_len); if (err) { return err; } } else { if (!(param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY)) { start_param.timeout = BT_GAP_ADV_HIGH_DUTY_CYCLE_MAX_TIMEOUT; atomic_set_bit(adv->flags, BT_ADV_LIMITED); } } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && (param->options & BT_LE_ADV_OPT_CONNECTABLE)) { err = le_adv_start_add_conn(adv, &conn); if (err) { return err; } } err = set_le_adv_enable_ext(adv, true, &start_param); if (err) { BT_ERR("Failed to start advertiser"); if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) { bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); } return err; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) { /* If undirected connectable advertiser we have created a * connection object that we don't yet give to the application. * Since we don't give the application a reference to manage in * this case, we need to release this reference here */ bt_conn_unref(conn); } /* Flag always set to false by le_ext_adv_param_set */ atomic_set_bit_to(adv->flags, BT_ADV_PERSIST, !dir_adv && !(param->options & BT_LE_ADV_OPT_ONE_TIME)); return 0; } int bt_le_adv_start(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) { if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { struct bt_le_ext_adv *adv = adv_new_legacy(); int err; if (!adv) { return -ENOMEM; } err = bt_le_adv_start_ext(adv, param, ad, ad_len, sd, sd_len); if (err) { adv_delete_legacy(); } return err; } return bt_le_adv_start_legacy(param, ad, ad_len, sd, sd_len); } int bt_le_adv_stop(void) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); int err; if (!adv) { BT_ERR("No valid legacy adv"); return 0; } /* Make sure advertising is not re-enabled later even if it's not * currently enabled (i.e. BT_DEV_ADVERTISING is not set). */ atomic_clear_bit(adv->flags, BT_ADV_PERSIST); if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { /* Legacy advertiser exists, but is not currently advertising. * This happens when keep advertising behavior is active but * no conn object is available to do connectable advertising. */ adv_delete_legacy(); return 0; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) { le_adv_stop_free_conn(adv, 0); } if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { err = set_le_adv_enable_ext(adv, false, NULL); if (err) { return err; } } else { err = set_le_adv_enable_legacy(adv, false); if (err) { return err; } } adv_delete_legacy(); #if defined(CONFIG_BT_OBSERVER) if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) && !IS_ENABLED(CONFIG_BT_PRIVACY) && !IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY)) { /* If scan is ongoing set back NRPA */ if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); le_set_private_addr(BT_ID_DEFAULT); set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); } } #endif /* defined(CONFIG_BT_OBSERVER) */ return 0; } static inline int parse_ad(uint8_t *data, uint16_t len, int (* cb)(struct bt_data *data, void *arg), void *cb_arg) { int num = 0; uint8_t *pdata = data; struct bt_data ad = {0}; int ret; while (len) { if (pdata[0] == 0) { return num; } if (len < pdata[0] + 1) { return -1; }; ad.data_len = pdata[0] - 1; ad.type = pdata[1]; ad.data = &pdata[2]; if (cb) { ret = cb(&ad, cb_arg); if (ret) { break; } } num++; len -= (pdata[0] + 1); pdata += (pdata[0] + 1); } return num; } static inline int adv_ad_callback(struct bt_data *ad, void *arg) { struct bt_data **pad = (struct bt_data **)arg; (*pad)->type = ad->type; (*pad)->data_len = ad->data_len; (*pad)->data = ad->data; (*pad)++; return 0; } int bt_le_adv_start_instant(const struct bt_le_adv_param *param, uint8_t *ad_data, size_t ad_len, uint8_t *sd_data, size_t sd_len) { struct bt_data ad[10] = {0}; struct bt_data *pad = NULL; struct bt_data sd[10] = {0}; struct bt_data *psd = NULL; int ad_num = 0; int sd_num = 0; if (ad_data && ad_len) { pad = ad; ad_num = parse_ad(ad_data, ad_len, adv_ad_callback, (void *)&pad); pad = ad; } if (sd_data && sd_len) { psd = sd; sd_num = parse_ad(sd_data, sd_len, adv_ad_callback, (void *)&psd); psd = sd; } return bt_le_adv_start(param, pad, ad_num, psd, sd_num); } int bt_le_adv_stop_instant(void) { return bt_le_adv_stop(); } #if defined(CONFIG_BT_PERIPHERAL) void bt_le_adv_resume(void) { struct bt_le_ext_adv *adv = bt_adv_lookup_legacy(); struct bt_conn *conn; int err; if (!adv) { BT_DBG("No valid legacy adv"); return; } if (!(atomic_test_bit(adv->flags, BT_ADV_PERSIST) && !atomic_test_bit(adv->flags, BT_ADV_ENABLED))) { return; } if (!atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) { return; } err = le_adv_start_add_conn(adv, &conn); if (err) { BT_DBG("Cannot resume connectable advertising (%d)", err); return; } BT_DBG("Resuming connectable advertising"); if (IS_ENABLED(CONFIG_BT_PRIVACY) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { le_adv_set_private_addr(adv); } err = set_le_adv_enable(adv, true); if (err) { bt_conn_set_state(conn, BT_CONN_DISCONNECTED); } /* Since we don't give the application a reference to manage in * this case, we need to release this reference here. */ bt_conn_unref(conn); } #endif /* defined(CONFIG_BT_PERIPHERAL) */ #if defined(CONFIG_BT_EXT_ADV) int bt_le_ext_adv_get_info(const struct bt_le_ext_adv *adv, struct bt_le_ext_adv_info *info) { info->id = adv->id; info->tx_power = adv->tx_power; return 0; } int bt_le_ext_adv_create(const struct bt_le_adv_param *param, const struct bt_le_ext_adv_cb *cb, struct bt_le_ext_adv **out_adv) { struct bt_le_ext_adv *adv; int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (!valid_adv_ext_param(param)) { return -EINVAL; } adv = adv_new(); if (!adv) { return -ENOMEM; } adv->id = param->id; adv->cb = cb; err = le_ext_adv_param_set(adv, param, false); if (err) { adv_delete(adv); return err; } *out_adv = adv; return 0; } int bt_le_ext_adv_update_param(struct bt_le_ext_adv *adv, const struct bt_le_adv_param *param) { if (!valid_adv_ext_param(param)) { return -EINVAL; } if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return -EINVAL; } if (param->id != adv->id) { atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID); } return le_ext_adv_param_set(adv, param, false); } int bt_le_ext_adv_start(struct bt_le_ext_adv *adv, struct bt_le_ext_adv_start_param *param) { struct bt_conn *conn = NULL; int err; if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) { err = le_adv_start_add_conn(adv, &conn); if (err) { return err; } } atomic_set_bit_to(adv->flags, BT_ADV_LIMITED, param && (param->timeout > 0 || param->num_events > 0)); le_adv_set_private_addr(adv); if (atomic_test_bit(adv->flags, BT_ADV_INCLUDE_NAME) && !atomic_test_bit(adv->flags, BT_ADV_DATA_SET)) { /* Set the advertiser name */ bt_le_ext_adv_set_data(adv, NULL, 0, NULL, 0); } err = set_le_adv_enable_ext(adv, true, param); if (err) { BT_ERR("Failed to start advertiser"); if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) { bt_conn_set_state(conn, BT_CONN_DISCONNECTED); bt_conn_unref(conn); } return err; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) { /* If undirected connectable advertiser we have created a * connection object that we don't yet give to the application. * Since we don't give the application a reference to manage in * this case, we need to release this reference here */ bt_conn_unref(conn); } return 0; } int bt_le_ext_adv_stop(struct bt_le_ext_adv *adv) { atomic_clear_bit(adv->flags, BT_ADV_PERSIST); if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return 0; } if (atomic_test_and_clear_bit(adv->flags, BT_ADV_LIMITED)) { atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID); #if defined(CONFIG_BT_SMP) pending_id_keys_update(); #endif } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) { le_adv_stop_free_conn(adv, 0); } return set_le_adv_enable_ext(adv, false, NULL); } int bt_le_ext_adv_set_data(struct bt_le_ext_adv *adv, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) { bool scannable, use_name; scannable = atomic_test_bit(adv->flags, BT_ADV_SCANNABLE); use_name = atomic_test_bit(adv->flags, BT_ADV_INCLUDE_NAME); return le_adv_update(adv, ad, ad_len, sd, sd_len, scannable, use_name); } int bt_le_ext_adv_delete(struct bt_le_ext_adv *adv) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_remove_adv_set *cp; struct net_buf *buf; #endif if (!BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { return -ENOTSUP; } /* Advertising set should be stopped first */ if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) { return -EINVAL; } #if !defined(CONFIG_BT_USE_HCI_API) buf = bt_hci_cmd_create(BT_HCI_OP_LE_REMOVE_ADV_SET, sizeof(*cp)); if (!buf) { BT_WARN("No HCI buffers"); return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->handle = adv->handle; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REMOVE_ADV_SET, buf, NULL); #else err = hci_api_le_remove_adv_set(adv->handle); #endif if (err) { return err; } adv_delete(adv); return 0; } #endif /* defined(CONFIG_BT_EXT_ADV) */ #if defined(CONFIG_BT_OBSERVER) static bool valid_le_scan_param(const struct bt_le_scan_param *param) { if (param->type != BT_HCI_LE_SCAN_PASSIVE && param->type != BT_HCI_LE_SCAN_ACTIVE) { return false; } if (param->options & ~(BT_LE_SCAN_OPT_FILTER_DUPLICATE | BT_LE_SCAN_OPT_FILTER_WHITELIST | BT_LE_SCAN_OPT_CODED | BT_LE_SCAN_OPT_NO_1M)) { return false; } if (param->interval < 0x0004 || param->interval > 0x4000) { return false; } if (param->window < 0x0004 || param->window > 0x4000) { return false; } if (param->window > param->interval) { return false; } return true; } int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb) { int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } /* Check that the parameters have valid values */ if (!valid_le_scan_param(param)) { return -EINVAL; } if (param->type && !bt_le_scan_random_addr_check()) { return -EINVAL; } /* Return if active scan is already enabled */ if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { return -EALREADY; } if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); if (err) { atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); return err; } } atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, param->options & BT_LE_SCAN_OPT_FILTER_DUPLICATE); #if defined(CONFIG_BT_WHITELIST) atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, param->options & BT_LE_SCAN_OPT_FILTER_WHITELIST); #endif /* defined(CONFIG_BT_WHITELIST) */ if (IS_ENABLED(CONFIG_BT_EXT_ADV) && BT_FEAT_LE_EXT_ADV(bt_dev.le.features)) { struct bt_hci_ext_scan_phy param_1m; struct bt_hci_ext_scan_phy param_coded; struct bt_hci_ext_scan_phy *phy_1m = NULL; struct bt_hci_ext_scan_phy *phy_coded = NULL; if (!(param->options & BT_LE_SCAN_OPT_NO_1M)) { param_1m.type = param->type; param_1m.interval = sys_cpu_to_le16(param->interval); param_1m.window = sys_cpu_to_le16(param->window); phy_1m = &param_1m; } if (param->options & BT_LE_SCAN_OPT_CODED) { u16_t interval = param->interval_coded ? param->interval_coded : param->interval; u16_t window = param->window_coded ? param->window_coded : param->window; param_coded.type = param->type; param_coded.interval = sys_cpu_to_le16(interval); param_coded.window = sys_cpu_to_le16(window); phy_coded = &param_coded; } err = start_le_scan_ext(phy_1m, phy_coded, param->timeout); } else { if (param->timeout) { return -ENOTSUP; } err = start_le_scan_legacy(param->type, param->interval, param->window); } if (err) { atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); return err; } scan_dev_found_cb = cb; return 0; } int bt_le_scan_stop(void) { /* Return if active scanning is already disabled */ if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { return -EALREADY; } scan_dev_found_cb = NULL; if (IS_ENABLED(CONFIG_BT_EXT_ADV) && atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) { atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); #if defined(CONFIG_BT_SMP) pending_id_keys_update(); #endif } return bt_le_scan_update(false); } void bt_le_scan_cb_register(struct bt_le_scan_cb *cb) { sys_slist_append(&scan_cbs, &cb->node); } #endif /* CONFIG_BT_OBSERVER */ #if defined(CONFIG_BT_WHITELIST) int bt_le_whitelist_add(const bt_addr_le_t *addr) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_add_dev_to_wl *cp; struct net_buf *buf; #endif if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } #if !defined(CONFIG_BT_USE_HCI_API) buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_le_copy(&cp->addr, addr); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL); #else err = hci_api_white_list_add(addr->type, (u8_t *)addr->a.val); #endif if (err) { BT_ERR("Failed to add device to whitelist"); return err; } return 0; } int bt_le_whitelist_rem(const bt_addr_le_t *addr) { int err; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_rem_dev_from_wl *cp; struct net_buf *buf; #endif if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } #if !defined(CONFIG_BT_USE_HCI_API) buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_le_copy(&cp->addr, addr); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL); #else err = hci_api_white_list_remove(addr->type, (u8_t *)addr->a.val); #endif if (err) { BT_ERR("Failed to remove device from whitelist"); return err; } return 0; } int bt_le_whitelist_clear(void) { int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } #if !defined(CONFIG_BT_USE_HCI_API) err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL); #else err = hci_api_white_list_clear(); #endif if (err) { BT_ERR("Failed to clear whitelist"); return err; } return 0; } int bt_le_whitelist_size(u8_t *size) { #if !defined(CONFIG_BT_USE_HCI_API) int err; struct net_buf *rsp; err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL, &rsp); if (err) { return err; } struct bt_hci_rp_le_read_wl_size *rp = (void *)rsp->data; if (rp->status) { net_buf_unref(rsp); return rp->status; } *size = rp->wl_size; net_buf_unref(rsp); return 0; #else return hci_api_white_list_size(size); #endif } #endif /* defined(CONFIG_BT_WHITELIST) */ int bt_le_set_chan_map(u8_t chan_map[5]) { if (!IS_ENABLED(CONFIG_BT_CENTRAL)) { return -ENOTSUP; } #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_set_host_chan_classif *cp; struct net_buf *buf; if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) { BT_WARN("Set Host Channel Classification command is " "not supported"); return -ENOTSUP; } buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memcpy(&cp->ch_map[0], &chan_map[0], 4); cp->ch_map[4] = chan_map[4] & BIT_MASK(5); return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, buf, NULL); #else u8_t ch_map[5] = {0}; memcpy(&ch_map[0], &chan_map[0], 4); ch_map[4] = chan_map[4] & BIT_MASK(5); return hci_api_le_set_host_chan_classif(ch_map); #endif } struct net_buf *bt_buf_get_rx(enum bt_buf_type type, k_timeout_t timeout) { struct net_buf *buf; __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN, "Invalid buffer type requested"); #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) if (type == BT_BUF_EVT) { buf = net_buf_alloc(&hci_rx_pool, timeout); } else { buf = net_buf_alloc(&acl_in_pool, timeout); } #else buf = net_buf_alloc(&hci_rx_pool, timeout); #endif if (buf) { net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, type); } return buf; } #if !defined(CONFIG_BT_USE_HCI_API) struct net_buf *bt_buf_get_cmd_complete(k_timeout_t timeout) { struct net_buf *buf; unsigned int key; key = irq_lock(); buf = bt_dev.sent_cmd; bt_dev.sent_cmd = NULL; irq_unlock(key); BT_DBG("sent_cmd %p", buf); if (buf) { bt_buf_set_type(buf, BT_BUF_EVT); buf->len = 0U; net_buf_reserve(buf, BT_BUF_RESERVE); return buf; } return bt_buf_get_rx(BT_BUF_EVT, timeout); } #endif struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, k_timeout_t timeout) { switch (evt) { #if defined(CONFIG_BT_CONN) case BT_HCI_EVT_NUM_COMPLETED_PACKETS: { struct net_buf *buf; buf = net_buf_alloc(&num_complete_pool, timeout); if (buf) { net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, BT_BUF_EVT); } return buf; } #endif /* CONFIG_BT_CONN */ case BT_HCI_EVT_CMD_COMPLETE: case BT_HCI_EVT_CMD_STATUS: return bt_buf_get_cmd_complete(timeout); default: #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT) if (discardable) { struct net_buf *buf; buf = net_buf_alloc(&discardable_pool, timeout); if (buf) { net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, BT_BUF_EVT); } return buf; } #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */ return bt_buf_get_rx(BT_BUF_EVT, timeout); } } #if defined(CONFIG_BT_BREDR) static int br_start_inquiry(const struct bt_br_discovery_param *param) { const u8_t iac[3] = { 0x33, 0x8b, 0x9e }; struct bt_hci_op_inquiry *cp; struct net_buf *buf; buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp)); if (!buf) { return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); cp->length = param->length; cp->num_rsp = 0xff; /* we limit discovery only by time */ memcpy(cp->lap, iac, 3); if (param->limited) { cp->lap[0] = 0x00; } return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL); } static bool valid_br_discov_param(const struct bt_br_discovery_param *param, size_t num_results) { if (!num_results || num_results > 255) { return false; } if (!param->length || param->length > 0x30) { return false; } return true; } int bt_br_discovery_start(const struct bt_br_discovery_param *param, struct bt_br_discovery_result *results, size_t cnt, bt_br_discovery_cb_t cb) { int err; BT_DBG(""); if (!valid_br_discov_param(param, cnt)) { return -EINVAL; } if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { return -EALREADY; } err = br_start_inquiry(param); if (err) { return err; } atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY); (void)memset(results, 0, sizeof(*results) * cnt); discovery_cb = cb; discovery_results = results; discovery_results_size = cnt; discovery_results_count = 0; return 0; } int bt_br_discovery_stop(void) { int err; int i; BT_DBG(""); if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { return -EALREADY; } err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL); if (err) { return err; } for (i = 0; i < discovery_results_count; i++) { struct discovery_priv *priv; struct bt_hci_cp_remote_name_cancel *cp; struct net_buf *buf; priv = (struct discovery_priv *)&discovery_results[i]._priv; if (!priv->resolving) { continue; } buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL, sizeof(*cp)); if (!buf) { continue; } cp = net_buf_add(buf, sizeof(*cp)); bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr); bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL); } atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); discovery_cb = NULL; discovery_results = NULL; discovery_results_size = 0; discovery_results_count = 0; return 0; } static int write_scan_enable(u8_t scan) { struct net_buf *buf; int err; BT_DBG("type %u", scan); buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1); if (!buf) { return -ENOBUFS; } net_buf_add_u8(buf, scan); err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL); if (err) { return err; } atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN, (scan & BT_BREDR_SCAN_INQUIRY)); atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN, (scan & BT_BREDR_SCAN_PAGE)); return 0; } int bt_br_set_connectable(bool enable) { if (enable) { if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { return -EALREADY; } else { return write_scan_enable(BT_BREDR_SCAN_PAGE); } } else { if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { return -EALREADY; } else { return write_scan_enable(BT_BREDR_SCAN_DISABLED); } } } int bt_br_set_discoverable(bool enable) { if (enable) { if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) { return -EALREADY; } if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { return -EPERM; } return write_scan_enable(BT_BREDR_SCAN_INQUIRY | BT_BREDR_SCAN_PAGE); } else { if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) { return -EALREADY; } return write_scan_enable(BT_BREDR_SCAN_PAGE); } } #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_ECC) int bt_pub_key_gen(struct bt_pub_key_cb *new_cb) { int err; /* * We check for both "LE Read Local P-256 Public Key" and * "LE Generate DH Key" support here since both commands are needed for * ECC support. If "LE Generate DH Key" is not supported then there * is no point in reading local public key. */ if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) || !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) { BT_WARN("ECC HCI commands not available"); return -ENOTSUP; } new_cb->_next = pub_key_cb; pub_key_cb = new_cb; if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { return 0; } atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); #if !defined(CONFIG_BT_USE_HCI_API) err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL); #else err = hci_api_le_gen_p256_pubkey(); #endif if (err) { BT_ERR("Sending LE P256 Public Key command failed"); atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); pub_key_cb = NULL; return err; } return 0; } const u8_t *bt_pub_key_get(void) { if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { return pub_key; } return NULL; } int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_cp_le_generate_dhkey *cp; struct net_buf *buf; int err; if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { return -EBUSY; } if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { return -EADDRNOTAVAIL; } dh_key_cb = cb; buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp)); if (!buf) { dh_key_cb = NULL; return -ENOBUFS; } cp = net_buf_add(buf, sizeof(*cp)); memcpy(cp->key, remote_pk, sizeof(cp->key)); err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL); if (err) { dh_key_cb = NULL; return err; } return 0; #else int err = 0; if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { return -EBUSY; } if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { return -EADDRNOTAVAIL; } dh_key_cb = cb; err = hci_api_le_gen_dhkey((uint8_t *)remote_pk); if (err) { dh_key_cb = NULL; } return err; #endif } #endif /* CONFIG_BT_ECC */ #if defined(CONFIG_BT_BREDR) int bt_br_oob_get_local(struct bt_br_oob *oob) { bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a); return 0; } #endif /* CONFIG_BT_BREDR */ int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob) { struct bt_le_ext_adv *adv; int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (id >= CONFIG_BT_ID_MAX) { return -EINVAL; } adv = bt_adv_lookup_legacy(); if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(adv && adv->id == id && atomic_test_bit(adv->flags, BT_ADV_ENABLED) && atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) && bt_dev.id_addr[id].type == BT_ADDR_LE_RANDOM)) { if (IS_ENABLED(CONFIG_BT_CENTRAL) && atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) { struct bt_conn *conn; conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_CONNECT_SCAN); if (conn) { /* Cannot set new RPA while creating * connections. */ bt_conn_unref(conn); return -EINVAL; } } if (adv && atomic_test_bit(adv->flags, BT_ADV_ENABLED) && atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) && (bt_dev.id_addr[id].type == BT_ADDR_LE_RANDOM)) { /* Cannot set a new RPA address while advertising with * random static identity address for a different * identity. */ return -EINVAL; } if (IS_ENABLED(CONFIG_BT_OBSERVER) && id != BT_ID_DEFAULT && (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) || atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING))) { /* Cannot switch identity of scanner or initiator */ return -EINVAL; } le_rpa_invalidate(); le_update_private_addr(); bt_addr_le_copy(&oob->addr, &bt_dev.random_addr); } else { bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]); } if (IS_ENABLED(CONFIG_BT_SMP)) { err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data); if (err) { return err; } } return 0; } #if defined(CONFIG_BT_EXT_ADV) int bt_le_ext_adv_oob_get_local(struct bt_le_ext_adv *adv, struct bt_le_oob *oob) { int err; if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } if (IS_ENABLED(CONFIG_BT_PRIVACY) && !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) { /* Don't refresh RPA addresses if the RPA is new. * This allows back to back calls to this function or * bt_le_oob_get_local to not invalidate the previously set * RPAs. */ if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED) && !rpa_is_new()) { if (IS_ENABLED(CONFIG_BT_CENTRAL) && atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) { struct bt_conn *conn; conn = bt_conn_lookup_state_le( BT_ID_DEFAULT, NULL, BT_CONN_CONNECT_SCAN); if (conn) { /* Cannot set new RPA while creating * connections. */ bt_conn_unref(conn); return -EINVAL; } } le_rpa_invalidate(); le_update_private_addr(); } bt_addr_le_copy(&oob->addr, &adv->random_addr); } else { bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[adv->id]); } if (IS_ENABLED(CONFIG_BT_SMP) && !IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) { err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data); if (err) { return err; } } return 0; } #endif /* defined(CONFIG_BT_EXT_ADV) */ #if defined(CONFIG_BT_SMP) #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) int bt_le_oob_set_legacy_tk(struct bt_conn *conn, const u8_t *tk) { return bt_smp_le_oob_set_tk(conn, tk); } #endif /* !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) */ #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) int bt_le_oob_set_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data *oobd_local, const struct bt_le_oob_sc_data *oobd_remote) { if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote); } int bt_le_oob_get_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data **oobd_local, const struct bt_le_oob_sc_data **oobd_remote) { if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { return -EAGAIN; } return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote); } #endif /* !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) */ #endif /* defined(CONFIG_BT_SMP) */ int bt_le_hci_version_get() { return bt_dev.hci_version; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_core.c
C
apache-2.0
241,782
/* hci_core.h - Bluetooth HCI core access */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __HCI_CORE_H #define __HCI_CORE_H /* LL connection parameters */ #define LE_CONN_LATENCY 0x0000 #define LE_CONN_TIMEOUT 0x002a #if defined(CONFIG_BT_BREDR) #define LMP_FEAT_PAGES_COUNT 3 #else #define LMP_FEAT_PAGES_COUNT 1 #endif /* SCO settings */ #define BT_VOICE_CVSD_16BIT 0x0060 /* k_poll event tags */ enum { BT_EVENT_CMD_TX, BT_EVENT_CONN_TX_QUEUE, }; /* bt_dev flags: the flags defined here represent BT controller state */ enum { BT_DEV_ENABLE, BT_DEV_READY, BT_DEV_PRESET_ID, BT_DEV_HAS_PUB_KEY, BT_DEV_PUB_KEY_BUSY, BT_DEV_SCANNING, BT_DEV_EXPLICIT_SCAN, BT_DEV_ACTIVE_SCAN, BT_DEV_SCAN_FILTER_DUP, BT_DEV_SCAN_WL, BT_DEV_SCAN_LIMITED, BT_DEV_INITIATING, BT_DEV_RPA_VALID, BT_DEV_RPA_TIMEOUT_SET, BT_DEV_ID_PENDING, BT_DEV_STORE_ID, #if defined(CONFIG_BT_BREDR) BT_DEV_ISCAN, BT_DEV_PSCAN, BT_DEV_INQUIRY, #endif /* CONFIG_BT_BREDR */ /* Total number of flags - must be at the end of the enum */ BT_DEV_NUM_FLAGS, }; /* Flags which should not be cleared upon HCI_Reset */ #define BT_DEV_PERSISTENT_FLAGS (BIT(BT_DEV_ENABLE) | \ BIT(BT_DEV_PRESET_ID)) enum { /* Advertising set has been created in the host. */ BT_ADV_CREATED, /* Advertising parameters has been set in the controller. * This implies that the advertising set has been created in the * controller. */ BT_ADV_PARAMS_SET, /* Advertising data has been set in the controller. */ BT_ADV_DATA_SET, /* Advertising random address pending to be set in the controller. */ BT_ADV_RANDOM_ADDR_PENDING, /* The private random address of the advertiser is valid for this cycle * of the RPA timeout. */ BT_ADV_RPA_VALID, /* The advertiser set is limited by a timeout, or number of advertising * events, or both. */ BT_ADV_LIMITED, /* Advertiser set is currently advertising in the controller. */ BT_ADV_ENABLED, /* Advertiser should include name in advertising data */ BT_ADV_INCLUDE_NAME, /* Advertiser set is connectable */ BT_ADV_CONNECTABLE, /* Advertiser set is scannable */ BT_ADV_SCANNABLE, /* Advertiser set has disabled the use of private addresses and is using * the identity address instead. */ BT_ADV_USE_IDENTITY, /* Advertiser has been configured to keep advertising after a connection * has been established as long as there are connections available. */ BT_ADV_PERSIST, /* Advertiser has been temporarily disabled. */ BT_ADV_PAUSED, BT_ADV_NUM_FLAGS, }; struct bt_le_ext_adv { /* ID Address used for advertising */ u8_t id; /* Advertising handle */ u16_t handle; /* Current local Random Address */ bt_addr_le_t random_addr; /* Current target address */ bt_addr_le_t target_addr; ATOMIC_DEFINE(flags, BT_ADV_NUM_FLAGS); #if defined(CONFIG_BT_EXT_ADV) const struct bt_le_ext_adv_cb *cb; /* TX Power in use by the controller */ s8_t tx_power; #endif /* defined(CONFIG_BT_EXT_ADV) */ }; struct bt_dev_le { /* LE features */ u8_t features[8]; /* LE states */ u64_t states; #if defined(CONFIG_BT_CONN) /* Controller buffer information */ u16_t mtu_init; u16_t mtu; struct k_sem pkts; #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) /* Size of the the controller resolving list */ u8_t rl_size; /* Number of entries in the resolving list. rl_entries > rl_size * means that host-side resolving is used. */ u8_t rl_entries; #endif /* CONFIG_BT_SMP */ }; #if defined(CONFIG_BT_BREDR) struct bt_dev_br { /* Max controller's acceptable ACL packet length */ u16_t mtu; struct k_sem pkts; u16_t esco_pkt_type; }; #endif /* The theoretical max for these is 8 and 64, but there's no point * in allocating the full memory if we only support a small subset. * These values must be updated whenever the host implementation is * extended beyond the current values. */ #define BT_DEV_VS_FEAT_MAX 1 #define BT_DEV_VS_CMDS_MAX 2 /* State tracking for the local Bluetooth controller */ struct bt_dev { /* Local Identity Address(es) */ bt_addr_le_t id_addr[CONFIG_BT_ID_MAX]; u8_t id_count; struct bt_conn_le_create_param create_param; #if !defined(CONFIG_BT_EXT_ADV) /* Legacy advertiser */ struct bt_le_ext_adv adv; #else /* Pointer to reserved advertising set */ struct bt_le_ext_adv *adv; #endif /* Current local Random Address */ bt_addr_le_t random_addr; u8_t adv_conn_id; /* Controller version & manufacturer information */ u8_t hci_version; u8_t lmp_version; u16_t hci_revision; u16_t lmp_subversion; u16_t manufacturer; /* LMP features (pages 0, 1, 2) */ u8_t features[LMP_FEAT_PAGES_COUNT][8]; /* Supported commands */ u8_t supported_commands[64]; #if defined(CONFIG_BT_HCI_VS_EXT) /* Vendor HCI support */ u8_t vs_features[BT_DEV_VS_FEAT_MAX]; u8_t vs_commands[BT_DEV_VS_CMDS_MAX]; #endif struct k_work init; ATOMIC_DEFINE(flags, BT_DEV_NUM_FLAGS); /* LE controller specific features */ struct bt_dev_le le; #if defined(CONFIG_BT_BREDR) /* BR/EDR controller specific features */ struct bt_dev_br br; #endif /* Number of commands controller can accept */ struct k_sem ncmd_sem; /* Last sent HCI command */ struct net_buf *sent_cmd; #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) /* Queue for incoming HCI events & ACL data */ struct kfifo rx_queue; #endif /* Queue for outgoing HCI commands */ struct kfifo cmd_tx_queue; /* Registered HCI driver */ const struct bt_hci_driver *drv; #if defined(CONFIG_BT_PRIVACY) /* Local Identity Resolving Key */ u8_t irk[CONFIG_BT_ID_MAX][16]; /* Work used for RPA rotation */ struct k_delayed_work rpa_update; #endif /* Local Name */ #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) char name[CONFIG_BT_DEVICE_NAME_MAX + 1]; #endif }; extern struct bt_dev bt_dev; #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) extern const struct bt_conn_auth_cb *bt_auth; #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ int bt_hci_disconnect(u16_t handle, u8_t reason); bool bt_le_conn_params_valid(const struct bt_le_conn_param *param); int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time); int bt_le_set_phy(struct bt_conn *conn, u8_t tx_phy, u8_t rx_phy); int bt_le_scan_update(bool fast_scan); int bt_le_create_conn(const struct bt_conn *conn); int bt_le_create_conn_cancel(void); bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr); const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr); int bt_send(struct net_buf *buf); /* Don't require everyone to include keys.h */ struct bt_keys; void bt_id_add(struct bt_keys *keys); void bt_id_del(struct bt_keys *keys); int bt_setup_random_id_addr(void); void bt_setup_public_id_addr(void); void bt_finalize_init(void); int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, const bt_addr_le_t *peer); void bt_le_adv_resume(void); bool bt_le_scan_random_addr_check(void); int hci_driver_init(); int hci_h5_driver_init(); #if defined(CONFIG_BT_USE_HCI_API) struct event_handler { u8_t event; u8_t min_len; void (*handler)(struct net_buf *buf); }; #define EVENT_HANDLER(_evt, _handler, _min_len) \ { \ .event = _evt, \ .handler = _handler, \ .min_len = _min_len, \ } #endif #endif // __HCI_CORE_H
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_core.h
C
apache-2.0
7,631
/** * @file hci_ecc.c * HCI ECC emulation */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <atomic.h> #include <misc/stack.h> #include <misc/byteorder.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> #include <tinycrypt/ecc.h> #include <tinycrypt/ecc_dh.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE) #define LOG_MODULE_NAME bt_hci_ecc #include "common/log.h" #include "hci_ecc.h" #ifdef CONFIG_BT_HCI_RAW #include <bluetooth/hci_raw.h> #include "hci_raw_internal.h" #else #include "hci_core.h" #endif /* NOTE: This is an advanced setting and should not be changed unless absolutely necessary */ #ifndef CONFIG_BT_HCI_ECC_STACK_SIZE #define CONFIG_BT_HCI_ECC_STACK_SIZE 1100 #endif static struct k_thread ecc_thread_data; static BT_STACK_NOINIT(ecc_thread_stack, 1100); /* based on Core Specification 4.2 Vol 3. Part H 2.3.5.6.1 */ static const bt_u32_t debug_private_key[8] = { 0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3, 0xa3c55f38, 0x3f49f6d4 }; #if defined(CONFIG_BT_USE_DEBUG_KEYS) static const u8_t debug_public_key[64] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc }; #endif enum { PENDING_PUB_KEY, PENDING_DHKEY, /* Total number of flags - must be at the end of the enum */ NUM_FLAGS, }; static ATOMIC_DEFINE(flags, NUM_FLAGS); //static K_SEM_DEFINE(cmd_sem, 0, 1); static struct k_sem cmd_sem; static struct { u8_t private_key[32]; union { u8_t pk[64]; u8_t dhkey[32]; }; } ecc; static void send_cmd_status(u16_t opcode, u8_t status) { struct bt_hci_evt_cmd_status *evt; struct bt_hci_evt_hdr *hdr; struct net_buf *buf; BT_DBG("opcode %x status %x", opcode, status); buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER); bt_buf_set_type(buf, BT_BUF_EVT); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->evt = BT_HCI_EVT_CMD_STATUS; hdr->len = sizeof(*evt); evt = net_buf_add(buf, sizeof(*evt)); evt->ncmd = 1U; evt->opcode = sys_cpu_to_le16(opcode); evt->status = status; bt_recv_prio(buf); } static u8_t generate_keys(void) { #if !defined(CONFIG_BT_USE_DEBUG_KEYS) do { int rc; rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1); if (rc == TC_CRYPTO_FAIL) { BT_ERR("Failed to create ECC public/private pair"); return BT_HCI_ERR_UNSPECIFIED; } /* make sure generated key isn't debug key */ } while (memcmp(ecc.private_key, debug_private_key, 32) == 0); #else sys_memcpy_swap(&ecc.pk, debug_public_key, 32); sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32); sys_memcpy_swap(ecc.private_key, debug_private_key, 32); #endif return 0; } static void emulate_le_p256_public_key_cmd(void) { struct bt_hci_evt_le_p256_public_key_complete *evt; struct bt_hci_evt_le_meta_event *meta; struct bt_hci_evt_hdr *hdr; struct net_buf *buf; u8_t status; BT_DBG(""); status = generate_keys(); buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->evt = BT_HCI_EVT_LE_META_EVENT; hdr->len = sizeof(*meta) + sizeof(*evt); meta = net_buf_add(buf, sizeof(*meta)); meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE; evt = net_buf_add(buf, sizeof(*evt)); evt->status = status; if (status) { (void)memset(evt->key, 0, sizeof(evt->key)); } else { /* Convert X and Y coordinates from big-endian (provided * by crypto API) to little endian HCI. */ sys_memcpy_swap(evt->key, ecc.pk, 32); sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32); } atomic_clear_bit(flags, PENDING_PUB_KEY); bt_recv(buf); } static void emulate_le_generate_dhkey(void) { struct bt_hci_evt_le_generate_dhkey_complete *evt; struct bt_hci_evt_le_meta_event *meta; struct bt_hci_evt_hdr *hdr; struct net_buf *buf; int ret; ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1); if (ret < 0) { BT_ERR("public key is not valid (ret %d)", ret); ret = TC_CRYPTO_FAIL; } else { ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey, &curve_secp256r1); } if (ret == TC_CRYPTO_SUCCESS) { ret = 0; } else { ret = -1; } buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->evt = BT_HCI_EVT_LE_META_EVENT; hdr->len = sizeof(*meta) + sizeof(*evt); meta = net_buf_add(buf, sizeof(*meta)); meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE; evt = net_buf_add(buf, sizeof(*evt)); if (ret) { evt->status = BT_HCI_ERR_UNSPECIFIED; (void)memset(evt->dhkey, 0, sizeof(evt->dhkey)); } else { evt->status = 0U; /* Convert from big-endian (provided by crypto API) to * little-endian HCI. */ sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey)); } atomic_clear_bit(flags, PENDING_DHKEY); bt_recv(buf); } static void ecc_thread(void *arg) { while (true) { k_sem_take(&cmd_sem, K_FOREVER); if (atomic_test_bit(flags, PENDING_PUB_KEY)) { emulate_le_p256_public_key_cmd(); } else if (atomic_test_bit(flags, PENDING_DHKEY)) { emulate_le_generate_dhkey(); } else { __ASSERT(0, "Unhandled ECC command"); } } } static void clear_ecc_events(struct net_buf *buf) { struct bt_hci_cp_le_set_event_mask *cmd; cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr)); /* * don't enable controller ECC events as those will be generated from * emulation code */ cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */ cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */ } static void le_gen_dhkey(struct net_buf *buf) { struct bt_hci_cp_le_generate_dhkey *cmd; u8_t status; if (atomic_test_bit(flags, PENDING_PUB_KEY)) { status = BT_HCI_ERR_CMD_DISALLOWED; goto send_status; } if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) { status = BT_HCI_ERR_INVALID_PARAM; goto send_status; } if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) { status = BT_HCI_ERR_CMD_DISALLOWED; goto send_status; } cmd = (void *)buf->data; /* Convert X and Y coordinates from little-endian HCI to * big-endian (expected by the crypto API). */ sys_memcpy_swap(ecc.pk, cmd->key, 32); sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32); k_sem_give(&cmd_sem); status = BT_HCI_ERR_SUCCESS; send_status: net_buf_unref(buf); send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status); } static void le_p256_pub_key(struct net_buf *buf) { u8_t status; net_buf_unref(buf); if (atomic_test_bit(flags, PENDING_DHKEY)) { status = BT_HCI_ERR_CMD_DISALLOWED; } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) { status = BT_HCI_ERR_CMD_DISALLOWED; } else { k_sem_give(&cmd_sem); status = BT_HCI_ERR_SUCCESS; } send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status); } int bt_hci_ecc_send(struct net_buf *buf) { if (bt_buf_get_type(buf) == BT_BUF_CMD) { struct bt_hci_cmd_hdr *chdr = (void *)buf->data; switch (sys_le16_to_cpu(chdr->opcode)) { case BT_HCI_OP_LE_P256_PUBLIC_KEY: net_buf_pull(buf, sizeof(*chdr)); le_p256_pub_key(buf); return 0; case BT_HCI_OP_LE_GENERATE_DHKEY: net_buf_pull(buf, sizeof(*chdr)); le_gen_dhkey(buf); return 0; case BT_HCI_OP_LE_SET_EVENT_MASK: clear_ecc_events(buf); break; default: break; } } return bt_dev.drv->send(buf); } int default_CSPRNG(u8_t *dst, unsigned int len) { return !bt_rand(dst, len); } void bt_hci_ecc_init(void) { k_sem_init(&cmd_sem, 0, 1); k_thread_spawn(&ecc_thread_data, "ecc task", ecc_thread_stack, K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread, NULL, 30); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_ecc.c
C
apache-2.0
8,014
/* hci_ecc.h - HCI ECC emulation */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ void bt_hci_ecc_init(void); int bt_hci_ecc_send(struct net_buf *buf);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_ecc.h
C
apache-2.0
197
/* hci_userchan.c - HCI user channel Bluetooth handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <atomic.h> #ifdef CONFIG_BT_HCI_RAW #include <bluetooth/hci_driver.h> #include <bluetooth/hci_raw.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE) #define LOG_MODULE_NAME bt_hci_raw #include "common/log.h" #include "hci_ecc.h" #include "monitor.h" #include "hci_raw_internal.h" #define H4_CMD 0x01 #define H4_ACL 0x02 #define H4_SCO 0x03 #define H4_EVT 0x04 static struct k_fifo *raw_rx; #if defined(CONFIG_BT_HCI_RAW_H4_ENABLE) static u8_t raw_mode = BT_HCI_RAW_MODE_H4; #else static u8_t raw_mode; #endif NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL); NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, BT_BUF_RX_SIZE, NULL); NET_BUF_POOL_FIXED_DEFINE(hci_acl_pool, BT_HCI_ACL_COUNT, BT_BUF_ACL_SIZE, NULL); struct bt_dev_raw bt_dev; struct bt_hci_raw_cmd_ext *cmd_ext; static size_t cmd_ext_size; int bt_hci_driver_register(const struct bt_hci_driver *drv) { if (bt_dev.drv) { return -EALREADY; } if (!drv->open || !drv->send) { return -EINVAL; } bt_dev.drv = drv; BT_DBG("Registered %s", drv->name ? drv->name : ""); NET_BUF_POOL_INIT(hci_rx_pool); NET_BUF_POOL_INIT(hci_cmd_pool); NET_BUF_POOL_INIT(hci_acl_pool); bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus, BT_ADDR_ANY, drv->name ? drv->name : "bt0"); return 0; } struct net_buf *bt_buf_get_rx(enum bt_buf_type type, k_timeout_t timeout) { struct net_buf *buf; switch (type) { case BT_BUF_EVT: case BT_BUF_ACL_IN: break; default: BT_ERR("Invalid type: %u", type); return NULL; } buf = net_buf_alloc(&hci_rx_pool, timeout); if (!buf) { return buf; } net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, type); return buf; } struct net_buf *bt_buf_get_tx(enum bt_buf_type type, k_timeout_t timeout, const void *data, size_t size) { struct net_buf_pool *pool; struct net_buf *buf; switch (type) { case BT_BUF_CMD: pool = &hci_cmd_pool; break; case BT_BUF_ACL_OUT: pool = &hci_acl_pool; break; case BT_BUF_H4: if (IS_ENABLED(CONFIG_BT_HCI_RAW_H4) && raw_mode == BT_HCI_RAW_MODE_H4) { switch (((u8_t *)data)[0]) { case H4_CMD: type = BT_BUF_CMD; pool = &hci_cmd_pool; break; case H4_ACL: type = BT_BUF_ACL_OUT; pool = &hci_acl_pool; break; default: LOG_ERR("Unknown H4 type %u", type); return NULL; } /* Adjust data pointer to discard the header */ data = (u8_t *)data + 1; size--; break; } /* Fallthrough */ default: BT_ERR("Invalid type: %u", type); return NULL; } buf = net_buf_alloc(pool, timeout); if (!buf) { return buf; } net_buf_reserve(buf, BT_BUF_RESERVE); bt_buf_set_type(buf, type); if (data && size) { net_buf_add_mem(buf, data, size); } return buf; } struct net_buf *bt_buf_get_cmd_complete(k_timeout_t timeout) { return bt_buf_get_rx(BT_BUF_EVT, timeout); } struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, k_timeout_t timeout) { return bt_buf_get_rx(BT_BUF_EVT, timeout); } int bt_recv(struct net_buf *buf) { BT_DBG("buf %p len %u", buf, buf->len); bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); if (IS_ENABLED(CONFIG_BT_HCI_RAW_H4) && raw_mode == BT_HCI_RAW_MODE_H4) { switch (bt_buf_get_type(buf)) { case BT_BUF_EVT: net_buf_push_u8(buf, H4_EVT); break; case BT_BUF_ACL_IN: net_buf_push_u8(buf, H4_ACL); break; default: BT_ERR("Unknown type %u", bt_buf_get_type(buf)); return -EINVAL; } } /* Queue to RAW rx queue */ net_buf_put(raw_rx, buf); return 0; } int bt_recv_prio(struct net_buf *buf) { return bt_recv(buf); } static void bt_cmd_complete_ext(u16_t op, u8_t status) { struct net_buf *buf; struct bt_hci_evt_cc_status *cc; if (status == BT_HCI_ERR_EXT_HANDLED) { return; } buf = bt_hci_cmd_complete_create(op, sizeof(*cc)); cc = net_buf_add(buf, sizeof(*cc)); cc->status = status; bt_recv(buf); } static u8_t bt_send_ext(struct net_buf *buf) { struct bt_hci_cmd_hdr *hdr; struct net_buf_simple_state state; int i; u16_t op; u8_t status; status = BT_HCI_ERR_SUCCESS; if (!cmd_ext) { return status; } net_buf_simple_save(&buf->b, &state); if (buf->len < sizeof(*hdr)) { BT_ERR("No HCI Command header"); return BT_HCI_ERR_INVALID_PARAM; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); if (buf->len < hdr->param_len) { BT_ERR("Invalid HCI CMD packet length"); return BT_HCI_ERR_INVALID_PARAM; } op = sys_le16_to_cpu(hdr->opcode); for (i = 0; i < cmd_ext_size; i++) { struct bt_hci_raw_cmd_ext *cmd = &cmd_ext[i]; if (cmd->op == op) { if (buf->len < cmd->min_len) { status = BT_HCI_ERR_INVALID_PARAM; } else { status = cmd->func(buf); } break; } } if (status) { bt_cmd_complete_ext(op, status); return status; } net_buf_simple_restore(&buf->b, &state); return status; } int bt_send(struct net_buf *buf) { BT_DBG("buf %p len %u", buf, buf->len); bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); if (IS_ENABLED(CONFIG_BT_HCI_RAW_CMD_EXT) && bt_buf_get_type(buf) == BT_BUF_CMD) { u8_t status; status = bt_send_ext(buf); if (status) { return status; } } if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { return bt_hci_ecc_send(buf); } return bt_dev.drv->send(buf); } int bt_hci_raw_set_mode(u8_t mode) { BT_DBG("mode %u", mode); if (IS_ENABLED(CONFIG_BT_HCI_RAW_H4)) { switch (mode) { case BT_HCI_RAW_MODE_PASSTHROUGH: case BT_HCI_RAW_MODE_H4: raw_mode = mode; return 0; } } return -EINVAL; } u8_t bt_hci_raw_get_mode(void) { if (IS_ENABLED(CONFIG_BT_HCI_RAW_H4)) { return raw_mode; } return BT_HCI_RAW_MODE_PASSTHROUGH; } void bt_hci_raw_cmd_ext_register(struct bt_hci_raw_cmd_ext *cmds, size_t size) { if (IS_ENABLED(CONFIG_BT_HCI_RAW_CMD_EXT)) { cmd_ext = cmds; cmd_ext_size = size; } } int bt_enable_raw(struct k_fifo *rx_queue) { const struct bt_hci_driver *drv = bt_dev.drv; int err; BT_DBG(""); raw_rx = rx_queue; if (!bt_dev.drv) { BT_ERR("No HCI driver registered"); return -ENODEV; } if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { bt_hci_ecc_init(); } err = drv->open(); if (err) { BT_ERR("HCI driver open failed (%d)", err); return err; } BT_INFO("Bluetooth enabled in RAW mode"); return 0; } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_raw.c
C
apache-2.0
6,513
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __BT_HCI_RAW_INTERNAL_H #define __BT_HCI_RAW_INTERNAL_H #ifdef __cplusplus extern "C" { #endif struct bt_dev_raw { /* Registered HCI driver */ const struct bt_hci_driver *drv; }; extern struct bt_dev_raw bt_dev; #ifdef __cplusplus } #endif #endif /* __BT_HCI_RAW_INTERNAL_H */
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hci_raw_internal.h
C
apache-2.0
381
/* hfp_hf.c - Hands free Profile - Handsfree side handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <bt_errno.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <misc/printk.h> #ifdef CONFIG_BT_HFP_HF #include <bluetooth/conn.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HFP_HF) #define LOG_MODULE_NAME bt_hfp_hf /* FIXME: #include "common/log.h" */ #include <bluetooth/rfcomm.h> #include <bluetooth/hfp_hf.h> #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "rfcomm_internal.h" #include "at.h" #include "hfp_internal.h" #define MAX_IND_STR_LEN 17 struct bt_hfp_hf_cb *bt_hf; NET_BUF_POOL_FIXED_DEFINE(hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL); static struct bt_hfp_hf bt_hfp_hf_pool[CONFIG_BT_MAX_CONN]; /* The order should follow the enum hfp_hf_ag_indicators */ static const struct { char *name; bt_u32_t min; bt_u32_t max; } ag_ind[] = { {"service", 0, 1}, /* HF_SERVICE_IND */ {"call", 0, 1}, /* HF_CALL_IND */ {"callsetup", 0, 3}, /* HF_CALL_SETUP_IND */ {"callheld", 0, 2}, /* HF_CALL_HELD_IND */ {"signal", 0, 5}, /* HF_SINGNAL_IND */ {"roam", 0, 1}, /* HF_ROAM_IND */ {"battchg", 0, 5} /* HF_BATTERY_IND */ }; void hf_slc_error(struct at_client *hf_at) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); int err; BT_ERR("SLC error: disconnecting"); err = bt_rfcomm_dlc_disconnect(&hf->rfcomm_dlc); if (err) { BT_ERR("Rfcomm: Unable to disconnect :%d", -err); } } int hfp_hf_send_cmd(struct bt_hfp_hf *hf, at_resp_cb_t resp, at_finish_cb_t finish, const char *format, ...) { struct net_buf *buf; va_list vargs; int ret; /* register the callbacks */ at_register(&hf->at, resp, finish); buf = bt_rfcomm_create_pdu(&hf_pool); if (!buf) { BT_ERR("No Buffers!"); return -ENOMEM; } va_start(vargs, format); ret = vsnprintk(buf->data, (net_buf_tailroom(buf) - 1), format, vargs); if (ret < 0) { BT_ERR("Unable to format variable arguments"); return ret; } va_end(vargs); net_buf_add(buf, ret); net_buf_add_u8(buf, '\r'); ret = bt_rfcomm_dlc_send(&hf->rfcomm_dlc, buf); if (ret < 0) { BT_ERR("Rfcomm send error :(%d)", ret); return ret; } return 0; } int brsf_handle(struct at_client *hf_at) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); bt_u32_t val; int ret; ret = at_get_number(hf_at, &val); if (ret < 0) { BT_ERR("Error getting value"); return ret; } hf->ag_features = val; return 0; } int brsf_resp(struct at_client *hf_at, struct net_buf *buf) { int err; BT_DBG(""); err = at_parse_cmd_input(hf_at, buf, "BRSF", brsf_handle, AT_CMD_TYPE_NORMAL); if (err < 0) { /* Returning negative value is avoided before SLC connection * established. */ BT_ERR("Error parsing CMD input"); hf_slc_error(hf_at); } return 0; } static void cind_handle_values(struct at_client *hf_at, bt_u32_t index, char *name, bt_u32_t min, bt_u32_t max) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); int i; BT_DBG("index: %u, name: %s, min: %u, max:%u", index, name, min, max); for (i = 0; i < ARRAY_SIZE(ag_ind); i++) { if (strcmp(name, ag_ind[i].name) != 0) { continue; } if (min != ag_ind[i].min || max != ag_ind[i].max) { BT_ERR("%s indicator min/max value not matching", name); } hf->ind_table[index] = i; break; } } int cind_handle(struct at_client *hf_at) { bt_u32_t index = 0U; /* Parsing Example: CIND: ("call",(0,1)) etc.. */ while (at_has_next_list(hf_at)) { char name[MAX_IND_STR_LEN]; bt_u32_t min, max; if (at_open_list(hf_at) < 0) { BT_ERR("Could not get open list"); goto error; } if (at_list_get_string(hf_at, name, sizeof(name)) < 0) { BT_ERR("Could not get string"); goto error; } if (at_open_list(hf_at) < 0) { BT_ERR("Could not get open list"); goto error; } if (at_list_get_range(hf_at, &min, &max) < 0) { BT_ERR("Could not get range"); goto error; } if (at_close_list(hf_at) < 0) { BT_ERR("Could not get close list"); goto error; } if (at_close_list(hf_at) < 0) { BT_ERR("Could not get close list"); goto error; } cind_handle_values(hf_at, index, name, min, max); index++; } return 0; error: BT_ERR("Error on CIND response"); hf_slc_error(hf_at); return -EINVAL; } int cind_resp(struct at_client *hf_at, struct net_buf *buf) { int err; err = at_parse_cmd_input(hf_at, buf, "CIND", cind_handle, AT_CMD_TYPE_NORMAL); if (err < 0) { BT_ERR("Error parsing CMD input"); hf_slc_error(hf_at); } return 0; } void ag_indicator_handle_values(struct at_client *hf_at, bt_u32_t index, bt_u32_t value) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn; BT_DBG("Index :%u, Value :%u", index, value); if (index >= ARRAY_SIZE(ag_ind)) { BT_ERR("Max only %lu indicators are supported", ARRAY_SIZE(ag_ind)); return; } if (value > ag_ind[hf->ind_table[index]].max || value < ag_ind[hf->ind_table[index]].min) { BT_ERR("Indicators out of range - value: %u", value); return; } switch (hf->ind_table[index]) { case HF_SERVICE_IND: if (bt_hf->service) { bt_hf->service(conn, value); } break; case HF_CALL_IND: if (bt_hf->call) { bt_hf->call(conn, value); } break; case HF_CALL_SETUP_IND: if (bt_hf->call_setup) { bt_hf->call_setup(conn, value); } break; case HF_CALL_HELD_IND: if (bt_hf->call_held) { bt_hf->call_held(conn, value); } break; case HF_SINGNAL_IND: if (bt_hf->signal) { bt_hf->signal(conn, value); } break; case HF_ROAM_IND: if (bt_hf->roam) { bt_hf->roam(conn, value); } break; case HF_BATTERY_IND: if (bt_hf->battery) { bt_hf->battery(conn, value); } break; default: BT_ERR("Unknown AG indicator"); break; } } int cind_status_handle(struct at_client *hf_at) { bt_u32_t index = 0U; while (at_has_next_list(hf_at)) { bt_u32_t value; int ret; ret = at_get_number(hf_at, &value); if (ret < 0) { BT_ERR("could not get the value"); return ret; } ag_indicator_handle_values(hf_at, index, value); index++; } return 0; } int cind_status_resp(struct at_client *hf_at, struct net_buf *buf) { int err; err = at_parse_cmd_input(hf_at, buf, "CIND", cind_status_handle, AT_CMD_TYPE_NORMAL); if (err < 0) { BT_ERR("Error parsing CMD input"); hf_slc_error(hf_at); } return 0; } int ciev_handle(struct at_client *hf_at) { bt_u32_t index, value; int ret; ret = at_get_number(hf_at, &index); if (ret < 0) { BT_ERR("could not get the Index"); return ret; } /* The first element of the list shall have 1 */ if (!index) { BT_ERR("Invalid index value '0'"); return 0; } ret = at_get_number(hf_at, &value); if (ret < 0) { BT_ERR("could not get the value"); return ret; } ag_indicator_handle_values(hf_at, (index - 1), value); return 0; } int ring_handle(struct at_client *hf_at) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn; if (bt_hf->ring_indication) { bt_hf->ring_indication(conn); } return 0; } static const struct unsolicited { const char *cmd; enum at_cmd_type type; int (*func)(struct at_client *hf_at); } handlers[] = { { "CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle }, { "RING", AT_CMD_TYPE_OTHER, ring_handle } }; static const struct unsolicited *hfp_hf_unsol_lookup(struct at_client *hf_at) { int i; for (i = 0; i < ARRAY_SIZE(handlers); i++) { if (!strncmp(hf_at->buf, handlers[i].cmd, strlen(handlers[i].cmd))) { return &handlers[i]; } } return NULL; } int unsolicited_cb(struct at_client *hf_at, struct net_buf *buf) { const struct unsolicited *handler; handler = hfp_hf_unsol_lookup(hf_at); if (!handler) { BT_ERR("Unhandled unsolicited response"); return -ENOMSG; } if (!at_parse_cmd_input(hf_at, buf, handler->cmd, handler->func, handler->type)) { return 0; } return -ENOMSG; } int cmd_complete(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn; struct bt_hfp_hf_cmd_complete cmd = { 0 }; BT_DBG(""); switch (result) { case AT_RESULT_OK: cmd.type = HFP_HF_CMD_OK; break; case AT_RESULT_ERROR: cmd.type = HFP_HF_CMD_ERROR; break; case AT_RESULT_CME_ERROR: cmd.type = HFP_HF_CMD_CME_ERROR; cmd.cme = cme_err; break; default: BT_ERR("Unknown error code"); cmd.type = HFP_HF_CMD_UNKNOWN_ERROR; break; } if (bt_hf->cmd_complete_cb) { bt_hf->cmd_complete_cb(conn, &cmd); } return 0; } int cmee_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) { if (result != AT_RESULT_OK) { BT_ERR("SLC Connection ERROR in response"); return -EINVAL; } return 0; } static void slc_completed(struct at_client *hf_at) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn; if (bt_hf->connected) { bt_hf->connected(conn); } if (hfp_hf_send_cmd(hf, NULL, cmee_finish, "AT+CMEE=1") < 0) { BT_ERR("Error Sending AT+CMEE"); } } int cmer_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) { if (result != AT_RESULT_OK) { BT_ERR("SLC Connection ERROR in response"); hf_slc_error(hf_at); return -EINVAL; } slc_completed(hf_at); return 0; } int cind_status_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); int err; if (result != AT_RESULT_OK) { BT_ERR("SLC Connection ERROR in response"); hf_slc_error(hf_at); return -EINVAL; } at_register_unsolicited(hf_at, unsolicited_cb); err = hfp_hf_send_cmd(hf, NULL, cmer_finish, "AT+CMER=3,0,0,1"); if (err < 0) { hf_slc_error(hf_at); return err; } return 0; } int cind_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); int err; if (result != AT_RESULT_OK) { BT_ERR("SLC Connection ERROR in response"); hf_slc_error(hf_at); return -EINVAL; } err = hfp_hf_send_cmd(hf, cind_status_resp, cind_status_finish, "AT+CIND?"); if (err < 0) { hf_slc_error(hf_at); return err; } return 0; } int brsf_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) { struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at); int err; if (result != AT_RESULT_OK) { BT_ERR("SLC Connection ERROR in response"); hf_slc_error(hf_at); return -EINVAL; } err = hfp_hf_send_cmd(hf, cind_resp, cind_finish, "AT+CIND=?"); if (err < 0) { hf_slc_error(hf_at); return err; } return 0; } int hf_slc_establish(struct bt_hfp_hf *hf) { int err; BT_DBG(""); err = hfp_hf_send_cmd(hf, brsf_resp, brsf_finish, "AT+BRSF=%u", hf->hf_features); if (err < 0) { hf_slc_error(&hf->at); return err; } return 0; } static struct bt_hfp_hf *bt_hfp_hf_lookup_bt_conn(struct bt_conn *conn) { int i; for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) { struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i]; if (hf->rfcomm_dlc.session->br_chan.chan.conn == conn) { return hf; } } return NULL; } int bt_hfp_hf_send_cmd(struct bt_conn *conn, enum bt_hfp_hf_at_cmd cmd) { struct bt_hfp_hf *hf; int err; BT_DBG(""); if (!conn) { BT_ERR("Invalid connection"); return -ENOTCONN; } hf = bt_hfp_hf_lookup_bt_conn(conn); if (!hf) { BT_ERR("No HF connection found"); return -ENOTCONN; } switch (cmd) { case BT_HFP_HF_ATA: err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "ATA"); if (err < 0) { BT_ERR("Failed ATA"); return err; } break; case BT_HFP_HF_AT_CHUP: err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "AT+CHUP"); if (err < 0) { BT_ERR("Failed AT+CHUP"); return err; } break; default: BT_ERR("Invalid AT Command"); return -EINVAL; } return 0; } static void hfp_hf_connected(struct bt_rfcomm_dlc *dlc) { struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc); BT_DBG("hf connected"); BT_ASSERT(hf); hf_slc_establish(hf); } static void hfp_hf_disconnected(struct bt_rfcomm_dlc *dlc) { struct bt_conn *conn = dlc->session->br_chan.chan.conn; BT_DBG("hf disconnected!"); if (bt_hf->disconnected) { bt_hf->disconnected(conn); } } static void hfp_hf_recv(struct bt_rfcomm_dlc *dlc, struct net_buf *buf) { struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc); if (at_parse_input(&hf->at, buf) < 0) { BT_ERR("Parsing failed"); } } static int bt_hfp_hf_accept(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc) { int i; static struct bt_rfcomm_dlc_ops ops = { .connected = hfp_hf_connected, .disconnected = hfp_hf_disconnected, .recv = hfp_hf_recv, }; BT_DBG("conn %p", conn); for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) { struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i]; int j; if (hf->rfcomm_dlc.session) { continue; } hf->at.buf = hf->hf_buffer; hf->at.buf_max_len = HF_MAX_BUF_LEN; hf->rfcomm_dlc.ops = &ops; hf->rfcomm_dlc.mtu = BT_HFP_MAX_MTU; *dlc = &hf->rfcomm_dlc; /* Set the supported features*/ hf->hf_features = BT_HFP_HF_SUPPORTED_FEATURES; for (j = 0; j < HF_MAX_AG_INDICATORS; j++) { hf->ind_table[j] = -1; } return 0; } BT_ERR("Unable to establish HF connection (%p)", conn); return -ENOMEM; } static void hfp_hf_init(void) { static struct bt_rfcomm_server chan = { .channel = BT_RFCOMM_CHAN_HFP_HF, .accept = bt_hfp_hf_accept, }; NET_BUF_POOL_INIT(hf_pool); bt_rfcomm_server_register(&chan); } int bt_hfp_hf_register(struct bt_hfp_hf_cb *cb) { if (!cb) { return -EINVAL; } if (bt_hf) { return -EALREADY; } bt_hf = cb; hfp_hf_init(); return 0; } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hfp_hf.c
C
apache-2.0
14,139
/** @file * @brief Internal APIs for Bluetooth Handsfree profile handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #define BT_HFP_MAX_MTU 140 #define BT_HF_CLIENT_MAX_PDU BT_HFP_MAX_MTU /* HFP AG Features */ #define BT_HFP_AG_FEATURE_3WAY_CALL 0x00000001 /* Three-way calling */ #define BT_HFP_AG_FEATURE_ECNR 0x00000002 /* EC and/or NR function */ #define BT_HFP_AG_FEATURE_VOICE_RECG 0x00000004 /* Voice recognition */ #define BT_HFP_AG_INBAND_RING_TONE 0x00000008 /* In-band ring capability */ #define BT_HFP_AG_VOICE_TAG 0x00000010 /* Attach no. to voice tag */ #define BT_HFP_AG_FEATURE_REJECT_CALL 0x00000020 /* Ability to reject call */ #define BT_HFP_AG_FEATURE_ECS 0x00000040 /* Enhanced call status */ #define BT_HFP_AG_FEATURE_ECC 0x00000080 /* Enhanced call control */ #define BT_HFP_AG_FEATURE_EXT_ERR 0x00000100 /* Extented error codes */ #define BT_HFP_AG_FEATURE_CODEC_NEG 0x00000200 /* Codec negotiation */ #define BT_HFP_AG_FEATURE_HF_IND 0x00000400 /* HF Indicators */ #define BT_HFP_AG_FEARTURE_ESCO_S4 0x00000800 /* eSCO S4 Settings */ /* HFP HF Features */ #define BT_HFP_HF_FEATURE_ECNR 0x00000001 /* EC and/or NR */ #define BT_HFP_HF_FEATURE_3WAY_CALL 0x00000002 /* Three-way calling */ #define BT_HFP_HF_FEATURE_CLI 0x00000004 /* CLI presentation */ #define BT_HFP_HF_FEATURE_VOICE_RECG 0x00000008 /* Voice recognition */ #define BT_HFP_HF_FEATURE_VOLUME 0x00000010 /* Remote volume control */ #define BT_HFP_HF_FEATURE_ECS 0x00000020 /* Enhanced call status */ #define BT_HFP_HF_FEATURE_ECC 0x00000040 /* Enhanced call control */ #define BT_HFP_HF_FEATURE_CODEC_NEG 0x00000080 /* CODEC Negotiation */ #define BT_HFP_HF_FEATURE_HF_IND 0x00000100 /* HF Indicators */ #define BT_HFP_HF_FEATURE_ESCO_S4 0x00000200 /* eSCO S4 Settings */ /* HFP HF Supported features */ #define BT_HFP_HF_SUPPORTED_FEATURES (BT_HFP_HF_FEATURE_CLI | \ BT_HFP_HF_FEATURE_VOLUME) #define HF_MAX_BUF_LEN BT_HF_CLIENT_MAX_PDU #define HF_MAX_AG_INDICATORS 20 struct bt_hfp_hf { struct bt_rfcomm_dlc rfcomm_dlc; char hf_buffer[HF_MAX_BUF_LEN]; struct at_client at; bt_u32_t hf_features; bt_u32_t ag_features; s8_t ind_table[HF_MAX_AG_INDICATORS]; }; enum hfp_hf_ag_indicators { HF_SERVICE_IND, HF_CALL_IND, HF_CALL_SETUP_IND, HF_CALL_HELD_IND, HF_SINGNAL_IND, HF_ROAM_IND, HF_BATTERY_IND };
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/hfp_internal.h
C
apache-2.0
2,567
/* keys.c - Bluetooth key handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <stdlib.h> #include <atomic.h> #include <misc/util.h> #include <settings/settings.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci.h> #if defined(CONFIG_BT_SMP) #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_KEYS) #define LOG_MODULE_NAME bt_keys #include "common/log.h" #include "common/rpa.h" #include "gatt_internal.h" #include "hci_core.h" #include "smp.h" #include "settings.h" #include "keys.h" #include "bt_errno.h" static struct bt_keys key_pool[CONFIG_BT_MAX_PAIRED]; #define BT_KEYS_STORAGE_LEN_COMPAT (BT_KEYS_STORAGE_LEN - sizeof(uint32_t)) #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) static bt_u32_t aging_counter_val; static struct bt_keys *last_keys_updated; #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr) { struct bt_keys *keys; int i; size_t first_free_slot = ARRAY_SIZE(key_pool); BT_DBG("%s", bt_addr_le_str(addr)); for (i = 0; i < ARRAY_SIZE(key_pool); i++) { keys = &key_pool[i]; if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) { return keys; } if (first_free_slot == ARRAY_SIZE(key_pool) && !bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY)) { first_free_slot = i; } } #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) if (first_free_slot == ARRAY_SIZE(key_pool)) { struct bt_keys *oldest = &key_pool[0]; bt_addr_le_t oldest_addr; for (i = 1; i < ARRAY_SIZE(key_pool); i++) { struct bt_keys *current = &key_pool[i]; if (current->aging_counter < oldest->aging_counter) { oldest = current; } } /* Use a copy as bt_unpair will clear the oldest key. */ bt_addr_le_copy(&oldest_addr, &oldest->addr); bt_unpair(oldest->id, &oldest_addr); if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) { first_free_slot = oldest - &key_pool[0]; } } #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ if (first_free_slot < ARRAY_SIZE(key_pool)) { keys = &key_pool[first_free_slot]; keys->id = id; bt_addr_le_copy(&keys->addr, addr); #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) keys->aging_counter = ++aging_counter_val; last_keys_updated = keys; #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ BT_DBG("created %p for %s", keys, bt_addr_le_str(addr)); return keys; } BT_DBG("unable to create keys for %s", bt_addr_le_str(addr)); return NULL; } void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, void *user_data), void *user_data) { int i; for (i = 0; i < ARRAY_SIZE(key_pool); i++) { struct bt_keys *keys = &key_pool[i]; if (keys->keys && keys->id == id) { struct bt_bond_info info; bt_addr_le_copy(&info.addr, &keys->addr); func(&info, user_data); } } } void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data), void *data) { int i; for (i = 0; i < ARRAY_SIZE(key_pool); i++) { if ((key_pool[i].keys & type)) { func(&key_pool[i], data); } } } struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr) { int i; BT_DBG("type %d %s", type, bt_addr_le_str(addr)); for (i = 0; i < ARRAY_SIZE(key_pool); i++) { if ((key_pool[i].keys & type) && key_pool[i].id == id && !bt_addr_le_cmp(&key_pool[i].addr, addr)) { return &key_pool[i]; } } return NULL; } struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr) { struct bt_keys *keys; BT_DBG("type %d %s", type, bt_addr_le_str(addr)); keys = bt_keys_find(type, id, addr); if (keys) { return keys; } keys = bt_keys_get_addr(id, addr); if (!keys) { return NULL; } bt_keys_add_type(keys, type); return keys; } struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr) { int i; BT_DBG("%s", bt_addr_le_str(addr)); if (!bt_addr_le_is_rpa(addr)) { return NULL; } for (i = 0; i < ARRAY_SIZE(key_pool); i++) { if (!(key_pool[i].keys & BT_KEYS_IRK)) { continue; } if (key_pool[i].id == id && !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) { BT_DBG("cached RPA %s for %s", bt_addr_str(&key_pool[i].irk.rpa), bt_addr_le_str(&key_pool[i].addr)); return &key_pool[i]; } } for (i = 0; i < ARRAY_SIZE(key_pool); i++) { if (!(key_pool[i].keys & BT_KEYS_IRK)) { continue; } if (key_pool[i].id != id) { continue; } if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) { BT_DBG("RPA %s matches %s", bt_addr_str(&key_pool[i].irk.rpa), bt_addr_le_str(&key_pool[i].addr)); bt_addr_copy(&key_pool[i].irk.rpa, &addr->a); return &key_pool[i]; } } BT_DBG("No IRK for %s", bt_addr_le_str(addr)); return NULL; } struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr) { int i; BT_DBG("%s", bt_addr_le_str(addr)); for (i = 0; i < ARRAY_SIZE(key_pool); i++) { if (key_pool[i].id == id && !bt_addr_le_cmp(&key_pool[i].addr, addr)) { return &key_pool[i]; } } return NULL; } void bt_keys_add_type(struct bt_keys *keys, int type) { keys->keys |= type; } void bt_keys_clear(struct bt_keys *keys) { BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys); if (keys->state & BT_KEYS_ID_ADDED) { bt_id_del(keys); } if (IS_ENABLED(CONFIG_BT_SETTINGS)) { char key[BT_SETTINGS_KEY_MAX]; /* Delete stored keys from flash */ if (keys->id) { char id[4]; u8_to_dec(id, sizeof(id), keys->id); bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, id); } else { bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, NULL); } BT_DBG("Deleting key %s", log_strdup(key)); settings_delete(key); } (void)memset(keys, 0, sizeof(*keys)); } #if defined(CONFIG_BT_SETTINGS) int bt_keys_store(struct bt_keys *keys) { char key[BT_SETTINGS_KEY_MAX]; int err; if (keys->id) { char id[4]; u8_to_dec(id, sizeof(id), keys->id); bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, id); } else { bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, NULL); } err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN); if (err) { BT_ERR("Failed to save keys (err %d)", err); return err; } BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr), log_strdup(key)); return 0; } static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) { struct bt_keys *keys; bt_addr_le_t addr; u8_t id; ssize_t len; int err; char val[BT_KEYS_STORAGE_LEN]; const char *next; if (!name) { BT_ERR("Insufficient number of arguments"); return -EINVAL; } len = read_cb(cb_arg, val, sizeof(val)); if (len < 0) { BT_ERR("Failed to read value (err %zd)", len); return -EINVAL; } BT_DBG("name %s val %s", log_strdup(name), (len) ? bt_hex(val, sizeof(val)) : "(null)"); err = bt_settings_decode_key(name, &addr); if (err) { BT_ERR("Unable to decode address %s", name); return -EINVAL; } settings_name_next(name, &next); if (!next) { id = BT_ID_DEFAULT; } else { id = strtol(next, NULL, 10); } if (!len) { keys = bt_keys_find(BT_KEYS_ALL, id, &addr); if (keys) { (void)memset(keys, 0, sizeof(*keys)); BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr)); } else { BT_WARN("Unable to find deleted keys for %s", bt_addr_le_str(&addr)); } return 0; } keys = bt_keys_get_addr(id, &addr); if (!keys) { BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr)); return -ENOMEM; } if (len != BT_KEYS_STORAGE_LEN) { do { /* Load shorter structure for compatibility with old * records format with no counter. */ if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) && len == BT_KEYS_STORAGE_LEN_COMPAT) { BT_WARN("Keys for %s have no aging counter", bt_addr_le_str(&addr)); memcpy(keys->storage_start, val, len); continue; } BT_ERR("Invalid key length %zd != %zu", len, BT_KEYS_STORAGE_LEN); bt_keys_clear(keys); return -EINVAL; } while (0); } else { memcpy(keys->storage_start, val, len); } BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr)); #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) if (aging_counter_val < keys->aging_counter) { aging_counter_val = keys->aging_counter; } #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ return 0; } static void id_add(struct bt_keys *keys, void *user_data) { bt_id_add(keys); } static int keys_commit(void) { BT_DBG(""); /* We do this in commit() rather than add() since add() may get * called multiple times for the same address, especially if * the keys were already removed. */ if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_PRIVACY)) { bt_keys_foreach(BT_KEYS_ALL, id_add, NULL); } else { bt_keys_foreach(BT_KEYS_IRK, id_add, NULL); } return 0; } //SETTINGS_STATIC_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit, // NULL); int bt_key_settings_init() { SETTINGS_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit, NULL); return 0; } #endif /* CONFIG_BT_SETTINGS */ #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr) { struct bt_keys *keys = bt_keys_find_addr(id, addr); if (!keys) { return; } if (last_keys_updated == keys) { return; } keys->aging_counter = ++aging_counter_val; last_keys_updated = keys; BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr), keys->aging_counter); if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) { bt_keys_store(keys); } } #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/keys.c
C
apache-2.0
9,847
/* keys.h - Bluetooth key handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ enum { BT_KEYS_SLAVE_LTK = BIT(0), BT_KEYS_IRK = BIT(1), BT_KEYS_LTK = BIT(2), BT_KEYS_LOCAL_CSRK = BIT(3), BT_KEYS_REMOTE_CSRK = BIT(4), BT_KEYS_LTK_P256 = BIT(5), BT_KEYS_ALL = (BT_KEYS_SLAVE_LTK | BT_KEYS_IRK | \ BT_KEYS_LTK | BT_KEYS_LOCAL_CSRK | \ BT_KEYS_REMOTE_CSRK | BT_KEYS_LTK_P256), }; enum { BT_KEYS_ID_PENDING_ADD = BIT(0), BT_KEYS_ID_PENDING_DEL = BIT(1), BT_KEYS_ID_ADDED = BIT(2), }; enum { BT_KEYS_AUTHENTICATED = BIT(0), BT_KEYS_DEBUG = BIT(1), /* Bit 2 and 3 might accidentally exist in old stored keys */ BT_KEYS_SC = BIT(4), }; struct bt_ltk { u8_t rand[8]; u8_t ediv[2]; u8_t val[16]; }; struct bt_irk { u8_t val[16]; bt_addr_t rpa; }; struct bt_csrk { u8_t val[16]; bt_u32_t cnt; }; struct bt_keys { u8_t id; bt_addr_le_t addr; u8_t state; u8_t storage_start[0] __aligned(sizeof(void *)); u8_t enc_size; u8_t flags; u16_t keys; struct bt_ltk ltk; struct bt_irk irk; #if defined(CONFIG_BT_SIGNING) struct bt_csrk local_csrk; struct bt_csrk remote_csrk; #endif /* BT_SIGNING */ #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) struct bt_ltk slave_ltk; #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ #if (defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)) bt_u32_t aging_counter; #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ }; #define BT_KEYS_STORAGE_LEN (sizeof(struct bt_keys) - \ offsetof(struct bt_keys, storage_start)) void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data), void *data); struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr); struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr); struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr); struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr); struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr); void bt_keys_add_type(struct bt_keys *keys, int type); void bt_keys_clear(struct bt_keys *keys); #if defined(CONFIG_BT_SETTINGS) int bt_keys_store(struct bt_keys *keys); #else static inline int bt_keys_store(struct bt_keys *keys) { return 0; } #endif enum { BT_LINK_KEY_AUTHENTICATED = BIT(0), BT_LINK_KEY_DEBUG = BIT(1), BT_LINK_KEY_SC = BIT(2), }; struct bt_keys_link_key { bt_addr_t addr; u8_t flags; u8_t val[16]; }; struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr); struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr); void bt_keys_link_key_clear(struct bt_keys_link_key *link_key); void bt_keys_link_key_clear_addr(const bt_addr_t *addr); /* This function is used to signal that the key has been used for paring */ /* It updates the aging counter and saves it to flash if configuration option */ /* BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING is enabled */ void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/keys.h
C
apache-2.0
3,427
/* keys_br.c - Bluetooth BR/EDR key handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <atomic.h> #include <misc/util.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_KEYS) #define LOG_MODULE_NAME bt_keys_br #include "common/log.h" #include "hci_core.h" #include "keys.h" static struct bt_keys_link_key key_pool[CONFIG_BT_MAX_PAIRED]; struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr) { struct bt_keys_link_key *key; int i; BT_DBG("%s", bt_addr_str(addr)); for (i = 0; i < ARRAY_SIZE(key_pool); i++) { key = &key_pool[i]; if (!bt_addr_cmp(&key->addr, addr)) { return key; } } return NULL; } struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr) { struct bt_keys_link_key *key; key = bt_keys_find_link_key(addr); if (key) { return key; } key = bt_keys_find_link_key(BT_ADDR_ANY); if (key) { bt_addr_copy(&key->addr, addr); BT_DBG("created %p for %s", key, bt_addr_str(addr)); return key; } BT_DBG("unable to create link key for %s", bt_addr_str(addr)); return NULL; } void bt_keys_link_key_clear(struct bt_keys_link_key *link_key) { BT_DBG("%s", bt_addr_str(&link_key->addr)); (void)memset(link_key, 0, sizeof(*link_key)); } void bt_keys_link_key_clear_addr(const bt_addr_t *addr) { struct bt_keys_link_key *key; if (!addr) { (void)memset(key_pool, 0, sizeof(key_pool)); return; } key = bt_keys_find_link_key(addr); if (key) { bt_keys_link_key_clear(key); } }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/keys_br.c
C
apache-2.0
1,658
/* l2cap.c - L2CAP handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <bt_errno.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_L2CAP) #define LOG_MODULE_NAME bt_l2cap #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include <string.h> #define LE_CHAN_RTX(_w) CONTAINER_OF(_w, struct bt_l2cap_le_chan, chan.rtx_work) #define CHAN_RX(_w) CONTAINER_OF(_w, struct bt_l2cap_le_chan, rx_work) #define L2CAP_LE_MIN_MTU 23 #define L2CAP_ECRED_MIN_MTU 64 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) #define L2CAP_LE_MAX_CREDITS (CONFIG_BT_ACL_RX_COUNT - 1) #else #define L2CAP_LE_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1) #endif #define L2CAP_LE_CID_DYN_START 0x0040 #define L2CAP_LE_CID_DYN_END 0x007f #define L2CAP_LE_CID_IS_DYN(_cid) \ (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END) #define L2CAP_LE_PSM_FIXED_START 0x0001 #define L2CAP_LE_PSM_FIXED_END 0x007f #define L2CAP_LE_PSM_DYN_START 0x0080 #define L2CAP_LE_PSM_DYN_END 0x00ff #define L2CAP_LE_PSM_IS_DYN(_psm) \ (_psm >= L2CAP_LE_PSM_DYN_START && _psm <= L2CAP_LE_PSM_DYN_END) #define L2CAP_CONN_TIMEOUT K_SECONDS(40) #define L2CAP_DISC_TIMEOUT K_SECONDS(2) #define L2CAP_RTX_TIMEOUT K_SECONDS(2) static sys_slist_t le_channels; /* Dedicated pool for disconnect buffers so they are guaranteed to be send * even in case of data congestion due to flooding. */ NET_BUF_POOL_FIXED_DEFINE(disc_pool, 1, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) /* Size of MTU is based on the maximum amount of data the buffer can hold * excluding ACL and driver headers. */ #define L2CAP_MAX_LE_MPS BT_L2CAP_RX_MTU /* For now use MPS - SDU length to disable segmentation */ #define L2CAP_MAX_LE_MTU (L2CAP_MAX_LE_MPS - 2) #define L2CAP_ECRED_CHAN_MAX 5 #define l2cap_lookup_ident(conn, ident) __l2cap_lookup_ident(conn, ident, false) #define l2cap_remove_ident(conn, ident) __l2cap_lookup_ident(conn, ident, true) struct data_sent { u16_t len; }; #define data_sent(buf) ((struct data_sent *)net_buf_user_data(buf)) static sys_slist_t servers; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ /* L2CAP signalling channel specific context */ struct bt_l2cap { /* The channel this context is associated with */ struct bt_l2cap_le_chan chan; }; static struct bt_l2cap bt_l2cap_pool[CONFIG_BT_MAX_CONN]; static u8_t get_ident(void) { static u8_t ident; ident++; /* handle integer overflow (0 is not valid) */ if (!ident) { ident++; } return ident; } void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan) { BT_DBG("CID 0x%04x", chan->cid); sys_slist_append(&le_channels, &chan->node); } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn, struct bt_l2cap_chan *chan) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); u16_t cid; /* * No action needed if there's already a CID allocated, e.g. in * the case of a fixed channel. */ if (ch->rx.cid > 0) { return ch; } for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) { if (!bt_l2cap_le_lookup_rx_cid(conn, cid)) { ch->rx.cid = cid; return ch; } } return NULL; } static struct bt_l2cap_le_chan * __l2cap_lookup_ident(struct bt_conn *conn, u16_t ident, bool remove) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (chan->ident == ident) { if (remove) { sys_slist_remove(&conn->channels, prev, &chan->node); } return BT_L2CAP_LE_CHAN(chan); } prev = &chan->node; } return NULL; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (chan == ch) { sys_slist_remove(&conn->channels, prev, &chan->node); return; } prev = &chan->node; } } const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state) { switch (state) { case BT_L2CAP_DISCONNECTED: return "disconnected"; case BT_L2CAP_CONNECT: return "connect"; case BT_L2CAP_CONFIG: return "config"; case BT_L2CAP_CONNECTED: return "connected"; case BT_L2CAP_DISCONNECT: return "disconnect"; default: return "unknown"; } } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) #if defined(CONFIG_BT_DEBUG_L2CAP) void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state, const char *func, int line) { BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm, bt_l2cap_chan_state_str(chan->state), bt_l2cap_chan_state_str(state)); /* check transitions validness */ switch (state) { case BT_L2CAP_DISCONNECTED: /* regardless of old state always allows this state */ break; case BT_L2CAP_CONNECT: if (chan->state != BT_L2CAP_DISCONNECTED) { BT_WARN("%s()%d: invalid transition", func, line); } break; case BT_L2CAP_CONFIG: if (chan->state != BT_L2CAP_CONNECT) { BT_WARN("%s()%d: invalid transition", func, line); } break; case BT_L2CAP_CONNECTED: if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECT) { BT_WARN("%s()%d: invalid transition", func, line); } break; case BT_L2CAP_DISCONNECT: if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECTED) { BT_WARN("%s()%d: invalid transition", func, line); } break; default: BT_ERR("%s()%d: unknown (%u) state was set", func, line, state); return; } chan->state = state; } #else void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state) { chan->state = state; } #endif /* CONFIG_BT_DEBUG_L2CAP */ #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_del(struct bt_l2cap_chan *chan) { const struct bt_l2cap_chan_ops *ops = chan->ops; BT_DBG("conn %p chan %p", chan->conn, chan); if (!chan->conn) { goto destroy; } if (ops->disconnected) { ops->disconnected(chan); } chan->conn = NULL; destroy: #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) /* Reset internal members of common channel */ bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED); chan->psm = 0U; #endif if (chan->destroy) { chan->destroy(chan); } if (ops->released) { ops->released(chan); } } static void l2cap_rtx_timeout(struct k_work *work) { struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work); struct bt_conn *conn = chan->chan.conn; BT_ERR("chan %p timeout", chan); bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) /* Remove other channels if pending on the same ident */ while ((chan = l2cap_remove_ident(conn, chan->chan.ident))) { bt_l2cap_chan_del(&chan->chan); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf); static void l2cap_rx_process(struct k_work *work) { struct bt_l2cap_le_chan *ch = CHAN_RX(work); struct net_buf *buf; while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { BT_DBG("ch %p buf %p", ch, buf); l2cap_chan_le_recv(ch, buf); net_buf_unref(buf); } } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) { /* Attach channel to the connection */ sys_slist_append(&conn->channels, &chan->node); chan->conn = conn; chan->destroy = destroy; BT_DBG("conn %p chan %p", conn, chan); } static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) { struct bt_l2cap_le_chan *ch; #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) ch = l2cap_chan_alloc_cid(conn, chan); #else ch = BT_L2CAP_LE_CHAN(chan); #endif if (!ch) { BT_ERR("Unable to allocate L2CAP CID"); return false; } k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout); atomic_clear(chan->status); bt_l2cap_chan_add(conn, chan, destroy); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { k_work_init(&ch->rx_work, l2cap_rx_process); k_fifo_init(&ch->rx_queue); bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ return true; } void bt_l2cap_connected(struct bt_conn *conn) { struct bt_l2cap_fixed_chan *fchan; struct bt_l2cap_chan *chan; if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { bt_l2cap_br_connected(conn); return; } SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node) { struct bt_l2cap_le_chan *ch; if (fchan->accept(conn, &chan) < 0) { continue; } ch = BT_L2CAP_LE_CHAN(chan); /* Fill up remaining fixed channel context attached in * fchan->accept() */ ch->rx.cid = fchan->cid; ch->tx.cid = fchan->cid; if (!l2cap_chan_add(conn, chan, fchan->destroy)) { return; } if (chan->ops->connected) { chan->ops->connected(chan); } /* Always set output status to fixed channels */ atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT); if (chan->ops->status) { chan->ops->status(chan, chan->status); } } } void bt_l2cap_disconnected(struct bt_conn *conn) { struct bt_l2cap_chan *chan, *next; SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node) { bt_l2cap_chan_del(chan); } } static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf, u8_t code, u8_t ident, u16_t len) { struct bt_l2cap_sig_hdr *hdr; struct net_buf_pool *pool = NULL; if (code == BT_L2CAP_DISCONN_REQ) { pool = &disc_pool; } /* Don't wait more than the minimum RTX timeout of 2 seconds */ buf = bt_l2cap_create_pdu_timeout(pool, 0, L2CAP_RTX_TIMEOUT); if (!buf) { /* If it was not possible to allocate a buffer within the * timeout return NULL. */ BT_ERR("Unable to allocate buffer for op 0x%02x", code); return NULL; } hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = code; hdr->ident = ident; hdr->len = sys_cpu_to_le16(len); return buf; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_send_req(struct bt_l2cap_chan *chan, struct net_buf *buf, k_timeout_t timeout) { /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126: * * The value of this timer is implementation-dependent but the minimum * initial value is 1 second and the maximum initial value is 60 * seconds. One RTX timer shall exist for each outstanding signaling * request, including each Echo Request. The timer disappears on the * final expiration, when the response is received, or the physical * link is lost. */ k_delayed_work_submit(&chan->rtx_work, timeout); bt_l2cap_send(chan->conn, BT_L2CAP_CID_LE_SIG, buf); } static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch) { struct net_buf *buf; struct bt_l2cap_le_conn_req *req; ch->chan.ident = get_ident(); buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ, ch->chan.ident, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->psm = sys_cpu_to_le16(ch->chan.psm); req->scid = sys_cpu_to_le16(ch->rx.cid); req->mtu = sys_cpu_to_le16(ch->rx.mtu); req->mps = sys_cpu_to_le16(ch->rx.mps); req->credits = sys_cpu_to_le16(ch->rx.init_credits); l2cap_chan_send_req(&ch->chan, buf, L2CAP_CONN_TIMEOUT); return 0; } static int l2cap_ecred_conn_req(struct bt_l2cap_chan **chan, int channels) { struct net_buf *buf; struct bt_l2cap_ecred_conn_req *req; struct bt_l2cap_le_chan *ch; int i; u8_t ident; if (!chan || !channels) { return -EINVAL; } ident = get_ident(); buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_ECRED_CONN_REQ, ident, sizeof(*req) + (channels * sizeof(u16_t))); req = net_buf_add(buf, sizeof(*req)); ch = BT_L2CAP_LE_CHAN(chan[0]); /* Init common parameters */ req->psm = sys_cpu_to_le16(ch->chan.psm); req->mtu = sys_cpu_to_le16(ch->rx.mtu); req->mps = sys_cpu_to_le16(ch->rx.mps); req->credits = sys_cpu_to_le16(ch->rx.init_credits); for (i = 0; i < channels; i++) { ch = BT_L2CAP_LE_CHAN(chan[i]); ch->chan.ident = ident; net_buf_add_le16(buf, ch->rx.cid); } l2cap_chan_send_req(*chan, buf, L2CAP_CONN_TIMEOUT); return 0; } static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, u8_t status) { /* Skip channels that are not pending waiting for encryption */ if (!atomic_test_and_clear_bit(chan->status, BT_L2CAP_STATUS_ENCRYPT_PENDING)) { return; } if (status) { bt_l2cap_chan_remove(chan->conn, chan); bt_l2cap_chan_del(chan); return; } if (chan->ident) { struct bt_l2cap_chan *echan[L2CAP_ECRED_CHAN_MAX]; struct bt_l2cap_le_chan *ch; int i = 0; while ((ch = l2cap_remove_ident(chan->conn, chan->ident))) { echan[i++] = &ch->chan; } /* Retry ecred connect */ l2cap_ecred_conn_req(echan, i); return; } /* Retry to connect */ l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan)); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status) { struct bt_l2cap_chan *chan; if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { l2cap_br_encrypt_change(conn, hci_status); return; } SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) l2cap_le_encrypt_change(chan, hci_status); #endif if (chan->ops->encrypt_change) { chan->ops->encrypt_change(chan, hci_status); } } } struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout) { return bt_conn_create_pdu_timeout(pool, sizeof(struct bt_l2cap_hdr) + reserve, timeout); } int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) { struct bt_l2cap_hdr *hdr; BT_DBG("conn %p cid %u len %u", conn, cid, net_buf_frags_len(buf)); hdr = net_buf_push(buf, sizeof(*hdr)); hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); hdr->cid = sys_cpu_to_le16(cid); return bt_conn_send_cb(conn, buf, cb, user_data); } static void l2cap_send_reject(struct bt_conn *conn, u8_t ident, u16_t reason, void *data, u8_t data_len) { struct bt_l2cap_cmd_reject *rej; struct net_buf *buf; buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident, sizeof(*rej) + data_len); if (!buf) { return; } rej = net_buf_add(buf, sizeof(*rej)); rej->reason = sys_cpu_to_le16(reason); if (data) { net_buf_add_mem(buf, data, data_len); } bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf) { struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small LE conn param rsp"); return; } BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result)); } static void le_conn_param_update_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_le_conn_param param; struct bt_l2cap_conn_param_rsp *rsp; struct bt_l2cap_conn_param_req *req = (void *)buf->data; bool accepted; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn update param req"); return; } if (conn->role != BT_HCI_ROLE_MASTER) { l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); return; } param.interval_min = sys_le16_to_cpu(req->min_interval); param.interval_max = sys_le16_to_cpu(req->max_interval); param.latency = sys_le16_to_cpu(req->latency); param.timeout = sys_le16_to_cpu(req->timeout); BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x", param.interval_min, param.interval_max, param.latency, param.timeout); buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident, sizeof(*rsp)); if (!buf) { return; } accepted = le_param_req(conn, &param); rsp = net_buf_add(buf, sizeof(*rsp)); if (accepted) { rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED); } else { rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED); } bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); if (accepted) { bt_conn_le_conn_update(conn, &param); } } struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, u16_t cid) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) { return chan; } } return NULL; } struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, u16_t cid) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { return chan; } } return NULL; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static struct bt_l2cap_server *l2cap_server_lookup_psm(u16_t psm) { struct bt_l2cap_server *server; SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node) { if (server->psm == psm) { return server; } } return NULL; } int bt_l2cap_server_register(struct bt_l2cap_server *server) { if (!server->accept) { return -EINVAL; } if (server->psm) { if (server->psm < L2CAP_LE_PSM_FIXED_START || server->psm > L2CAP_LE_PSM_DYN_END) { return -EINVAL; } /* Check if given PSM is already in use */ if (l2cap_server_lookup_psm(server->psm)) { BT_DBG("PSM already registered"); return -EADDRINUSE; } } else { u16_t psm; for (psm = L2CAP_LE_PSM_DYN_START; psm <= L2CAP_LE_PSM_DYN_END; psm++) { if (!l2cap_server_lookup_psm(psm)) { break; } } if (psm > L2CAP_LE_PSM_DYN_END) { BT_WARN("No free dynamic PSMs available"); return -EADDRNOTAVAIL; } BT_DBG("Allocated PSM 0x%04x for new server", psm); server->psm = psm; } if (server->sec_level > BT_SECURITY_L4) { return -EINVAL; } else if (server->sec_level < BT_SECURITY_L1) { /* Level 0 is only applicable for BR/EDR */ server->sec_level = BT_SECURITY_L1; } BT_DBG("PSM 0x%04x", server->psm); sys_slist_append(&servers, &server->node); return 0; } static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan) { BT_DBG("chan %p", chan); /* Use existing MTU if defined */ if (!chan->rx.mtu) { chan->rx.mtu = L2CAP_MAX_LE_MTU; } /* Use existing credits if defined */ if (!chan->rx.init_credits) { if (chan->chan.ops->alloc_buf) { /* Auto tune credits to receive a full packet */ chan->rx.init_credits = (chan->rx.mtu + (L2CAP_MAX_LE_MPS - 1)) / L2CAP_MAX_LE_MPS; } else { chan->rx.init_credits = L2CAP_LE_MAX_CREDITS; } } /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot * be used. */ chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS); atomic_set(&chan->rx.credits, 0); if (BT_DBG_ENABLED && chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) { BT_WARN("Not enough credits for a full packet"); } } static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch) { struct net_buf *buf; /* Return current buffer */ if (ch->tx_buf) { buf = ch->tx_buf; ch->tx_buf = NULL; return buf; } return net_buf_get(&ch->tx_queue, K_NO_WAIT); } static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, struct net_buf **buf, u16_t sent); static void l2cap_chan_tx_process(struct k_work *work) { struct bt_l2cap_le_chan *ch; struct net_buf *buf; ch = CONTAINER_OF(work, struct bt_l2cap_le_chan, tx_work); /* Resume tx in case there are buffers in the queue */ while ((buf = l2cap_chan_le_get_tx_buf(ch))) { int sent = data_sent(buf)->len; BT_DBG("buf %p sent %u", buf, sent); sent = l2cap_chan_le_send_sdu(ch, &buf, sent); if (sent < 0) { if (sent == -EAGAIN) { ch->tx_buf = buf; } break; } } } static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan) { BT_DBG("chan %p", chan); (void)memset(&chan->tx, 0, sizeof(chan->tx)); atomic_set(&chan->tx.credits, 0); k_fifo_init(&chan->tx_queue); k_work_init(&chan->tx_work, l2cap_chan_tx_process); } static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan, u16_t credits) { BT_DBG("chan %p credits %u", chan, credits); atomic_add(&chan->tx.credits, credits); if (!atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) && chan->chan.ops->status) { chan->chan.ops->status(&chan->chan, chan->chan.status); } } static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan, u16_t credits) { BT_DBG("chan %p credits %u", chan, credits); atomic_add(&chan->rx.credits, credits); } static void l2cap_chan_destroy(struct bt_l2cap_chan *chan) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct net_buf *buf; BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid); /* Cancel ongoing work */ k_delayed_work_cancel(&chan->rtx_work); if (ch->tx_buf) { net_buf_unref(ch->tx_buf); ch->tx_buf = NULL; } /* Remove buffers on the TX queue */ while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Remove buffers on the RX queue */ while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Destroy segmented SDU if it exists */ if (ch->_sdu) { net_buf_unref(ch->_sdu); ch->_sdu = NULL; ch->_sdu_len = 0U; } } static u16_t le_err_to_result(int err) { switch (err) { case -ENOMEM: return BT_L2CAP_LE_ERR_NO_RESOURCES; case -EACCES: return BT_L2CAP_LE_ERR_AUTHORIZATION; case -EPERM: return BT_L2CAP_LE_ERR_KEY_SIZE; case -ENOTSUP: /* This handle the cases where a fixed channel is registered but * for some reason (e.g. controller not suporting a feature) * cannot be used. */ return BT_L2CAP_LE_ERR_PSM_NOT_SUPP; default: return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS; } } static u16_t l2cap_chan_accept(struct bt_conn *conn, struct bt_l2cap_server *server, u16_t scid, u16_t mtu, u16_t mps, u16_t credits, struct bt_l2cap_chan **chan) { struct bt_l2cap_le_chan *ch; int err; BT_DBG("conn %p scid 0x%04x chan %p", conn, scid, chan); if (!L2CAP_LE_CID_IS_DYN(scid)) { return BT_L2CAP_LE_ERR_INVALID_SCID; } *chan = bt_l2cap_le_lookup_tx_cid(conn, scid); if (*chan) { return BT_L2CAP_LE_ERR_SCID_IN_USE; } /* Request server to accept the new connection and allocate the * channel. */ err = server->accept(conn, chan); if (err < 0) { return le_err_to_result(err); } (*chan)->required_sec_level = server->sec_level; if (!l2cap_chan_add(conn, *chan, l2cap_chan_destroy)) { return BT_L2CAP_LE_ERR_NO_RESOURCES; } ch = BT_L2CAP_LE_CHAN(*chan); /* Init TX parameters */ l2cap_chan_tx_init(ch); ch->tx.cid = scid; ch->tx.mps = mps; ch->tx.mtu = mtu; ch->tx.init_credits = credits; l2cap_chan_tx_give_credits(ch, credits); /* Init RX parameters */ l2cap_chan_rx_init(ch); l2cap_chan_rx_give_credits(ch, ch->rx.init_credits); /* Set channel PSM */ (*chan)->psm = server->psm; /* Update state */ bt_l2cap_chan_set_state(*chan, BT_L2CAP_CONNECTED); if ((*chan)->ops->connected) { (*chan)->ops->connected(*chan); } return BT_L2CAP_LE_SUCCESS; } static void le_conn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_le_chan *ch; struct bt_l2cap_server *server; struct bt_l2cap_le_conn_req *req = (void *)buf->data; struct bt_l2cap_le_conn_rsp *rsp; u16_t psm, scid, mtu, mps, credits; u16_t result; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn req packet size"); return; } psm = sys_le16_to_cpu(req->psm); scid = sys_le16_to_cpu(req->scid); mtu = sys_le16_to_cpu(req->mtu); mps = sys_le16_to_cpu(req->mps); credits = sys_le16_to_cpu(req->credits); BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid, mtu, mps, credits); if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) { BT_ERR("Invalid LE-Conn Req params"); return; } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident, sizeof(*rsp)); if (!buf) { return; } rsp = net_buf_add(buf, sizeof(*rsp)); (void)memset(rsp, 0, sizeof(*rsp)); /* Check if there is a server registered */ server = l2cap_server_lookup_psm(psm); if (!server) { rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP); goto rsp; } /* Check if connection has minimum required security level */ if (conn->sec_level < server->sec_level) { rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION); goto rsp; } result = l2cap_chan_accept(conn, server, scid, mtu, mps, credits, &chan); if (result != BT_L2CAP_LE_SUCCESS) { rsp->result = sys_cpu_to_le16(result); goto rsp; } ch = BT_L2CAP_LE_CHAN(chan); /* Prepare response protocol data */ rsp->dcid = sys_cpu_to_le16(ch->rx.cid); rsp->mps = sys_cpu_to_le16(ch->rx.mps); rsp->mtu = sys_cpu_to_le16(ch->rx.mtu); rsp->credits = sys_cpu_to_le16(ch->rx.init_credits); rsp->result = BT_L2CAP_LE_SUCCESS; rsp: bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_ecred_conn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan[L2CAP_ECRED_CHAN_MAX]; struct bt_l2cap_le_chan *ch = NULL; struct bt_l2cap_server *server; struct bt_l2cap_ecred_conn_req *req; struct bt_l2cap_ecred_conn_rsp *rsp; u16_t psm, mtu, mps, credits, result = BT_L2CAP_LE_ERR_INVALID_SCID; u16_t scid, dcid[L2CAP_ECRED_CHAN_MAX]; int i = 0; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn req packet size"); result = BT_L2CAP_LE_ERR_INVALID_PARAMS; goto response; } req = net_buf_pull_mem(buf, sizeof(*req)); psm = sys_le16_to_cpu(req->psm); mtu = sys_le16_to_cpu(req->mtu); mps = sys_le16_to_cpu(req->mps); credits = sys_le16_to_cpu(req->credits); BT_DBG("psm 0x%02x mtu %u mps %u credits %u", psm, mtu, mps, credits); if (mtu < L2CAP_ECRED_MIN_MTU || mps < L2CAP_ECRED_MIN_MTU) { BT_ERR("Invalid ecred conn req params"); result = BT_L2CAP_LE_ERR_UNACCEPT_PARAMS; goto response; } /* Check if there is a server registered */ server = l2cap_server_lookup_psm(psm); if (!server) { result = BT_L2CAP_LE_ERR_PSM_NOT_SUPP; goto response; } /* Check if connection has minimum required security level */ if (conn->sec_level < server->sec_level) { result = BT_L2CAP_LE_ERR_AUTHENTICATION; goto response; } while (buf->len >= sizeof(scid) && i < L2CAP_ECRED_CHAN_MAX) { scid = net_buf_pull_le16(buf); result = l2cap_chan_accept(conn, server, scid, mtu, mps, credits, &chan[i]); switch (result) { case BT_L2CAP_LE_SUCCESS: ch = BT_L2CAP_LE_CHAN(chan[i]); dcid[i++] = sys_cpu_to_le16(ch->rx.cid); continue; /* Some connections refused – invalid Source CID */ case BT_L2CAP_LE_ERR_INVALID_SCID: /* Some connections refused – Source CID already allocated */ case BT_L2CAP_LE_ERR_SCID_IN_USE: /* If a Destination CID is 0x0000, the channel was not * established. */ dcid[i++] = 0x0000; continue; /* Some connections refused – not enough resources * available. */ case BT_L2CAP_LE_ERR_NO_RESOURCES: default: goto response; } } response: if (!i) { i = buf->len / sizeof(scid); } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_ECRED_CONN_RSP, ident, sizeof(*rsp) + (sizeof(scid) * i)); rsp = net_buf_add(buf, sizeof(*rsp)); (void)memset(rsp, 0, sizeof(*rsp)); if (result == BT_L2CAP_LE_ERR_UNACCEPT_PARAMS || result == BT_L2CAP_LE_ERR_PSM_NOT_SUPP || result == BT_L2CAP_LE_ERR_AUTHENTICATION) { memset(dcid, 0, sizeof(scid) * i); } else if (ch) { rsp->mps = sys_cpu_to_le16(ch->rx.mps); rsp->mtu = sys_cpu_to_le16(ch->rx.mtu); rsp->credits = sys_cpu_to_le16(ch->rx.init_credits); } net_buf_add_mem(buf, dcid, sizeof(scid) * i); rsp->result = sys_cpu_to_le16(result); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_ecred_reconf_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_ecred_reconf_req *req; struct bt_l2cap_ecred_reconf_rsp *rsp; u16_t mtu, mps; u16_t scid, result; if (buf->len < sizeof(*req)) { BT_ERR("Too small ecred reconf req packet size"); return; } req = net_buf_pull_mem(buf, sizeof(*req)); mtu = sys_le16_to_cpu(req->mtu); mps = sys_le16_to_cpu(req->mps); if (mtu < L2CAP_ECRED_MIN_MTU) { result = BT_L2CAP_RECONF_INVALID_MTU; goto response; } if (mps < L2CAP_ECRED_MIN_MTU) { result = BT_L2CAP_RECONF_INVALID_MTU; goto response; } while (buf->len >= sizeof(scid)) { struct bt_l2cap_chan *chan; scid = net_buf_pull_le16(buf); BT_DBG("scid 0x%04x", scid); if (!scid) { continue; } chan = bt_l2cap_le_lookup_tx_cid(conn, scid); if (!chan) { continue; } /* If the MTU value is decreased for any of the included * channels, then the receiver shall disconnect all * included channels. */ if (BT_L2CAP_LE_CHAN(chan)->tx.mtu > mtu) { BT_ERR("chan %p decreased MTU %u -> %u", chan, BT_L2CAP_LE_CHAN(chan)->tx.mtu, mtu); result = BT_L2CAP_RECONF_INVALID_MTU; bt_l2cap_chan_disconnect(chan); goto response; } BT_L2CAP_LE_CHAN(chan)->tx.mtu = mtu; BT_L2CAP_LE_CHAN(chan)->tx.mps = mps; } BT_DBG("mtu %u mps %u", mtu, mps); result = BT_L2CAP_RECONF_SUCCESS; response: buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_ECRED_RECONF_RSP, ident, sizeof(*rsp)); rsp = net_buf_add(buf, sizeof(*rsp)); rsp->result = sys_cpu_to_le16(result); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn, u16_t cid) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; /* Protect fixed channels against accidental removal */ if (!L2CAP_LE_CID_IS_DYN(cid)) { return NULL; } SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { sys_slist_remove(&conn->channels, prev, &chan->node); return BT_L2CAP_LE_CHAN(chan); } prev = &chan->node; } return NULL; } static void le_disconn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_disconn_req *req = (void *)buf->data; struct bt_l2cap_disconn_rsp *rsp; u16_t dcid; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn req packet size"); return; } dcid = sys_le16_to_cpu(req->dcid); BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid)); chan = l2cap_remove_rx_cid(conn, dcid); if (!chan) { struct bt_l2cap_cmd_reject_cid_data data; data.scid = req->scid; data.dcid = req->dcid; l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, sizeof(data)); return; } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident, sizeof(*rsp)); if (!buf) { return; } rsp = net_buf_add(buf, sizeof(*rsp)); rsp->dcid = sys_cpu_to_le16(chan->rx.cid); rsp->scid = sys_cpu_to_le16(chan->tx.cid); bt_l2cap_chan_del(&chan->chan); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static int l2cap_change_security(struct bt_l2cap_le_chan *chan, u16_t err) { int ret; if (atomic_test_bit(chan->chan.status, BT_L2CAP_STATUS_ENCRYPT_PENDING)) { return -EINPROGRESS; } switch (err) { case BT_L2CAP_LE_ERR_ENCRYPTION: if (chan->chan.required_sec_level >= BT_SECURITY_L2) { return -EALREADY; } chan->chan.required_sec_level = BT_SECURITY_L2; break; case BT_L2CAP_LE_ERR_AUTHENTICATION: if (chan->chan.required_sec_level < BT_SECURITY_L2) { chan->chan.required_sec_level = BT_SECURITY_L2; } else if (chan->chan.required_sec_level < BT_SECURITY_L3) { chan->chan.required_sec_level = BT_SECURITY_L3; } else if (chan->chan.required_sec_level < BT_SECURITY_L4) { chan->chan.required_sec_level = BT_SECURITY_L4; } else { return -EALREADY; } break; default: return -EINVAL; } ret = bt_conn_set_security(chan->chan.conn, chan->chan.required_sec_level); if (ret < 0) { return ret; } atomic_set_bit(chan->chan.status, BT_L2CAP_STATUS_ENCRYPT_PENDING); return 0; } static void le_ecred_conn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_ecred_conn_rsp *rsp; u16_t dcid, mtu, mps, credits, result; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small ecred conn rsp packet size"); return; } rsp = net_buf_pull_mem(buf, sizeof(*rsp)); mtu = sys_le16_to_cpu(rsp->mtu); mps = sys_le16_to_cpu(rsp->mps); credits = sys_le16_to_cpu(rsp->credits); result = sys_le16_to_cpu(rsp->result); BT_DBG("mtu 0x%04x mps 0x%04x credits 0x%04x result %u", mtu, mps, credits, result); switch (result) { case BT_L2CAP_LE_ERR_AUTHENTICATION: case BT_L2CAP_LE_ERR_ENCRYPTION: while ((chan = l2cap_lookup_ident(conn, ident))) { /* Cancel RTX work */ k_delayed_work_cancel(&chan->chan.rtx_work); /* If security needs changing wait it to be completed */ if (!l2cap_change_security(chan, result)) { return; } bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); } break; case BT_L2CAP_LE_SUCCESS: /* Some connections refused – invalid Source CID */ case BT_L2CAP_LE_ERR_INVALID_SCID: /* Some connections refused – Source CID already allocated */ case BT_L2CAP_LE_ERR_SCID_IN_USE: /* Some connections refused – not enough resources available */ case BT_L2CAP_LE_ERR_NO_RESOURCES: while ((chan = l2cap_lookup_ident(conn, ident))) { struct bt_l2cap_chan *c; /* Cancel RTX work */ k_delayed_work_cancel(&chan->chan.rtx_work); /* bt_spec5.2, multi dcid wrong package received */ if (buf->len < 2) { bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); continue; } dcid = net_buf_pull_le16(buf); BT_DBG("dcid 0x%04x", dcid); /* If a Destination CID is 0x0000, the channel was not * established. */ if (!dcid) { bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); continue; } c = bt_l2cap_le_lookup_tx_cid(conn, dcid); if (c) { /* If a device receives a * L2CAP_CREDIT_BASED_CONNECTION_RSP packet * with an already assigned Destination CID, * then both the original channel and the new * channel shall be immediately discarded and * not used. */ bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); bt_l2cap_chan_disconnect(c); continue; } chan->tx.cid = dcid; chan->chan.ident = 0U; chan->tx.mtu = mtu; chan->tx.mps = mps; /* Update state */ bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED); if (chan->chan.ops->connected) { chan->chan.ops->connected(&chan->chan); } /* Give credits */ l2cap_chan_tx_give_credits(chan, credits); l2cap_chan_rx_give_credits(chan, chan->rx.init_credits); } break; case BT_L2CAP_LE_ERR_PSM_NOT_SUPP: default: while ((chan = l2cap_remove_ident(conn, ident))) { bt_l2cap_chan_del(&chan->chan); } break; } } static void le_conn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data; u16_t dcid, mtu, mps, credits, result; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small LE conn rsp packet size"); return; } dcid = sys_le16_to_cpu(rsp->dcid); mtu = sys_le16_to_cpu(rsp->mtu); mps = sys_le16_to_cpu(rsp->mps); credits = sys_le16_to_cpu(rsp->credits); result = sys_le16_to_cpu(rsp->result); BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid, mtu, mps, credits, result); /* Keep the channel in case of security errors */ if (result == BT_L2CAP_LE_SUCCESS || result == BT_L2CAP_LE_ERR_AUTHENTICATION || result == BT_L2CAP_LE_ERR_ENCRYPTION) { chan = l2cap_lookup_ident(conn, ident); } else { chan = l2cap_remove_ident(conn, ident); } if (!chan) { BT_ERR("Cannot find channel for ident %u", ident); return; } /* Cancel RTX work */ k_delayed_work_cancel(&chan->chan.rtx_work); /* Reset ident since it got a response */ chan->chan.ident = 0U; switch (result) { case BT_L2CAP_LE_SUCCESS: chan->tx.cid = dcid; chan->tx.mtu = mtu; chan->tx.mps = mps; /* Update state */ bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED); if (chan->chan.ops->connected) { chan->chan.ops->connected(&chan->chan); } /* Give credits */ l2cap_chan_tx_give_credits(chan, credits); l2cap_chan_rx_give_credits(chan, chan->rx.init_credits); break; case BT_L2CAP_LE_ERR_AUTHENTICATION: case BT_L2CAP_LE_ERR_ENCRYPTION: /* If security needs changing wait it to be completed */ if (l2cap_change_security(chan, result) == 0) { return; } bt_l2cap_chan_remove(conn, &chan->chan); default: bt_l2cap_chan_del(&chan->chan); break; } } static void le_disconn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data; u16_t scid; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small LE disconn rsp packet size"); return; } scid = sys_le16_to_cpu(rsp->scid); BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid); chan = l2cap_remove_rx_cid(conn, scid); if (!chan) { return; } bt_l2cap_chan_del(&chan->chan); } static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); struct net_buf *seg; /* Try to use original pool if possible */ seg = net_buf_alloc(pool, K_NO_WAIT); if (seg) { net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE); return seg; } /* Fallback to using global connection tx pool */ return bt_l2cap_create_pdu_timeout(NULL, 0, K_NO_WAIT); } static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch, struct net_buf *buf, size_t sdu_hdr_len) { struct net_buf *seg; u16_t headroom; u16_t len; /* Segment if data (+ data headroom) is bigger than MPS */ if (buf->len + sdu_hdr_len > ch->tx.mps) { goto segment; } headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len; /* Check if original buffer has enough headroom and don't have any * fragments. */ if (net_buf_headroom(buf) >= headroom && !buf->frags) { if (sdu_hdr_len) { /* Push SDU length if set */ net_buf_push_le16(buf, net_buf_frags_len(buf)); } return net_buf_ref(buf); } segment: seg = l2cap_alloc_seg(buf); if (!seg) { return NULL; } if (sdu_hdr_len) { net_buf_add_le16(seg, net_buf_frags_len(buf)); } /* Don't send more that TX MPS including SDU length */ len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len); /* Limit if original buffer is smaller than the segment */ len = MIN(buf->len, len); net_buf_add_mem(seg, buf->data, len); net_buf_pull(buf, len); BT_DBG("ch %p seg %p len %u", ch, seg, seg->len); return seg; } static void l2cap_chan_tx_resume(struct bt_l2cap_le_chan *ch) { if (!atomic_get(&ch->tx.credits) || (k_fifo_is_empty(&ch->tx_queue) && !ch->tx_buf)) { return; } k_work_submit(&ch->tx_work); } static void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data) { struct bt_l2cap_chan *chan = user_data; BT_DBG("conn %p chan %p", conn, chan); if (chan->ops->sent) { chan->ops->sent(chan); } l2cap_chan_tx_resume(BT_L2CAP_LE_CHAN(chan)); } static void l2cap_chan_seg_sent(struct bt_conn *conn, void *user_data) { struct bt_l2cap_chan *chan = user_data; BT_DBG("conn %p chan %p", conn, chan); l2cap_chan_tx_resume(BT_L2CAP_LE_CHAN(chan)); } static bool test_and_dec(atomic_t *target) { atomic_t old_value, new_value; do { old_value = atomic_get(target); if (!old_value) { return false; } new_value = old_value - 1; } while (atomic_cas(target, old_value, new_value) == 0); return true; } /* This returns -EAGAIN whenever a segment cannot be send immediately which can * happen under the following circuntances: * * 1. There are no credits * 2. There are no buffers * 3. There are no TX contexts * * In all cases the original buffer is unaffected so it can be pushed back to * be sent later. */ static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf, u16_t sdu_hdr_len) { struct net_buf *seg; struct net_buf_simple_state state; int len, err; if (!test_and_dec(&ch->tx.credits)) { BT_WARN("No credits to transmit packet"); return -EAGAIN; } /* Save state so it can be restored if we failed to send */ net_buf_simple_save(&buf->b, &state); seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len); if (!seg) { atomic_inc(&ch->tx.credits); return -EAGAIN; } BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid, seg->len, atomic_get(&ch->tx.credits)); len = seg->len - sdu_hdr_len; /* Set a callback if there is no data left in the buffer and sent * callback has been set. */ if ((buf == seg || !buf->len) && ch->chan.ops->sent) { err = bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, l2cap_chan_sdu_sent, &ch->chan); } else { err = bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, l2cap_chan_seg_sent, &ch->chan); } if (err) { BT_WARN("Unable to send seg %d", err); atomic_inc(&ch->tx.credits); if (err == -ENOBUFS) { /* Restore state since segment could not be sent */ net_buf_simple_restore(&buf->b, &state); return -EAGAIN; } return err; } /* Check if there is no credits left clear output status and notify its * change. */ if (!atomic_get(&ch->tx.credits)) { atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT); if (ch->chan.ops->status) { ch->chan.ops->status(&ch->chan, ch->chan.status); } } return len; } static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, struct net_buf **buf, u16_t sent) { int ret, total_len; struct net_buf *frag; total_len = net_buf_frags_len(*buf) + sent; if (total_len > ch->tx.mtu) { return -EMSGSIZE; } frag = *buf; if (!frag->len && frag->frags) { frag = frag->frags; } if (!sent) { /* Add SDU length for the first segment */ ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN); if (ret < 0) { if (ret == -EAGAIN) { /* Store sent data into user_data */ data_sent(frag)->len = sent; } *buf = frag; return ret; } sent = ret; } /* Send remaining segments */ for (ret = 0; sent < total_len; sent += ret) { /* Proceed to next fragment */ if (!frag->len) { frag = net_buf_frag_del(NULL, frag); } ret = l2cap_chan_le_send(ch, frag, 0); if (ret < 0) { if (ret == -EAGAIN) { /* Store sent data into user_data */ data_sent(frag)->len = sent; } *buf = frag; return ret; } } BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent, total_len); net_buf_unref(frag); return ret; } static void le_credits(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_le_credits *ev = (void *)buf->data; struct bt_l2cap_le_chan *ch; u16_t credits, cid; if (buf->len < sizeof(*ev)) { BT_ERR("Too small LE Credits packet size"); return; } cid = sys_le16_to_cpu(ev->cid); credits = sys_le16_to_cpu(ev->credits); BT_DBG("cid 0x%04x credits %u", cid, credits); chan = bt_l2cap_le_lookup_tx_cid(conn, cid); if (!chan) { BT_ERR("Unable to find channel of LE Credits packet"); return; } ch = BT_L2CAP_LE_CHAN(chan); if (atomic_get(&ch->tx.credits) + credits > UINT16_MAX) { BT_ERR("Credits overflow"); bt_l2cap_chan_disconnect(chan); return; } l2cap_chan_tx_give_credits(ch, credits); BT_DBG("chan %p total credits %u", ch, atomic_get(&ch->tx.credits)); l2cap_chan_tx_resume(ch); } static void reject_cmd(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; /* Check if there is a outstanding channel */ chan = l2cap_remove_ident(conn, ident); if (!chan) { return; } bt_l2cap_chan_del(&chan->chan); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan); struct bt_l2cap_sig_hdr *hdr; u16_t len; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small L2CAP signaling PDU"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); len = sys_le16_to_cpu(hdr->len); BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, hdr->ident, len); if (buf->len != len) { BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len); return 0; } if (!hdr->ident) { BT_ERR("Invalid ident value in L2CAP PDU"); return 0; } switch (hdr->code) { case BT_L2CAP_CONN_PARAM_RSP: le_conn_param_rsp(l2cap, buf); break; #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) case BT_L2CAP_LE_CONN_REQ: le_conn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_LE_CONN_RSP: le_conn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_DISCONN_REQ: le_disconn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_DISCONN_RSP: le_disconn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_LE_CREDITS: le_credits(l2cap, hdr->ident, buf); break; case BT_L2CAP_CMD_REJECT: reject_cmd(l2cap, hdr->ident, buf); break; case BT_L2CAP_ECRED_CONN_REQ: le_ecred_conn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_ECRED_CONN_RSP: le_ecred_conn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_ECRED_RECONF_REQ: le_ecred_reconf_req(l2cap, hdr->ident, buf); break; #else case BT_L2CAP_CMD_REJECT: /* Ignored */ break; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ case BT_L2CAP_CONN_PARAM_REQ: if (IS_ENABLED(CONFIG_BT_CENTRAL)) { le_conn_param_update_req(l2cap, hdr->ident, buf); break; } /* Fall-through */ default: BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code); l2cap_send_reject(chan->conn, hdr->ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); break; } return 0; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_shutdown(struct bt_l2cap_chan *chan) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct net_buf *buf; BT_DBG("chan %p", chan); atomic_set_bit(chan->status, BT_L2CAP_STATUS_SHUTDOWN); /* Destroy segmented SDU if it exists */ if (ch->_sdu) { net_buf_unref(ch->_sdu); ch->_sdu = NULL; ch->_sdu_len = 0U; } /* Cleanup outstanding request */ if (ch->tx_buf) { net_buf_unref(ch->tx_buf); ch->tx_buf = NULL; } /* Remove buffers on the TX queue */ while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Remove buffers on the RX queue */ while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Update status */ if (chan->ops->status) { chan->ops->status(chan, chan->status); } } static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf, u16_t credits) { struct bt_l2cap_le_credits *ev; /* Cap the number of credits given */ if (credits > chan->rx.init_credits) { credits = chan->rx.init_credits; } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(), sizeof(*ev)); if (!buf) { BT_ERR("Unable to send credits update"); /* Disconnect would probably not work either so the only * option left is to shutdown the channel. */ l2cap_chan_shutdown(&chan->chan); return; } l2cap_chan_rx_give_credits(chan, credits); ev = net_buf_add(buf, sizeof(*ev)); ev->cid = sys_cpu_to_le16(chan->rx.cid); ev->credits = sys_cpu_to_le16(credits); bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf); BT_DBG("chan %p credits %u", chan, atomic_get(&chan->rx.credits)); } static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { u16_t credits; atomic_val_t old_credits = atomic_get(&chan->rx.credits); /* Restore enough credits to complete the sdu */ credits = ((chan->_sdu_len - net_buf_frags_len(buf)) + (chan->rx.mps - 1)) / chan->rx.mps; if (credits < old_credits) { return; } credits -= old_credits; l2cap_chan_send_credits(chan, buf, credits); } int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct bt_conn *conn = chan->conn; u16_t credits; __ASSERT_NO_MSG(chan); __ASSERT_NO_MSG(buf); if (!conn) { return -ENOTCONN; } if (conn->type != BT_CONN_TYPE_LE) { return -ENOTSUP; } BT_DBG("chan %p buf %p", chan, buf); /* Restore credits used by packet */ memcpy(&credits, net_buf_user_data(buf), sizeof(credits)); l2cap_chan_send_credits(ch, buf, credits); net_buf_unref(buf); return 0; } static struct net_buf *l2cap_alloc_frag(k_timeout_t timeout, void *user_data) { struct bt_l2cap_le_chan *chan = user_data; struct net_buf *frag = NULL; frag = chan->chan.ops->alloc_buf(&chan->chan); if (!frag) { return NULL; } BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag)); return frag; } static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan, struct net_buf *buf, u16_t seg) { int err; BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf)); /* Receiving complete SDU, notify channel and reset SDU buf */ err = chan->chan.ops->recv(&chan->chan, buf); if (err < 0) { if (err != -EINPROGRESS) { BT_ERR("err %d", err); bt_l2cap_chan_disconnect(&chan->chan); net_buf_unref(buf); } return; } l2cap_chan_send_credits(chan, buf, seg); net_buf_unref(buf); } static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { u16_t len; u16_t seg = 0U; len = net_buf_frags_len(chan->_sdu); if (len) { memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg)); } if (len + buf->len > chan->_sdu_len) { BT_ERR("SDU length mismatch"); bt_l2cap_chan_disconnect(&chan->chan); return; } seg++; /* Store received segments in user_data */ memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg)); BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf)); /* Append received segment to SDU */ len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT, l2cap_alloc_frag, chan); if (len != buf->len) { BT_ERR("Unable to store SDU"); bt_l2cap_chan_disconnect(&chan->chan); return; } if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) { /* Give more credits if remote has run out of them, this * should only happen if the remote cannot fully utilize the * MPS for some reason. */ if (!atomic_get(&chan->rx.credits) && seg == chan->rx.init_credits) { l2cap_chan_update_credits(chan, buf); } return; } buf = chan->_sdu; chan->_sdu = NULL; chan->_sdu_len = 0U; l2cap_chan_le_recv_sdu(chan, buf, seg); } static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { u16_t sdu_len; int err; if (!test_and_dec(&chan->rx.credits)) { BT_ERR("No credits to receive packet"); bt_l2cap_chan_disconnect(&chan->chan); return; } /* Check if segments already exist */ if (chan->_sdu) { l2cap_chan_le_recv_seg(chan, buf); return; } sdu_len = net_buf_pull_le16(buf); BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len); if (sdu_len > chan->rx.mtu) { BT_ERR("Invalid SDU length"); bt_l2cap_chan_disconnect(&chan->chan); return; } /* Always allocate buffer from the channel if supported. */ if (chan->chan.ops->alloc_buf) { chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan); if (!chan->_sdu) { BT_ERR("Unable to allocate buffer for SDU"); bt_l2cap_chan_disconnect(&chan->chan); return; } chan->_sdu_len = sdu_len; l2cap_chan_le_recv_seg(chan, buf); return; } err = chan->chan.ops->recv(&chan->chan, buf); if (err) { if (err != -EINPROGRESS) { BT_ERR("err %d", err); bt_l2cap_chan_disconnect(&chan->chan); } return; } l2cap_chan_send_credits(chan, buf, 1); } static void l2cap_chan_recv_queue(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { if (chan->chan.state == BT_L2CAP_DISCONNECT) { BT_WARN("Ignoring data received while disconnecting"); net_buf_unref(buf); return; } if (atomic_test_bit(chan->chan.status, BT_L2CAP_STATUS_SHUTDOWN)) { BT_WARN("Ignoring data received while channel has shutdown"); net_buf_unref(buf); return; } if (!L2CAP_LE_PSM_IS_DYN(chan->chan.psm)) { l2cap_chan_le_recv(chan, buf); net_buf_unref(buf); return; } net_buf_put(&chan->rx_queue, buf); k_work_submit(&chan->rx_work); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { l2cap_chan_recv_queue(ch, buf); return; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ BT_DBG("chan %p len %u", chan, buf->len); chan->ops->recv(chan, buf); net_buf_unref(buf); } void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf) { struct bt_l2cap_hdr *hdr; struct bt_l2cap_chan *chan; u16_t cid; if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { bt_l2cap_br_recv(conn, buf); return; } if (buf->len < sizeof(*hdr)) { BT_ERR("Too small L2CAP PDU received"); net_buf_unref(buf); return; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); cid = sys_le16_to_cpu(hdr->cid); BT_DBG("Packet for CID %u len %u", cid, buf->len); chan = bt_l2cap_le_lookup_rx_cid(conn, cid); if (!chan) { BT_WARN("Ignoring data for unknown CID 0x%04x", cid); net_buf_unref(buf); return; } l2cap_chan_recv(chan, buf); } int bt_l2cap_update_conn_param(struct bt_conn *conn, const struct bt_le_conn_param *param) { struct bt_l2cap_conn_param_req *req; struct net_buf *buf; buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, get_ident(), sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->min_interval = sys_cpu_to_le16(param->interval_min); req->max_interval = sys_cpu_to_le16(param->interval_max); req->latency = sys_cpu_to_le16(param->latency); req->timeout = sys_cpu_to_le16(param->timeout); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); return 0; } static void l2cap_connected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); } static void l2cap_disconnected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); } static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { int i; static const struct bt_l2cap_chan_ops ops = { .connected = l2cap_connected, .disconnected = l2cap_disconnected, .recv = l2cap_recv, }; BT_DBG("conn %p handle %u", conn, conn->handle); for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) { struct bt_l2cap *l2cap = &bt_l2cap_pool[i]; if (l2cap->chan.chan.conn) { continue; } l2cap->chan.chan.ops = &ops; *chan = &l2cap->chan.chan; return 0; } BT_ERR("No available L2CAP context for conn %p", conn); return -ENOMEM; } BT_L2CAP_CHANNEL_DEFINE(le_fixed_chan, BT_L2CAP_CID_LE_SIG, l2cap_accept, NULL); void bt_l2cap_init(void) { NET_BUF_POOL_INIT(disc_pool); bt_l2cap_le_fixed_chan_register(&le_fixed_chan); if (IS_ENABLED(CONFIG_BT_BREDR)) { bt_l2cap_br_init(); } } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, u16_t psm) { if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) { return -EINVAL; } l2cap_chan_tx_init(ch); l2cap_chan_rx_init(ch); if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) { return -ENOMEM; } ch->chan.psm = psm; return l2cap_le_conn_req(ch); } static int l2cap_ecred_init(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, u16_t psm) { if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) { return -EINVAL; } l2cap_chan_tx_init(ch); l2cap_chan_rx_init(ch); if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) { return -ENOMEM; } ch->chan.psm = psm; BT_DBG("ch %p psm 0x%02x mtu %u mps %u credits %u", ch, ch->chan.psm, ch->rx.mtu, ch->rx.mps, ch->rx.init_credits); return 0; } int bt_l2cap_ecred_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan **chan, u16_t psm) { int i, err; BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm); if (!conn || !chan) { return -EINVAL; } /* Init non-null channels */ for (i = 0; i < L2CAP_ECRED_CHAN_MAX; i++) { if (!chan[i]) { break; } err = l2cap_ecred_init(conn, BT_L2CAP_LE_CHAN(chan[i]), psm); if (err < 0) { i--; goto fail; } } return l2cap_ecred_conn_req(chan, i); fail: /* Remove channels added */ for (; i >= 0; i--) { if (!chan[i]) { continue; } bt_l2cap_chan_remove(conn, chan[i]); } return err; } int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm) { BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm); if (!conn || conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (!chan) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { return bt_l2cap_br_chan_connect(conn, chan, psm); } if (chan->required_sec_level > BT_SECURITY_L4) { return -EINVAL; } else if (chan->required_sec_level == BT_SECURITY_L0) { chan->required_sec_level = BT_SECURITY_L1; } return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm); } int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan) { struct bt_conn *conn = chan->conn; struct net_buf *buf; struct bt_l2cap_disconn_req *req; struct bt_l2cap_le_chan *ch; if (!conn) { return -ENOTCONN; } if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { return bt_l2cap_br_chan_disconnect(chan); } ch = BT_L2CAP_LE_CHAN(chan); BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, ch->tx.cid); ch->chan.ident = get_ident(); buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ, ch->chan.ident, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->dcid = sys_cpu_to_le16(ch->rx.cid); req->scid = sys_cpu_to_le16(ch->tx.cid); l2cap_chan_send_req(chan, buf, L2CAP_DISC_TIMEOUT); bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT); return 0; } int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); int err; if (!buf) { return -EINVAL; } BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf)); if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (atomic_test_bit(chan->status, BT_L2CAP_STATUS_SHUTDOWN)) { return -ESHUTDOWN; } if (IS_ENABLED(CONFIG_BT_BREDR) && chan->conn->type == BT_CONN_TYPE_BR) { return bt_l2cap_br_chan_send(chan, buf); } /* Queue if there are pending segments left from previous packet or * there are no credits available. */ if (ch->tx_buf || !k_fifo_is_empty(&ch->tx_queue) || !atomic_get(&ch->tx.credits)) { data_sent(buf)->len = 0; net_buf_put(&ch->tx_queue, buf); k_work_submit(&ch->tx_work); return 0; } err = l2cap_chan_le_send_sdu(ch, &buf, 0); if (err < 0) { if (err == -EAGAIN && data_sent(buf)->len) { /* Queue buffer if at least one segment could be sent */ net_buf_put(&ch->tx_queue, buf); return data_sent(buf)->len; } BT_ERR("failed to send message %d", err); } return err; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/l2cap.c
C
apache-2.0
60,588
/* l2cap_br.c - L2CAP BREDR oriented handling */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <bt_errno.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #ifdef CONFIG_BT_BREDR #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_L2CAP) #define LOG_MODULE_NAME bt_l2cap_br #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "avdtp_internal.h" #include "a2dp_internal.h" #include "rfcomm_internal.h" #include "sdp_internal.h" #define BR_CHAN(_ch) CONTAINER_OF(_ch, struct bt_l2cap_br_chan, chan) #define BR_CHAN_RTX(_w) CONTAINER_OF(_w, struct bt_l2cap_br_chan, chan.rtx_work) #define L2CAP_BR_PSM_START 0x0001 #define L2CAP_BR_PSM_END 0xffff #define L2CAP_BR_CID_DYN_START 0x0040 #define L2CAP_BR_CID_DYN_END 0xffff #define L2CAP_BR_CID_IS_DYN(_cid) \ (_cid >= L2CAP_BR_CID_DYN_START && _cid <= L2CAP_BR_CID_DYN_END) #define L2CAP_BR_MIN_MTU 48 #define L2CAP_BR_DEFAULT_MTU 672 #define L2CAP_BR_PSM_SDP 0x0001 #define L2CAP_BR_INFO_TIMEOUT K_SECONDS(4) #define L2CAP_BR_CFG_TIMEOUT K_SECONDS(4) #define L2CAP_BR_DISCONN_TIMEOUT K_SECONDS(1) #define L2CAP_BR_CONN_TIMEOUT K_SECONDS(40) /* Size of MTU is based on the maximum amount of data the buffer can hold * excluding ACL and driver headers. */ #define L2CAP_BR_MAX_MTU BT_L2CAP_RX_MTU /* * L2CAP extended feature mask: * BR/EDR fixed channel support enabled */ #define L2CAP_FEAT_FIXED_CHAN_MASK 0x00000080 enum { /* Connection oriented channels flags */ L2CAP_FLAG_CONN_LCONF_DONE, /* local config accepted by remote */ L2CAP_FLAG_CONN_RCONF_DONE, /* remote config accepted by local */ L2CAP_FLAG_CONN_ACCEPTOR, /* getting incoming connection req */ L2CAP_FLAG_CONN_PENDING, /* remote sent pending result in rsp */ /* Signaling channel flags */ L2CAP_FLAG_SIG_INFO_PENDING, /* retrieving remote l2cap info */ L2CAP_FLAG_SIG_INFO_DONE, /* remote l2cap info is done */ /* fixed channels flags */ L2CAP_FLAG_FIXED_CONNECTED, /* fixed connected */ }; static sys_slist_t br_servers; static sys_slist_t br_fixed_channels; /* Pool for outgoing BR/EDR signaling packets, min MTU is 48 */ NET_BUF_POOL_FIXED_DEFINE(br_sig_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(L2CAP_BR_MIN_MTU), NULL); /* BR/EDR L2CAP signalling channel specific context */ struct bt_l2cap_br { /* The channel this context is associated with */ struct bt_l2cap_br_chan chan; u8_t info_ident; u8_t info_fixed_chan; bt_u32_t info_feat_mask; }; static struct bt_l2cap_br bt_l2cap_br_pool[CONFIG_BT_MAX_CONN]; struct bt_l2cap_chan *bt_l2cap_br_lookup_rx_cid(struct bt_conn *conn, u16_t cid) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BR_CHAN(chan)->rx.cid == cid) { return chan; } } return NULL; } struct bt_l2cap_chan *bt_l2cap_br_lookup_tx_cid(struct bt_conn *conn, u16_t cid) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BR_CHAN(chan)->tx.cid == cid) { return chan; } } return NULL; } static struct bt_l2cap_br_chan* l2cap_br_chan_alloc_cid(struct bt_conn *conn, struct bt_l2cap_chan *chan) { struct bt_l2cap_br_chan *ch = BR_CHAN(chan); u16_t cid; /* * No action needed if there's already a CID allocated, e.g. in * the case of a fixed channel. */ if (ch->rx.cid > 0) { return ch; } /* * L2CAP_BR_CID_DYN_END is 0xffff so we don't check against it since * cid is u16_t, just check against u16_t overflow */ for (cid = L2CAP_BR_CID_DYN_START; cid; cid++) { if (!bt_l2cap_br_lookup_rx_cid(conn, cid)) { ch->rx.cid = cid; return ch; } } return NULL; } static void l2cap_br_chan_cleanup(struct bt_l2cap_chan *chan) { bt_l2cap_chan_remove(chan->conn, chan); bt_l2cap_chan_del(chan); } static void l2cap_br_chan_destroy(struct bt_l2cap_chan *chan) { BT_DBG("chan %p cid 0x%04x", BR_CHAN(chan), BR_CHAN(chan)->rx.cid); /* Cancel ongoing work */ k_delayed_work_cancel(&chan->rtx_work); atomic_clear(BR_CHAN(chan)->flags); } static void l2cap_br_rtx_timeout(struct k_work *work) { struct bt_l2cap_br_chan *chan = BR_CHAN_RTX(work); BT_WARN("chan %p timeout", chan); if (chan->rx.cid == BT_L2CAP_CID_BR_SIG) { BT_DBG("Skip BR/EDR signalling channel "); atomic_clear_bit(chan->flags, L2CAP_FLAG_SIG_INFO_PENDING); return; } BT_DBG("chan %p %s scid 0x%04x", chan, bt_l2cap_chan_state_str(chan->chan.state), chan->rx.cid); switch (chan->chan.state) { case BT_L2CAP_CONFIG: bt_l2cap_br_chan_disconnect(&chan->chan); break; case BT_L2CAP_DISCONNECT: case BT_L2CAP_CONNECT: l2cap_br_chan_cleanup(&chan->chan); break; default: break; } } static bool l2cap_br_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) { struct bt_l2cap_br_chan *ch = l2cap_br_chan_alloc_cid(conn, chan); if (!ch) { BT_DBG("Unable to allocate L2CAP CID"); return false; } k_delayed_work_init(&chan->rtx_work, l2cap_br_rtx_timeout); bt_l2cap_chan_add(conn, chan, destroy); return true; } static u8_t l2cap_br_get_ident(void) { static u8_t ident; ident++; /* handle integer overflow (0 is not valid) */ if (!ident) { ident++; } return ident; } static void l2cap_br_chan_send_req(struct bt_l2cap_br_chan *chan, struct net_buf *buf, k_timeout_t timeout) { /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126: * * The value of this timer is implementation-dependent but the minimum * initial value is 1 second and the maximum initial value is 60 * seconds. One RTX timer shall exist for each outstanding signaling * request, including each Echo Request. The timer disappears on the * final expiration, when the response is received, or the physical * link is lost. */ k_delayed_work_submit(&chan->chan.rtx_work, timeout); bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_BR_SIG, buf); } static void l2cap_br_get_info(struct bt_l2cap_br *l2cap, u16_t info_type) { struct bt_l2cap_info_req *info; struct net_buf *buf; struct bt_l2cap_sig_hdr *hdr; BT_DBG("info type %u", info_type); if (atomic_test_bit(l2cap->chan.flags, L2CAP_FLAG_SIG_INFO_PENDING)) { return; } switch (info_type) { case BT_L2CAP_INFO_FEAT_MASK: case BT_L2CAP_INFO_FIXED_CHAN: break; default: BT_WARN("Unsupported info type %u", info_type); return; } buf = bt_l2cap_create_pdu(&br_sig_pool, 0); atomic_set_bit(l2cap->chan.flags, L2CAP_FLAG_SIG_INFO_PENDING); l2cap->info_ident = l2cap_br_get_ident(); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_INFO_REQ; hdr->ident = l2cap->info_ident; hdr->len = sys_cpu_to_le16(sizeof(*info)); info = net_buf_add(buf, sizeof(*info)); info->type = sys_cpu_to_le16(info_type); l2cap_br_chan_send_req(&l2cap->chan, buf, L2CAP_BR_INFO_TIMEOUT); } static void connect_fixed_channel(struct bt_l2cap_br_chan *chan) { if (atomic_test_and_set_bit(chan->flags, L2CAP_FLAG_FIXED_CONNECTED)) { return; } if (chan->chan.ops && chan->chan.ops->connected) { chan->chan.ops->connected(&chan->chan); } } static void connect_optional_fixed_channels(struct bt_l2cap_br *l2cap) { /* can be change to loop if more BR/EDR fixed channels are added */ if (l2cap->info_fixed_chan & BIT(BT_L2CAP_CID_BR_SMP)) { struct bt_l2cap_chan *chan; chan = bt_l2cap_br_lookup_rx_cid(l2cap->chan.chan.conn, BT_L2CAP_CID_BR_SMP); if (chan) { connect_fixed_channel(BR_CHAN(chan)); } } } static int l2cap_br_info_rsp(struct bt_l2cap_br *l2cap, u8_t ident, struct net_buf *buf) { struct bt_l2cap_info_rsp *rsp; u16_t type, result; int err = 0; if (atomic_test_bit(l2cap->chan.flags, L2CAP_FLAG_SIG_INFO_DONE)) { return 0; } if (atomic_test_and_clear_bit(l2cap->chan.flags, L2CAP_FLAG_SIG_INFO_PENDING)) { /* * Release RTX timer since got the response & there's pending * command request. */ k_delayed_work_cancel(&l2cap->chan.chan.rtx_work); } if (buf->len < sizeof(*rsp)) { BT_ERR("Too small info rsp packet size"); err = -EINVAL; goto done; } if (ident != l2cap->info_ident) { BT_WARN("Idents mismatch"); err = -EINVAL; goto done; } rsp = net_buf_pull_mem(buf, sizeof(*rsp)); result = sys_le16_to_cpu(rsp->result); if (result != BT_L2CAP_INFO_SUCCESS) { BT_WARN("Result unsuccessful"); err = -EINVAL; goto done; } type = sys_le16_to_cpu(rsp->type); switch (type) { case BT_L2CAP_INFO_FEAT_MASK: /* we should check rfcomm packet length */ if (buf->len < 4) { err = -EINVAL; break; } l2cap->info_feat_mask = net_buf_pull_le32(buf); BT_DBG("remote info mask 0x%08x", l2cap->info_feat_mask); if (!(l2cap->info_feat_mask & L2CAP_FEAT_FIXED_CHAN_MASK)) { break; } l2cap_br_get_info(l2cap, BT_L2CAP_INFO_FIXED_CHAN); return 0; case BT_L2CAP_INFO_FIXED_CHAN: /* we should check rfcomm packet length */ if (buf->len < 1) { err = -EINVAL; break; } l2cap->info_fixed_chan = net_buf_pull_u8(buf); BT_DBG("remote fixed channel mask 0x%02x", l2cap->info_fixed_chan); connect_optional_fixed_channels(l2cap); break; default: BT_WARN("type 0x%04x unsupported", type); err = -EINVAL; break; } done: atomic_set_bit(l2cap->chan.flags, L2CAP_FLAG_SIG_INFO_DONE); l2cap->info_ident = 0U; return err; } static u8_t get_fixed_channels_mask(void) { u8_t mask = 0U; /* this needs to be enhanced if AMP Test Manager support is added */ SYS_SLIST_FOR_EACH_CONTAINER(&br_fixed_channels, fchan, node) { mask |= BIT(fchan->cid); } return mask; } static int l2cap_br_info_req(struct bt_l2cap_br *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_info_req *req = (void *)buf->data; struct bt_l2cap_info_rsp *rsp; struct net_buf *rsp_buf; struct bt_l2cap_sig_hdr *hdr_info; u16_t type; if (buf->len < sizeof(*req)) { BT_ERR("Too small info req packet size"); return -EINVAL; } rsp_buf = bt_l2cap_create_pdu(&br_sig_pool, 0); type = sys_le16_to_cpu(req->type); BT_DBG("type 0x%04x", type); hdr_info = net_buf_add(rsp_buf, sizeof(*hdr_info)); hdr_info->code = BT_L2CAP_INFO_RSP; hdr_info->ident = ident; rsp = net_buf_add(rsp_buf, sizeof(*rsp)); switch (type) { case BT_L2CAP_INFO_FEAT_MASK: rsp->type = sys_cpu_to_le16(BT_L2CAP_INFO_FEAT_MASK); rsp->result = sys_cpu_to_le16(BT_L2CAP_INFO_SUCCESS); net_buf_add_le32(rsp_buf, L2CAP_FEAT_FIXED_CHAN_MASK); hdr_info->len = sys_cpu_to_le16(sizeof(*rsp) + sizeof(bt_u32_t)); break; case BT_L2CAP_INFO_FIXED_CHAN: rsp->type = sys_cpu_to_le16(BT_L2CAP_INFO_FIXED_CHAN); rsp->result = sys_cpu_to_le16(BT_L2CAP_INFO_SUCCESS); /* fixed channel mask protocol data is 8 octets wide */ (void)memset(net_buf_add(rsp_buf, 8), 0, 8); rsp->data[0] = get_fixed_channels_mask(); hdr_info->len = sys_cpu_to_le16(sizeof(*rsp) + 8); break; default: rsp->type = req->type; rsp->result = sys_cpu_to_le16(BT_L2CAP_INFO_NOTSUPP); hdr_info->len = sys_cpu_to_le16(sizeof(*rsp)); break; } bt_l2cap_send(conn, BT_L2CAP_CID_BR_SIG, rsp_buf); return 0; } void bt_l2cap_br_connected(struct bt_conn *conn) { struct bt_l2cap_fixed_chan *fchan; struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&br_fixed_channels, fchan, node) { struct bt_l2cap_br_chan *ch; if (!fchan->accept) { continue; } if (fchan->accept(conn, &chan) < 0) { continue; } ch = BR_CHAN(chan); ch->rx.cid = fchan->cid; ch->tx.cid = fchan->cid; if (!l2cap_br_chan_add(conn, chan, NULL)) { return; } /* * other fixed channels will be connected after Information * Response is received */ if (fchan->cid == BT_L2CAP_CID_BR_SIG) { struct bt_l2cap_br *sig_ch; connect_fixed_channel(ch); sig_ch = CONTAINER_OF(ch, struct bt_l2cap_br, chan); l2cap_br_get_info(sig_ch, BT_L2CAP_INFO_FEAT_MASK); } } } static struct bt_l2cap_server *l2cap_br_server_lookup_psm(u16_t psm) { struct bt_l2cap_server *server; SYS_SLIST_FOR_EACH_CONTAINER(&br_servers, server, node) { if (server->psm == psm) { return server; } } return NULL; } static void l2cap_br_conf_add_mtu(struct net_buf *buf, const u16_t mtu) { net_buf_add_u8(buf, BT_L2CAP_CONF_OPT_MTU); net_buf_add_u8(buf, sizeof(mtu)); net_buf_add_le16(buf, mtu); } static void l2cap_br_conf(struct bt_l2cap_chan *chan) { struct bt_l2cap_sig_hdr *hdr; struct bt_l2cap_conf_req *conf; struct net_buf *buf; buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_CONF_REQ; hdr->ident = l2cap_br_get_ident(); conf = net_buf_add(buf, sizeof(*conf)); (void)memset(conf, 0, sizeof(*conf)); conf->dcid = sys_cpu_to_le16(BR_CHAN(chan)->tx.cid); /* * Add MTU option if app set non default BR/EDR L2CAP MTU, * otherwise sent empty configuration data meaning default MTU * to be used. */ if (BR_CHAN(chan)->rx.mtu != L2CAP_BR_DEFAULT_MTU) { l2cap_br_conf_add_mtu(buf, BR_CHAN(chan)->rx.mtu); } hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); /* * TODO: * might be needed to start tracking number of configuration iterations * on both directions */ l2cap_br_chan_send_req(BR_CHAN(chan), buf, L2CAP_BR_CFG_TIMEOUT); } enum l2cap_br_conn_security_result { L2CAP_CONN_SECURITY_PASSED, L2CAP_CONN_SECURITY_REJECT, L2CAP_CONN_SECURITY_PENDING }; /* * Security helper against channel connection. * Returns L2CAP_CONN_SECURITY_PASSED if: * - existing security on link is applicable for requested PSM in connection, * - legacy (non SSP) devices connecting with low security requirements, * Returns L2CAP_CONN_SECURITY_PENDING if: * - channel connection process is on hold since there were valid security * conditions triggering authentication indirectly in subcall. * Returns L2CAP_CONN_SECURITY_REJECT if: * - bt_conn_set_security API returns < 0. */ static enum l2cap_br_conn_security_result l2cap_br_conn_security(struct bt_l2cap_chan *chan, const u16_t psm) { int check; /* For SDP PSM there's no need to change existing security on link */ if (chan->required_sec_level == BT_SECURITY_L0) { return L2CAP_CONN_SECURITY_PASSED; } /* * No link key needed for legacy devices (pre 2.1) and when low security * level is required. */ if (chan->required_sec_level == BT_SECURITY_L1 && !BT_FEAT_HOST_SSP(chan->conn->br.features)) { return L2CAP_CONN_SECURITY_PASSED; } switch (chan->required_sec_level) { case BT_SECURITY_L4: case BT_SECURITY_L3: case BT_SECURITY_L2: break; default: /* * For non SDP PSM connections GAP's Security Mode 4 requires at * least unauthenticated link key and enabled encryption if * remote supports SSP before any L2CAP CoC traffic. So preset * local to MEDIUM security to trigger it if needed. */ if (BT_FEAT_HOST_SSP(chan->conn->br.features)) { chan->required_sec_level = BT_SECURITY_L2; } break; } check = bt_conn_set_security(chan->conn, chan->required_sec_level); /* * Check case when on existing connection security level already covers * channel (service) security requirements against link security and * bt_conn_set_security API returns 0 what implies also there was no * need to trigger authentication. */ if (check == 0 && chan->conn->sec_level >= chan->required_sec_level) { return L2CAP_CONN_SECURITY_PASSED; } /* * If 'check' still holds 0, it means local host just sent HCI * authentication command to start procedure to increase link security * since service/profile requires that. */ if (check == 0) { return L2CAP_CONN_SECURITY_PENDING; }; /* * For any other values in 'check' it means there was internal * validation condition forbidding to start authentication at this * moment. */ return L2CAP_CONN_SECURITY_REJECT; } static void l2cap_br_send_conn_rsp(struct bt_conn *conn, u16_t scid, u16_t dcid, u8_t ident, u16_t result) { struct net_buf *buf; struct bt_l2cap_conn_rsp *rsp; struct bt_l2cap_sig_hdr *hdr; buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_CONN_RSP; hdr->ident = ident; hdr->len = sys_cpu_to_le16(sizeof(*rsp)); rsp = net_buf_add(buf, sizeof(*rsp)); rsp->dcid = sys_cpu_to_le16(dcid); rsp->scid = sys_cpu_to_le16(scid); rsp->result = sys_cpu_to_le16(result); if (result == BT_L2CAP_BR_PENDING) { rsp->status = sys_cpu_to_le16(BT_L2CAP_CS_AUTHEN_PEND); } else { rsp->status = sys_cpu_to_le16(BT_L2CAP_CS_NO_INFO); } bt_l2cap_send(conn, BT_L2CAP_CID_BR_SIG, buf); } static int l2cap_br_conn_req_reply(struct bt_l2cap_chan *chan, u16_t result) { /* Send response to connection request only when in acceptor role */ if (!atomic_test_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_ACCEPTOR)) { return -ESRCH; } l2cap_br_send_conn_rsp(chan->conn, BR_CHAN(chan)->tx.cid, BR_CHAN(chan)->rx.cid, chan->ident, result); chan->ident = 0U; return 0; } static void l2cap_br_conn_req(struct bt_l2cap_br *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_server *server; struct bt_l2cap_conn_req *req = (void *)buf->data; u16_t psm, scid, result; if (buf->len < sizeof(*req)) { BT_ERR("Too small L2CAP conn req packet size"); return; } psm = sys_le16_to_cpu(req->psm); scid = sys_le16_to_cpu(req->scid); BT_DBG("psm 0x%02x scid 0x%04x", psm, scid); /* Check if there is a server registered */ server = l2cap_br_server_lookup_psm(psm); if (!server) { result = BT_L2CAP_BR_ERR_PSM_NOT_SUPP; goto no_chan; } /* * Report security violation for non SDP channel without encryption when * remote supports SSP. */ if (server->sec_level != BT_SECURITY_L0 && BT_FEAT_HOST_SSP(conn->br.features) && !conn->encrypt) { result = BT_L2CAP_BR_ERR_SEC_BLOCK; goto no_chan; } if (!L2CAP_BR_CID_IS_DYN(scid)) { result = BT_L2CAP_BR_ERR_INVALID_SCID; goto no_chan; } chan = bt_l2cap_br_lookup_tx_cid(conn, scid); if (chan) { /* * we have a chan here but this is due to SCID being already in * use so it is not channel we are suppose to pass to * l2cap_br_conn_req_reply as wrong DCID would be used */ result = BT_L2CAP_BR_ERR_SCID_IN_USE; goto no_chan; } /* * Request server to accept the new connection and allocate the * channel. If no free channels available for PSM server reply with * proper result and quit since chan pointer is uninitialized then. */ if (server->accept(conn, &chan) < 0) { result = BT_L2CAP_BR_ERR_NO_RESOURCES; goto no_chan; } chan->required_sec_level = server->sec_level; l2cap_br_chan_add(conn, chan, l2cap_br_chan_destroy); BR_CHAN(chan)->tx.cid = scid; chan->ident = ident; bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT); atomic_set_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_ACCEPTOR); /* Disable fragmentation of l2cap rx pdu */ BR_CHAN(chan)->rx.mtu = MIN(BR_CHAN(chan)->rx.mtu, L2CAP_BR_MAX_MTU); switch (l2cap_br_conn_security(chan, psm)) { case L2CAP_CONN_SECURITY_PENDING: result = BT_L2CAP_BR_PENDING; /* TODO: auth timeout */ break; case L2CAP_CONN_SECURITY_PASSED: result = BT_L2CAP_BR_SUCCESS; break; case L2CAP_CONN_SECURITY_REJECT: default: result = BT_L2CAP_BR_ERR_SEC_BLOCK; break; } /* Reply on connection request as acceptor */ l2cap_br_conn_req_reply(chan, result); if (result != BT_L2CAP_BR_SUCCESS) { /* Disconnect link when security rules were violated */ if (result == BT_L2CAP_BR_ERR_SEC_BLOCK) { bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); } return; } bt_l2cap_chan_set_state(chan, BT_L2CAP_CONFIG); l2cap_br_conf(chan); return; no_chan: l2cap_br_send_conn_rsp(conn, scid, 0, ident, result); } static void l2cap_br_conf_rsp(struct bt_l2cap_br *l2cap, u8_t ident, u16_t len, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_conf_rsp *rsp = (void *)buf->data; u16_t flags, scid, result, opt_len; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small L2CAP conf rsp packet size"); return; } flags = sys_le16_to_cpu(rsp->flags); scid = sys_le16_to_cpu(rsp->scid); result = sys_le16_to_cpu(rsp->result); opt_len = len - sizeof(*rsp); BT_DBG("scid 0x%04x flags 0x%02x result 0x%02x len %u", scid, flags, result, opt_len); chan = bt_l2cap_br_lookup_rx_cid(conn, scid); if (!chan) { BT_ERR("channel mismatch!"); return; } /* Release RTX work since got the response */ k_delayed_work_cancel(&chan->rtx_work); /* * TODO: handle other results than success and parse response data if * available */ switch (result) { case BT_L2CAP_CONF_SUCCESS: atomic_set_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_LCONF_DONE); if (chan->state == BT_L2CAP_CONFIG && atomic_test_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_RCONF_DONE)) { BT_DBG("scid 0x%04x rx MTU %u dcid 0x%04x tx MTU %u", BR_CHAN(chan)->rx.cid, BR_CHAN(chan)->rx.mtu, BR_CHAN(chan)->tx.cid, BR_CHAN(chan)->tx.mtu); bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED); if (chan->ops && chan->ops->connected) { chan->ops->connected(chan); } } break; default: /* currently disconnect channel on non success result */ bt_l2cap_chan_disconnect(chan); break; } } int bt_l2cap_br_server_register(struct bt_l2cap_server *server) { if (server->psm < L2CAP_BR_PSM_START || !server->accept) { return -EINVAL; } /* PSM must be odd and lsb of upper byte must be 0 */ if ((server->psm & 0x0101) != 0x0001) { return -EINVAL; } if (server->sec_level > BT_SECURITY_L4) { return -EINVAL; } else if (server->sec_level == BT_SECURITY_L0 && server->psm != L2CAP_BR_PSM_SDP) { server->sec_level = BT_SECURITY_L1; } /* Check if given PSM is already in use */ if (l2cap_br_server_lookup_psm(server->psm)) { BT_DBG("PSM already registered"); return -EADDRINUSE; } BT_DBG("PSM 0x%04x", server->psm); sys_slist_append(&br_servers, &server->node); return 0; } static void l2cap_br_send_reject(struct bt_conn *conn, u8_t ident, u16_t reason, void *data, u8_t data_len) { struct bt_l2cap_cmd_reject *rej; struct bt_l2cap_sig_hdr *hdr; struct net_buf *buf; buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_CMD_REJECT; hdr->ident = ident; hdr->len = sys_cpu_to_le16(sizeof(*rej) + data_len); rej = net_buf_add(buf, sizeof(*rej)); rej->reason = sys_cpu_to_le16(reason); /* * optional data if available must be already in little-endian format * made by caller.and be compliant with Core 4.2 [Vol 3, Part A, 4.1, * table 4.4] */ if (data) { net_buf_add_mem(buf, data, data_len); } bt_l2cap_send(conn, BT_L2CAP_CID_BR_SIG, buf); } static u16_t l2cap_br_conf_opt_mtu(struct bt_l2cap_chan *chan, struct net_buf *buf, size_t len) { u16_t mtu, result = BT_L2CAP_CONF_SUCCESS; /* Core 4.2 [Vol 3, Part A, 5.1] MTU payload length */ if (len != 2) { BT_ERR("tx MTU length %zu invalid", len); result = BT_L2CAP_CONF_REJECT; goto done; } /* pulling MTU value moves buf data to next option item */ mtu = net_buf_pull_le16(buf); if (mtu < L2CAP_BR_MIN_MTU) { result = BT_L2CAP_CONF_UNACCEPT; BR_CHAN(chan)->tx.mtu = L2CAP_BR_MIN_MTU; BT_DBG("tx MTU %u invalid", mtu); goto done; } BR_CHAN(chan)->tx.mtu = mtu; BT_DBG("tx MTU %u", mtu); done: return result; } static void l2cap_br_conf_req(struct bt_l2cap_br *l2cap, u8_t ident, u16_t len, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_conf_req *req; struct bt_l2cap_sig_hdr *hdr; struct bt_l2cap_conf_rsp *rsp; struct bt_l2cap_conf_opt *opt; u16_t flags, dcid, opt_len, hint, result = BT_L2CAP_CONF_SUCCESS; if (buf->len < sizeof(*req)) { BT_ERR("Too small L2CAP conf req packet size"); return; } req = net_buf_pull_mem(buf, sizeof(*req)); flags = sys_le16_to_cpu(req->flags); dcid = sys_le16_to_cpu(req->dcid); opt_len = len - sizeof(*req); BT_DBG("dcid 0x%04x flags 0x%02x len %u", dcid, flags, opt_len); chan = bt_l2cap_br_lookup_rx_cid(conn, dcid); if (!chan) { BT_ERR("rx channel mismatch!"); struct bt_l2cap_cmd_reject_cid_data data = {.scid = req->dcid, .dcid = 0, }; l2cap_br_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, sizeof(data)); return; } if (!opt_len) { BT_DBG("tx default MTU %u", L2CAP_BR_DEFAULT_MTU); BR_CHAN(chan)->tx.mtu = L2CAP_BR_DEFAULT_MTU; goto send_rsp; } while (buf->len >= sizeof(*opt)) { opt = net_buf_pull_mem(buf, sizeof(*opt)); /* make sure opt object can get safe dereference in iteration */ if (buf->len < opt->len) { BT_ERR("Received too short option data"); result = BT_L2CAP_CONF_REJECT; break; } hint = opt->type & BT_L2CAP_CONF_HINT; switch (opt->type & BT_L2CAP_CONF_MASK) { case BT_L2CAP_CONF_OPT_MTU: /* getting MTU modifies buf internals */ result = l2cap_br_conf_opt_mtu(chan, buf, opt->len); /* * MTU is done. For now bailout the loop but later on * there can be a need to continue checking next options * that are after MTU value and then goto is not proper * way out here. */ goto send_rsp; default: if (!hint) { BT_DBG("option %u not handled", opt->type); goto send_rsp; } /* Update buffer to point at next option */ net_buf_pull(buf, opt->len); break; } } send_rsp: buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_CONF_RSP; hdr->ident = ident; rsp = net_buf_add(buf, sizeof(*rsp)); (void)memset(rsp, 0, sizeof(*rsp)); rsp->result = sys_cpu_to_le16(result); rsp->scid = sys_cpu_to_le16(BR_CHAN(chan)->tx.cid); /* * TODO: If options other than MTU bacame meaningful then processing * the options chain need to be modified and taken into account when * sending back to peer. */ if (result == BT_L2CAP_CONF_UNACCEPT) { l2cap_br_conf_add_mtu(buf, BR_CHAN(chan)->tx.mtu); } hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); bt_l2cap_send(conn, BT_L2CAP_CID_BR_SIG, buf); if (result != BT_L2CAP_CONF_SUCCESS) { return; } atomic_set_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_RCONF_DONE); if (atomic_test_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_LCONF_DONE) && chan->state == BT_L2CAP_CONFIG) { BT_DBG("scid 0x%04x rx MTU %u dcid 0x%04x tx MTU %u", BR_CHAN(chan)->rx.cid, BR_CHAN(chan)->rx.mtu, BR_CHAN(chan)->tx.cid, BR_CHAN(chan)->tx.mtu); bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED); if (chan->ops && chan->ops->connected) { chan->ops->connected(chan); } } } static struct bt_l2cap_br_chan *l2cap_br_remove_tx_cid(struct bt_conn *conn, u16_t cid) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; /* Protect fixed channels against accidental removal */ if (!L2CAP_BR_CID_IS_DYN(cid)) { return NULL; } SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BR_CHAN(chan)->tx.cid == cid) { sys_slist_remove(&conn->channels, prev, &chan->node); return BR_CHAN(chan); } prev = &chan->node; } return NULL; } static void l2cap_br_disconn_req(struct bt_l2cap_br *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_br_chan *chan; struct bt_l2cap_disconn_req *req = (void *)buf->data; struct bt_l2cap_disconn_rsp *rsp; struct bt_l2cap_sig_hdr *hdr; u16_t scid, dcid; if (buf->len < sizeof(*req)) { BT_ERR("Too small disconn req packet size"); return; } dcid = sys_le16_to_cpu(req->dcid); scid = sys_le16_to_cpu(req->scid); BT_DBG("scid 0x%04x dcid 0x%04x", dcid, scid); chan = l2cap_br_remove_tx_cid(conn, scid); if (!chan) { struct bt_l2cap_cmd_reject_cid_data data; data.scid = req->scid; data.dcid = req->dcid; l2cap_br_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, sizeof(data)); return; } buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_DISCONN_RSP; hdr->ident = ident; hdr->len = sys_cpu_to_le16(sizeof(*rsp)); rsp = net_buf_add(buf, sizeof(*rsp)); rsp->dcid = sys_cpu_to_le16(chan->rx.cid); rsp->scid = sys_cpu_to_le16(chan->tx.cid); bt_l2cap_chan_del(&chan->chan); bt_l2cap_send(conn, BT_L2CAP_CID_BR_SIG, buf); } static void l2cap_br_connected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BR_CHAN(chan), BR_CHAN(chan)->rx.cid); } static void l2cap_br_disconnected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BR_CHAN(chan), BR_CHAN(chan)->rx.cid); if (atomic_test_and_clear_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_SIG_INFO_PENDING)) { /* Cancel RTX work on signal channel */ k_delayed_work_cancel(&chan->rtx_work); } } int bt_l2cap_br_chan_disconnect(struct bt_l2cap_chan *chan) { struct bt_conn *conn = chan->conn; struct net_buf *buf; struct bt_l2cap_disconn_req *req; struct bt_l2cap_sig_hdr *hdr; struct bt_l2cap_br_chan *ch; if (!conn) { return -ENOTCONN; } if (chan->state == BT_L2CAP_DISCONNECT) { return -EALREADY; } ch = BR_CHAN(chan); BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, ch->tx.cid); buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_DISCONN_REQ; hdr->ident = l2cap_br_get_ident(); hdr->len = sys_cpu_to_le16(sizeof(*req)); req = net_buf_add(buf, sizeof(*req)); req->dcid = sys_cpu_to_le16(ch->tx.cid); req->scid = sys_cpu_to_le16(ch->rx.cid); l2cap_br_chan_send_req(ch, buf, L2CAP_BR_DISCONN_TIMEOUT); bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT); return 0; } static void l2cap_br_disconn_rsp(struct bt_l2cap_br *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_br_chan *chan; struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data; u16_t dcid, scid; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small disconn rsp packet size"); return; } dcid = sys_le16_to_cpu(rsp->dcid); scid = sys_le16_to_cpu(rsp->scid); BT_DBG("dcid 0x%04x scid 0x%04x", dcid, scid); chan = l2cap_br_remove_tx_cid(conn, dcid); if (!chan) { BT_WARN("No dcid 0x%04x channel found", dcid); return; } bt_l2cap_chan_del(&chan->chan); } int bt_l2cap_br_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm) { struct net_buf *buf; struct bt_l2cap_sig_hdr *hdr; struct bt_l2cap_conn_req *req; if (!psm) { return -EINVAL; } if (chan->psm) { return -EEXIST; } /* PSM must be odd and lsb of upper byte must be 0 */ if ((psm & 0x0101) != 0x0001) { return -EINVAL; } if (chan->required_sec_level > BT_SECURITY_L4) { return -EINVAL; } else if (chan->required_sec_level == BT_SECURITY_L0 && psm != L2CAP_BR_PSM_SDP) { chan->required_sec_level = BT_SECURITY_L1; } switch (chan->state) { case BT_L2CAP_CONNECTED: /* Already connected */ return -EISCONN; case BT_L2CAP_DISCONNECTED: /* Can connect */ break; case BT_L2CAP_CONFIG: case BT_L2CAP_DISCONNECT: default: /* Bad context */ return -EBUSY; } if (!l2cap_br_chan_add(conn, chan, l2cap_br_chan_destroy)) { return -ENOMEM; } chan->psm = psm; bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT); atomic_set_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_PENDING); switch (l2cap_br_conn_security(chan, psm)) { case L2CAP_CONN_SECURITY_PENDING: /* * Authentication was triggered, wait with sending request on * connection security changed callback context. */ return 0; case L2CAP_CONN_SECURITY_PASSED: break; case L2CAP_CONN_SECURITY_REJECT: default: l2cap_br_chan_cleanup(chan); return -EIO; } buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_CONN_REQ; hdr->ident = l2cap_br_get_ident(); hdr->len = sys_cpu_to_le16(sizeof(*req)); req = net_buf_add(buf, sizeof(*req)); req->psm = sys_cpu_to_le16(psm); req->scid = sys_cpu_to_le16(BR_CHAN(chan)->rx.cid); l2cap_br_chan_send_req(BR_CHAN(chan), buf, L2CAP_BR_CONN_TIMEOUT); return 0; } static void l2cap_br_conn_rsp(struct bt_l2cap_br *l2cap, u8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_conn_rsp *rsp = (void *)buf->data; u16_t dcid, scid, result, status; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small L2CAP conn rsp packet size"); return; } dcid = sys_le16_to_cpu(rsp->dcid); scid = sys_le16_to_cpu(rsp->scid); result = sys_le16_to_cpu(rsp->result); status = sys_le16_to_cpu(rsp->status); BT_DBG("dcid 0x%04x scid 0x%04x result %u status %u", dcid, scid, result, status); chan = bt_l2cap_br_lookup_rx_cid(conn, scid); if (!chan) { BT_ERR("No scid 0x%04x channel found", scid); return; } /* Release RTX work since got the response */ k_delayed_work_cancel(&chan->rtx_work); if (chan->state != BT_L2CAP_CONNECT) { BT_DBG("Invalid channel %p state %s", chan, bt_l2cap_chan_state_str(chan->state)); return; } switch (result) { case BT_L2CAP_BR_SUCCESS: chan->ident = 0U; BR_CHAN(chan)->tx.cid = dcid; l2cap_br_conf(chan); bt_l2cap_chan_set_state(chan, BT_L2CAP_CONFIG); atomic_clear_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_PENDING); break; case BT_L2CAP_BR_PENDING: k_delayed_work_submit(&chan->rtx_work, L2CAP_BR_CONN_TIMEOUT); break; default: l2cap_br_chan_cleanup(chan); break; } } int bt_l2cap_br_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_br_chan *ch = BR_CHAN(chan); if (buf->len > ch->tx.mtu) { return -EMSGSIZE; } bt_l2cap_send(ch->chan.conn, ch->tx.cid, buf); return buf->len; } static int l2cap_br_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_br *l2cap = CONTAINER_OF(chan, struct bt_l2cap_br, chan); struct bt_l2cap_sig_hdr *hdr; u16_t len; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small L2CAP signaling PDU"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); len = sys_le16_to_cpu(hdr->len); BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, hdr->ident, len); if (buf->len != len) { BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len); return 0; } if (!hdr->ident) { BT_ERR("Invalid ident value in L2CAP PDU"); return 0; } switch (hdr->code) { case BT_L2CAP_INFO_RSP: l2cap_br_info_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_INFO_REQ: l2cap_br_info_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_DISCONN_REQ: l2cap_br_disconn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_CONN_REQ: l2cap_br_conn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_CONF_RSP: l2cap_br_conf_rsp(l2cap, hdr->ident, len, buf); break; case BT_L2CAP_CONF_REQ: l2cap_br_conf_req(l2cap, hdr->ident, len, buf); break; case BT_L2CAP_DISCONN_RSP: l2cap_br_disconn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_CONN_RSP: l2cap_br_conn_rsp(l2cap, hdr->ident, buf); break; default: BT_WARN("Unknown/Unsupported L2CAP PDU code 0x%02x", hdr->code); l2cap_br_send_reject(chan->conn, hdr->ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); break; } return 0; } static void l2cap_br_conn_pend(struct bt_l2cap_chan *chan, u8_t status) { struct net_buf *buf; struct bt_l2cap_sig_hdr *hdr; struct bt_l2cap_conn_req *req; if (chan->state != BT_L2CAP_CONNECT) { return; } BT_DBG("chan %p status 0x%02x encr 0x%02x", chan, status, chan->conn->encrypt); if (status) { /* * Security procedure status is non-zero so respond with * security violation only as channel acceptor. */ l2cap_br_conn_req_reply(chan, BT_L2CAP_BR_ERR_SEC_BLOCK); /* Release channel allocated to outgoing connection request */ if (atomic_test_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_PENDING)) { l2cap_br_chan_cleanup(chan); } return; } if (!chan->conn->encrypt) { return; } /* * For incoming connection state send confirming outstanding * response and initiate configuration request. */ if (l2cap_br_conn_req_reply(chan, BT_L2CAP_BR_SUCCESS) == 0) { bt_l2cap_chan_set_state(chan, BT_L2CAP_CONFIG); /* * Initialize config request since remote needs to know * local MTU segmentation. */ l2cap_br_conf(chan); } else if (atomic_test_and_clear_bit(BR_CHAN(chan)->flags, L2CAP_FLAG_CONN_PENDING)) { buf = bt_l2cap_create_pdu(&br_sig_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_L2CAP_CONN_REQ; hdr->ident = l2cap_br_get_ident(); hdr->len = sys_cpu_to_le16(sizeof(*req)); req = net_buf_add(buf, sizeof(*req)); req->psm = sys_cpu_to_le16(chan->psm); req->scid = sys_cpu_to_le16(BR_CHAN(chan)->rx.cid); l2cap_br_chan_send_req(BR_CHAN(chan), buf, L2CAP_BR_CONN_TIMEOUT); } } void l2cap_br_encrypt_change(struct bt_conn *conn, u8_t hci_status) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { l2cap_br_conn_pend(chan, hci_status); if (chan->ops && chan->ops->encrypt_change) { chan->ops->encrypt_change(chan, hci_status); } } } static void check_fixed_channel(struct bt_l2cap_chan *chan) { struct bt_l2cap_br_chan *br_chan = BR_CHAN(chan); if (br_chan->rx.cid < L2CAP_BR_CID_DYN_START) { connect_fixed_channel(br_chan); } } void bt_l2cap_br_recv(struct bt_conn *conn, struct net_buf *buf) { struct bt_l2cap_hdr *hdr; struct bt_l2cap_chan *chan; u16_t cid; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small L2CAP PDU received"); net_buf_unref(buf); return; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); cid = sys_le16_to_cpu(hdr->cid); chan = bt_l2cap_br_lookup_rx_cid(conn, cid); if (!chan) { BT_WARN("Ignoring data for unknown CID 0x%04x", cid); net_buf_unref(buf); return; } /* * if data was received for fixed channel before Information * Response we connect channel here. */ check_fixed_channel(chan); chan->ops->recv(chan, buf); net_buf_unref(buf); } static int l2cap_br_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { int i; static const struct bt_l2cap_chan_ops ops = { .connected = l2cap_br_connected, .disconnected = l2cap_br_disconnected, .recv = l2cap_br_recv, }; BT_DBG("conn %p handle %u", conn, conn->handle); for (i = 0; i < ARRAY_SIZE(bt_l2cap_br_pool); i++) { struct bt_l2cap_br *l2cap = &bt_l2cap_br_pool[i]; if (l2cap->chan.chan.conn) { continue; } l2cap->chan.chan.ops = &ops; *chan = &l2cap->chan.chan; atomic_set(l2cap->chan.flags, 0); return 0; } BT_ERR("No available L2CAP context for conn %p", conn); return -ENOMEM; } void bt_l2cap_br_fixed_chan_register(struct bt_l2cap_fixed_chan *chan) { BT_DBG("CID 0x%04x", chan->cid); sys_slist_append(&br_fixed_channels, &chan->node); } void bt_l2cap_br_init(void) { static struct bt_l2cap_fixed_chan chan_br = { .cid = BT_L2CAP_CID_BR_SIG, .accept = l2cap_br_accept, }; sys_slist_init(&br_servers); NET_BUF_POOL_INIT(br_sig_pool); bt_l2cap_br_fixed_chan_register(&chan_br); if (IS_ENABLED(CONFIG_BT_RFCOMM)) { bt_rfcomm_init(); } if (IS_ENABLED(CONFIG_BT_AVDTP)) { bt_avdtp_init(); } bt_sdp_init(); if (IS_ENABLED(CONFIG_BT_A2DP)) { bt_a2dp_init(); } } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/l2cap_br.c
C
apache-2.0
39,623
/** @file * @brief Internal APIs for Bluetooth L2CAP handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bluetooth/l2cap.h> enum l2cap_conn_list_action { BT_L2CAP_CHAN_LOOKUP, BT_L2CAP_CHAN_DETACH, }; #define BT_L2CAP_CID_BR_SIG 0x0001 #define BT_L2CAP_CID_ATT 0x0004 #define BT_L2CAP_CID_LE_SIG 0x0005 #define BT_L2CAP_CID_SMP 0x0006 #define BT_L2CAP_CID_BR_SMP 0x0007 #define BT_L2CAP_PSM_RFCOMM 0x0003 struct bt_l2cap_hdr { u16_t len; u16_t cid; } __packed; struct bt_l2cap_sig_hdr { u8_t code; u8_t ident; u16_t len; } __packed; #define BT_L2CAP_REJ_NOT_UNDERSTOOD 0x0000 #define BT_L2CAP_REJ_MTU_EXCEEDED 0x0001 #define BT_L2CAP_REJ_INVALID_CID 0x0002 #define BT_L2CAP_CMD_REJECT 0x01 struct bt_l2cap_cmd_reject { u16_t reason; u8_t data[0]; } __packed; struct bt_l2cap_cmd_reject_cid_data { u16_t scid; u16_t dcid; } __packed; #define BT_L2CAP_CONN_REQ 0x02 struct bt_l2cap_conn_req { u16_t psm; u16_t scid; } __packed; /* command statuses in reposnse */ #define BT_L2CAP_CS_NO_INFO 0x0000 #define BT_L2CAP_CS_AUTHEN_PEND 0x0001 /* valid results in conn response on BR/EDR */ #define BT_L2CAP_BR_SUCCESS 0x0000 #define BT_L2CAP_BR_PENDING 0x0001 #define BT_L2CAP_BR_ERR_PSM_NOT_SUPP 0x0002 #define BT_L2CAP_BR_ERR_SEC_BLOCK 0x0003 #define BT_L2CAP_BR_ERR_NO_RESOURCES 0x0004 #define BT_L2CAP_BR_ERR_INVALID_SCID 0x0006 #define BT_L2CAP_BR_ERR_SCID_IN_USE 0x0007 #define BT_L2CAP_CONN_RSP 0x03 struct bt_l2cap_conn_rsp { u16_t dcid; u16_t scid; u16_t result; u16_t status; } __packed; #define BT_L2CAP_CONF_SUCCESS 0x0000 #define BT_L2CAP_CONF_UNACCEPT 0x0001 #define BT_L2CAP_CONF_REJECT 0x0002 #define BT_L2CAP_CONF_REQ 0x04 struct bt_l2cap_conf_req { u16_t dcid; u16_t flags; u8_t data[0]; } __packed; #define BT_L2CAP_CONF_RSP 0x05 struct bt_l2cap_conf_rsp { u16_t scid; u16_t flags; u16_t result; u8_t data[0]; } __packed; /* Option type used by MTU config request data */ #define BT_L2CAP_CONF_OPT_MTU 0x01 /* Options bits selecting most significant bit (hint) in type field */ #define BT_L2CAP_CONF_HINT 0x80 #define BT_L2CAP_CONF_MASK 0x7f struct bt_l2cap_conf_opt { u8_t type; u8_t len; u8_t data[0]; } __packed; #define BT_L2CAP_DISCONN_REQ 0x06 struct bt_l2cap_disconn_req { u16_t dcid; u16_t scid; } __packed; #define BT_L2CAP_DISCONN_RSP 0x07 struct bt_l2cap_disconn_rsp { u16_t dcid; u16_t scid; } __packed; #define BT_L2CAP_INFO_FEAT_MASK 0x0002 #define BT_L2CAP_INFO_FIXED_CHAN 0x0003 #define BT_L2CAP_INFO_REQ 0x0a struct bt_l2cap_info_req { u16_t type; } __packed; /* info result */ #define BT_L2CAP_INFO_SUCCESS 0x0000 #define BT_L2CAP_INFO_NOTSUPP 0x0001 #define BT_L2CAP_INFO_RSP 0x0b struct bt_l2cap_info_rsp { u16_t type; u16_t result; u8_t data[0]; } __packed; #define BT_L2CAP_CONN_PARAM_REQ 0x12 struct bt_l2cap_conn_param_req { u16_t min_interval; u16_t max_interval; u16_t latency; u16_t timeout; } __packed; #define BT_L2CAP_CONN_PARAM_ACCEPTED 0x0000 #define BT_L2CAP_CONN_PARAM_REJECTED 0x0001 #define BT_L2CAP_CONN_PARAM_RSP 0x13 struct bt_l2cap_conn_param_rsp { u16_t result; } __packed; #define BT_L2CAP_LE_CONN_REQ 0x14 struct bt_l2cap_le_conn_req { u16_t psm; u16_t scid; u16_t mtu; u16_t mps; u16_t credits; } __packed; /* valid results in conn response on LE */ #define BT_L2CAP_LE_SUCCESS 0x0000 #define BT_L2CAP_LE_ERR_PSM_NOT_SUPP 0x0002 #define BT_L2CAP_LE_ERR_NO_RESOURCES 0x0004 #define BT_L2CAP_LE_ERR_AUTHENTICATION 0x0005 #define BT_L2CAP_LE_ERR_AUTHORIZATION 0x0006 #define BT_L2CAP_LE_ERR_KEY_SIZE 0x0007 #define BT_L2CAP_LE_ERR_ENCRYPTION 0x0008 #define BT_L2CAP_LE_ERR_INVALID_SCID 0x0009 #define BT_L2CAP_LE_ERR_SCID_IN_USE 0x000A #define BT_L2CAP_LE_ERR_UNACCEPT_PARAMS 0x000B #define BT_L2CAP_LE_ERR_INVALID_PARAMS 0x000C #define BT_L2CAP_LE_CONN_RSP 0x15 struct bt_l2cap_le_conn_rsp { u16_t dcid; u16_t mtu; u16_t mps; u16_t credits; u16_t result; } __packed; #define BT_L2CAP_LE_CREDITS 0x16 struct bt_l2cap_le_credits { u16_t cid; u16_t credits; } __packed; #define BT_L2CAP_ECRED_CONN_REQ 0x17 struct bt_l2cap_ecred_conn_req { u16_t psm; u16_t mtu; u16_t mps; u16_t credits; u16_t scid[0]; } __packed; #define BT_L2CAP_ECRED_CONN_RSP 0x18 struct bt_l2cap_ecred_conn_rsp { u16_t mtu; u16_t mps; u16_t credits; u16_t result; u16_t dcid[0]; } __packed; #define BT_L2CAP_ECRED_RECONF_REQ 0x19 struct bt_l2cap_ecred_reconf_req { u16_t mtu; u16_t mps; u16_t scid[0]; } __packed; #define BT_L2CAP_RECONF_SUCCESS 0x0000 #define BT_L2CAP_RECONF_INVALID_MTU 0x0001 #define BT_L2CAP_RECONF_INVALID_MPS 0x0002 #define BT_L2CAP_ECRED_RECONF_RSP 0x1a struct bt_l2cap_ecred_reconf_rsp { u16_t result; } __packed; #define BT_L2CAP_SDU_HDR_LEN 2 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) #define BT_L2CAP_RX_MTU CONFIG_BT_L2CAP_RX_MTU #else #define BT_L2CAP_RX_MTU (CONFIG_BT_RX_BUF_LEN - \ BT_HCI_ACL_HDR_SIZE - BT_L2CAP_HDR_SIZE) #endif struct bt_l2cap_fixed_chan { u16_t cid; int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); bt_l2cap_chan_destroy_t destroy; sys_snode_t node; }; /* Register a fixed L2CAP channel for L2CAP */ void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan); #define BT_L2CAP_CHANNEL_DEFINE(_name, _cid, _accept, _destroy) \ static struct bt_l2cap_fixed_chan _name = { \ .cid = _cid, \ .accept = _accept, \ .destroy = _destroy, \ } /* Need a name different than bt_l2cap_fixed_chan for a different section */ struct bt_l2cap_br_fixed_chan { u16_t cid; int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); sys_snode_t node; }; #define BT_L2CAP_BR_CHANNEL_DEFINE(_name, _cid, _accept) \ static struct bt_l2cap_br_fixed_chan _name = { \ .cid = _cid, \ .accept = _accept, \ } /* Notify L2CAP channels of a new connection */ void bt_l2cap_connected(struct bt_conn *conn); /* Notify L2CAP channels of a disconnect event */ void bt_l2cap_disconnected(struct bt_conn *conn); /* Add channel to the connection */ void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy); /* Remove channel from the connection */ void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *chan); /* Delete channel */ void bt_l2cap_chan_del(struct bt_l2cap_chan *chan); const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state); #if defined(CONFIG_BT_DEBUG_L2CAP) void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state, const char *func, int line); #define bt_l2cap_chan_set_state(_chan, _state) \ bt_l2cap_chan_set_state_debug(_chan, _state, __func__, __LINE__) #else void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state); #endif /* CONFIG_BT_DEBUG_L2CAP */ /* * Notify L2CAP channels of a change in encryption state passing additionally * HCI status of performed security procedure. */ void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status); /* Prepare an L2CAP PDU to be sent over a connection */ struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout); #define bt_l2cap_create_pdu(_pool, _reserve) \ bt_l2cap_create_pdu_timeout(_pool, _reserve, K_FOREVER) /* Prepare a L2CAP Response PDU to be sent over a connection */ struct net_buf *bt_l2cap_create_rsp(struct net_buf *buf, size_t reserve); /* Send L2CAP PDU over a connection * * Buffer ownership is transferred to stack so either in case of success * or error the buffer will be unref internally. * * Calling this from RX thread is assumed to never fail so the return can be * ignored. */ int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data); static inline void bt_l2cap_send(struct bt_conn *conn, u16_t cid, struct net_buf *buf) { bt_l2cap_send_cb(conn, cid, buf, NULL, NULL); } /* Receive a new L2CAP PDU from a connection */ void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf); /* Perform connection parameter update request */ int bt_l2cap_update_conn_param(struct bt_conn *conn, const struct bt_le_conn_param *param); /* Initialize L2CAP and supported channels */ void bt_l2cap_init(void); /* Lookup channel by Transmission CID */ struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, u16_t cid); /* Lookup channel by Receiver CID */ struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, u16_t cid); /* Initialize BR/EDR L2CAP signal layer */ void bt_l2cap_br_init(void); /* Register fixed channel */ void bt_l2cap_br_fixed_chan_register(struct bt_l2cap_fixed_chan *chan); /* Notify BR/EDR L2CAP channels about established new ACL connection */ void bt_l2cap_br_connected(struct bt_conn *conn); /* Lookup BR/EDR L2CAP channel by Receiver CID */ struct bt_l2cap_chan *bt_l2cap_br_lookup_rx_cid(struct bt_conn *conn, u16_t cid); /* Disconnects dynamic channel */ int bt_l2cap_br_chan_disconnect(struct bt_l2cap_chan *chan); /* Make connection to peer psm server */ int bt_l2cap_br_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm); /* Send packet data to connected peer */ int bt_l2cap_br_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf); /* * Handle security level changed on link passing HCI status of performed * security procedure. */ void l2cap_br_encrypt_change(struct bt_conn *conn, u8_t hci_status); /* Handle received data */ void bt_l2cap_br_recv(struct bt_conn *conn, struct net_buf *buf);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/l2cap_internal.h
C
apache-2.0
10,265
/** @file * @brief Custom logging over UART */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_types/types.h> #include <stdbool.h> #if defined(CONFIG_BT_DEBUG_MONITOR) #include <ble_os.h> #include <bt_device.h> #include <init.h> #include <drivers/console/uart_pipe.h> #include <misc/byteorder.h> #include <misc/printk.h> #include <uart.h> #include <logging/log_backend.h> #include <logging/log_output.h> #include <logging/log_ctrl.h> #include <logging/log.h> #include <bluetooth/buf.h> #include "monitor.h" /* This is the same default priority as for other console handlers, * except that we're not exporting it as a Kconfig variable until a * clear need arises. */ #define MONITOR_INIT_PRIORITY 60 /* These defines follow the values used by syslog(2) */ #define BT_LOG_ERR 3 #define BT_LOG_WARN 4 #define BT_LOG_INFO 6 #define BT_LOG_DBG 7 /* TS resolution is 1/10th of a millisecond */ #define MONITOR_TS_FREQ 10000 /* Maximum (string) length of a log message */ #define MONITOR_MSG_MAX 128 static struct device *monitor_dev; enum { BT_LOG_BUSY, BT_CONSOLE_BUSY, }; static atomic_t flags; static struct { atomic_t cmd; atomic_t evt; atomic_t acl_tx; atomic_t acl_rx; #if defined(CONFIG_BT_BREDR) atomic_t sco_tx; atomic_t sco_rx; #endif atomic_t other; } drops; extern int z_prf(int (*func)(), void *dest, const char *format, va_list vargs); static void monitor_send(const void *data, size_t len) { const u8_t *buf = data; while (len--) { uart_poll_out(monitor_dev, *buf++); } } static void encode_drops(struct bt_monitor_hdr *hdr, u8_t type, atomic_t *val) { atomic_val_t count; count = atomic_set(val, 0); if (count) { hdr->ext[hdr->hdr_len++] = type; hdr->ext[hdr->hdr_len++] = MIN(count, 255); } } static bt_u32_t monitor_ts_get(void) { return (k_cycle_get_32() / (sys_clock_hw_cycles_per_sec() / MONITOR_TS_FREQ)); } static inline void encode_hdr(struct bt_monitor_hdr *hdr, bt_u32_t timestamp, u16_t opcode, u16_t len) { struct bt_monitor_ts32 *ts; hdr->opcode = sys_cpu_to_le16(opcode); hdr->flags = 0U; ts = (void *)hdr->ext; ts->type = BT_MONITOR_TS32; ts->ts32 = timestamp; hdr->hdr_len = sizeof(*ts); encode_drops(hdr, BT_MONITOR_COMMAND_DROPS, &drops.cmd); encode_drops(hdr, BT_MONITOR_EVENT_DROPS, &drops.evt); encode_drops(hdr, BT_MONITOR_ACL_TX_DROPS, &drops.acl_tx); encode_drops(hdr, BT_MONITOR_ACL_RX_DROPS, &drops.acl_rx); #if defined(CONFIG_BT_BREDR) encode_drops(hdr, BT_MONITOR_SCO_TX_DROPS, &drops.sco_tx); encode_drops(hdr, BT_MONITOR_SCO_RX_DROPS, &drops.sco_rx); #endif encode_drops(hdr, BT_MONITOR_OTHER_DROPS, &drops.other); hdr->data_len = sys_cpu_to_le16(4 + hdr->hdr_len + len); } static void drop_add(u16_t opcode) { switch (opcode) { case BT_MONITOR_COMMAND_PKT: atomic_inc(&drops.cmd); break; case BT_MONITOR_EVENT_PKT: atomic_inc(&drops.evt); break; case BT_MONITOR_ACL_TX_PKT: atomic_inc(&drops.acl_tx); break; case BT_MONITOR_ACL_RX_PKT: atomic_inc(&drops.acl_rx); break; #if defined(CONFIG_BT_BREDR) case BT_MONITOR_SCO_TX_PKT: atomic_inc(&drops.sco_tx); break; case BT_MONITOR_SCO_RX_PKT: atomic_inc(&drops.sco_rx); break; #endif default: atomic_inc(&drops.other); break; } } void bt_monitor_send(u16_t opcode, const void *data, size_t len) { struct bt_monitor_hdr hdr; if (atomic_test_and_set_bit(&flags, BT_LOG_BUSY)) { drop_add(opcode); return; } encode_hdr(&hdr, monitor_ts_get(), opcode, len); monitor_send(&hdr, BT_MONITOR_BASE_HDR_LEN + hdr.hdr_len); monitor_send(data, len); atomic_clear_bit(&flags, BT_LOG_BUSY); } void bt_monitor_new_index(u8_t type, u8_t bus, bt_addr_t *addr, const char *name) { struct bt_monitor_new_index pkt; pkt.type = type; pkt.bus = bus; memcpy(pkt.bdaddr, addr, 6); strncpy(pkt.name, name, sizeof(pkt.name) - 1); pkt.name[sizeof(pkt.name) - 1] = '\0'; bt_monitor_send(BT_MONITOR_NEW_INDEX, &pkt, sizeof(pkt)); } #if !defined(CONFIG_UART_CONSOLE) && !defined(CONFIG_LOG_PRINTK) static int monitor_console_out(int c) { static char buf[MONITOR_MSG_MAX]; static size_t len; if (atomic_test_and_set_bit(&flags, BT_CONSOLE_BUSY)) { return c; } if (c != '\n' && len < sizeof(buf) - 1) { buf[len++] = c; atomic_clear_bit(&flags, BT_CONSOLE_BUSY); return c; } buf[len++] = '\0'; bt_monitor_send(BT_MONITOR_SYSTEM_NOTE, buf, len); len = 0; atomic_clear_bit(&flags, BT_CONSOLE_BUSY); return c; } extern void __printk_hook_install(int (*fn)(int)); extern void __stdout_hook_install(int (*fn)(int)); #endif /* !CONFIG_UART_CONSOLE */ #if defined(CONFIG_HAS_DTS) && !defined(CONFIG_BT_MONITOR_ON_DEV_NAME) #define CONFIG_BT_MONITOR_ON_DEV_NAME CONFIG_UART_CONSOLE_ON_DEV_NAME #endif #ifndef CONFIG_LOG_MINIMAL struct monitor_log_ctx { size_t total_len; char msg[MONITOR_MSG_MAX]; }; static int monitor_log_out(u8_t *data, size_t length, void *user_data) { struct monitor_log_ctx *ctx = user_data; size_t i; for (i = 0; i < length && ctx->total_len < sizeof(ctx->msg); i++) { /* With CONFIG_LOG_PRINTK the line terminator will come as * as part of messages. */ if (IS_ENABLED(CONFIG_LOG_PRINTK) && (data[i] == '\r' || data[i] == '\n')) { break; } ctx->msg[ctx->total_len++] = data[i]; } return length; } static u8_t buf; LOG_OUTPUT_DEFINE(monitor_log_output, monitor_log_out, &buf, 1); static inline u8_t monitor_priority_get(u8_t log_level) { static const u8_t prios[] = { [LOG_LEVEL_NONE] = 0, [LOG_LEVEL_ERR] = BT_LOG_ERR, [LOG_LEVEL_WRN] = BT_LOG_WARN, [LOG_LEVEL_INF] = BT_LOG_INFO, [LOG_LEVEL_DBG] = BT_LOG_DBG, }; if (log_level < ARRAY_SIZE(prios)) { return prios[log_level]; } return BT_LOG_DBG; } static void monitor_log_put(const struct log_backend *const backend, struct log_msg *msg) { struct bt_monitor_user_logging log; struct monitor_log_ctx ctx; struct bt_monitor_hdr hdr; const char id[] = "bt"; log_msg_get(msg); log_output_ctx_set(&monitor_log_output, &ctx); ctx.total_len = 0; log_output_msg_process(&monitor_log_output, msg, LOG_OUTPUT_FLAG_CRLF_NONE); if (atomic_test_and_set_bit(&flags, BT_LOG_BUSY)) { drop_add(BT_MONITOR_USER_LOGGING); log_msg_put(msg); return; } encode_hdr(&hdr, msg->hdr.timestamp, BT_MONITOR_USER_LOGGING, sizeof(log) + sizeof(id) + ctx.total_len + 1); log.priority = monitor_priority_get(msg->hdr.ids.level); log.ident_len = sizeof(id); log_msg_put(msg); monitor_send(&hdr, BT_MONITOR_BASE_HDR_LEN + hdr.hdr_len); monitor_send(&log, sizeof(log)); monitor_send(id, sizeof(id)); monitor_send(ctx.msg, ctx.total_len); /* Terminate the string with null */ uart_poll_out(monitor_dev, '\0'); atomic_clear_bit(&flags, BT_LOG_BUSY); } static void monitor_log_panic(const struct log_backend *const backend) { } static void monitor_log_init(void) { log_set_timestamp_func(monitor_ts_get, MONITOR_TS_FREQ); } static const struct log_backend_api monitor_log_api = { .put = monitor_log_put, .panic = monitor_log_panic, .init = monitor_log_init, }; LOG_BACKEND_DEFINE(bt_monitor, monitor_log_api, true); #endif /* CONFIG_LOG_MINIMAL */ static int bt_monitor_init(struct device *d) { ARG_UNUSED(d); monitor_dev = device_get_binding(CONFIG_BT_MONITOR_ON_DEV_NAME); __ASSERT_NO_MSG(monitor_dev); #if defined(CONFIG_UART_INTERRUPT_DRIVEN) uart_irq_rx_disable(monitor_dev); uart_irq_tx_disable(monitor_dev); #endif #if !defined(CONFIG_UART_CONSOLE) && !defined(CONFIG_LOG_PRINTK) __printk_hook_install(monitor_console_out); __stdout_hook_install(monitor_console_out); #endif return 0; } SYS_INIT(bt_monitor_init, PRE_KERNEL_1, MONITOR_INIT_PRIORITY); #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/monitor.c
C
apache-2.0
7,756
/** @file * @brief Custom monitor protocol logging over UART */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #if defined(CONFIG_BT_DEBUG_MONITOR) #define BT_MONITOR_NEW_INDEX 0 #define BT_MONITOR_DEL_INDEX 1 #define BT_MONITOR_COMMAND_PKT 2 #define BT_MONITOR_EVENT_PKT 3 #define BT_MONITOR_ACL_TX_PKT 4 #define BT_MONITOR_ACL_RX_PKT 5 #define BT_MONITOR_SCO_TX_PKT 6 #define BT_MONITOR_SCO_RX_PKT 7 #define BT_MONITOR_OPEN_INDEX 8 #define BT_MONITOR_CLOSE_INDEX 9 #define BT_MONITOR_INDEX_INFO 10 #define BT_MONITOR_VENDOR_DIAG 11 #define BT_MONITOR_SYSTEM_NOTE 12 #define BT_MONITOR_USER_LOGGING 13 #define BT_MONITOR_NOP 255 #define BT_MONITOR_TYPE_PRIMARY 0 #define BT_MONITOR_TYPE_AMP 1 /* Extended header types */ #define BT_MONITOR_COMMAND_DROPS 1 #define BT_MONITOR_EVENT_DROPS 2 #define BT_MONITOR_ACL_RX_DROPS 3 #define BT_MONITOR_ACL_TX_DROPS 4 #define BT_MONITOR_SCO_RX_DROPS 5 #define BT_MONITOR_SCO_TX_DROPS 6 #define BT_MONITOR_OTHER_DROPS 7 #define BT_MONITOR_TS32 8 #define BT_MONITOR_BASE_HDR_LEN 6 #if defined(CONFIG_BT_BREDR) #define BT_MONITOR_EXT_HDR_MAX 19 #else #define BT_MONITOR_EXT_HDR_MAX 15 #endif struct bt_monitor_hdr { u16_t data_len; u16_t opcode; u8_t flags; u8_t hdr_len; u8_t ext[BT_MONITOR_EXT_HDR_MAX]; } __packed; struct bt_monitor_ts32 { u8_t type; bt_u32_t ts32; } __packed; struct bt_monitor_new_index { u8_t type; u8_t bus; u8_t bdaddr[6]; char name[8]; } __packed; struct bt_monitor_user_logging { u8_t priority; u8_t ident_len; } __packed; static inline u8_t bt_monitor_opcode(struct net_buf *buf) { switch (bt_buf_get_type(buf)) { case BT_BUF_CMD: return BT_MONITOR_COMMAND_PKT; case BT_BUF_EVT: return BT_MONITOR_EVENT_PKT; case BT_BUF_ACL_OUT: return BT_MONITOR_ACL_TX_PKT; case BT_BUF_ACL_IN: return BT_MONITOR_ACL_RX_PKT; default: return BT_MONITOR_NOP; } } void bt_monitor_send(u16_t opcode, const void *data, size_t len); void bt_monitor_new_index(u8_t type, u8_t bus, bt_addr_t *addr, const char *name); #else /* !CONFIG_BT_DEBUG_MONITOR */ #define bt_monitor_send(opcode, data, len) #define bt_monitor_new_index(type, bus, addr, name) #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/monitor.h
C
apache-2.0
2,232
/* rfcomm.c - RFCOMM handling */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <string.h> #include <bt_errno.h> #include <atomic.h> #include <misc/byteorder.h> #include <misc/util.h> #include <misc/stack.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/hci_driver.h> #include <bluetooth/l2cap.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_RFCOMM) #define LOG_MODULE_NAME bt_rfcomm #include "common/log.h" #include <bluetooth/rfcomm.h> #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "rfcomm_internal.h" #define RFCOMM_CHANNEL_START 0x01 #define RFCOMM_CHANNEL_END 0x1e #define RFCOMM_MIN_MTU BT_RFCOMM_SIG_MIN_MTU #define RFCOMM_DEFAULT_MTU 127 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) #define RFCOMM_MAX_CREDITS (CONFIG_BT_ACL_RX_COUNT - 1) #else #define RFCOMM_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1) #endif #define RFCOMM_CREDITS_THRESHOLD (RFCOMM_MAX_CREDITS / 2) #define RFCOMM_DEFAULT_CREDIT RFCOMM_MAX_CREDITS #define RFCOMM_CONN_TIMEOUT K_SECONDS(60) #define RFCOMM_DISC_TIMEOUT K_SECONDS(20) #define RFCOMM_IDLE_TIMEOUT K_SECONDS(2) #define DLC_RTX(_w) CONTAINER_OF(_w, struct bt_rfcomm_dlc, rtx_work) #define SESSION_RTX(_w) CONTAINER_OF(_w, struct bt_rfcomm_session, rtx_work) static struct bt_rfcomm_server *servers; /* Pool for dummy buffers to wake up the tx threads */ NET_BUF_POOL_DEFINE(dummy_pool, CONFIG_BT_MAX_CONN, 0, 0, NULL); #define RFCOMM_SESSION(_ch) CONTAINER_OF(_ch, \ struct bt_rfcomm_session, br_chan.chan) static struct bt_rfcomm_session bt_rfcomm_pool[CONFIG_BT_MAX_CONN]; /* reversed, 8-bit, poly=0x07 */ static const u8_t rfcomm_crc_table[256] = { 0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75, 0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b, 0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69, 0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67, 0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d, 0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43, 0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51, 0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f, 0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05, 0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b, 0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19, 0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17, 0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d, 0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33, 0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21, 0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f, 0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95, 0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b, 0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89, 0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87, 0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad, 0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3, 0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1, 0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf, 0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5, 0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb, 0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9, 0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7, 0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd, 0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3, 0xb4, 0x25, 0x57, 0xc6, 0xb3, 0x22, 0x50, 0xc1, 0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf }; static u8_t rfcomm_calc_fcs(u16_t len, const u8_t *data) { u8_t fcs = 0xff; while (len--) { fcs = rfcomm_crc_table[fcs ^ *data++]; } /* Ones compliment */ return (0xff - fcs); } static bool rfcomm_check_fcs(u16_t len, const u8_t *data, u8_t recvd_fcs) { u8_t fcs = 0xff; while (len--) { fcs = rfcomm_crc_table[fcs ^ *data++]; } /* Ones compliment */ fcs = rfcomm_crc_table[fcs ^ recvd_fcs]; /*0xCF is the reversed order of 11110011.*/ return (fcs == 0xcf); } static struct bt_rfcomm_dlc *rfcomm_dlcs_lookup_dlci(struct bt_rfcomm_dlc *dlcs, u8_t dlci) { for (; dlcs; dlcs = dlcs->_next) { if (dlcs->dlci == dlci) { return dlcs; } } return NULL; } static struct bt_rfcomm_dlc *rfcomm_dlcs_remove_dlci(struct bt_rfcomm_dlc *dlcs, u8_t dlci) { struct bt_rfcomm_dlc *tmp; if (!dlcs) { return NULL; } /* If first node is the one to be removed */ if (dlcs->dlci == dlci) { dlcs->session->dlcs = dlcs->_next; return dlcs; } for (tmp = dlcs, dlcs = dlcs->_next; dlcs; dlcs = dlcs->_next) { if (dlcs->dlci == dlci) { tmp->_next = dlcs->_next; return dlcs; } tmp = dlcs; } return NULL; } static struct bt_rfcomm_server *rfcomm_server_lookup_channel(u8_t channel) { struct bt_rfcomm_server *server; for (server = servers; server; server = server->_next) { if (server->channel == channel) { return server; } } return NULL; } static struct bt_rfcomm_session * rfcomm_sessions_lookup_bt_conn(struct bt_conn *conn) { int i; for (i = 0; i < ARRAY_SIZE(bt_rfcomm_pool); i++) { struct bt_rfcomm_session *session = &bt_rfcomm_pool[i]; if (session->br_chan.chan.conn == conn) { return session; } } return NULL; } int bt_rfcomm_server_register(struct bt_rfcomm_server *server) { if (server->channel < RFCOMM_CHANNEL_START || server->channel > RFCOMM_CHANNEL_END || !server->accept) { return -EINVAL; } /* Check if given channel is already in use */ if (rfcomm_server_lookup_channel(server->channel)) { BT_DBG("Channel already registered"); return -EADDRINUSE; } BT_DBG("Channel 0x%02x", server->channel); server->_next = servers; servers = server; return 0; } static void rfcomm_dlc_tx_give_credits(struct bt_rfcomm_dlc *dlc, u8_t credits) { BT_DBG("dlc %p credits %u", dlc, credits); while (credits--) { k_sem_give(&dlc->tx_credits); } BT_DBG("dlc %p updated credits %u", dlc, k_sem_count_get(&dlc->tx_credits)); } static void rfcomm_dlc_destroy(struct bt_rfcomm_dlc *dlc) { BT_DBG("dlc %p", dlc); k_delayed_work_cancel(&dlc->rtx_work); dlc->state = BT_RFCOMM_STATE_IDLE; dlc->session = NULL; if (dlc->ops && dlc->ops->disconnected) { dlc->ops->disconnected(dlc); } } static void rfcomm_dlc_disconnect(struct bt_rfcomm_dlc *dlc) { u8_t old_state = dlc->state; BT_DBG("dlc %p", dlc); if (dlc->state == BT_RFCOMM_STATE_DISCONNECTED) { return; } dlc->state = BT_RFCOMM_STATE_DISCONNECTED; switch (old_state) { case BT_RFCOMM_STATE_CONNECTED: /* Queue a dummy buffer to wake up and stop the * tx thread for states where it was running. */ net_buf_put(&dlc->tx_queue, net_buf_alloc(&dummy_pool, K_NO_WAIT)); /* There could be a writer waiting for credits so return a * dummy credit to wake it up. */ rfcomm_dlc_tx_give_credits(dlc, 1); k_sem_give(&dlc->session->fc); break; default: rfcomm_dlc_destroy(dlc); break; } } static void rfcomm_session_disconnected(struct bt_rfcomm_session *session) { struct bt_rfcomm_dlc *dlc; BT_DBG("Session %p", session); if (session->state == BT_RFCOMM_STATE_DISCONNECTED) { return; } for (dlc = session->dlcs; dlc;) { struct bt_rfcomm_dlc *next; /* prefetch since disconnected callback may cleanup */ next = dlc->_next; dlc->_next = NULL; rfcomm_dlc_disconnect(dlc); dlc = next; } session->state = BT_RFCOMM_STATE_DISCONNECTED; session->dlcs = NULL; } struct net_buf *bt_rfcomm_create_pdu(struct net_buf_pool *pool) { /* Length in RFCOMM header can be 2 bytes depending on length of user * data */ return bt_conn_create_pdu(pool, sizeof(struct bt_l2cap_hdr) + sizeof(struct bt_rfcomm_hdr) + 1); } static int rfcomm_send_sabm(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_hdr *hdr; struct net_buf *buf; u8_t cr, fcs; buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); cr = BT_RFCOMM_CMD_CR(session->role); hdr->address = BT_RFCOMM_SET_ADDR(dlci, cr); hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_SABM, BT_RFCOMM_PF_NON_UIH); hdr->length = BT_RFCOMM_SET_LEN_8(0); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_NON_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static int rfcomm_send_disc(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_hdr *hdr; struct net_buf *buf; u8_t fcs, cr; BT_DBG("dlci %d", dlci); buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); cr = BT_RFCOMM_RESP_CR(session->role); hdr->address = BT_RFCOMM_SET_ADDR(dlci, cr); hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_DISC, BT_RFCOMM_PF_NON_UIH); hdr->length = BT_RFCOMM_SET_LEN_8(0); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_NON_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static void rfcomm_session_disconnect(struct bt_rfcomm_session *session) { if (session->dlcs) { return; } session->state = BT_RFCOMM_STATE_DISCONNECTING; rfcomm_send_disc(session, 0); k_delayed_work_submit(&session->rtx_work, RFCOMM_DISC_TIMEOUT); } static struct net_buf *rfcomm_make_uih_msg(struct bt_rfcomm_session *session, u8_t cr, u8_t type, u8_t len) { struct bt_rfcomm_hdr *hdr; struct bt_rfcomm_msg_hdr *msg_hdr; struct net_buf *buf; u8_t hdr_cr; buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr_cr = BT_RFCOMM_UIH_CR(session->role); hdr->address = BT_RFCOMM_SET_ADDR(0, hdr_cr); hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_UIH, BT_RFCOMM_PF_UIH); hdr->length = BT_RFCOMM_SET_LEN_8(sizeof(*msg_hdr) + len); msg_hdr = net_buf_add(buf, sizeof(*msg_hdr)); msg_hdr->type = BT_RFCOMM_SET_MSG_TYPE(type, cr); msg_hdr->len = BT_RFCOMM_SET_LEN_8(len); return buf; } static void rfcomm_connected(struct bt_l2cap_chan *chan) { struct bt_rfcomm_session *session = RFCOMM_SESSION(chan); BT_DBG("Session %p", session); /* Need to include UIH header and FCS*/ session->mtu = MIN(session->br_chan.rx.mtu, session->br_chan.tx.mtu) - BT_RFCOMM_HDR_SIZE + BT_RFCOMM_FCS_SIZE; if (session->state == BT_RFCOMM_STATE_CONNECTING) { rfcomm_send_sabm(session, 0); } } static void rfcomm_disconnected(struct bt_l2cap_chan *chan) { struct bt_rfcomm_session *session = RFCOMM_SESSION(chan); BT_DBG("Session %p", session); k_delayed_work_cancel(&session->rtx_work); rfcomm_session_disconnected(session); session->state = BT_RFCOMM_STATE_IDLE; } static void rfcomm_dlc_rtx_timeout(struct k_work *work) { struct bt_rfcomm_dlc *dlc = DLC_RTX(work); struct bt_rfcomm_session *session = dlc->session; BT_WARN("dlc %p state %d timeout", dlc, dlc->state); rfcomm_dlcs_remove_dlci(session->dlcs, dlc->dlci); rfcomm_dlc_disconnect(dlc); rfcomm_session_disconnect(session); } static void rfcomm_dlc_init(struct bt_rfcomm_dlc *dlc, struct bt_rfcomm_session *session, u8_t dlci, bt_rfcomm_role_t role) { BT_DBG("dlc %p", dlc); dlc->dlci = dlci; dlc->session = session; dlc->rx_credit = RFCOMM_DEFAULT_CREDIT; dlc->state = BT_RFCOMM_STATE_INIT; dlc->role = role; k_delayed_work_init(&dlc->rtx_work, rfcomm_dlc_rtx_timeout); /* Start a conn timer which includes auth as well */ k_delayed_work_submit(&dlc->rtx_work, RFCOMM_CONN_TIMEOUT); dlc->_next = session->dlcs; session->dlcs = dlc; } static struct bt_rfcomm_dlc *rfcomm_dlc_accept(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_server *server; struct bt_rfcomm_dlc *dlc; u8_t channel; channel = BT_RFCOMM_GET_CHANNEL(dlci); server = rfcomm_server_lookup_channel(channel); if (!server) { BT_ERR("Server Channel not registered"); return NULL; } if (server->accept(session->br_chan.chan.conn, &dlc) < 0) { BT_DBG("Incoming connection rejected"); return NULL; } if (!BT_RFCOMM_CHECK_MTU(dlc->mtu)) { rfcomm_dlc_destroy(dlc); return NULL; } rfcomm_dlc_init(dlc, session, dlci, BT_RFCOMM_ROLE_ACCEPTOR); dlc->mtu = MIN(dlc->mtu, session->mtu); return dlc; } static int rfcomm_send_dm(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_hdr *hdr; struct net_buf *buf; u8_t fcs, cr; BT_DBG("dlci %d", dlci); buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); cr = BT_RFCOMM_RESP_CR(session->role); hdr->address = BT_RFCOMM_SET_ADDR(dlci, cr); /* For DM PF bit is not relevant, we set it 1 */ hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_DM, BT_RFCOMM_PF_NON_UIH); hdr->length = BT_RFCOMM_SET_LEN_8(0); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_NON_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static void rfcomm_check_fc(struct bt_rfcomm_dlc *dlc) { BT_DBG("%p", dlc); BT_DBG("Wait for credits or MSC FC %p", dlc); /* Wait for credits or MSC FC */ k_sem_take(&dlc->tx_credits, K_FOREVER); if (dlc->session->cfc == BT_RFCOMM_CFC_SUPPORTED) { return; } k_sem_take(&dlc->session->fc, K_FOREVER); /* Give the sems immediately so that sem will be available for all * the bufs in the queue. It will be blocked only once all the bufs * are sent (which will preempt this thread) and FCOFF / FC bit * with 1, is received. */ k_sem_give(&dlc->session->fc); k_sem_give(&dlc->tx_credits); } static void rfcomm_dlc_tx_thread(void *p1, void *p2, void *p3) { struct bt_rfcomm_dlc *dlc = p1; k_timeout_t timeout = K_FOREVER; struct net_buf *buf; BT_DBG("Started for dlc %p", dlc); while (dlc->state == BT_RFCOMM_STATE_CONNECTED || dlc->state == BT_RFCOMM_STATE_USER_DISCONNECT) { /* Get next packet for dlc */ BT_DBG("Wait for buf %p", dlc); buf = net_buf_get(&dlc->tx_queue, timeout); /* If its dummy buffer or non user disconnect then break */ if ((dlc->state != BT_RFCOMM_STATE_CONNECTED && dlc->state != BT_RFCOMM_STATE_USER_DISCONNECT) || !buf || !buf->len) { if (buf) { net_buf_unref(buf); } break; } rfcomm_check_fc(dlc); if (dlc->state != BT_RFCOMM_STATE_CONNECTED && dlc->state != BT_RFCOMM_STATE_USER_DISCONNECT) { net_buf_unref(buf); break; } if (bt_l2cap_chan_send(&dlc->session->br_chan.chan, buf) < 0) { /* This fails only if channel is disconnected */ dlc->state = BT_RFCOMM_STATE_DISCONNECTED; net_buf_unref(buf); break; } if (dlc->state == BT_RFCOMM_STATE_USER_DISCONNECT) { timeout = K_NO_WAIT; } } BT_DBG("dlc %p disconnected - cleaning up", dlc); /* Give back any allocated buffers */ while ((buf = net_buf_get(&dlc->tx_queue, K_NO_WAIT))) { net_buf_unref(buf); } if (dlc->state == BT_RFCOMM_STATE_USER_DISCONNECT) { dlc->state = BT_RFCOMM_STATE_DISCONNECTING; } if (dlc->state == BT_RFCOMM_STATE_DISCONNECTING) { rfcomm_send_disc(dlc->session, dlc->dlci); k_delayed_work_submit(&dlc->rtx_work, RFCOMM_DISC_TIMEOUT); } else { rfcomm_dlc_destroy(dlc); } BT_DBG("dlc %p exiting", dlc); } static int rfcomm_send_ua(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_hdr *hdr; struct net_buf *buf; u8_t cr, fcs; buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); cr = BT_RFCOMM_RESP_CR(session->role); hdr->address = BT_RFCOMM_SET_ADDR(dlci, cr); hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_UA, BT_RFCOMM_PF_NON_UIH); hdr->length = BT_RFCOMM_SET_LEN_8(0); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_NON_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static int rfcomm_send_msc(struct bt_rfcomm_dlc *dlc, u8_t cr, u8_t v24_signal) { struct bt_rfcomm_msc *msc; struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(dlc->session, cr, BT_RFCOMM_MSC, sizeof(*msc)); msc = net_buf_add(buf, sizeof(*msc)); /* cr bit should be always 1 in MSC */ msc->dlci = BT_RFCOMM_SET_ADDR(dlc->dlci, 1); msc->v24_signal = v24_signal; fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&dlc->session->br_chan.chan, buf); } static int rfcomm_send_rls(struct bt_rfcomm_dlc *dlc, u8_t cr, u8_t line_status) { struct bt_rfcomm_rls *rls; struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(dlc->session, cr, BT_RFCOMM_RLS, sizeof(*rls)); rls = net_buf_add(buf, sizeof(*rls)); /* cr bit should be always 1 in RLS */ rls->dlci = BT_RFCOMM_SET_ADDR(dlc->dlci, 1); rls->line_status = line_status; fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&dlc->session->br_chan.chan, buf); } static int rfcomm_send_rpn(struct bt_rfcomm_session *session, u8_t cr, struct bt_rfcomm_rpn *rpn) { struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(session, cr, BT_RFCOMM_RPN, sizeof(*rpn)); net_buf_add_mem(buf, rpn, sizeof(*rpn)); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static int rfcomm_send_test(struct bt_rfcomm_session *session, u8_t cr, u8_t *pattern, u8_t len) { struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(session, cr, BT_RFCOMM_TEST, len); net_buf_add_mem(buf, pattern, len); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static int rfcomm_send_nsc(struct bt_rfcomm_session *session, u8_t cmd_type) { struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(session, BT_RFCOMM_MSG_RESP_CR, BT_RFCOMM_NSC, sizeof(cmd_type)); net_buf_add_u8(buf, cmd_type); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static int rfcomm_send_fcon(struct bt_rfcomm_session *session, u8_t cr) { struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(session, cr, BT_RFCOMM_FCON, 0); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static int rfcomm_send_fcoff(struct bt_rfcomm_session *session, u8_t cr) { struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(session, cr, BT_RFCOMM_FCOFF, 0); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&session->br_chan.chan, buf); } static void rfcomm_dlc_connected(struct bt_rfcomm_dlc *dlc) { dlc->state = BT_RFCOMM_STATE_CONNECTED; rfcomm_send_msc(dlc, BT_RFCOMM_MSG_CMD_CR, BT_RFCOMM_DEFAULT_V24_SIG); if (dlc->session->cfc == BT_RFCOMM_CFC_UNKNOWN) { /* This means PN negotiation is not done for this session and * can happen only for 1.0b device. */ dlc->session->cfc = BT_RFCOMM_CFC_NOT_SUPPORTED; } if (dlc->session->cfc == BT_RFCOMM_CFC_NOT_SUPPORTED) { BT_DBG("CFC not supported %p", dlc); rfcomm_send_fcon(dlc->session, BT_RFCOMM_MSG_CMD_CR); /* Use tx_credits as binary sem for MSC FC */ k_sem_init(&dlc->tx_credits, 0, 1); } /* Cancel conn timer */ k_delayed_work_cancel(&dlc->rtx_work); k_fifo_init(&dlc->tx_queue); k_thread_create(&dlc->tx_thread, dlc->stack, K_THREAD_STACK_SIZEOF(dlc->stack), rfcomm_dlc_tx_thread, dlc, NULL, NULL, K_PRIO_COOP(7), 0, K_NO_WAIT); k_thread_name_set(&dlc->tx_thread, "BT DLC"); if (dlc->ops && dlc->ops->connected) { dlc->ops->connected(dlc); } } enum security_result { RFCOMM_SECURITY_PASSED, RFCOMM_SECURITY_REJECT, RFCOMM_SECURITY_PENDING }; static enum security_result rfcomm_dlc_security(struct bt_rfcomm_dlc *dlc) { struct bt_conn *conn = dlc->session->br_chan.chan.conn; BT_DBG("dlc %p", dlc); /* If current security level is greater than or equal to required * security level then return SUCCESS. * For SSP devices the current security will be atleast MEDIUM * since L2CAP is enforcing it */ if (conn->sec_level >= dlc->required_sec_level) { return RFCOMM_SECURITY_PASSED; } if (!bt_conn_set_security(conn, dlc->required_sec_level)) { /* If Security elevation is initiated or in progress */ return RFCOMM_SECURITY_PENDING; } /* Security request failed */ return RFCOMM_SECURITY_REJECT; } static void rfcomm_dlc_drop(struct bt_rfcomm_dlc *dlc) { BT_DBG("dlc %p", dlc); rfcomm_dlcs_remove_dlci(dlc->session->dlcs, dlc->dlci); rfcomm_dlc_destroy(dlc); } static int rfcomm_dlc_close(struct bt_rfcomm_dlc *dlc) { BT_DBG("dlc %p", dlc); switch (dlc->state) { case BT_RFCOMM_STATE_SECURITY_PENDING: if (dlc->role == BT_RFCOMM_ROLE_ACCEPTOR) { rfcomm_send_dm(dlc->session, dlc->dlci); } /* Fall Through */ case BT_RFCOMM_STATE_INIT: rfcomm_dlc_drop(dlc); break; case BT_RFCOMM_STATE_CONNECTING: case BT_RFCOMM_STATE_CONFIG: dlc->state = BT_RFCOMM_STATE_DISCONNECTING; rfcomm_send_disc(dlc->session, dlc->dlci); k_delayed_work_submit(&dlc->rtx_work, RFCOMM_DISC_TIMEOUT); break; case BT_RFCOMM_STATE_CONNECTED: dlc->state = BT_RFCOMM_STATE_DISCONNECTING; /* Queue a dummy buffer to wake up and stop the * tx thread. */ net_buf_put(&dlc->tx_queue, net_buf_alloc(&dummy_pool, K_NO_WAIT)); /* There could be a writer waiting for credits so return a * dummy credit to wake it up. */ rfcomm_dlc_tx_give_credits(dlc, 1); break; case BT_RFCOMM_STATE_DISCONNECTING: case BT_RFCOMM_STATE_DISCONNECTED: break; case BT_RFCOMM_STATE_IDLE: default: return -EINVAL; } return 0; } static void rfcomm_handle_sabm(struct bt_rfcomm_session *session, u8_t dlci) { if (!dlci) { if (rfcomm_send_ua(session, dlci) < 0) { return; } session->state = BT_RFCOMM_STATE_CONNECTED; } else { struct bt_rfcomm_dlc *dlc; enum security_result result; dlc = rfcomm_dlcs_lookup_dlci(session->dlcs, dlci); if (!dlc) { dlc = rfcomm_dlc_accept(session, dlci); if (!dlc) { rfcomm_send_dm(session, dlci); return; } } result = rfcomm_dlc_security(dlc); switch (result) { case RFCOMM_SECURITY_PENDING: dlc->state = BT_RFCOMM_STATE_SECURITY_PENDING; return; case RFCOMM_SECURITY_PASSED: break; case RFCOMM_SECURITY_REJECT: default: rfcomm_send_dm(session, dlci); rfcomm_dlc_drop(dlc); return; } if (rfcomm_send_ua(session, dlci) < 0) { return; } /* Cancel idle timer if any */ k_delayed_work_cancel(&session->rtx_work); rfcomm_dlc_connected(dlc); } } static int rfcomm_send_pn(struct bt_rfcomm_dlc *dlc, u8_t cr) { struct bt_rfcomm_pn *pn; struct net_buf *buf; u8_t fcs; buf = rfcomm_make_uih_msg(dlc->session, cr, BT_RFCOMM_PN, sizeof(*pn)); BT_DBG("mtu %x", dlc->mtu); pn = net_buf_add(buf, sizeof(*pn)); pn->dlci = dlc->dlci; pn->mtu = sys_cpu_to_le16(dlc->mtu); if (dlc->state == BT_RFCOMM_STATE_CONFIG && (dlc->session->cfc == BT_RFCOMM_CFC_UNKNOWN || dlc->session->cfc == BT_RFCOMM_CFC_SUPPORTED)) { pn->credits = dlc->rx_credit; if (cr) { pn->flow_ctrl = BT_RFCOMM_PN_CFC_CMD; } else { pn->flow_ctrl = BT_RFCOMM_PN_CFC_RESP; } } else { /* If PN comes in already opened dlc or cfc not supported * these should be 0 */ pn->credits = 0U; pn->flow_ctrl = 0U; } pn->max_retrans = 0U; pn->ack_timer = 0U; pn->priority = 0U; fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&dlc->session->br_chan.chan, buf); } static int rfcomm_send_credit(struct bt_rfcomm_dlc *dlc, u8_t credits) { struct bt_rfcomm_hdr *hdr; struct net_buf *buf; u8_t fcs, cr; BT_DBG("Dlc %p credits %d", dlc, credits); buf = bt_l2cap_create_pdu(NULL, 0); hdr = net_buf_add(buf, sizeof(*hdr)); cr = BT_RFCOMM_UIH_CR(dlc->session->role); hdr->address = BT_RFCOMM_SET_ADDR(dlc->dlci, cr); hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_UIH, BT_RFCOMM_PF_UIH_CREDIT); hdr->length = BT_RFCOMM_SET_LEN_8(0); net_buf_add_u8(buf, credits); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); return bt_l2cap_chan_send(&dlc->session->br_chan.chan, buf); } static int rfcomm_dlc_start(struct bt_rfcomm_dlc *dlc) { enum security_result result; BT_DBG("dlc %p", dlc); result = rfcomm_dlc_security(dlc); switch (result) { case RFCOMM_SECURITY_PASSED: dlc->mtu = MIN(dlc->mtu, dlc->session->mtu); dlc->state = BT_RFCOMM_STATE_CONFIG; rfcomm_send_pn(dlc, BT_RFCOMM_MSG_CMD_CR); break; case RFCOMM_SECURITY_PENDING: dlc->state = BT_RFCOMM_STATE_SECURITY_PENDING; break; case RFCOMM_SECURITY_REJECT: default: return -EIO; } return 0; } static void rfcomm_handle_ua(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_dlc *dlc, *next; int err; if (!dlci) { switch (session->state) { case BT_RFCOMM_STATE_CONNECTING: session->state = BT_RFCOMM_STATE_CONNECTED; for (dlc = session->dlcs; dlc; dlc = next) { next = dlc->_next; if (dlc->role == BT_RFCOMM_ROLE_INITIATOR && dlc->state == BT_RFCOMM_STATE_INIT) { if (rfcomm_dlc_start(dlc) < 0) { rfcomm_dlc_drop(dlc); } } } /* Disconnect session if there is no dlcs left */ rfcomm_session_disconnect(session); break; case BT_RFCOMM_STATE_DISCONNECTING: session->state = BT_RFCOMM_STATE_DISCONNECTED; /* Cancel disc timer */ k_delayed_work_cancel(&session->rtx_work); err = bt_l2cap_chan_disconnect(&session->br_chan.chan); if (err < 0) { session->state = BT_RFCOMM_STATE_IDLE; } break; default: break; } } else { dlc = rfcomm_dlcs_lookup_dlci(session->dlcs, dlci); if (!dlc) { return; } switch (dlc->state) { case BT_RFCOMM_STATE_CONNECTING: rfcomm_dlc_connected(dlc); break; case BT_RFCOMM_STATE_DISCONNECTING: rfcomm_dlc_drop(dlc); rfcomm_session_disconnect(session); break; default: break; } } } static void rfcomm_handle_dm(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_dlc *dlc; BT_DBG("dlci %d", dlci); dlc = rfcomm_dlcs_remove_dlci(session->dlcs, dlci); if (!dlc) { return; } rfcomm_dlc_disconnect(dlc); rfcomm_session_disconnect(session); } static void rfcomm_handle_msc(struct bt_rfcomm_session *session, struct net_buf *buf, u8_t cr) { struct bt_rfcomm_msc *msc = (void *)buf->data; struct bt_rfcomm_dlc *dlc; u8_t dlci; /* we should check rfcomm packet length */ if (buf->len < sizeof(struct bt_rfcomm_msc)) { return; } dlci = BT_RFCOMM_GET_DLCI(msc->dlci); BT_DBG("dlci %d", dlci); dlc = rfcomm_dlcs_lookup_dlci(session->dlcs, dlci); if (!dlc) { return; } if (cr == BT_RFCOMM_MSG_RESP_CR) { return; } if (dlc->session->cfc == BT_RFCOMM_CFC_NOT_SUPPORTED) { /* Only FC bit affects the flow on RFCOMM level */ if (BT_RFCOMM_GET_FC(msc->v24_signal)) { /* If FC bit is 1 the device is unable to accept frames. * Take the semaphore with timeout K_NO_WAIT so that * dlc thread will be blocked when it tries sem_take * before sending the data. K_NO_WAIT timeout will make * sure that RX thread will not be blocked while taking * the semaphore. */ k_sem_take(&dlc->tx_credits, K_NO_WAIT); } else { /* Give the sem so that it will unblock the waiting dlc * thread in sem_take(). */ k_sem_give(&dlc->tx_credits); } } rfcomm_send_msc(dlc, BT_RFCOMM_MSG_RESP_CR, msc->v24_signal); } static void rfcomm_handle_rls(struct bt_rfcomm_session *session, struct net_buf *buf, u8_t cr) { struct bt_rfcomm_rls *rls = (void *)buf->data; u8_t dlci; struct bt_rfcomm_dlc *dlc; /* we should check rfcomm packet length */ if (buf->len < sizeof(struct bt_rfcomm_rls)) { return; } dlci = BT_RFCOMM_GET_DLCI(rls->dlci); BT_DBG("dlci %d", dlci); if (!cr) { /* Ignore if its a response */ return; } dlc = rfcomm_dlcs_lookup_dlci(session->dlcs, dlci); if (!dlc) { return; } /* As per the ETSI same line status has to returned in the response */ rfcomm_send_rls(dlc, BT_RFCOMM_MSG_RESP_CR, rls->line_status); } static void rfcomm_handle_rpn(struct bt_rfcomm_session *session, struct net_buf *buf, u8_t cr) { struct bt_rfcomm_rpn default_rpn, *rpn = (void *)buf->data; u8_t dlci; u8_t data_bits, stop_bits, parity_bits; /* Exclude fcs to get number of value bytes */ u8_t value_len = buf->len - 1; /* we should check rfcomm packet length */ if (buf->len < sizeof(struct bt_rfcomm_rpn)) { return; } dlci = BT_RFCOMM_GET_DLCI(rpn->dlci); BT_DBG("dlci %d", dlci); if (!cr) { /* Ignore if its a response */ return; } if (value_len == sizeof(*rpn)) { /* Accept all the values proposed by the sender */ rpn->param_mask = sys_cpu_to_le16(BT_RFCOMM_RPN_PARAM_MASK_ALL); rfcomm_send_rpn(session, BT_RFCOMM_MSG_RESP_CR, rpn); return; } if (value_len != 1U) { return; } /* If only one value byte then current port settings has to be returned * We will send default values */ default_rpn.dlci = BT_RFCOMM_SET_ADDR(dlci, 1); default_rpn.baud_rate = BT_RFCOMM_RPN_BAUD_RATE_9600; default_rpn.flow_control = BT_RFCOMM_RPN_FLOW_NONE; default_rpn.xoff_char = BT_RFCOMM_RPN_XOFF_CHAR; default_rpn.xon_char = BT_RFCOMM_RPN_XON_CHAR; data_bits = BT_RFCOMM_RPN_DATA_BITS_8; stop_bits = BT_RFCOMM_RPN_STOP_BITS_1; parity_bits = BT_RFCOMM_RPN_PARITY_NONE; default_rpn.line_settings = BT_RFCOMM_SET_LINE_SETTINGS(data_bits, stop_bits, parity_bits); default_rpn.param_mask = sys_cpu_to_le16(BT_RFCOMM_RPN_PARAM_MASK_ALL); rfcomm_send_rpn(session, BT_RFCOMM_MSG_RESP_CR, &default_rpn); } static void rfcomm_handle_pn(struct bt_rfcomm_session *session, struct net_buf *buf, u8_t cr) { struct bt_rfcomm_pn *pn = (void *)buf->data; struct bt_rfcomm_dlc *dlc; /* we should check rfcomm packet length */ if (buf->len < sizeof(struct bt_rfcomm_pn)) { return; } dlc = rfcomm_dlcs_lookup_dlci(session->dlcs, pn->dlci); if (!dlc) { /* Ignore if it is a response */ if (!cr) { return; } if (!BT_RFCOMM_CHECK_MTU(pn->mtu)) { BT_ERR("Invalid mtu %d", pn->mtu); rfcomm_send_dm(session, pn->dlci); return; } dlc = rfcomm_dlc_accept(session, pn->dlci); if (!dlc) { rfcomm_send_dm(session, pn->dlci); return; } BT_DBG("Incoming connection accepted dlc %p", dlc); dlc->mtu = MIN(dlc->mtu, sys_le16_to_cpu(pn->mtu)); if (pn->flow_ctrl == BT_RFCOMM_PN_CFC_CMD) { if (session->cfc == BT_RFCOMM_CFC_UNKNOWN) { session->cfc = BT_RFCOMM_CFC_SUPPORTED; } k_sem_init(&dlc->tx_credits, 0, UINT32_MAX); rfcomm_dlc_tx_give_credits(dlc, pn->credits); } else { session->cfc = BT_RFCOMM_CFC_NOT_SUPPORTED; } dlc->state = BT_RFCOMM_STATE_CONFIG; rfcomm_send_pn(dlc, BT_RFCOMM_MSG_RESP_CR); /* Cancel idle timer if any */ k_delayed_work_cancel(&session->rtx_work); } else { /* If its a command */ if (cr) { if (!BT_RFCOMM_CHECK_MTU(pn->mtu)) { BT_ERR("Invalid mtu %d", pn->mtu); rfcomm_dlc_close(dlc); return; } dlc->mtu = MIN(dlc->mtu, sys_le16_to_cpu(pn->mtu)); rfcomm_send_pn(dlc, BT_RFCOMM_MSG_RESP_CR); } else { if (dlc->state != BT_RFCOMM_STATE_CONFIG) { return; } dlc->mtu = MIN(dlc->mtu, sys_le16_to_cpu(pn->mtu)); if (pn->flow_ctrl == BT_RFCOMM_PN_CFC_RESP) { if (session->cfc == BT_RFCOMM_CFC_UNKNOWN) { session->cfc = BT_RFCOMM_CFC_SUPPORTED; } k_sem_init(&dlc->tx_credits, 0, UINT32_MAX); rfcomm_dlc_tx_give_credits(dlc, pn->credits); } else { session->cfc = BT_RFCOMM_CFC_NOT_SUPPORTED; } dlc->state = BT_RFCOMM_STATE_CONNECTING; rfcomm_send_sabm(session, dlc->dlci); } } } static void rfcomm_handle_disc(struct bt_rfcomm_session *session, u8_t dlci) { struct bt_rfcomm_dlc *dlc; BT_DBG("Dlci %d", dlci); if (dlci) { dlc = rfcomm_dlcs_remove_dlci(session->dlcs, dlci); if (!dlc) { rfcomm_send_dm(session, dlci); return; } rfcomm_send_ua(session, dlci); rfcomm_dlc_disconnect(dlc); if (!session->dlcs) { /* Start a session idle timer */ k_delayed_work_submit(&dlc->session->rtx_work, RFCOMM_IDLE_TIMEOUT); } } else { /* Cancel idle timer */ k_delayed_work_cancel(&session->rtx_work); rfcomm_send_ua(session, 0); rfcomm_session_disconnected(session); } } static void rfcomm_handle_msg(struct bt_rfcomm_session *session, struct net_buf *buf) { struct bt_rfcomm_msg_hdr *hdr; u8_t msg_type, len, cr; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small RFCOMM message"); return; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); msg_type = BT_RFCOMM_GET_MSG_TYPE(hdr->type); cr = BT_RFCOMM_GET_MSG_CR(hdr->type); len = BT_RFCOMM_GET_LEN(hdr->len); BT_DBG("msg type %x cr %x", msg_type, cr); switch (msg_type) { case BT_RFCOMM_PN: rfcomm_handle_pn(session, buf, cr); break; case BT_RFCOMM_MSC: rfcomm_handle_msc(session, buf, cr); break; case BT_RFCOMM_RLS: rfcomm_handle_rls(session, buf, cr); break; case BT_RFCOMM_RPN: rfcomm_handle_rpn(session, buf, cr); break; case BT_RFCOMM_TEST: if (!cr) { break; } /* we should check rfcomm packet length */ if (!buf->len) { break; } rfcomm_send_test(session, BT_RFCOMM_MSG_RESP_CR, buf->data, buf->len - 1); break; case BT_RFCOMM_FCON: if (session->cfc == BT_RFCOMM_CFC_SUPPORTED) { BT_ERR("FCON received when CFC is supported "); return; } if (!cr) { break; } /* Give the sem so that it will unblock the waiting dlc threads * of this session in sem_take(). */ k_sem_give(&session->fc); rfcomm_send_fcon(session, BT_RFCOMM_MSG_RESP_CR); break; case BT_RFCOMM_FCOFF: if (session->cfc == BT_RFCOMM_CFC_SUPPORTED) { BT_ERR("FCOFF received when CFC is supported "); return; } if (!cr) { break; } /* Take the semaphore with timeout K_NO_WAIT so that all the * dlc threads in this session will be blocked when it tries * sem_take before sending the data. K_NO_WAIT timeout will * make sure that RX thread will not be blocked while taking * the semaphore. */ k_sem_take(&session->fc, K_NO_WAIT); rfcomm_send_fcoff(session, BT_RFCOMM_MSG_RESP_CR); break; default: BT_WARN("Unknown/Unsupported RFCOMM Msg type 0x%02x", msg_type); rfcomm_send_nsc(session, hdr->type); break; } } static void rfcomm_dlc_update_credits(struct bt_rfcomm_dlc *dlc) { u8_t credits; if (dlc->session->cfc == BT_RFCOMM_CFC_NOT_SUPPORTED) { return; } BT_DBG("dlc %p credits %u", dlc, dlc->rx_credit); /* Only give more credits if it went below the defined threshold */ if (dlc->rx_credit > RFCOMM_CREDITS_THRESHOLD) { return; } /* Restore credits */ credits = RFCOMM_MAX_CREDITS - dlc->rx_credit; dlc->rx_credit += credits; rfcomm_send_credit(dlc, credits); } static void rfcomm_handle_data(struct bt_rfcomm_session *session, struct net_buf *buf, u8_t dlci, u8_t pf) { struct bt_rfcomm_dlc *dlc; BT_DBG("dlci %d, pf %d", dlci, pf); dlc = rfcomm_dlcs_lookup_dlci(session->dlcs, dlci); if (!dlc) { BT_ERR("Data recvd in non existing DLC"); rfcomm_send_dm(session, dlci); return; } BT_DBG("dlc %p rx credit %d", dlc, dlc->rx_credit); if (dlc->state != BT_RFCOMM_STATE_CONNECTED) { return; } if (pf == BT_RFCOMM_PF_UIH_CREDIT) { rfcomm_dlc_tx_give_credits(dlc, net_buf_pull_u8(buf)); } if (buf->len > BT_RFCOMM_FCS_SIZE) { if (dlc->session->cfc == BT_RFCOMM_CFC_SUPPORTED && !dlc->rx_credit) { BT_ERR("Data recvd when rx credit is 0"); rfcomm_dlc_close(dlc); return; } /* Remove FCS */ buf->len -= BT_RFCOMM_FCS_SIZE; if (dlc->ops && dlc->ops->recv) { dlc->ops->recv(dlc, buf); } dlc->rx_credit--; rfcomm_dlc_update_credits(dlc); } } int bt_rfcomm_dlc_send(struct bt_rfcomm_dlc *dlc, struct net_buf *buf) { struct bt_rfcomm_hdr *hdr; u8_t fcs, cr; if (!buf) { return -EINVAL; } BT_DBG("dlc %p tx credit %d", dlc, k_sem_count_get(&dlc->tx_credits)); if (dlc->state != BT_RFCOMM_STATE_CONNECTED) { return -ENOTCONN; } if (buf->len > dlc->mtu) { return -EMSGSIZE; } if (buf->len > BT_RFCOMM_MAX_LEN_8) { u16_t *len; /* Length is 2 byte */ hdr = net_buf_push(buf, sizeof(*hdr) + 1); len = (u16_t *)&hdr->length; *len = BT_RFCOMM_SET_LEN_16(sys_cpu_to_le16(buf->len - sizeof(*hdr) - 1)); } else { hdr = net_buf_push(buf, sizeof(*hdr)); hdr->length = BT_RFCOMM_SET_LEN_8(buf->len - sizeof(*hdr)); } cr = BT_RFCOMM_UIH_CR(dlc->session->role); hdr->address = BT_RFCOMM_SET_ADDR(dlc->dlci, cr); hdr->control = BT_RFCOMM_SET_CTRL(BT_RFCOMM_UIH, BT_RFCOMM_PF_UIH_NO_CREDIT); fcs = rfcomm_calc_fcs(BT_RFCOMM_FCS_LEN_UIH, buf->data); net_buf_add_u8(buf, fcs); net_buf_put(&dlc->tx_queue, buf); return buf->len; } static int rfcomm_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_rfcomm_session *session = RFCOMM_SESSION(chan); struct bt_rfcomm_hdr *hdr = (void *)buf->data; u8_t dlci, frame_type, fcs, fcs_len; /* Need to consider FCS also*/ if (buf->len < (sizeof(*hdr) + 1)) { BT_ERR("Too small RFCOMM Frame"); return 0; } dlci = BT_RFCOMM_GET_DLCI(hdr->address); frame_type = BT_RFCOMM_GET_FRAME_TYPE(hdr->control); BT_DBG("session %p dlci %x type %x", session, dlci, frame_type); fcs_len = (frame_type == BT_RFCOMM_UIH) ? BT_RFCOMM_FCS_LEN_UIH : BT_RFCOMM_FCS_LEN_NON_UIH; /* should check the length for rfcomm packet */ if (buf->len < (sizeof(*hdr) + 1 + fcs_len)) { BT_ERR("Too small RFCOMM Frame"); return 0; } fcs = *(net_buf_tail(buf) - 1); if (!rfcomm_check_fcs(fcs_len, buf->data, fcs)) { BT_ERR("FCS check failed"); return 0; } if (BT_RFCOMM_LEN_EXTENDED(hdr->length)) { net_buf_pull(buf, sizeof(*hdr) + 1); } else { net_buf_pull(buf, sizeof(*hdr)); } switch (frame_type) { case BT_RFCOMM_SABM: rfcomm_handle_sabm(session, dlci); break; case BT_RFCOMM_UIH: if (!dlci) { rfcomm_handle_msg(session, buf); } else { rfcomm_handle_data(session, buf, dlci, BT_RFCOMM_GET_PF(hdr->control)); } break; case BT_RFCOMM_DISC: rfcomm_handle_disc(session, dlci); break; case BT_RFCOMM_UA: rfcomm_handle_ua(session, dlci); break; case BT_RFCOMM_DM: rfcomm_handle_dm(session, dlci); break; default: BT_WARN("Unknown/Unsupported RFCOMM Frame type 0x%02x", frame_type); break; } return 0; } static void rfcomm_encrypt_change(struct bt_l2cap_chan *chan, u8_t hci_status) { struct bt_rfcomm_session *session = RFCOMM_SESSION(chan); struct bt_conn *conn = chan->conn; struct bt_rfcomm_dlc *dlc, *next; BT_DBG("session %p status 0x%02x encr 0x%02x", session, hci_status, conn->encrypt); for (dlc = session->dlcs; dlc; dlc = next) { next = dlc->_next; if (dlc->state != BT_RFCOMM_STATE_SECURITY_PENDING) { continue; } if (hci_status || !conn->encrypt || conn->sec_level < dlc->required_sec_level) { rfcomm_dlc_close(dlc); continue; } if (dlc->role == BT_RFCOMM_ROLE_ACCEPTOR) { rfcomm_send_ua(session, dlc->dlci); rfcomm_dlc_connected(dlc); } else { dlc->mtu = MIN(dlc->mtu, session->mtu); dlc->state = BT_RFCOMM_STATE_CONFIG; rfcomm_send_pn(dlc, BT_RFCOMM_MSG_CMD_CR); } } } static void rfcomm_session_rtx_timeout(struct k_work *work) { struct bt_rfcomm_session *session = SESSION_RTX(work); BT_WARN("session %p state %d timeout", session, session->state); switch (session->state) { case BT_RFCOMM_STATE_CONNECTED: rfcomm_session_disconnect(session); break; case BT_RFCOMM_STATE_DISCONNECTING: session->state = BT_RFCOMM_STATE_DISCONNECTED; if (bt_l2cap_chan_disconnect(&session->br_chan.chan) < 0) { session->state = BT_RFCOMM_STATE_IDLE; } break; } } static struct bt_rfcomm_session *rfcomm_session_new(bt_rfcomm_role_t role) { int i; static const struct bt_l2cap_chan_ops ops = { .connected = rfcomm_connected, .disconnected = rfcomm_disconnected, .recv = rfcomm_recv, .encrypt_change = rfcomm_encrypt_change, }; for (i = 0; i < ARRAY_SIZE(bt_rfcomm_pool); i++) { struct bt_rfcomm_session *session = &bt_rfcomm_pool[i]; if (session->br_chan.chan.conn) { continue; } BT_DBG("session %p initialized", session); session->br_chan.chan.ops = &ops; session->br_chan.rx.mtu = CONFIG_BT_RFCOMM_L2CAP_MTU; session->state = BT_RFCOMM_STATE_INIT; session->role = role; session->cfc = BT_RFCOMM_CFC_UNKNOWN; k_delayed_work_init(&session->rtx_work, rfcomm_session_rtx_timeout); k_sem_init(&session->fc, 0, 1); return session; } return NULL; } int bt_rfcomm_dlc_connect(struct bt_conn *conn, struct bt_rfcomm_dlc *dlc, u8_t channel) { struct bt_rfcomm_session *session; struct bt_l2cap_chan *chan; u8_t dlci; int ret; BT_DBG("conn %p dlc %p channel %d", conn, dlc, channel); if (!dlc) { return -EINVAL; } if (!conn || conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (channel < RFCOMM_CHANNEL_START || channel > RFCOMM_CHANNEL_END) { return -EINVAL; } if (!BT_RFCOMM_CHECK_MTU(dlc->mtu)) { return -EINVAL; } session = rfcomm_sessions_lookup_bt_conn(conn); if (!session) { session = rfcomm_session_new(BT_RFCOMM_ROLE_INITIATOR); if (!session) { return -ENOMEM; } } dlci = BT_RFCOMM_DLCI(session->role, channel); if (rfcomm_dlcs_lookup_dlci(session->dlcs, dlci)) { return -EBUSY; } rfcomm_dlc_init(dlc, session, dlci, BT_RFCOMM_ROLE_INITIATOR); switch (session->state) { case BT_RFCOMM_STATE_INIT: if (session->role == BT_RFCOMM_ROLE_ACCEPTOR) { /* There is an ongoing incoming conn */ break; } chan = &session->br_chan.chan; chan->required_sec_level = dlc->required_sec_level; ret = bt_l2cap_chan_connect(conn, chan, BT_L2CAP_PSM_RFCOMM); if (ret < 0) { session->state = BT_RFCOMM_STATE_IDLE; goto fail; } session->state = BT_RFCOMM_STATE_CONNECTING; break; case BT_RFCOMM_STATE_CONNECTING: break; case BT_RFCOMM_STATE_CONNECTED: ret = rfcomm_dlc_start(dlc); if (ret < 0) { goto fail; } /* Cancel idle timer if any */ k_delayed_work_cancel(&session->rtx_work); break; default: BT_ERR("Invalid session state %d", session->state); ret = -EINVAL; goto fail; } return 0; fail: rfcomm_dlcs_remove_dlci(session->dlcs, dlc->dlci); dlc->state = BT_RFCOMM_STATE_IDLE; dlc->session = NULL; return ret; } int bt_rfcomm_dlc_disconnect(struct bt_rfcomm_dlc *dlc) { BT_DBG("dlc %p", dlc); if (!dlc) { return -EINVAL; } if (dlc->state == BT_RFCOMM_STATE_CONNECTED) { /* This is to handle user initiated disconnect to send pending * bufs in the queue before disconnecting * Queue a dummy buffer (in case if queue is empty) to wake up * and stop the tx thread. */ dlc->state = BT_RFCOMM_STATE_USER_DISCONNECT; net_buf_put(&dlc->tx_queue, net_buf_alloc(&dummy_pool, K_NO_WAIT)); k_delayed_work_submit(&dlc->rtx_work, RFCOMM_DISC_TIMEOUT); return 0; } return rfcomm_dlc_close(dlc); } static int rfcomm_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { struct bt_rfcomm_session *session; BT_DBG("conn %p", conn); session = rfcomm_session_new(BT_RFCOMM_ROLE_ACCEPTOR); if (session) { *chan = &session->br_chan.chan; return 0; } BT_ERR("No available RFCOMM context for conn %p", conn); return -ENOMEM; } void bt_rfcomm_init(void) { static struct bt_l2cap_server server = { .psm = BT_L2CAP_PSM_RFCOMM, .accept = rfcomm_accept, .sec_level = BT_SECURITY_L1, }; NET_BUF_POOL_INIT(dummy_pool); bt_l2cap_br_server_register(&server); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/rfcomm.c
C
apache-2.0
43,252
/** @file * @brief Internal APIs for Bluetooth RFCOMM handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bluetooth/rfcomm.h> typedef enum { BT_RFCOMM_CFC_UNKNOWN, BT_RFCOMM_CFC_NOT_SUPPORTED, BT_RFCOMM_CFC_SUPPORTED, } __packed bt_rfcomm_cfc_t; /* RFCOMM signalling connection specific context */ struct bt_rfcomm_session { /* L2CAP channel this context is associated with */ struct bt_l2cap_br_chan br_chan; /* Response Timeout eXpired (RTX) timer */ struct k_delayed_work rtx_work; /* Binary sem for aggregate fc */ struct k_sem fc; struct bt_rfcomm_dlc *dlcs; u16_t mtu; u8_t state; bt_rfcomm_role_t role; bt_rfcomm_cfc_t cfc; }; enum { BT_RFCOMM_STATE_IDLE, BT_RFCOMM_STATE_INIT, BT_RFCOMM_STATE_SECURITY_PENDING, BT_RFCOMM_STATE_CONNECTING, BT_RFCOMM_STATE_CONNECTED, BT_RFCOMM_STATE_CONFIG, BT_RFCOMM_STATE_USER_DISCONNECT, BT_RFCOMM_STATE_DISCONNECTING, BT_RFCOMM_STATE_DISCONNECTED, }; struct bt_rfcomm_hdr { u8_t address; u8_t control; u8_t length; } __packed; #define BT_RFCOMM_SABM 0x2f #define BT_RFCOMM_UA 0x63 #define BT_RFCOMM_UIH 0xef struct bt_rfcomm_msg_hdr { u8_t type; u8_t len; } __packed; #define BT_RFCOMM_PN 0x20 struct bt_rfcomm_pn { u8_t dlci; u8_t flow_ctrl; u8_t priority; u8_t ack_timer; u16_t mtu; u8_t max_retrans; u8_t credits; } __packed; #define BT_RFCOMM_MSC 0x38 struct bt_rfcomm_msc { u8_t dlci; u8_t v24_signal; } __packed; #define BT_RFCOMM_DISC 0x43 #define BT_RFCOMM_DM 0x0f #define BT_RFCOMM_RLS 0x14 struct bt_rfcomm_rls { u8_t dlci; u8_t line_status; } __packed; #define BT_RFCOMM_RPN 0x24 struct bt_rfcomm_rpn { u8_t dlci; u8_t baud_rate; u8_t line_settings; u8_t flow_control; u8_t xon_char; u8_t xoff_char; u16_t param_mask; } __packed; #define BT_RFCOMM_TEST 0x08 #define BT_RFCOMM_NSC 0x04 #define BT_RFCOMM_FCON 0x28 #define BT_RFCOMM_FCOFF 0x18 /* Default RPN Settings */ #define BT_RFCOMM_RPN_BAUD_RATE_9600 0x03 #define BT_RFCOMM_RPN_DATA_BITS_8 0x03 #define BT_RFCOMM_RPN_STOP_BITS_1 0x00 #define BT_RFCOMM_RPN_PARITY_NONE 0x00 #define BT_RFCOMM_RPN_FLOW_NONE 0x00 #define BT_RFCOMM_RPN_XON_CHAR 0x11 #define BT_RFCOMM_RPN_XOFF_CHAR 0x13 /* Set 1 to all the param mask except reserved */ #define BT_RFCOMM_RPN_PARAM_MASK_ALL 0x3f7f #define BT_RFCOMM_SET_LINE_SETTINGS(data, stop, parity) ((data & 0x3) | \ ((stop & 0x1) << 2) | \ ((parity & 0x7) << 3)) /* DV = 1 IC = 0 RTR = 1 RTC = 1 FC = 0 EXT = 0 */ #define BT_RFCOMM_DEFAULT_V24_SIG 0x8d #define BT_RFCOMM_GET_FC(v24_signal) (((v24_signal) & 0x02) >> 1) #define BT_RFCOMM_SIG_MIN_MTU 23 #define BT_RFCOMM_SIG_MAX_MTU 32767 #define BT_RFCOMM_CHECK_MTU(mtu) (!!((mtu) >= BT_RFCOMM_SIG_MIN_MTU && \ (mtu) <= BT_RFCOMM_SIG_MAX_MTU)) /* Helper to calculate needed outgoing buffer size. * Length in rfcomm header can be two bytes depending on user data length. * One byte in the tail should be reserved for FCS. */ #define BT_RFCOMM_BUF_SIZE(mtu) (BT_BUF_RESERVE + \ BT_HCI_ACL_HDR_SIZE + BT_L2CAP_HDR_SIZE + \ sizeof(struct bt_rfcomm_hdr) + 1 + (mtu) + \ BT_RFCOMM_FCS_SIZE) #define BT_RFCOMM_GET_DLCI(addr) (((addr) & 0xfc) >> 2) #define BT_RFCOMM_GET_FRAME_TYPE(ctrl) ((ctrl) & 0xef) #define BT_RFCOMM_GET_MSG_TYPE(type) (((type) & 0xfc) >> 2) #define BT_RFCOMM_GET_MSG_CR(type) (((type) & 0x02) >> 1) #define BT_RFCOMM_GET_LEN(len) (((len) & 0xfe) >> 1) #define BT_RFCOMM_GET_CHANNEL(dlci) ((dlci) >> 1) #define BT_RFCOMM_GET_PF(ctrl) (((ctrl) & 0x10) >> 4) #define BT_RFCOMM_SET_ADDR(dlci, cr) ((((dlci) & 0x3f) << 2) | \ ((cr) << 1) | 0x01) #define BT_RFCOMM_SET_CTRL(type, pf) (((type) & 0xef) | ((pf) << 4)) #define BT_RFCOMM_SET_LEN_8(len) (((len) << 1) | 1) #define BT_RFCOMM_SET_LEN_16(len) ((len) << 1) #define BT_RFCOMM_SET_MSG_TYPE(type, cr) (((type) << 2) | (cr << 1) | 0x01) #define BT_RFCOMM_LEN_EXTENDED(len) (!((len) & 0x01)) /* For CR in UIH Packet header * Initiating station have the C/R bit set to 1 and those sent by the * responding station have the C/R bit set to 0 */ #define BT_RFCOMM_UIH_CR(role) ((role) == BT_RFCOMM_ROLE_INITIATOR) /* For CR in Non UIH Packet header * Command * Initiator --> Responder 1 * Responder --> Initiator 0 * Response * Initiator --> Responder 0 * Responder --> Initiator 1 */ #define BT_RFCOMM_CMD_CR(role) ((role) == BT_RFCOMM_ROLE_INITIATOR) #define BT_RFCOMM_RESP_CR(role) ((role) == BT_RFCOMM_ROLE_ACCEPTOR) /* For CR in MSG header * If the C/R bit is set to 1 the message is a command, * if it is set to 0 the message is a response. */ #define BT_RFCOMM_MSG_CMD_CR 1 #define BT_RFCOMM_MSG_RESP_CR 0 #define BT_RFCOMM_DLCI(role, channel) ((((channel) & 0x1f) << 1) | \ ((role) == BT_RFCOMM_ROLE_ACCEPTOR)) /* Excluding ext bit */ #define BT_RFCOMM_MAX_LEN_8 127 /* Length can be 2 bytes depending on data size */ #define BT_RFCOMM_HDR_SIZE (sizeof(struct bt_rfcomm_hdr) + 1) #define BT_RFCOMM_FCS_SIZE 1 #define BT_RFCOMM_FCS_LEN_UIH 2 #define BT_RFCOMM_FCS_LEN_NON_UIH 3 /* For non UIH packets * The P bit set to 1 shall be used to solicit a response frame with the * F bit set to 1 from the other station. */ #define BT_RFCOMM_PF_NON_UIH 1 /* For UIH packets * Both stations set the P-bit to 0 * If credit based flow control is used, If P/F is 1 then one credit byte * will be there after control in the frame else no credit byte. */ #define BT_RFCOMM_PF_UIH 0 #define BT_RFCOMM_PF_UIH_CREDIT 1 #define BT_RFCOMM_PF_UIH_NO_CREDIT 0 #define BT_RFCOMM_PN_CFC_CMD 0xf0 #define BT_RFCOMM_PN_CFC_RESP 0xe0 /* Initialize RFCOMM signal layer */ void bt_rfcomm_init(void);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/rfcomm_internal.h
C
apache-2.0
5,962
/** @file * @brief Service Discovery Protocol handling. */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <sys/types.h> #include <misc/byteorder.h> #include <misc/__assert.h> #if defined(CONFIG_BT_BREDR) #include <bluetooth/sdp.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_SDP) #define LOG_MODULE_NAME bt_sdp #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "sdp_internal.h" #define SDP_PSM 0x0001 #define SDP_CHAN(_ch) CONTAINER_OF(_ch, struct bt_sdp, chan.chan) #define IN_RANGE(val, min, max) (val >= min && val <= max) #define SDP_DATA_MTU 200 #define SDP_MTU (SDP_DATA_MTU + sizeof(struct bt_sdp_hdr)) #define MAX_NUM_ATT_ID_FILTER 10 #define SDP_SERVICE_HANDLE_BASE 0x10000 #define SDP_DATA_ELEM_NEST_LEVEL_MAX 5 /* Size of Cont state length */ #define SDP_CONT_STATE_LEN_SIZE 1 /* 1 byte for the no. of services searched till this response */ /* 2 bytes for the total no. of matching records */ #define SDP_SS_CONT_STATE_SIZE 3 /* 1 byte for the no. of attributes searched till this response */ #define SDP_SA_CONT_STATE_SIZE 1 /* 1 byte for the no. of services searched till this response */ /* 1 byte for the no. of attributes searched till this response */ #define SDP_SSA_CONT_STATE_SIZE 2 #define SDP_INVALID 0xff struct bt_sdp { struct bt_l2cap_br_chan chan; struct kfifo partial_resp_queue; /* TODO: Allow more than one pending request */ }; static struct bt_sdp_record *db; static u8_t num_services; static struct bt_sdp bt_sdp_pool[CONFIG_BT_MAX_CONN]; /* Pool for outgoing SDP packets */ NET_BUF_POOL_FIXED_DEFINE(sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL); #define SDP_CLIENT_CHAN(_ch) CONTAINER_OF(_ch, struct bt_sdp_client, chan.chan) #define SDP_CLIENT_MTU 64 struct bt_sdp_client { struct bt_l2cap_br_chan chan; /* list of waiting to be resolved UUID params */ sys_slist_t reqs; /* required SDP transaction ID */ u16_t tid; /* UUID params holder being now resolved */ const struct bt_sdp_discover_params *param; /* PDU continuation state object */ struct bt_sdp_pdu_cstate cstate; /* buffer for collecting record data */ struct net_buf *rec_buf; }; static struct bt_sdp_client bt_sdp_client_pool[CONFIG_BT_MAX_CONN]; enum { BT_SDP_ITER_STOP, BT_SDP_ITER_CONTINUE, }; struct search_state { u16_t att_list_size; u8_t current_svc; u8_t last_att; bool pkt_full; }; struct select_attrs_data { struct bt_sdp_record *rec; struct net_buf *rsp_buf; struct bt_sdp *sdp; struct bt_sdp_data_elem_seq *seq; struct search_state *state; bt_u32_t *filter; u16_t max_att_len; u16_t att_list_len; u8_t cont_state_size; u8_t num_filters; bool new_service; }; /* @typedef bt_sdp_attr_func_t * @brief SDP attribute iterator callback. * * @param attr Attribute found. * @param att_idx Index of the found attribute in the attribute database. * @param user_data Data given. * * @return BT_SDP_ITER_CONTINUE if should continue to the next attribute * or BT_SDP_ITER_STOP to stop. */ typedef u8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr, u8_t att_idx, void *user_data); /* @typedef bt_sdp_svc_func_t * @brief SDP service record iterator callback. * * @param rec Service record found. * @param user_data Data given. * * @return BT_SDP_ITER_CONTINUE if should continue to the next service record * or BT_SDP_ITER_STOP to stop. */ typedef u8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec, void *user_data); /* @brief Callback for SDP connection * * Gets called when an SDP connection is established * * @param chan L2CAP channel * * @return None */ static void bt_sdp_connected(struct bt_l2cap_chan *chan) { struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan); struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan); BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); k_fifo_init(&sdp->partial_resp_queue); } /** @brief Callback for SDP disconnection * * Gets called when an SDP connection is terminated * * @param chan L2CAP channel * * @return None */ static void bt_sdp_disconnected(struct bt_l2cap_chan *chan) { struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan); struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan); BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); (void)memset(sdp, 0, sizeof(*sdp)); } /* @brief Creates an SDP PDU * * Creates an empty SDP PDU and returns the buffer * * @param None * * @return Pointer to the net_buf buffer */ static struct net_buf *bt_sdp_create_pdu(void) { return bt_l2cap_create_pdu(&sdp_pool, sizeof(struct bt_sdp_hdr)); } /* @brief Sends out an SDP PDU * * Sends out an SDP PDU after adding the relevant header * * @param chan L2CAP channel * @param buf Buffer to be sent out * @param op Opcode to be used in the packet header * @param tid Transaction ID to be used in the packet header * * @return None */ static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf, u8_t op, u16_t tid) { struct bt_sdp_hdr *hdr; u16_t param_len = buf->len; hdr = net_buf_push(buf, sizeof(struct bt_sdp_hdr)); hdr->op_code = op; hdr->tid = tid; hdr->param_len = sys_cpu_to_be16(param_len); bt_l2cap_chan_send(chan, buf); } /* @brief Sends an error response PDU * * Creates and sends an error response PDU * * @param chan L2CAP channel * @param err Error code to be sent in the packet * @param tid Transaction ID to be used in the packet header * * @return None */ static void send_err_rsp(struct bt_l2cap_chan *chan, u16_t err, u16_t tid) { struct net_buf *buf; BT_DBG("tid %u, error %u", tid, err); buf = bt_sdp_create_pdu(); net_buf_add_be16(buf, err); bt_sdp_send(chan, buf, BT_SDP_ERROR_RSP, tid); } /* @brief Parses data elements from a net_buf * * Parses the first data element from a buffer and splits it into type, size, * data. Used for parsing incoming requests. Net buf is advanced to the data * part of the element. * * @param buf Buffer to be advanced * @param data_elem Pointer to the parsed data element structure * * @return 0 for success, or relevant error code */ static u16_t parse_data_elem(struct net_buf *buf, struct bt_sdp_data_elem *data_elem) { u8_t size_field_len = 0U; /* Space used to accommodate the size */ if (buf->len < 1) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } data_elem->type = net_buf_pull_u8(buf); switch (data_elem->type & BT_SDP_TYPE_DESC_MASK) { case BT_SDP_UINT8: case BT_SDP_INT8: case BT_SDP_UUID_UNSPEC: case BT_SDP_BOOL: data_elem->data_size = BIT(data_elem->type & BT_SDP_SIZE_DESC_MASK); break; case BT_SDP_TEXT_STR_UNSPEC: case BT_SDP_SEQ_UNSPEC: case BT_SDP_ALT_UNSPEC: case BT_SDP_URL_STR_UNSPEC: size_field_len = BIT((data_elem->type & BT_SDP_SIZE_DESC_MASK) - BT_SDP_SIZE_INDEX_OFFSET); if (buf->len < size_field_len) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } switch (size_field_len) { case 1: data_elem->data_size = net_buf_pull_u8(buf); break; case 2: data_elem->data_size = net_buf_pull_be16(buf); break; case 4: data_elem->data_size = net_buf_pull_be32(buf); break; default: BT_WARN("Invalid size in remote request"); return BT_SDP_INVALID_SYNTAX; } break; default: BT_WARN("Invalid type in remote request"); return BT_SDP_INVALID_SYNTAX; } if (buf->len < data_elem->data_size) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } data_elem->total_size = data_elem->data_size + size_field_len + 1; data_elem->data = buf->data; return 0; } /* @brief Searches for an UUID within an attribute * * Searches for an UUID within an attribute. If the attribute has data element * sequences, it recursively searches within them as well. On finding a match * with the UUID, it sets the found flag. * * @param elem Attribute to be used as the search space (haystack) * @param uuid UUID to be looked for (needle) * @param found Flag set to true if the UUID is found (to be returned) * @param nest_level Used to limit the extent of recursion into nested data * elements, to avoid potential stack overflows * * @return Size of the last data element that has been searched * (used in recursion) */ static bt_u32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid, bool *found, u8_t nest_level) { const u8_t *cur_elem; bt_u32_t seq_size, size; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_32 u32; struct bt_uuid_128 u128; } u; if (*found) { return 0; } /* Limit recursion depth to avoid stack overflows */ if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) { return 0; } seq_size = elem->data_size; cur_elem = elem->data; if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) { if (seq_size == 2U) { u.uuid.type = BT_UUID_TYPE_16; u.u16.val = *((u16_t *)cur_elem); if (!bt_uuid_cmp(&u.uuid, uuid)) { *found = true; } } else if (seq_size == 4U) { u.uuid.type = BT_UUID_TYPE_32; u.u32.val = *((bt_u32_t *)cur_elem); if (!bt_uuid_cmp(&u.uuid, uuid)) { *found = true; } } else if (seq_size == 16U) { u.uuid.type = BT_UUID_TYPE_128; memcpy(u.u128.val, cur_elem, seq_size); if (!bt_uuid_cmp(&u.uuid, uuid)) { *found = true; } } else { BT_WARN("Invalid UUID size in local database"); BT_ASSERT(0); } } if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) { do { /* Recursively parse data elements */ size = search_uuid((struct bt_sdp_data_elem *)cur_elem, uuid, found, nest_level + 1); if (*found) { return 0; } cur_elem += sizeof(struct bt_sdp_data_elem); seq_size -= size; } while (seq_size); } return elem->total_size; } /* @brief SDP service record iterator. * * Iterate over service records from a starting point. * * @param func Callback function. * @param user_data Data to pass to the callback. * * @return Pointer to the record where the iterator stopped, or NULL if all * records are covered */ static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func, void *user_data) { struct bt_sdp_record *rec = db; while (rec) { if (func(rec, user_data) == BT_SDP_ITER_STOP) { break; } rec = rec->next; } return rec; } /* @brief Inserts a service record into a record pointer list * * Inserts a service record into a record pointer list * * @param rec The current service record. * @param user_data Pointer to the destination record list. * * @return BT_SDP_ITER_CONTINUE to move on to the next record. */ static u8_t insert_record(struct bt_sdp_record *rec, void *user_data) { struct bt_sdp_record **rec_list = user_data; rec_list[rec->index] = rec; return BT_SDP_ITER_CONTINUE; } /* @brief Looks for matching UUIDs in a list of service records * * Parses out a sequence of UUIDs from an input buffer, and checks if a record * in the list contains all the UUIDs. If it doesn't, the record is removed * from the list, so the list contains only the records which has all the * input UUIDs in them. * * @param buf Incoming buffer containing all the UUIDs to be matched * @param matching_recs List of service records to use for storing matching * records * * @return 0 for success, or relevant error code */ static u16_t find_services(struct net_buf *buf, struct bt_sdp_record **matching_recs) { struct bt_sdp_data_elem data_elem; struct bt_sdp_record *record; bt_u32_t uuid_list_size; u16_t res; u8_t att_idx, rec_idx = 0U; bool found; union { struct bt_uuid uuid; struct bt_uuid_16 u16; struct bt_uuid_32 u32; struct bt_uuid_128 u128; } u; res = parse_data_elem(buf, &data_elem); if (res) { return res; } if (((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_SEQ_UNSPEC) && ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_ALT_UNSPEC)) { BT_WARN("Invalid type %x in service search pattern", data_elem.type); return BT_SDP_INVALID_SYNTAX; } uuid_list_size = data_elem.data_size; bt_sdp_foreach_svc(insert_record, matching_recs); /* Go over the sequence of UUIDs, and match one UUID at a time */ while (uuid_list_size) { res = parse_data_elem(buf, &data_elem); if (res) { return res; } if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UUID_UNSPEC) { BT_WARN("Invalid type %u in service search pattern", data_elem.type); return BT_SDP_INVALID_SYNTAX; } if (buf->len < data_elem.data_size) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } if (data_elem.data_size == 2U) { u.uuid.type = BT_UUID_TYPE_16; u.u16.val = net_buf_pull_be16(buf); } else if (data_elem.data_size == 4U) { u.uuid.type = BT_UUID_TYPE_32; u.u32.val = net_buf_pull_be32(buf); } else if (data_elem.data_size == 16U) { u.uuid.type = BT_UUID_TYPE_128; sys_memcpy_swap(u.u128.val, buf->data, data_elem.data_size); net_buf_pull(buf, data_elem.data_size); } else { BT_WARN("Invalid UUID len %u in service search pattern", data_elem.data_size); net_buf_pull(buf, data_elem.data_size); } uuid_list_size -= data_elem.total_size; /* Go over the list of services, and look for a service which * doesn't have this UUID */ for (rec_idx = 0U; rec_idx < num_services; rec_idx++) { record = matching_recs[rec_idx]; if (!record) { continue; } found = false; /* Search for the UUID in all the attrs of the svc */ for (att_idx = 0U; att_idx < record->attr_count; att_idx++) { search_uuid(&record->attrs[att_idx].val, &u.uuid, &found, 1); if (found) { break; } } /* Remove the record from the list if it doesn't have * the UUID */ if (!found) { matching_recs[rec_idx] = NULL; } } } return 0; } /* @brief Handler for Service Search Request * * Parses, processes and responds to a Service Search Request * * @param sdp Pointer to the SDP structure * @param buf Request net buf * @param tid Transaction ID * * @return 0 for success, or relevant error code */ static u16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf, u16_t tid) { struct bt_sdp_svc_rsp *rsp; struct net_buf *resp_buf; struct bt_sdp_record *record; struct bt_sdp_record *matching_recs[BT_SDP_MAX_SERVICES]; u16_t max_rec_count, total_recs = 0U, current_recs = 0U, res; u8_t cont_state_size, cont_state = 0U, idx = 0U, count = 0U; bool pkt_full = false; res = find_services(buf, matching_recs); if (res) { /* Error in parsing */ return res; } if (buf->len < 3) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } max_rec_count = net_buf_pull_be16(buf); cont_state_size = net_buf_pull_u8(buf); /* Zero out the matching services beyond max_rec_count */ for (idx = 0U; idx < num_services; idx++) { if (count == max_rec_count) { matching_recs[idx] = NULL; continue; } if (matching_recs[idx]) { count++; } } /* We send out only SDP_SS_CONT_STATE_SIZE bytes continuation state in * responses, so expect only SDP_SS_CONT_STATE_SIZE bytes in requests */ if (cont_state_size) { if (cont_state_size != SDP_SS_CONT_STATE_SIZE) { BT_WARN("Invalid cont state size %u", cont_state_size); return BT_SDP_INVALID_CSTATE; } if (buf->len < cont_state_size) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } cont_state = net_buf_pull_u8(buf); /* We include total_recs in the continuation state. We calculate * it once and preserve it across all the partial responses */ total_recs = net_buf_pull_be16(buf); } BT_DBG("max_rec_count %u, cont_state %u", max_rec_count, cont_state); resp_buf = bt_sdp_create_pdu(); rsp = net_buf_add(resp_buf, sizeof(*rsp)); for (; cont_state < num_services; cont_state++) { record = matching_recs[cont_state]; if (!record) { continue; } /* Calculate total recs only if it is first packet */ if (!cont_state_size) { total_recs++; } if (pkt_full) { continue; } /* 4 bytes per Service Record Handle */ /* 4 bytes for ContinuationState */ if ((MIN(SDP_MTU, sdp->chan.tx.mtu) - resp_buf->len) < (4 + 4 + sizeof(struct bt_sdp_hdr))) { pkt_full = true; } if (pkt_full) { /* Packet exhausted: Add continuation state and break */ BT_DBG("Packet full, num_services_covered %u", cont_state); net_buf_add_u8(resp_buf, SDP_SS_CONT_STATE_SIZE); net_buf_add_u8(resp_buf, cont_state); /* If it is the first packet of a partial response, * continue dry-running to calculate total_recs. * Else break */ if (cont_state_size) { break; } continue; } /* Add the service record handle to the packet */ net_buf_add_be32(resp_buf, record->handle); current_recs++; } /* Add 0 continuation state if packet is exhausted */ if (!pkt_full) { net_buf_add_u8(resp_buf, 0); } else { net_buf_add_be16(resp_buf, total_recs); } rsp->total_recs = sys_cpu_to_be16(total_recs); rsp->current_recs = sys_cpu_to_be16(current_recs); BT_DBG("Sending response, len %u", resp_buf->len); bt_sdp_send(&sdp->chan.chan, resp_buf, BT_SDP_SVC_SEARCH_RSP, tid); return 0; } /* @brief Copies an attribute into an outgoing buffer * * Copies an attribute into a buffer. Recursively calls itself for complex * attributes. * * @param elem Attribute to be copied to the buffer * @param buf Buffer where the attribute is to be copied * * @return Size of the last data element that has been searched * (used in recursion) */ static bt_u32_t copy_attribute(struct bt_sdp_data_elem *elem, struct net_buf *buf, u8_t nest_level) { const u8_t *cur_elem; bt_u32_t size, seq_size, total_size; /* Limit recursion depth to avoid stack overflows */ if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) { return 0; } seq_size = elem->data_size; total_size = elem->total_size; cur_elem = elem->data; /* Copy the header */ net_buf_add_u8(buf, elem->type); switch (total_size - (seq_size + 1U)) { case 1: net_buf_add_u8(buf, elem->data_size); break; case 2: net_buf_add_be16(buf, elem->data_size); break; case 4: net_buf_add_be32(buf, elem->data_size); break; } /* Recursively parse (till the last element is not another data element) * and then fill the elements */ if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) { do { size = copy_attribute((struct bt_sdp_data_elem *) cur_elem, buf, nest_level + 1); cur_elem += sizeof(struct bt_sdp_data_elem); seq_size -= size; } while (seq_size); } else if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UINT8 || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_INT8 || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) { if (seq_size == 1U) { net_buf_add_u8(buf, *((u8_t *)elem->data)); } else if (seq_size == 2U) { net_buf_add_be16(buf, *((u16_t *)elem->data)); } else if (seq_size == 4U) { net_buf_add_be32(buf, *((bt_u32_t *)elem->data)); } else { /* TODO: Convert 32bit and 128bit values to big-endian*/ net_buf_add_mem(buf, elem->data, seq_size); } } else { net_buf_add_mem(buf, elem->data, seq_size); } return total_size; } /* @brief SDP attribute iterator. * * Iterate over attributes of a service record from a starting index. * * @param record Service record whose attributes are to be iterated over. * @param idx Index in the attribute list from where to start. * @param func Callback function. * @param user_data Data to pass to the callback. * * @return Index of the attribute where the iterator stopped */ static u8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, u8_t idx, bt_sdp_attr_func_t func, void *user_data) { for (; idx < record->attr_count; idx++) { if (func(&record->attrs[idx], idx, user_data) == BT_SDP_ITER_STOP) { break; } } return idx; } /* @brief Check if an attribute matches a range, and include it in the response * * Checks if an attribute matches a given attribute ID or range, and if so, * includes it in the response packet * * @param attr The current attribute * @param att_idx Index of the current attribute in the database * @param user_data Pointer to the structure containing response packet, byte * count, states, etc * * @return BT_SDP_ITER_CONTINUE if should continue to the next attribute * or BT_SDP_ITER_STOP to stop. */ static u8_t select_attrs(struct bt_sdp_attribute *attr, u8_t att_idx, void *user_data) { struct select_attrs_data *sad = user_data; u16_t att_id_lower, att_id_upper, att_id_cur, space; bt_u32_t attr_size, seq_size; u8_t idx_filter; for (idx_filter = 0U; idx_filter < sad->num_filters; idx_filter++) { att_id_lower = (sad->filter[idx_filter] >> 16); att_id_upper = (sad->filter[idx_filter]); att_id_cur = attr->id; /* Check for range values */ if (att_id_lower != 0xffff && (!IN_RANGE(att_id_cur, att_id_lower, att_id_upper))) { continue; } /* Check for match values */ if (att_id_lower == 0xffff && att_id_cur != att_id_upper) { continue; } /* Attribute ID matches */ /* 3 bytes for Attribute ID */ attr_size = 3 + attr->val.total_size; /* If this is the first attribute of the service, then we need * to account for the space required to add the per-service * data element sequence header as well. */ if ((sad->state->current_svc != sad->rec->index) && sad->new_service) { /* 3 bytes for Per-Service Data Elem Seq declaration */ seq_size = attr_size + 3; } else { seq_size = attr_size; } if (sad->rsp_buf) { space = MIN(SDP_MTU, sad->sdp->chan.tx.mtu) - sad->rsp_buf->len - sizeof(struct bt_sdp_hdr); if ((!sad->state->pkt_full) && ((seq_size > sad->max_att_len) || (space < seq_size + sad->cont_state_size))) { /* Packet exhausted */ sad->state->pkt_full = true; } } /* Keep filling data only if packet is not exhausted */ if (!sad->state->pkt_full && sad->rsp_buf) { /* Add Per-Service Data Element Seq declaration once * only when we are starting from the first attribute */ if (!sad->seq && (sad->state->current_svc != sad->rec->index)) { sad->seq = net_buf_add(sad->rsp_buf, sizeof(*sad->seq)); sad->seq->type = BT_SDP_SEQ16; sad->seq->size = 0U; } /* Add attribute ID */ net_buf_add_u8(sad->rsp_buf, BT_SDP_UINT16); net_buf_add_be16(sad->rsp_buf, att_id_cur); /* Add attribute value */ copy_attribute(&attr->val, sad->rsp_buf, 1); sad->max_att_len -= seq_size; sad->att_list_len += seq_size; sad->state->last_att = att_idx; sad->state->current_svc = sad->rec->index; } if (sad->seq) { /* Keep adding the sequence size if this packet contains * the Per-Service Data Element Seq declaration header */ sad->seq->size += attr_size; sad->state->att_list_size += seq_size; } else { /* Keep adding the total attr lists size if: * It's a dry-run, calculating the total attr lists size */ sad->state->att_list_size += seq_size; } sad->new_service = false; break; } /* End the search if: * 1. We have exhausted the packet * AND * 2. This packet doesn't contain the service element declaration header * AND * 3. This is not a dry-run (then we look for other attrs that match) */ if (sad->state->pkt_full && !sad->seq && sad->rsp_buf) { return BT_SDP_ITER_STOP; } return BT_SDP_ITER_CONTINUE; } /* @brief Creates attribute list in the given buffer * * Populates the attribute list of a service record in the buffer. To be used * for responding to Service Attribute and Service Search Attribute requests * * @param sdp Pointer to the SDP structure * @param record Service record whose attributes are to be included in the * response * @param filter Attribute values/ranges to be used as a filter * @param num_filters Number of elements in the attribute filter * @param max_att_len Maximum size of attributes to be included in the response * @param cont_state_size No. of additional continuation state bytes to keep * space for in the packet. This will vary based on the type of the request * @param next_att Starting position of the search in the service's attr list * @param state State of the overall search * @param rsp_buf Response buffer which is filled in * * @return len Length of the attribute list created */ static u16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *record, bt_u32_t *filter, u8_t num_filters, u16_t max_att_len, u8_t cont_state_size, u8_t next_att, struct search_state *state, struct net_buf *rsp_buf) { struct select_attrs_data sad; u8_t idx_att; sad.num_filters = num_filters; sad.rec = record; sad.rsp_buf = rsp_buf; sad.sdp = sdp; sad.max_att_len = max_att_len; sad.cont_state_size = cont_state_size; sad.seq = NULL; sad.filter = filter; sad.state = state; sad.att_list_len = 0U; sad.new_service = true; idx_att = bt_sdp_foreach_attr(sad.rec, next_att, select_attrs, &sad); if (sad.seq) { sad.seq->size = sys_cpu_to_be16(sad.seq->size); } return sad.att_list_len; } /* @brief Extracts the attribute search list from a buffer * * Parses a buffer to extract the attribute search list (list of attribute IDs * and ranges) which are to be used to filter attributes. * * @param buf Buffer to be parsed for extracting the attribute search list * @param filter Empty list of 4byte filters that are filled in. For attribute * IDs, the lower 2 bytes contain the ID and the upper 2 bytes are set to * 0xFFFF. For attribute ranges, the lower 2bytes indicate the start ID and * the upper 2bytes indicate the end ID * @param num_filters No. of filter elements filled in (to be returned) * * @return 0 for success, or relevant error code */ static u16_t get_att_search_list(struct net_buf *buf, bt_u32_t *filter, u8_t *num_filters) { struct bt_sdp_data_elem data_elem; u16_t res; bt_u32_t size; *num_filters = 0U; res = parse_data_elem(buf, &data_elem); if (res) { return res; } size = data_elem.data_size; while (size) { res = parse_data_elem(buf, &data_elem); if (res) { return res; } if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UINT8) { BT_WARN("Invalid type %u in attribute ID list", data_elem.type); return BT_SDP_INVALID_SYNTAX; } if (buf->len < data_elem.data_size) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } /* we should check if num_filters out of range */ if (*num_filters >= MAX_NUM_ATT_ID_FILTER) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } /* This is an attribute ID */ if (data_elem.data_size == 2U) { filter[(*num_filters)++] = 0xffff0000 | net_buf_pull_be16(buf); } /* This is an attribute ID range */ if (data_elem.data_size == 4U) { filter[(*num_filters)++] = net_buf_pull_be32(buf); } size -= data_elem.total_size; } return 0; } /* @brief Check if a given handle matches that of the current service * * Checks if a given handle matches that of the current service * * @param rec The current service record * @param user_data Pointer to the service record handle to be matched * * @return BT_SDP_ITER_CONTINUE if should continue to the next record * or BT_SDP_ITER_STOP to stop. */ static u8_t find_handle(struct bt_sdp_record *rec, void *user_data) { bt_u32_t *svc_rec_hdl = user_data; if (rec->handle == *svc_rec_hdl) { return BT_SDP_ITER_STOP; } return BT_SDP_ITER_CONTINUE; } /* @brief Handler for Service Attribute Request * * Parses, processes and responds to a Service Attribute Request * * @param sdp Pointer to the SDP structure * @param buf Request buffer * @param tid Transaction ID * * @return 0 for success, or relevant error code */ static u16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf, u16_t tid) { bt_u32_t filter[MAX_NUM_ATT_ID_FILTER]; struct search_state state = { .current_svc = SDP_INVALID, .last_att = SDP_INVALID, .pkt_full = false }; struct bt_sdp_record *record; struct bt_sdp_att_rsp *rsp; struct net_buf *rsp_buf; bt_u32_t svc_rec_hdl; u16_t max_att_len, res, att_list_len; u8_t num_filters, cont_state_size, next_att = 0U; if (buf->len < 6) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } svc_rec_hdl = net_buf_pull_be32(buf); max_att_len = net_buf_pull_be16(buf); /* Set up the filters */ res = get_att_search_list(buf, filter, &num_filters); if (res) { /* Error in parsing */ return res; } if (buf->len < 1) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } cont_state_size = net_buf_pull_u8(buf); /* We only send out 1 byte continuation state in responses, * so expect only 1 byte in requests */ if (cont_state_size) { if (cont_state_size != SDP_SA_CONT_STATE_SIZE) { BT_WARN("Invalid cont state size %u", cont_state_size); return BT_SDP_INVALID_CSTATE; } if (buf->len < cont_state_size) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } state.last_att = net_buf_pull_u8(buf) + 1; next_att = state.last_att; } BT_DBG("svc_rec_hdl %u, max_att_len 0x%04x, cont_state %u", svc_rec_hdl, max_att_len, next_att); /* Find the service */ record = bt_sdp_foreach_svc(find_handle, &svc_rec_hdl); if (!record) { BT_WARN("Handle %u not found", svc_rec_hdl); return BT_SDP_INVALID_RECORD_HANDLE; } /* For partial responses, restore the search state */ if (cont_state_size) { state.current_svc = record->index; } rsp_buf = bt_sdp_create_pdu(); rsp = net_buf_add(rsp_buf, sizeof(*rsp)); /* cont_state_size should include 1 byte header */ att_list_len = create_attr_list(sdp, record, filter, num_filters, max_att_len, SDP_SA_CONT_STATE_SIZE + 1, next_att, &state, rsp_buf); if (!att_list_len) { /* For empty responses, add an empty data element sequence */ net_buf_add_u8(rsp_buf, BT_SDP_SEQ8); net_buf_add_u8(rsp_buf, 0); att_list_len = 2U; } /* Add continuation state */ if (state.pkt_full) { BT_DBG("Packet full, state.last_att %u", state.last_att); net_buf_add_u8(rsp_buf, 1); net_buf_add_u8(rsp_buf, state.last_att); } else { net_buf_add_u8(rsp_buf, 0); } rsp->att_list_len = sys_cpu_to_be16(att_list_len); BT_DBG("Sending response, len %u", rsp_buf->len); bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_ATTR_RSP, tid); return 0; } /* @brief Handler for Service Search Attribute Request * * Parses, processes and responds to a Service Search Attribute Request * * @param sdp Pointer to the SDP structure * @param buf Request buffer * @param tid Transaction ID * * @return 0 for success, or relevant error code */ static u16_t sdp_svc_search_att_req(struct bt_sdp *sdp, struct net_buf *buf, u16_t tid) { bt_u32_t filter[MAX_NUM_ATT_ID_FILTER]; struct bt_sdp_record *matching_recs[BT_SDP_MAX_SERVICES]; struct search_state state = { .att_list_size = 0, .current_svc = SDP_INVALID, .last_att = SDP_INVALID, .pkt_full = false }; struct net_buf *rsp_buf, *rsp_buf_cpy; struct bt_sdp_record *record; struct bt_sdp_att_rsp *rsp; struct bt_sdp_data_elem_seq *seq = NULL; u16_t max_att_len, res, att_list_len = 0U; u8_t num_filters, cont_state_size, next_svc = 0U, next_att = 0U; bool dry_run = false; res = find_services(buf, matching_recs); if (res) { return res; } if (buf->len < 2) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } max_att_len = net_buf_pull_be16(buf); /* Set up the filters */ res = get_att_search_list(buf, filter, &num_filters); if (res) { /* Error in parsing */ return res; } if (buf->len < 1) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } cont_state_size = net_buf_pull_u8(buf); /* We only send out 2 bytes continuation state in responses, * so expect only 2 bytes in requests */ if (cont_state_size) { if (cont_state_size != SDP_SSA_CONT_STATE_SIZE) { BT_WARN("Invalid cont state size %u", cont_state_size); return BT_SDP_INVALID_CSTATE; } if (buf->len < cont_state_size) { BT_WARN("Malformed packet"); return BT_SDP_INVALID_SYNTAX; } state.current_svc = net_buf_pull_u8(buf); state.last_att = net_buf_pull_u8(buf) + 1; next_svc = state.current_svc; next_att = state.last_att; } BT_DBG("max_att_len 0x%04x, state.current_svc %u, state.last_att %u", max_att_len, state.current_svc, state.last_att); rsp_buf = bt_sdp_create_pdu(); rsp = net_buf_add(rsp_buf, sizeof(*rsp)); /* Add headers only if this is not a partial response */ if (!cont_state_size) { seq = net_buf_add(rsp_buf, sizeof(*seq)); seq->type = BT_SDP_SEQ16; seq->size = 0U; /* 3 bytes for Outer Data Element Sequence declaration */ att_list_len = 3U; } rsp_buf_cpy = rsp_buf; for (; next_svc < num_services; next_svc++) { record = matching_recs[next_svc]; if (!record) { continue; } att_list_len += create_attr_list(sdp, record, filter, num_filters, max_att_len, SDP_SSA_CONT_STATE_SIZE + 1, next_att, &state, rsp_buf_cpy); /* Check if packet is full and not dry run */ if (state.pkt_full && !dry_run) { BT_DBG("Packet full, state.last_att %u", state.last_att); dry_run = true; /* Add continuation state */ net_buf_add_u8(rsp_buf, 2); net_buf_add_u8(rsp_buf, state.current_svc); net_buf_add_u8(rsp_buf, state.last_att); /* Break if it's not a partial response, else dry-run * Dry run: Look for other services that match */ if (cont_state_size) { break; } rsp_buf_cpy = NULL; } next_att = 0U; } if (!dry_run) { if (!att_list_len) { /* For empty responses, add an empty data elem seq */ net_buf_add_u8(rsp_buf, BT_SDP_SEQ8); net_buf_add_u8(rsp_buf, 0); att_list_len = 2U; } /* Search exhausted */ net_buf_add_u8(rsp_buf, 0); } rsp->att_list_len = sys_cpu_to_be16(att_list_len); if (seq) { seq->size = sys_cpu_to_be16(state.att_list_size); } BT_DBG("Sending response, len %u", rsp_buf->len); bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_SEARCH_ATTR_RSP, tid); return 0; } static const struct { u8_t op_code; u16_t (*func)(struct bt_sdp *sdp, struct net_buf *buf, u16_t tid); } handlers[] = { { BT_SDP_SVC_SEARCH_REQ, sdp_svc_search_req }, { BT_SDP_SVC_ATTR_REQ, sdp_svc_att_req }, { BT_SDP_SVC_SEARCH_ATTR_REQ, sdp_svc_search_att_req }, }; /* @brief Callback for SDP data receive * * Gets called when an SDP PDU is received. Calls the corresponding handler * based on the op code of the PDU. * * @param chan L2CAP channel * @param buf Received PDU * * @return None */ static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan); struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan); struct bt_sdp_hdr *hdr; u16_t err = BT_SDP_INVALID_SYNTAX; size_t i; BT_DBG("chan %p, ch %p, cid 0x%04x", chan, ch, ch->tx.cid); BT_ASSERT(sdp); if (buf->len < sizeof(*hdr)) { BT_ERR("Too small SDP PDU received"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_DBG("Received SDP code 0x%02x len %u", hdr->op_code, buf->len); if (sys_cpu_to_be16(hdr->param_len) != buf->len) { err = BT_SDP_INVALID_PDU_SIZE; } else { for (i = 0; i < ARRAY_SIZE(handlers); i++) { if (hdr->op_code != handlers[i].op_code) { continue; } err = handlers[i].func(sdp, buf, hdr->tid); break; } } if (err) { BT_WARN("SDP error 0x%02x", err); send_err_rsp(chan, err, hdr->tid); } return 0; } /* @brief Callback for SDP connection accept * * Gets called when an incoming SDP connection needs to be authorized. * Registers the L2CAP callbacks and allocates an SDP context to the connection * * @param conn BT connection object * @param chan L2CAP channel structure (to be returned) * * @return 0 for success, or relevant error code */ static int bt_sdp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { static const struct bt_l2cap_chan_ops ops = { .connected = bt_sdp_connected, .disconnected = bt_sdp_disconnected, .recv = bt_sdp_recv, }; int i; BT_DBG("conn %p", conn); for (i = 0; i < ARRAY_SIZE(bt_sdp_pool); i++) { struct bt_sdp *sdp = &bt_sdp_pool[i]; if (sdp->chan.chan.conn) { continue; } sdp->chan.chan.ops = &ops; sdp->chan.rx.mtu = SDP_MTU; *chan = &sdp->chan.chan; return 0; } BT_ERR("No available SDP context for conn %p", conn); return -ENOMEM; } void bt_sdp_init(void) { static struct bt_l2cap_server server = { .psm = SDP_PSM, .accept = bt_sdp_accept, .sec_level = BT_SECURITY_L0, }; int res; res = bt_l2cap_br_server_register(&server); if (res) { BT_ERR("L2CAP server registration failed with error %d", res); } } int bt_sdp_register_service(struct bt_sdp_record *service) { bt_u32_t handle = SDP_SERVICE_HANDLE_BASE; if (!service) { BT_ERR("No service record specified"); return 0; } if (num_services == BT_SDP_MAX_SERVICES) { BT_ERR("Reached max allowed registrations"); return -ENOMEM; } if (db) { handle = db->handle + 1; } service->next = db; service->index = num_services++; service->handle = handle; *((bt_u32_t *)(service->attrs[0].val.data)) = handle; db = service; BT_DBG("Service registered at %u", handle); return 0; } #define GET_PARAM(__node) \ CONTAINER_OF(__node, struct bt_sdp_discover_params, _node) /* ServiceSearchAttribute PDU, ref to BT Core 4.2, Vol 3, part B, 4.7.1 */ static int sdp_client_ssa_search(struct bt_sdp_client *session) { const struct bt_sdp_discover_params *param; struct bt_sdp_hdr *hdr; struct net_buf *buf; /* * Select proper user params, if session->param is invalid it means * getting new UUID from top of to be resolved params list. Otherwise * the context is in a middle of partial SDP PDU responses and cached * value from context can be used. */ if (!session->param) { param = GET_PARAM(sys_slist_peek_head(&session->reqs)); } else { param = session->param; } if (!param) { BT_WARN("No UUIDs to be resolved on remote"); return -EINVAL; } buf = bt_l2cap_create_pdu(&sdp_pool, 0); hdr = net_buf_add(buf, sizeof(*hdr)); hdr->op_code = BT_SDP_SVC_SEARCH_ATTR_REQ; /* BT_SDP_SEQ8 means length of sequence is on additional next byte */ net_buf_add_u8(buf, BT_SDP_SEQ8); switch (param->uuid->type) { case BT_UUID_TYPE_16: /* Seq length */ net_buf_add_u8(buf, 0x03); /* Seq type */ net_buf_add_u8(buf, BT_SDP_UUID16); /* Seq value */ net_buf_add_be16(buf, BT_UUID_16(param->uuid)->val); break; case BT_UUID_TYPE_32: net_buf_add_u8(buf, 0x05); net_buf_add_u8(buf, BT_SDP_UUID32); net_buf_add_be32(buf, BT_UUID_32(param->uuid)->val); break; case BT_UUID_TYPE_128: net_buf_add_u8(buf, 0x11); net_buf_add_u8(buf, BT_SDP_UUID128); net_buf_add_mem(buf, BT_UUID_128(param->uuid)->val, ARRAY_SIZE(BT_UUID_128(param->uuid)->val)); break; default: BT_ERR("Unknown UUID type %u", param->uuid->type); return -EINVAL; } /* Set attribute max bytes count to be returned from server */ net_buf_add_be16(buf, BT_SDP_MAX_ATTR_LEN); /* * Sequence definition where data is sequence of elements and where * additional next byte points the size of elements within */ net_buf_add_u8(buf, BT_SDP_SEQ8); net_buf_add_u8(buf, 0x05); /* Data element definition for two following 16bits range elements */ net_buf_add_u8(buf, BT_SDP_UINT32); /* Get all attributes. It enables filter out wanted only attributes */ net_buf_add_be16(buf, 0x0000); net_buf_add_be16(buf, 0xffff); /* * Update and validate PDU ContinuationState. Initial SSA Request has * zero length continuation state since no interaction has place with * server so far, otherwise use the original state taken from remote's * last response PDU that is cached by SDP client context. */ if (session->cstate.length == 0U) { net_buf_add_u8(buf, 0x00); } else { net_buf_add_u8(buf, session->cstate.length); net_buf_add_mem(buf, session->cstate.data, session->cstate.length); } /* set overall PDU length */ hdr->param_len = sys_cpu_to_be16(buf->len - sizeof(*hdr)); /* Update context param to the one being resolving now */ session->param = param; session->tid++; hdr->tid = sys_cpu_to_be16(session->tid); return bt_l2cap_chan_send(&session->chan.chan, buf); } static void sdp_client_params_iterator(struct bt_sdp_client *session) { struct bt_l2cap_chan *chan = &session->chan.chan; struct bt_sdp_discover_params *param, *tmp; SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&session->reqs, param, tmp, _node) { if (param != session->param) { continue; } BT_DBG(""); /* Remove already checked UUID node */ sys_slist_remove(&session->reqs, NULL, &param->_node); /* Invalidate cached param in context */ session->param = NULL; /* Reset continuation state in current context */ (void)memset(&session->cstate, 0, sizeof(session->cstate)); /* Check if there's valid next UUID */ if (!sys_slist_is_empty(&session->reqs)) { sdp_client_ssa_search(session); return; } /* No UUID items, disconnect channel */ bt_l2cap_chan_disconnect(chan); break; } } static u16_t sdp_client_get_total(struct bt_sdp_client *session, struct net_buf *buf, u16_t *total) { u16_t pulled; u8_t seq; /* * Pull value of total octets of all attributes available to be * collected when response gets completed for given UUID. Such info can * be get from the very first response frame after initial SSA request * was sent. For subsequent calls related to the same SSA request input * buf and in/out function parameters stays neutral. */ if (session->cstate.length == 0U) { seq = net_buf_pull_u8(buf); pulled = 1U; switch (seq) { case BT_SDP_SEQ8: *total = net_buf_pull_u8(buf); pulled += 1U; break; case BT_SDP_SEQ16: *total = net_buf_pull_be16(buf); pulled += 2U; break; default: BT_WARN("Sequence type 0x%02x not handled", seq); *total = 0U; break; } BT_DBG("Total %u octets of all attributes", *total); } else { pulled = 0U; *total = 0U; } return pulled; } static u16_t get_record_len(struct net_buf *buf) { u16_t len; u8_t seq; seq = net_buf_pull_u8(buf); switch (seq) { case BT_SDP_SEQ8: len = net_buf_pull_u8(buf); break; case BT_SDP_SEQ16: len = net_buf_pull_be16(buf); break; default: BT_WARN("Sequence type 0x%02x not handled", seq); len = 0U; break; } BT_DBG("Record len %u", len); return len; } enum uuid_state { UUID_NOT_RESOLVED, UUID_RESOLVED, }; static void sdp_client_notify_result(struct bt_sdp_client *session, enum uuid_state state) { struct bt_conn *conn = session->chan.chan.conn; struct bt_sdp_client_result result; u16_t rec_len; u8_t user_ret; result.uuid = session->param->uuid; if (state == UUID_NOT_RESOLVED) { result.resp_buf = NULL; result.next_record_hint = false; session->param->func(conn, &result); return; } while (session->rec_buf->len) { struct net_buf_simple_state buf_state; rec_len = get_record_len(session->rec_buf); /* tell the user about multi record resolution */ if (session->rec_buf->len > rec_len) { result.next_record_hint = true; } else { result.next_record_hint = false; } /* save the original session buffer */ net_buf_simple_save(&session->rec_buf->b, &buf_state); /* initialize internal result buffer instead of memcpy */ result.resp_buf = session->rec_buf; /* * Set user internal result buffer length as same as record * length to fake user. User will see the individual record * length as rec_len insted of whole session rec_buf length. */ result.resp_buf->len = rec_len; user_ret = session->param->func(conn, &result); /* restore original session buffer */ net_buf_simple_restore(&session->rec_buf->b, &buf_state); /* * sync session buffer data length with next record chunk not * send to user so far */ net_buf_pull(session->rec_buf, rec_len); if (user_ret == BT_SDP_DISCOVER_UUID_STOP) { break; } } } static int sdp_client_receive(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan); struct bt_sdp_hdr *hdr; struct bt_sdp_pdu_cstate *cstate; u16_t len, tid, frame_len; u16_t total; BT_DBG("session %p buf %p", session, buf); if (buf->len < sizeof(*hdr)) { BT_ERR("Too small SDP PDU"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); if (hdr->op_code == BT_SDP_ERROR_RSP) { BT_INFO("Error SDP PDU response"); return 0; } len = sys_be16_to_cpu(hdr->param_len); tid = sys_be16_to_cpu(hdr->tid); BT_DBG("SDP PDU tid %u len %u", tid, len); if (buf->len != len) { BT_ERR("SDP PDU length mismatch (%u != %u)", buf->len, len); return 0; } if (tid != session->tid) { BT_ERR("Mismatch transaction ID value in SDP PDU"); return 0; } switch (hdr->op_code) { case BT_SDP_SVC_SEARCH_ATTR_RSP: /* Get number of attributes in this frame. */ frame_len = net_buf_pull_be16(buf); /* Check valid buf len for attribute list and cont state */ if (buf->len < frame_len + SDP_CONT_STATE_LEN_SIZE) { BT_ERR("Invalid frame payload length"); return 0; } /* Check valid range of attributes length */ if (frame_len < 2) { BT_ERR("Invalid attributes data length"); return 0; } /* Get PDU continuation state */ cstate = (struct bt_sdp_pdu_cstate *)(buf->data + frame_len); if (cstate->length > BT_SDP_MAX_PDU_CSTATE_LEN) { BT_ERR("Invalid SDP PDU Continuation State length %u", cstate->length); return 0; } if ((frame_len + SDP_CONT_STATE_LEN_SIZE + cstate->length) > buf->len) { BT_ERR("Invalid frame payload length"); return 0; } /* * No record found for given UUID. The check catches case when * current response frame has Continuation State shortest and * valid and this is the first response frame as well. */ if (frame_len == 2U && cstate->length == 0U && session->cstate.length == 0U) { BT_DBG("record for UUID 0x%s not found", bt_uuid_str(session->param->uuid)); /* Call user UUID handler */ sdp_client_notify_result(session, UUID_NOT_RESOLVED); net_buf_pull(buf, frame_len + sizeof(cstate->length)); goto iterate; } /* Get total value of all attributes to be collected */ frame_len -= sdp_client_get_total(session, buf, &total); if (total > net_buf_tailroom(session->rec_buf)) { BT_WARN("Not enough room for getting records data"); goto iterate; } net_buf_add_mem(session->rec_buf, buf->data, frame_len); net_buf_pull(buf, frame_len); /* * check if current response says there's next portion to be * fetched */ if (cstate->length) { /* Cache original Continuation State in context */ memcpy(&session->cstate, cstate, sizeof(struct bt_sdp_pdu_cstate)); net_buf_pull(buf, cstate->length + sizeof(cstate->length)); /* Request for next portion of attributes data */ sdp_client_ssa_search(session); break; } net_buf_pull(buf, sizeof(cstate->length)); BT_DBG("UUID 0x%s resolved", bt_uuid_str(session->param->uuid)); sdp_client_notify_result(session, UUID_RESOLVED); iterate: /* Get next UUID and start resolving it */ sdp_client_params_iterator(session); break; default: BT_DBG("PDU 0x%0x response not handled", hdr->op_code); break; } return 0; } static int sdp_client_chan_connect(struct bt_sdp_client *session) { return bt_l2cap_br_chan_connect(session->chan.chan.conn, &session->chan.chan, SDP_PSM); } static struct net_buf *sdp_client_alloc_buf(struct bt_l2cap_chan *chan) { struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan); struct net_buf *buf; BT_DBG("session %p chan %p", session, chan); session->param = GET_PARAM(sys_slist_peek_head(&session->reqs)); buf = net_buf_alloc(session->param->pool, K_FOREVER); __ASSERT_NO_MSG(buf); return buf; } static void sdp_client_connected(struct bt_l2cap_chan *chan) { struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan); BT_DBG("session %p chan %p connected", session, chan); session->rec_buf = chan->ops->alloc_buf(chan); sdp_client_ssa_search(session); } static void sdp_client_disconnected(struct bt_l2cap_chan *chan) { struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan); BT_DBG("session %p chan %p disconnected", session, chan); net_buf_unref(session->rec_buf); /* * Reset session excluding L2CAP channel member. Let's the channel * resets autonomous. */ (void)memset(&session->reqs, 0, sizeof(*session) - sizeof(session->chan)); } static const struct bt_l2cap_chan_ops sdp_client_chan_ops = { .connected = sdp_client_connected, .disconnected = sdp_client_disconnected, .recv = sdp_client_receive, .alloc_buf = sdp_client_alloc_buf, }; static struct bt_sdp_client *sdp_client_new_session(struct bt_conn *conn) { int i; for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) { struct bt_sdp_client *session = &bt_sdp_client_pool[i]; int err; if (session->chan.chan.conn) { continue; } sys_slist_init(&session->reqs); session->chan.chan.ops = &sdp_client_chan_ops; session->chan.chan.conn = conn; session->chan.rx.mtu = SDP_CLIENT_MTU; err = sdp_client_chan_connect(session); if (err) { (void)memset(session, 0, sizeof(*session)); BT_ERR("Cannot connect %d", err); return NULL; } return session; } BT_ERR("No available SDP client context"); return NULL; } static struct bt_sdp_client *sdp_client_get_session(struct bt_conn *conn) { int i; for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) { if (bt_sdp_client_pool[i].chan.chan.conn == conn) { return &bt_sdp_client_pool[i]; } } /* * Try to allocate session context since not found in pool and attempt * connect to remote SDP endpoint. */ return sdp_client_new_session(conn); } int bt_sdp_discover(struct bt_conn *conn, const struct bt_sdp_discover_params *params) { struct bt_sdp_client *session; if (!params || !params->uuid || !params->func || !params->pool) { BT_WARN("Invalid user params"); return -EINVAL; } session = sdp_client_get_session(conn); if (!session) { return -ENOMEM; } sys_slist_append(&session->reqs, (sys_snode_t *)&params->_node); return 0; } /* Helper getting length of data determined by DTD for integers */ static inline ssize_t sdp_get_int_len(const u8_t *data, size_t len) { BT_ASSERT(data); switch (data[0]) { case BT_SDP_DATA_NIL: return 1; case BT_SDP_BOOL: case BT_SDP_INT8: case BT_SDP_UINT8: if (len < 2) { break; } return 2; case BT_SDP_INT16: case BT_SDP_UINT16: if (len < 3) { break; } return 3; case BT_SDP_INT32: case BT_SDP_UINT32: if (len < 5) { break; } return 5; case BT_SDP_INT64: case BT_SDP_UINT64: if (len < 9) { break; } return 9; case BT_SDP_INT128: case BT_SDP_UINT128: default: BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]); return -EINVAL; } BT_ERR("Too short buffer length %zu", len); return -EMSGSIZE; } /* Helper getting length of data determined by DTD for UUID */ static inline ssize_t sdp_get_uuid_len(const u8_t *data, size_t len) { BT_ASSERT(data); switch (data[0]) { case BT_SDP_UUID16: if (len < 3) { break; } return 3; case BT_SDP_UUID32: if (len < 5) { break; } return 5; case BT_SDP_UUID128: default: BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]); return -EINVAL; } BT_ERR("Too short buffer length %zu", len); return -EMSGSIZE; } /* Helper getting length of data determined by DTD for strings */ static inline ssize_t sdp_get_str_len(const u8_t *data, size_t len) { const u8_t *pnext; BT_ASSERT(data); /* validate len for pnext safe use to read next 8bit value */ if (len < 2) { goto err; } pnext = data + sizeof(u8_t); switch (data[0]) { case BT_SDP_TEXT_STR8: case BT_SDP_URL_STR8: if (len < (2 + pnext[0])) { break; } return 2 + pnext[0]; case BT_SDP_TEXT_STR16: case BT_SDP_URL_STR16: /* validate len for pnext safe use to read 16bit value */ if (len < 3) { break; } if (len < (3 + sys_get_be16(pnext))) { break; } return 3 + sys_get_be16(pnext); case BT_SDP_TEXT_STR32: case BT_SDP_URL_STR32: default: BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]); return -EINVAL; } err: BT_ERR("Too short buffer length %zu", len); return -EMSGSIZE; } /* Helper getting length of data determined by DTD for sequences */ static inline ssize_t sdp_get_seq_len(const u8_t *data, size_t len) { const u8_t *pnext; BT_ASSERT(data); /* validate len for pnext safe use to read 8bit bit value */ if (len < 2) { goto err; } pnext = data + sizeof(u8_t); switch (data[0]) { case BT_SDP_SEQ8: case BT_SDP_ALT8: if (len < (2 + pnext[0])) { break; } return 2 + pnext[0]; case BT_SDP_SEQ16: case BT_SDP_ALT16: /* validate len for pnext safe use to read 16bit value */ if (len < 3) { break; } if (len < (3 + sys_get_be16(pnext))) { break; } return 3 + sys_get_be16(pnext); case BT_SDP_SEQ32: case BT_SDP_ALT32: default: BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]); return -EINVAL; } err: BT_ERR("Too short buffer length %zu", len); return -EMSGSIZE; } /* Helper getting length of attribute value data */ static ssize_t sdp_get_attr_value_len(const u8_t *data, size_t len) { BT_ASSERT(data); BT_DBG("Attr val DTD 0x%02x", data[0]); switch (data[0]) { case BT_SDP_DATA_NIL: case BT_SDP_BOOL: case BT_SDP_UINT8: case BT_SDP_UINT16: case BT_SDP_UINT32: case BT_SDP_UINT64: case BT_SDP_UINT128: case BT_SDP_INT8: case BT_SDP_INT16: case BT_SDP_INT32: case BT_SDP_INT64: case BT_SDP_INT128: return sdp_get_int_len(data, len); case BT_SDP_UUID16: case BT_SDP_UUID32: case BT_SDP_UUID128: return sdp_get_uuid_len(data, len); case BT_SDP_TEXT_STR8: case BT_SDP_TEXT_STR16: case BT_SDP_TEXT_STR32: case BT_SDP_URL_STR8: case BT_SDP_URL_STR16: case BT_SDP_URL_STR32: return sdp_get_str_len(data, len); case BT_SDP_SEQ8: case BT_SDP_SEQ16: case BT_SDP_SEQ32: case BT_SDP_ALT8: case BT_SDP_ALT16: case BT_SDP_ALT32: return sdp_get_seq_len(data, len); default: BT_ERR("Unknown DTD 0x%02x", data[0]); return -EINVAL; } } /* Type holding UUID item and related to it specific information. */ struct bt_sdp_uuid_desc { union { struct bt_uuid uuid; struct bt_uuid_16 uuid16; struct bt_uuid_32 uuid32; }; u16_t attr_id; u8_t *params; u16_t params_len; }; /* Generic attribute item collector. */ struct bt_sdp_attr_item { /* Attribute identifier. */ u16_t attr_id; /* Address of beginning attribute value taken from original buffer * holding response from server. */ u8_t *val; /* Says about the length of attribute value. */ u16_t len; }; static int bt_sdp_get_attr(const struct net_buf *buf, struct bt_sdp_attr_item *attr, u16_t attr_id) { u8_t *data; u16_t id; data = buf->data; while (data - buf->data < buf->len) { ssize_t dlen; /* data need to point to attribute id descriptor field (DTD)*/ if (data[0] != BT_SDP_UINT16) { BT_ERR("Invalid descriptor 0x%02x", data[0]); return -EINVAL; } data += sizeof(u8_t); id = sys_get_be16(data); BT_DBG("Attribute ID 0x%04x", id); data += sizeof(u16_t); dlen = sdp_get_attr_value_len(data, buf->len - (data - buf->data)); if (dlen < 0) { BT_ERR("Invalid attribute value data"); return -EINVAL; } if (id == attr_id) { BT_DBG("Attribute ID 0x%04x Value found", id); /* * Initialize attribute value buffer data using selected * data slice from original buffer. */ attr->val = data; attr->len = dlen; attr->attr_id = id; return 0; } data += dlen; } return -ENOENT; } /* reads SEQ item length, moves input buffer data reader forward */ static ssize_t sdp_get_seq_len_item(u8_t **data, size_t len) { const u8_t *pnext; BT_ASSERT(data); BT_ASSERT(*data); /* validate len for pnext safe use to read 8bit bit value */ if (len < 2) { goto err; } pnext = *data + sizeof(u8_t); switch (*data[0]) { case BT_SDP_SEQ8: if (len < (2 + pnext[0])) { break; } *data += 2; return pnext[0]; case BT_SDP_SEQ16: /* validate len for pnext safe use to read 16bit value */ if (len < 3) { break; } if (len < (3 + sys_get_be16(pnext))) { break; } *data += 3; return sys_get_be16(pnext); case BT_SDP_SEQ32: /* validate len for pnext safe use to read 32bit value */ if (len < 5) { break; } if (len < (5 + sys_get_be32(pnext))) { break; } *data += 5; return sys_get_be32(pnext); default: BT_ERR("Invalid/unhandled DTD 0x%02x", *data[0]); return -EINVAL; } err: BT_ERR("Too short buffer length %zu", len); return -EMSGSIZE; } static int sdp_get_uuid_data(const struct bt_sdp_attr_item *attr, struct bt_sdp_uuid_desc *pd, u16_t proto_profile) { /* get start address of attribute value */ u8_t *p = attr->val; ssize_t slen; BT_ASSERT(p); /* Attribute value is a SEQ, get length of parent SEQ frame */ slen = sdp_get_seq_len_item(&p, attr->len); if (slen < 0) { return slen; } /* start reading stacked UUIDs in analyzed sequences tree */ while (p - attr->val < attr->len) { size_t to_end, left = 0; /* to_end tells how far to the end of input buffer */ to_end = attr->len - (p - attr->val); /* how long is current UUID's item data associated to */ slen = sdp_get_seq_len_item(&p, to_end); if (slen < 0) { return slen; } /* left tells how far is to the end of current UUID */ left = slen; /* check if at least DTD + UUID16 can be read safely */ if (left < 3) { return -EMSGSIZE; } /* check DTD and get stacked UUID value */ switch (p[0]) { case BT_SDP_UUID16: memcpy(&pd->uuid16, BT_UUID_DECLARE_16(sys_get_be16(++p)), sizeof(struct bt_uuid_16)); p += sizeof(u16_t); left -= sizeof(u16_t); break; case BT_SDP_UUID32: /* check if valid UUID32 can be read safely */ if (left < 5) { return -EMSGSIZE; } memcpy(&pd->uuid32, BT_UUID_DECLARE_32(sys_get_be32(++p)), sizeof(struct bt_uuid_32)); p += sizeof(bt_u32_t); left -= sizeof(bt_u32_t); break; default: BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]); return -EINVAL; } /* include last DTD in p[0] size itself updating left */ left -= sizeof(p[0]); /* * Check if current UUID value matches input one given by user. * If found save it's location and length and return. */ if ((proto_profile == BT_UUID_16(&pd->uuid)->val) || (proto_profile == BT_UUID_32(&pd->uuid)->val)) { pd->params = p; pd->params_len = left; BT_DBG("UUID 0x%s found", bt_uuid_str(&pd->uuid)); return 0; } /* skip left octets to point beginning of next UUID in tree */ p += left; } BT_DBG("Value 0x%04x not found", proto_profile); return -ENOENT; } /* * Helper extracting specific parameters associated with UUID node given in * protocol descriptor list or profile descriptor list. */ static int sdp_get_param_item(struct bt_sdp_uuid_desc *pd_item, u16_t *param) { const u8_t *p = pd_item->params; bool len_err = false; BT_ASSERT(p); BT_DBG("Getting UUID's 0x%s params", bt_uuid_str(&pd_item->uuid)); switch (p[0]) { case BT_SDP_UINT8: /* check if 8bits value can be read safely */ if (pd_item->params_len < 2) { len_err = true; break; } *param = (++p)[0]; p += sizeof(u8_t); break; case BT_SDP_UINT16: /* check if 16bits value can be read safely */ if (pd_item->params_len < 3) { len_err = true; break; } *param = sys_get_be16(++p); p += sizeof(u16_t); break; case BT_SDP_UINT32: /* check if 32bits value can be read safely */ if (pd_item->params_len < 5) { len_err = true; break; } *param = sys_get_be32(++p); p += sizeof(bt_u32_t); break; default: BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]); return -EINVAL; } /* * Check if no more data than already read is associated with UUID. In * valid case after getting parameter we should reach data buf end. */ if (p - pd_item->params != pd_item->params_len || len_err) { BT_DBG("Invalid param buffer length"); return -EMSGSIZE; } return 0; } int bt_sdp_get_proto_param(const struct net_buf *buf, enum bt_sdp_proto proto, u16_t *param) { struct bt_sdp_attr_item attr; struct bt_sdp_uuid_desc pd; int res; if (proto != BT_SDP_PROTO_RFCOMM && proto != BT_SDP_PROTO_L2CAP) { BT_ERR("Invalid protocol specifier"); return -EINVAL; } res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROTO_DESC_LIST); if (res < 0) { BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_PROTO_DESC_LIST, res); return res; } res = sdp_get_uuid_data(&attr, &pd, proto); if (res < 0) { BT_WARN("Protocol specifier 0x%04x not found, err %d", proto, res); return res; } return sdp_get_param_item(&pd, param); } int bt_sdp_get_profile_version(const struct net_buf *buf, u16_t profile, u16_t *version) { struct bt_sdp_attr_item attr; struct bt_sdp_uuid_desc pd; int res; res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROFILE_DESC_LIST); if (res < 0) { BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_PROFILE_DESC_LIST, res); return res; } res = sdp_get_uuid_data(&attr, &pd, profile); if (res < 0) { BT_WARN("Profile 0x%04x not found, err %d", profile, res); return res; } return sdp_get_param_item(&pd, version); } int bt_sdp_get_features(const struct net_buf *buf, u16_t *features) { struct bt_sdp_attr_item attr; const u8_t *p; int res; res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_SUPPORTED_FEATURES); if (res < 0) { BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_SUPPORTED_FEATURES, res); return res; } p = attr.val; BT_ASSERT(p); if (p[0] != BT_SDP_UINT16) { BT_ERR("Invalid DTD 0x%02x", p[0]); return -EINVAL; } /* assert 16bit can be read safely */ if (attr.len < 3) { BT_ERR("Data length too short %u", attr.len); return -EMSGSIZE; } *features = sys_get_be16(++p); p += sizeof(u16_t); if (p - attr.val != attr.len) { BT_ERR("Invalid data length %u", attr.len); return -EMSGSIZE; } return 0; } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/sdp.c
C
apache-2.0
63,132
/* sdp_internal.h - Service Discovery Protocol handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /* * The PDU identifiers of SDP packets between client and server */ #define BT_SDP_ERROR_RSP 0x01 #define BT_SDP_SVC_SEARCH_REQ 0x02 #define BT_SDP_SVC_SEARCH_RSP 0x03 #define BT_SDP_SVC_ATTR_REQ 0x04 #define BT_SDP_SVC_ATTR_RSP 0x05 #define BT_SDP_SVC_SEARCH_ATTR_REQ 0x06 #define BT_SDP_SVC_SEARCH_ATTR_RSP 0x07 /* * Some additions to support service registration. * These are outside the scope of the Bluetooth specification */ #define BT_SDP_SVC_REGISTER_REQ 0x75 #define BT_SDP_SVC_REGISTER_RSP 0x76 #define BT_SDP_SVC_UPDATE_REQ 0x77 #define BT_SDP_SVC_UPDATE_RSP 0x78 #define BT_SDP_SVC_REMOVE_REQ 0x79 #define BT_SDP_SVC_REMOVE_RSP 0x80 /* * SDP Error codes */ #define BT_SDP_INVALID_VERSION 0x0001 #define BT_SDP_INVALID_RECORD_HANDLE 0x0002 #define BT_SDP_INVALID_SYNTAX 0x0003 #define BT_SDP_INVALID_PDU_SIZE 0x0004 #define BT_SDP_INVALID_CSTATE 0x0005 #define BT_SDP_MAX_SERVICES 10 struct bt_sdp_data_elem_seq { u8_t type; /* Type: Will be data element sequence */ u16_t size; /* We only support 2 byte sizes for now */ } __packed; struct bt_sdp_hdr { u8_t op_code; u16_t tid; u16_t param_len; } __packed; struct bt_sdp_svc_rsp { u16_t total_recs; u16_t current_recs; } __packed; struct bt_sdp_att_rsp { u16_t att_list_len; } __packed; /* Allowed attributes length in SSA Request PDU to be taken from server */ #define BT_SDP_MAX_ATTR_LEN 0xffff /* Max allowed length of PDU Continuation State */ #define BT_SDP_MAX_PDU_CSTATE_LEN 16 /* Type mapping SDP PDU Continuation State */ struct bt_sdp_pdu_cstate { u8_t length; u8_t data[BT_SDP_MAX_PDU_CSTATE_LEN]; } __packed; void bt_sdp_init(void);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/sdp_internal.h
C
apache-2.0
1,864
/* * Copyright (c) 2018 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <ble_os.h> #include <settings/settings.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_SETTINGS) #define LOG_MODULE_NAME bt_settings #include "common/log.h" #include "hci_core.h" #include "settings.h" #if defined(CONFIG_BT_SETTINGS_USE_PRINTK) void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, const bt_addr_le_t *addr, const char *key) { if (key) { snprintf(path, path_size, "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys, addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], addr->type, key); } else { snprintf(path, path_size, "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys, addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], addr->type); } BT_DBG("Encoded path %s", log_strdup(path)); } #else void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, const bt_addr_le_t *addr, const char *key) { size_t len = 3; /* Skip if path_size is less than 3; strlen("bt/") */ if (len < path_size) { /* Key format: * "bt/<subsys>/<addr><type>/<key>", "/<key>" is optional */ strcpy(path, "bt/"); strncpy(&path[len], subsys, path_size - len); len = strlen(path); if (len < path_size) { path[len] = '/'; len++; } for (s8_t i = 5; i >= 0 && len < path_size; i--) { len += bin2hex(&addr->a.val[i], 1, &path[len], path_size - len); } if (len < path_size) { /* Type can be either BT_ADDR_LE_PUBLIC or * BT_ADDR_LE_RANDOM (value 0 or 1) */ path[len] = '0' + addr->type; len++; } if (key && len < path_size) { path[len] = '/'; len++; strncpy(&path[len], key, path_size - len); len += strlen(&path[len]); } if (len >= path_size) { /* Truncate string */ path[path_size - 1] = '\0'; } } else if (path_size > 0) { *path = '\0'; } BT_DBG("Encoded path %s", log_strdup(path)); } #endif int bt_settings_decode_key(const char *key, bt_addr_le_t *addr) { if (settings_name_next(key, NULL) != 13) { return -EINVAL; } if (key[12] == '0') { addr->type = BT_ADDR_LE_PUBLIC; } else if (key[12] == '1') { addr->type = BT_ADDR_LE_RANDOM; } else { return -EINVAL; } for (u8_t i = 0; i < 6; i++) { hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1); } BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr)); return 0; } static int set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) { ssize_t len; const char *next; if (!name) { BT_ERR("Insufficient number of arguments"); return -ENOENT; } len = settings_name_next(name, &next); if (!strncmp(name, "id", len)) { /* Any previously provided identities supersede flash */ if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) { BT_WARN("Ignoring identities stored in flash"); return 0; } len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr)); if (len < sizeof(bt_dev.id_addr[0])) { if (len < 0) { BT_ERR("Failed to read ID address from storage" " (err %d)", len); } else { BT_ERR("Invalid length ID address in storage"); //BT_HEXDUMP_DBG(&bt_dev.id_addr, len, // "data read"); } (void)memset(bt_dev.id_addr, 0, sizeof(bt_dev.id_addr)); bt_dev.id_count = 0U; } else { int i; bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]); for (i = 0; i < bt_dev.id_count; i++) { BT_DBG("ID[%d] %s", i, bt_addr_le_str(&bt_dev.id_addr[i])); } } return 0; } #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) if (!strncmp(name, "name", len)) { len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1); if (len < 0) { BT_ERR("Failed to read device name from storage" " (err %d)", len); } else { bt_dev.name[len] = '\0'; BT_DBG("Name set to %s", log_strdup(bt_dev.name)); } return 0; } #endif #if defined(CONFIG_BT_PRIVACY) if (!strncmp(name, "irk", len)) { len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk)); if (len < sizeof(bt_dev.irk[0])) { if (len < 0) { BT_ERR("Failed to read IRK from storage" " (err %d)", len); } else { BT_ERR("Invalid length IRK in storage"); (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk)); } } else { int i, count; count = len / sizeof(bt_dev.irk[0]); for (i = 0; i < count; i++) { BT_DBG("IRK[%d] %s", i, bt_hex(bt_dev.irk[i], 16)); } } return 0; } #endif /* CONFIG_BT_PRIVACY */ return -ENOENT; } #define ID_DATA_LEN(array) (bt_dev.id_count * sizeof(array[0])) static void save_id(struct k_work *work) { int err; BT_INFO("Saving ID"); err = settings_save_one("bt/id", &bt_dev.id_addr, ID_DATA_LEN(bt_dev.id_addr)); if (err) { BT_ERR("Failed to save ID (err %d)", err); } #if defined(CONFIG_BT_PRIVACY) err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk)); if (err) { BT_ERR("Failed to save IRK (err %d)", err); } #endif } //K_WORK_DEFINE(save_id_work, save_id); static struct k_work save_id_work; void bt_settings_save_id(void) { k_work_submit(&save_id_work); } static int commit(void) { BT_DBG(""); #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) if (bt_dev.name[0] == '\0') { bt_set_name(CONFIG_BT_DEVICE_NAME); } #endif if (!bt_dev.id_count) { bt_setup_public_id_addr(); } if (!bt_dev.id_count) { int err; err = bt_setup_random_id_addr(); if (err) { BT_ERR("Unable to setup an identity address"); return err; } } if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { bt_finalize_init(); } /* If any part of the Identity Information of the device has been * generated this Identity needs to be saved persistently. */ if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_STORE_ID)) { BT_DBG("Storing Identity Information"); bt_settings_save_id(); } return 0; } //SETTINGS_STATIC_HANDLER_DEFINE(bt, "bt", NULL, set, commit, NULL); int bt_settings_init(void) { int err; BT_DBG(""); k_work_init(&save_id_work, save_id); err = settings_subsys_init(); if (err) { BT_ERR("settings_subsys_init failed (err %d)", err); return err; } SETTINGS_HANDLER_DEFINE(bt, "bt", NULL, set, commit, NULL); return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/settings.c
C
apache-2.0
6,417
/* * Copyright (c) 2018 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /* Max settings key length (with all components) */ #define BT_SETTINGS_KEY_MAX 36 /* Base64-encoded string buffer size of in_size bytes */ #define BT_SETTINGS_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1) /* Helpers for keys containing a bdaddr */ void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, const bt_addr_le_t *addr, const char *key); int bt_settings_decode_key(const char *key, bt_addr_le_t *addr); void bt_settings_save_id(void); int bt_settings_init(void);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/settings.h
C
apache-2.0
605
/** * @file smp.c * Security Manager Protocol implementation */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <stddef.h> #include <bt_errno.h> #include <string.h> #include <atomic.h> #include <misc/util.h> #include <misc/byteorder.h> #include <misc/stack.h> #include <net/buf.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/buf.h> #if !defined(CONFIG_BT_USE_HCI_API) #include <tinycrypt/constants.h> #include <tinycrypt/aes.h> #include <tinycrypt/utils.h> #include <tinycrypt/cmac_mode.h> #endif #if defined(CONFIG_BT_SMP) #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_SMP) #define LOG_MODULE_NAME bt_smp #include "common/log.h" #include "hci_core.h" #include "ecc.h" #include "keys.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "smp.h" #include "bt_crypto.h" #define SMP_TIMEOUT K_SECONDS(30) #if defined(CONFIG_BT_SIGNING) #define SIGN_DIST BT_SMP_DIST_SIGN #else #define SIGN_DIST 0 #endif #if defined(CONFIG_BT_PRIVACY) #define ID_DIST BT_SMP_DIST_ID_KEY #else #define ID_DIST 0 #endif #if defined(CONFIG_BT_BREDR) #define LINK_DIST BT_SMP_DIST_LINK_KEY #else #define LINK_DIST 0 #endif #define RECV_KEYS (BT_SMP_DIST_ENC_KEY | BT_SMP_DIST_ID_KEY | SIGN_DIST |\ LINK_DIST) #define SEND_KEYS (BT_SMP_DIST_ENC_KEY | ID_DIST | SIGN_DIST | LINK_DIST) #define RECV_KEYS_SC (RECV_KEYS & ~(BT_SMP_DIST_ENC_KEY)) #define SEND_KEYS_SC (SEND_KEYS & ~(BT_SMP_DIST_ENC_KEY)) #define BR_RECV_KEYS_SC (RECV_KEYS & ~(LINK_DIST)) #define BR_SEND_KEYS_SC (SEND_KEYS & ~(LINK_DIST)) #define BT_SMP_AUTH_MASK 0x07 #if defined(CONFIG_BT_BONDABLE) #define BT_SMP_AUTH_BONDING_FLAGS BT_SMP_AUTH_BONDING #else #define BT_SMP_AUTH_BONDING_FLAGS 0 #endif /* CONFIG_BT_BONDABLE */ #if defined(CONFIG_BT_BREDR) #define BT_SMP_AUTH_MASK_SC 0x2f #if defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_CT2) #else #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_CT2 |\ BT_SMP_AUTH_SC) #endif /* CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */ #else #define BT_SMP_AUTH_MASK_SC 0x0f #if defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS) #else #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_SC) #endif /* CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */ #endif /* CONFIG_BT_BREDR */ enum pairing_method { JUST_WORKS, /* JustWorks pairing */ PASSKEY_INPUT, /* Passkey Entry input */ PASSKEY_DISPLAY, /* Passkey Entry display */ PASSKEY_CONFIRM, /* Passkey confirm */ PASSKEY_ROLE, /* Passkey Entry depends on role */ LE_SC_OOB, /* LESC Out of Band */ LEGACY_OOB, /* Legacy Out of Band */ }; enum { SMP_FLAG_CFM_DELAYED, /* if confirm should be send when TK is valid */ SMP_FLAG_ENC_PENDING, /* if waiting for an encryption change event */ SMP_FLAG_KEYS_DISTR, /* if keys distribution phase is in progress */ SMP_FLAG_PAIRING, /* if pairing is in progress */ SMP_FLAG_TIMEOUT, /* if SMP timeout occurred */ SMP_FLAG_SC, /* if LE Secure Connections is used */ SMP_FLAG_PKEY_SEND, /* if should send Public Key when available */ SMP_FLAG_DHKEY_PENDING, /* if waiting for local DHKey */ SMP_FLAG_DHKEY_SEND, /* if should generate and send DHKey Check */ SMP_FLAG_USER, /* if waiting for user input */ SMP_FLAG_DISPLAY, /* if display_passkey() callback was called */ SMP_FLAG_OOB_PENDING, /* if waiting for OOB data */ SMP_FLAG_BOND, /* if bonding */ SMP_FLAG_SC_DEBUG_KEY, /* if Secure Connection are using debug key */ SMP_FLAG_SEC_REQ, /* if Security Request was sent/received */ SMP_FLAG_DHCHECK_WAIT, /* if waiting for remote DHCheck (as slave) */ SMP_FLAG_DERIVE_LK, /* if Link Key should be derived */ SMP_FLAG_BR_CONNECTED, /* if BR/EDR channel is connected */ SMP_FLAG_BR_PAIR, /* if should start BR/EDR pairing */ SMP_FLAG_CT2, /* if should use H7 for keys derivation */ /* Total number of flags - must be at the end */ SMP_NUM_FLAGS, }; /* SMP channel specific context */ struct bt_smp { /* The channel this context is associated with */ struct bt_l2cap_le_chan chan; /* Commands that remote is allowed to send */ atomic_t allowed_cmds; /* Flags for SMP state machine */ ATOMIC_DEFINE(flags, SMP_NUM_FLAGS); /* Type of method used for pairing */ u8_t method; /* Pairing Request PDU */ u8_t preq[7]; /* Pairing Response PDU */ u8_t prsp[7]; /* Pairing Confirm PDU */ u8_t pcnf[16]; /* Local random number */ u8_t prnd[16]; /* Remote random number */ u8_t rrnd[16]; /* Temporary key */ u8_t tk[16]; /* Remote Public Key for LE SC */ u8_t pkey[64]; /* DHKey */ u8_t dhkey[32]; /* Remote DHKey check */ u8_t e[16]; /* MacKey */ u8_t mackey[16]; /* LE SC passkey */ bt_u32_t passkey; /* LE SC passkey round */ u8_t passkey_round; /* LE SC local OOB data */ const struct bt_le_oob_sc_data *oobd_local; /* LE SC remote OOB data */ const struct bt_le_oob_sc_data *oobd_remote; /* Local key distribution */ u8_t local_dist; /* Remote key distribution */ u8_t remote_dist; /* Delayed work for timeout handling */ struct k_delayed_work work; }; static unsigned int fixed_passkey = BT_PASSKEY_INVALID; #define DISPLAY_FIXED(smp) (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && \ fixed_passkey != BT_PASSKEY_INVALID && \ (smp)->method == PASSKEY_DISPLAY) #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) /* based on table 2.8 Core Spec 2.3.5.1 Vol. 3 Part H */ static const u8_t gen_method_legacy[5 /* remote */][5 /* local */] = { { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, PASSKEY_DISPLAY }, { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, PASSKEY_ROLE }, }; #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) /* based on table 2.8 Core Spec 2.3.5.1 Vol. 3 Part H */ static const u8_t gen_method_sc[5 /* remote */][5 /* local */] = { { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS, PASSKEY_CONFIRM }, { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, PASSKEY_DISPLAY }, { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, { PASSKEY_DISPLAY, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS, PASSKEY_CONFIRM }, }; #endif /* !CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */ static const u8_t sc_debug_public_key[64] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc }; #if defined(CONFIG_BT_BREDR) /* SMP over BR/EDR channel specific context */ struct bt_smp_br { /* The channel this context is associated with */ struct bt_l2cap_br_chan chan; /* Commands that remote is allowed to send */ atomic_t allowed_cmds; /* Flags for SMP state machine */ ATOMIC_DEFINE(flags, SMP_NUM_FLAGS); /* Local key distribution */ u8_t local_dist; /* Remote key distribution */ u8_t remote_dist; /* Encryption Key Size used for connection */ u8_t enc_key_size; /* Delayed work for timeout handling */ struct k_delayed_work work; }; static struct bt_smp_br bt_smp_br_pool[CONFIG_BT_MAX_CONN]; #endif /* CONFIG_BT_BREDR */ static struct bt_smp bt_smp_pool[CONFIG_BT_MAX_CONN]; static bool bondable = IS_ENABLED(CONFIG_BT_BONDABLE); static bool oobd_present; static bool sc_supported; static const u8_t *sc_public_key; // static K_SEM_DEFINE(sc_local_pkey_ready, 0, 1); static struct k_sem sc_local_pkey_ready; static u8_t get_io_capa(void) { if (!bt_auth) { goto no_callbacks; } /* Passkey Confirmation is valid only for LE SC */ if (bt_auth->passkey_display && bt_auth->passkey_entry && (bt_auth->passkey_confirm || !sc_supported)) { return BT_SMP_IO_KEYBOARD_DISPLAY; } /* DisplayYesNo is useful only for LE SC */ if (sc_supported && bt_auth->passkey_display && bt_auth->passkey_confirm) { return BT_SMP_IO_DISPLAY_YESNO; } if (bt_auth->passkey_entry) { if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && fixed_passkey != BT_PASSKEY_INVALID) { return BT_SMP_IO_KEYBOARD_DISPLAY; } else { return BT_SMP_IO_KEYBOARD_ONLY; } } if (bt_auth->passkey_display) { return BT_SMP_IO_DISPLAY_ONLY; } no_callbacks: if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && fixed_passkey != BT_PASSKEY_INVALID) { return BT_SMP_IO_DISPLAY_ONLY; } else { return BT_SMP_IO_NO_INPUT_OUTPUT; } } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static u8_t legacy_get_pair_method(struct bt_smp *smp, u8_t remote_io); #endif static bool smp_keys_check(struct bt_conn *conn) { if (atomic_test_bit(conn->flags, BT_CONN_FORCE_PAIR)) { return false; } if (!conn->le.keys) { conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, &conn->le.dst); if (!conn->le.keys) { conn->le.keys = bt_keys_find(BT_KEYS_LTK, conn->id, &conn->le.dst); } } if (!conn->le.keys || !(conn->le.keys->keys & (BT_KEYS_LTK | BT_KEYS_LTK_P256))) { return false; } if (conn->required_sec_level > BT_SECURITY_L2 && !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { return false; } if (conn->required_sec_level > BT_SECURITY_L3 && !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && !(conn->le.keys->keys & BT_KEYS_LTK_P256) && !(conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE)) { return false; } return true; } static u8_t get_pair_method(struct bt_smp *smp, u8_t remote_io) { #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { return legacy_get_pair_method(smp, remote_io); } #endif #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) struct bt_smp_pairing *req, *rsp; req = (struct bt_smp_pairing *)&smp->preq[1]; rsp = (struct bt_smp_pairing *)&smp->prsp[1]; if ((req->auth_req & rsp->auth_req) & BT_SMP_AUTH_SC) { /* if one side has OOB data use OOB */ if ((req->oob_flag | rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) { return LE_SC_OOB; } } if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) { return JUST_WORKS; } /* if none side requires MITM use JustWorks */ if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) { return JUST_WORKS; } return gen_method_sc[remote_io][get_io_capa()]; #else return JUST_WORKS; #endif } static enum bt_security_err auth_err_get(u8_t smp_err) { switch (smp_err) { case BT_SMP_ERR_PASSKEY_ENTRY_FAILED: case BT_SMP_ERR_DHKEY_CHECK_FAILED: case BT_SMP_ERR_NUMERIC_COMP_FAILED: case BT_SMP_ERR_CONFIRM_FAILED: return BT_SECURITY_ERR_AUTH_FAIL; case BT_SMP_ERR_OOB_NOT_AVAIL: return BT_SECURITY_ERR_OOB_NOT_AVAILABLE; case BT_SMP_ERR_AUTH_REQUIREMENTS: case BT_SMP_ERR_ENC_KEY_SIZE: return BT_SECURITY_ERR_AUTH_REQUIREMENT; case BT_SMP_ERR_PAIRING_NOTSUPP: case BT_SMP_ERR_CMD_NOTSUPP: return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED; case BT_SMP_ERR_REPEATED_ATTEMPTS: case BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS: case BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED: return BT_SECURITY_ERR_PAIR_NOT_ALLOWED; case BT_SMP_ERR_INVALID_PARAMS: return BT_SECURITY_ERR_INVALID_PARAM; case BT_SMP_ERR_UNSPECIFIED: default: return BT_SECURITY_ERR_UNSPECIFIED; } } #if defined(CONFIG_BT_SMP_APP_PAIRING_ACCEPT) static u8_t smp_err_get(enum bt_security_err auth_err) { switch (auth_err) { case BT_SECURITY_ERR_OOB_NOT_AVAILABLE: return BT_SMP_ERR_OOB_NOT_AVAIL; case BT_SECURITY_ERR_AUTH_FAIL: case BT_SECURITY_ERR_AUTH_REQUIREMENT: return BT_SMP_ERR_AUTH_REQUIREMENTS; case BT_SECURITY_ERR_PAIR_NOT_SUPPORTED: return BT_SMP_ERR_PAIRING_NOTSUPP; case BT_SECURITY_ERR_INVALID_PARAM: return BT_SMP_ERR_INVALID_PARAMS; case BT_SECURITY_ERR_PIN_OR_KEY_MISSING: case BT_SECURITY_ERR_PAIR_NOT_ALLOWED: case BT_SECURITY_ERR_UNSPECIFIED: return BT_SMP_ERR_UNSPECIFIED; default: return 0; } } #endif /* CONFIG_BT_SMP_APP_PAIRING_ACCEPT */ static struct net_buf *smp_create_pdu(struct bt_smp *smp, u8_t op, size_t len) { struct bt_smp_hdr *hdr; struct net_buf *buf; k_timeout_t timeout; /* Don't if session had already timed out */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { timeout = K_NO_WAIT; } else { timeout = SMP_TIMEOUT; } /* Use smaller timeout if returning an error since that could be * caused by lack of buffers. */ buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout); if (!buf) { /* If it was not possible to allocate a buffer within the * timeout marked it as timed out. */ atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); return NULL; } hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = op; return buf; } /* Cypher based Message Authentication Code (CMAC) with AES 128 bit * * Input : key ( 128-bit key ) * : in ( message to be authenticated ) * : len ( length of the message in octets ) * Output : out ( message authentication code ) */ static int bt_smp_aes_cmac(const u8_t *key, const u8_t *in, size_t len, u8_t *out) { #if !defined(CONFIG_BT_USE_HCI_API) struct tc_aes_key_sched_struct sched; struct tc_cmac_struct state; if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) { return -EIO; } if (tc_cmac_update(&state, in, len) == TC_CRYPTO_FAIL) { return -EIO; } if (tc_cmac_final(out, &state) == TC_CRYPTO_FAIL) { return -EIO; } return 0; #else struct bt_crypto_sg sg; sg.data = in; sg.len = len; return bt_crypto_aes_cmac(key, &sg, 1, out); #endif } static int smp_d1(const u8_t *key, u16_t d, u16_t r, u8_t res[16]) { int err; BT_DBG("key %s d %u r %u", bt_hex(key, 16), d, r); sys_put_le16(d, &res[0]); sys_put_le16(r, &res[2]); memset(&res[4], 0, 16 - 4); err = bt_encrypt_le(key, res, res); if (err) { return err; } BT_DBG("res %s", bt_hex(res, 16)); return 0; } static int smp_f4(const u8_t *u, const u8_t *v, const u8_t *x, u8_t z, u8_t res[16]) { u8_t xs[16]; u8_t m[65]; int err; BT_DBG("u %s", bt_hex(u, 32)); BT_DBG("v %s", bt_hex(v, 32)); BT_DBG("x %s z 0x%x", bt_hex(x, 16), z); /* * U, V and Z are concatenated and used as input m to the function * AES-CMAC and X is used as the key k. * * Core Spec 4.2 Vol 3 Part H 2.2.5 * * note: * bt_smp_aes_cmac uses BE data and smp_f4 accept LE so we swap */ sys_memcpy_swap(m, u, 32); sys_memcpy_swap(m + 32, v, 32); m[64] = z; sys_memcpy_swap(xs, x, 16); err = bt_smp_aes_cmac(xs, m, sizeof(m), res); if (err) { return err; } sys_mem_swap(res, 16); BT_DBG("res %s", bt_hex(res, 16)); return err; } static int smp_f5(const u8_t *w, const u8_t *n1, const u8_t *n2, const bt_addr_le_t *a1, const bt_addr_le_t *a2, u8_t *mackey, u8_t *ltk) { static const u8_t salt[16] = { 0x6c, 0x88, 0x83, 0x91, 0xaa, 0xf5, 0xa5, 0x38, 0x60, 0x37, 0x0b, 0xdb, 0x5a, 0x60, 0x83, 0xbe }; u8_t m[53] = { 0x00, /* counter */ 0x62, 0x74, 0x6c, 0x65, /* keyID */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*n1*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*2*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a1 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a2 */ 0x01, 0x00 /* length */ }; u8_t t[16], ws[32]; int err; BT_DBG("w %s", bt_hex(w, 32)); BT_DBG("n1 %s", bt_hex(n1, 16)); BT_DBG("n2 %s", bt_hex(n2, 16)); sys_memcpy_swap(ws, w, 32); err = bt_smp_aes_cmac(salt, ws, 32, t); if (err) { return err; } BT_DBG("t %s", bt_hex(t, 16)); sys_memcpy_swap(m + 5, n1, 16); sys_memcpy_swap(m + 21, n2, 16); m[37] = a1->type; sys_memcpy_swap(m + 38, a1->a.val, 6); m[44] = a2->type; sys_memcpy_swap(m + 45, a2->a.val, 6); err = bt_smp_aes_cmac(t, m, sizeof(m), mackey); if (err) { return err; } BT_DBG("mackey %1s", bt_hex(mackey, 16)); sys_mem_swap(mackey, 16); /* counter for ltk is 1 */ m[0] = 0x01; err = bt_smp_aes_cmac(t, m, sizeof(m), ltk); if (err) { return err; } BT_DBG("ltk %s", bt_hex(ltk, 16)); sys_mem_swap(ltk, 16); return 0; } static int smp_f6(const u8_t *w, const u8_t *n1, const u8_t *n2, const u8_t *r, const u8_t *iocap, const bt_addr_le_t *a1, const bt_addr_le_t *a2, u8_t *check) { u8_t ws[16]; u8_t m[65]; int err; BT_DBG("w %s", bt_hex(w, 16)); BT_DBG("n1 %s", bt_hex(n1, 16)); BT_DBG("n2 %s", bt_hex(n2, 16)); BT_DBG("r %s", bt_hex(r, 16)); BT_DBG("io_cap %s", bt_hex(iocap, 3)); BT_DBG("a1 %s", bt_hex(a1, 7)); BT_DBG("a2 %s", bt_hex(a2, 7)); sys_memcpy_swap(m, n1, 16); sys_memcpy_swap(m + 16, n2, 16); sys_memcpy_swap(m + 32, r, 16); sys_memcpy_swap(m + 48, iocap, 3); m[51] = a1->type; memcpy(m + 52, a1->a.val, 6); sys_memcpy_swap(m + 52, a1->a.val, 6); m[58] = a2->type; memcpy(m + 59, a2->a.val, 6); sys_memcpy_swap(m + 59, a2->a.val, 6); sys_memcpy_swap(ws, w, 16); err = bt_smp_aes_cmac(ws, m, sizeof(m), check); if (err) { return err; } BT_DBG("res %s", bt_hex(check, 16)); sys_mem_swap(check, 16); return 0; } static int smp_g2(const u8_t u[32], const u8_t v[32], const u8_t x[16], const u8_t y[16], bt_u32_t *passkey) { u8_t m[80], xs[16]; int err; BT_DBG("u %s", bt_hex(u, 32)); BT_DBG("v %s", bt_hex(v, 32)); BT_DBG("x %s", bt_hex(x, 16)); BT_DBG("y %s", bt_hex(y, 16)); sys_memcpy_swap(m, u, 32); sys_memcpy_swap(m + 32, v, 32); sys_memcpy_swap(m + 64, y, 16); sys_memcpy_swap(xs, x, 16); /* reuse xs (key) as buffer for result */ err = bt_smp_aes_cmac(xs, m, sizeof(m), xs); if (err) { return err; } BT_DBG("res %s", bt_hex(xs, 16)); memcpy(passkey, xs + 12, 4); *passkey = sys_be32_to_cpu(*passkey) % 1000000; BT_DBG("passkey %u", *passkey); return 0; } static u8_t get_encryption_key_size(struct bt_smp *smp) { struct bt_smp_pairing *req, *rsp; req = (struct bt_smp_pairing *)&smp->preq[1]; rsp = (struct bt_smp_pairing *)&smp->prsp[1]; /* * The smaller value of the initiating and responding devices maximum * encryption key length parameters shall be used as the encryption key * size. */ return MIN(req->max_key_size, rsp->max_key_size); } /* Check that if a new pairing procedure with an existing bond will not lower * the established security level of the bond. */ static bool update_keys_check(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; if (!conn->le.keys) { conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); } if (IS_ENABLED(CONFIG_BT_SMP_DISABLE_LEGACY_JW_PASSKEY) && !atomic_test_bit(smp->flags, SMP_FLAG_SC) && smp->method != LEGACY_OOB) { return false; } if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) && smp->method != LEGACY_OOB) { return false; } if (!conn->le.keys || !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { return true; } if (conn->le.keys->enc_size > get_encryption_key_size(smp)) { return false; } if ((conn->le.keys->keys & BT_KEYS_LTK_P256) && !atomic_test_bit(smp->flags, SMP_FLAG_SC)) { return false; } if ((conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && smp->method == JUST_WORKS) { return false; } if (!IS_ENABLED(CONFIG_BT_SMP_ALLOW_UNAUTH_OVERWRITE) && (!(conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && smp->method == JUST_WORKS)) { return false; } return true; } static bool update_debug_keys_check(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; if (!conn->le.keys) { conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); } if (!conn->le.keys || !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { return true; } if (conn->le.keys->flags & BT_KEYS_DEBUG) { return false; } return true; } #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_SIGNING) || \ !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) /* For TX callbacks */ static void smp_pairing_complete(struct bt_smp *smp, u8_t status); #if defined(CONFIG_BT_BREDR) static void smp_pairing_br_complete(struct bt_smp_br *smp, u8_t status); #endif static void smp_check_complete(struct bt_conn *conn, u8_t dist_complete) { struct bt_l2cap_chan *chan; if (conn->type == BT_CONN_TYPE_LE) { struct bt_smp *smp; chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_SMP); __ASSERT(chan, "No SMP channel found"); smp = CONTAINER_OF(chan, struct bt_smp, chan); smp->local_dist &= ~dist_complete; /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_complete(smp, 0); } return; } #if defined(CONFIG_BT_BREDR) if (conn->type == BT_CONN_TYPE_BR) { struct bt_smp_br *smp; chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_BR_SMP); __ASSERT(chan, "No SMP channel found"); smp = CONTAINER_OF(chan, struct bt_smp_br, chan); smp->local_dist &= ~dist_complete; /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_br_complete(smp, 0); } } #endif } #endif #if defined(CONFIG_BT_PRIVACY) static void smp_id_sent(struct bt_conn *conn, void *user_data) { smp_check_complete(conn, BT_SMP_DIST_ID_KEY); } #endif /* CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_SIGNING) static void smp_sign_info_sent(struct bt_conn *conn, void *user_data) { smp_check_complete(conn, BT_SMP_DIST_SIGN); } #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_BREDR) static int smp_h6(const u8_t w[16], const u8_t key_id[4], u8_t res[16]) { u8_t ws[16]; u8_t key_id_s[4]; int err; BT_DBG("w %s", bt_hex(w, 16)); BT_DBG("key_id %s", bt_hex(key_id, 4)); sys_memcpy_swap(ws, w, 16); sys_memcpy_swap(key_id_s, key_id, 4); err = bt_smp_aes_cmac(ws, key_id_s, 4, res); if (err) { return err; } BT_DBG("res %s", bt_hex(res, 16)); sys_mem_swap(res, 16); return 0; } static int smp_h7(const u8_t salt[16], const u8_t w[16], u8_t res[16]) { u8_t ws[16]; u8_t salt_s[16]; int err; BT_DBG("w %s", bt_hex(w, 16)); BT_DBG("salt %s", bt_hex(salt, 16)); sys_memcpy_swap(ws, w, 16); sys_memcpy_swap(salt_s, salt, 16); err = bt_smp_aes_cmac(salt_s, ws, 16, res); if (err) { return err; } BT_DBG("res %s", bt_hex(res, 16)); sys_mem_swap(res, 16); return 0; } static void sc_derive_link_key(struct bt_smp *smp) { /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ static const u8_t lebr[4] = { 0x72, 0x62, 0x65, 0x6c }; struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys_link_key *link_key; u8_t ilk[16]; BT_DBG(""); /* TODO handle errors? */ /* * At this point remote device identity is known so we can use * destination address here */ link_key = bt_keys_get_link_key(&conn->le.dst.a); if (!link_key) { return; } if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) { /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ static const u8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (smp_h7(salt, conn->le.keys->ltk.val, ilk)) { bt_keys_link_key_clear(link_key); return; } } else { /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ static const u8_t tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 }; if (smp_h6(conn->le.keys->ltk.val, tmp1, ilk)) { bt_keys_link_key_clear(link_key); return; } } if (smp_h6(ilk, lebr, link_key->val)) { bt_keys_link_key_clear(link_key); } link_key->flags |= BT_LINK_KEY_SC; if (conn->le.keys->flags & BT_KEYS_AUTHENTICATED) { link_key->flags |= BT_LINK_KEY_AUTHENTICATED; } else { link_key->flags &= ~BT_LINK_KEY_AUTHENTICATED; } } static void smp_br_reset(struct bt_smp_br *smp) { k_delayed_work_cancel(&smp->work); atomic_set(smp->flags, 0); atomic_set(&smp->allowed_cmds, 0); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); } static void smp_pairing_br_complete(struct bt_smp_br *smp, u8_t status) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; bt_addr_le_t addr; BT_DBG("status 0x%x", status); /* For dualmode devices LE address is same as BR/EDR address * and is of public type. */ bt_addr_copy(&addr.a, &conn->br.dst); addr.type = BT_ADDR_LE_PUBLIC; keys = bt_keys_find_addr(conn->id, &addr); if (status) { if (keys) { bt_keys_clear(keys); } if (bt_auth && bt_auth->pairing_failed) { bt_auth->pairing_failed(smp->chan.chan.conn, auth_err_get(status)); } } else { bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND); if (bond_flag && keys) { bt_keys_store(keys); } if (bt_auth && bt_auth->pairing_complete) { bt_auth->pairing_complete(smp->chan.chan.conn, bond_flag); } } smp_br_reset(smp); } static void smp_br_timeout(struct k_work *work) { struct bt_smp_br *smp = CONTAINER_OF(work, struct bt_smp_br, work); BT_ERR("SMP Timeout"); smp_pairing_br_complete(smp, BT_SMP_ERR_UNSPECIFIED); atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); } static void smp_br_send(struct bt_smp_br *smp, struct net_buf *buf, bt_conn_tx_cb_t cb) { bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_BR_SMP, buf, cb, NULL); k_delayed_work_submit(&smp->work, SMP_TIMEOUT); } static void bt_smp_br_connected(struct bt_l2cap_chan *chan) { struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); BT_DBG("chan %p cid 0x%04x", chan, CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid); atomic_set_bit(smp->flags, SMP_FLAG_BR_CONNECTED); /* * if this flag is set it means pairing was requested before channel * was connected */ if (atomic_test_bit(smp->flags, SMP_FLAG_BR_PAIR)) { bt_smp_br_send_pairing_req(chan->conn); } } static void bt_smp_br_disconnected(struct bt_l2cap_chan *chan) { struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); BT_DBG("chan %p cid 0x%04x", chan, CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid); k_delayed_work_cancel(&smp->work); (void)memset(smp, 0, sizeof(*smp)); } static void smp_br_init(struct bt_smp_br *smp) { /* Initialize SMP context without clearing L2CAP channel context */ (void)memset((u8_t *)smp + sizeof(smp->chan), 0, sizeof(*smp) - (sizeof(smp->chan) + sizeof(smp->work))); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL); } static void smp_br_derive_ltk(struct bt_smp_br *smp) { /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ static const u8_t brle[4] = { 0x65, 0x6c, 0x72, 0x62 }; struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys_link_key *link_key = conn->br.link_key; struct bt_keys *keys; bt_addr_le_t addr; u8_t ilk[16]; BT_DBG(""); if (!link_key) { return; } if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && conn->encrypt != 0x02) { BT_WARN("Using P192 Link Key for P256 LTK derivation"); } /* * For dualmode devices LE address is same as BR/EDR address and is of * public type. */ bt_addr_copy(&addr.a, &conn->br.dst); addr.type = BT_ADDR_LE_PUBLIC; keys = bt_keys_get_type(BT_KEYS_LTK_P256, conn->id, &addr); if (!keys) { BT_ERR("No keys space for %s", bt_addr_le_str(&addr)); return; } if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) { /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ static const u8_t salt[16] = { 0x32, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (smp_h7(salt, link_key->val, ilk)) { bt_keys_link_key_clear(link_key); return; } } else { /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ static const u8_t tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 }; if (smp_h6(link_key->val, tmp2, ilk)) { bt_keys_clear(keys); return; } } if (smp_h6(ilk, brle, keys->ltk.val)) { bt_keys_clear(keys); return; } (void)memset(keys->ltk.ediv, 0, sizeof(keys->ltk.ediv)); (void)memset(keys->ltk.rand, 0, sizeof(keys->ltk.rand)); keys->enc_size = smp->enc_key_size; if (link_key->flags & BT_LINK_KEY_AUTHENTICATED) { keys->flags |= BT_KEYS_AUTHENTICATED; } else { keys->flags &= ~BT_KEYS_AUTHENTICATED; } BT_DBG("LTK derived from LinkKey"); } static struct net_buf *smp_br_create_pdu(struct bt_smp_br *smp, u8_t op, size_t len) { struct bt_smp_hdr *hdr; struct net_buf *buf; k_timeout_t timeout; /* Don't if session had already timed out */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { timeout = K_NO_WAIT; } else { timeout = SMP_TIMEOUT; } /* Use smaller timeout if returning an error since that could be * caused by lack of buffers. */ buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout); if (!buf) { /* If it was not possible to allocate a buffer within the * timeout marked it as timed out. */ atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); return NULL; } hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = op; return buf; } static void smp_br_distribute_keys(struct bt_smp_br *smp) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; bt_addr_le_t addr; /* * For dualmode devices LE address is same as BR/EDR address and is of * public type. */ bt_addr_copy(&addr.a, &conn->br.dst); addr.type = BT_ADDR_LE_PUBLIC; keys = bt_keys_get_addr(conn->id, &addr); if (!keys) { BT_ERR("No keys space for %s", bt_addr_le_str(&addr)); return; } #if defined(CONFIG_BT_PRIVACY) if (smp->local_dist & BT_SMP_DIST_ID_KEY) { struct bt_smp_ident_info *id_info; struct bt_smp_ident_addr_info *id_addr_info; struct net_buf *buf; smp->local_dist &= ~BT_SMP_DIST_ID_KEY; buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_INFO, sizeof(*id_info)); if (!buf) { BT_ERR("Unable to allocate Ident Info buffer"); return; } id_info = net_buf_add(buf, sizeof(*id_info)); memcpy(id_info->irk, bt_dev.irk[conn->id], 16); smp_br_send(smp, buf, NULL); buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO, sizeof(*id_addr_info)); if (!buf) { BT_ERR("Unable to allocate Ident Addr Info buffer"); return; } id_addr_info = net_buf_add(buf, sizeof(*id_addr_info)); bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]); smp_br_send(smp, buf, smp_id_sent); } #endif /* CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_SIGNING) if (smp->local_dist & BT_SMP_DIST_SIGN) { struct bt_smp_signing_info *info; struct net_buf *buf; smp->local_dist &= ~BT_SMP_DIST_SIGN; buf = smp_br_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO, sizeof(*info)); if (!buf) { BT_ERR("Unable to allocate Signing Info buffer"); return; } info = net_buf_add(buf, sizeof(*info)); bt_rand(info->csrk, sizeof(info->csrk)); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK); memcpy(keys->local_csrk.val, info->csrk, 16); keys->local_csrk.cnt = 0U; } smp_br_send(smp, buf, smp_sign_info_sent); } #endif /* CONFIG_BT_SIGNING */ } static bool smp_br_pairing_allowed(struct bt_smp_br *smp) { if (smp->chan.chan.conn->encrypt == 0x02) { return true; } if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && smp->chan.chan.conn->encrypt == 0x01) { BT_WARN("Allowing BR/EDR SMP with P-192 key"); return true; } return false; } static u8_t smp_br_pairing_req(struct bt_smp_br *smp, struct net_buf *buf) { struct bt_smp_pairing *req = (void *)buf->data; struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_pairing *rsp; struct net_buf *rsp_buf; u8_t max_key_size; BT_DBG(""); /* * If a Pairing Request is received over the BR/EDR transport when * either cross-transport key derivation/generation is not supported or * the BR/EDR transport is not encrypted using a Link Key generated * using P256, a Pairing Failed shall be sent with the error code * "Cross-transport Key Derivation/Generation not allowed" (0x0E)." */ if (!smp_br_pairing_allowed(smp)) { return BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED; } max_key_size = bt_conn_enc_key_size(conn); if (!max_key_size) { return BT_SMP_ERR_UNSPECIFIED; } if (req->max_key_size != max_key_size) { return BT_SMP_ERR_ENC_KEY_SIZE; } rsp_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp)); if (!rsp_buf) { return BT_SMP_ERR_UNSPECIFIED; } smp_br_init(smp); smp->enc_key_size = max_key_size; /* * If Secure Connections pairing has been initiated over BR/EDR, the IO * Capability, OOB data flag and Auth Req fields of the SM Pairing * Request/Response PDU shall be set to zero on transmission, and * ignored on reception. */ rsp = net_buf_add(rsp_buf, sizeof(*rsp)); rsp->auth_req = 0x00; rsp->io_capability = 0x00; rsp->oob_flag = 0x00; rsp->max_key_size = max_key_size; rsp->init_key_dist = (req->init_key_dist & BR_RECV_KEYS_SC); rsp->resp_key_dist = (req->resp_key_dist & BR_RECV_KEYS_SC); smp->local_dist = rsp->resp_key_dist; smp->remote_dist = rsp->init_key_dist; smp_br_send(smp, rsp_buf, NULL); atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); /* derive LTK if requested and clear distribution bits */ if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) && (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) { smp_br_derive_ltk(smp); } smp->local_dist &= ~BT_SMP_DIST_ENC_KEY; smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; /* BR/EDR acceptor is like LE Slave and distributes keys first */ smp_br_distribute_keys(smp); if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_br_complete(smp, 0); } return 0; } static u8_t smp_br_pairing_rsp(struct bt_smp_br *smp, struct net_buf *buf) { struct bt_smp_pairing *rsp = (void *)buf->data; struct bt_conn *conn = smp->chan.chan.conn; u8_t max_key_size; BT_DBG(""); max_key_size = bt_conn_enc_key_size(conn); if (!max_key_size) { return BT_SMP_ERR_UNSPECIFIED; } if (rsp->max_key_size != max_key_size) { return BT_SMP_ERR_ENC_KEY_SIZE; } smp->local_dist &= rsp->init_key_dist; smp->remote_dist &= rsp->resp_key_dist; smp->local_dist &= SEND_KEYS_SC; smp->remote_dist &= RECV_KEYS_SC; /* slave distributes its keys first */ if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } /* derive LTK if requested and clear distribution bits */ if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) && (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) { smp_br_derive_ltk(smp); } smp->local_dist &= ~BT_SMP_DIST_ENC_KEY; smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; /* Pairing acceptor distributes it's keys first */ if (smp->remote_dist) { return 0; } smp_br_distribute_keys(smp); /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_br_complete(smp, 0); } return 0; } static u8_t smp_br_pairing_failed(struct bt_smp_br *smp, struct net_buf *buf) { struct bt_smp_pairing_fail *req = (void *)buf->data; BT_ERR("reason 0x%x", req->reason); smp_pairing_br_complete(smp, req->reason); smp_br_reset(smp); /* return no error to avoid sending Pairing Failed in response */ return 0; } static u8_t smp_br_ident_info(struct bt_smp_br *smp, struct net_buf *buf) { struct bt_smp_ident_info *req = (void *)buf->data; struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; bt_addr_le_t addr; BT_DBG(""); /* TODO should we resolve LE address if matching RPA is connected? */ /* * For dualmode devices LE address is same as BR/EDR address and is of * public type. */ bt_addr_copy(&addr.a, &conn->br.dst); addr.type = BT_ADDR_LE_PUBLIC; keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &addr); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&addr)); return BT_SMP_ERR_UNSPECIFIED; } memcpy(keys->irk.val, req->irk, sizeof(keys->irk.val)); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO); return 0; } static u8_t smp_br_ident_addr_info(struct bt_smp_br *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_ident_addr_info *req = (void *)buf->data; bt_addr_le_t addr; BT_DBG("identity %s", bt_addr_le_str(&req->addr)); /* * For dual mode device identity address must be same as BR/EDR address * and be of public type. So if received one doesn't match BR/EDR * address we fail. */ bt_addr_copy(&addr.a, &conn->br.dst); addr.type = BT_ADDR_LE_PUBLIC; if (bt_addr_le_cmp(&addr, &req->addr)) { return BT_SMP_ERR_UNSPECIFIED; } smp->remote_dist &= ~BT_SMP_DIST_ID_KEY; if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } if (conn->role == BT_CONN_ROLE_MASTER && !smp->remote_dist) { smp_br_distribute_keys(smp); } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_br_complete(smp, 0); } return 0; } #if defined(CONFIG_BT_SIGNING) static u8_t smp_br_signing_info(struct bt_smp_br *smp, struct net_buf *buf) { struct bt_smp_signing_info *req = (void *)buf->data; struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; bt_addr_le_t addr; BT_DBG(""); /* * For dualmode devices LE address is same as BR/EDR address and is of * public type. */ bt_addr_copy(&addr.a, &conn->br.dst); addr.type = BT_ADDR_LE_PUBLIC; keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, &addr); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&addr)); return BT_SMP_ERR_UNSPECIFIED; } memcpy(keys->remote_csrk.val, req->csrk, sizeof(keys->remote_csrk.val)); smp->remote_dist &= ~BT_SMP_DIST_SIGN; if (conn->role == BT_CONN_ROLE_MASTER && !smp->remote_dist) { smp_br_distribute_keys(smp); } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_br_complete(smp, 0); } return 0; } #else static u8_t smp_br_signing_info(struct bt_smp_br *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_SIGNING */ static const struct { u8_t (*func)(struct bt_smp_br *smp, struct net_buf *buf); u8_t expect_len; } br_handlers[] = { { }, /* No op-code defined for 0x00 */ { smp_br_pairing_req, sizeof(struct bt_smp_pairing) }, { smp_br_pairing_rsp, sizeof(struct bt_smp_pairing) }, { }, /* pairing confirm not used over BR/EDR */ { }, /* pairing random not used over BR/EDR */ { smp_br_pairing_failed, sizeof(struct bt_smp_pairing_fail) }, { }, /* encrypt info not used over BR/EDR */ { }, /* master ident not used over BR/EDR */ { smp_br_ident_info, sizeof(struct bt_smp_ident_info) }, { smp_br_ident_addr_info, sizeof(struct bt_smp_ident_addr_info) }, { smp_br_signing_info, sizeof(struct bt_smp_signing_info) }, /* security request not used over BR/EDR */ /* public key not used over BR/EDR */ /* DHKey check not used over BR/EDR */ }; static int smp_br_error(struct bt_smp_br *smp, u8_t reason) { struct bt_smp_pairing_fail *rsp; struct net_buf *buf; /* reset context and report */ smp_br_reset(smp); buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp)); if (!buf) { return -ENOBUFS; } rsp = net_buf_add(buf, sizeof(*rsp)); rsp->reason = reason; /* * SMP timer is not restarted for PairingFailed so don't use * smp_br_send */ bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf); return 0; } static int bt_smp_br_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); struct bt_smp_hdr *hdr; u8_t err; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small SMP PDU received"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len); /* * If SMP timeout occurred "no further SMP commands shall be sent over * the L2CAP Security Manager Channel. A new SM procedure shall only be * performed when a new physical link has been established." */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { BT_WARN("SMP command (code 0x%02x) received after timeout", hdr->code); return 0; } if (hdr->code >= ARRAY_SIZE(br_handlers) || !br_handlers[hdr->code].func) { BT_WARN("Unhandled SMP code 0x%02x", hdr->code); smp_br_error(smp, BT_SMP_ERR_CMD_NOTSUPP); return 0; } if (!atomic_test_and_clear_bit(&smp->allowed_cmds, hdr->code)) { BT_WARN("Unexpected SMP code 0x%02x", hdr->code); smp_br_error(smp, BT_SMP_ERR_UNSPECIFIED); return 0; } if (buf->len != br_handlers[hdr->code].expect_len) { BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); smp_br_error(smp, BT_SMP_ERR_INVALID_PARAMS); return 0; } err = br_handlers[hdr->code].func(smp, buf); if (err) { smp_br_error(smp, err); } return 0; } static bool br_sc_supported(void) { if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR)) { BT_WARN("Enabling BR/EDR SMP without BR/EDR SC support"); return true; } return BT_FEAT_SC(bt_dev.features); } static int bt_smp_br_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { static const struct bt_l2cap_chan_ops ops = { .connected = bt_smp_br_connected, .disconnected = bt_smp_br_disconnected, .recv = bt_smp_br_recv, }; int i; /* Check BR/EDR SC is supported */ if (!br_sc_supported()) { return -ENOTSUP; } BT_DBG("conn %p handle %u", conn, conn->handle); for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { struct bt_smp_br *smp = &bt_smp_br_pool[i]; if (smp->chan.chan.conn) { continue; } smp->chan.chan.ops = &ops; *chan = &smp->chan.chan; k_delayed_work_init(&smp->work, smp_br_timeout); smp_br_reset(smp); return 0; } BT_ERR("No available SMP context for conn %p", conn); return -ENOMEM; } static struct bt_smp_br *smp_br_chan_get(struct bt_conn *conn) { struct bt_l2cap_chan *chan; chan = bt_l2cap_br_lookup_rx_cid(conn, BT_L2CAP_CID_BR_SMP); if (!chan) { BT_ERR("Unable to find SMP channel"); return NULL; } return CONTAINER_OF(chan, struct bt_smp_br, chan); } int bt_smp_br_send_pairing_req(struct bt_conn *conn) { struct bt_smp_pairing *req; struct net_buf *req_buf; u8_t max_key_size; struct bt_smp_br *smp; smp = smp_br_chan_get(conn); if (!smp) { return -ENOTCONN; } /* SMP Timeout */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { return -EIO; } /* pairing is in progress */ if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { return -EBUSY; } /* check if we are allowed to start SMP over BR/EDR */ if (!smp_br_pairing_allowed(smp)) { return 0; } /* Channel not yet connected, will start pairing once connected */ if (!atomic_test_bit(smp->flags, SMP_FLAG_BR_CONNECTED)) { atomic_set_bit(smp->flags, SMP_FLAG_BR_PAIR); return 0; } max_key_size = bt_conn_enc_key_size(conn); if (!max_key_size) { return -EIO; } smp_br_init(smp); smp->enc_key_size = max_key_size; req_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req)); if (!req_buf) { return -ENOBUFS; } req = net_buf_add(req_buf, sizeof(*req)); /* * If Secure Connections pairing has been initiated over BR/EDR, the IO * Capability, OOB data flag and Auth Req fields of the SM Pairing * Request/Response PDU shall be set to zero on transmission, and * ignored on reception. */ req->auth_req = 0x00; req->io_capability = 0x00; req->oob_flag = 0x00; req->max_key_size = max_key_size; req->init_key_dist = BR_SEND_KEYS_SC; req->resp_key_dist = BR_RECV_KEYS_SC; smp_br_send(smp, req_buf, NULL); smp->local_dist = BR_SEND_KEYS_SC; smp->remote_dist = BR_RECV_KEYS_SC; atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP); atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); return 0; } #endif /* CONFIG_BT_BREDR */ static void smp_reset(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; k_delayed_work_cancel(&smp->work); smp->method = JUST_WORKS; atomic_set(&smp->allowed_cmds, 0); atomic_set(smp->flags, 0); if (conn->required_sec_level != conn->sec_level) { /* TODO report error */ /* reset required security level in case of error */ conn->required_sec_level = conn->sec_level; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); return; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); } } /* Note: This function not only does set the status but also calls smp_reset * at the end which clears any flags previously set. */ static void smp_pairing_complete(struct bt_smp *smp, u8_t status) { BT_DBG("status 0x%x", status); if (!status) { #if defined(CONFIG_BT_BREDR) /* * Don't derive if Debug Keys are used. * TODO should we allow this if BR/EDR is already connected? */ if (atomic_test_bit(smp->flags, SMP_FLAG_DERIVE_LK) && (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) || IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS))) { sc_derive_link_key(smp); } #endif /* CONFIG_BT_BREDR */ bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND); if (bond_flag) { bt_keys_store(smp->chan.chan.conn->le.keys); } if (bt_auth && bt_auth->pairing_complete) { bt_auth->pairing_complete(smp->chan.chan.conn, bond_flag); } } else { u8_t auth_err = auth_err_get(status); /* Clear the key pool entry in case of pairing failure if the * keys already existed before the pairing procedure or the * pairing failed during key distribution. */ if (smp->chan.chan.conn->le.keys && (!smp->chan.chan.conn->le.keys->enc_size || atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR))) { bt_keys_clear(smp->chan.chan.conn->le.keys); smp->chan.chan.conn->le.keys = NULL; } if (!atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) { bt_conn_security_changed(smp->chan.chan.conn, auth_err); } if (bt_auth && bt_auth->pairing_failed) { bt_auth->pairing_failed(smp->chan.chan.conn, auth_err); } } smp_reset(smp); } static void smp_timeout(struct k_work *work) { struct bt_smp *smp = CONTAINER_OF(work, struct bt_smp, work); BT_ERR("SMP Timeout"); smp_pairing_complete(smp, BT_SMP_ERR_UNSPECIFIED); /* smp_pairing_complete clears flags so setting timeout flag must come * after it. */ atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); } static void smp_send(struct bt_smp *smp, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) { bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf, cb, NULL); k_delayed_work_submit(&smp->work, SMP_TIMEOUT); } static int smp_error(struct bt_smp *smp, u8_t reason) { struct bt_smp_pairing_fail *rsp; struct net_buf *buf; /* reset context and report */ smp_pairing_complete(smp, reason); buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp)); if (!buf) { return -ENOBUFS; } rsp = net_buf_add(buf, sizeof(*rsp)); rsp->reason = reason; /* SMP timer is not restarted for PairingFailed so don't use smp_send */ bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf); return 0; } static u8_t smp_send_pairing_random(struct bt_smp *smp) { struct bt_smp_pairing_random *req; struct net_buf *rsp_buf; rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RANDOM, sizeof(*req)); if (!rsp_buf) { return BT_SMP_ERR_UNSPECIFIED; } req = net_buf_add(rsp_buf, sizeof(*req)); memcpy(req->val, smp->prnd, sizeof(req->val)); smp_send(smp, rsp_buf, NULL, NULL); return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static void xor_128(const u8_t p[16], const u8_t q[16], u8_t r[16]) { size_t len = 16; while (len--) { *r++ = *p++ ^ *q++; } } static int smp_c1(const u8_t k[16], const u8_t r[16], const u8_t preq[7], const u8_t pres[7], const bt_addr_le_t *ia, const bt_addr_le_t *ra, u8_t enc_data[16]) { u8_t p1[16], p2[16]; int err; BT_DBG("k %s", bt_hex(k, 16)); BT_DBG("r %s", bt_hex(r, 16)); BT_DBG("ia %s", bt_addr_le_str(ia)); BT_DBG("ra %s", bt_addr_le_str(ra)); BT_DBG("preq %s", bt_hex(preq, 7)); BT_DBG("pres %s", bt_hex(pres, 7)); /* pres, preq, rat and iat are concatenated to generate p1 */ p1[0] = ia->type; p1[1] = ra->type; memcpy(p1 + 2, preq, 7); memcpy(p1 + 9, pres, 7); BT_DBG("p1 %s", bt_hex(p1, 16)); /* c1 = e(k, e(k, r XOR p1) XOR p2) */ /* Using enc_data as temporary output buffer */ xor_128(r, p1, enc_data); err = bt_encrypt_le(k, enc_data, enc_data); if (err) { return err; } /* ra is concatenated with ia and padding to generate p2 */ memcpy(p2, ra->a.val, 6); memcpy(p2 + 6, ia->a.val, 6); (void)memset(p2 + 12, 0, 4); BT_DBG("p2 %s", bt_hex(p2, 16)); xor_128(enc_data, p2, enc_data); return bt_encrypt_le(k, enc_data, enc_data); } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ static u8_t smp_send_pairing_confirm(struct bt_smp *smp) { struct bt_smp_pairing_confirm *req; struct net_buf *buf; u8_t r; switch (smp->method) { case PASSKEY_CONFIRM: case JUST_WORKS: r = 0U; break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: /* * In the Passkey Entry protocol, the most significant * bit of Z is set equal to one and the least * significant bit is made up from one bit of the * passkey e.g. if the passkey bit is 1, then Z = 0x81 * and if the passkey bit is 0, then Z = 0x80. */ r = (smp->passkey >> smp->passkey_round) & 0x01; r |= 0x80; break; default: return BT_SMP_ERR_UNSPECIFIED; } buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req)); if (!buf) { return BT_SMP_ERR_UNSPECIFIED; } req = net_buf_add(buf, sizeof(*req)); if (smp_f4(sc_public_key, smp->pkey, smp->prnd, r, req->val)) { net_buf_unref(buf); return BT_SMP_ERR_UNSPECIFIED; } smp_send(smp, buf, NULL, NULL); atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED); return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static void smp_ident_sent(struct bt_conn *conn, void *user_data) { smp_check_complete(conn, BT_SMP_DIST_ENC_KEY); } static void legacy_distribute_keys(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys = conn->le.keys; if (smp->local_dist & BT_SMP_DIST_ENC_KEY) { struct bt_smp_encrypt_info *info; struct bt_smp_master_ident *ident; struct net_buf *buf; /* Use struct to get randomness in single call to bt_rand */ struct { u8_t key[16]; u8_t rand[8]; u8_t ediv[2]; } rand; bt_rand((void *)&rand, sizeof(rand)); buf = smp_create_pdu(smp, BT_SMP_CMD_ENCRYPT_INFO, sizeof(*info)); if (!buf) { BT_ERR("Unable to allocate Encrypt Info buffer"); return; } info = net_buf_add(buf, sizeof(*info)); /* distributed only enc_size bytes of key */ memcpy(info->ltk, rand.key, keys->enc_size); if (keys->enc_size < sizeof(info->ltk)) { (void)memset(info->ltk + keys->enc_size, 0, sizeof(info->ltk) - keys->enc_size); } smp_send(smp, buf, NULL, NULL); buf = smp_create_pdu(smp, BT_SMP_CMD_MASTER_IDENT, sizeof(*ident)); if (!buf) { BT_ERR("Unable to allocate Master Ident buffer"); return; } ident = net_buf_add(buf, sizeof(*ident)); memcpy(ident->rand, rand.rand, sizeof(ident->rand)); memcpy(ident->ediv, rand.ediv, sizeof(ident->ediv)); smp_send(smp, buf, smp_ident_sent, NULL); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { bt_keys_add_type(keys, BT_KEYS_SLAVE_LTK); memcpy(keys->slave_ltk.val, rand.key, sizeof(keys->slave_ltk.val)); memcpy(keys->slave_ltk.rand, rand.rand, sizeof(keys->slave_ltk.rand)); memcpy(keys->slave_ltk.ediv, rand.ediv, sizeof(keys->slave_ltk.ediv)); } } } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ static u8_t bt_smp_distribute_keys(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys = conn->le.keys; if (!keys) { BT_ERR("No keys space for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_UNSPECIFIED; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) /* Distribute legacy pairing specific keys */ if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { legacy_distribute_keys(smp); } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ #if defined(CONFIG_BT_PRIVACY) if (smp->local_dist & BT_SMP_DIST_ID_KEY) { struct bt_smp_ident_info *id_info; struct bt_smp_ident_addr_info *id_addr_info; struct net_buf *buf; buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_INFO, sizeof(*id_info)); if (!buf) { BT_ERR("Unable to allocate Ident Info buffer"); return BT_SMP_ERR_UNSPECIFIED; } id_info = net_buf_add(buf, sizeof(*id_info)); memcpy(id_info->irk, bt_dev.irk[conn->id], 16); smp_send(smp, buf, NULL, NULL); buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO, sizeof(*id_addr_info)); if (!buf) { BT_ERR("Unable to allocate Ident Addr Info buffer"); return BT_SMP_ERR_UNSPECIFIED; } id_addr_info = net_buf_add(buf, sizeof(*id_addr_info)); bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]); smp_send(smp, buf, smp_id_sent, NULL); } #endif /* CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_SIGNING) if (smp->local_dist & BT_SMP_DIST_SIGN) { struct bt_smp_signing_info *info; struct net_buf *buf; buf = smp_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO, sizeof(*info)); if (!buf) { BT_ERR("Unable to allocate Signing Info buffer"); return BT_SMP_ERR_UNSPECIFIED; } info = net_buf_add(buf, sizeof(*info)); bt_rand(info->csrk, sizeof(info->csrk)); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK); memcpy(keys->local_csrk.val, info->csrk, 16); keys->local_csrk.cnt = 0U; } smp_send(smp, buf, smp_sign_info_sent, NULL); } #endif /* CONFIG_BT_SIGNING */ return 0; } #if defined(CONFIG_BT_PERIPHERAL) static u8_t send_pairing_rsp(struct bt_smp *smp) { struct bt_smp_pairing *rsp; struct net_buf *rsp_buf; rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp)); if (!rsp_buf) { return BT_SMP_ERR_UNSPECIFIED; } rsp = net_buf_add(rsp_buf, sizeof(*rsp)); memcpy(rsp, smp->prsp + 1, sizeof(*rsp)); smp_send(smp, rsp_buf, NULL, NULL); return 0; } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t smp_pairing_accept_query(struct bt_conn *conn, struct bt_smp_pairing *pairing) { #if defined(CONFIG_BT_SMP_APP_PAIRING_ACCEPT) if (bt_auth && bt_auth->pairing_accept) { const struct bt_conn_pairing_feat feat = { .io_capability = pairing->io_capability, .oob_data_flag = pairing->oob_flag, .auth_req = pairing->auth_req, .max_enc_key_size = pairing->max_key_size, .init_key_dist = pairing->init_key_dist, .resp_key_dist = pairing->resp_key_dist }; return smp_err_get(bt_auth->pairing_accept(conn, &feat)); } #endif /* CONFIG_BT_SMP_APP_PAIRING_ACCEPT */ return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static int smp_s1(const u8_t k[16], const u8_t r1[16], const u8_t r2[16], u8_t out[16]) { /* The most significant 64-bits of r1 are discarded to generate * r1' and the most significant 64-bits of r2 are discarded to * generate r2'. * r1' is concatenated with r2' to generate r' which is used as * the 128-bit input parameter plaintextData to security function e: * * r' = r1' || r2' */ memcpy(out, r2, 8); memcpy(out + 8, r1, 8); /* s1(k, r1 , r2) = e(k, r') */ return bt_encrypt_le(k, out, out); } static u8_t legacy_get_pair_method(struct bt_smp *smp, u8_t remote_io) { struct bt_smp_pairing *req, *rsp; u8_t method; if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) { return JUST_WORKS; } req = (struct bt_smp_pairing *)&smp->preq[1]; rsp = (struct bt_smp_pairing *)&smp->prsp[1]; /* if both sides have OOB data use OOB */ if ((req->oob_flag & rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) { return LEGACY_OOB; } /* if none side requires MITM use JustWorks */ if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) { return JUST_WORKS; } method = gen_method_legacy[remote_io][get_io_capa()]; /* if both sides have KeyboardDisplay capabilities, initiator displays * and responder inputs */ if (method == PASSKEY_ROLE) { if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { method = PASSKEY_DISPLAY; } else { method = PASSKEY_INPUT; } } return method; } static u8_t legacy_request_tk(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; bt_u32_t passkey; /* * Fail if we have keys that are stronger than keys that will be * distributed in new pairing. This is to avoid replacing authenticated * keys with unauthenticated ones. */ keys = bt_keys_find_addr(conn->id, &conn->le.dst); if (keys && (keys->flags & BT_KEYS_AUTHENTICATED) && smp->method == JUST_WORKS) { BT_ERR("JustWorks failed, authenticated keys present"); return BT_SMP_ERR_UNSPECIFIED; } switch (smp->method) { case LEGACY_OOB: if (bt_auth && bt_auth->oob_data_request) { struct bt_conn_oob_info info = { .type = BT_CONN_OOB_LE_LEGACY, }; atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->oob_data_request(smp->chan.chan.conn, &info); } else { return BT_SMP_ERR_OOB_NOT_AVAIL; } break; case PASSKEY_DISPLAY: if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && fixed_passkey != BT_PASSKEY_INVALID) { passkey = fixed_passkey; } else { if (bt_rand(&passkey, sizeof(passkey))) { return BT_SMP_ERR_UNSPECIFIED; } passkey %= 1000000; } if (bt_auth && bt_auth->passkey_display) { atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY); bt_auth->passkey_display(conn, passkey); } sys_put_le32(passkey, smp->tk); break; case PASSKEY_INPUT: atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->passkey_entry(conn); break; case JUST_WORKS: break; default: BT_ERR("Unknown pairing method (%u)", smp->method); return BT_SMP_ERR_UNSPECIFIED; } return 0; } static u8_t legacy_send_pairing_confirm(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_pairing_confirm *req; struct net_buf *buf; buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req)); if (!buf) { return BT_SMP_ERR_UNSPECIFIED; } req = net_buf_add(buf, sizeof(*req)); if (smp_c1(smp->tk, smp->prnd, smp->preq, smp->prsp, &conn->le.init_addr, &conn->le.resp_addr, req->val)) { net_buf_unref(buf); return BT_SMP_ERR_UNSPECIFIED; } smp_send(smp, buf, NULL, NULL); atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED); return 0; } #if defined(CONFIG_BT_PERIPHERAL) static u8_t legacy_pairing_req(struct bt_smp *smp) { u8_t ret; BT_DBG(""); /* ask for consent if pairing is not due to sending SecReq*/ if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && bt_auth && bt_auth->pairing_confirm) { atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->pairing_confirm(smp->chan.chan.conn); return 0; } ret = send_pairing_rsp(smp); if (ret) { return ret; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return legacy_request_tk(smp); } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t legacy_pairing_random(struct bt_smp *smp) { struct bt_conn *conn = smp->chan.chan.conn; u8_t tmp[16]; int err; BT_DBG(""); /* calculate confirmation */ err = smp_c1(smp->tk, smp->rrnd, smp->preq, smp->prsp, &conn->le.init_addr, &conn->le.resp_addr, tmp); if (err) { return BT_SMP_ERR_UNSPECIFIED; } BT_DBG("pcnf %s", bt_hex(smp->pcnf, 16)); BT_DBG("cfm %s", bt_hex(tmp, 16)); if (memcmp(smp->pcnf, tmp, sizeof(smp->pcnf))) { return BT_SMP_ERR_CONFIRM_FAILED; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER) { u8_t ediv[2], rand[8]; /* No need to store master STK */ err = smp_s1(smp->tk, smp->rrnd, smp->prnd, tmp); if (err) { return BT_SMP_ERR_UNSPECIFIED; } /* Rand and EDiv are 0 for the STK */ (void)memset(ediv, 0, sizeof(ediv)); (void)memset(rand, 0, sizeof(rand)); if (bt_conn_le_start_encryption(conn, rand, ediv, tmp, get_encryption_key_size(smp))) { BT_ERR("Failed to start encryption"); return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) { if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_ENCRYPT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } } return 0; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { err = smp_s1(smp->tk, smp->prnd, smp->rrnd, tmp); if (err) { return BT_SMP_ERR_UNSPECIFIED; } memcpy(smp->tk, tmp, sizeof(smp->tk)); BT_DBG("generated STK %s", bt_hex(smp->tk, 16)); atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); return smp_send_pairing_random(smp); } return 0; } static u8_t legacy_pairing_confirm(struct bt_smp *smp) { BT_DBG(""); if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return legacy_send_pairing_confirm(smp); } if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); return legacy_send_pairing_confirm(smp); } atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); } return 0; } static void legacy_user_tk_entry(struct bt_smp *smp) { if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) { return; } /* if confirm failed ie. due to invalid passkey, cancel pairing */ if (legacy_pairing_confirm(smp)) { smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); return; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); } } static void legacy_passkey_entry(struct bt_smp *smp, unsigned int passkey) { passkey = sys_cpu_to_le32(passkey); memcpy(smp->tk, &passkey, sizeof(passkey)); legacy_user_tk_entry(smp); } static u8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf) { BT_DBG(""); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { struct bt_smp_encrypt_info *req = (void *)buf->data; struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_UNSPECIFIED; } memcpy(keys->ltk.val, req->ltk, 16); } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_MASTER_IDENT); return 0; } static u8_t smp_master_ident(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; u8_t err; BT_DBG(""); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { struct bt_smp_master_ident *req = (void *)buf->data; struct bt_keys *keys; keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_UNSPECIFIED; } memcpy(keys->ltk.ediv, req->ediv, sizeof(keys->ltk.ediv)); memcpy(keys->ltk.rand, req->rand, sizeof(req->rand)); smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; } if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { err = bt_smp_distribute_keys(smp); if (err) { return err; } } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_complete(smp, 0); } return 0; } #if defined(CONFIG_BT_CENTRAL) static u8_t legacy_pairing_rsp(struct bt_smp *smp) { u8_t ret; BT_DBG(""); /* ask for consent if this is due to received SecReq */ if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && bt_auth && bt_auth->pairing_confirm) { atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->pairing_confirm(smp->chan.chan.conn); return 0; } ret = legacy_request_tk(smp); if (ret) { return ret; } if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return legacy_send_pairing_confirm(smp); } atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); return 0; } #endif /* CONFIG_BT_CENTRAL */ #else static u8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } static u8_t smp_master_ident(struct bt_smp *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ static int smp_init(struct bt_smp *smp) { /* Initialize SMP context without clearing L2CAP channel context */ (void)memset((u8_t *)smp + sizeof(smp->chan), 0, sizeof(*smp) - (sizeof(smp->chan) + sizeof(smp->work))); /* Generate local random number */ if (bt_rand(smp->prnd, 16)) { return BT_SMP_ERR_UNSPECIFIED; } BT_DBG("prnd %s", bt_hex(smp->prnd, 16)); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL); #if defined(CONFIG_BT_ECC) #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) sc_public_key = bt_pub_key_get(); #endif #endif return 0; } void bt_set_bondable(bool enable) { bondable = enable; } void bt_set_oob_data_flag(bool enable) { oobd_present = enable; } static u8_t get_auth(struct bt_conn *conn, u8_t auth) { if (sc_supported) { auth &= BT_SMP_AUTH_MASK_SC; } else { auth &= BT_SMP_AUTH_MASK; } if ((get_io_capa() == BT_SMP_IO_NO_INPUT_OUTPUT) || (!IS_ENABLED(CONFIG_BT_SMP_ENFORCE_MITM) && (conn->required_sec_level < BT_SECURITY_L3))) { auth &= ~(BT_SMP_AUTH_MITM); } else { auth |= BT_SMP_AUTH_MITM; } if (bondable) { auth |= BT_SMP_AUTH_BONDING; } else { auth &= ~BT_SMP_AUTH_BONDING; } return auth; } static bool sec_level_reachable(struct bt_conn *conn) { switch (conn->required_sec_level) { case BT_SECURITY_L1: case BT_SECURITY_L2: return true; case BT_SECURITY_L3: return get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT || (bt_auth && bt_auth->oob_data_request); case BT_SECURITY_L4: return (get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT || (bt_auth && bt_auth->oob_data_request)) && sc_supported; default: return false; } } static struct bt_smp *smp_chan_get(struct bt_conn *conn) { struct bt_l2cap_chan *chan; chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_SMP); if (!chan) { BT_ERR("Unable to find SMP channel"); return NULL; } return CONTAINER_OF(chan, struct bt_smp, chan); } bool bt_smp_request_ltk(struct bt_conn *conn, u64_t rand, u16_t ediv, u8_t *ltk) { struct bt_smp *smp; u8_t enc_size; smp = smp_chan_get(conn); if (!smp) { return false; } /* * Both legacy STK and LE SC LTK have rand and ediv equal to zero. * If pairing is in progress use the TK for encryption. */ if (ediv == 0U && rand == 0U && atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) && atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { enc_size = get_encryption_key_size(smp); /* * We keep both legacy STK and LE SC LTK in TK. * Also use only enc_size bytes of key for encryption. */ memcpy(ltk, smp->tk, enc_size); if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { (void)memset(ltk + enc_size, 0, BT_SMP_MAX_ENC_KEY_SIZE - enc_size); } atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); return true; } if (!conn->le.keys) { conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, &conn->le.dst); if (!conn->le.keys) { conn->le.keys = bt_keys_find(BT_KEYS_SLAVE_LTK, conn->id, &conn->le.dst); } } if (ediv == 0U && rand == 0U && conn->le.keys && (conn->le.keys->keys & BT_KEYS_LTK_P256)) { enc_size = conn->le.keys->enc_size; memcpy(ltk, conn->le.keys->ltk.val, enc_size); if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { (void)memset(ltk + enc_size, 0, BT_SMP_MAX_ENC_KEY_SIZE - enc_size); } return true; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) if (conn->le.keys && (conn->le.keys->keys & BT_KEYS_SLAVE_LTK) && !memcmp(conn->le.keys->slave_ltk.rand, &rand, 8) && !memcmp(conn->le.keys->slave_ltk.ediv, &ediv, 2)) { enc_size = conn->le.keys->enc_size; memcpy(ltk, conn->le.keys->slave_ltk.val, enc_size); if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { (void)memset(ltk + enc_size, 0, BT_SMP_MAX_ENC_KEY_SIZE - enc_size); } atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); return true; } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ if (atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) { /* Notify higher level that security failed if security was * initiated by slave. */ bt_conn_security_changed(smp->chan.chan.conn, BT_SECURITY_ERR_PIN_OR_KEY_MISSING); } smp_reset(smp); return false; } #if defined(CONFIG_BT_PERIPHERAL) static int smp_send_security_req(struct bt_conn *conn) { struct bt_smp *smp; struct bt_smp_security_request *req; struct net_buf *req_buf; BT_DBG(""); smp = smp_chan_get(conn); if (!smp) { return -ENOTCONN; } /* SMP Timeout */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { return -EIO; } /* pairing is in progress */ if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { return -EBUSY; } if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { return -EBUSY; } /* early verify if required sec level if reachable */ if (!(sec_level_reachable(conn) || smp_keys_check(conn))) { return -EINVAL; } if (!conn->le.keys) { conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); if (!conn->le.keys) { return -ENOMEM; } } if (smp_init(smp) != 0) { return -ENOBUFS; } req_buf = smp_create_pdu(smp, BT_SMP_CMD_SECURITY_REQUEST, sizeof(*req)); if (!req_buf) { return -ENOBUFS; } req = net_buf_add(req_buf, sizeof(*req)); req->auth_req = get_auth(conn, BT_SMP_AUTH_DEFAULT); /* SMP timer is not restarted for SecRequest so don't use smp_send */ bt_l2cap_send(conn, BT_L2CAP_CID_SMP, req_buf); atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); return 0; } static u8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_pairing *req = (void *)buf->data; struct bt_smp_pairing *rsp; BT_DBG(""); if ((req->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) || (req->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) { return BT_SMP_ERR_ENC_KEY_SIZE; } if (!conn->le.keys) { conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); if (!conn->le.keys) { return BT_SMP_ERR_UNSPECIFIED; } } /* If we already sent a security request then the SMP context * is already initialized. */ if (!atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) { int ret = smp_init(smp); if (ret) { return ret; } } /* Store req for later use */ smp->preq[0] = BT_SMP_CMD_PAIRING_REQ; memcpy(smp->preq + 1, req, sizeof(*req)); /* create rsp, it will be used later on */ smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP; rsp = (struct bt_smp_pairing *)&smp->prsp[1]; rsp->auth_req = get_auth(conn, req->auth_req); rsp->io_capability = get_io_capa(); rsp->oob_flag = oobd_present ? BT_SMP_OOB_PRESENT : BT_SMP_OOB_NOT_PRESENT; rsp->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE; rsp->init_key_dist = (req->init_key_dist & RECV_KEYS); rsp->resp_key_dist = (req->resp_key_dist & SEND_KEYS); if ((rsp->auth_req & BT_SMP_AUTH_SC) && (req->auth_req & BT_SMP_AUTH_SC)) { atomic_set_bit(smp->flags, SMP_FLAG_SC); rsp->init_key_dist &= RECV_KEYS_SC; rsp->resp_key_dist &= SEND_KEYS_SC; } if ((rsp->auth_req & BT_SMP_AUTH_CT2) && (req->auth_req & BT_SMP_AUTH_CT2)) { atomic_set_bit(smp->flags, SMP_FLAG_CT2); } smp->local_dist = rsp->resp_key_dist; smp->remote_dist = rsp->init_key_dist; if ((rsp->auth_req & BT_SMP_AUTH_BONDING) && (req->auth_req & BT_SMP_AUTH_BONDING)) { atomic_set_bit(smp->flags, SMP_FLAG_BOND); } else if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED)) { /* Reject pairing req if not both intend to bond */ return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); smp->method = get_pair_method(smp, req->io_capability); if (!update_keys_check(smp)) { return BT_SMP_ERR_AUTH_REQUIREMENTS; } if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY) return BT_SMP_ERR_AUTH_REQUIREMENTS; #else if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) { u8_t err; err = smp_pairing_accept_query(smp->chan.chan.conn, req); if (err) { return err; } } return legacy_pairing_req(smp); #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ } if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || conn->required_sec_level == BT_SECURITY_L4) && smp->method == JUST_WORKS) { return BT_SMP_ERR_AUTH_REQUIREMENTS; } if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || conn->required_sec_level == BT_SECURITY_L4) && get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) { return BT_SMP_ERR_ENC_KEY_SIZE; } if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) { u8_t err; err = smp_pairing_accept_query(smp->chan.chan.conn, req); if (err) { return err; } } if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && bt_auth && bt_auth->pairing_confirm) { atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->pairing_confirm(smp->chan.chan.conn); return 0; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); return send_pairing_rsp(smp); } #else static u8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t sc_send_public_key(struct bt_smp *smp) { struct bt_smp_public_key *req; struct net_buf *req_buf; req_buf = smp_create_pdu(smp, BT_SMP_CMD_PUBLIC_KEY, sizeof(*req)); if (!req_buf) { return BT_SMP_ERR_UNSPECIFIED; } req = net_buf_add(req_buf, sizeof(*req)); memcpy(req->x, sc_public_key, sizeof(req->x)); memcpy(req->y, &sc_public_key[32], sizeof(req->y)); smp_send(smp, req_buf, NULL, NULL); if (IS_ENABLED(CONFIG_BT_USE_DEBUG_KEYS)) { atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY); } return 0; } #if defined(CONFIG_BT_CENTRAL) static int smp_send_pairing_req(struct bt_conn *conn) { struct bt_smp *smp; struct bt_smp_pairing *req; struct net_buf *req_buf; BT_DBG(""); smp = smp_chan_get(conn); if (!smp) { return -ENOTCONN; } /* SMP Timeout */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { return -EIO; } /* pairing is in progress */ if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { return -EBUSY; } /* Encryption is in progress */ if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { return -EBUSY; } /* early verify if required sec level if reachable */ if (!sec_level_reachable(conn)) { return -EINVAL; } if (!conn->le.keys) { conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); if (!conn->le.keys) { return -ENOMEM; } } if (smp_init(smp)) { return -ENOBUFS; } req_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req)); if (!req_buf) { return -ENOBUFS; } req = net_buf_add(req_buf, sizeof(*req)); req->auth_req = get_auth(conn, BT_SMP_AUTH_DEFAULT); req->io_capability = get_io_capa(); req->oob_flag = oobd_present ? BT_SMP_OOB_PRESENT : BT_SMP_OOB_NOT_PRESENT; req->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE; req->init_key_dist = SEND_KEYS; req->resp_key_dist = RECV_KEYS; smp->local_dist = SEND_KEYS; smp->remote_dist = RECV_KEYS; /* Store req for later use */ smp->preq[0] = BT_SMP_CMD_PAIRING_REQ; memcpy(smp->preq + 1, req, sizeof(*req)); smp_send(smp, req_buf, NULL, NULL); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP); atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); return 0; } static u8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_pairing *rsp = (void *)buf->data; struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1]; BT_DBG(""); if ((rsp->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) || (rsp->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) { return BT_SMP_ERR_ENC_KEY_SIZE; } smp->local_dist &= rsp->init_key_dist; smp->remote_dist &= rsp->resp_key_dist; /* Store rsp for later use */ smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP; memcpy(smp->prsp + 1, rsp, sizeof(*rsp)); if ((rsp->auth_req & BT_SMP_AUTH_SC) && (req->auth_req & BT_SMP_AUTH_SC)) { atomic_set_bit(smp->flags, SMP_FLAG_SC); } if ((rsp->auth_req & BT_SMP_AUTH_CT2) && (req->auth_req & BT_SMP_AUTH_CT2)) { atomic_set_bit(smp->flags, SMP_FLAG_CT2); } if ((rsp->auth_req & BT_SMP_AUTH_BONDING) && (req->auth_req & BT_SMP_AUTH_BONDING)) { atomic_set_bit(smp->flags, SMP_FLAG_BOND); } else if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED)) { /* Reject pairing req if not both intend to bond */ return BT_SMP_ERR_UNSPECIFIED; } smp->method = get_pair_method(smp, rsp->io_capability); if (!update_keys_check(smp)) { return BT_SMP_ERR_AUTH_REQUIREMENTS; } if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY) return BT_SMP_ERR_AUTH_REQUIREMENTS; #else if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) { u8_t err; err = smp_pairing_accept_query(smp->chan.chan.conn, rsp); if (err) { return err; } } return legacy_pairing_rsp(smp); #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ } if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || conn->required_sec_level == BT_SECURITY_L4) && smp->method == JUST_WORKS) { return BT_SMP_ERR_AUTH_REQUIREMENTS; } if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || conn->required_sec_level == BT_SECURITY_L4) && get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) { return BT_SMP_ERR_ENC_KEY_SIZE; } smp->local_dist &= SEND_KEYS_SC; smp->remote_dist &= RECV_KEYS_SC; if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) { u8_t err; err = smp_pairing_accept_query(smp->chan.chan.conn, rsp); if (err) { return err; } } if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && bt_auth && bt_auth->pairing_confirm) { atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->pairing_confirm(smp->chan.chan.conn); return 0; } if (!sc_public_key) { atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); return 0; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); atomic_clear_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); return sc_send_public_key(smp); } #else static u8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_CENTRAL */ static u8_t smp_pairing_confirm(struct bt_smp *smp, struct net_buf *buf) { struct bt_smp_pairing_confirm *req = (void *)buf->data; BT_DBG(""); atomic_clear_bit(smp->flags, SMP_FLAG_DISPLAY); memcpy(smp->pcnf, req->val, sizeof(smp->pcnf)); if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); return smp_send_pairing_random(smp); } if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) { return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { return legacy_pairing_confirm(smp); } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ switch (smp->method) { case PASSKEY_DISPLAY: atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); return smp_send_pairing_confirm(smp); case PASSKEY_INPUT: if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); return 0; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); return smp_send_pairing_confirm(smp); case JUST_WORKS: case PASSKEY_CONFIRM: default: return BT_SMP_ERR_UNSPECIFIED; } } static u8_t sc_smp_send_dhkey_check(struct bt_smp *smp, const u8_t *e) { struct bt_smp_dhkey_check *req; struct net_buf *buf; BT_DBG(""); buf = smp_create_pdu(smp, BT_SMP_DHKEY_CHECK, sizeof(*req)); if (!buf) { return BT_SMP_ERR_UNSPECIFIED; } req = net_buf_add(buf, sizeof(*req)); memcpy(req->e, e, sizeof(req->e)); smp_send(smp, buf, NULL, NULL); return 0; } #if defined(CONFIG_BT_CENTRAL) static u8_t compute_and_send_master_dhcheck(struct bt_smp *smp) { u8_t e[16], r[16]; (void)memset(r, 0, sizeof(r)); switch (smp->method) { case JUST_WORKS: case PASSKEY_CONFIRM: break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: memcpy(r, &smp->passkey, sizeof(smp->passkey)); break; case LE_SC_OOB: if (smp->oobd_remote) { memcpy(r, smp->oobd_remote->r, sizeof(r)); } break; default: return BT_SMP_ERR_UNSPECIFIED; } /* calculate LTK and mackey */ if (smp_f5(smp->dhkey, smp->prnd, smp->rrnd, &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr, smp->mackey, smp->tk)) { return BT_SMP_ERR_UNSPECIFIED; } /* calculate local DHKey check */ if (smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->preq[1], &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr, e)) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); return sc_smp_send_dhkey_check(smp, e); } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) static u8_t compute_and_check_and_send_slave_dhcheck(struct bt_smp *smp) { u8_t re[16], e[16], r[16]; u8_t err; (void)memset(r, 0, sizeof(r)); switch (smp->method) { case JUST_WORKS: case PASSKEY_CONFIRM: break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: memcpy(r, &smp->passkey, sizeof(smp->passkey)); break; case LE_SC_OOB: if (smp->oobd_remote) { memcpy(r, smp->oobd_remote->r, sizeof(r)); } break; default: return BT_SMP_ERR_UNSPECIFIED; } /* calculate LTK and mackey */ if (smp_f5(smp->dhkey, smp->rrnd, smp->prnd, &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr, smp->mackey, smp->tk)) { return BT_SMP_ERR_UNSPECIFIED; } /* calculate local DHKey check */ if (smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->prsp[1], &smp->chan.chan.conn->le.resp_addr, &smp->chan.chan.conn->le.init_addr, e)) { return BT_SMP_ERR_UNSPECIFIED; } if (smp->method == LE_SC_OOB) { if (smp->oobd_local) { memcpy(r, smp->oobd_local->r, sizeof(r)); } else { memset(r, 0, sizeof(r)); } } /* calculate remote DHKey check */ if (smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->preq[1], &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr, re)) { return BT_SMP_ERR_UNSPECIFIED; } /* compare received E with calculated remote */ if (memcmp(smp->e, re, 16)) { return BT_SMP_ERR_DHKEY_CHECK_FAILED; } /* send local e */ err = sc_smp_send_dhkey_check(smp, e); if (err) { return err; } atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); return 0; } #endif /* CONFIG_BT_PERIPHERAL */ static void bt_smp_dhkey_ready(const u8_t *dhkey) { struct bt_smp *smp = NULL; int i; BT_DBG("%p", dhkey); for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { if (atomic_test_and_clear_bit(bt_smp_pool[i].flags, SMP_FLAG_DHKEY_PENDING)) { smp = &bt_smp_pool[i]; break; } } if (!smp) { return; } if (!dhkey) { smp_error(smp, BT_SMP_ERR_DHKEY_CHECK_FAILED); return; } memcpy(smp->dhkey, dhkey, 32); /* wait for user passkey confirmation */ if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return; } /* wait for remote DHKey Check */ if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return; } if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) { u8_t err; #if defined(CONFIG_BT_CENTRAL) if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { err = compute_and_send_master_dhcheck(smp); if (err) { smp_error(smp, err); } return; } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) err = compute_and_check_and_send_slave_dhcheck(smp); if (err) { smp_error(smp, err); } #endif /* CONFIG_BT_PERIPHERAL */ } } static u8_t sc_smp_check_confirm(struct bt_smp *smp) { u8_t cfm[16]; u8_t r; switch (smp->method) { case LE_SC_OOB: return 0; case PASSKEY_CONFIRM: case JUST_WORKS: r = 0U; break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: /* * In the Passkey Entry protocol, the most significant * bit of Z is set equal to one and the least * significant bit is made up from one bit of the * passkey e.g. if the passkey bit is 1, then Z = 0x81 * and if the passkey bit is 0, then Z = 0x80. */ r = (smp->passkey >> smp->passkey_round) & 0x01; r |= 0x80; break; default: return BT_SMP_ERR_UNSPECIFIED; } if (smp_f4(smp->pkey, sc_public_key, smp->rrnd, r, cfm)) { return BT_SMP_ERR_UNSPECIFIED; } BT_DBG("pcnf %s", bt_hex(smp->pcnf, 16)); BT_DBG("cfm %s", bt_hex(cfm, 16)); if (memcmp(smp->pcnf, cfm, 16)) { return BT_SMP_ERR_CONFIRM_FAILED; } return 0; } static bool le_sc_oob_data_req_check(struct bt_smp *smp) { struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1]; return ((req->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT); } static bool le_sc_oob_data_rsp_check(struct bt_smp *smp) { struct bt_smp_pairing *rsp = (struct bt_smp_pairing *)&smp->prsp[1]; return ((rsp->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT); } static void le_sc_oob_config_set(struct bt_smp *smp, struct bt_conn_oob_info *info) { bool req_oob_present = le_sc_oob_data_req_check(smp); bool rsp_oob_present = le_sc_oob_data_rsp_check(smp); int oob_config = BT_CONN_OOB_NO_DATA; if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { oob_config = req_oob_present ? BT_CONN_OOB_REMOTE_ONLY : BT_CONN_OOB_NO_DATA; if (rsp_oob_present) { oob_config = (oob_config == BT_CONN_OOB_REMOTE_ONLY) ? BT_CONN_OOB_BOTH_PEERS : BT_CONN_OOB_LOCAL_ONLY; } } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { oob_config = req_oob_present ? BT_CONN_OOB_LOCAL_ONLY : BT_CONN_OOB_NO_DATA; if (rsp_oob_present) { oob_config = (oob_config == BT_CONN_OOB_LOCAL_ONLY) ? BT_CONN_OOB_BOTH_PEERS : BT_CONN_OOB_REMOTE_ONLY; } } info->lesc.oob_config = oob_config; } static u8_t smp_pairing_random(struct bt_smp *smp, struct net_buf *buf) { struct bt_smp_pairing_random *req = (void *)buf->data; bt_u32_t passkey; u8_t err; BT_DBG(""); memcpy(smp->rrnd, req->val, sizeof(smp->rrnd)); #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { return legacy_pairing_random(smp); } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ #if defined(CONFIG_BT_CENTRAL) if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { err = sc_smp_check_confirm(smp); if (err) { return err; } switch (smp->method) { case PASSKEY_CONFIRM: /* compare passkey before calculating LTK */ if (smp_g2(sc_public_key, smp->pkey, smp->prnd, smp->rrnd, &passkey)) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_USER); atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); bt_auth->passkey_confirm(smp->chan.chan.conn, passkey); return 0; case JUST_WORKS: break; case LE_SC_OOB: break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: smp->passkey_round++; if (smp->passkey_round == 20U) { break; } if (bt_rand(smp->prnd, 16)) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return smp_send_pairing_confirm(smp); default: return BT_SMP_ERR_UNSPECIFIED; } /* wait for DHKey being generated */ if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return 0; } return compute_and_send_master_dhcheck(smp); } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) switch (smp->method) { case PASSKEY_CONFIRM: if (smp_g2(smp->pkey, sc_public_key, smp->rrnd, smp->prnd, &passkey)) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->passkey_confirm(smp->chan.chan.conn, passkey); break; case JUST_WORKS: break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: err = sc_smp_check_confirm(smp); if (err) { return err; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); err = smp_send_pairing_random(smp); if (err) { return err; } smp->passkey_round++; if (smp->passkey_round == 20U) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); return 0; } if (bt_rand(smp->prnd, 16)) { return BT_SMP_ERR_UNSPECIFIED; } return 0; case LE_SC_OOB: /* Step 6: Select random N */ if (bt_rand(smp->prnd, 16)) { return BT_SMP_ERR_UNSPECIFIED; } if (bt_auth && bt_auth->oob_data_request) { struct bt_conn_oob_info info = { .type = BT_CONN_OOB_LE_SC, .lesc.oob_config = BT_CONN_OOB_NO_DATA, }; le_sc_oob_config_set(smp, &info); smp->oobd_local = NULL; smp->oobd_remote = NULL; atomic_set_bit(smp->flags, SMP_FLAG_OOB_PENDING); bt_auth->oob_data_request(smp->chan.chan.conn, &info); return 0; } else { return BT_SMP_ERR_OOB_NOT_AVAIL; } default: return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); return smp_send_pairing_random(smp); #else return BT_SMP_ERR_PAIRING_NOTSUPP; #endif /* CONFIG_BT_PERIPHERAL */ } static u8_t smp_pairing_failed(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_pairing_fail *req = (void *)buf->data; BT_ERR("reason 0x%x", req->reason); if (atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER) || atomic_test_and_clear_bit(smp->flags, SMP_FLAG_DISPLAY)) { if (bt_auth && bt_auth->cancel) { bt_auth->cancel(conn); } } smp_pairing_complete(smp, req->reason); /* return no error to avoid sending Pairing Failed in response */ return 0; } static u8_t smp_ident_info(struct bt_smp *smp, struct net_buf *buf) { BT_DBG(""); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { struct bt_smp_ident_info *req = (void *)buf->data; struct bt_conn *conn = smp->chan.chan.conn; struct bt_keys *keys; keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_UNSPECIFIED; } memcpy(keys->irk.val, req->irk, 16); } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO); return 0; } static u8_t smp_ident_addr_info(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_ident_addr_info *req = (void *)buf->data; u8_t err; BT_DBG("identity %s", bt_addr_le_str(&req->addr)); if (!bt_addr_le_is_identity(&req->addr)) { BT_ERR("Invalid identity %s", bt_addr_le_str(&req->addr)); BT_ERR(" for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_INVALID_PARAMS; } if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { const bt_addr_le_t *dst; struct bt_keys *keys; keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_UNSPECIFIED; } /* * We can't use conn->dst here as this might already contain * identity address known from previous pairing. Since all keys * are cleared on re-pairing we wouldn't store IRK distributed * in new pairing. */ if (conn->role == BT_HCI_ROLE_MASTER) { dst = &conn->le.resp_addr; } else { dst = &conn->le.init_addr; } if (bt_addr_le_is_rpa(dst)) { /* always update last use RPA */ bt_addr_copy(&keys->irk.rpa, &dst->a); /* * Update connection address and notify about identity * resolved only if connection wasn't already reported * with identity address. This may happen if IRK was * present before ie. due to re-pairing. */ if (!bt_addr_le_is_identity(&conn->le.dst)) { bt_addr_le_copy(&keys->addr, &req->addr); bt_addr_le_copy(&conn->le.dst, &req->addr); bt_conn_identity_resolved(conn); } } bt_id_add(keys); } smp->remote_dist &= ~BT_SMP_DIST_ID_KEY; if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { err = bt_smp_distribute_keys(smp); if (err) { return err; } } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_complete(smp, 0); } return 0; } #if defined(CONFIG_BT_SIGNING) static u8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; u8_t err; BT_DBG(""); if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { struct bt_smp_signing_info *req = (void *)buf->data; struct bt_keys *keys; keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst)); return BT_SMP_ERR_UNSPECIFIED; } memcpy(keys->remote_csrk.val, req->csrk, sizeof(keys->remote_csrk.val)); } smp->remote_dist &= ~BT_SMP_DIST_SIGN; if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { err = bt_smp_distribute_keys(smp); if (err) { return err; } } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_complete(smp, 0); } return 0; } #else static u8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_CENTRAL) static u8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf) { struct bt_conn *conn = smp->chan.chan.conn; struct bt_smp_security_request *req = (void *)buf->data; u8_t auth; BT_DBG(""); if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { /* We have already started pairing process */ return 0; } if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { /* We have already started encryption procedure */ return 0; } if (sc_supported) { auth = req->auth_req & BT_SMP_AUTH_MASK_SC; } else { auth = req->auth_req & BT_SMP_AUTH_MASK; } if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED) && !(bondable && (auth & BT_SMP_AUTH_BONDING))) { /* Reject security req if not both intend to bond */ return BT_SMP_ERR_UNSPECIFIED; } if (conn->le.keys) { /* Make sure we have an LTK to encrypt with */ if (!(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { goto pair; } } else { conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, &conn->le.dst); if (!conn->le.keys) { conn->le.keys = bt_keys_find(BT_KEYS_LTK, conn->id, &conn->le.dst); } } if (!conn->le.keys) { goto pair; } /* if MITM required key must be authenticated */ if ((auth & BT_SMP_AUTH_MITM) && !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { if (get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT) { BT_INFO("New auth requirements: 0x%x, repairing", auth); goto pair; } BT_WARN("Unsupported auth requirements: 0x%x, repairing", auth); goto pair; } /* if LE SC required and no p256 key present repair */ if ((auth & BT_SMP_AUTH_SC) && !(conn->le.keys->keys & BT_KEYS_LTK_P256)) { BT_INFO("New auth requirements: 0x%x, repairing", auth); goto pair; } if (bt_conn_le_start_encryption(conn, conn->le.keys->ltk.rand, conn->le.keys->ltk.ediv, conn->le.keys->ltk.val, conn->le.keys->enc_size) < 0) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); return 0; pair: if (smp_send_pairing_req(conn) < 0) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ); return 0; } #else static u8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf) { return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_CENTRAL */ static u8_t generate_dhkey(struct bt_smp *smp) { if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) { return BT_SMP_ERR_UNSPECIFIED; } if (bt_dh_key_gen(smp->pkey, bt_smp_dhkey_ready)) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_PENDING); return 0; } static u8_t display_passkey(struct bt_smp *smp) { if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && fixed_passkey != BT_PASSKEY_INVALID) { smp->passkey = fixed_passkey; } else { if (bt_rand(&smp->passkey, sizeof(smp->passkey))) { return BT_SMP_ERR_UNSPECIFIED; } smp->passkey %= 1000000; } smp->passkey_round = 0U; if (bt_auth && bt_auth->passkey_display) { atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY); bt_auth->passkey_display(smp->chan.chan.conn, smp->passkey); } smp->passkey = sys_cpu_to_le32(smp->passkey); return 0; } #if defined(CONFIG_BT_PERIPHERAL) static u8_t smp_public_key_slave(struct bt_smp *smp) { u8_t err; err = sc_send_public_key(smp); if (err) { return err; } switch (smp->method) { case PASSKEY_CONFIRM: case JUST_WORKS: atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); err = smp_send_pairing_confirm(smp); if (err) { return err; } break; case PASSKEY_DISPLAY: err = display_passkey(smp); if (err) { return err; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); break; case PASSKEY_INPUT: atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->passkey_entry(smp->chan.chan.conn); break; case LE_SC_OOB: atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); break; default: return BT_SMP_ERR_UNSPECIFIED; } return generate_dhkey(smp); } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t smp_public_key(struct bt_smp *smp, struct net_buf *buf) { struct bt_smp_public_key *req = (void *)buf->data; u8_t err; BT_DBG(""); memcpy(smp->pkey, req->x, 32); memcpy(&smp->pkey[32], req->y, 32); /* mark key as debug if remote is using it */ if (memcmp(smp->pkey, sc_debug_public_key, 64) == 0) { BT_INFO("Remote is using Debug Public key"); atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY); /* Don't allow a bond established without debug key to be * updated using LTK generated from debug key. */ if (!update_debug_keys_check(smp)) { return BT_SMP_ERR_AUTH_REQUIREMENTS; } } if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { switch (smp->method) { case PASSKEY_CONFIRM: case JUST_WORKS: atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); break; case PASSKEY_DISPLAY: err = display_passkey(smp); if (err) { return err; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); err = smp_send_pairing_confirm(smp); if (err) { return err; } break; case PASSKEY_INPUT: atomic_set_bit(smp->flags, SMP_FLAG_USER); bt_auth->passkey_entry(smp->chan.chan.conn); break; case LE_SC_OOB: /* Step 6: Select random N */ if (bt_rand(smp->prnd, 16)) { return BT_SMP_ERR_UNSPECIFIED; } if (bt_auth && bt_auth->oob_data_request) { struct bt_conn_oob_info info = { .type = BT_CONN_OOB_LE_SC, .lesc.oob_config = BT_CONN_OOB_NO_DATA, }; le_sc_oob_config_set(smp, &info); smp->oobd_local = NULL; smp->oobd_remote = NULL; atomic_set_bit(smp->flags, SMP_FLAG_OOB_PENDING); bt_auth->oob_data_request(smp->chan.chan.conn, &info); } else { return BT_SMP_ERR_OOB_NOT_AVAIL; } break; default: return BT_SMP_ERR_UNSPECIFIED; } return generate_dhkey(smp); } #if defined(CONFIG_BT_PERIPHERAL) if (!sc_public_key) { atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); return 0; } err = smp_public_key_slave(smp); if (err) { return err; } #endif /* CONFIG_BT_PERIPHERAL */ return 0; } static u8_t smp_dhkey_check(struct bt_smp *smp, struct net_buf *buf) { struct bt_smp_dhkey_check *req = (void *)buf->data; BT_DBG(""); if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { u8_t e[16], r[16], enc_size; u8_t ediv[2], rand[8]; (void)memset(r, 0, sizeof(r)); switch (smp->method) { case JUST_WORKS: case PASSKEY_CONFIRM: break; case PASSKEY_DISPLAY: case PASSKEY_INPUT: memcpy(r, &smp->passkey, sizeof(smp->passkey)); break; case LE_SC_OOB: if (smp->oobd_local) { memcpy(r, smp->oobd_local->r, sizeof(r)); } break; default: return BT_SMP_ERR_UNSPECIFIED; } /* calculate remote DHKey check for comparison */ if (smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->prsp[1], &smp->chan.chan.conn->le.resp_addr, &smp->chan.chan.conn->le.init_addr, e)) { return BT_SMP_ERR_UNSPECIFIED; } if (memcmp(e, req->e, 16)) { return BT_SMP_ERR_DHKEY_CHECK_FAILED; } enc_size = get_encryption_key_size(smp); /* Rand and EDiv are 0 */ (void)memset(ediv, 0, sizeof(ediv)); (void)memset(rand, 0, sizeof(rand)); if (bt_conn_le_start_encryption(smp->chan.chan.conn, rand, ediv, smp->tk, enc_size) < 0) { return BT_SMP_ERR_UNSPECIFIED; } atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) { if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } } return 0; } #if defined(CONFIG_BT_PERIPHERAL) if (smp->chan.chan.conn->role == BT_HCI_ROLE_SLAVE) { atomic_clear_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); memcpy(smp->e, req->e, sizeof(smp->e)); /* wait for DHKey being generated */ if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return 0; } /* waiting for user to confirm passkey */ if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return 0; } return compute_and_check_and_send_slave_dhcheck(smp); } #endif /* CONFIG_BT_PERIPHERAL */ return 0; } static const struct { u8_t (*func)(struct bt_smp *smp, struct net_buf *buf); u8_t expect_len; } handlers[] = { { }, /* No op-code defined for 0x00 */ { smp_pairing_req, sizeof(struct bt_smp_pairing) }, { smp_pairing_rsp, sizeof(struct bt_smp_pairing) }, { smp_pairing_confirm, sizeof(struct bt_smp_pairing_confirm) }, { smp_pairing_random, sizeof(struct bt_smp_pairing_random) }, { smp_pairing_failed, sizeof(struct bt_smp_pairing_fail) }, { smp_encrypt_info, sizeof(struct bt_smp_encrypt_info) }, { smp_master_ident, sizeof(struct bt_smp_master_ident) }, { smp_ident_info, sizeof(struct bt_smp_ident_info) }, { smp_ident_addr_info, sizeof(struct bt_smp_ident_addr_info) }, { smp_signing_info, sizeof(struct bt_smp_signing_info) }, { smp_security_request, sizeof(struct bt_smp_security_request) }, #if defined(CONFIG_BT_ECC) { smp_public_key, sizeof(struct bt_smp_public_key) }, { smp_dhkey_check, sizeof(struct bt_smp_dhkey_check) }, #endif }; static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); struct bt_smp_hdr *hdr; u8_t err; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small SMP PDU received"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); BT_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len); /* * If SMP timeout occurred "no further SMP commands shall be sent over * the L2CAP Security Manager Channel. A new SM procedure shall only be * performed when a new physical link has been established." */ if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { BT_WARN("SMP command (code 0x%02x) received after timeout", hdr->code); return 0; } if (hdr->code >= ARRAY_SIZE(handlers) || !handlers[hdr->code].func) { BT_WARN("Unhandled SMP code 0x%02x", hdr->code); smp_error(smp, BT_SMP_ERR_CMD_NOTSUPP); return 0; } if (!atomic_test_and_clear_bit(&smp->allowed_cmds, hdr->code)) { BT_WARN("Unexpected SMP code 0x%02x", hdr->code); /* Don't send error responses to error PDUs */ if (hdr->code != BT_SMP_CMD_PAIRING_FAIL) { smp_error(smp, BT_SMP_ERR_UNSPECIFIED); } return 0; } if (buf->len != handlers[hdr->code].expect_len) { BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); smp_error(smp, BT_SMP_ERR_INVALID_PARAMS); return 0; } err = handlers[hdr->code].func(smp, buf); if (err) { smp_error(smp, err); } return 0; } static void bt_smp_pkey_ready(const u8_t *pkey) { int i; BT_DBG(""); sc_public_key = pkey; if (!pkey) { BT_WARN("Public key not available"); return; } k_sem_init(&sc_local_pkey_ready, 0, 1); k_sem_give(&sc_local_pkey_ready); for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { struct bt_smp *smp = &bt_smp_pool[i]; u8_t err; if (!atomic_test_bit(smp->flags, SMP_FLAG_PKEY_SEND)) { continue; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { err = sc_send_public_key(smp); if (err) { smp_error(smp, err); } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); continue; } #if defined(CONFIG_BT_PERIPHERAL) err = smp_public_key_slave(smp); if (err) { smp_error(smp, err); } #endif /* CONFIG_BT_PERIPHERAL */ } } static void bt_smp_connected(struct bt_l2cap_chan *chan) { struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); BT_DBG("chan %p cid 0x%04x", chan, CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid); k_delayed_work_init(&smp->work, smp_timeout); smp_reset(smp); } static void bt_smp_disconnected(struct bt_l2cap_chan *chan) { struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); struct bt_keys *keys = chan->conn->le.keys; BT_DBG("chan %p cid 0x%04x", chan, CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid); k_delayed_work_cancel(&smp->work); if (keys) { /* * If debug keys were used for pairing remove them. * No keys indicate no bonding so free keys storage. */ if (!keys->keys || (!IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS) && (keys->flags & BT_KEYS_DEBUG))) { bt_keys_clear(keys); } } (void)memset(smp, 0, sizeof(*smp)); } static void bt_smp_encrypt_change(struct bt_l2cap_chan *chan, u8_t hci_status) { struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); struct bt_conn *conn = chan->conn; BT_DBG("chan %p conn %p handle %u encrypt 0x%02x hci status 0x%02x", chan, conn, conn->handle, conn->encrypt, hci_status); atomic_clear_bit(smp->flags, SMP_FLAG_ENC_PENDING); if (hci_status) { return; } if (!conn->encrypt) { return; } /* We were waiting for encryption but with no pairing in progress. * This can happen if paired slave sent Security Request and we * enabled encryption. */ if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { smp_reset(smp); return; } /* derive BR/EDR LinkKey if supported by both sides */ if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) { if ((smp->local_dist & BT_SMP_DIST_LINK_KEY) && (smp->remote_dist & BT_SMP_DIST_LINK_KEY)) { /* * Link Key will be derived after key distribution to * make sure remote device identity is known */ atomic_set_bit(smp->flags, SMP_FLAG_DERIVE_LK); } /* * Those are used as pairing finished indicator so generated * but not distributed keys must be cleared here. */ smp->local_dist &= ~BT_SMP_DIST_LINK_KEY; smp->remote_dist &= ~BT_SMP_DIST_LINK_KEY; } if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_ENCRYPT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); } if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_PRIVACY) && !(smp->remote_dist & BT_SMP_DIST_ID_KEY)) { /* To resolve directed advertising we need our local IRK * in the controllers resolving list, add it now since the * peer has no identity key. */ bt_id_add(conn->le.keys); } atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR); /* Slave distributes it's keys first */ if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER && smp->remote_dist) { return; } if (IS_ENABLED(CONFIG_BT_TESTING)) { /* Avoid the HCI-USB race condition where HCI data and * HCI events can be re-ordered, and pairing information appears * to be sent unencrypted. */ k_sleep(K_MSEC(100)); } if (bt_smp_distribute_keys(smp)) { return; } /* if all keys were distributed, pairing is done */ if (!smp->local_dist && !smp->remote_dist) { smp_pairing_complete(smp, 0); } } #if defined(CONFIG_BT_SIGNING) || defined(CONFIG_BT_SMP_SELFTEST) /* Sign message using msg as a buffer, len is a size of the message, * msg buffer contains message itself, 32 bit count and signature, * so total buffer size is len + 4 + 8 octets. * API is Little Endian to make it suitable for Bluetooth. */ static int smp_sign_buf(const u8_t *key, u8_t *msg, u16_t len) { u8_t *m = msg; bt_u32_t cnt = UNALIGNED_GET((bt_u32_t *)&msg[len]); u8_t *sig = msg + len; u8_t key_s[16], tmp[16]; int err; BT_DBG("Signing msg %s len %u key %s", bt_hex(msg, len), len, bt_hex(key, 16)); sys_mem_swap(m, len + sizeof(cnt)); sys_memcpy_swap(key_s, key, 16); err = bt_smp_aes_cmac(key_s, m, len + sizeof(cnt), tmp); if (err) { BT_ERR("Data signing failed"); return err; } sys_mem_swap(tmp, sizeof(tmp)); memcpy(tmp + 4, &cnt, sizeof(cnt)); /* Swap original message back */ sys_mem_swap(m, len + sizeof(cnt)); memcpy(sig, tmp + 4, 12); BT_DBG("sig %s", bt_hex(sig, 12)); return 0; } #endif #if defined(CONFIG_BT_SIGNING) int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { struct bt_keys *keys; u8_t sig[12]; bt_u32_t cnt; int err; /* Store signature incl. count */ memcpy(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig)); keys = bt_keys_find(BT_KEYS_REMOTE_CSRK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to find Remote CSRK for %s", bt_addr_le_str(&conn->le.dst)); return -ENOENT; } /* Copy signing count */ cnt = sys_cpu_to_le32(keys->remote_csrk.cnt); memcpy(net_buf_tail(buf) - sizeof(sig), &cnt, sizeof(cnt)); BT_DBG("Sign data len %zu key %s count %u", buf->len - sizeof(sig), bt_hex(keys->remote_csrk.val, 16), keys->remote_csrk.cnt); err = smp_sign_buf(keys->remote_csrk.val, buf->data, buf->len - sizeof(sig)); if (err) { BT_ERR("Unable to create signature for %s", bt_addr_le_str(&conn->le.dst)); return -EIO; }; if (memcmp(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig))) { BT_ERR("Unable to verify signature for %s", bt_addr_le_str(&conn->le.dst)); return -EBADMSG; }; keys->remote_csrk.cnt++; return 0; } int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { struct bt_keys *keys; bt_u32_t cnt; int err; keys = bt_keys_find(BT_KEYS_LOCAL_CSRK, conn->id, &conn->le.dst); if (!keys) { BT_ERR("Unable to find local CSRK for %s", bt_addr_le_str(&conn->le.dst)); return -ENOENT; } /* Reserve space for data signature */ net_buf_add(buf, 12); /* Copy signing count */ cnt = sys_cpu_to_le32(keys->local_csrk.cnt); memcpy(net_buf_tail(buf) - 12, &cnt, sizeof(cnt)); BT_DBG("Sign data len %u key %s count %u", buf->len, bt_hex(keys->local_csrk.val, 16), keys->local_csrk.cnt); err = smp_sign_buf(keys->local_csrk.val, buf->data, buf->len - 12); if (err) { BT_ERR("Unable to create signature for %s", bt_addr_le_str(&conn->le.dst)); return -EIO; } keys->local_csrk.cnt++; return 0; } #else int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; } int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; } #endif /* CONFIG_BT_SIGNING */ int bt_smp_irk_get(u8_t *ir, u8_t *irk) { u8_t invalid_ir[16] = { 0 }; if (!memcmp(ir, invalid_ir, 16)) { return -EINVAL; } return smp_d1(ir, 1, 0, irk); } #if defined(CONFIG_BT_SMP_SELFTEST) /* Test vectors are taken from RFC 4493 * https://tools.ietf.org/html/rfc4493 * Same mentioned in the Bluetooth Spec. */ static const u8_t key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; static const u8_t M[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }; static int aes_test(const char *prefix, const u8_t *key, const u8_t *m, u16_t len, const u8_t *mac) { u8_t out[16]; BT_DBG("%s: AES CMAC of message with len %u", prefix, len); bt_smp_aes_cmac(key, m, len, out); if (!memcmp(out, mac, 16)) { BT_DBG("%s: Success", prefix); } else { BT_ERR("%s: Failed", prefix); return -1; } return 0; } static int smp_aes_cmac_test(void) { u8_t mac1[] = { 0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46 }; u8_t mac2[] = { 0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c }; u8_t mac3[] = { 0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27 }; u8_t mac4[] = { 0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe }; int err; err = aes_test("Test aes-cmac0", key, M, 0, mac1); if (err) { return err; } err = aes_test("Test aes-cmac16", key, M, 16, mac2); if (err) { return err; } err = aes_test("Test aes-cmac40", key, M, 40, mac3); if (err) { return err; } err = aes_test("Test aes-cmac64", key, M, 64, mac4); if (err) { return err; } return 0; } static int sign_test(const char *prefix, const u8_t *key, const u8_t *m, u16_t len, const u8_t *sig) { u8_t msg[len + sizeof(bt_u32_t) + 8]; u8_t orig[len + sizeof(bt_u32_t) + 8]; u8_t *out = msg + len; int err; BT_DBG("%s: Sign message with len %u", prefix, len); (void)memset(msg, 0, sizeof(msg)); memcpy(msg, m, len); (void)memset(msg + len, 0, sizeof(bt_u32_t)); memcpy(orig, msg, sizeof(msg)); err = smp_sign_buf(key, msg, len); if (err) { return err; } /* Check original message */ if (!memcmp(msg, orig, len + sizeof(bt_u32_t))) { BT_DBG("%s: Original message intact", prefix); } else { BT_ERR("%s: Original message modified", prefix); BT_DBG("%s: orig %s", prefix, bt_hex(orig, sizeof(orig))); BT_DBG("%s: msg %s", prefix, bt_hex(msg, sizeof(msg))); return -1; } if (!memcmp(out, sig, 12)) { BT_DBG("%s: Success", prefix); } else { BT_ERR("%s: Failed", prefix); return -1; } return 0; } static int smp_sign_test(void) { const u8_t sig1[] = { 0x00, 0x00, 0x00, 0x00, 0xb3, 0xa8, 0x59, 0x41, 0x27, 0xeb, 0xc2, 0xc0 }; const u8_t sig2[] = { 0x00, 0x00, 0x00, 0x00, 0x27, 0x39, 0x74, 0xf4, 0x39, 0x2a, 0x23, 0x2a }; const u8_t sig3[] = { 0x00, 0x00, 0x00, 0x00, 0xb7, 0xca, 0x94, 0xab, 0x87, 0xc7, 0x82, 0x18 }; const u8_t sig4[] = { 0x00, 0x00, 0x00, 0x00, 0x44, 0xe1, 0xe6, 0xce, 0x1d, 0xf5, 0x13, 0x68 }; u8_t key_s[16]; int err; /* Use the same key as aes-cmac but swap bytes */ sys_memcpy_swap(key_s, key, 16); err = sign_test("Test sign0", key_s, M, 0, sig1); if (err) { return err; } err = sign_test("Test sign16", key_s, M, 16, sig2); if (err) { return err; } err = sign_test("Test sign40", key_s, M, 40, sig3); if (err) { return err; } err = sign_test("Test sign64", key_s, M, 64, sig4); if (err) { return err; } return 0; } static int smp_f4_test(void) { u8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 }; u8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b, 0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59, 0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90, 0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 }; u8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; u8_t z = 0x00; u8_t exp[16] = { 0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1, 0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 }; u8_t res[16]; int err; err = smp_f4(u, v, x, z, res); if (err) { return err; } if (memcmp(res, exp, 16)) { return -EINVAL; } return 0; } static int smp_f5_test(void) { u8_t w[32] = { 0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86, 0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99, 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; u8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; u8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; bt_addr_le_t a1 = { .type = 0x00, .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } }; bt_addr_le_t a2 = { .type = 0x00, .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } }; u8_t exp_ltk[16] = { 0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05, 0x98, 0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79, 0x86, 0x69 }; u8_t exp_mackey[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd, 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 }; u8_t mackey[16], ltk[16]; int err; err = smp_f5(w, n1, n2, &a1, &a2, mackey, ltk); if (err) { return err; } if (memcmp(mackey, exp_mackey, 16) || memcmp(ltk, exp_ltk, 16)) { return -EINVAL; } return 0; } static int smp_f6_test(void) { u8_t w[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd, 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 }; u8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; u8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; u8_t r[16] = { 0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08, 0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 }; u8_t io_cap[3] = { 0x02, 0x01, 0x01 }; bt_addr_le_t a1 = { .type = 0x00, .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } }; bt_addr_le_t a2 = { .type = 0x00, .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } }; u8_t exp[16] = { 0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2, 0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 }; u8_t res[16]; int err; err = smp_f6(w, n1, n2, r, io_cap, &a1, &a2, res); if (err) return err; if (memcmp(res, exp, 16)) return -EINVAL; return 0; } static int smp_g2_test(void) { u8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 }; u8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b, 0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59, 0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90, 0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 }; u8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; u8_t y[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; bt_u32_t exp_val = 0x2f9ed5ba % 1000000; bt_u32_t val; int err; err = smp_g2(u, v, x, y, &val); if (err) { return err; } if (val != exp_val) { return -EINVAL; } return 0; } #if defined(CONFIG_BT_BREDR) static int smp_h6_test(void) { u8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; u8_t key_id[4] = { 0x72, 0x62, 0x65, 0x6c }; u8_t exp_res[16] = { 0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8, 0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d}; u8_t res[16]; int err; err = smp_h6(w, key_id, res); if (err) { return err; } if (memcmp(res, exp_res, 16)) { return -EINVAL; } return 0; } static int smp_h7_test(void) { u8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; u8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; u8_t exp_res[16] = { 0x11, 0x70, 0xa5, 0x75, 0x2a, 0x8c, 0x99, 0xd2, 0xec, 0xc0, 0xa3, 0xc6, 0x97, 0x35, 0x17, 0xfb}; u8_t res[16]; int err; err = smp_h7(salt, w, res); if (err) { return err; } if (memcmp(res, exp_res, 16)) { return -EINVAL; } return 0; } #endif /* CONFIG_BT_BREDR */ static int smp_self_test(void) { int err; err = smp_aes_cmac_test(); if (err) { BT_ERR("SMP AES-CMAC self tests failed"); return err; } err = smp_sign_test(); if (err) { BT_ERR("SMP signing self tests failed"); return err; } err = smp_f4_test(); if (err) { BT_ERR("SMP f4 self test failed"); return err; } err = smp_f5_test(); if (err) { BT_ERR("SMP f5 self test failed"); return err; } err = smp_f6_test(); if (err) { BT_ERR("SMP f6 self test failed"); return err; } err = smp_g2_test(); if (err) { BT_ERR("SMP g2 self test failed"); return err; } #if defined(CONFIG_BT_BREDR) err = smp_h6_test(); if (err) { BT_ERR("SMP h6 self test failed"); return err; } err = smp_h7_test(); if (err) { BT_ERR("SMP h7 self test failed"); return err; } #endif /* CONFIG_BT_BREDR */ return 0; } #else static inline int smp_self_test(void) { return 0; } #endif int bt_smp_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey) { struct bt_smp *smp; u8_t err; smp = smp_chan_get(conn); if (!smp) { return -EINVAL; } if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { return -EINVAL; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { legacy_passkey_entry(smp, passkey); return 0; } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ smp->passkey = sys_cpu_to_le32(passkey); if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { err = smp_send_pairing_confirm(smp); if (err) { smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); return 0; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return 0; } if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && atomic_test_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) { err = smp_send_pairing_confirm(smp); if (err) { smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); return 0; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); } return 0; } int bt_smp_auth_passkey_confirm(struct bt_conn *conn) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return -EINVAL; } if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { return -EINVAL; } /* wait for DHKey being generated */ if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return 0; } /* wait for remote DHKey Check */ if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) { atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); return 0; } if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) { u8_t err; #if defined(CONFIG_BT_CENTRAL) if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { err = compute_and_send_master_dhcheck(smp); if (err) { smp_error(smp, err); } return 0; } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) err = compute_and_check_and_send_slave_dhcheck(smp); if (err) { smp_error(smp, err); } #endif /* CONFIG_BT_PERIPHERAL */ } return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) int bt_smp_le_oob_set_tk(struct bt_conn *conn, const u8_t *tk) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp || !tk) { return -EINVAL; } BT_DBG("%s", bt_hex(tk, 16)); if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { return -EINVAL; } memcpy(smp->tk, tk, 16*sizeof(u8_t)); legacy_user_tk_entry(smp); return 0; } #endif /* !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) */ #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) int bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data *le_sc_oob) { int err; if (!sc_public_key) { err = k_sem_take(&sc_local_pkey_ready, K_FOREVER); if (err) { return err; } } if (IS_ENABLED(CONFIG_BT_OOB_DATA_FIXED)) { u8_t rand_num[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, }; memcpy(le_sc_oob->r, rand_num, sizeof(le_sc_oob->r)); } else { err = bt_rand(le_sc_oob->r, 16); if (err) { return err; } } err = smp_f4(sc_public_key, sc_public_key, le_sc_oob->r, 0, le_sc_oob->c); if (err) { return err; } return 0; } #endif /* !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) */ #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) static bool le_sc_oob_data_check(struct bt_smp *smp, bool oobd_local_present, bool oobd_remote_present) { bool req_oob_present = le_sc_oob_data_req_check(smp); bool rsp_oob_present = le_sc_oob_data_rsp_check(smp); if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { if ((req_oob_present != oobd_remote_present) && (rsp_oob_present != oobd_local_present)) { return false; } } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { if ((req_oob_present != oobd_local_present) && (rsp_oob_present != oobd_remote_present)) { return false; } } return true; } static int le_sc_oob_pairing_continue(struct bt_smp *smp) { if (smp->oobd_remote) { int err; u8_t c[16]; err = smp_f4(smp->pkey, smp->pkey, smp->oobd_remote->r, 0, c); if (err) { return err; } bool match = (memcmp(c, smp->oobd_remote->c, sizeof(c)) == 0); if (!match) { smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED); return 0; } } if (IS_ENABLED(CONFIG_BT_CENTRAL) && smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); } return smp_send_pairing_random(smp); } int bt_smp_le_oob_set_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data *oobd_local, const struct bt_le_oob_sc_data *oobd_remote) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return -EINVAL; } if (!le_sc_oob_data_check(smp, (oobd_local != NULL), (oobd_remote != NULL))) { return -EINVAL; } if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_OOB_PENDING)) { return -EINVAL; } smp->oobd_local = oobd_local; smp->oobd_remote = oobd_remote; return le_sc_oob_pairing_continue(smp); } int bt_smp_le_oob_get_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data **oobd_local, const struct bt_le_oob_sc_data **oobd_remote) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return -EINVAL; } if (!smp->oobd_local && !smp->oobd_remote) { return -ESRCH; } if (oobd_local) { *oobd_local = smp->oobd_local; } if (oobd_remote) { *oobd_remote = smp->oobd_remote; } return 0; } #endif /* !CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */ int bt_smp_auth_cancel(struct bt_conn *conn) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return -EINVAL; } if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { return -EINVAL; } switch (smp->method) { case PASSKEY_INPUT: case PASSKEY_DISPLAY: return smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); case PASSKEY_CONFIRM: return smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED); case LE_SC_OOB: case LEGACY_OOB: return smp_error(smp, BT_SMP_ERR_OOB_NOT_AVAIL); case JUST_WORKS: return smp_error(smp, BT_SMP_ERR_UNSPECIFIED); default: return 0; } } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) int bt_smp_auth_pairing_confirm(struct bt_conn *conn) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return -EINVAL; } if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) { if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return legacy_send_pairing_confirm(smp); } if (!sc_public_key) { atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); return 0; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); return sc_send_public_key(smp); } #if defined(CONFIG_BT_PERIPHERAL) if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); return send_pairing_rsp(smp); } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); if (send_pairing_rsp(smp)) { return -EIO; } #endif /* CONFIG_BT_PERIPHERAL */ return 0; } #else int bt_smp_auth_pairing_confirm(struct bt_conn *conn) { /* confirm_pairing will never be called in LE SC only mode */ return -EINVAL; } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ #if defined(CONFIG_BT_FIXED_PASSKEY) int bt_passkey_set(unsigned int passkey) { if (passkey == BT_PASSKEY_INVALID) { passkey = BT_PASSKEY_INVALID; return 0; } if (passkey > 999999) { return -EINVAL; } fixed_passkey = passkey; return 0; } #endif /* CONFIG_BT_FIXED_PASSKEY */ int bt_smp_start_security(struct bt_conn *conn) { switch (conn->role) { #if defined(CONFIG_BT_CENTRAL) case BT_HCI_ROLE_MASTER: { int err; struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return -ENOTCONN; } if (!smp_keys_check(conn)) { return smp_send_pairing_req(conn); } /* pairing is in progress */ if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { return -EBUSY; } /* Encryption is in progress */ if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { return -EBUSY; } /* LE SC LTK and legacy master LTK are stored in same place */ err = bt_conn_le_start_encryption(conn, conn->le.keys->ltk.rand, conn->le.keys->ltk.ediv, conn->le.keys->ltk.val, conn->le.keys->enc_size); if (err) { return err; } atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); return 0; } #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_SMP */ #if defined(CONFIG_BT_PERIPHERAL) case BT_HCI_ROLE_SLAVE: return smp_send_security_req(conn); #endif /* CONFIG_BT_PERIPHERAL && CONFIG_BT_SMP */ default: return -EINVAL; } } void bt_smp_update_keys(struct bt_conn *conn) { struct bt_smp *smp; smp = smp_chan_get(conn); if (!smp) { return; } if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { return; } /* * If link was successfully encrypted cleanup old keys as from now on * only keys distributed in this pairing or LTK from LE SC will be used. */ if (conn->le.keys) { bt_keys_clear(conn->le.keys); } conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); if (!conn->le.keys) { BT_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst)); smp_error(smp, BT_SMP_ERR_UNSPECIFIED); return; } /* mark keys as debug */ if (atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY)) { conn->le.keys->flags |= BT_KEYS_DEBUG; } /* * store key type deducted from pairing method used * it is important to store it since type is used to determine * security level upon encryption */ switch (smp->method) { case PASSKEY_DISPLAY: case PASSKEY_INPUT: case PASSKEY_CONFIRM: case LE_SC_OOB: case LEGACY_OOB: conn->le.keys->flags |= BT_KEYS_AUTHENTICATED; break; case JUST_WORKS: default: /* unauthenticated key, clear it */ conn->le.keys->flags &= ~BT_KEYS_AUTHENTICATED; break; } conn->le.keys->enc_size = get_encryption_key_size(smp); /* * Store LTK if LE SC is used, this is safe since LE SC is mutually * exclusive with legacy pairing. Other keys are added on keys * distribution. */ if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) { conn->le.keys->flags |= BT_KEYS_SC; if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { bt_keys_add_type(conn->le.keys, BT_KEYS_LTK_P256); memcpy(conn->le.keys->ltk.val, smp->tk, sizeof(conn->le.keys->ltk.val)); (void)memset(conn->le.keys->ltk.rand, 0, sizeof(conn->le.keys->ltk.rand)); (void)memset(conn->le.keys->ltk.ediv, 0, sizeof(conn->le.keys->ltk.ediv)); } } else { conn->le.keys->flags &= ~BT_KEYS_SC; } } static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { int i; static const struct bt_l2cap_chan_ops ops = { .connected = bt_smp_connected, .disconnected = bt_smp_disconnected, .encrypt_change = bt_smp_encrypt_change, .recv = bt_smp_recv, }; BT_DBG("conn %p handle %u", conn, conn->handle); for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { struct bt_smp *smp = &bt_smp_pool[i]; if (smp->chan.chan.conn) { continue; } smp->chan.chan.ops = &ops; *chan = &smp->chan.chan; return 0; } BT_ERR("No available SMP context for conn %p", conn); return -ENOMEM; } static bool le_sc_supported(void) { /* * If controller based ECC is to be used it must support * "LE Read Local P-256 Public Key" and "LE Generate DH Key" commands. * Otherwise LE SC are not supported. */ if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) { return false; } return BT_CMD_TEST(bt_dev.supported_commands, 34, 1) && BT_CMD_TEST(bt_dev.supported_commands, 34, 2); } BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept, NULL); #if defined(CONFIG_BT_BREDR) BT_L2CAP_CHANNEL_DEFINE(smp_br_fixed_chan, BT_L2CAP_CID_BR_SMP, bt_smp_br_accept, NULL); #endif /* CONFIG_BT_BREDR */ int bt_smp_init(void) { #if defined(CONFIG_BT_ECC) static struct bt_pub_key_cb pub_key_cb = { .func = bt_smp_pkey_ready, }; #endif sc_supported = le_sc_supported(); if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) && !sc_supported) { BT_ERR("SC Pair Only Mode selected but LE SC not supported"); return -ENOENT; } if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) { BT_WARN("BT_SMP_USB_HCI_CTLR_WORKAROUND is enabled, which " "exposes a security vulnerability!"); } BT_DBG("LE SC %s", sc_supported ? "enabled" : "disabled"); extern void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan); bt_l2cap_le_fixed_chan_register(&smp_fixed_chan); #if defined(CONFIG_BT_BREDR) /* Register BR/EDR channel only if BR/EDR SC is supported */ if (br_sc_supported()) { bt_l2cap_br_fixed_chan_register(&smp_br_fixed_chan); } #endif #if defined(CONFIG_BT_ECC) if (!IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) { bt_pub_key_gen(&pub_key_cb); } #endif #if defined(CONFIG_BT_SETTINGS) extern int bt_key_settings_init(); bt_key_settings_init(); #endif return smp_self_test(); } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/smp.c
C
apache-2.0
137,450
/** * @file smp.h * Security Manager Protocol implementation header */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ struct bt_smp_hdr { u8_t code; } __packed; #define BT_SMP_ERR_PASSKEY_ENTRY_FAILED 0x01 #define BT_SMP_ERR_OOB_NOT_AVAIL 0x02 #define BT_SMP_ERR_AUTH_REQUIREMENTS 0x03 #define BT_SMP_ERR_CONFIRM_FAILED 0x04 #define BT_SMP_ERR_PAIRING_NOTSUPP 0x05 #define BT_SMP_ERR_ENC_KEY_SIZE 0x06 #define BT_SMP_ERR_CMD_NOTSUPP 0x07 #define BT_SMP_ERR_UNSPECIFIED 0x08 #define BT_SMP_ERR_REPEATED_ATTEMPTS 0x09 #define BT_SMP_ERR_INVALID_PARAMS 0x0a #define BT_SMP_ERR_DHKEY_CHECK_FAILED 0x0b #define BT_SMP_ERR_NUMERIC_COMP_FAILED 0x0c #define BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS 0x0d #define BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED 0x0e #define BT_SMP_IO_DISPLAY_ONLY 0x00 #define BT_SMP_IO_DISPLAY_YESNO 0x01 #define BT_SMP_IO_KEYBOARD_ONLY 0x02 #define BT_SMP_IO_NO_INPUT_OUTPUT 0x03 #define BT_SMP_IO_KEYBOARD_DISPLAY 0x04 #define BT_SMP_OOB_DATA_MASK 0x01 #define BT_SMP_OOB_NOT_PRESENT 0x00 #define BT_SMP_OOB_PRESENT 0x01 #define BT_SMP_MIN_ENC_KEY_SIZE 7 #define BT_SMP_MAX_ENC_KEY_SIZE 16 #define BT_SMP_DIST_ENC_KEY 0x01 #define BT_SMP_DIST_ID_KEY 0x02 #define BT_SMP_DIST_SIGN 0x04 #define BT_SMP_DIST_LINK_KEY 0x08 #define BT_SMP_DIST_MASK 0x0f #define BT_SMP_AUTH_NONE 0x00 #define BT_SMP_AUTH_BONDING 0x01 #define BT_SMP_AUTH_MITM 0x04 #define BT_SMP_AUTH_SC 0x08 #define BT_SMP_AUTH_KEYPRESS 0x10 #define BT_SMP_AUTH_CT2 0x20 #define BT_SMP_CMD_PAIRING_REQ 0x01 #define BT_SMP_CMD_PAIRING_RSP 0x02 struct bt_smp_pairing { u8_t io_capability; u8_t oob_flag; u8_t auth_req; u8_t max_key_size; u8_t init_key_dist; u8_t resp_key_dist; } __packed; #define BT_SMP_CMD_PAIRING_CONFIRM 0x03 struct bt_smp_pairing_confirm { u8_t val[16]; } __packed; #define BT_SMP_CMD_PAIRING_RANDOM 0x04 struct bt_smp_pairing_random { u8_t val[16]; } __packed; #define BT_SMP_CMD_PAIRING_FAIL 0x05 struct bt_smp_pairing_fail { u8_t reason; } __packed; #define BT_SMP_CMD_ENCRYPT_INFO 0x06 struct bt_smp_encrypt_info { u8_t ltk[16]; } __packed; #define BT_SMP_CMD_MASTER_IDENT 0x07 struct bt_smp_master_ident { u8_t ediv[2]; u8_t rand[8]; } __packed; #define BT_SMP_CMD_IDENT_INFO 0x08 struct bt_smp_ident_info { u8_t irk[16]; } __packed; #define BT_SMP_CMD_IDENT_ADDR_INFO 0x09 struct bt_smp_ident_addr_info { bt_addr_le_t addr; } __packed; #define BT_SMP_CMD_SIGNING_INFO 0x0a struct bt_smp_signing_info { u8_t csrk[16]; } __packed; #define BT_SMP_CMD_SECURITY_REQUEST 0x0b struct bt_smp_security_request { u8_t auth_req; } __packed; #define BT_SMP_CMD_PUBLIC_KEY 0x0c struct bt_smp_public_key { u8_t x[32]; u8_t y[32]; } __packed; #define BT_SMP_DHKEY_CHECK 0x0d struct bt_smp_dhkey_check { u8_t e[16]; } __packed; int bt_smp_start_security(struct bt_conn *conn); bool bt_smp_request_ltk(struct bt_conn *conn, u64_t rand, u16_t ediv, u8_t *ltk); void bt_smp_update_keys(struct bt_conn *conn); int bt_smp_br_send_pairing_req(struct bt_conn *conn); int bt_smp_init(void); int bt_smp_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey); int bt_smp_auth_passkey_confirm(struct bt_conn *conn); int bt_smp_auth_pairing_confirm(struct bt_conn *conn); int bt_smp_auth_cancel(struct bt_conn *conn); int bt_smp_le_oob_set_tk(struct bt_conn *conn, const u8_t *tk); int bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data *le_sc_oob); int bt_smp_le_oob_set_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data *oobd_local, const struct bt_le_oob_sc_data *oobd_remote); int bt_smp_le_oob_get_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data **oobd_local, const struct bt_le_oob_sc_data **oobd_remote); /** brief Verify signed message * * @param conn Bluetooth connection * @param buf received packet buffer with message and signature * * @return 0 in success, error code otherwise */ int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf); /** brief Sign message * * @param conn Bluetooth connection * @param buf message buffer * * @return 0 in success, error code otherwise */ int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf); /** Generate IRK from Identity Root (IR) */ int bt_smp_irk_get(u8_t *ir, u8_t *irk);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/smp.h
C
apache-2.0
4,401
/** * @file smp_null.c * Security Manager Protocol stub */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <bt_errno.h> #include <atomic.h> #include <misc/util.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <bluetooth/buf.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE) #if !defined(CONFIG_BT_SMP) #define LOG_MODULE_NAME bt_smp #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #include "smp.h" #ifndef ENOTSUP #define ENOTSUP 134 /* unsupported*/ #endif static struct bt_l2cap_le_chan bt_smp_pool[CONFIG_BT_MAX_CONN]; int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; } int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; } static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_conn *conn = chan->conn; struct bt_smp_pairing_fail *rsp; struct bt_smp_hdr *hdr; /* If a device does not support pairing then it shall respond with * a Pairing Failed command with the reason set to "Pairing Not * Supported" when any command is received. * Core Specification Vol. 3, Part H, 3.3 */ buf = bt_l2cap_create_pdu(NULL, 0); /* NULL is not a possible return due to K_FOREVER */ hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = BT_SMP_CMD_PAIRING_FAIL; rsp = net_buf_add(buf, sizeof(*rsp)); rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP; bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf); return 0; } static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { int i; static const struct bt_l2cap_chan_ops ops = { .recv = bt_smp_recv, }; BT_DBG("conn %p handle %u", conn, conn->handle); for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { struct bt_l2cap_le_chan *smp = &bt_smp_pool[i]; if (smp->chan.conn) { continue; } smp->chan.ops = &ops; *chan = &smp->chan; return 0; } BT_ERR("No available SMP context for conn %p", conn); return -ENOMEM; } BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept, NULL); int bt_smp_init(void) { bt_l2cap_le_fixed_chan_register(&smp_fixed_chan); return 0; } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/smp_null.c
C
apache-2.0
2,250
/* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #include <stddef.h> #include <bluetooth/mesh.h> #include <bluetooth/testing.h> #if defined(CONFIG_BT_MESH) #include "mesh/net.h" #include "mesh/lpn.h" #include "mesh/transport.h" #endif /* CONFIG_BT_MESH */ #include "testing.h" static sys_slist_t cb_slist; void bt_test_cb_register(struct bt_test_cb *cb) { sys_slist_append(&cb_slist, &cb->node); } void bt_test_cb_unregister(struct bt_test_cb *cb) { sys_slist_find_and_remove(&cb_slist, &cb->node); } #if defined(CONFIG_BT_MESH) void bt_test_mesh_net_recv(u8_t ttl, u8_t ctl, u16_t src, u16_t dst, const void *payload, size_t payload_len) { struct bt_test_cb *cb; SYS_SLIST_FOR_EACH_CONTAINER(&cb_slist, cb, node) { if (cb->mesh_net_recv) { cb->mesh_net_recv(ttl, ctl, src, dst, payload, payload_len); } } } void bt_test_mesh_model_bound(u16_t addr, struct bt_mesh_model *model, u16_t key_idx) { struct bt_test_cb *cb; SYS_SLIST_FOR_EACH_CONTAINER(&cb_slist, cb, node) { if (cb->mesh_model_bound) { cb->mesh_model_bound(addr, model, key_idx); } } } void bt_test_mesh_model_unbound(u16_t addr, struct bt_mesh_model *model, u16_t key_idx) { struct bt_test_cb *cb; SYS_SLIST_FOR_EACH_CONTAINER(&cb_slist, cb, node) { if (cb->mesh_model_unbound) { cb->mesh_model_unbound(addr, model, key_idx); } } } void bt_test_mesh_prov_invalid_bearer(u8_t opcode) { struct bt_test_cb *cb; SYS_SLIST_FOR_EACH_CONTAINER(&cb_slist, cb, node) { if (cb->mesh_prov_invalid_bearer) { cb->mesh_prov_invalid_bearer(opcode); } } } void bt_test_mesh_trans_incomp_timer_exp(void) { struct bt_test_cb *cb; SYS_SLIST_FOR_EACH_CONTAINER(&cb_slist, cb, node) { if (cb->mesh_trans_incomp_timer_exp) { cb->mesh_trans_incomp_timer_exp(); } } } int bt_test_mesh_lpn_group_add(u16_t group) { bt_mesh_lpn_group_add(group); return 0; } int bt_test_mesh_lpn_group_remove(u16_t *groups, size_t groups_count) { bt_mesh_lpn_group_del(groups, groups_count); return 0; } int bt_test_mesh_rpl_clear(void) { bt_mesh_rpl_clear(); return 0; } #endif /* CONFIG_BT_MESH */
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/testing.c
C
apache-2.0
2,188
/** * @file testing.h * @brief Internal API for Bluetooth testing. */ /* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #if defined(CONFIG_BT_MESH) void bt_test_mesh_net_recv(u8_t ttl, u8_t ctl, u16_t src, u16_t dst, const void *payload, size_t payload_len); void bt_test_mesh_model_bound(u16_t addr, struct bt_mesh_model *model, u16_t key_idx); void bt_test_mesh_model_unbound(u16_t addr, struct bt_mesh_model *model, u16_t key_idx); void bt_test_mesh_prov_invalid_bearer(u8_t opcode); void bt_test_mesh_trans_incomp_timer_exp(void); #endif /* CONFIG_BT_MESH */
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/testing.h
C
apache-2.0
626
/* uuid.c - Bluetooth UUID handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <bt_errno.h> #include <misc/byteorder.h> #include <misc/printk.h> #include <bluetooth/uuid.h> #define UUID_16_BASE_OFFSET 12 /* TODO: Decide whether to continue using BLE format or switch to RFC 4122 */ /* Base UUID : 0000[0000]-0000-1000-8000-00805F9B34FB * 0x2800 : 0000[2800]-0000-1000-8000-00805F9B34FB * little endian 0x2800 : [00 28] -> no swapping required * big endian 0x2800 : [28 00] -> swapping required */ static const struct bt_uuid_128 uuid128_base = { .uuid = { BT_UUID_TYPE_128 }, .val = { BT_UUID_128_ENCODE( 0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB) } }; static void uuid_to_uuid128(const struct bt_uuid *src, struct bt_uuid_128 *dst) { switch (src->type) { case BT_UUID_TYPE_16: *dst = uuid128_base; sys_put_le16(BT_UUID_16(src)->val, &dst->val[UUID_16_BASE_OFFSET]); return; case BT_UUID_TYPE_32: *dst = uuid128_base; sys_put_le32(BT_UUID_32(src)->val, &dst->val[UUID_16_BASE_OFFSET]); return; case BT_UUID_TYPE_128: memcpy(dst, src, sizeof(*dst)); return; } } static int uuid128_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) { struct bt_uuid_128 uuid1, uuid2; uuid_to_uuid128(u1, &uuid1); uuid_to_uuid128(u2, &uuid2); return memcmp(uuid1.val, uuid2.val, 16); } int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) { /* Convert to 128 bit if types don't match */ if (u1->type != u2->type) { return uuid128_cmp(u1, u2); } switch (u1->type) { case BT_UUID_TYPE_16: return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val; case BT_UUID_TYPE_32: return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val; case BT_UUID_TYPE_128: return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16); } return -EINVAL; } bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len) { /* Copy UUID from packet data/internal variable to internal bt_uuid */ switch (data_len) { case 2: uuid->type = BT_UUID_TYPE_16; BT_UUID_16(uuid)->val = sys_get_le16(data); break; case 4: uuid->type = BT_UUID_TYPE_32; BT_UUID_32(uuid)->val = sys_get_le32(data); break; case 16: uuid->type = BT_UUID_TYPE_128; memcpy(&BT_UUID_128(uuid)->val, data, 16); break; default: return 0; // return false; } return 1; // return true; } #if defined(CONFIG_BT_DEBUG) void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len) { bt_u32_t tmp1, tmp5; u16_t tmp0, tmp2, tmp3, tmp4; switch (uuid->type) { case BT_UUID_TYPE_16: snprintk(str, len, "%04x", BT_UUID_16(uuid)->val); break; case BT_UUID_TYPE_32: snprintk(str, len, "%08x", BT_UUID_32(uuid)->val); break; case BT_UUID_TYPE_128: memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0)); memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1)); memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2)); memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3)); memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4)); memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5)); snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x", tmp5, tmp4, tmp3, tmp2, tmp1, tmp0); break; default: (void)memset(str, 0, len); return; } } const char *bt_uuid_str(const struct bt_uuid *uuid) { static char str[37]; bt_uuid_to_str(uuid, str, sizeof(str)); return str; } #endif /* CONFIG_BT_DEBUG */
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/uuid.c
C
apache-2.0
3,499
/* * Copyright (C) 2017 C-SKY Microsystems Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __BLE_H__ #define __BLE_H__ #include <stdint.h> #include <aos/list.h> #include <aos/uuid.h> #include <aos/gatt.h> #ifdef __cplusplus extern "C" { #endif #define BLE_ARRAY_NUM(a) (sizeof(a) / sizeof((a)[0])) #define BLE_MIN(a, b) ((a) < (b) ? (a) : (b)) #define BLE_CHAR_RANGE_CHECK(a, b, c, d) \ do { \ if (((c) >= (a)) && ((c) < ((a) + (b)))) \ { \ d = c - a; \ } \ else \ { \ return 0; \ } \ } while(0); #define ATT_ERR_INVALID_HANDLE 0x01 #define ATT_ERR_READ_NOT_PERMITTED 0x02 #define ATT_ERR_WRITE_NOT_PERMITTED 0x03 #define ATT_ERR_INVALID_PDU 0x04 #define ATT_ERR_AUTHENTICATION 0x05 #define ATT_ERR_NOT_SUPPORTED 0x06 #define ATT_ERR_INVALID_OFFSET 0x07 #define ATT_ERR_AUTHORIZATION 0x08 #define ATT_ERR_PREPARE_QUEUE_FULL 0x09 #define ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a #define ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b #define ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c #define ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d #define ATT_ERR_UNLIKELY 0x0e #define ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f #define ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 #define ATT_ERR_INSUFFICIENT_RESOURCES 0x11 typedef struct _conn_param_t { uint16_t interval_min; uint16_t interval_max; uint16_t latency; uint16_t timeout; } conn_param_t; enum { BLE_STACK_OK = 0, BLE_STACK_ERR_NULL, BLE_STACK_ERR_PARAM, BLE_STACK_ERR_INTERNAL, BLE_STACK_ERR_INIT, BLE_STACK_ERR_CONN, BLE_STACK_ERR_ALREADY, }; typedef enum { DEV_ADDR_LE_PUBLIC = 0x00, DEV_ADDR_LE_RANDOM = 0x01, DEV_ADDR_LE_PUBLIC_ID = 0x02, DEV_ADDR_LE_RANDOM_ID = 0x03, } adv_addr_type_en; typedef enum { ADV_IND = 0x00, ADV_DIRECT_IND = 0x01, ADV_SCAN_IND = 0x02, ADV_NONCONN_IND = 0x03, ADV_DIRECT_IND_LOW_DUTY = 0x04, } adv_type_en; #ifndef EVENT_BLE #define EVENT_BLE 0x05000000 #endif typedef enum { EVENT_STACK_INIT = EVENT_BLE, EVENT_GAP_CONN_CHANGE, EVENT_GAP_DEV_FIND, EVENT_GAP_CONN_PARAM_REQ, EVENT_GAP_CONN_PARAM_UPDATE, EVENT_GAP_CONN_SECURITY_CHANGE, EVENT_GAP_ADV_TIMEOUT, EVENT_GATT_NOTIFY, EVENT_GATT_INDICATE = EVENT_GATT_NOTIFY, EVENT_GATT_CHAR_READ, EVENT_GATT_CHAR_WRITE, EVENT_GATT_INDICATE_CB, EVENT_GATT_CHAR_READ_CB, EVENT_GATT_CHAR_WRITE_CB, EVENT_GATT_CHAR_CCC_CHANGE, EVENT_GATT_CHAR_CCC_WRITE, EVENT_GATT_CHAR_CCC_MATCH, EVENT_GATT_MTU_EXCHANGE, EVENT_GATT_DISCOVERY_SVC, EVENT_GATT_DISCOVERY_INC_SVC, EVENT_GATT_DISCOVERY_CHAR, EVENT_GATT_DISCOVERY_CHAR_DES, EVENT_GATT_DISCOVERY_COMPLETE, EVENT_SMP_PASSKEY_DISPLAY, EVENT_SMP_PASSKEY_CONFIRM, EVENT_SMP_PASSKEY_ENTER, EVENT_SMP_PAIRING_CONFIRM, EVENT_SMP_PAIRING_COMPLETE, EVENT_SMP_CANCEL, EVENT_STACK_UNKNOWN, } ble_event_en; typedef enum { DISCONNECTED, CONNECTED, } conn_state_en; #pragma pack(1) typedef struct _dev_addr_t { uint8_t type; uint8_t val[6]; } dev_addr_t; typedef struct _evt_data_gap_conn_change_t { int16_t conn_handle; int16_t err; conn_state_en connected; } evt_data_gap_conn_change_t; typedef struct _evt_data_gap_conn_param_req_t { int16_t conn_handle; int8_t accept; conn_param_t param; } evt_data_gap_conn_param_req_t; typedef struct _evt_data_gap_conn_param_update_t { int16_t conn_handle; uint16_t interval; uint16_t latency; uint16_t timeout; } evt_data_gap_conn_param_update_t; typedef struct _evt_data_gap_security_change_t { int16_t conn_handle; uint16_t level; uint8_t err; } evt_data_gap_security_change_t; typedef struct _evt_data_gap_dev_find_t { dev_addr_t dev_addr; adv_type_en adv_type; uint8_t adv_len; int8_t rssi; uint8_t adv_data[31]; } evt_data_gap_dev_find_t; typedef struct _evt_data_gatt_notify_t { int16_t conn_handle; int16_t char_handle; uint8_t len; const uint8_t *data; } evt_data_gatt_notify_t; typedef evt_data_gatt_notify_t evt_data_gatt_indicate_t; typedef struct _evt_data_gatt_indicate_cb_t { int16_t conn_handle; int16_t char_handle; int err; } evt_data_gatt_indicate_cb_t; typedef struct _evt_data_gatt_write_cb_t { int16_t conn_handle; int16_t char_handle; int err; } evt_data_gatt_write_cb_t; typedef struct _evt_data_gatt_read_cb_t { int16_t conn_handle; int err; uint16_t len; const uint8_t *data; } evt_data_gatt_read_cb_t; typedef struct _evt_data_gatt_char_read_t { int16_t conn_handle; int16_t char_handle; int32_t len; uint8_t *data; uint16_t offset; } evt_data_gatt_char_read_t; typedef struct _evt_data_gatt_char_write_t { int16_t conn_handle; int16_t char_handle; int32_t len; const uint8_t *data; uint16_t offset; uint8_t flag; } evt_data_gatt_char_write_t; typedef struct _evt_data_gatt_char_ccc_change_t { int16_t char_handle; ccc_value_en ccc_value; } evt_data_gatt_char_ccc_change_t; typedef struct _evt_data_gatt_char_ccc_write_t { int16_t conn_handle; int16_t char_handle; ccc_value_en ccc_value; int8_t allow_write; } evt_data_gatt_char_ccc_write_t; typedef struct _evt_data_gatt_char_ccc_match_t { int16_t conn_handle; int16_t char_handle; int8_t is_matched; } evt_data_gatt_char_ccc_match_t; typedef struct _evt_data_gatt_mtu_exchange_t { int16_t conn_handle; int err; } evt_data_gatt_mtu_exchange_t; typedef struct _evt_data_smp_passkey_display_t { int16_t conn_handle; dev_addr_t peer_addr; char *passkey; } evt_data_smp_passkey_display_t; typedef struct _evt_data_smp_passkey_confirm_t { int16_t conn_handle; dev_addr_t peer_addr; char *passkey; } evt_data_smp_passkey_confirm_t; typedef struct _evt_data_smp_passkey_enter_t { int16_t conn_handle; dev_addr_t peer_addr; } evt_data_smp_passkey_enter_t; typedef struct _evt_data_smp_pairing_confirm_t { int16_t conn_handle; dev_addr_t peer_addr; } evt_data_smp_pairing_confirm_t; typedef struct _evt_data_smp_pairing_complete_t { int16_t conn_handle; dev_addr_t peer_addr; int8_t bonded; int16_t err; } evt_data_smp_pairing_complete_t; typedef struct _evt_data_smp_cancel_t { int16_t conn_handle; dev_addr_t peer_addr; } evt_data_smp_cancel_t; typedef struct _evt_data_gatt_discovery_svc_t { int16_t conn_handle; uint16_t start_handle; uint16_t end_handle; union { uuid_t uuid; struct ut_uuid_16 uuid16; struct ut_uuid_32 uuid32; struct ut_uuid_128 uuid128; }; } evt_data_gatt_discovery_svc_t; typedef struct _evt_data_gatt_discovery_inc_svc_t { int16_t conn_handle; uint16_t attr_handle; uint16_t start_handle; uint16_t end_handle; union { uuid_t uuid; struct ut_uuid_16 uuid16; struct ut_uuid_32 uuid32; struct ut_uuid_128 uuid128; }; } evt_data_gatt_discovery_inc_svc_t; typedef struct _evt_data_gatt_discovery_char_t { int16_t conn_handle; uint16_t attr_handle; uint16_t val_handle; uint16_t props; union { uuid_t uuid; struct ut_uuid_16 uuid16; struct ut_uuid_32 uuid32; struct ut_uuid_128 uuid128; }; } evt_data_gatt_discovery_char_t; typedef struct _evt_data_gatt_discovery_char_des_t { int16_t conn_handle; uint16_t attr_handle; union { uuid_t uuid; struct ut_uuid_16 uuid16; struct ut_uuid_32 uuid32; struct ut_uuid_128 uuid128; }; } evt_data_gatt_discovery_char_des_t; typedef struct _evt_data_gatt_discovery_complete_t { int16_t conn_handle; int err; } evt_data_gatt_discovery_complete_t; #pragma pack() typedef int (*event_callback_func_t)(ble_event_en event, void *event_data); typedef struct _ble_event_cb_t { event_callback_func_t callback; slist_t next; } ble_event_cb_t; typedef struct _init_param_t { char *dev_name; dev_addr_t *dev_addr; uint16_t conn_num_max; } init_param_t; typedef enum { AD_DATA_TYPE_FLAGS = 0x01, /* AD flags */ AD_DATA_TYPE_UUID16_SOME = 0x02, /* 16-bit UUID, more available */ AD_DATA_TYPE_UUID16_ALL = 0x03, /* 16-bit UUID, all listed */ AD_DATA_TYPE_UUID32_SOME = 0x04, /* 32-bit UUID, more available */ AD_DATA_TYPE_UUID32_ALL = 0x05, /* 32-bit UUID, all listed */ AD_DATA_TYPE_UUID128_SOME = 0x06, /* 128-bit UUID, more available */ AD_DATA_TYPE_UUID128_ALL = 0x07, /* 128-bit UUID, all listed */ AD_DATA_TYPE_NAME_SHORTENED = 0x08, /* Shortened name */ AD_DATA_TYPE_NAME_COMPLETE = 0x09, /* Complete name */ AD_DATA_TYPE_TX_POWER = 0x0a, /* Tx Power */ AD_DATA_TYPE_SOLICIT16 = 0x14, /* Solicit UUIDs, 16-bit */ AD_DATA_TYPE_SOLICIT128 = 0x15, /* Solicit UUIDs, 128-bit */ AD_DATA_TYPE_SVC_DATA16 = 0x16, /* Service data, 16-bit UUID */ AD_DATA_TYPE_GAP_APPEARANCE = 0x19, /* GAP appearance */ AD_DATA_TYPE_SOLICIT32 = 0x1f, /* Solicit UUIDs, 32-bit */ AD_DATA_TYPE_SVC_DATA32 = 0x20, /* Service data, 32-bit UUID */ AD_DATA_TYPE_SVC_DATA128 = 0x21, /* Service data, 128-bit UUID */ AD_DATA_TYPE_URI = 0x24, /* URI */ AD_DATA_TYPE_MESH_PROV = 0x29, /* Mesh Provisioning PDU */ AD_DATA_TYPE_MESH_MESSAGE = 0x2a, /* Mesh Networking PDU */ AD_DATA_TYPE_MESH_BEACON = 0x2b, /* Mesh Beacon */ AD_DATA_TYPE_MANUFACTURER_DATA = 0xff, /* Manufacturer Specific Data */ } ad_date_type_en; typedef enum { AD_FLAG_LIMITED = 0x01, /* Limited Discoverable */ AD_FLAG_GENERAL = 0x02, /* General Discoverable */ AD_FLAG_NO_BREDR = 0x04, /* BR/EDR not supported */ } ad_flag_en; typedef enum { ADV_FAST_INT_MIN_1 = 0x0030, /* 30 ms */ ADV_FAST_INT_MAX_1 = 0x0060, /* 60 ms */ ADV_FAST_INT_MIN_2 = 0x00a0, /* 100 ms */ ADV_FAST_INT_MAX_2 = 0x00f0, /* 150 ms */ ADV_SLOW_INT_MIN = 0x0640, /* 1 s */ ADV_SLOW_INT_MAX = 0x0780, /* 1.2 s */ ADV_SCAN_INT_MIN_1 = 0x0120, /* 112.5 ms */ ADV_SCAN_INT_MAX_1 = 0x0140, /* 200 ms */ } adv_interval_en; typedef struct _ad_data_t { uint8_t type; uint8_t len; uint8_t *data; } ad_data_t; typedef enum { ADV_FILTER_POLICY_ANY_REQ = 0, /* any scan request or connect request */ ADV_FILTER_POLICY_SCAN_REQ = 1, /* all connect request, white list scan request */ ADV_FILTER_POLICY_CONN_REQ = 2, /* all scan request, white list connect request */ ADV_FILTER_POLICY_ALL_REQ = 3, /* white list scan request and connect request */ } adv_filter_policy_en; typedef enum { ADV_CHAN_37 = 0x01, ADV_CHAN_38 = 0x02, ADV_CHAN_39 = 0x04, } adv_chan_en; #define ADV_DEFAULT_CHAN_MAP (ADV_CHAN_37 | ADV_CHAN_38 | ADV_CHAN_39) typedef struct _adv_param_t { adv_type_en type; ad_data_t *ad; ad_data_t *sd; uint8_t ad_num; uint8_t sd_num; uint16_t interval_min; uint16_t interval_max; adv_filter_policy_en filter_policy; adv_chan_en channel_map; dev_addr_t direct_peer_addr; } adv_param_t; typedef enum { SCAN_PASSIVE = 0x00, SCAN_ACTIVE = 0x01, } scan_type_en; typedef enum { SCAN_FILTER_DUP_DISABLE = 0x00, SCAN_FILTER_DUP_ENABLE = 0x01, } scan_filter_en; typedef enum { SCAN_FAST_INTERVAL = 0x0060, /* 60 ms */ SCAN_SLOW_INTERVAL_1 = 0x0800, /* 1.28 s */ SCAN_SLOW_INTERVAL_2 = 0x1000, /* 2.56 s */ } scan_interval_en; typedef enum { SCAN_FAST_WINDOW = 0x0030, /* 30 ms */ SCAN_SLOW_WINDOW = 0x0012, /* 11.25 ms */ } scan_window_en; typedef enum { SCAN_FILTER_POLICY_ANY_ADV = 0, /* any adv packages */ SCAN_FILTER_POLICY_WHITE_LIST = 1, /* white list adv packages */ } scan_filter_policy_en; typedef struct _scan_param_t { scan_type_en type; scan_filter_en filter_dup; uint16_t interval; uint16_t window; scan_filter_policy_en scan_filter; } scan_param_t; typedef enum { CONN_INT_MIN_INTERVAL = 0x0018, /* 30 ms */ CONN_INT_MAX_INTERVAL = 0x0028, /* 50 ms */ } conn_interval_en; typedef enum { IO_CAP_IN_NONE = 0x01, IO_CAP_IN_YESNO = 0x02, IO_CAP_IN_KEYBOARD = 0x04, IO_CAP_OUT_NONE = 0x08, IO_CAP_OUT_DISPLAY = 0x10, } io_cap_en; typedef struct _connect_info_t { int16_t conn_handle; uint8_t role; uint16_t interval; uint16_t latency; uint16_t timeout; dev_addr_t local_addr; dev_addr_t peer_addr; } connect_info_t; typedef enum { /** Only for BR/EDR special cases, like SDP */ SECURITY_NONE, /** No encryption and no authentication. */ SECURITY_LOW, /** Encryption and no authentication (no MITM). */ SECURITY_MEDIUM, /** Encryption and authentication (MITM). */ SECURITY_HIGH, /** Authenticated Secure Connections */ SECURITY_FIPS, } security_en; int ble_stack_init(init_param_t *param); int ble_stack_set_name(const char *name); int ble_stack_iocapability_set(uint8_t io_cap); int ble_stack_event_register(ble_event_cb_t *callback); int ble_stack_adv_start(adv_param_t *param); int ble_stack_adv_stop(); int ble_stack_scan_start(const scan_param_t *param); int ble_stack_scan_stop(); int ble_stack_get_local_addr(dev_addr_t *addr); int ble_stack_connect(dev_addr_t *peer_addr, conn_param_t *param, uint8_t auto_connect); int ble_stack_disconnect(int16_t conn_handle); int ble_stack_connect_info_get(int16_t conn_handle, connect_info_t *info); int ble_stack_security(int16_t conn_handle, security_en level); int ble_stack_connect_param_update(int16_t conn_handle, conn_param_t *param); int ble_stack_smp_passkey_entry(int16_t conn_handle, uint32_t passkey); int ble_stack_smp_cancel(int16_t conn_handle); int ble_stack_smp_passkey_confirm(int16_t conn_handle); int ble_stack_smp_pairing_confirm(int16_t conn_handle); int ble_stack_setting_load(); int ble_stack_dev_unpair(dev_addr_t *peer_addr); int ble_stack_enc_key_size_get(int16_t conn_handle); int ble_stack_white_list_clear(); int ble_stack_white_list_add(dev_addr_t *peer_addr); int ble_stack_white_list_remove(dev_addr_t *peer_addr); int ble_stack_white_list_size(); int ble_stack_check_conn_params(const conn_param_t *param); #ifdef __cplusplus } #endif #endif /* __BLE_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/aos/ble.h
C
apache-2.0
15,108
/* * Copyright (C) 2017 C-SKY Microsystems Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __GATT_H__ #define __GATT_H__ #include <aos/uuid.h> #include <ble_config.h> #define ARRAY_SIZES(array) (sizeof(array)/sizeof(array[0])) #ifdef __cplusplus extern "C" { #endif typedef enum { CCC_VALUE_NONE = 0, CCC_VALUE_NOTIFY = 1, CCC_VALUE_INDICATE = 2 } ccc_value_en; /* GATT attribute permission bit field values */ typedef enum { /** No operations supported, e.g. for notify-only */ GATT_PERM_NONE = 0, /** Attribute read permission. */ GATT_PERM_READ = BLE_BIT(0), /** Attribute write permission. */ GATT_PERM_WRITE = BLE_BIT(1), /** Attribute read permission with encryption. * * If set, requires encryption for read access. */ GATT_PERM_READ_ENCRYPT = BLE_BIT(2), /** Attribute write permission with encryption. * * If set, requires encryption for write access. */ GATT_PERM_WRITE_ENCRYPT = BLE_BIT(3), /** Attribute read permission with authentication. * * If set, requires encryption using authenticated link-key for read * access. */ GATT_PERM_READ_AUTHEN = BLE_BIT(4), /** Attribute write permission with authentication. * * If set, requires encryption using authenticated link-key for write * access. */ GATT_PERM_WRITE_AUTHEN = BLE_BIT(5), /** Attribute prepare write permission. * * If set, allows prepare writes with use of GATT_WRITE_FLAG_PREPARE * passed to write callback. */ GATT_PERM_PREPARE_WRITE = BLE_BIT(6), } gatt_perm_en; /* Characteristic Properties Bit field values */ typedef enum { /** @def BT_GATT_CHRC_BROADCAST * @brief Characteristic broadcast property. * * If set, permits broadcasts of the Characteristic Value using Server * Characteristic Configuration Descriptor. */ GATT_CHRC_PROP_BROADCAST = BLE_BIT(0), /** @def BT_GATT_CHRC_READ * @brief Characteristic read property. * * If set, permits reads of the Characteristic Value. */ GATT_CHRC_PROP_READ = BLE_BIT(1), /** @def BT_GATT_CHRC_WRITE_WITHOUT_RESP * @brief Characteristic write without response property. * * If set, permits write of the Characteristic Value without response. */ GATT_CHRC_PROP_WRITE_WITHOUT_RESP = BLE_BIT(2), /** @def BT_GATT_CHRC_WRITE * @brief Characteristic write with response property. * * If set, permits write of the Characteristic Value with response. */ GATT_CHRC_PROP_WRITE = BLE_BIT(3), /** @def BT_GATT_CHRC_NOTIFY * @brief Characteristic notify property. * * If set, permits notifications of a Characteristic Value without * acknowledgment. */ GATT_CHRC_PROP_NOTIFY = BLE_BIT(4), /** @def BT_GATT_CHRC_INDICATE * @brief Characteristic indicate property. * * If set, permits indications of a Characteristic Value with acknowledgment. */ GATT_CHRC_PROP_INDICATE = BLE_BIT(5), /** @def BT_GATT_CHRC_AUTH * @brief Characteristic Authenticated Signed Writes property. * * If set, permits signed writes to the Characteristic Value. */ GATT_CHRC_PROP_AUTH = BLE_BIT(6), /** @def BT_GATT_CHRC_EXT_PROP * @brief Characteristic Extended Properties property. * * If set, additional characteristic properties are defined in the * Characteristic Extended Properties Descriptor. */ GATT_CHRC_PROP_EXT_PROP = BLE_BIT(7), } gatt_prop_en; /* Error codes for Error response PDU */ #define ATT_ERR_INVALID_HANDLE 0x01 #define ATT_ERR_READ_NOT_PERMITTED 0x02 #define ATT_ERR_WRITE_NOT_PERMITTED 0x03 #define ATT_ERR_INVALID_PDU 0x04 #define ATT_ERR_AUTHENTICATION 0x05 #define ATT_ERR_NOT_SUPPORTED 0x06 #define ATT_ERR_INVALID_OFFSET 0x07 #define ATT_ERR_AUTHORIZATION 0x08 #define ATT_ERR_PREPARE_QUEUE_FULL 0x09 #define ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a #define ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b #define ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c #define ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d #define ATT_ERR_UNLIKELY 0x0e #define ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f #define ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 #define ATT_ERR_INSUFFICIENT_RESOURCES 0x11 typedef int (*char_read_func_t)(uint16_t conn_handle, uint16_t char_handle, void *buf, uint16_t len, uint16_t offset); typedef int (*char_write_func_t)(uint16_t conn_handle, uint16_t char_handle, void *buf, uint16_t len, uint16_t offset); typedef void (*char_ccc_change_func_t)(ccc_value_en value); struct gatt_char_t { /** Characteristic UUID. */ const uuid_t *uuid; /** Characteristic Value handle. */ uint16_t value_handle; /** Characteristic properties. */ uint8_t properties; }; typedef struct _gatt_cep_t { uint16_t ext_props; } gatt_cep_t; typedef struct _gatt_cud_t { char *user_des; /* User Description */ } gatt_cud_t; typedef struct _gatt_cpf_t { /** Format of the value of the characteristic */ uint8_t format; /** Exponent field to determine how the value of this characteristic is further formatted */ int8_t exponent; /** Unit of the characteristic */ uint16_t unit; /** Name space of the description */ uint8_t name_space; /** Description of the characteristic as defined in a higher layer profile */ uint16_t description; } gatt_cpf_t; #if 0 typedef struct _gatt_att_t { uuid_t *uuid; uint8_t perm; /* for Characteristic Value Declaration*/ union { void *value; gatt_char_t *char_def; gatt_cep_t *cep; gatt_cud_t *cud; gatt_cpf_t *cpf; }; char_read_func_t read; char_write_func_t write; } gatt_att_t; #endif typedef struct _gatt_attr_t { /** Attribute UUID */ uuid_t *uuid; char_read_func_t read; char_write_func_t write; /** Attribute user data */ void *user_data; /** Attribute handle */ uint16_t handle; /** Attribute permissions */ uint8_t perm; } gatt_attr_t; typedef struct { uint8_t val[6]; } bt_addr; typedef struct { uint8_t type; bt_addr a; } bt_addr_le; struct bt_gatt_ccc_cfg_t { uint8_t id; bt_addr_le peer; uint16_t value; }; #define BT_RTL struct bt_gatt_ccc_t { #ifndef BT_RTL struct bt_gatt_ccc_cfg_t cfg[CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN]; #else struct bt_gatt_ccc_cfg_t cfg[2]; #endif uint16_t value; void (*cfg_changed)(const gatt_attr_t *attr, uint16_t value); int (*cfg_write)(void *conn, gatt_attr_t *attr, uint16_t value); int (*cfg_match)(void *conn, gatt_attr_t *attr); }; #define GATT_ATT_DEFINE(_uuid, _perm, _read, _write,_value) \ { \ .uuid = _uuid, \ .perm = _perm, \ .read = _read, \ .write = _write, \ .user_data =(void *){ _value}, \ } #define GATT_PRIMARY_SERVICE_DEFINE(_uuid) \ GATT_ATT_DEFINE(UUID_GATT_PRIMARY, GATT_PERM_READ, NULL, NULL,_uuid) #define GATT_SECONDARY_SERVICE_DEFINE(_uuid) \ GATT_ATT_DEFINE(UUID_GATT_SECONDARY, GATT_PERM_READ, NULL, NULL, _uuid) #define GATT_CHAR_DEFINE(_uuid, _props) \ GATT_ATT_DEFINE(UUID_GATT_CHRC, GATT_PERM_READ, \ NULL, NULL,(&(struct gatt_char_t){.uuid= _uuid,.value_handle = 0,.properties = _props,})) #define GATT_CHAR_VAL_DEFINE(_uuid, _perm) \ GATT_ATT_DEFINE(_uuid, _perm, NULL, NULL, NULL) #define GATT_CHAR_DESCRIPTOR_DEFINE(_uuid, _perm) \ GATT_ATT_DEFINE(_uuid, _perm, NULL, NULL, NULL) #define GATT_CHAR_CCC_DEFINE() \ GATT_ATT_DEFINE(UUID_GATT_CCC, GATT_PERM_READ | GATT_PERM_WRITE, \ NULL, NULL,(&(struct bt_gatt_ccc_t){.cfg= {{0}}})) #define GATT_CHAR_CUD_DEFINE(_value, _perm) \ GATT_ATT_DEFINE(UUID_GATT_CUD, _perm, NULL, NULL,(&(gatt_cud_t) {.user_des = _value})) #define GATT_CHAR_CPF_DEFINE(_value, _perm) \ GATT_ATT_DEFINE(UUID_GATT_CPF, _perm, NULL, NULL,(&(gatt_cep_t) {.ext_props = _value})) typedef enum { GATT_SERVER_TYPE_PRIMARY = 0, GATT_SERVER_TYPE_SECONDARY, GATT_SERVER_TYPE_INCLUDE, } gatt_service_type_en; typedef struct _gatt_service_param_t { uuid_t *uuid; gatt_service_type_en type; } gatt_service_param; #if 0 typedef struct _gatt_char_param_t { uuid_t *uuid; void *value; char_read_func_t read; char_write_func_t write; uint8_t props; uint8_t perm; } gatt_char_param; typedef struct _gatt_char_des_param_t { uuid_t *uuid; void *value; char_read_func_t read; char_write_func_t write; uint8_t perm; } gatt_char_des_param_t; #endif typedef enum { GATT_FIND_PRIMARY_SERVICE, GATT_FIND_INC_SERVICE, GATT_FIND_CHAR, GATT_FIND_CHAR_DESCRIPTOR, } gatt_discovery_type_en; struct _snode_ { struct _snode_ *next; }; typedef struct _snode_ sys_snode; /** @brief GATT Service structure */ typedef struct _gatt_service_ { /** Service Attributes */ struct bt_gatt_attr *attrs; /** Service Attribute count */ uint32_t attr_count; sys_snode node; } gatt_service; int ble_stack_gatt_registe_service(gatt_service *s, gatt_attr_t attrs[], uint16_t attr_num); int ble_stack_gatt_notificate(int16_t conn_handle, uint16_t char_handle, const uint8_t *data, uint16_t len); int ble_stack_gatt_indicate(int16_t conn_handle, int16_t char_handle, const uint8_t *data, uint16_t len); int ble_stack_gatt_mtu_get(int16_t conn_handle); int ble_stack_gatt_mtu_exchange(int16_t conn_handle); int ble_stack_gatt_service_discovery(int16_t conn_handle); int ble_stack_gatt_discovery(int16_t conn_handle, gatt_discovery_type_en type, uuid_t *uuid, uint16_t start_handle, uint16_t end_handle); #define ble_stack_gatt_discovery_all(conn_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_PRIMARY_SERVICE, 0, 0x0001, 0xffff) #define ble_stack_gatt_discovery_primary(conn_handle, uuid, start_handle, end_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_PRIMARY_SERVICE, uuid, start_handle, end_handle) #define ble_stack_gatt_discovery_include(conn_handle, uuid, start_handle, end_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_INC_SERVICE, uuid, start_handle, end_handle) #define ble_stack_gatt_discovery_char_all(conn_handle, start_handle, end_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_CHAR, 0, start_handle, end_handle) #define ble_stack_gatt_discovery_char(conn_handle, uuid, start_handle, end_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_CHAR, uuid, start_handle, end_handle) #define ble_stack_gatt_discovery_descriptor(conn_handle, uuid,start_handle, end_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_CHAR_DESCRIPTOR, uuid, start_handle, end_handle) #define ble_stack_gatt_discovery_descriptor_all(conn_handle, start_handle, end_handle) \ ble_stack_gatt_discovery(conn_handle, GATT_FIND_CHAR_DESCRIPTOR, 0, start_handle, end_handle) typedef enum { GATT_WRITE, GATT_WRITE_WITHOUT_RESPONSE, GATT_WRITE_SINGED, } gatt_write_en; int ble_stack_gatt_write(int16_t conn_handle, uint16_t attr_handle, uint8_t *data, uint16_t len, uint16_t offset, gatt_write_en type); #define ble_stack_gatt_write_response(conn_handle, attr_handle, data, len, offset) \ ble_stack_gatt_write(conn_handle, attr_handle, (uint8_t *)data, len, offset, GATT_WRITE) #define ble_stack_gatt_write_no_response(conn_handle, attr_handle, data, len, offset) \ ble_stack_gatt_write(conn_handle, attr_handle, (uint8_t *)data, len, offset, GATT_WRITE_WITHOUT_RESPONSE) #define ble_stack_gatt_write_signed(conn_handle, attr_handle, data, len, offset) \ ble_stack_gatt_write(conn_handle, attr_handle, (uint8_t *)data, len, offset, GATT_WRITE_SINGED) int ble_stack_gatt_read(int16_t conn_handle, uint16_t attr_handle, uint16_t offset); int ble_stack_gatt_read_multiple(int16_t conn_handle, uint16_t attr_count, uint16_t attr_handle[]); #ifdef __cplusplus } #endif #endif /* __BLE_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/aos/gatt.h
C
apache-2.0
12,930
/* * Copyright (C) 2017 C-SKY Microsystems Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MODELS_H__ #define __MODELS_H__ #ifdef __cplusplus extern "C" { #endif /* SIG Foundation Models, SIG Mesh Profile SPEC v1.0, 4.5.5 */ /* Configuration Server */ #define MESH_MODEL_ID_CFG_SRV 0x0000 /* Configuration Client */ #define MESH_MODEL_ID_CFG_CLI 0x0001 /* Health Server */ #define MESH_MODEL_ID_HEALTH_SRV 0x0002 /* Health Client */ #define MESH_MODEL_ID_HEALTH_CLI 0x0003 /* SIG Mesh Models, SIG Mesh Model SPEC v1.0, 7.3 */ #define MESH_MODEL_ID_GEN_ONOFF_SRV 0x1000 #define MESH_MODEL_ID_GEN_ONOFF_CLI 0x1001 #define MESH_MODEL_ID_GEN_LEVEL_SRV 0x1002 #define MESH_MODEL_ID_GEN_LEVEL_CLI 0x1003 #define MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV 0x1004 #define MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI 0x1005 #define MESH_MODEL_ID_GEN_POWER_ONOFF_SRV 0x1006 #define MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV 0x1007 #define MESH_MODEL_ID_GEN_POWER_ONOFF_CLI 0x1008 #define MESH_MODEL_ID_GEN_POWER_LEVEL_SRV 0x1009 #define MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV 0x100a #define MESH_MODEL_ID_GEN_POWER_LEVEL_CLI 0x100b #define MESH_MODEL_ID_GEN_BATTERY_SRV 0x100c #define MESH_MODEL_ID_GEN_BATTERY_CLI 0x100d #define MESH_MODEL_ID_GEN_LOCATION_SRV 0x100e #define MESH_MODEL_ID_GEN_LOCATION_SETUPSRV 0x100f #define MESH_MODEL_ID_GEN_LOCATION_CLI 0x1010 #define MESH_MODEL_ID_GEN_ADMIN_PROP_SRV 0x1011 #define MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV 0x1012 #define MESH_MODEL_ID_GEN_USER_PROP_SRV 0x1013 #define MESH_MODEL_ID_GEN_CLIENT_PROP_SRV 0x1014 #define MESH_MODEL_ID_GEN_PROP_CLI 0x1015 #define MESH_MODEL_ID_SENSOR_SRV 0x1100 #define MESH_MODEL_ID_SENSOR_SETUP_SRV 0x1101 #define MESH_MODEL_ID_SENSOR_CLI 0x1102 #define MESH_MODEL_ID_TIME_SRV 0x1200 #define MESH_MODEL_ID_TIME_SETUP_SRV 0x1201 #define MESH_MODEL_ID_TIME_CLI 0x1202 #define MESH_MODEL_ID_SCENE_SRV 0x1203 #define MESH_MODEL_ID_SCENE_SETUP_SRV 0x1204 #define MESH_MODEL_ID_SCENE_CLI 0x1205 #define MESH_MODEL_ID_SCHEDULER_SRV 0x1206 #define MESH_MODEL_ID_SCHEDULER_SETUP_SRV 0x1207 #define MESH_MODEL_ID_SCHEDULER_CLI 0x1208 #define MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV 0x1300 #define MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV 0x1301 #define MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI 0x1302 #define MESH_MODEL_ID_LIGHT_CTL_SRV 0x1303 #define MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV 0x1304 #define MESH_MODEL_ID_LIGHT_CTL_CLI 0x1305 #define MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV 0x1306 #define MESH_MODEL_ID_LIGHT_HSL_SRV 0x1307 #define MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV 0x1308 #define MESH_MODEL_ID_LIGHT_HSL_CLI 0x1309 #define MESH_MODEL_ID_LIGHT_HSL_HUE_SRV 0x130a #define MESH_MODEL_ID_LIGHT_HSL_SAT_SRV 0x130b #define MESH_MODEL_ID_LIGHT_XYL_SRV 0x130c #define MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV 0x130d #define MESH_MODEL_ID_LIGHT_XYL_CLI 0x130e #define MESH_MODEL_ID_LIGHT_LC_SRV 0x130f #define MESH_MODEL_ID_LIGHT_LC_SETUPSRV 0x1310 #define MESH_MODEL_ID_LIGHT_LC_CLI 0x1311 #ifndef BIT #define BIT(s) (1 << (s)) #endif /** @def MESH_MODEL_OP1 * @brief 1-octet opcodes * * used for Bluetooth SIG defined application opcodes * * @param b0 1-octet opcode, 0x7F is reserved */ #define MESH_MODEL_OP1(b0) (b0) /** @def MESH_MODEL_OP2 * @brief 2-octet opcodes * * used for Bluetooth SIG defined application opcodes * * @param b0 MSB octet of the 2-octets * @param b1 LSB octet of the 2-octets */ #define MESH_MODEL_OP2(b0, b1) (((b0) << 8) | (b1)) /** @def MESH_MODEL_OP3 * @brief 3-octet opcodes * * used for manufacturer-specific opcodes * * @param b0 opcode, 0~63 is vaild * @param cid company identifiers, 16-bit values defined by the Bluetooth SIG */ #define MESH_MODEL_OP3(b0, cid) ((((b0) << 16) | 0xc00000) | (cid)) /* SIG Mesh opcodes, SIG Mesh Profile SPEC v1.0, 4.3.4 */ #define OP_APP_KEY_ADD MESH_MODEL_OP1(0x00) #define OP_APP_KEY_UPDATE MESH_MODEL_OP1(0x01) #define OP_DEV_COMP_DATA_STATUS MESH_MODEL_OP1(0x02) #define OP_MOD_PUB_SET MESH_MODEL_OP1(0x03) #define OP_HEALTH_CURRENT_STATUS MESH_MODEL_OP1(0x04) #define OP_HEALTH_FAULT_STATUS MESH_MODEL_OP1(0x05) #define OP_HEARTBEAT_PUB_STATUS MESH_MODEL_OP1(0x06) #define OP_APP_KEY_DEL MESH_MODEL_OP2(0x80, 0x00) #define OP_APP_KEY_GET MESH_MODEL_OP2(0x80, 0x01) #define OP_APP_KEY_LIST MESH_MODEL_OP2(0x80, 0x02) #define OP_APP_KEY_STATUS MESH_MODEL_OP2(0x80, 0x03) #define OP_ATTENTION_GET MESH_MODEL_OP2(0x80, 0x04) #define OP_ATTENTION_SET MESH_MODEL_OP2(0x80, 0x05) #define OP_ATTENTION_SET_UNREL MESH_MODEL_OP2(0x80, 0x06) #define OP_ATTENTION_STATUS MESH_MODEL_OP2(0x80, 0x07) #define OP_DEV_COMP_DATA_GET MESH_MODEL_OP2(0x80, 0x08) #define OP_BEACON_GET MESH_MODEL_OP2(0x80, 0x09) #define OP_BEACON_SET MESH_MODEL_OP2(0x80, 0x0a) #define OP_BEACON_STATUS MESH_MODEL_OP2(0x80, 0x0b) #define OP_DEFAULT_TTL_GET MESH_MODEL_OP2(0x80, 0x0c) #define OP_DEFAULT_TTL_SET MESH_MODEL_OP2(0x80, 0x0d) #define OP_DEFAULT_TTL_STATUS MESH_MODEL_OP2(0x80, 0x0e) #define OP_FRIEND_GET MESH_MODEL_OP2(0x80, 0x0f) #define OP_FRIEND_SET MESH_MODEL_OP2(0x80, 0x10) #define OP_FRIEND_STATUS MESH_MODEL_OP2(0x80, 0x11) #define OP_GATT_PROXY_GET MESH_MODEL_OP2(0x80, 0x12) #define OP_GATT_PROXY_SET MESH_MODEL_OP2(0x80, 0x13) #define OP_GATT_PROXY_STATUS MESH_MODEL_OP2(0x80, 0x14) #define OP_KRP_GET MESH_MODEL_OP2(0x80, 0x15) #define OP_KRP_SET MESH_MODEL_OP2(0x80, 0x16) #define OP_KRP_STATUS MESH_MODEL_OP2(0x80, 0x17) #define OP_MOD_PUB_GET MESH_MODEL_OP2(0x80, 0x18) #define OP_MOD_PUB_STATUS MESH_MODEL_OP2(0x80, 0x19) #define OP_MOD_PUB_VA_SET MESH_MODEL_OP2(0x80, 0x1a) #define OP_MOD_SUB_ADD MESH_MODEL_OP2(0x80, 0x1b) #define OP_MOD_SUB_DEL MESH_MODEL_OP2(0x80, 0x1c) #define OP_MOD_SUB_DEL_ALL MESH_MODEL_OP2(0x80, 0x1d) #define OP_MOD_SUB_OVERWRITE MESH_MODEL_OP2(0x80, 0x1e) #define OP_MOD_SUB_STATUS MESH_MODEL_OP2(0x80, 0x1f) #define OP_MOD_SUB_VA_ADD MESH_MODEL_OP2(0x80, 0x20) #define OP_MOD_SUB_VA_DEL MESH_MODEL_OP2(0x80, 0x21) #define OP_MOD_SUB_VA_OVERWRITE MESH_MODEL_OP2(0x80, 0x22) #define OP_NET_TRANSMIT_GET MESH_MODEL_OP2(0x80, 0x23) #define OP_NET_TRANSMIT_SET MESH_MODEL_OP2(0x80, 0x24) #define OP_NET_TRANSMIT_STATUS MESH_MODEL_OP2(0x80, 0x25) #define OP_RELAY_GET MESH_MODEL_OP2(0x80, 0x26) #define OP_RELAY_SET MESH_MODEL_OP2(0x80, 0x27) #define OP_RELAY_STATUS MESH_MODEL_OP2(0x80, 0x28) #define OP_MOD_SUB_GET MESH_MODEL_OP2(0x80, 0x29) #define OP_MOD_SUB_LIST MESH_MODEL_OP2(0x80, 0x2a) #define OP_MOD_SUB_GET_VND MESH_MODEL_OP2(0x80, 0x2b) #define OP_MOD_SUB_LIST_VND MESH_MODEL_OP2(0x80, 0x2c) #define OP_LPN_TIMEOUT_GET MESH_MODEL_OP2(0x80, 0x2d) #define OP_LPN_TIMEOUT_STATUS MESH_MODEL_OP2(0x80, 0x2e) #define OP_HEALTH_FAULT_CLEAR MESH_MODEL_OP2(0x80, 0x2f) #define OP_HEALTH_FAULT_CLEAR_UNREL MESH_MODEL_OP2(0x80, 0x30) #define OP_HEALTH_FAULT_GET MESH_MODEL_OP2(0x80, 0x31) #define OP_HEALTH_FAULT_TEST MESH_MODEL_OP2(0x80, 0x32) #define OP_HEALTH_FAULT_TEST_UNREL MESH_MODEL_OP2(0x80, 0x33) #define OP_HEALTH_PERIOD_GET MESH_MODEL_OP2(0x80, 0x34) #define OP_HEALTH_PERIOD_SET MESH_MODEL_OP2(0x80, 0x35) #define OP_HEALTH_PERIOD_SET_UNREL MESH_MODEL_OP2(0x80, 0x36) #define OP_HEALTH_PERIOD_STATUS MESH_MODEL_OP2(0x80, 0x37) #define OP_HEARTBEAT_PUB_GET MESH_MODEL_OP2(0x80, 0x38) #define OP_HEARTBEAT_PUB_SET MESH_MODEL_OP2(0x80, 0x39) #define OP_HEARTBEAT_SUB_GET MESH_MODEL_OP2(0x80, 0x3a) #define OP_HEARTBEAT_SUB_SET MESH_MODEL_OP2(0x80, 0x3b) #define OP_HEARTBEAT_SUB_STATUS MESH_MODEL_OP2(0x80, 0x3c) #define OP_MOD_APP_BIND MESH_MODEL_OP2(0x80, 0x3d) #define OP_MOD_APP_STATUS MESH_MODEL_OP2(0x80, 0x3e) #define OP_MOD_APP_UNBIND MESH_MODEL_OP2(0x80, 0x3f) #define OP_NET_KEY_ADD MESH_MODEL_OP2(0x80, 0x40) #define OP_NET_KEY_DEL MESH_MODEL_OP2(0x80, 0x41) #define OP_NET_KEY_GET MESH_MODEL_OP2(0x80, 0x42) #define OP_NET_KEY_LIST MESH_MODEL_OP2(0x80, 0x43) #define OP_NET_KEY_STATUS MESH_MODEL_OP2(0x80, 0x44) #define OP_NET_KEY_UPDATE MESH_MODEL_OP2(0x80, 0x45) #define OP_NODE_IDENTITY_GET MESH_MODEL_OP2(0x80, 0x46) #define OP_NODE_IDENTITY_SET MESH_MODEL_OP2(0x80, 0x47) #define OP_NODE_IDENTITY_STATUS MESH_MODEL_OP2(0x80, 0x48) #define OP_NODE_RESET MESH_MODEL_OP2(0x80, 0x49) #define OP_NODE_RESET_STATUS MESH_MODEL_OP2(0x80, 0x4a) #define OP_SIG_MOD_APP_GET MESH_MODEL_OP2(0x80, 0x4b) #define OP_SIG_MOD_APP_LIST MESH_MODEL_OP2(0x80, 0x4c) #define OP_VND_MOD_APP_GET MESH_MODEL_OP2(0x80, 0x4d) #define OP_VND_MOD_APP_LIST MESH_MODEL_OP2(0x80, 0x4e) #ifdef __cplusplus } #endif #endif /* __MODELS_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/aos/models.h
C
apache-2.0
10,888
/* * Copyright (C) 2017 C-SKY Microsystems Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __UUID_H__ #define __UUID_H__ #ifdef __cplusplus extern "C" { #endif //#pragma pack(1) #define BLE_BIT(n) (1UL << (n)) typedef enum { UUID_TYPE_16, UUID_TYPE_32, UUID_TYPE_128, } uuid_type_en; typedef struct _uuid_t { uint8_t type; } uuid_t; struct ut_uuid_16 { uuid_t uuid; uint16_t val; }; struct ut_uuid_32 { uuid_t uuid; uint32_t val; }; struct ut_uuid_128 { uuid_t uuid; uint8_t val[16]; }; #define UUID16_INIT(value) \ { \ .uuid.type = UUID_TYPE_16, \ .val = (value) \ } #define UUID32_INIT(value) \ { \ .uuid.type = UUID_TYPE_32, \ .val = (value)\ } #define UUID128_INIT(value...) \ { \ .uuid.type = UUID_TYPE_128, \ .val = {value},\ } #define UUID16_DECLARE(value) \ ((uuid_t *) (&((struct ut_uuid_16)UUID16_INIT(value)))) #define UUID32_DECLARE(value) \ ((uuid_t *) (&((struct ut_uuid_32)UUID32_INIT(value)))) #define UUID128_DECLARE(value...) \ ((uuid_t *) (&((struct ut_uuid_128)UUID128_INIT(value)))) #define UUID16(__u) (((struct ut_uuid_16 *)(__u))->val) #define UUID32(__u) (((struct ut_uuid_32 *)(__u))->val) #define UUID128(__u) (((struct ut_uuid_128 *)(__u))->val) int uuid_compare(const uuid_t *uuid1, const uuid_t *uuid2); uint8_t *get_uuid_val(uuid_t *uuid); uint8_t UUID_EQUAL(uuid_t *uuid1 , uuid_t *uuid2); #define UUID_TYPE(__u) ((__u)->type) #define UUID_LEN(__u) (UUID_TYPE(__u) == UUID_TYPE_16?2: (UUID_TYPE(__u) == UUID_TYPE_32?4:16)) /** @def UUID_GAP * @brief Generic Access */ #define UUID_GAP UUID16_DECLARE(0x1800) /** @def UUID_GATT * @brief Generic Attribute */ #define UUID_GATT UUID16_DECLARE(0x1801) /** @def UUID_CTS * @brief Current Time Service */ #define UUID_CTS UUID16_DECLARE(0x1805) /** @def UUID_DIS * @brief Device Information Service */ #define UUID_DIS UUID16_DECLARE(0x180a) /** @def UUID_HRS * @brief Heart Rate Service */ #define UUID_HRS UUID16_DECLARE(0x180d) /** @def UUID_BAS * @brief Battery Service */ #define UUID_BAS UUID16_DECLARE(0x180f) /** @def UUID_HIDS * @brief HID Service */ #define UUID_HIDS UUID16_DECLARE(0x1812) /** @def UUID_CSC * @brief Cycling Speed and Cadence Service */ #define UUID_CSC UUID16_DECLARE(0x1816) /** @def UUID_ESS * @brief Environmental Sensing Service */ #define UUID_ESS UUID16_DECLARE(0x181a) /** @def UUID_IPSS * @brief IP Support Service */ #define UUID_IPSS UUID16_DECLARE(0x1820) /** @def UUID_MESH_PROV * @brief Mesh Provisioning Service */ #define UUID_MESH_PROV UUID16_DECLARE(0x1827) /** @def UUID_MESH_PROXY * @brief Mesh Proxy Service */ #define UUID_MESH_PROXY UUID16_DECLARE(0x1828) /** @def UUID_GATT_PRIMARY * @brief GATT Primary Service */ #define UUID_GATT_PRIMARY UUID16_DECLARE(0x2800) /** @def UUID_GATT_SECONDARY * @brief GATT Secondary Service */ #define UUID_GATT_SECONDARY UUID16_DECLARE(0x2801) /** @def UUID_GATT_INCLUDE * @brief GATT Include Service */ #define UUID_GATT_INCLUDE UUID16_DECLARE(0x2802) /** @def UUID_GATT_CHRC * @brief GATT Characteristic */ #define UUID_GATT_CHRC UUID16_DECLARE(0x2803) /** @def UUID_GATT_CEP * @brief GATT Characteristic Extended Properties */ #define UUID_GATT_CEP UUID16_DECLARE(0x2900) /** @def UUID_GATT_CUD * @brief GATT Characteristic User Description */ #define UUID_GATT_CUD UUID16_DECLARE(0x2901) /** @def UUID_GATT_CCC * @brief GATT Client Characteristic Configuration */ #define UUID_GATT_CCC UUID16_DECLARE(0x2902) /** @def UUID_GATT_SCC * @brief GATT Server Characteristic Configuration */ #define UUID_GATT_SCC UUID16_DECLARE(0x2903) /** @def UUID_GATT_CPF * @brief GATT Characteristic Presentation Format */ #define UUID_GATT_CPF UUID16_DECLARE(0x2904) /** @def UUID_VALID_RANGE * @brief Valid Range Descriptor */ #define UUID_VALID_RANGE UUID16_DECLARE(0x2906) /** @def UUID_HIDS_EXT_REPORT * @brief HID External Report Descriptor */ #define UUID_HIDS_EXT_REPORT UUID16_DECLARE(0x2907) /** @def UUID_HIDS_REPORT_REF * @brief HID Report Reference Descriptor */ #define UUID_HIDS_REPORT_REF UUID16_DECLARE(0x2908) /** @def UUID_ES_CONFIGURATION * @brief Environmental Sensing Configuration Descriptor */ #define UUID_ES_CONFIGURATION UUID16_DECLARE(0x290b) /** @def UUID_ES_MEASUREMENT * @brief Environmental Sensing Measurement Descriptor */ #define UUID_ES_MEASUREMENT UUID16_DECLARE(0x290c) /** @def UUID_ES_TRIGGER_SETTING * @brief Environmental Sensing Trigger Setting Descriptor */ #define UUID_ES_TRIGGER_SETTING UUID16_DECLARE(0x290d) /** @def UUID_GAP_DEVICE_NAME * @brief GAP Characteristic Device Name */ #define UUID_GAP_DEVICE_NAME UUID16_DECLARE(0x2a00) /** @def UUID_GAP_APPEARANCE * @brief GAP Characteristic Appearance */ #define UUID_GAP_APPEARANCE UUID16_DECLARE(0x2a01) /** @def UUID_GAP_PPCP * @brief GAP Characteristic Peripheral Preferred Connection Parameters */ #define UUID_GAP_PPCP UUID16_DECLARE(0x2a04) /** @def UUID_GATT_SC * @brief GATT Characteristic Service Changed */ #define UUID_GATT_SC UUID16_DECLARE(0x2a05) /** @def UUID_BAS_BATTERY_LEVEL * @brief BAS Characteristic Battery Level */ #define UUID_BAS_BATTERY_LEVEL UUID16_DECLARE(0x2a19) /** @def UUID_HIDS_BOOT_KB_IN_REPORT * @brief HID Characteristic Boot Keyboard Input Report */ #define UUID_HIDS_BOOT_KB_IN_REPORT UUID16_DECLARE(0x2a22) /** @def UUID_DIS_SYSTEM_ID * @brief DIS Characteristic System ID */ #define UUID_DIS_SYSTEM_ID UUID16_DECLARE(0x2a23) /** @def UUID_DIS_MODEL_NUMBER * @brief DIS Characteristic Model Number String */ #define UUID_DIS_MODEL_NUMBER UUID16_DECLARE(0x2a24) /** @def UUID_DIS_SERIAL_NUMBER * @brief DIS Characteristic Serial Number String */ #define UUID_DIS_SERIAL_NUMBER UUID16_DECLARE(0x2a25) /** @def UUID_DIS_FIRMWARE_REVISION * @brief DIS Characteristic Firmware Revision String */ #define UUID_DIS_FIRMWARE_REVISION UUID16_DECLARE(0x2a26) /** @def UUID_DIS_HARDWARE_REVISION * @brief DIS Characteristic Hardware Revision String */ #define UUID_DIS_HARDWARE_REVISION UUID16_DECLARE(0x2a27) /** @def UUID_DIS_SOFTWARE_REVISION * @brief DIS Characteristic Software Revision String */ #define UUID_DIS_SOFTWARE_REVISION UUID16_DECLARE(0x2a28) /** @def UUID_DIS_MANUFACTURER_NAME * @brief DIS Characteristic Manufacturer Name String */ #define UUID_DIS_MANUFACTURER_NAME UUID16_DECLARE(0x2a29) /** @def UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST * @brief IEEE Regulatory Certification Data List characteristic UUID. */ #define UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST UUID16_DECLARE(0x2a2a) /** @def UUID_DIS_PNP_ID * @brief DIS Characteristic PnP ID */ #define UUID_DIS_PNP_ID UUID16_DECLARE(0x2a50) /** @def UUID_CTS_CURRENT_TIME * @brief CTS Characteristic Current Time */ #define UUID_CTS_CURRENT_TIME UUID16_DECLARE(0x2a2b) /** @def UUID_MAGN_DECLINATION * @brief Magnetic Declination Characteristic */ #define UUID_MAGN_DECLINATION UUID16_DECLARE(0x2a2c) /** @def UUID_HIDS_BOOT_KB_OUT_REPORT * @brief HID Boot Keyboard Output Report Characteristic */ #define UUID_HIDS_BOOT_KB_OUT_REPORT UUID16_DECLARE(0x2a32) /** @def UUID_HIDS_BOOT_MOUSE_IN_REPORT * @brief HID Boot Mouse Input Report Characteristic */ #define UUID_HIDS_BOOT_MOUSE_IN_REPORT UUID16_DECLARE(0x2a33) /** @def UUID_HRS_MEASUREMENT * @brief HRS Characteristic Measurement Interval */ #define UUID_HRS_MEASUREMENT UUID16_DECLARE(0x2a37) /** @def UUID_HRS_BODY_SENSOR * @brief HRS Characteristic Body Sensor Location */ #define UUID_HRS_BODY_SENSOR UUID16_DECLARE(0x2a38) /** @def UUID_HRS_CONTROL_POINT * @brief HRS Characteristic Control Point */ #define UUID_HRS_CONTROL_POINT UUID16_DECLARE(0x2a39) /** @def UUID_HIDS_INFO * @brief HID Information Characteristic */ #define UUID_HIDS_INFO UUID16_DECLARE(0x2a4a) /** @def UUID_HIDS_REPORT_MAP * @brief HID Report Map Characteristic */ #define UUID_HIDS_REPORT_MAP UUID16_DECLARE(0x2a4b) /** @def UUID_HIDS_CTRL_POINT * @brief HID Control Point Characteristic */ #define UUID_HIDS_CTRL_POINT UUID16_DECLARE(0x2a4c) /** @def UUID_HIDS_REPORT * @brief HID Report Characteristic */ #define UUID_HIDS_REPORT UUID16_DECLARE(0x2a4d) /** @def UUID_HIDS_PROTOCOL_MODE * @brief HID Protocol Mode Characteristic */ #define UUID_HIDS_PROTOCOL_MODE UUID16_DECLARE(0x2a4e) /** @def UUID_CSC_MEASUREMENT * @brief CSC Measurement Characteristic */ #define UUID_CSC_MEASUREMENT UUID16_DECLARE(0x2a5b) /** @def UUID_CSC_FEATURE * @brief CSC Feature Characteristic */ #define UUID_CSC_FEATURE UUID16_DECLARE(0x2a5c) /** @def UUID_SENSOR_LOCATION * @brief Sensor Location Characteristic */ #define UUID_SENSOR_LOCATION UUID16_DECLARE(0x2a5d) /** @def UUID_SC_CONTROL_POINT * @brief SC Control Point Characteristic */ #define UUID_SC_CONTROL_POINT UUID16_DECLARE(0x2a55) /** @def UUID_ELEVATION * @brief Elevation Characteristic */ #define UUID_ELEVATION UUID16_DECLARE(0x2a6c) /** @def UUID_PRESSURE * @brief Pressure Characteristic */ #define UUID_PRESSURE UUID16_DECLARE(0x2a6d) /** @def UUID_TEMPERATURE * @brief Temperature Characteristic */ #define UUID_TEMPERATURE UUID16_DECLARE(0x2a6e) /** @def UUID_HUMIDITY * @brief Humidity Characteristic */ #define UUID_HUMIDITY UUID16_DECLARE(0x2a6f) /** @def UUID_TRUE_WIND_SPEED * @brief True Wind Speed Characteristic */ #define UUID_TRUE_WIND_SPEED UUID16_DECLARE(0x2a70) /** @def UUID_TRUE_WIND_DIR * @brief True Wind Direction Characteristic */ #define UUID_TRUE_WIND_DIR UUID16_DECLARE(0x2a71) /** @def UUID_APPARENT_WIND_SPEED * @brief Apparent Wind Speed Characteristic */ #define UUID_APPARENT_WIND_SPEED UUID16_DECLARE(0x2a72) /** @def UUID_APPARENT_WIND_DIR * @brief Apparent Wind Direction Characteristic */ #define UUID_APPARENT_WIND_DIR UUID16_DECLARE(0x2a73) /** @def UUID_GUST_FACTOR * @brief Gust Factor Characteristic */ #define UUID_GUST_FACTOR UUID16_DECLARE(0x2a74) /** @def UUID_POLLEN_CONCENTRATION * @brief Pollen Concentration Characteristic */ #define UUID_POLLEN_CONCENTRATION UUID16_DECLARE(0x2a75) /** @def UUID_UV_INDEX * @brief UV Index Characteristic */ #define UUID_UV_INDEX UUID16_DECLARE(0x2a76) /** @def UUID_IRRADIANCE * @brief Irradiance Characteristic */ #define UUID_IRRADIANCE UUID16_DECLARE(0x2a77) /** @def UUID_RAINFALL * @brief Rainfall Characteristic */ #define UUID_RAINFALL UUID16_DECLARE(0x2a78) /** @def UUID_WIND_CHILL * @brief Wind Chill Characteristic */ #define UUID_WIND_CHILL UUID16_DECLARE(0x2a79) /** @def UUID_HEAT_INDEX * @brief Heat Index Characteristic */ #define UUID_HEAT_INDEX UUID16_DECLARE(0x2a7a) /** @def UUID_DEW_POINT * @brief Dew Point Characteristic */ #define UUID_DEW_POINT UUID16_DECLARE(0x2a7b) /** @def UUID_DESC_VALUE_CHANGED * @brief Descriptor Value Changed Characteristic */ #define UUID_DESC_VALUE_CHANGED UUID16_DECLARE(0x2a7d) /** @def UUID_MAGN_FLUX_DENSITY_2D * @brief Magnetic Flux Density - 2D Characteristic */ #define UUID_MAGN_FLUX_DENSITY_2D UUID16_DECLARE(0x2aa0) /** @def UUID_MAGN_FLUX_DENSITY_3D * @brief Magnetic Flux Density - 3D Characteristic */ #define UUID_MAGN_FLUX_DENSITY_3D UUID16_DECLARE(0x2aa1) /** @def UUID_BAR_PRESSURE_TREND * @brief Barometric Pressure Trend Characteristic */ #define UUID_BAR_PRESSURE_TREND UUID16_DECLARE(0x2aa3) /** @def UUID_CENTRAL_ADDR_RES * @brief Central Address Resolution Characteristic */ #define UUID_CENTRAL_ADDR_RES UUID16_DECLARE(0x2aa6) /** @def UUID_MESH_PROV_DATA_IN * @brief Mesh Provisioning Data In */ #define UUID_MESH_PROV_DATA_IN UUID16_DECLARE(0x2adb) /** @def UUID_MESH_PROV_DATA_OUT * @brief Mesh Provisioning Data Out */ #define UUID_MESH_PROV_DATA_OUT UUID16_DECLARE(0x2adc) /** @def UUID_MESH_PROXY_DATA_IN * @brief Mesh Proxy Data In */ #define UUID_MESH_PROXY_DATA_IN UUID16_DECLARE(0x2add) /** @def UUID_MESH_PROXY_DATA_OUT * @brief Mesh Proxy Data Out */ #define UUID_MESH_PROXY_DATA_OUT UUID16_DECLARE(0x2ade) /* * Protocol UUIDs */ #define UUID_SDP UUID16_DECLARE(0x0001) #define UUID_UDP UUID16_DECLARE(0x0002) #define UUID_RFCOMM UUID16_DECLARE(0x0003) #define UUID_TCP UUID16_DECLARE(0x0004) #define UUID_TCS_BIN UUID16_DECLARE(0x0005) #define UUID_TCS_AT UUID16_DECLARE(0x0006) #define UUID_ATT UUID16_DECLARE(0x0007) #define UUID_OBEX UUID16_DECLARE(0x0008) #define UUID_IP UUID16_DECLARE(0x0009) #define UUID_FTP UUID16_DECLARE(0x000a) #define UUID_HTTP UUID16_DECLARE(0x000c) #define UUID_BNEP UUID16_DECLARE(0x000f) #define UUID_UPNP UUID16_DECLARE(0x0010) #define UUID_HIDP UUID16_DECLARE(0x0011) #define UUID_HCRP_CTRL UUID16_DECLARE(0x0012) #define UUID_HCRP_DATA UUID16_DECLARE(0x0014) #define UUID_HCRP_NOTE UUID16_DECLARE(0x0016) #define UUID_AVCTP UUID16_DECLARE(0x0017) #define UUID_AVDTP UUID16_DECLARE(0x0019) #define UUID_CMTP UUID16_DECLARE(0x001b) #define UUID_UDI UUID16_DECLARE(0x001d) #define UUID_MCAP_CTRL UUID16_DECLARE(0x001e) #define UUID_MCAP_DATA UUID16_DECLARE(0x001f) #define UUID_L2CAP UUID16_DECLARE(0x0100) #ifdef __cplusplus } #endif #endif /* __UUID_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/aos/uuid.h
C
apache-2.0
15,258
/** @file * @brief Advance Audio Distribution Profile - SBC Codec header. */ /* * Copyright (c) 2015-2016 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_A2DP_CODEC_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_A2DP_CODEC_H_ #ifdef __cplusplus extern "C" { #endif /* Sampling Frequency */ #define A2DP_SBC_SAMP_FREQ_16000 BIT(7) #define A2DP_SBC_SAMP_FREQ_32000 BIT(6) #define A2DP_SBC_SAMP_FREQ_44100 BIT(5) #define A2DP_SBC_SAMP_FREQ_48000 BIT(4) /* Channel Mode */ #define A2DP_SBC_CH_MODE_MONO BIT(3) #define A2DP_SBC_CH_MODE_DUAL BIT(2) #define A2DP_SBC_CH_MODE_STREO BIT(1) #define A2DP_SBC_CH_MODE_JOINT BIT(0) /* Block Length */ #define A2DP_SBC_BLK_LEN_4 BIT(7) #define A2DP_SBC_BLK_LEN_8 BIT(6) #define A2DP_SBC_BLK_LEN_12 BIT(5) #define A2DP_SBC_BLK_LEN_16 BIT(4) /* Subbands */ #define A2DP_SBC_SUBBAND_4 BIT(3) #define A2DP_SBC_SUBBAND_8 BIT(2) /* Allocation Method */ #define A2DP_SBC_ALLOC_MTHD_SNR BIT(1) #define A2DP_SBC_ALLOC_MTHD_LOUDNESS BIT(0) #define BT_A2DP_SBC_SAMP_FREQ(preset) ((preset->config[0] >> 4) & 0x0f) #define BT_A2DP_SBC_CHAN_MODE(preset) ((preset->config[0]) & 0x0f) #define BT_A2DP_SBC_BLK_LEN(preset) ((preset->config[1] >> 4) & 0x0f) #define BT_A2DP_SBC_SUB_BAND(preset) ((preset->config[1] >> 2) & 0x03) #define BT_A2DP_SBC_ALLOC_MTHD(preset) ((preset->config[1]) & 0x03) /** @brief SBC Codec */ struct bt_a2dp_codec_sbc_params { /** First two octets of configuration */ u8_t config[2]; /** Minimum Bitpool Value */ u8_t min_bitpool; /** Maximum Bitpool Value */ u8_t max_bitpool; } __packed; #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_A2DP_CODEC_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/a2dp-codec.h
C
apache-2.0
2,215
/** @file * @brief Advance Audio Distribution Profile header. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_A2DP_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_A2DP_H_ #include <bluetooth/avdtp.h> #ifdef __cplusplus extern "C" { #endif /** @brief Stream Structure */ struct bt_a2dp_stream { /* TODO */ }; /** @brief Codec ID */ enum bt_a2dp_codec_id { /** Codec SBC */ BT_A2DP_SBC = 0x00, /** Codec MPEG-1 */ BT_A2DP_MPEG1 = 0x01, /** Codec MPEG-2 */ BT_A2DP_MPEG2 = 0x02, /** Codec ATRAC */ BT_A2DP_ATRAC = 0x04, /** Codec Non-A2DP */ BT_A2DP_VENDOR = 0xff }; /** @brief Preset for the endpoint */ struct bt_a2dp_preset { /** Length of preset */ u8_t len; /** Preset */ u8_t preset[0]; }; /** @brief Stream End Point */ struct bt_a2dp_endpoint { /** Code ID */ u8_t codec_id; /** Stream End Point Information */ struct bt_avdtp_seid_lsep info; /** Pointer to preset codec chosen */ struct bt_a2dp_preset *preset; /** Capabilities */ struct bt_a2dp_preset *caps; }; /** @brief Stream End Point Media Type */ enum MEDIA_TYPE { /** Audio Media Type */ BT_A2DP_AUDIO = 0x00, /** Video Media Type */ BT_A2DP_VIDEO = 0x01, /** Multimedia Media Type */ BT_A2DP_MULTIMEDIA = 0x02 }; /** @brief Stream End Point Role */ enum ROLE_TYPE { /** Source Role */ BT_A2DP_SOURCE = 0, /** Sink Role */ BT_A2DP_SINK = 1 }; /** @brief A2DP structure */ struct bt_a2dp; /** @brief A2DP Connect. * * This function is to be called after the conn parameter is obtained by * performing a GAP procedure. The API is to be used to establish A2DP * connection between devices. * * @param conn Pointer to bt_conn structure. * * @return pointer to struct bt_a2dp in case of success or NULL in case * of error. */ struct bt_a2dp *bt_a2dp_connect(struct bt_conn *conn); /** @brief Endpoint Registration. * * This function is used for registering the stream end points. The user has * to take care of allocating the memory, the preset pointer and then pass the * required arguments. Also, only one sep can be registered at a time. * * @param endpoint Pointer to bt_a2dp_endpoint structure. * @param media_type Media type that the Endpoint is. * @param role Role of Endpoint. * * @return 0 in case of success and error code in case of error. */ int bt_a2dp_register_endpoint(struct bt_a2dp_endpoint *endpoint, u8_t media_type, u8_t role); #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_A2DP_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/a2dp.h
C
apache-2.0
2,544
/** @file * @brief Bluetooth device address definitions and utilities. */ /* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_ADDR_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_ADDR_H_ #include <string.h> #include <stdbool.h> #include <ble_types/types.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Bluetooth device address definitions and utilities. * @defgroup bt_addr Device Address * @ingroup bluetooth * @{ */ #define BT_ADDR_LE_PUBLIC 0x00 #define BT_ADDR_LE_RANDOM 0x01 #define BT_ADDR_LE_PUBLIC_ID 0x02 #define BT_ADDR_LE_RANDOM_ID 0x03 /** Bluetooth Device Address */ typedef struct { u8_t val[6]; } bt_addr_t; /** Bluetooth LE Device Address */ typedef struct { u8_t type; bt_addr_t a; } bt_addr_le_t; #define BT_ADDR_ANY ((bt_addr_t[]) { { { 0, 0, 0, 0, 0, 0 } } }) #define BT_ADDR_NONE ((bt_addr_t[]) { { \ { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } }) #define BT_ADDR_LE_ANY ((bt_addr_le_t[]) { { 0, { { 0, 0, 0, 0, 0, 0 } } } }) #define BT_ADDR_LE_NONE ((bt_addr_le_t[]) { { 0, \ { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } } }) static inline int bt_addr_cmp(const bt_addr_t *a, const bt_addr_t *b) { return memcmp(a, b, sizeof(*a)); } static inline int bt_addr_le_cmp(const bt_addr_le_t *a, const bt_addr_le_t *b) { return memcmp(a, b, sizeof(*a)); } static inline void bt_addr_copy(bt_addr_t *dst, const bt_addr_t *src) { memcpy(dst, src, sizeof(*dst)); } static inline void bt_addr_le_copy(bt_addr_le_t *dst, const bt_addr_le_t *src) { memcpy(dst, src, sizeof(*dst)); } #define BT_ADDR_IS_RPA(a) (((a)->val[5] & 0xc0) == 0x40) #define BT_ADDR_IS_NRPA(a) (((a)->val[5] & 0xc0) == 0x00) #define BT_ADDR_IS_STATIC(a) (((a)->val[5] & 0xc0) == 0xc0) #define BT_ADDR_SET_RPA(a) ((a)->val[5] = (((a)->val[5] & 0x3f) | 0x40)) #define BT_ADDR_SET_NRPA(a) ((a)->val[5] &= 0x3f) #define BT_ADDR_SET_STATIC(a) ((a)->val[5] |= 0xc0) int bt_addr_le_create_nrpa(bt_addr_le_t *addr); int bt_addr_le_create_static(bt_addr_le_t *addr); static inline bool bt_addr_le_is_rpa(const bt_addr_le_t *addr) { if (addr->type != BT_ADDR_LE_RANDOM) { return false; } return BT_ADDR_IS_RPA(&addr->a); } static inline bool bt_addr_le_is_identity(const bt_addr_le_t *addr) { if (addr->type == BT_ADDR_LE_PUBLIC) { return true; } return BT_ADDR_IS_STATIC(&addr->a); } /** * @} */ #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_ADDR_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/addr.h
C
apache-2.0
2,512
/** @file * @brief Attribute Protocol handling. */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_ATT_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_ATT_H_ #include <misc/slist.h> #ifdef __cplusplus extern "C" { #endif /* Error codes for Error response PDU */ #define BT_ATT_ERR_INVALID_HANDLE 0x01 #define BT_ATT_ERR_READ_NOT_PERMITTED 0x02 #define BT_ATT_ERR_WRITE_NOT_PERMITTED 0x03 #define BT_ATT_ERR_INVALID_PDU 0x04 #define BT_ATT_ERR_AUTHENTICATION 0x05 #define BT_ATT_ERR_NOT_SUPPORTED 0x06 #define BT_ATT_ERR_INVALID_OFFSET 0x07 #define BT_ATT_ERR_AUTHORIZATION 0x08 #define BT_ATT_ERR_PREPARE_QUEUE_FULL 0x09 #define BT_ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a #define BT_ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b #define BT_ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c #define BT_ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d #define BT_ATT_ERR_UNLIKELY 0x0e #define BT_ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f #define BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 #define BT_ATT_ERR_INSUFFICIENT_RESOURCES 0x11 #define BT_ATT_ERR_DB_OUT_OF_SYNC 0x12 #define BT_ATT_ERR_VALUE_NOT_ALLOWED 0x13 /* Common Profile Error Codes (from CSS) */ #define BT_ATT_ERR_WRITE_REQ_REJECTED 0xfc #define BT_ATT_ERR_CCC_IMPROPER_CONF 0xfd #define BT_ATT_ERR_PROCEDURE_IN_PROGRESS 0xfe #define BT_ATT_ERR_OUT_OF_RANGE 0xff #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_ATT_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/att.h
C
apache-2.0
1,432
/** @file * @brief Audio/Video Distribution Transport Protocol header. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_AVDTP_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_AVDTP_H_ #ifdef __cplusplus extern "C" { #endif /** @brief AVDTP SEID Information */ struct bt_avdtp_seid_info { /** Stream End Point ID */ u8_t id:6; /** End Point usage status */ u8_t inuse:1; /** Reserved */ u8_t rfa0:1; /** Media-type of the End Point */ u8_t media_type:4; /** TSEP of the End Point */ u8_t tsep:1; /** Reserved */ u8_t rfa1:3; } __packed; /** @brief AVDTP Local SEP*/ struct bt_avdtp_seid_lsep { /** Stream End Point information */ struct bt_avdtp_seid_info sep; /** Pointer to next local Stream End Point structure */ struct bt_avdtp_seid_lsep *next; }; /** @brief AVDTP Stream */ struct bt_avdtp_stream { struct bt_l2cap_br_chan chan; /* Transport Channel*/ struct bt_avdtp_seid_info lsep; /* Configured Local SEP */ struct bt_avdtp_seid_info rsep; /* Configured Remote SEP*/ u8_t state; /* current state of the stream */ struct bt_avdtp_stream *next; }; #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_AVDTP_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/avdtp.h
C
apache-2.0
1,227
/** @file * @brief Bluetooth subsystem core APIs. */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_BLUETOOTH_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_BLUETOOTH_H_ /** * @brief Bluetooth APIs * @defgroup bluetooth Bluetooth APIs * @{ */ #include <stdbool.h> #include <string.h> #include <stdio.h> #include <misc/util.h> #include <net/buf.h> #include <bluetooth/gap.h> #include <bluetooth/addr.h> #include <bluetooth/crypto.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Generic Access Profile * @defgroup bt_gap Generic Access Profile * @ingroup bluetooth * @{ */ /** @def BT_ID_DEFAULT * * Convenience macro for specifying the default identity. This helps * make the code more readable, especially when only one identity is * supported. */ #define BT_ID_DEFAULT 0 /** Opaque type representing an advertiser. */ struct bt_le_ext_adv; /* Don't require everyone to include conn.h */ struct bt_conn; struct bt_le_ext_adv_sent_info { /** The number of advertising events completed. */ u8_t num_sent; }; struct bt_le_ext_adv_connected_info { /** Connection object of the new connection */ struct bt_conn *conn; }; struct bt_le_ext_adv_scanned_info { /** Active scanner LE address and type */ bt_addr_le_t *addr; }; struct bt_le_ext_adv_cb { /** @brief The advertising set has finished sending adv data. * * This callback notifies the application that the advertising set has * finished sending advertising data. * The advertising set can either have been stopped by a timeout or * because the specified number of advertising events has been reached. * * @param adv The advertising set object. * @param info Information about the sent event. */ void (*sent)(struct bt_le_ext_adv *adv, struct bt_le_ext_adv_sent_info *info); /** @brief The advertising set has accepted a new connection. * * This callback notifies the application that the advertising set has * accepted a new connection. * * @param adv The advertising set object. * @param info Information about the connected event. */ void (*connected)(struct bt_le_ext_adv *adv, struct bt_le_ext_adv_connected_info *info); /** @brief The advertising set has sent scan response data. * * This callback notifies the application that the advertising set has * has received a Scan Request packet, and has sent a Scan Response * packet. * * @param adv The advertising set object. * @param addr Information about the scanned event. */ void (*scanned)(struct bt_le_ext_adv *adv, struct bt_le_ext_adv_scanned_info *info); }; /** @typedef bt_ready_cb_t * @brief Callback for notifying that Bluetooth has been enabled. * * @param err zero on success or (negative) error code otherwise. */ typedef void (*bt_ready_cb_t)(int err); /** @brief Enable Bluetooth * * Enable Bluetooth. Must be the called before any calls that * require communication with the local Bluetooth hardware. * * @param cb Callback to notify completion or NULL to perform the * enabling synchronously. * * @return Zero on success or (negative) error code otherwise. */ int bt_enable(bt_ready_cb_t cb); /** @brief Set Bluetooth Device Name * * Set Bluetooth GAP Device Name. * * @param name New name * * @return Zero on success or (negative) error code otherwise. */ int bt_set_name(const char *name); /** @brief Get Bluetooth Device Name * * Get Bluetooth GAP Device Name. * * @return Bluetooth Device Name */ const char *bt_get_name(void); /** @brief Set the local Identity Address * * Allows setting the local Identity Address from the application. * This API must be called before calling bt_enable(). Calling it at any * other time will cause it to fail. In most cases the application doesn't * need to use this API, however there are a few valid cases where * it can be useful (such as for testing). * * At the moment, the given address must be a static random address. In the * future support for public addresses may be added. * * @return Zero on success or (negative) error code otherwise. */ int bt_set_id_addr(const bt_addr_le_t *addr); /** @brief Get the currently configured identities. * * Returns an array of the currently configured identity addresses. To * make sure all available identities can be retrieved, the number of * elements in the @a addrs array should be CONFIG_BT_ID_MAX. The identity * identifier that some APIs expect (such as advertising parameters) is * simply the index of the identity in the @a addrs array. * * @note Deleted identities may show up as BT_LE_ADDR_ANY in the returned * array. * * @param addrs Array where to store the configured identities. * @param count Should be initialized to the array size. Once the function * returns it will contain the number of returned identities. */ void bt_id_get(bt_addr_le_t *addrs, size_t *count); /** @brief Create a new identity. * * Create a new identity using the given address and IRK. This function * can be called before calling bt_enable(), in which case it can be used * to override the controller's public address (in case it has one). However, * the new identity will only be stored persistently in flash when this API * is used after bt_enable(). The reason is that the persistent settings * are loaded after bt_enable() and would therefore cause potential conflicts * with the stack blindly overwriting what's stored in flash. The identity * will also not be written to flash in case a pre-defined address is * provided, since in such a situation the app clearly has some place it got * the address from and will be able to repeat the procedure on every power * cycle, i.e. it would be redundant to also store the information in flash. * * If the application wants to have the stack randomly generate identities * and store them in flash for later recovery, the way to do it would be * to first initialize the stack (using bt_enable), then call settings_load(), * and after that check with bt_id_get() how many identities were recovered. * If an insufficient amount of identities were recovered the app may then * call bt_id_create() to create new ones. * * @param addr Address to use for the new identity. If NULL or initialized * to BT_ADDR_LE_ANY the stack will generate a new static * random address for the identity and copy it to the given * parameter upon return from this function (in case the * parameter was non-NULL). * @param irk Identity Resolving Key (16 bytes) to be used with this * identity. If set to all zeroes or NULL, the stack will * generate a random IRK for the identity and copy it back * to the parameter upon return from this function (in case * the parameter was non-NULL). If privacy * :option:`CONFIG_BT_PRIVACY` is not enabled this parameter must * be NULL. * * @return Identity identifier (>= 0) in case of success, or a negative * error code on failure. */ int bt_id_create(bt_addr_le_t *addr, u8_t *irk); /** @brief Reset/reclaim an identity for reuse. * * The semantics of the @a addr and @a irk parameters of this function * are the same as with bt_id_create(). The difference is the first * @a id parameter that needs to be an existing identity (if it doesn't * exist this function will return an error). When given an existing * identity this function will disconnect any connections created using it, * remove any pairing keys or other data associated with it, and then create * a new identity in the same slot, based on the @a addr and @a irk * parameters. * * @note the default identity (BT_ID_DEFAULT) cannot be reset, i.e. this * API will return an error if asked to do that. * * @param id Existing identity identifier. * @param addr Address to use for the new identity. If NULL or initialized * to BT_ADDR_LE_ANY the stack will generate a new static * random address for the identity and copy it to the given * parameter upon return from this function (in case the * parameter was non-NULL). * @param irk Identity Resolving Key (16 bytes) to be used with this * identity. If set to all zeroes or NULL, the stack will * generate a random IRK for the identity and copy it back * to the parameter upon return from this function (in case * the parameter was non-NULL). If privacy * :option:`CONFIG_BT_PRIVACY` is not enabled this parameter must * be NULL. * * @return Identity identifier (>= 0) in case of success, or a negative * error code on failure. */ int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk); /** @brief Delete an identity. * * When given a valid identity this function will disconnect any connections * created using it, remove any pairing keys or other data associated with * it, and then flag is as deleted, so that it can not be used for any * operations. To take back into use the slot the identity was occupying the * bt_id_reset() API needs to be used. * * @note the default identity (BT_ID_DEFAULT) cannot be deleted, i.e. this * API will return an error if asked to do that. * * @param id Existing identity identifier. * * @return 0 in case of success, or a negative error code on failure. */ int bt_id_delete(u8_t id); /** @brief Bluetooth data. * * Description of different data types that can be encoded into * advertising data. Used to form arrays that are passed to the * bt_le_adv_start() function. */ struct bt_data { u8_t type; u8_t data_len; const u8_t *data; }; /** @brief Helper to declare elements of bt_data arrays * * This macro is mainly for creating an array of struct bt_data * elements which is then passed to e.g. @ref bt_le_adv_start(). * * @param _type Type of advertising data field * @param _data Pointer to the data field payload * @param _data_len Number of bytes behind the _data pointer */ #define BT_DATA(_type, _data, _data_len) \ { \ .type = (_type), \ .data_len = (_data_len), \ .data = (const u8_t *)(_data), \ } /** @brief Helper to declare elements of bt_data arrays * * This macro is mainly for creating an array of struct bt_data * elements which is then passed to e.g. @ref bt_le_adv_start(). * * @param _type Type of advertising data field * @param _bytes Variable number of single-byte parameters */ #define BT_DATA_BYTES(_type, _bytes...) \ BT_DATA(_type, ((u8_t []) { _bytes }), \ sizeof((u8_t []) { _bytes })) /** Advertising options */ enum { /** Convenience value when no options are specified. */ BT_LE_ADV_OPT_NONE = 0, /** @brief Advertise as connectable. * * Advertise as connectable. If not connectable then the type of * advertising is determined by providing scan response data. * The advertiser address is determined by the type of advertising * and/or enabling privacy :option:`CONFIG_BT_PRIVACY`. */ BT_LE_ADV_OPT_CONNECTABLE = BIT(0), /** @brief Advertise one time. * * Don't try to resume connectable advertising after a connection. * This option is only meaningful when used together with * BT_LE_ADV_OPT_CONNECTABLE. If set the advertising will be stopped * when bt_le_adv_stop() is called or when an incoming (slave) * connection happens. If this option is not set the stack will * take care of keeping advertising enabled even as connections * occur. * If Advertising directed or the advertiser was started with * @ref bt_le_ext_adv_start then this behavior is the default behavior * and this flag has no effect. */ BT_LE_ADV_OPT_ONE_TIME = BIT(1), /** @brief Advertise using identity address. * * Advertise using the identity address as the advertiser address. * @warning This will compromise the privacy of the device, so care * must be taken when using this option. * @note The address used for advertising will not be the same as * returned by @ref bt_le_oob_get_local, instead @ref bt_id_get * should be used to get the LE address. */ BT_LE_ADV_OPT_USE_IDENTITY = BIT(2), /** Advertise using GAP device name */ BT_LE_ADV_OPT_USE_NAME = BIT(3), /** @brief Low duty cycle directed advertising. * * Use low duty directed advertising mode, otherwise high duty mode * will be used. */ BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY = BIT(4), /** @brief Directed advertising to privacy-enabled peer. * * Enable use of Resolvable Private Address (RPA) as the target address * in directed advertisements when :option:`CONFIG_BT_PRIVACY` is not * enabled. * This is required if the remote device is privacy-enabled and * supports address resolution of the target address in directed * advertisement. * It is the responsibility of the application to check that the remote * device supports address resolution of directed advertisements by * reading its Central Address Resolution characteristic. */ BT_LE_ADV_OPT_DIR_ADDR_RPA = BIT(5), /** Use whitelist to filter devices that can request scan response data. */ BT_LE_ADV_OPT_FILTER_SCAN_REQ = BIT(6), /** Use whitelist to filter devices that can connect. */ BT_LE_ADV_OPT_FILTER_CONN = BIT(7), /** Notify the application when a scan response data has been sent to an * active scanner. */ BT_LE_ADV_OPT_NOTIFY_SCAN_REQ = BIT(8), /** @brief Support scan response data. * * When used together with @ref BT_LE_ADV_OPT_EXT_ADV then this option * cannot be used together with the @ref BT_LE_ADV_OPT_CONNECTABLE * option. * When used together with @ref BT_LE_ADV_OPT_EXT_ADV then scan * response data must be set. */ BT_LE_ADV_OPT_SCANNABLE = BIT(9), /** @brief Advertise with extended advertising. * * This options enables extended advertising in the advertising set. * In extended advertising the advertising set will send a small header * packet on the three primary advertising channels. This small header * points to the advertising data packet that will be sent on one of * the 37 secondary advertising channels. * The advertiser will send primary advertising on LE 1M PHY, and * secondary advertising on LE 2M PHY. * Connections will be established on LE 2M PHY. * * Without this option the advertiser will send advertising data on the * three primary advertising channels. * * @note Enabling this option requires extended advertising support in * the peer devices scanning for advertisement packets. */ BT_LE_ADV_OPT_EXT_ADV = BIT(10), /** @brief Disable use of LE 2M PHY on the secondary advertising * channel. * * Disabling the use of LE 2M PHY could be necessary if scanners don't * support the LE 2M PHY. * The advertiser will send primary advertising on LE 1M PHY, and * secondary advertising on LE 1M PHY. * Connections will be established on LE 1M PHY. * * @note Cannot be set if BT_LE_ADV_OPT_CODED is set. * * @note Requires @ref BT_LE_ADV_OPT_EXT_ADV. */ BT_LE_ADV_OPT_NO_2M = BIT(11), /** @brief Advertise on the LE Coded PHY (Long Range). * * The advertiser will send both primary and secondary advertising * on the LE Coded PHY. This gives the advertiser increased range with * the trade-off of lower data rate and higher power consumption. * Connections will be established on LE Coded PHY. * * @note Requires @ref BT_LE_ADV_OPT_EXT_ADV */ BT_LE_ADV_OPT_CODED = BIT(12), /** @brief Advertise without a device address (identity or RPA). * * @note Requires @ref BT_LE_ADV_OPT_EXT_ADV */ BT_LE_ADV_OPT_ANONYMOUS = BIT(13), /** @brief Advertise with transmit power. * * @note Requires @ref BT_LE_ADV_OPT_EXT_ADV */ BT_LE_ADV_OPT_USE_TX_POWER = BIT(14), }; /** LE Advertising Parameters. */ struct bt_le_adv_param { /** @brief Local identity. * * @note When extended advertising :option:`CONFIG_BT_EXT_ADV` is not * enabled or not supported by the controller it is not possible * to scan and advertise simultaneously using two different * random addresses. * * @note It is not possible to have multiple connectable advertising * sets advertising simultaneously using different identities. */ u8_t id; /** @brief Advertising Set Identifier, valid range 0x00 - 0x0f. * * @note Requires @ref BT_LE_ADV_OPT_EXT_ADV **/ u8_t sid; /** @brief Secondary channel maximum skip count. * * Maximum advertising events the advertiser can skip before it must * send advertising data on the secondary advertising channel. * * @note Requires @ref BT_LE_ADV_OPT_EXT_ADV */ u8_t secondary_max_skip; /** Bit-field of advertising options */ bt_u32_t options; /** Minimum Advertising Interval (N * 0.625) */ bt_u32_t interval_min; /** Maximum Advertising Interval (N * 0.625) */ bt_u32_t interval_max; u8_t channel_map; /** @brief Directed advertising to peer * * When this parameter is set the advertiser will send directed * advertising to the remote device. * * The advertising type will either be high duty cycle, or low duty * cycle if the BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY option is enabled. * * In case of connectable high duty cycle if the connection could not * be established within the timeout the connected() callback will be * called with the status set to @ref BT_HCI_ERR_ADV_TIMEOUT. */ const bt_addr_le_t *peer; }; /** @brief Initialize advertising parameters * * @param _options Advertising Options * @param _int_min Minimum advertising interval * @param _int_max Maximum advertising interval * @param _peer Peer address, set to NULL for undirected advertising or * address of peer for directed advertising. */ #define BT_LE_ADV_PARAM_INIT(_options, _int_min, _int_max, _peer) \ { \ .id = BT_ID_DEFAULT, \ .sid = 0, \ .secondary_max_skip = 0, \ .options = (_options), \ .interval_min = (_int_min), \ .interval_max = (_int_max), \ .peer = (_peer), \ } /** @brief Helper to declare advertising parameters inline * * @param _options Advertising Options * @param _int_min Minimum advertising interval * @param _int_max Maximum advertising interval * @param _peer Peer address, set to NULL for undirected advertising or * address of peer for directed advertising. */ #define BT_LE_ADV_PARAM(_options, _int_min, _int_max, _peer) \ ((struct bt_le_adv_param[]) { \ BT_LE_ADV_PARAM_INIT(_options, _int_min, _int_max, _peer) \ }) #define BT_LE_ADV_CONN_DIR(_peer) BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | \ BT_LE_ADV_OPT_ONE_TIME, 0, 0,\ _peer) #define BT_LE_ADV_CONN BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE, \ BT_GAP_ADV_FAST_INT_MIN_2, \ BT_GAP_ADV_FAST_INT_MAX_2, NULL) #define BT_LE_ADV_CONN_NAME BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | \ BT_LE_ADV_OPT_USE_NAME, \ BT_GAP_ADV_FAST_INT_MIN_2, \ BT_GAP_ADV_FAST_INT_MAX_2, NULL) #define BT_LE_ADV_CONN_DIR_LOW_DUTY(_peer) \ BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME | \ BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY, \ BT_GAP_ADV_FAST_INT_MIN_2, BT_GAP_ADV_FAST_INT_MAX_2, \ _peer) #define BT_LE_ADV_NCONN BT_LE_ADV_PARAM(0, BT_GAP_ADV_FAST_INT_MIN_2, \ BT_GAP_ADV_FAST_INT_MAX_2, NULL) #define BT_LE_ADV_NCONN_NAME BT_LE_ADV_PARAM(BT_LE_ADV_OPT_USE_NAME, \ BT_GAP_ADV_FAST_INT_MIN_2, \ BT_GAP_ADV_FAST_INT_MAX_2, NULL) /** @brief Start advertising * * Set advertisement data, scan response data, advertisement parameters * and start advertising. * * When the advertisement parameter peer address has been set the advertising * will be directed to the peer. In this case advertisement data and scan * response data parameters are ignored. If the mode is high duty cycle * the timeout will be @ref BT_GAP_ADV_HIGH_DUTY_CYCLE_MAX_TIMEOUT. * * @param param Advertising parameters. * @param ad Data to be used in advertisement packets. * @param ad_len Number of elements in ad * @param sd Data to be used in scan response packets. * @param sd_len Number of elements in sd * * @return Zero on success or (negative) error code otherwise. * @return -ENOMEM No free connection objects available for connectable * advertiser. * @return -ECONNREFUSED When connectable advertising is requested and there * is already maximum number of connections established * in the controller. * This error code is only guaranteed when using Zephyr * controller, for other controllers code returned in * this case may be -EIO. */ int bt_le_adv_start(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len); /** @brief Update advertising * * Update advertisement and scan response data. * * @param ad Data to be used in advertisement packets. * @param ad_len Number of elements in ad * @param sd Data to be used in scan response packets. * @param sd_len Number of elements in sd * * @return Zero on success or (negative) error code otherwise. */ int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len); /** @brief Stop advertising * * Stops ongoing advertising. * * @return Zero on success or (negative) error code otherwise. */ int bt_le_adv_stop(void); /** @brief Create advertising set. * * Create a new advertising set and set advertising parameters. * Advertising parameters can be updated with @ref bt_le_ext_adv_update_param. * * @param[in] param Advertising parameters. * @param[in] cb Callback struct to notify about advertiser activity. Can be * NULL. Must point to valid memory during the lifetime of the * advertising set. * @param[out] adv Valid advertising set object on success. * * @return Zero on success or (negative) error code otherwise. */ int bt_le_ext_adv_create(const struct bt_le_adv_param *param, const struct bt_le_ext_adv_cb *cb, struct bt_le_ext_adv **adv); struct bt_le_ext_adv_start_param { /** @brief Advertiser timeout (N * 10 ms). * * Application will be notified by the advertiser sent callback. * Set to zero for no timeout. * * When using high duty cycle directed connectable advertising then * this parameters must be set to a non-zero value less than or equal * to the maximum of @ref BT_GAP_ADV_HIGH_DUTY_CYCLE_MAX_TIMEOUT. * * If privacy :option:`CONFIG_BT_PRIVACY` is enabled then the timeout * must be less than :option:`CONFIG_BT_RPA_TIMEOUT`. */ u16_t timeout; /** @brief Number of advertising events. * * Application will be notified by the advertiser sent callback. * Set to zero for no limit. */ u8_t num_events; }; /** @brief Start advertising with the given advertising set * * If the advertiser is limited by either the timeout or number of advertising * events the application will be notified by the advertiser sent callback once * the limit is reached. * If the advertiser is limited by both the timeout and the number of * advertising events then the limit that is reached first will stop the * advertiser. * * @param adv Advertising set object. * @param param Advertise start parameters. */ int bt_le_ext_adv_start(struct bt_le_ext_adv *adv, struct bt_le_ext_adv_start_param *param); /** @brief Stop advertising with the given advertising set * * Stop advertising with a specific advertising set. When using this function * the advertising sent callback will not be called. * * @param adv Advertising set object. * * @return Zero on success or (negative) error code otherwise. */ int bt_le_ext_adv_stop(struct bt_le_ext_adv *adv); /** @brief Set an advertising set's advertising or scan response data. * * Set advertisement data or scan response data. If the advertising set is * currently advertising then the advertising data will be updated in * subsequent advertising events. * * If the advertising set has been configured to send advertising data on the * primary advertising channels then the maximum data length is * @ref BT_GAP_ADV_MAX_ADV_DATA_LEN bytes. * If the advertising set has been configured for extended advertising, * then the maximum data length is defined by the controller with the maximum * possible of @ref BT_GAP_ADV_MAX_EXT_ADV_DATA_LEN bytes. * * @note Not all scanners support extended data length advertising data. * * @note When updating the advertising data while advertising the advertising * data and scan response data length must be smaller or equal to what * can be fit in a single advertising packet. Otherwise the * advertiser must be stopped. * * @param adv Advertising set object. * @param ad Data to be used in advertisement packets. * @param ad_len Number of elements in ad * @param sd Data to be used in scan response packets. * @param sd_len Number of elements in sd * * @return Zero on success or (negative) error code otherwise. */ int bt_le_ext_adv_set_data(struct bt_le_ext_adv *adv, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len); /** @brief Update advertising parameters. * * Update the advertising parameters. The function will return an error if the * advertiser set is currently advertising. Stop the advertising set before * calling this function. * * @param adv Advertising set object. * @param param Advertising parameters. * * @return Zero on success or (negative) error code otherwise. */ int bt_le_ext_adv_update_param(struct bt_le_ext_adv *adv, const struct bt_le_adv_param *param); /** @brief Delete advertising set. * * Delete advertising set. This will free up the advertising set and make it * possible to create a new advertising set. * * @return Zero on success or (negative) error code otherwise. */ int bt_le_ext_adv_delete(struct bt_le_ext_adv *adv); /** @brief Get array index of an advertising set. * * This function is used to map bt_adv to index of an array of * advertising sets. The array has CONFIG_BT_EXT_ADV_MAX_ADV_SET elements. * * @param adv Advertising set. * * @return Index of the advertising set object. * The range of the returned value is 0..CONFIG_BT_EXT_ADV_MAX_ADV_SET-1 */ u8_t bt_le_ext_adv_get_index(struct bt_le_ext_adv *adv); /** @brief Advertising set info structure. */ struct bt_le_ext_adv_info { /* Local identity */ u8_t id; /** Currently selected Transmit Power (dBM). */ s8_t tx_power; }; /** @brief Get advertising set info * * @param adv Advertising set object * @param info Advertising set info object * * @return Zero on success or (negative) error code on failure. */ int bt_le_ext_adv_get_info(const struct bt_le_ext_adv *adv, struct bt_le_ext_adv_info *info); /** @typedef bt_le_scan_cb_t * @brief Callback type for reporting LE scan results. * * A function of this type is given to the bt_le_scan_start() function * and will be called for any discovered LE device. * * @param addr Advertiser LE address and type. * @param rssi Strength of advertiser signal. * @param adv_type Type of advertising response from advertiser. * @param buf Buffer containing advertiser data. */ typedef void bt_le_scan_cb_t(const bt_addr_le_t *addr, s8_t rssi, u8_t adv_type, struct net_buf_simple *buf); enum { /** Convenience value when no options are specified. */ BT_LE_SCAN_OPT_NONE = 0, /** Filter duplicates. */ BT_LE_SCAN_OPT_FILTER_DUPLICATE = BIT(0), /** Filter using whitelist. */ BT_LE_SCAN_OPT_FILTER_WHITELIST = BIT(1), /** Enable scan on coded PHY (Long Range).*/ BT_LE_SCAN_OPT_CODED = BIT(2), /** @brief Disable scan on 1M phy. * * @note Requires @ref BT_LE_SCAN_OPT_CODED. */ BT_LE_SCAN_OPT_NO_1M = BIT(3), BT_LE_SCAN_FILTER_DUPLICATE = BT_LE_SCAN_OPT_FILTER_DUPLICATE, // __deprecated BT_LE_SCAN_FILTER_WHITELIST = BT_LE_SCAN_OPT_FILTER_WHITELIST, // __deprecated }; enum { /** Scan without requesting additional information from advertisers. */ BT_LE_SCAN_TYPE_PASSIVE = 0x00, /** Scan and request additional information from advertisers. */ BT_LE_SCAN_TYPE_ACTIVE = 0x01, }; /** LE scan parameters */ struct bt_le_scan_param { /** Scan type (BT_LE_SCAN_TYPE_ACTIVE or BT_LE_SCAN_TYPE_PASSIVE) */ u8_t type; union { /** Bit-field of scanning filter options. */ bt_u32_t filter_dup; // __deprecated /** Bit-field of scanning options. */ bt_u32_t options; }; /** Scan interval (N * 0.625 ms) */ u16_t interval; /** Scan window (N * 0.625 ms) */ u16_t window; /** @brief Scan timeout (N * 10 ms) * * Application will be notified by the scan timeout callback. * Set zero to disable timeout. */ u16_t timeout; /** @brief Scan interval LE Coded PHY (N * 0.625 MS) * * Set zero to use same as LE 1M PHY scan interval. */ u16_t interval_coded; /** @brief Scan window LE Coded PHY (N * 0.625 MS) * * Set zero to use same as LE 1M PHY scan window. */ u16_t window_coded; }; /** LE advertisement packet information */ struct bt_le_scan_recv_info { /** @brief Advertiser LE address and type. * * If advertiser is anonymous then this address will be * @ref BT_ADDR_LE_ANY. */ const bt_addr_le_t *addr; /** Advertising Set Identifier. */ u8_t sid; /** Strength of advertiser signal. */ s8_t rssi; /** Transmit power of the advertiser. */ s8_t tx_power; /** Advertising packet type. */ u8_t adv_type; /** Advertising packet properties. */ u16_t adv_props; /** Primary advertising channel PHY. */ u8_t primary_phy; /** Secondary advertising channel PHY. */ u8_t secondary_phy; }; /** Listener context for (LE) scanning. */ struct bt_le_scan_cb { /** @brief Advertisement packet received callback. * * @param info Advertiser packet information. * @param buf Buffer containing advertiser data. */ void (*recv)(const struct bt_le_scan_recv_info *info, struct net_buf_simple *buf); /** @brief The scanner has stopped scanning after scan timeout. */ void (*timeout)(void); sys_snode_t node; }; /** @brief Initialize scan parameters * * @param _type Scan Type, BT_LE_SCAN_TYPE_ACTIVE or * BT_LE_SCAN_TYPE_PASSIVE. * @param _options Scan options * @param _interval Scan Interval (N * 0.625 ms) * @param _window Scan Window (N * 0.625 ms) */ #define BT_LE_SCAN_PARAM_INIT(_type, _options, _interval, _window) \ { \ .type = (_type), \ .options = (_options), \ .interval = (_interval), \ .window = (_window), \ .timeout = 0, \ .interval_coded = 0, \ .window_coded = 0, \ } /** @brief Helper to declare scan parameters inline * * @param _type Scan Type, BT_LE_SCAN_TYPE_ACTIVE or * BT_LE_SCAN_TYPE_PASSIVE. * @param _options Scan options * @param _interval Scan Interval (N * 0.625 ms) * @param _window Scan Window (N * 0.625 ms) */ #define BT_LE_SCAN_PARAM(_type, _options, _interval, _window) \ ((struct bt_le_scan_param[]) { \ BT_LE_SCAN_PARAM_INIT(_type, _options, _interval, _window) \ }) /** Helper macro to enable active scanning to discover new devices. */ #define BT_LE_SCAN_ACTIVE BT_LE_SCAN_PARAM(BT_LE_SCAN_TYPE_ACTIVE, \ BT_LE_SCAN_OPT_FILTER_DUPLICATE, \ BT_GAP_SCAN_FAST_INTERVAL, \ BT_GAP_SCAN_FAST_WINDOW) /** @brief Helper macro to enable passive scanning to discover new devices. * * This macro should be used if information required for device identification * (e.g., UUID) are known to be placed in Advertising Data. */ #define BT_LE_SCAN_PASSIVE BT_LE_SCAN_PARAM(BT_LE_SCAN_TYPE_PASSIVE, \ BT_LE_SCAN_OPT_FILTER_DUPLICATE, \ BT_GAP_SCAN_FAST_INTERVAL, \ BT_GAP_SCAN_FAST_WINDOW) /** @brief Start (LE) scanning * * Start LE scanning with given parameters and provide results through * the specified callback. * * @note The LE scanner by default does not use the Identity Address of the * local device when :option:`CONFIG_BT_PRIVACY` is disabled. This is to * prevent the active scanner from disclosing the identity information * when requesting additional information from advertisers. * In order to enable directed advertiser reports then * :option:`CONFIG_BT_SCAN_WITH_IDENTITY` must be enabled. * * @param param Scan parameters. * @param cb Callback to notify scan results. May be NULL if callback * registration through @ref bt_le_scan_cb_register is preferred. * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb); /** @brief Stop (LE) scanning. * * Stops ongoing LE scanning. * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_scan_stop(void); /** @brief Register scanner packet callbacks. * * Adds the callback structure to the list of callback structures that monitors * scanner activity. * * This callback will be called for all scanner activity, regardless of what * API was used to start the scanner. * * @param cb Callback struct. Must point to static memory. */ void bt_le_scan_cb_register(struct bt_le_scan_cb *cb); /** @brief Add device (LE) to whitelist. * * Add peer device LE address to the whitelist. * * @note The whitelist cannot be modified when an LE role is using * the whitelist, i.e advertiser or scanner using a whitelist or automatic * connecting to devices using whitelist. * * @param addr Bluetooth LE identity address. * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_whitelist_add(const bt_addr_le_t *addr); /** @brief Remove device (LE) from whitelist. * * Remove peer device LE address from the whitelist. * * @note The whitelist cannot be modified when an LE role is using * the whitelist, i.e advertiser or scanner using a whitelist or automatic * connecting to devices using whitelist. * * @param addr Bluetooth LE identity address. * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_whitelist_rem(const bt_addr_le_t *addr); /** @brief Clear whitelist. * * Clear all devices from the whitelist. * * @note The whitelist cannot be modified when an LE role is using * the whitelist, i.e advertiser or scanner using a whitelist or automatic * connecting to devices using whitelist. * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_whitelist_clear(void); int bt_le_whitelist_size(u8_t *size); /** @brief Set (LE) channel map. * * @param chan_map Channel map. * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_set_chan_map(u8_t chan_map[5]); /** @brief Helper for parsing advertising (or EIR or OOB) data. * * A helper for parsing the basic data types used for Extended Inquiry * Response (EIR), Advertising Data (AD), and OOB data blocks. The most * common scenario is to call this helper on the advertising data * received in the callback that was given to bt_le_scan_start(). * * @param ad Advertising data as given to the bt_le_scan_cb_t callback. * @param func Callback function which will be called for each element * that's found in the data. The callback should return * true to continue parsing, or false to stop parsing. * @param user_data User data to be passed to the callback. */ void bt_data_parse(struct net_buf_simple *ad, bool (*func)(struct bt_data *data, void *user_data), void *user_data); /** LE Secure Connections pairing Out of Band data. */ struct bt_le_oob_sc_data { /** Random Number. */ u8_t r[16]; /** Confirm Value. */ u8_t c[16]; }; /** LE Out of Band information. */ struct bt_le_oob { /** LE address. If privacy is enabled this is a Resolvable Private * Address. */ bt_addr_le_t addr; /** LE Secure Connections pairing Out of Band data. */ struct bt_le_oob_sc_data le_sc_data; }; /** @brief Get local LE Out of Band (OOB) information. * * This function allows to get local information that are useful for * Out of Band pairing or connection creation. * * If privacy :option:`CONFIG_BT_PRIVACY` is enabled this will result in * generating new Resolvable Private Address (RPA) that is valid for * :option:`CONFIG_BT_RPA_TIMEOUT` seconds. This address will be used for * advertising started by @ref bt_le_adv_start, active scanning and * connection creation. * * @note If privacy is enabled the RPA cannot be refreshed in the following * cases: * - Creating a connection in progress, wait for the connected callback. * In addition when extended advertising :option:`CONFIG_BT_EXT_ADV` is * not enabled or not supported by the controller: * - Advertiser is enabled using a Random Static Identity Address for a * different local identity. * - The local identity conflicts with the local identity used by other * roles. * * @param[in] id Local identity, in most cases BT_ID_DEFAULT. * @param[out] oob LE OOB information * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob); /** @brief Get local LE Out of Band (OOB) information. * * This function allows to get local information that are useful for * Out of Band pairing or connection creation. * * If privacy :option:`CONFIG_BT_PRIVACY` is enabled this will result in * generating new Resolvable Private Address (RPA) that is valid for * :option:`CONFIG_BT_RPA_TIMEOUT` seconds. This address will be used by the * advertising set. * * @note When generating OOB information for multiple advertising set all * OOB information needs to be generated at the same time. * * @note If privacy is enabled the RPA cannot be refreshed in the following * cases: * - Creating a connection in progress, wait for the connected callback. * * @param[in] adv The advertising set object * @param[out] oob LE OOB information * * @return Zero on success or error code otherwise, positive in case * of protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_ext_adv_oob_get_local(struct bt_le_ext_adv *adv, struct bt_le_oob *oob); /** @brief BR/EDR discovery result structure */ struct bt_br_discovery_result { /** private */ u8_t _priv[4]; /** Remote device address */ bt_addr_t addr; /** RSSI from inquiry */ s8_t rssi; /** Class of Device */ u8_t cod[3]; /** Extended Inquiry Response */ u8_t eir[240]; }; /** @typedef bt_br_discovery_cb_t * @brief Callback type for reporting BR/EDR discovery (inquiry) * results. * * A callback of this type is given to the bt_br_discovery_start() * function and will be called at the end of the discovery with * information about found devices populated in the results array. * * @param results Storage used for discovery results * @param count Number of valid discovery results. */ typedef void bt_br_discovery_cb_t(struct bt_br_discovery_result *results, size_t count); /** BR/EDR discovery parameters */ struct bt_br_discovery_param { /** Maximum length of the discovery in units of 1.28 seconds. * Valid range is 0x01 - 0x30. */ u8_t length; /** True if limited discovery procedure is to be used. */ bool limited; }; /** @brief Start BR/EDR discovery * * Start BR/EDR discovery (inquiry) and provide results through the specified * callback. When bt_br_discovery_cb_t is called it indicates that discovery * has completed. If more inquiry results were received during session than * fits in provided result storage, only ones with highest RSSI will be * reported. * * @param param Discovery parameters. * @param results Storage for discovery results. * @param count Number of results in storage. Valid range: 1-255. * @param cb Callback to notify discovery results. * * @return Zero on success or error code otherwise, positive in case * of protocol error or negative (POSIX) in case of stack internal error */ int bt_br_discovery_start(const struct bt_br_discovery_param *param, struct bt_br_discovery_result *results, size_t count, bt_br_discovery_cb_t cb); /** @brief Stop BR/EDR discovery. * * Stops ongoing BR/EDR discovery. If discovery was stopped by this call * results won't be reported * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_br_discovery_stop(void); struct bt_br_oob { /** BR/EDR address. */ bt_addr_t addr; }; /** @brief Get BR/EDR local Out Of Band information * * This function allows to get local controller information that are useful * for Out Of Band pairing or connection creation process. * * @param oob Out Of Band information */ int bt_br_oob_get_local(struct bt_br_oob *oob); /** @def BT_ADDR_STR_LEN * * @brief Recommended length of user string buffer for Bluetooth address * * @details The recommended length guarantee the output of address * conversion will not lose valuable information about address being * processed. */ #define BT_ADDR_STR_LEN 18 /** @def BT_ADDR_LE_STR_LEN * * @brief Recommended length of user string buffer for Bluetooth LE address * * @details The recommended length guarantee the output of address * conversion will not lose valuable information about address being * processed. */ #define BT_ADDR_LE_STR_LEN 30 /** @brief Converts binary Bluetooth address to string. * * @param addr Address of buffer containing binary Bluetooth address. * @param str Address of user buffer with enough room to store formatted * string containing binary address. * @param len Length of data to be copied to user string buffer. Refer to * BT_ADDR_STR_LEN about recommended value. * * @return Number of successfully formatted bytes from binary address. */ static inline int bt_addr_to_str(const bt_addr_t *addr, char *str, size_t len) { return snprintf(str, len, "%02X:%02X:%02X:%02X:%02X:%02X", addr->val[5], addr->val[4], addr->val[3], addr->val[2], addr->val[1], addr->val[0]); } /** @brief Converts binary LE Bluetooth address to string. * * @param addr Address of buffer containing binary LE Bluetooth address. * @param str Address of user buffer with enough room to store * formatted string containing binary LE address. * @param len Length of data to be copied to user string buffer. Refer to * BT_ADDR_LE_STR_LEN about recommended value. * * @return Number of successfully formatted bytes from binary address. */ static inline int bt_addr_le_to_str(const bt_addr_le_t *addr, char *str, size_t len) { char type[10]; switch (addr->type) { case BT_ADDR_LE_PUBLIC: strcpy(type, "public"); break; case BT_ADDR_LE_RANDOM: strcpy(type, "random"); break; case BT_ADDR_LE_PUBLIC_ID: strcpy(type, "public-id"); break; case BT_ADDR_LE_RANDOM_ID: strcpy(type, "random-id"); break; default: snprintf(type, sizeof(type), "0x%02x", addr->type); break; } return snprintf(str, len, "%02X:%02X:%02X:%02X:%02X:%02X (%s)", addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], type); } /** @brief Convert Bluetooth address from string to binary. * * @param[in] str The string representation of a Bluetooth address. * @param[out] addr Address of buffer to store the Bluetooth address * * @return Zero on success or (negative) error code otherwise. */ int bt_addr_from_str(const char *str, bt_addr_t *addr); /** @brief Convert LE Bluetooth address from string to binary. * * @param[in] str The string representation of an LE Bluetooth address. * @param[in] type The string representation of the LE Bluetooth address * type. * @param[out] addr Address of buffer to store the LE Bluetooth address * * @return Zero on success or (negative) error code otherwise. */ int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr); /** @brief Enable/disable set controller in discoverable state. * * Allows make local controller to listen on INQUIRY SCAN channel and responds * to devices making general inquiry. To enable this state it's mandatory * to first be in connectable state. * * @param enable Value allowing/disallowing controller to become discoverable. * * @return Negative if fail set to requested state or requested state has been * already set. Zero if done successfully. */ int bt_br_set_discoverable(bool enable); /** @brief Enable/disable set controller in connectable state. * * Allows make local controller to be connectable. It means the controller * start listen to devices requests on PAGE SCAN channel. If disabled also * resets discoverability if was set. * * @param enable Value allowing/disallowing controller to be connectable. * * @return Negative if fail set to requested state or requested state has been * already set. Zero if done successfully. */ int bt_br_set_connectable(bool enable); /** @brief Clear pairing information. * * @param id Local identity (mostly just BT_ID_DEFAULT). * @param addr Remote address, NULL or BT_ADDR_LE_ANY to clear all remote * devices. * * @return 0 on success or negative error value on failure. */ int bt_unpair(u8_t id, const bt_addr_le_t *addr); /** Information about a bond with a remote device. */ struct bt_bond_info { /** Address of the remote device. */ bt_addr_le_t addr; }; /** @brief Iterate through all existing bonds. * * @param id Local identity (mostly just BT_ID_DEFAULT). * @param func Function to call for each bond. * @param user_data Data to pass to the callback function. */ void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, void *user_data), void *user_data); /** * @} */ #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_BLUETOOTH_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/bluetooth.h
C
apache-2.0
47,337
/** @file * @brief Bluetooth data buffer API */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_BUF_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_BUF_H_ /** * @brief Data buffers * @defgroup bt_buf Data buffers * @ingroup bluetooth * @{ */ #include <ble_types/types.h> #include <net/buf.h> #include <bluetooth/hci.h> /** Possible types of buffers passed around the Bluetooth stack */ enum bt_buf_type { /** HCI command */ BT_BUF_CMD, /** HCI event */ BT_BUF_EVT, /** Outgoing ACL data */ BT_BUF_ACL_OUT, /** Incoming ACL data */ BT_BUF_ACL_IN, /** H:4 data */ BT_BUF_H4, }; /** Minimum amount of user data size for buffers passed to the stack. */ #define BT_BUF_USER_DATA_MIN 4 // __DEPRECATED_MACRO #if defined(CONFIG_BT_HCI_RAW) #define BT_BUF_RESERVE MAX(CONFIG_BT_HCI_RESERVE, CONFIG_BT_HCI_RAW_RESERVE) #else #define BT_BUF_RESERVE CONFIG_BT_HCI_RESERVE #endif #define BT_BUF_SIZE(size) (BT_BUF_RESERVE + (size)) /** Data size neeed for HCI RX buffers */ #define BT_BUF_RX_SIZE (BT_BUF_SIZE(CONFIG_BT_RX_BUF_LEN)) /** Allocate a buffer for incoming data * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_recv_prio(). * * @param type Type of buffer. Only BT_BUF_EVT and BT_BUF_ACL_IN are * allowed. * @param timeout Non-negative waiting period to obtain a buffer or one of the * special values K_NO_WAIT and K_FOREVER. * @return A new buffer. */ struct net_buf *bt_buf_get_rx(enum bt_buf_type type, k_timeout_t timeout); /** Allocate a buffer for outgoing data * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_send(). * * @param type Type of buffer. Only BT_BUF_CMD, BT_BUF_ACL_OUT or * BT_BUF_H4, when operating on H:4 mode, are allowed. * @param timeout Non-negative waiting period to obtain a buffer or one of the * special values K_NO_WAIT and K_FOREVER. * @param data Initial data to append to buffer. * @param size Initial data size. * @return A new buffer. */ struct net_buf *bt_buf_get_tx(enum bt_buf_type type, k_timeout_t timeout, const void *data, size_t size); /** Allocate a buffer for an HCI Command Complete/Status Event * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_recv_prio(). * * @param timeout Non-negative waiting period to obtain a buffer or one of the * special values K_NO_WAIT and K_FOREVER. * @return A new buffer. */ struct net_buf *bt_buf_get_cmd_complete(k_timeout_t timeout); /** Allocate a buffer for an HCI Event * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_recv_prio() or bt_recv(). * * @param evt HCI event code * @param discardable Whether the driver considers the event discardable. * @param timeout Non-negative waiting period to obtain a buffer or one of * the special values K_NO_WAIT and K_FOREVER. * @return A new buffer. */ struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, k_timeout_t timeout); /** Set the buffer type * * @param buf Bluetooth buffer * @param type The BT_* type to set the buffer to */ static inline void bt_buf_set_type(struct net_buf *buf, enum bt_buf_type type) { *(u8_t *)net_buf_user_data(buf) = type; } /** Get the buffer type * * @param buf Bluetooth buffer * * @return The BT_* type to of the buffer */ static inline enum bt_buf_type bt_buf_get_type(struct net_buf *buf) { /* De-referencing the pointer from net_buf_user_data(buf) as a * pointer to an enum causes issues on qemu_x86 because the true * size is 8-bit, but the enum is 32-bit on qemu_x86. So we put in * a temporary cast to 8-bit to ensure only 8 bits are read from * the pointer. */ return (enum bt_buf_type)(*(u8_t *)net_buf_user_data(buf)); } /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_BUF_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/buf.h
C
apache-2.0
4,109
/** @file * @brief Bluetooth connection handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_CONN_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_CONN_H_ /** * @brief Connection management * @defgroup bt_conn Connection management * @ingroup bluetooth * @{ */ #include <stdbool.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci_err.h> #include <bluetooth/addr.h> #include <bluetooth/gap.h> #ifdef __cplusplus extern "C" { #endif #if 0 /** LE Advertising Parameters. */ struct bt_le_adv_param { /** Bit-field of advertising options */ u8_t options; /** Minimum Advertising Interval (N * 0.625) */ u16_t interval_min; /** Maximum Advertising Interval (N * 0.625) */ u16_t interval_max; /** Optional predefined (random) own address. Currently * the only permitted use of this is for NRPA with * non-connectable advertising. */ const bt_addr_t *own_addr; }; #endif /** Opaque type representing a connection to a remote device */ struct bt_conn; /** Connection parameters for LE connections */ struct bt_le_conn_param { u16_t interval_min; u16_t interval_max; u16_t latency; u16_t timeout; }; /** @brief Initialize connection parameters * * @param int_min Minimum Connection Interval (N * 1.25 ms) * @param int_max Maximum Connection Interval (N * 1.25 ms) * @param lat Connection Latency * @param to Supervision Timeout (N * 10 ms) */ #define BT_LE_CONN_PARAM_INIT(int_min, int_max, lat, to) \ { \ .interval_min = (int_min), \ .interval_max = (int_max), \ .latency = (lat), \ .timeout = (to), \ } /** Helper to declare connection parameters inline * * @param int_min Minimum Connection Interval (N * 1.25 ms) * @param int_max Maximum Connection Interval (N * 1.25 ms) * @param lat Connection Latency * @param to Supervision Timeout (N * 10 ms) */ #define BT_LE_CONN_PARAM(int_min, int_max, lat, to) \ ((struct bt_le_conn_param[]) { \ BT_LE_CONN_PARAM_INIT(int_min, int_max, lat, to) \ }) /** Default LE connection parameters: * Connection Interval: 30-50 ms * Latency: 0 * Timeout: 4 s */ #define BT_LE_CONN_PARAM_DEFAULT BT_LE_CONN_PARAM(BT_GAP_INIT_CONN_INT_MIN, \ BT_GAP_INIT_CONN_INT_MAX, \ 0, 400) /** Connection PHY information for LE connections */ struct bt_conn_le_phy_info { u8_t tx_phy; /** Connection transmit PHY */ u8_t rx_phy; /** Connection receive PHY */ }; /** Preferred PHY parameters for LE connections */ struct bt_conn_le_phy_param { u8_t pref_tx_phy; /** Bitmask of preferred transmit PHYs */ u8_t pref_rx_phy; /** Bitmask of preferred receive PHYs */ }; /** Initialize PHY parameters * * @param _pref_tx_phy Bitmask of preferred transmit PHYs. * @param _pref_rx_phy Bitmask of preferred receive PHYs. */ #define BT_CONN_LE_PHY_PARAM_INIT(_pref_tx_phy, _pref_rx_phy) \ { \ .pref_tx_phy = (_pref_tx_phy), \ .pref_rx_phy = (_pref_rx_phy), \ } /** Helper to declare PHY parameters inline * * @param _pref_tx_phy Bitmask of preferred transmit PHYs. * @param _pref_rx_phy Bitmask of preferred receive PHYs. */ #define BT_CONN_LE_PHY_PARAM(_pref_tx_phy, _pref_rx_phy) \ ((struct bt_conn_le_phy_param []) { \ BT_CONN_LE_PHY_PARAM_INIT(_pref_tx_phy, _pref_rx_phy) \ }) /** Only LE 1M PHY */ #define BT_CONN_LE_PHY_PARAM_1M BT_CONN_LE_PHY_PARAM(BT_GAP_LE_PHY_1M, \ BT_GAP_LE_PHY_1M) /** Only LE 2M PHY */ #define BT_CONN_LE_PHY_PARAM_2M BT_CONN_LE_PHY_PARAM(BT_GAP_LE_PHY_2M, \ BT_GAP_LE_PHY_2M) /** Only LE Coded PHY. */ #define BT_CONN_LE_PHY_PARAM_CODED BT_CONN_LE_PHY_PARAM(BT_GAP_LE_PHY_CODED, \ BT_GAP_LE_PHY_CODED) /** All LE PHYs. */ #define BT_CONN_LE_PHY_PARAM_ALL BT_CONN_LE_PHY_PARAM(BT_GAP_LE_PHY_1M | \ BT_GAP_LE_PHY_2M | \ BT_GAP_LE_PHY_CODED, \ BT_GAP_LE_PHY_1M | \ BT_GAP_LE_PHY_2M | \ BT_GAP_LE_PHY_CODED) /** Connection data length information for LE connections */ struct bt_conn_le_data_len_info { /** Maximum Link Layer transmission payload size in bytes. */ u16_t tx_max_len; /** Maximum Link Layer transmission payload time in us. */ u16_t tx_max_time; /** Maximum Link Layer reception payload size in bytes. */ u16_t rx_max_len; /** Maximum Link Layer reception payload time in us. */ u16_t rx_max_time; }; /** Connection data length parameters for LE connections */ struct bt_conn_le_data_len_param { /** Maximum Link Layer transmission payload size in bytes. */ u16_t tx_max_len; /** Maximum Link Layer transmission payload time in us. */ u16_t tx_max_time; }; /** Initialize transmit data length parameters * * @param _tx_max_len Maximum Link Layer transmission payload size in bytes. * @param _tx_max_time Maximum Link Layer transmission payload time in us. */ #define BT_CONN_LE_DATA_LEN_PARAM_INIT(_tx_max_len, _tx_max_time) \ { \ .tx_max_len = (_tx_max_len), \ .tx_max_time = (_tx_max_time), \ } /** Helper to declare transmit data length parameters inline * * @param _tx_max_len Maximum Link Layer transmission payload size in bytes. * @param _tx_max_time Maximum Link Layer transmission payload time in us. */ #define BT_CONN_LE_DATA_LEN_PARAM(_tx_max_len, _tx_max_time) \ ((struct bt_conn_le_data_len_param[]) { \ BT_CONN_LE_DATA_LEN_PARAM_INIT(_tx_max_len, _tx_max_time) \ }) /** Default LE data length parameters. */ #define BT_LE_DATA_LEN_PARAM_DEFAULT \ BT_CONN_LE_DATA_LEN_PARAM(BT_GAP_DATA_LEN_DEFAULT, \ BT_GAP_DATA_TIME_DEFAULT) /** Maximum LE data length parameters. */ #define BT_LE_DATA_LEN_PARAM_MAX \ BT_CONN_LE_DATA_LEN_PARAM(BT_GAP_DATA_LEN_MAX, \ BT_GAP_DATA_TIME_MAX) /** @brief Increment a connection's reference count. * * Increment the reference count of a connection object. * * @param conn Connection object. * * @return Connection object with incremented reference count. */ struct bt_conn *bt_conn_ref(struct bt_conn *conn); /** @brief Decrement a connection's reference count. * * Decrement the reference count of a connection object. * * @param conn Connection object. */ void bt_conn_unref(struct bt_conn *conn); /** @brief Iterate through all existing connections. * * @param type Connection Type * @param func Function to call for each connection. * @param data Data to pass to the callback function. */ void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), void *data); /** @brief Look up an existing connection by address. * * Look up an existing connection based on the remote address. * * The caller gets a new reference to the connection object which must be * released with bt_conn_unref() once done using the object. * * @param id Local identity (in most cases BT_ID_DEFAULT). * @param peer Remote address. * * @return Connection object or NULL if not found. */ struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer); /** @brief Get destination (peer) address of a connection. * * @param conn Connection object. * * @return Destination address. */ const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn); /** @brief Get array index of a connection * * This function is used to map bt_conn to index of an array of * connections. The array has CONFIG_BT_MAX_CONN elements. * * @param conn Connection object. * * @return Index of the connection object. * The range of the returned value is 0..CONFIG_BT_MAX_CONN-1 */ u8_t bt_conn_index(struct bt_conn *conn); /** Connection Type */ enum { /** LE Connection Type */ BT_CONN_TYPE_LE = BIT(0), /** BR/EDR Connection Type */ BT_CONN_TYPE_BR = BIT(1), /** SCO Connection Type */ BT_CONN_TYPE_SCO = BIT(2), /** All Connection Type */ BT_CONN_TYPE_ALL = BT_CONN_TYPE_LE | BT_CONN_TYPE_BR | BT_CONN_TYPE_SCO, }; /** LE Connection Info Structure */ struct bt_conn_le_info { /** Source (Local) Identity Address */ const bt_addr_le_t *src; /** Destination (Remote) Identity Address or remote Resolvable Private * Address (RPA) before identity has been resolved. */ const bt_addr_le_t *dst; /** Local device address used during connection setup. */ const bt_addr_le_t *local; /** Remote device address used during connection setup. */ const bt_addr_le_t *remote; u16_t interval; /** Connection interval */ u16_t latency; /** Connection slave latency */ u16_t timeout; /** Connection supervision timeout */ #if defined(CONFIG_BT_USER_PHY_UPDATE) const struct bt_conn_le_phy_info *phy; #endif /* defined(CONFIG_BT_USER_PHY_UPDATE) */ #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) /* Connection maximum single fragment parameters */ const struct bt_conn_le_data_len_info *data_len; #endif /* defined(CONFIG_BT_USER_DATA_LEN_UPDATE) */ }; /** BR/EDR Connection Info Structure */ struct bt_conn_br_info { const bt_addr_t *dst; /** Destination (Remote) BR/EDR address */ }; /** Connection role (master or slave) */ enum { BT_CONN_ROLE_MASTER, BT_CONN_ROLE_SLAVE, }; /** Connection Info Structure */ struct bt_conn_info { /** Connection Type. */ u8_t type; /** Connection Role. */ u8_t role; /** Which local identity the connection was created with */ u8_t id; /** Connection Type specific Info.*/ union { /** LE Connection specific Info. */ struct bt_conn_le_info le; /** BR/EDR Connection specific Info. */ struct bt_conn_br_info br; }; }; /** LE Connection Remote Info Structure */ struct bt_conn_le_remote_info { /** Remote LE feature set (bitmask). */ const u8_t *features; }; /** BR/EDR Connection Remote Info structure */ struct bt_conn_br_remote_info { /** Remote feature set (pages of bitmasks). */ const u8_t *features; /** Number of pages in the remote feature set. */ u8_t num_pages; }; /** @brief Connection Remote Info Structure * * @note The version, manufacturer and subversion fields will only contain * valid data if :option:`CONFIG_BT_REMOTE_VERSION` is enabled. */ struct bt_conn_remote_info { /** Connection Type */ u8_t type; /** Remote Link Layer version */ u8_t version; /** Remote manufacturer identifier */ u16_t manufacturer; /** Per-manufacturer unique revision */ u16_t subversion; union { /** LE connection remote info */ struct bt_conn_le_remote_info le; /** BR/EDR connection remote info */ struct bt_conn_br_remote_info br; }; }; /** @brief Get connection info * * @param conn Connection object. * @param info Connection info object. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info); /** @brief Get connection info for the remote device. * * @param conn Connection object. * @param remote_info Connection remote info object. * * @note In order to retrieve the remote version (version, manufacturer * and subversion) :option:`CONFIG_BT_REMOTE_VERSION` must be enabled * * @note The remote information is exchanged directly after the connection has * been established. The application can be notified about when the remote * information is available through the remote_info_available callback. * * @return Zero on success or (negative) error code on failure. * @return -EBUSY The remote information is not yet available. */ int bt_conn_get_remote_info(struct bt_conn *conn, struct bt_conn_remote_info *remote_info); /** @brief Update the connection parameters. * * @param conn Connection object. * @param param Updated connection parameters. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param); /** @brief Update the connection transmit data length parameters. * * @param conn Connection object. * @param param Updated data length parameters. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_le_data_len_update(struct bt_conn *conn, const struct bt_conn_le_data_len_param *param); /** @brief Update the connection PHY parameters. * * @param conn Connection object. * @param param Updated connection parameters. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_le_phy_update(struct bt_conn *conn, const struct bt_conn_le_phy_param *param); /** @brief Disconnect from a remote device or cancel pending connection. * * Disconnect an active connection with the specified reason code or cancel * pending outgoing connection. * * @param conn Connection to disconnect. * @param reason Reason code for the disconnection. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_disconnect(struct bt_conn *conn, u8_t reason); enum { /** Convenience value when no options are specified. */ BT_CONN_LE_OPT_NONE = 0, /** @brief Enable LE Coded PHY. * * Enable scanning on the LE Coded PHY. */ BT_CONN_LE_OPT_CODED = BIT(0), /** @brief Disable LE 1M PHY. * * Disable scanning on the LE 1M PHY. * * @note Requires @ref BT_CONN_LE_OPT_CODED. */ BT_CONN_LE_OPT_NO_1M = BIT(1), }; struct bt_conn_le_create_param { /** Bit-field of create connection options. */ bt_u32_t options; /** Scan interval (N * 0.625 ms) */ u16_t interval; /** Scan window (N * 0.625 ms) */ u16_t window; /** @brief Scan interval LE Coded PHY (N * 0.625 MS) * * Set zero to use same as LE 1M PHY scan interval */ u16_t interval_coded; /** @brief Scan window LE Coded PHY (N * 0.625 MS) * * Set zero to use same as LE 1M PHY scan window. */ u16_t window_coded; /** @brief Connection initiation timeout (N * 10 MS) * * Set zero to use the default :option:`CONFIG_BT_CREATE_CONN_TIMEOUT` * timeout. * * @note Unused in @ref bt_conn_create_auto_le */ u16_t timeout; }; /** @brief Initialize create connection parameters * * @param _options Create connection options. * @param _interval Create connection scan interval (N * 0.625 ms). * @param _window Create connection scan window (N * 0.625 ms). */ #define BT_CONN_LE_CREATE_PARAM_INIT(_options, _interval, _window) \ { \ .options = (_options), \ .interval = (_interval), \ .window = (_window), \ .interval_coded = 0, \ .window_coded = 0, \ .timeout = 0, \ } /** Helper to declare create connection parameters inline * * @param _options Create connection options. * @param _interval Create connection scan interval (N * 0.625 ms). * @param _window Create connection scan window (N * 0.625 ms). */ #define BT_CONN_LE_CREATE_PARAM(_options, _interval, _window) \ ((struct bt_conn_le_create_param[]) { \ BT_CONN_LE_CREATE_PARAM_INIT(_options, _interval, _window) \ }) /** Default LE create connection parameters. * Scan continuously by setting scan interval equal to scan window. */ #define BT_CONN_LE_CREATE_CONN \ BT_CONN_LE_CREATE_PARAM(BT_CONN_LE_OPT_NONE, \ BT_GAP_SCAN_FAST_INTERVAL, \ BT_GAP_SCAN_FAST_INTERVAL) /** Default LE create connection using whitelist parameters. * Scan window: 30 ms. * Scan interval: 60 ms. */ #define BT_CONN_LE_CREATE_CONN_AUTO \ BT_CONN_LE_CREATE_PARAM(BT_CONN_LE_OPT_NONE, \ BT_GAP_SCAN_FAST_INTERVAL, \ BT_GAP_SCAN_FAST_WINDOW) /** @brief Initiate an LE connection to a remote device. * * Allows initiate new LE link to remote peer using its address. * * The caller gets a new reference to the connection object which must be * released with bt_conn_unref() once done using the object. * * This uses the General Connection Establishment procedure. * * @param[in] peer Remote address. * @param[in] create_param Create connection parameters. * @param[in] conn_param Initial connection parameters. * @param[out] conn Valid connection object on success. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_le_create(const bt_addr_le_t *peer, const struct bt_conn_le_create_param *create_param, const struct bt_le_conn_param *conn_param, struct bt_conn **conn); __deprecated static inline struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer, const struct bt_le_conn_param *conn_param) { struct bt_conn *conn; struct bt_conn_le_create_param param = BT_CONN_LE_CREATE_PARAM_INIT( BT_CONN_LE_OPT_NONE, BT_GAP_SCAN_FAST_INTERVAL, BT_GAP_SCAN_FAST_INTERVAL); if (bt_conn_le_create(peer, &param, conn_param, &conn)) { return NULL; } return conn; } /** @brief Automatically connect to remote devices in whitelist. * * This uses the Auto Connection Establishment procedure. * The procedure will continue until a single connection is established or the * procedure is stopped through @ref bt_conn_create_auto_stop. * To establish connections to all devices in the whitelist the procedure * should be started again in the connected callback after a new connection has * been established. * * @param create_param Create connection parameters * @param conn_param Initial connection parameters. * * @return Zero on success or (negative) error code on failure. * @return -ENOMEM No free connection object available. */ int bt_conn_le_create_auto(const struct bt_conn_le_create_param *create_param, const struct bt_le_conn_param *conn_param); __deprecated static inline int bt_conn_create_auto_le(const struct bt_le_conn_param *conn_param) { struct bt_conn_le_create_param param = BT_CONN_LE_CREATE_PARAM_INIT( BT_CONN_LE_OPT_NONE, BT_GAP_SCAN_FAST_INTERVAL, BT_GAP_SCAN_FAST_WINDOW); return bt_conn_le_create_auto(&param, conn_param); } /** @brief Stop automatic connect creation. * * @return Zero on success or (negative) error code on failure. */ int bt_conn_create_auto_stop(void); /** @brief Automatically connect to remote device if it's in range. * * This function enables/disables automatic connection initiation. * Every time the device loses the connection with peer, this connection * will be re-established if connectable advertisement from peer is received. * * @note Auto connect is disabled during explicit scanning. * * @param addr Remote Bluetooth address. * @param param If non-NULL, auto connect is enabled with the given * parameters. If NULL, auto connect is disabled. * * @return Zero on success or error code otherwise. */ int bt_le_set_auto_conn(const bt_addr_le_t *addr, const struct bt_le_conn_param *param); /** @brief Initiate directed advertising to a remote device * * Allows initiating a new LE connection to remote peer with the remote * acting in central role and the local device in peripheral role. * * The advertising type will either be BT_LE_ADV_DIRECT_IND, or * BT_LE_ADV_DIRECT_IND_LOW_DUTY if the BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY * option was used as part of the advertising parameters. * * In case of high duty cycle this will result in a callback with * connected() with a new connection or with an error. * * The advertising may be canceled with bt_conn_disconnect(). * * The caller gets a new reference to the connection object which must be * released with bt_conn_unref() once done using the object. * * @param peer Remote address. * @param param Directed advertising parameters. * * @return Valid connection object on success or NULL otherwise. */ __deprecated static inline struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer, const struct bt_le_adv_param *param) { struct bt_le_adv_param adv_param = *param; adv_param.options |= (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME); adv_param.peer = peer; if (!bt_le_adv_start(&adv_param, NULL, 0, NULL, 0)) { return NULL; } return bt_conn_lookup_addr_le(param->id, peer); } /** Security level. */ typedef enum __packed { /** Level 0: Only for BR/EDR special cases, like SDP */ BT_SECURITY_L0, /** Level 1: No encryption and no authentication. */ BT_SECURITY_L1, /** Level 2: Encryption and no authentication (no MITM). */ BT_SECURITY_L2, /** Level 3: Encryption and authentication (MITM). */ BT_SECURITY_L3, /** Level 4: Authenticated Secure Connections and 128-bit key. */ BT_SECURITY_L4, BT_SECURITY_NONE __deprecated = BT_SECURITY_L0, BT_SECURITY_LOW __deprecated = BT_SECURITY_L1, BT_SECURITY_MEDIUM __deprecated = BT_SECURITY_L2, BT_SECURITY_HIGH __deprecated = BT_SECURITY_L3, BT_SECURITY_FIPS __deprecated = BT_SECURITY_L4, /** Bit to force new pairing procedure, bit-wise OR with requested * security level. */ BT_SECURITY_FORCE_PAIR = BIT(7), } bt_security_t; /** @brief Set security level for a connection. * * This function enable security (encryption) for a connection. If device is * already paired with sufficiently strong key encryption will be enabled. If * link is already encrypted with sufficiently strong key this function does * nothing. * * If device is not paired pairing will be initiated. If device is paired and * keys are too weak but input output capabilities allow for strong enough keys * pairing will be initiated. * * This function may return error if required level of security is not possible * to achieve due to local or remote device limitation (e.g., input output * capabilities), or if the maximum number of paired devices has been reached. * * This function may return error if the pairing procedure has already been * initiated by the local device or the peer device. * * @param conn Connection object. * @param sec Requested security level. * * @return 0 on success or negative error */ int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec); /** @brief Get security level for a connection. * * @return Connection security level */ bt_security_t bt_conn_get_security(struct bt_conn *conn); static inline int __deprecated bt_conn_security(struct bt_conn *conn, bt_security_t sec) { return bt_conn_set_security(conn, sec); } /** @brief Get encryption key size. * * This function gets encryption key size. * If there is no security (encryption) enabled 0 will be returned. * * @param conn Existing connection object. * * @return Encryption key size. */ u8_t bt_conn_enc_key_size(struct bt_conn *conn); enum bt_security_err { /** Security procedure successful. */ BT_SECURITY_ERR_SUCCESS, /** Authentication failed. */ BT_SECURITY_ERR_AUTH_FAIL, /** PIN or encryption key is missing. */ BT_SECURITY_ERR_PIN_OR_KEY_MISSING, /** OOB data is not available. */ BT_SECURITY_ERR_OOB_NOT_AVAILABLE, /** The requested security level could not be reached. */ BT_SECURITY_ERR_AUTH_REQUIREMENT, /** Pairing is not supported */ BT_SECURITY_ERR_PAIR_NOT_SUPPORTED, /** Pairing is not allowed. */ BT_SECURITY_ERR_PAIR_NOT_ALLOWED, /** Invalid parameters. */ BT_SECURITY_ERR_INVALID_PARAM, /** Pairing failed but the exact reason could not be specified. */ BT_SECURITY_ERR_UNSPECIFIED, }; /** @brief Connection callback structure. * * This structure is used for tracking the state of a connection. * It is registered with the help of the bt_conn_cb_register() API. * It's permissible to register multiple instances of this @ref bt_conn_cb * type, in case different modules of an application are interested in * tracking the connection state. If a callback is not of interest for * an instance, it may be set to NULL and will as a consequence not be * used for that instance. */ struct bt_conn_cb { /** @brief A new connection has been established. * * This callback notifies the application of a new connection. * In case the err parameter is non-zero it means that the * connection establishment failed. * * @param conn New connection object. * @param err HCI error. Zero for success, non-zero otherwise. * * @p err can mean either of the following: * - @ref BT_HCI_ERR_UNKNOWN_CONN_ID Creating the connection started by * @ref bt_conn_create_le was canceled either by the user through * @ref bt_conn_disconnect or by the timeout in the host through * @ref bt_conn_le_create_param timeout parameter, which defaults to * :option:`CONFIG_BT_CREATE_CONN_TIMEOUT` seconds. * - @p BT_HCI_ERR_ADV_TIMEOUT High duty cycle directed connectable * advertiser started by @ref bt_le_adv_start failed to be connected * within the timeout. */ void (*connected)(struct bt_conn *conn, u8_t err); /** @brief A connection has been disconnected. * * This callback notifies the application that a connection * has been disconnected. * * When this callback is called the stack still has one reference to * the connection object. If the application in this callback tries to * start either a connectable advertiser or create a new connection * this might fail because there are no free connection objects * available. * To avoid this issue it is recommended to either start connectable * advertise or create a new connection using @ref k_work_submit or * increase :option:`CONFIG_BT_MAX_CONN`. * * @param conn Connection object. * @param reason HCI reason for the disconnection. */ void (*disconnected)(struct bt_conn *conn, u8_t reason); /** @brief LE connection parameter update request. * * This callback notifies the application that a remote device * is requesting to update the connection parameters. The * application accepts the parameters by returning true, or * rejects them by returning false. Before accepting, the * application may also adjust the parameters to better suit * its needs. * * It is recommended for an application to have just one of these * callbacks for simplicity. However, if an application registers * multiple it needs to manage the potentially different * requirements for each callback. Each callback gets the * parameters as returned by previous callbacks, i.e. they are not * necessarily the same ones as the remote originally sent. * * @param conn Connection object. * @param param Proposed connection parameters. * * @return true to accept the parameters, or false to reject them. */ bool (*le_param_req)(struct bt_conn *conn, struct bt_le_conn_param *param); /** @brief The parameters for an LE connection have been updated. * * This callback notifies the application that the connection * parameters for an LE connection have been updated. * * @param conn Connection object. * @param interval Connection interval. * @param latency Connection latency. * @param timeout Connection supervision timeout. */ void (*le_param_updated)(struct bt_conn *conn, u16_t interval, u16_t latency, u16_t timeout); #if defined(CONFIG_BT_SMP) /** @brief Remote Identity Address has been resolved. * * This callback notifies the application that a remote * Identity Address has been resolved * * @param conn Connection object. * @param rpa Resolvable Private Address. * @param identity Identity Address. */ void (*identity_resolved)(struct bt_conn *conn, const bt_addr_le_t *rpa, const bt_addr_le_t *identity); #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) /** @brief The security level of a connection has changed. * * This callback notifies the application that the security level * of a connection has changed. * * @param conn Connection object. * @param level New security level of the connection. * @param err Security error. Zero for success, non-zero otherwise. */ void (*security_changed)(struct bt_conn *conn, bt_security_t level, enum bt_security_err err); #endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */ #if defined(CONFIG_BT_REMOTE_INFO) /** @brief Remote information procedures has completed. * * This callback notifies the application that the remote information * has been retrieved from the remote peer. * * @param conn Connection object. * @param remote_info Connection information of remote device. */ void (*remote_info_available)(struct bt_conn *conn, struct bt_conn_remote_info *remote_info); #endif /* defined(CONFIG_BT_REMOTE_INFO) */ #if defined(CONFIG_BT_USER_PHY_UPDATE) /** @brief The PHY of the connection has changed. * * This callback notifies the application that the PHY of the * connection has changed. * * @param conn Connection object. * @param info Connection LE PHY information. */ void (*le_phy_updated)(struct bt_conn *conn, struct bt_conn_le_phy_info *param); #endif /* defined(CONFIG_BT_USER_PHY_UPDATE) */ #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE) /** @brief The data length parameters of the connection has changed. * * This callback notifies the application that the maximum Link Layer * payload length or transmission time has changed. * * @param conn Connection object. * @param info Connection data length information. */ void (*le_data_len_updated)(struct bt_conn *conn, struct bt_conn_le_data_len_info *info); #endif /* defined(CONFIG_BT_USER_PHY_UPDATE) */ struct bt_conn_cb *_next; }; /** @brief Register connection callbacks. * * Register callbacks to monitor the state of connections. * * @param cb Callback struct. */ void bt_conn_cb_register(struct bt_conn_cb *cb); /** @brief Enable/disable bonding. * * Set/clear the Bonding flag in the Authentication Requirements of * SMP Pairing Request/Response data. * The initial value of this flag depends on BT_BONDABLE Kconfig setting. * For the vast majority of applications calling this function shouldn't be * needed. * * @param enable Value allowing/disallowing to be bondable. */ void bt_set_bondable(bool enable); /** @brief Allow/disallow remote OOB data to be used for pairing. * * Set/clear the OOB data flag for SMP Pairing Request/Response data. * The initial value of this flag depends on BT_OOB_DATA_PRESENT Kconfig * setting. * * @param enable Value allowing/disallowing remote OOB data. */ void bt_set_oob_data_flag(bool enable); /** @brief Set OOB Temporary Key to be used for pairing * * This function allows to set OOB data for the LE legacy pairing procedure. * The function should only be called in response to the oob_data_request() * callback provided that the legacy method is user pairing. * * @param conn Connection object * @param tk Pointer to 16 byte long TK array * * @return Zero on success or -EINVAL if NULL */ int bt_le_oob_set_legacy_tk(struct bt_conn *conn, const u8_t *tk); /** @brief Set OOB data during LE Secure Connections (SC) pairing procedure * * This function allows to set OOB data during the LE SC pairing procedure. * The function should only be called in response to the oob_data_request() * callback provided that LE SC method is used for pairing. * * The user should submit OOB data according to the information received in the * callback. This may yield three different configurations: with only local OOB * data present, with only remote OOB data present or with both local and * remote OOB data present. * * @param conn Connection object * @param oobd_local Local OOB data or NULL if not present * @param oobd_remote Remote OOB data or NULL if not present * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_oob_set_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data *oobd_local, const struct bt_le_oob_sc_data *oobd_remote); /** @brief Get OOB data used for LE Secure Connections (SC) pairing procedure * * This function allows to get OOB data during the LE SC pairing procedure that * were set by the bt_le_oob_set_sc_data() API. * * @note The OOB data will only be available as long as the connection object * associated with it is valid. * * @param conn Connection object * @param oobd_local Local OOB data or NULL if not set * @param oobd_remote Remote OOB data or NULL if not set * * @return Zero on success or error code otherwise, positive in case of * protocol error or negative (POSIX) in case of stack internal error. */ int bt_le_oob_get_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data **oobd_local, const struct bt_le_oob_sc_data **oobd_remote); /** @def BT_PASSKEY_INVALID * * Special passkey value that can be used to disable a previously * set fixed passkey. */ #define BT_PASSKEY_INVALID 0xffffffff /** @brief Set a fixed passkey to be used for pairing. * * This API is only available when the CONFIG_BT_FIXED_PASSKEY * configuration option has been enabled. * * Sets a fixed passkey to be used for pairing. If set, the * pairing_confim() callback will be called for all incoming pairings. * * @param passkey A valid passkey (0 - 999999) or BT_PASSKEY_INVALID * to disable a previously set fixed passkey. * * @return 0 on success or a negative error code on failure. */ int bt_passkey_set(unsigned int passkey); /** Info Structure for OOB pairing */ struct bt_conn_oob_info { /** Type of OOB pairing method */ enum { /** LE legacy pairing */ BT_CONN_OOB_LE_LEGACY, /** LE SC pairing */ BT_CONN_OOB_LE_SC, } type; union { /** LE Secure Connections OOB pairing parameters */ struct { /** OOB data configuration */ enum { /** Local OOB data requested */ BT_CONN_OOB_LOCAL_ONLY, /** Remote OOB data requested */ BT_CONN_OOB_REMOTE_ONLY, /** Both local and remote OOB data requested */ BT_CONN_OOB_BOTH_PEERS, /** No OOB data requested */ BT_CONN_OOB_NO_DATA, } oob_config; } lesc; }; }; #if defined(CONFIG_BT_SMP_APP_PAIRING_ACCEPT) /** @brief Pairing request and pairing response info structure. * * This structure is the same for both smp_pairing_req and smp_pairing_rsp * and a subset of the packet data, except for the initial Code octet. * It is documented in Core Spec. Vol. 3, Part H, 3.5.1 and 3.5.2. */ struct bt_conn_pairing_feat { /** IO Capability, Core Spec. Vol 3, Part H, 3.5.1, Table 3.4 */ u8_t io_capability; /** OOB data flag, Core Spec. Vol 3, Part H, 3.5.1, Table 3.5 */ u8_t oob_data_flag; /** AuthReq, Core Spec. Vol 3, Part H, 3.5.1, Fig. 3.3 */ u8_t auth_req; /** Maximum Encryption Key Size, Core Spec. Vol 3, Part H, 3.5.1 */ u8_t max_enc_key_size; /** Initiator Key Distribution/Generation, Core Spec. Vol 3, Part H, * 3.6.1, Fig. 3.11 */ u8_t init_key_dist; /** Responder Key Distribution/Generation, Core Spec. Vol 3, Part H * 3.6.1, Fig. 3.11 */ u8_t resp_key_dist; }; #endif /* CONFIG_BT_SMP_APP_PAIRING_ACCEPT */ /** Authenticated pairing callback structure */ struct bt_conn_auth_cb { #if defined(CONFIG_BT_SMP_APP_PAIRING_ACCEPT) /** @brief Query to proceed incoming pairing or not. * * On any incoming pairing req/rsp this callback will be called for * the application to decide whether to allow for the pairing to * continue. * * The pairing info received from the peer is passed to assist * making the decision. * * As this callback is synchronous the application should return * a response value immediately. Otherwise it may affect the * timing during pairing. Hence, this information should not be * conveyed to the user to take action. * * The remaining callbacks are not affected by this, but do notice * that other callbacks can be called during the pairing. Eg. if * pairing_confirm is registered both will be called for Just-Works * pairings. * * This callback may be unregistered in which case pairing continues * as if the Kconfig flag was not set. * * This callback is not called for BR/EDR Secure Simple Pairing (SSP). * * @param conn Connection where pairing is initiated. * @param feat Pairing req/resp info. */ enum bt_security_err (*pairing_accept)(struct bt_conn *conn, const struct bt_conn_pairing_feat *const feat); #endif /* CONFIG_BT_SMP_APP_PAIRING_ACCEPT */ /** @brief Display a passkey to the user. * * When called the application is expected to display the given * passkey to the user, with the expectation that the passkey will * then be entered on the peer device. The passkey will be in the * range of 0 - 999999, and is expected to be padded with zeroes so * that six digits are always shown. E.g. the value 37 should be * shown as 000037. * * This callback may be set to NULL, which means that the local * device lacks the ability do display a passkey. If set * to non-NULL the cancel callback must also be provided, since * this is the only way the application can find out that it should * stop displaying the passkey. * * @param conn Connection where pairing is currently active. * @param passkey Passkey to show to the user. */ void (*passkey_display)(struct bt_conn *conn, unsigned int passkey); /** @brief Request the user to enter a passkey. * * When called the user is expected to enter a passkey. The passkey * must be in the range of 0 - 999999, and should be expected to * be zero-padded, as that's how the peer device will typically be * showing it (e.g. 37 would be shown as 000037). * * Once the user has entered the passkey its value should be given * to the stack using the bt_conn_auth_passkey_entry() API. * * This callback may be set to NULL, which means that the local * device lacks the ability to enter a passkey. If set to non-NULL * the cancel callback must also be provided, since this is the * only way the application can find out that it should stop * requesting the user to enter a passkey. * * @param conn Connection where pairing is currently active. */ void (*passkey_entry)(struct bt_conn *conn); /** @brief Request the user to confirm a passkey. * * When called the user is expected to confirm that the given * passkey is also shown on the peer device.. The passkey will * be in the range of 0 - 999999, and should be zero-padded to * always be six digits (e.g. 37 would be shown as 000037). * * Once the user has confirmed the passkey to match, the * bt_conn_auth_passkey_confirm() API should be called. If the * user concluded that the passkey doesn't match the * bt_conn_auth_cancel() API should be called. * * This callback may be set to NULL, which means that the local * device lacks the ability to confirm a passkey. If set to non-NULL * the cancel callback must also be provided, since this is the * only way the application can find out that it should stop * requesting the user to confirm a passkey. * * @param conn Connection where pairing is currently active. * @param passkey Passkey to be confirmed. */ void (*passkey_confirm)(struct bt_conn *conn, unsigned int passkey); /** @brief Request the user to provide Out of Band (OOB) data. * * When called the user is expected to provide OOB data. The required * data are indicated by the information structure. * * For LE Secure Connections OOB pairing, the user should provide * local OOB data, remote OOB data or both depending on their * availability. Their value should be given to the stack using the * bt_le_oob_set_sc_data() API. * * This callback must be set to non-NULL in order to support OOB * pairing. * * @param conn Connection where pairing is currently active. * @param info OOB pairing information. */ void (*oob_data_request)(struct bt_conn *conn, struct bt_conn_oob_info *info); /** @brief Cancel the ongoing user request. * * This callback will be called to notify the application that it * should cancel any previous user request (passkey display, entry * or confirmation). * * This may be set to NULL, but must always be provided whenever the * passkey_display, passkey_entry passkey_confirm or pairing_confirm * callback has been provided. * * @param conn Connection where pairing is currently active. */ void (*cancel)(struct bt_conn *conn); /** @brief Request confirmation for an incoming pairing. * * This callback will be called to confirm an incoming pairing * request where none of the other user callbacks is applicable. * * If the user decides to accept the pairing the * bt_conn_auth_pairing_confirm() API should be called. If the * user decides to reject the pairing the bt_conn_auth_cancel() API * should be called. * * This callback may be set to NULL, which means that the local * device lacks the ability to confirm a pairing request. If set * to non-NULL the cancel callback must also be provided, since * this is the only way the application can find out that it should * stop requesting the user to confirm a pairing request. * * @param conn Connection where pairing is currently active. */ void (*pairing_confirm)(struct bt_conn *conn); #if defined(CONFIG_BT_BREDR) /** @brief Request the user to enter a passkey. * * This callback will be called for a BR/EDR (Bluetooth Classic) * connection where pairing is being performed. Once called the * user is expected to enter a PIN code with a length between * 1 and 16 digits. If the @a highsec parameter is set to true * the PIN code must be 16 digits long. * * Once entered, the PIN code should be given to the stack using * the bt_conn_auth_pincode_entry() API. * * This callback may be set to NULL, however in that case pairing * over BR/EDR will not be possible. If provided, the cancel * callback must be provided as well. * * @param conn Connection where pairing is currently active. * @param highsec true if 16 digit PIN is required. */ void (*pincode_entry)(struct bt_conn *conn, bool highsec); #endif /** @brief notify that pairing process was complete. * * This callback notifies the application that the pairing process * has been completed. * * @param conn Connection object. * @param bonded pairing is bonded or not. */ void (*pairing_complete)(struct bt_conn *conn, bool bonded); /** @brief notify that pairing process has failed. * * @param conn Connection object. * @param reason Pairing failed reason */ void (*pairing_failed)(struct bt_conn *conn, enum bt_security_err reason); }; /** @brief Register authentication callbacks. * * Register callbacks to handle authenticated pairing. Passing NULL * unregisters a previous callbacks structure. * * @param cb Callback struct. * * @return Zero on success or negative error code otherwise */ int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb); /** @brief Reply with entered passkey. * * This function should be called only after passkey_entry callback from * bt_conn_auth_cb structure was called. * * @param conn Connection object. * @param passkey Entered passkey. * * @return Zero on success or negative error code otherwise */ int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey); /** @brief Cancel ongoing authenticated pairing. * * This function allows to cancel ongoing authenticated pairing. * * @param conn Connection object. * * @return Zero on success or negative error code otherwise */ int bt_conn_auth_cancel(struct bt_conn *conn); /** @brief Reply if passkey was confirmed to match by user. * * This function should be called only after passkey_confirm callback from * bt_conn_auth_cb structure was called. * * @param conn Connection object. * * @return Zero on success or negative error code otherwise */ int bt_conn_auth_passkey_confirm(struct bt_conn *conn); /** @brief Reply if incoming pairing was confirmed by user. * * This function should be called only after pairing_confirm callback from * bt_conn_auth_cb structure was called if user confirmed incoming pairing. * * @param conn Connection object. * * @return Zero on success or negative error code otherwise */ int bt_conn_auth_pairing_confirm(struct bt_conn *conn); /** @brief Reply with entered PIN code. * * This function should be called only after PIN code callback from * bt_conn_auth_cb structure was called. It's for legacy 2.0 devices. * * @param conn Connection object. * @param pin Entered PIN code. * * @return Zero on success or negative error code otherwise */ int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin); /** Connection parameters for BR/EDR connections */ struct bt_br_conn_param { bool allow_role_switch; }; /** @brief Initialize BR/EDR connection parameters * * @param role_switch True if role switch is allowed */ #define BT_BR_CONN_PARAM_INIT(role_switch) \ { \ .allow_role_switch = (role_switch), \ } /** Helper to declare BR/EDR connection parameters inline * * @param role_switch True if role switch is allowed */ #define BT_BR_CONN_PARAM(role_switch) \ ((struct bt_br_conn_param[]) { \ BT_BR_CONN_PARAM_INIT(role_switch) \ }) /** Default BR/EDR connection parameters: * Role switch allowed */ #define BT_BR_CONN_PARAM_DEFAULT BT_BR_CONN_PARAM(true) /** @brief Initiate an BR/EDR connection to a remote device. * * Allows initiate new BR/EDR link to remote peer using its address. * * The caller gets a new reference to the connection object which must be * released with bt_conn_unref() once done using the object. * * @param peer Remote address. * @param param Initial connection parameters. * * @return Valid connection object on success or NULL otherwise. */ struct bt_conn *bt_conn_create_br(const bt_addr_t *peer, const struct bt_br_conn_param *param); /** @brief Initiate an SCO connection to a remote device. * * Allows initiate new SCO link to remote peer using its address. * * The caller gets a new reference to the connection object which must be * released with bt_conn_unref() once done using the object. * * @param peer Remote address. * * @return Valid connection object on success or NULL otherwise. */ struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_CONN_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/conn.h
C
apache-2.0
46,291
/** @file * @brief Bluetooth subsystem crypto APIs. */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_CRYPTO_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_CRYPTO_H_ /** * @brief Cryptography * @defgroup bt_crypto Cryptography * @ingroup bluetooth * @{ */ #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /** @brief Generate random data. * * A random number generation helper which utilizes the Bluetooth * controller's own RNG. * * @param buf Buffer to insert the random data * @param len Length of random data to generate * * @return Zero on success or error code otherwise, positive in case * of protocol error or negative (POSIX) in case of stack internal error */ int bt_rand(void *buf, size_t len); /** @brief AES encrypt little-endian data. * * An AES encrypt helper is used to request the Bluetooth controller's own * hardware to encrypt the plaintext using the key and returns the encrypted * data. * * @param key 128 bit LS byte first key for the encryption of the plaintext * @param plaintext 128 bit LS byte first plaintext data block to be encrypted * @param enc_data 128 bit LS byte first encrypted data block * * @return Zero on success or error code otherwise. */ int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]); /** @brief AES encrypt big-endian data. * * An AES encrypt helper is used to request the Bluetooth controller's own * hardware to encrypt the plaintext using the key and returns the encrypted * data. * * @param key 128 bit MS byte first key for the encryption of the plaintext * @param plaintext 128 bit MS byte first plaintext data block to be encrypted * @param enc_data 128 bit MS byte first encrypted data block * * @return Zero on success or error code otherwise. */ int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]); int bt_decrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]); /** @brief Decrypt big-endian data with AES-CCM. * * Decrypts and authorizes @c enc_data with AES-CCM, as described in * https://tools.ietf.org/html/rfc3610. * * Assumes that the MIC follows directly after the encrypted data. * * @param key 128 bit MS byte first key * @param nonce 13 byte MS byte first nonce * @param enc_data Encrypted data * @param len Length of the encrypted data * @param aad Additional input data * @param aad_len Additional input data length * @param plaintext Plaintext buffer to place result in * @param mic_size Size of the trailing MIC (in bytes) * * @retval 0 Successfully decrypted the data. * @retval -EINVAL Invalid parameters. * @retval -EBADMSG Authentication failed. */ int bt_ccm_decrypt(const u8_t key[16], u8_t nonce[13], const u8_t *enc_data, size_t len, const u8_t *aad, size_t aad_len, u8_t *plaintext, size_t mic_size); /** @brief Encrypt big-endian data with AES-CCM. * * Encrypts and generates a MIC from @c plaintext with AES-CCM, as described in * https://tools.ietf.org/html/rfc3610. * * Places the MIC directly after the encrypted data. * * @param key 128 bit MS byte first key * @param nonce 13 byte MS byte first nonce * @param enc_data Buffer to place encrypted data in * @param len Length of the encrypted data * @param aad Additional input data * @param aad_len Additional input data length * @param plaintext Plaintext buffer to encrypt * @param mic_size Size of the trailing MIC (in bytes) * * @retval 0 Successfully encrypted the data. * @retval -EINVAL Invalid parameters. */ int bt_ccm_encrypt(const u8_t key[16], u8_t nonce[13], const u8_t *enc_data, size_t len, const u8_t *aad, size_t aad_len, u8_t *plaintext, size_t mic_size); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_CRYPTO_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/crypto.h
C
apache-2.0
4,056
/** @file * @brief Bluetooth Generic Access Profile defines and Assigned Numbers. */ /* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_GAP_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_GAP_H_ #ifdef __cplusplus extern "C" { #endif /** * @brief Bluetooth Generic Access Profile defines and Assigned Numbers. * @defgroup bt_gap_defines Defines and Assigned Numbers * @ingroup bluetooth * @{ */ /** Company Identifiers (see Bluetooth Assigned Numbers) */ #define BT_COMP_ID_LF 0x05f1 /* The Linux Foundation */ /** EIR/AD data type definitions */ #define BT_DATA_FLAGS 0x01 /* AD flags */ #define BT_DATA_UUID16_SOME 0x02 /* 16-bit UUID, more available */ #define BT_DATA_UUID16_ALL 0x03 /* 16-bit UUID, all listed */ #define BT_DATA_UUID32_SOME 0x04 /* 32-bit UUID, more available */ #define BT_DATA_UUID32_ALL 0x05 /* 32-bit UUID, all listed */ #define BT_DATA_UUID128_SOME 0x06 /* 128-bit UUID, more available */ #define BT_DATA_UUID128_ALL 0x07 /* 128-bit UUID, all listed */ #define BT_DATA_NAME_SHORTENED 0x08 /* Shortened name */ #define BT_DATA_NAME_COMPLETE 0x09 /* Complete name */ #define BT_DATA_TX_POWER 0x0a /* Tx Power */ #define BT_DATA_SM_TK_VALUE 0x10 /* Security Manager TK Value */ #define BT_DATA_SM_OOB_FLAGS 0x11 /* Security Manager OOB Flags */ #define BT_DATA_SOLICIT16 0x14 /* Solicit UUIDs, 16-bit */ #define BT_DATA_SOLICIT128 0x15 /* Solicit UUIDs, 128-bit */ #define BT_DATA_SVC_DATA16 0x16 /* Service data, 16-bit UUID */ #define BT_DATA_GAP_APPEARANCE 0x19 /* GAP appearance */ #define BT_DATA_LE_BT_DEVICE_ADDRESS 0x1b /* LE Bluetooth Device Address */ #define BT_DATA_LE_ROLE 0x1c /* LE Role */ #define BT_DATA_SOLICIT32 0x1f /* Solicit UUIDs, 32-bit */ #define BT_DATA_SVC_DATA32 0x20 /* Service data, 32-bit UUID */ #define BT_DATA_SVC_DATA128 0x21 /* Service data, 128-bit UUID */ #define BT_DATA_LE_SC_CONFIRM_VALUE 0x22 /* LE SC Confirmation Value */ #define BT_DATA_LE_SC_RANDOM_VALUE 0x23 /* LE SC Random Value */ #define BT_DATA_URI 0x24 /* URI */ #define BT_DATA_MESH_PROV 0x29 /* Mesh Provisioning PDU */ #define BT_DATA_MESH_MESSAGE 0x2a /* Mesh Networking PDU */ #define BT_DATA_MESH_BEACON 0x2b /* Mesh Beacon */ #define BT_DATA_MANUFACTURER_DATA 0xff /* Manufacturer Specific Data */ #define BT_LE_AD_LIMITED 0x01 /* Limited Discoverable */ #define BT_LE_AD_GENERAL 0x02 /* General Discoverable */ #define BT_LE_AD_NO_BREDR 0x04 /* BR/EDR not supported */ /* Defined GAP timers */ #define BT_GAP_SCAN_FAST_INTERVAL 0x0060 /* 60 ms */ #define BT_GAP_SCAN_FAST_WINDOW 0x0030 /* 30 ms */ #define BT_GAP_SCAN_SLOW_INTERVAL_1 0x0800 /* 1.28 s */ #define BT_GAP_SCAN_SLOW_WINDOW_1 0x0012 /* 11.25 ms */ #define BT_GAP_SCAN_SLOW_INTERVAL_2 0x1000 /* 2.56 s */ #define BT_GAP_SCAN_SLOW_WINDOW_2 0x0012 /* 11.25 ms */ #define BT_GAP_ADV_FAST_INT_MIN_1 0x0030 /* 30 ms */ #define BT_GAP_ADV_FAST_INT_MAX_1 0x0060 /* 60 ms */ #define BT_GAP_ADV_FAST_INT_MIN_2 0x00a0 /* 100 ms */ #define BT_GAP_ADV_FAST_INT_MAX_2 0x00f0 /* 150 ms */ #define BT_GAP_ADV_SLOW_INT_MIN 0x0640 /* 1 s */ #define BT_GAP_ADV_SLOW_INT_MAX 0x0780 /* 1.2 s */ #define BT_GAP_INIT_CONN_INT_MIN 0x0018 /* 30 ms */ #define BT_GAP_INIT_CONN_INT_MAX 0x0028 /* 50 ms */ /** LE PHY types */ enum { /** LE 1M PHY */ BT_GAP_LE_PHY_1M = BIT(0), /** LE 2M PHY */ BT_GAP_LE_PHY_2M = BIT(1), /** LE Coded PHY */ BT_GAP_LE_PHY_CODED = BIT(2), }; /** Advertising PDU types */ enum { /** Scannable and connectable advertising. */ BT_GAP_ADV_TYPE_ADV_IND = 0x00, /** Directed connectable advertising. */ BT_GAP_ADV_TYPE_ADV_DIRECT_IND = 0x01, /** Non-connectable and scannable advertising. */ BT_GAP_ADV_TYPE_ADV_SCAN_IND = 0x02, /** Non-connectable and non-scannable advertising. */ BT_GAP_ADV_TYPE_ADV_NONCONN_IND = 0x03, /** Additional advertising data requested by an active scanner. */ BT_GAP_ADV_TYPE_SCAN_RSP = 0x04, /** Extended advertising, see advertising properties. */ BT_GAP_ADV_TYPE_EXT_ADV = 0x05, }; /** Advertising PDU properties */ enum { /** Connectable advertising. */ BT_GAP_ADV_PROP_CONNECTABLE = BIT(0), /** Scannable advertising. */ BT_GAP_ADV_PROP_SCANNABLE = BIT(1), /** Directed advertising. */ BT_GAP_ADV_PROP_DIRECTED = BIT(2), /** Additional advertising data requested by an active scanner. */ BT_GAP_ADV_PROP_SCAN_RESPONSE = BIT(3), /** Extended advertising. */ BT_GAP_ADV_PROP_EXT_ADV = BIT(4), }; /** Maximum advertising data length. */ #define BT_GAP_ADV_MAX_ADV_DATA_LEN 31 /** Maximum extended advertising data length. * * @note The maximum advertising data length that can be sent by an extended * advertiser is defined by the controller. */ #define BT_GAP_ADV_MAX_EXT_ADV_DATA_LEN 1650 #define BT_GAP_TX_POWER_INVALID 0x7f #define BT_GAP_RSSI_INVALID 0x7f #define BT_GAP_SID_INVALID 0xff #define BT_GAP_NO_TIMEOUT 0x0000 /* The maximum allowed high duty cycle directed advertising timeout, 1.28 * seconds in 10 ms unit. */ #define BT_GAP_ADV_HIGH_DUTY_CYCLE_MAX_TIMEOUT 128 #define BT_GAP_DATA_LEN_DEFAULT 0x001b /* 27 bytes */ #define BT_GAP_DATA_LEN_MAX 0x00fb /* 251 bytes */ #define BT_GAP_DATA_TIME_DEFAULT 0x0148 /* 328 us */ #define BT_GAP_DATA_TIME_MAX 0x4290 /* 17040 us */ /** * @} */ #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_GAP_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/gap.h
C
apache-2.0
6,318
/** @file * @brief Generic Attribute Profile handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __BT_GATT_H #define __BT_GATT_H /** * @brief Generic Attribute Profile (GATT) * @defgroup bt_gatt Generic Attribute Profile (GATT) * @ingroup bluetooth * @{ */ #include <stddef.h> #include <sys/types.h> #include <misc/util.h> #include <bluetooth/conn.h> #include <bluetooth/uuid.h> #include <bluetooth/att.h> #ifdef __cplusplus extern "C" { #endif /** GATT attribute permission bit field values */ enum { /** No operations supported, e.g. for notify-only */ BT_GATT_PERM_NONE = 0, /** Attribute read permission. */ BT_GATT_PERM_READ = BIT(0), /** Attribute write permission. */ BT_GATT_PERM_WRITE = BIT(1), /** @brief Attribute read permission with encryption. * * If set, requires encryption for read access. */ BT_GATT_PERM_READ_ENCRYPT = BIT(2), /** @brief Attribute write permission with encryption. * * If set, requires encryption for write access. */ BT_GATT_PERM_WRITE_ENCRYPT = BIT(3), /** @brief Attribute read permission with authentication. * * If set, requires encryption using authenticated link-key for read * access. */ BT_GATT_PERM_READ_AUTHEN = BIT(4), /** @brief Attribute write permission with authentication. * * If set, requires encryption using authenticated link-key for write * access. */ BT_GATT_PERM_WRITE_AUTHEN = BIT(5), /** @brief Attribute prepare write permission. * * If set, allows prepare writes with use of BT_GATT_WRITE_FLAG_PREPARE * passed to write callback. */ BT_GATT_PERM_PREPARE_WRITE = BIT(6), }; /** @def BT_GATT_ERR * @brief Construct error return value for attribute read and write callbacks. * * @param _att_err ATT error code * * @return Appropriate error code for the attribute callbacks. */ #define BT_GATT_ERR(_att_err) (-(_att_err)) /** GATT attribute write flags */ enum { /** @brief Attribute prepare write flag * * If set, write callback should only check if the device is * authorized but no data shall be written. */ BT_GATT_WRITE_FLAG_PREPARE = BIT(0), /** @brief Attribute write command flag * * If set, indicates that write operation is a command (Write without * response) which doesn't generate any response. */ BT_GATT_WRITE_FLAG_CMD = BIT(1), }; /** @brief GATT Attribute structure. */ struct bt_gatt_attr { /** Attribute UUID */ const struct bt_uuid *uuid; /** @brief Attribute read callback * * The callback can also be used locally to read the contents of the * attribute in which case no connection will be set. * * @param conn The connection that is requesting to read * @param attr The attribute that's being read * @param buf Buffer to place the read result in * @param len Length of data to read * @param offset Offset to start reading from * * @return Number fo bytes read, or in case of an error * BT_GATT_ERR() with a specific ATT error code. */ ssize_t (*read)(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @brief Attribute write callback * * The callback can also be used locally to read the contents of the * attribute in which case no connection will be set. * * @param conn The connection that is requesting to write * @param attr The attribute that's being written * @param buf Buffer with the data to write * @param len Number of bytes in the buffer * @param offset Offset to start writing from * @param flags Flags (BT_GATT_WRITE_*) * * @return Number of bytes written, or in case of an error * BT_GATT_ERR() with a specific ATT error code. */ ssize_t (*write)(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags); /** Attribute user data */ void *user_data; /** Attribute handle */ u16_t handle; /** Attribute permissions */ u8_t perm; }; /** @brief GATT Service structure */ struct bt_gatt_service_static { /** Service Attributes */ const struct bt_gatt_attr *attrs; /** Service Attribute count */ size_t attr_count; }; /** @brief GATT Service structure */ struct bt_gatt_service { /** Service Attributes */ struct bt_gatt_attr *attrs; /** Service Attribute count */ size_t attr_count; sys_snode_t node; }; /** @brief Service Attribute Value. */ struct bt_gatt_service_val { /** Service UUID. */ const struct bt_uuid *uuid; /** Service end handle. */ u16_t end_handle; }; /** @brief Include Attribute Value. */ struct bt_gatt_include { /** Service UUID. */ const struct bt_uuid *uuid; /** Service start handle. */ u16_t start_handle; /** Service end handle. */ u16_t end_handle; }; /** Characteristic Properties Bit field values */ /** @def BT_GATT_CHRC_BROADCAST * @brief Characteristic broadcast property. * * If set, permits broadcasts of the Characteristic Value using Server * Characteristic Configuration Descriptor. */ #define BT_GATT_CHRC_BROADCAST 0x01 /** @def BT_GATT_CHRC_READ * @brief Characteristic read property. * * If set, permits reads of the Characteristic Value. */ #define BT_GATT_CHRC_READ 0x02 /** @def BT_GATT_CHRC_WRITE_WITHOUT_RESP * @brief Characteristic write without response property. * * If set, permits write of the Characteristic Value without response. */ #define BT_GATT_CHRC_WRITE_WITHOUT_RESP 0x04 /** @def BT_GATT_CHRC_WRITE * @brief Characteristic write with response property. * * If set, permits write of the Characteristic Value with response. */ #define BT_GATT_CHRC_WRITE 0x08 /** @def BT_GATT_CHRC_NOTIFY * @brief Characteristic notify property. * * If set, permits notifications of a Characteristic Value without * acknowledgment. */ #define BT_GATT_CHRC_NOTIFY 0x10 /** @def BT_GATT_CHRC_INDICATE * @brief Characteristic indicate property. * * If set, permits indications of a Characteristic Value with acknowledgment. */ #define BT_GATT_CHRC_INDICATE 0x20 /** @def BT_GATT_CHRC_AUTH * @brief Characteristic Authenticated Signed Writes property. * * If set, permits signed writes to the Characteristic Value. */ #define BT_GATT_CHRC_AUTH 0x40 /** @def BT_GATT_CHRC_EXT_PROP * @brief Characteristic Extended Properties property. * * If set, additional characteristic properties are defined in the * Characteristic Extended Properties Descriptor. */ #define BT_GATT_CHRC_EXT_PROP 0x80 /** @brief Characteristic Attribute Value. */ struct bt_gatt_chrc { /** Characteristic UUID. */ const struct bt_uuid *uuid; /** Characteristic Value handle. */ u16_t value_handle; /** Characteristic properties. */ u8_t properties; }; /** Characteristic Extended Properties Bit field values */ #define BT_GATT_CEP_RELIABLE_WRITE 0x0001 #define BT_GATT_CEP_WRITABLE_AUX 0x0002 /** @brief Characteristic Extended Properties Attribute Value. */ struct bt_gatt_cep { /** Characteristic Extended properties */ u16_t properties; }; /** Client Characteristic Configuration Values */ /** @def BT_GATT_CCC_NOTIFY * @brief Client Characteristic Configuration Notification. * * If set, changes to Characteristic Value shall be notified. */ #define BT_GATT_CCC_NOTIFY 0x0001 /** @def BT_GATT_CCC_INDICATE * @brief Client Characteristic Configuration Indication. * * If set, changes to Characteristic Value shall be indicated. */ #define BT_GATT_CCC_INDICATE 0x0002 /** Client Characteristic Configuration Attribute Value */ struct bt_gatt_ccc { /** Client Characteristic Configuration flags */ u16_t flags; }; /** @brief GATT Characteristic Presentation Format Attribute Value. */ struct bt_gatt_cpf { /** Format of the value of the characteristic */ u8_t format; /** Exponent field to determine how the value of this characteristic is * further formatted */ s8_t exponent; /** Unit of the characteristic */ u16_t unit; /** Name space of the description */ u8_t name_space; /** Description of the characteristic as defined in a higher layer profile */ u16_t description; } __packed; /** * @defgroup bt_gatt_server GATT Server APIs * @ingroup bt_gatt * @{ */ /** @brief Register GATT service. * * Register GATT service. Applications can make use of * macros such as BT_GATT_PRIMARY_SERVICE, BT_GATT_CHARACTERISTIC, * BT_GATT_DESCRIPTOR, etc. * * When using :option:`CONFIG_BT_GATT_CACHING` and :option:`CONFIG_BT_SETTINGS` * then all services that should be included in the GATT Database Hash * calculation should be added before calling @ref settings_load. * All services registered after settings_load will trigger a new database hash * calculation and a new hash stored. * * @param svc Service containing the available attributes * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_service_register(struct bt_gatt_service *svc); /** @brief Unregister GATT service. * * * @param svc Service to be unregistered. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_service_unregister(struct bt_gatt_service *svc); enum { BT_GATT_ITER_STOP = 0, BT_GATT_ITER_CONTINUE, }; /** @typedef bt_gatt_attr_func_t * @brief Attribute iterator callback. * * @param attr Attribute found. * @param user_data Data given. * * @return BT_GATT_ITER_CONTINUE if should continue to the next attribute. * @return BT_GATT_ITER_STOP to stop. */ typedef u8_t (*bt_gatt_attr_func_t)(const struct bt_gatt_attr *attr, void *user_data); /** @brief Attribute iterator by type. * * Iterate attributes in the given range matching given UUID and/or data. * * @param start_handle Start handle. * @param end_handle End handle. * @param uuid UUID to match, passing NULL skips UUID matching. * @param attr_data Attribute data to match, passing NULL skips data matching. * @param num_matches Number matches, passing 0 makes it unlimited. * @param func Callback function. * @param user_data Data to pass to the callback. */ void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data); /** @brief Attribute iterator. * * Iterate attributes in the given range. * * @param start_handle Start handle. * @param end_handle End handle. * @param func Callback function. * @param user_data Data to pass to the callback. */ static inline void bt_gatt_foreach_attr(u16_t start_handle, u16_t end_handle, bt_gatt_attr_func_t func, void *user_data) { bt_gatt_foreach_attr_type(start_handle, end_handle, NULL, NULL, 0, func, user_data); } /** @brief Iterate to the next attribute * * Iterate to the next attribute following a given attribute. * * @param attr Current Attribute. * * @return The next attribute or NULL if it cannot be found. */ struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr); /** @brief Get the handle of the characteristic value descriptor. * * @param attr A Characteristic Attribute * * @return the handle of the corresponding Characteristic Value. The value will * be zero (the invalid handle) if @p attr was not a characteristic * attribute. */ uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr); /** @brief Generic Read Attribute value helper. * * Read attribute value from local database storing the result into buffer. * * @param conn Connection object. * @param attr Attribute to read. * @param buf Buffer to store the value. * @param buf_len Buffer length. * @param offset Start offset. * @param value Attribute value. * @param value_len Length of the attribute value. * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t buf_len, u16_t offset, const void *value, u16_t value_len); /** @brief Read Service Attribute helper. * * Read service attribute value from local database storing the result into * buffer after encoding it. * @note Only use this with attributes which user_data is a bt_uuid. * * @param conn Connection object. * @param attr Attribute to read. * @param buf Buffer to store the value read. * @param len Buffer length. * @param offset Start offset. * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @def BT_GATT_SERVICE_DEFINE * @brief Statically define and register a service. * * Helper macro to statically define and register a service. * * @param _name Service name. */ #define BT_GATT_SERVICE_DEFINE(_name, ...) \ struct bt_gatt_attr attr_##_name[] = { __VA_ARGS__ }; \ const Z_STRUCT_SECTION_ITERABLE(bt_gatt_service_static, _name) =\ BT_GATT_SERVICE(attr_##_name) /** @def BT_GATT_SERVICE * @brief Service Structure Declaration Macro. * * Helper macro to declare a service structure. * * @param _attrs Service attributes. */ #define BT_GATT_SERVICE(_attrs) \ { \ .attrs = _attrs, \ .attr_count = ARRAY_SIZE(_attrs), \ } /** @def BT_GATT_PRIMARY_SERVICE * @brief Primary Service Declaration Macro. * * Helper macro to declare a primary service attribute. * * @param _service Service attribute value. */ #define BT_GATT_PRIMARY_SERVICE(_service) \ BT_GATT_ATTRIBUTE(BT_UUID_GATT_PRIMARY, BT_GATT_PERM_READ, \ bt_gatt_attr_read_service, NULL, _service) /** @def BT_GATT_SECONDARY_SERVICE * @brief Secondary Service Declaration Macro. * * Helper macro to declare a secondary service attribute. * * @param _service Service attribute value. */ #define BT_GATT_SECONDARY_SERVICE(_service) \ BT_GATT_ATTRIBUTE(BT_UUID_GATT_SECONDARY, BT_GATT_PERM_READ, \ bt_gatt_attr_read_service, NULL, _service) /** @brief Read Include Attribute helper. * * Read include service attribute value from local database storing the result * into buffer after encoding it. * @note Only use this with attributes which user_data is a bt_gatt_include. * * @param conn Connection object. * @param attr Attribute to read. * @param buf Buffer to store the value read. * @param len Buffer length. * @param offset Start offset. * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @def BT_GATT_INCLUDE_SERVICE * @brief Include Service Declaration Macro. * * Helper macro to declare database internal include service attribute. * * @param _service_incl the first service attribute of service to include */ #define BT_GATT_INCLUDE_SERVICE(_service_incl) \ BT_GATT_ATTRIBUTE(BT_UUID_GATT_INCLUDE, BT_GATT_PERM_READ, \ bt_gatt_attr_read_included, NULL, _service_incl) /** @brief Read Characteristic Attribute helper. * * Read characteristic attribute value from local database storing the result * into buffer after encoding it. * @note Only use this with attributes which user_data is a bt_gatt_chrc. * * @param conn Connection object. * @param attr Attribute to read. * @param buf Buffer to store the value read. * @param len Buffer length. * @param offset Start offset. * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @def BT_GATT_CHARACTERISTIC * @brief Characteristic and Value Declaration Macro. * * Helper macro to declare a characteristic attribute along with its * attribute value. * * @param _uuid Characteristic attribute uuid. * @param _props Characteristic attribute properties. * @param _perm Characteristic Attribute access permissions. * @param _read Characteristic Attribute read callback. * @param _write Characteristic Attribute write callback. * @param _value Characteristic Attribute value. */ #define BT_GATT_CHARACTERISTIC(_uuid, _props, _perm, _read, _write, _value) \ BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \ bt_gatt_attr_read_chrc, NULL, \ ((struct bt_gatt_chrc[]) { { .uuid = _uuid, \ .value_handle = 0U, \ .properties = _props, \ } })), \ BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) #if IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_CONN) #else #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) #endif /** @brief GATT CCC configuration entry. * * @param id Local identity, BT_ID_DEFAULT in most cases. * @param peer Remote peer address * @param value Configuration value. * @param data Configuration pointer data. */ struct bt_gatt_ccc_cfg { u8_t id; bt_addr_le_t peer; u16_t value; }; /** Internal representation of CCC value */ struct _bt_gatt_ccc { /** Configuration for each connection */ struct bt_gatt_ccc_cfg cfg[BT_GATT_CCC_MAX]; /** Highest value of all connected peer's subscriptions */ u16_t value; /** @brief CCC attribute changed callback * * @param attr The attribute that's changed value * @param value New value */ void (*cfg_changed)(const struct bt_gatt_attr *attr, u16_t value); /** @brief CCC attribute write validation callback * * @param conn The connection that is requesting to write * @param attr The attribute that's being written * @param value CCC value to write * * @return Number of bytes to write, or in case of an error * BT_GATT_ERR() with a specific error code. */ ssize_t (*cfg_write)(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t value); /** @brief CCC attribute match handler * * Indicate if it is OK to send a notification or indication * to the subscriber. * * @param conn The connection that is being checked * @param attr The attribute that's being checked * * @return true if application has approved notification/indication, * false if application does not approve. */ bool (*cfg_match)(struct bt_conn *conn, const struct bt_gatt_attr *attr); }; /** @brief Read Client Characteristic Configuration Attribute helper. * * Read CCC attribute value from local database storing the result into buffer * after encoding it. * * @note Only use this with attributes which user_data is a _bt_gatt_ccc. * * @param conn Connection object. * @param attr Attribute to read. * @param buf Buffer to store the value read. * @param len Buffer length. * @param offset Start offset. * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @brief Write Client Characteristic Configuration Attribute helper. * * Write value in the buffer into CCC attribute. * * @note Only use this with attributes which user_data is a _bt_gatt_ccc. * * @param conn Connection object. * @param attr Attribute to read. * @param buf Buffer to store the value read. * @param len Buffer length. * @param offset Start offset. * @param flags Write flags. * * @return number of bytes written in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags); /** @def BT_GATT_CCC_INITIALIZER * @brief Initialize Client Characteristic Configuration Declaration Macro. * * Helper macro to initialize a Managed CCC attribute value. * * @param _changed Configuration changed callback. * @param _write Configuration write callback. * @param _match Configuration match callback. */ #define BT_GATT_CCC_INITIALIZER(_changed, _write, _match) \ { \ .cfg = {{0}}, \ .cfg_changed = _changed, \ .cfg_write = _write, \ .cfg_match = _match, \ } /** @def BT_GATT_CCC_MANAGED * @brief Managed Client Characteristic Configuration Declaration Macro. * * Helper macro to declare a Managed CCC attribute. * * @param _ccc CCC attribute user data, shall point to a _bt_gatt_ccc. * @param _perm CCC access permissions. */ #define BT_GATT_CCC_MANAGED(_ccc, _perm) \ BT_GATT_ATTRIBUTE(BT_UUID_GATT_CCC, _perm, \ bt_gatt_attr_read_ccc, bt_gatt_attr_write_ccc, \ _ccc) /** @def BT_GATT_CCC * @brief Client Characteristic Configuration Declaration Macro. * * Helper macro to declare a CCC attribute. * * @param _changed Configuration changed callback. * @param _perm CCC access permissions. */ #define BT_GATT_CCC(_changed, _perm) \ BT_GATT_CCC_MANAGED(((struct _bt_gatt_ccc[]) \ {BT_GATT_CCC_INITIALIZER(_changed, NULL, NULL)}), _perm) /** @brief Read Characteristic Extended Properties Attribute helper * * Read CEP attribute value from local database storing the result into buffer * after encoding it. * * @note Only use this with attributes which user_data is a bt_gatt_cep. * * @param conn Connection object * @param attr Attribute to read * @param buf Buffer to store the value read * @param len Buffer length * @param offset Start offset * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @def BT_GATT_CEP * @brief Characteristic Extended Properties Declaration Macro. * * Helper macro to declare a CEP attribute. * * @param _value Descriptor attribute value. */ #define BT_GATT_CEP(_value) \ BT_GATT_DESCRIPTOR(BT_UUID_GATT_CEP, BT_GATT_PERM_READ, \ bt_gatt_attr_read_cep, NULL, (void *)_value) /** @brief Read Characteristic User Description Descriptor Attribute helper * * Read CUD attribute value from local database storing the result into buffer * after encoding it. * * @note Only use this with attributes which user_data is a NULL-terminated C * string. * * @param conn Connection object * @param attr Attribute to read * @param buf Buffer to store the value read * @param len Buffer length * @param offset Start offset * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @def BT_GATT_CUD * @brief Characteristic User Format Descriptor Declaration Macro. * * Helper macro to declare a CUD attribute. * * @param _value User description NULL-terminated C string. * @param _perm Descriptor attribute access permissions. */ #define BT_GATT_CUD(_value, _perm) \ BT_GATT_DESCRIPTOR(BT_UUID_GATT_CUD, _perm, bt_gatt_attr_read_cud, \ NULL, (void *)_value) /** @brief Read Characteristic Presentation format Descriptor Attribute helper * * Read CPF attribute value from local database storing the result into buffer * after encoding it. * * @note Only use this with attributes which user_data is a bt_gatt_pf. * * @param conn Connection object * @param attr Attribute to read * @param buf Buffer to store the value read * @param len Buffer length * @param offset Start offset * * @return number of bytes read in case of success or negative values in * case of error. */ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset); /** @def BT_GATT_CPF * @brief Characteristic Presentation Format Descriptor Declaration Macro. * * Helper macro to declare a CPF attribute. * * @param _value Descriptor attribute value. */ #define BT_GATT_CPF(_value) \ BT_GATT_DESCRIPTOR(BT_UUID_GATT_CPF, BT_GATT_PERM_READ, \ bt_gatt_attr_read_cpf, NULL, (void *)_value) /** @def BT_GATT_DESCRIPTOR * @brief Descriptor Declaration Macro. * * Helper macro to declare a descriptor attribute. * * @param _uuid Descriptor attribute uuid. * @param _perm Descriptor attribute access permissions. * @param _read Descriptor attribute read callback. * @param _write Descriptor attribute write callback. * @param _value Descriptor attribute value. */ #define BT_GATT_DESCRIPTOR(_uuid, _perm, _read, _write, _value) \ BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) /** @def BT_GATT_ATTRIBUTE * @brief Attribute Declaration Macro. * * Helper macro to declare an attribute. * * @param _uuid Attribute uuid. * @param _perm Attribute access permissions. * @param _read Attribute read callback. * @param _write Attribute write callback. * @param _value Attribute value. */ #define BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) \ { \ .uuid = _uuid, \ .read = _read, \ .write = _write, \ .user_data = _value, \ .handle = 0, \ .perm = _perm, \ } /** @brief Notification complete result callback. * * @param conn Connection object. */ typedef void (*bt_gatt_complete_func_t) (struct bt_conn *conn, void *user_data); struct bt_gatt_notify_params { /** Notification Attribute UUID type */ const struct bt_uuid *uuid; /** Notification Attribute object*/ const struct bt_gatt_attr *attr; /** Notification Value data */ const void *data; /** Notification Value length */ u16_t len; /** Notification Value callback */ bt_gatt_complete_func_t func; /** Notification Value callback user data */ void *user_data; }; /** @brief Notify attribute value change. * * This function works in the same way as @ref bt_gatt_notify. * With the addition that after sending the notification the * callback function will be called. * * The callback is run from System Workqueue context. * * Alternatively it is possible to notify by UUID by setting it on the * parameters, when using this method the attribute given is used as the * start range when looking up for possible matches. * * @param conn Connection object. * @param params Notification parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_notify_cb(struct bt_conn *conn, struct bt_gatt_notify_params *params); /** @brief Notify multiple attribute value change. * * @param conn Connection object. * @param num_params Number of notification parameters. * @param params Array of notification parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_notify_multiple(struct bt_conn *conn, u16_t num_params, struct bt_gatt_notify_params *params); /** @brief Notify attribute value change. * * Send notification of attribute value change, if connection is NULL notify * all peer that have notification enabled via CCC otherwise do a direct * notification only the given connection. * * The attribute object on the parameters can be the so called Characteristic * Declaration, which is usually declared with BT_GATT_CHARACTERISTIC followed * by BT_GATT_CCC, or the Characteristic Value Declaration which is * automatically created after the Characteristic Declaration when using * BT_GATT_CHARACTERISTIC. * * @param conn Connection object. * @param attr Characteristic or Characteristic Value attribute. * @param data Pointer to Attribute data. * @param len Attribute value length. * * @return 0 in case of success or negative value in case of error. */ static inline int bt_gatt_notify(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *data, u16_t len) { struct bt_gatt_notify_params params; memset(&params, 0, sizeof(params)); params.attr = attr; params.data = data; params.len = len; return bt_gatt_notify_cb(conn, &params); } /** @typedef bt_gatt_indicate_func_t * @brief Indication complete result callback. * * @param conn Connection object. * @param attr Attribute object. * @param err ATT error code */ typedef void (*bt_gatt_indicate_func_t)(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err); /** @brief GATT Indicate Value parameters */ struct bt_gatt_indicate_params { /** Notification Attribute UUID type */ const struct bt_uuid *uuid; /** Indicate Attribute object*/ const struct bt_gatt_attr *attr; /** Indicate Value callback */ bt_gatt_indicate_func_t func; /** Indicate Value data*/ const void *data; /** Indicate Value length*/ u16_t len; }; /** @brief Indicate attribute value change. * * Send an indication of attribute value change. if connection is NULL * indicate all peer that have notification enabled via CCC otherwise do a * direct indication only the given connection. * * The attribute object on the parameters can be the so called Characteristic * Declaration, which is usually declared with BT_GATT_CHARACTERISTIC followed * by BT_GATT_CCC, or the Characteristic Value Declaration which is * automatically created after the Characteristic Declaration when using * BT_GATT_CHARACTERISTIC. * * The callback is run from System Workqueue context. * * Alternatively it is possible to indicate by UUID by setting it on the * parameters, when using this method the attribute given is used as the * start range when looking up for possible matches. * * @note This procedure is asynchronous therefore the parameters need to * remains valid while it is active. * * @param conn Connection object. * @param params Indicate parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_indicate(struct bt_conn *conn, struct bt_gatt_indicate_params *params); /** @brief Check if connection have subscribed to attribute * * Check if connection has subscribed to attribute value change. * * The attribute object can be the so called Characteristic Declaration, * which is usually declared with BT_GATT_CHARACTERISTIC followed * by BT_GATT_CCC, or the Characteristic Value Declaration which is * automatically created after the Characteristic Declaration when using * BT_GATT_CHARACTERISTIC, or the Client Characteristic Configuration * Descriptor (CCCD) which is created by BT_GATT_CCC. * * @param conn Connection object. * @param attr Attribute object. * @param ccc_value The subscription type, either notifications or indications. * * @return true if the attribute object has been subscribed. */ bool bt_gatt_is_subscribed(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t ccc_value); /** @brief Get ATT MTU for a connection * * Get negotiated ATT connection MTU, note that this does not equal the largest * amount of attribute data that can be transferred within a single packet. * * @param conn Connection object. * * @return MTU in bytes */ u16_t bt_gatt_get_mtu(struct bt_conn *conn); /** @} */ /** * @defgroup bt_gatt_client GATT Client APIs * @ingroup bt_gatt * @{ */ /** @brief GATT Exchange MTU parameters */ struct bt_gatt_exchange_params { /** Response callback */ void (*func)(struct bt_conn *conn, u8_t err, struct bt_gatt_exchange_params *params); }; /** @brief Exchange MTU * * This client procedure can be used to set the MTU to the maximum possible * size the buffers can hold. * * @note Shall only be used once per connection. * * @param conn Connection object. * @param params Exchange MTU parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params); struct bt_gatt_discover_params; /** @typedef bt_gatt_discover_func_t * @brief Discover attribute callback function. * * @param conn Connection object. * @param attr Attribute found. * @param params Discovery parameters given. * * If discovery procedure has completed this callback will be called with * attr set to NULL. This will not happen if procedure was stopped by returning * BT_GATT_ITER_STOP. The attribute is read-only and cannot be cached without * copying its contents. * * @return BT_GATT_ITER_CONTINUE if should continue attribute discovery. * @return BT_GATT_ITER_STOP to stop discovery procedure. */ typedef u8_t (*bt_gatt_discover_func_t)(struct bt_conn *conn, const struct bt_gatt_attr *attr, struct bt_gatt_discover_params *params); /** GATT Discover types */ enum { /** Discover Primary Services. */ BT_GATT_DISCOVER_PRIMARY, /** Discover Secondary Services. */ BT_GATT_DISCOVER_SECONDARY, /** Discover Included Services. */ BT_GATT_DISCOVER_INCLUDE, /** @brief Discover Characteristic Values. * * Discover Characteristic Value and its properties. */ BT_GATT_DISCOVER_CHARACTERISTIC, /** @brief Discover Descriptors. * * Discover Attributes which are not services or characteristics. * * @note The use of this type of discover is not recommended for * discovering in ranges across multiple services/characteristics * as it may incur in extra round trips. */ BT_GATT_DISCOVER_DESCRIPTOR, /** @brief Discover Attributes. * * Discover Attributes of any type. * * @note The use of this type of discover is not recommended for * discovering in ranges across multiple services/characteristics * as it may incur in more round trips. */ BT_GATT_DISCOVER_ATTRIBUTE, }; /** @brief GATT Discover Attributes parameters */ struct bt_gatt_discover_params { /** Discover UUID type */ struct bt_uuid *uuid; /** Discover attribute callback */ bt_gatt_discover_func_t func; union { struct { /** Include service attribute declaration handle */ u16_t attr_handle; /** Included service start handle */ u16_t start_handle; /** Included service end handle */ u16_t end_handle; } _included; /** Discover start handle */ u16_t start_handle; }; /** Discover end handle */ u16_t end_handle; /** Discover type */ u8_t type; }; /** @brief GATT Discover function * * This procedure is used by a client to discover attributes on a server. * * Primary Service Discovery: Procedure allows to discover specific Primary * Service based on UUID. * Include Service Discovery: Procedure allows to discover all Include Services * within specified range. * Characteristic Discovery: Procedure allows to discover all characteristics * within specified handle range as well as * discover characteristics with specified UUID. * Descriptors Discovery: Procedure allows to discover all characteristic * descriptors within specified range. * * For each attribute found the callback is called which can then decide * whether to continue discovering or stop. * * @note This procedure is asynchronous therefore the parameters need to * remains valid while it is active. * * @param conn Connection object. * @param params Discover parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_discover(struct bt_conn *conn, struct bt_gatt_discover_params *params); struct bt_gatt_read_params; /** @typedef bt_gatt_read_func_t * @brief Read callback function * * @param conn Connection object. * @param err ATT error code. * @param params Read parameters used. * @param data Attribute value data. NULL means read has completed. * @param length Attribute value length. * * @return BT_GATT_ITER_CONTINUE if should continue to the next attribute. * @return BT_GATT_ITER_STOP to stop. */ typedef u8_t (*bt_gatt_read_func_t)(struct bt_conn *conn, u8_t err, struct bt_gatt_read_params *params, const void *data, u16_t length); /** @brief GATT Read parameters * * @param func Read attribute callback * @param handle_count If equals to 1 single.handle and single.offset * are used. If >1 Read Multiple Characteristic * Values is performed and handles are used. * If equals to 0 by_uuid is used for Read Using * Characteristic UUID. * @param handle Attribute handle * @param offset Attribute data offset * @param handles Handles to read in Read Multiple Characteristic Values * @param start_handle First requested handle number * @param end_handle Last requested handle number * @param uuid 2 or 16 octet UUID */ struct bt_gatt_read_params { bt_gatt_read_func_t func; size_t handle_count; union { struct { u16_t handle; u16_t offset; } single; u16_t *handles; struct { u16_t start_handle; u16_t end_handle; struct bt_uuid *uuid; } by_uuid; }; }; /** @brief Read Attribute Value by handle * * This procedure read the attribute value and return it to the callback. * * When reading attributes by UUID the callback can be called multiple times * depending on how many instances of given the UUID exists with the * start_handle being updated for each instance. * * If an instance does contain a long value which cannot be read entirely the * caller will need to read the remaining data separately using the handle and * offset. * * @note This procedure is asynchronous therefore the parameters need to * remains valid while it is active. * * @param conn Connection object. * @param params Read parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params); struct bt_gatt_write_params; /** @typedef bt_gatt_write_func_t * @brief Write callback function * * @param conn Connection object. * @param err ATT error code. * @param params Write parameters used. */ typedef void (*bt_gatt_write_func_t)(struct bt_conn *conn, u8_t err, struct bt_gatt_write_params *params); /** @brief GATT Write parameters */ struct bt_gatt_write_params { /** Response callback */ bt_gatt_write_func_t func; /** Attribute handle */ u16_t handle; /** Attribute data offset */ u16_t offset; /** Data to be written */ const void *data; /** Length of the data */ u16_t length; }; /** @brief Write Attribute Value by handle * * This procedure write the attribute value and return the result in the * callback. * * @note This procedure is asynchronous therefore the parameters need to * remains valid while it is active. * * @param conn Connection object. * @param params Write parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params); /** @brief Write Attribute Value by handle without response with callback. * * This function works in the same way as @ref bt_gatt_write_without_response. * With the addition that after sending the write the callback function will be * called. * * The callback is run from System Workqueue context. * * @note By using a callback it also disable the internal flow control * which would prevent sending multiple commands without waiting for * their transmissions to complete, so if that is required the caller * shall not submit more data until the callback is called. * * @param conn Connection object. * @param handle Attribute handle. * @param data Data to be written. * @param length Data length. * @param sign Whether to sign data * @param func Transmission complete callback. * @param user_data User data to be passed back to callback. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, const void *data, u16_t length, bool sign, bt_gatt_complete_func_t func, void *user_data); /** @brief Write Attribute Value by handle without response * * This procedure write the attribute value without requiring an * acknowledgment that the write was successfully performed * * @param conn Connection object. * @param handle Attribute handle. * @param data Data to be written. * @param length Data length. * @param sign Whether to sign data * * @return 0 in case of success or negative value in case of error. */ static inline int bt_gatt_write_without_response(struct bt_conn *conn, u16_t handle, const void *data, u16_t length, bool sign) { return bt_gatt_write_without_response_cb(conn, handle, data, length, sign, NULL, NULL); } struct bt_gatt_subscribe_params; /** @typedef bt_gatt_notify_func_t * @brief Notification callback function * * @param conn Connection object. May be NULL, indicating that the peer is * being unpaired * @param params Subscription parameters. * @param data Attribute value data. If NULL then subscription was removed. * @param length Attribute value length. * * @return BT_GATT_ITER_CONTINUE to continue receiving value notifications. * BT_GATT_ITER_STOP to unsubscribe from value notifications. */ typedef u8_t (*bt_gatt_notify_func_t)(struct bt_conn *conn, struct bt_gatt_subscribe_params *params, const void *data, u16_t length); /** Subscription flags */ enum { /** @brief Persistence flag * * If set, indicates that the subscription is not saved * on the GATT server side. Therefore, upon disconnection, * the subscription will be automatically removed * from the client's subscriptions list and * when the client reconnects, it will have to * issue a new subscription. */ BT_GATT_SUBSCRIBE_FLAG_VOLATILE, /** @brief No resubscribe flag * * By default when BT_GATT_SUBSCRIBE_FLAG_VOLATILE is unset, the * subscription will be automatically renewed when the client * reconnects, as a workaround for GATT servers that do not persist * subscriptions. * * This flag will disable the automatic resubscription. It is useful * if the application layer knows that the GATT server remembers * subscriptions from previous connections and wants to avoid renewing * the subscriptions. */ BT_GATT_SUBSCRIBE_FLAG_NO_RESUB, /** @brief Write pending flag * * If set, indicates write operation is pending waiting remote end to * respond. */ BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING, BT_GATT_SUBSCRIBE_NUM_FLAGS }; /** @brief GATT Subscribe parameters */ struct bt_gatt_subscribe_params { /** Notification value callback */ bt_gatt_notify_func_t notify; /** Subscribe value handle */ u16_t value_handle; /** Subscribe CCC handle */ u16_t ccc_handle; /** Subscribe value */ u16_t value; /** Subscription flags */ ATOMIC_DEFINE(flags, BT_GATT_SUBSCRIBE_NUM_FLAGS); sys_snode_t node; }; /** @brief Subscribe Attribute Value Notification * * This procedure subscribe to value notification using the Client * Characteristic Configuration handle. * If notification received subscribe value callback is called to return * notified value. One may then decide whether to unsubscribe directly from * this callback. Notification callback with NULL data will not be called if * subscription was removed by this method. * * @note This procedure is asynchronous therefore the parameters need to * remains valid while it is active. * * @param conn Connection object. * @param params Subscribe parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_subscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params); /** @brief Unsubscribe Attribute Value Notification * * This procedure unsubscribe to value notification using the Client * Characteristic Configuration handle. Notification callback with NULL data * will be called if subscription was removed by this call, until then the * parameters cannot be reused. * * @param conn Connection object. * @param params Subscribe parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_gatt_unsubscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params); /** @brief Cancel GATT pending request * * @param conn Connection object. * @param params Requested params address. */ void bt_gatt_cancel(struct bt_conn *conn, void *params); /** @} */ #ifdef __cplusplus } #endif /** * @} */ #endif /* __BT_GATT_H */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/gatt.h
C
apache-2.0
45,216
/* hci.h - Bluetooth Host Control Interface definitions */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_HCI_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_HCI_H_ #include <ble_types/types.h> #include <stdbool.h> #include <string.h> #include <misc/util.h> #include <net/buf.h> #include <bluetooth/addr.h> #include <bluetooth/hci_err.h> #include <bluetooth/conn.h> #ifdef __cplusplus extern "C" { #endif /* Special own address types for LL privacy (used in adv & scan parameters) */ #define BT_HCI_OWN_ADDR_RPA_OR_PUBLIC 0x02 #define BT_HCI_OWN_ADDR_RPA_OR_RANDOM 0x03 #define BT_HCI_OWN_ADDR_RPA_MASK 0x02 #define BT_HCI_PEER_ADDR_RPA_UNRESOLVED 0xfe #define BT_HCI_PEER_ADDR_ANONYMOUS 0xff #define BT_ENC_KEY_SIZE_MIN 0x07 #define BT_ENC_KEY_SIZE_MAX 0x10 struct bt_hci_evt_hdr { u8_t evt; u8_t len; } __packed; #define BT_HCI_EVT_HDR_SIZE 2 #define BT_ACL_START_NO_FLUSH 0x00 #define BT_ACL_CONT 0x01 #define BT_ACL_START 0x02 #define BT_ACL_COMPLETE 0x03 #define BT_ACL_POINT_TO_POINT 0x00 #define BT_ACL_BROADCAST 0x01 #define bt_acl_handle(h) ((h) & BIT_MASK(12)) #define bt_acl_flags(h) ((h) >> 12) #define bt_acl_flags_pb(f) ((f) & BIT_MASK(2)) #define bt_acl_flags_bc(f) ((f) >> 2) #define bt_acl_handle_pack(h, f) ((h) | ((f) << 12)) struct bt_hci_acl_hdr { u16_t handle; u16_t len; } __packed; #define BT_HCI_ACL_HDR_SIZE 4 struct bt_hci_cmd_hdr { u16_t opcode; u8_t param_len; } __packed; #define BT_HCI_CMD_HDR_SIZE 3 /* Supported Commands */ #define BT_CMD_TEST(cmd, octet, bit) (cmd[octet] & BIT(bit)) #define BT_CMD_LE_STATES(cmd) BT_CMD_TEST(cmd, 28, 3) #define BT_FEAT_TEST(feat, page, octet, bit) (feat[page][octet] & BIT(bit)) #define BT_FEAT_BREDR(feat) !BT_FEAT_TEST(feat, 0, 4, 5) #define BT_FEAT_LE(feat) BT_FEAT_TEST(feat, 0, 4, 6) #define BT_FEAT_EXT_FEATURES(feat) BT_FEAT_TEST(feat, 0, 7, 7) #define BT_FEAT_HOST_SSP(feat) BT_FEAT_TEST(feat, 1, 0, 0) #define BT_FEAT_SC(feat) BT_FEAT_TEST(feat, 2, 1, 0) #define BT_FEAT_LMP_ESCO_CAPABLE(feat) BT_FEAT_TEST(feat, 0, 3, 7) #define BT_FEAT_HV2_PKT(feat) BT_FEAT_TEST(feat, 0, 1, 4) #define BT_FEAT_HV3_PKT(feat) BT_FEAT_TEST(feat, 0, 1, 5) #define BT_FEAT_EV4_PKT(feat) BT_FEAT_TEST(feat, 0, 4, 0) #define BT_FEAT_EV5_PKT(feat) BT_FEAT_TEST(feat, 0, 4, 1) #define BT_FEAT_2EV3_PKT(feat) BT_FEAT_TEST(feat, 0, 5, 5) #define BT_FEAT_3EV3_PKT(feat) BT_FEAT_TEST(feat, 0, 5, 6) #define BT_FEAT_3SLOT_PKT(feat) BT_FEAT_TEST(feat, 0, 5, 7) /* LE features */ #define BT_LE_FEAT_BIT_ENC 0 #define BT_LE_FEAT_BIT_CONN_PARAM_REQ 1 #define BT_LE_FEAT_BIT_EXT_REJ_IND 2 #define BT_LE_FEAT_BIT_SLAVE_FEAT_REQ 3 #define BT_LE_FEAT_BIT_PING 4 #define BT_LE_FEAT_BIT_DLE 5 #define BT_LE_FEAT_BIT_PRIVACY 6 #define BT_LE_FEAT_BIT_EXT_SCAN 7 #define BT_LE_FEAT_BIT_PHY_2M 8 #define BT_LE_FEAT_BIT_SMI_TX 9 #define BT_LE_FEAT_BIT_SMI_RX 10 #define BT_LE_FEAT_BIT_PHY_CODED 11 #define BT_LE_FEAT_BIT_EXT_ADV 12 #define BT_LE_FEAT_BIT_PER_ADV 13 #define BT_LE_FEAT_BIT_CHAN_SEL_ALGO_2 14 #define BT_LE_FEAT_BIT_PWR_CLASS_1 15 #define BT_LE_FEAT_BIT_MIN_USED_CHAN_PROC 16 #define BT_LE_FEAT_BIT_CONN_CTE_REQ 17 #define BT_LE_FEAT_BIT_CONN_CTE_RESP 18 #define BT_LE_FEAT_BIT_CONNECTIONLESS_CTE_TX 19 #define BT_LE_FEAT_BIT_CONNECTIONLESS_CTE_RX 20 #define BT_LE_FEAT_BIT_ANT_SWITCH_TX_AOD 21 #define BT_LE_FEAT_BIT_ANT_SWITCH_RX_AOA 22 #define BT_LE_FEAT_BIT_RX_CTE 23 #define BT_LE_FEAT_BIT_PERIODIC_SYNC_XFER_SEND 24 #define BT_LE_FEAT_BIT_PERIODIC_SYNC_XFER_RECV 25 #define BT_LE_FEAT_BIT_SCA_UPDATE 26 #define BT_LE_FEAT_BIT_REMOTE_PUB_KEY_VALIDATE 27 #define BT_LE_FEAT_BIT_CIS_MASTER 28 #define BT_LE_FEAT_BIT_CIS_SLAVE 29 #define BT_LE_FEAT_BIT_ISO_BROADCASTER 30 #define BT_LE_FEAT_BIT_SYNC_RECEIVER 31 #define BT_LE_FEAT_BIT_ISO_CHANNELS 32 #define BT_LE_FEAT_BIT_PWR_CTRL_REQ 33 #define BT_LE_FEAT_BIT_PWR_CHG_IND 34 #define BT_LE_FEAT_BIT_PATH_LOSS_MONITOR 35 #define BT_LE_FEAT_TEST(feat, n) (feat[(n) >> 3] & \ BIT((n) & 7)) #define BT_FEAT_LE_ENCR(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_ENC) #define BT_FEAT_LE_CONN_PARAM_REQ_PROC(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_CONN_PARAM_REQ) #define BT_FEAT_LE_SLAVE_FEATURE_XCHG(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_SLAVE_FEAT_REQ) #define BT_FEAT_LE_DLE(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_DLE) #define BT_FEAT_LE_PHY_2M(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_PHY_2M) #define BT_FEAT_LE_PHY_CODED(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_PHY_CODED) #define BT_FEAT_LE_PRIVACY(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_PRIVACY) #define BT_FEAT_LE_EXT_ADV(feat) BT_LE_FEAT_TEST(feat, \ BT_LE_FEAT_BIT_EXT_ADV) /* LE States */ #define BT_LE_STATES_SLAVE_CONN_ADV(states) (states & 0x0000004000000000) /* Bonding/authentication types */ #define BT_HCI_NO_BONDING 0x00 #define BT_HCI_NO_BONDING_MITM 0x01 #define BT_HCI_DEDICATED_BONDING 0x02 #define BT_HCI_DEDICATED_BONDING_MITM 0x03 #define BT_HCI_GENERAL_BONDING 0x04 #define BT_HCI_GENERAL_BONDING_MITM 0x05 /* * MITM protection is enabled in SSP authentication requirements octet when * LSB bit is set. */ #define BT_MITM 0x01 /* I/O capabilities */ #define BT_IO_DISPLAY_ONLY 0x00 #define BT_IO_DISPLAY_YESNO 0x01 #define BT_IO_KEYBOARD_ONLY 0x02 #define BT_IO_NO_INPUT_OUTPUT 0x03 /* SCO packet types */ #define HCI_PKT_TYPE_HV1 0x0020 #define HCI_PKT_TYPE_HV2 0x0040 #define HCI_PKT_TYPE_HV3 0x0080 /* eSCO packet types */ #define HCI_PKT_TYPE_ESCO_HV1 0x0001 #define HCI_PKT_TYPE_ESCO_HV2 0x0002 #define HCI_PKT_TYPE_ESCO_HV3 0x0004 #define HCI_PKT_TYPE_ESCO_EV3 0x0008 #define HCI_PKT_TYPE_ESCO_EV4 0x0010 #define HCI_PKT_TYPE_ESCO_EV5 0x0020 #define HCI_PKT_TYPE_ESCO_2EV3 0x0040 #define HCI_PKT_TYPE_ESCO_3EV3 0x0080 #define HCI_PKT_TYPE_ESCO_2EV5 0x0100 #define HCI_PKT_TYPE_ESCO_3EV5 0x0200 #define ESCO_PKT_MASK (HCI_PKT_TYPE_ESCO_HV1 | \ HCI_PKT_TYPE_ESCO_HV2 | \ HCI_PKT_TYPE_ESCO_HV3) #define SCO_PKT_MASK (HCI_PKT_TYPE_HV1 | \ HCI_PKT_TYPE_HV2 | \ HCI_PKT_TYPE_HV3) #define EDR_ESCO_PKT_MASK (HCI_PKT_TYPE_ESCO_2EV3 | \ HCI_PKT_TYPE_ESCO_3EV3 | \ HCI_PKT_TYPE_ESCO_2EV5 | \ HCI_PKT_TYPE_ESCO_3EV5) /* HCI BR/EDR link types */ #define BT_HCI_SCO 0x00 #define BT_HCI_ACL 0x01 #define BT_HCI_ESCO 0x02 /* OpCode Group Fields */ #define BT_OGF_LINK_CTRL 0x01 #define BT_OGF_BASEBAND 0x03 #define BT_OGF_INFO 0x04 #define BT_OGF_STATUS 0x05 #define BT_OGF_LE 0x08 #define BT_OGF_VS 0x3f /* Construct OpCode from OGF and OCF */ #define BT_OP(ogf, ocf) ((ocf) | ((ogf) << 10)) /* Invalid opcode */ #define BT_OP_NOP 0x0000 /* Obtain OGF from OpCode */ #define BT_OGF(opcode) (((opcode) >> 10) & BIT_MASK(6)) /* Obtain OCF from OpCode */ #define BT_OCF(opcode) ((opcode) & BIT_MASK(10)) #define BT_HCI_OP_INQUIRY BT_OP(BT_OGF_LINK_CTRL, 0x0001) struct bt_hci_op_inquiry { u8_t lap[3]; u8_t length; u8_t num_rsp; } __packed; #define BT_HCI_OP_INQUIRY_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x0002) #define BT_HCI_OP_CONNECT BT_OP(BT_OGF_LINK_CTRL, 0x0005) struct bt_hci_cp_connect { bt_addr_t bdaddr; u16_t packet_type; u8_t pscan_rep_mode; u8_t reserved; u16_t clock_offset; u8_t allow_role_switch; } __packed; #define BT_HCI_OP_DISCONNECT BT_OP(BT_OGF_LINK_CTRL, 0x0006) struct bt_hci_cp_disconnect { u16_t handle; u8_t reason; } __packed; #define BT_HCI_OP_CONNECT_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x0008) struct bt_hci_cp_connect_cancel { bt_addr_t bdaddr; } __packed; struct bt_hci_rp_connect_cancel { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_ACCEPT_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x0009) struct bt_hci_cp_accept_conn_req { bt_addr_t bdaddr; u8_t role; } __packed; #define BT_HCI_OP_SETUP_SYNC_CONN BT_OP(BT_OGF_LINK_CTRL, 0x0028) struct bt_hci_cp_setup_sync_conn { u16_t handle; bt_u32_t tx_bandwidth; bt_u32_t rx_bandwidth; u16_t max_latency; u16_t content_format; u8_t retrans_effort; u16_t pkt_type; } __packed; #define BT_HCI_OP_ACCEPT_SYNC_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x0029) struct bt_hci_cp_accept_sync_conn_req { bt_addr_t bdaddr; bt_u32_t tx_bandwidth; bt_u32_t rx_bandwidth; u16_t max_latency; u16_t content_format; u8_t retrans_effort; u16_t pkt_type; } __packed; #define BT_HCI_OP_REJECT_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x000a) struct bt_hci_cp_reject_conn_req { bt_addr_t bdaddr; u8_t reason; } __packed; #define BT_HCI_OP_LINK_KEY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000b) struct bt_hci_cp_link_key_reply { bt_addr_t bdaddr; u8_t link_key[16]; } __packed; #define BT_HCI_OP_LINK_KEY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000c) struct bt_hci_cp_link_key_neg_reply { bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_PIN_CODE_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000d) struct bt_hci_cp_pin_code_reply { bt_addr_t bdaddr; u8_t pin_len; u8_t pin_code[16]; } __packed; struct bt_hci_rp_pin_code_reply { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_PIN_CODE_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000e) struct bt_hci_cp_pin_code_neg_reply { bt_addr_t bdaddr; } __packed; struct bt_hci_rp_pin_code_neg_reply { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_AUTH_REQUESTED BT_OP(BT_OGF_LINK_CTRL, 0x0011) struct bt_hci_cp_auth_requested { u16_t handle; } __packed; #define BT_HCI_OP_SET_CONN_ENCRYPT BT_OP(BT_OGF_LINK_CTRL, 0x0013) struct bt_hci_cp_set_conn_encrypt { u16_t handle; u8_t encrypt; } __packed; #define BT_HCI_OP_REMOTE_NAME_REQUEST BT_OP(BT_OGF_LINK_CTRL, 0x0019) struct bt_hci_cp_remote_name_request { bt_addr_t bdaddr; u8_t pscan_rep_mode; u8_t reserved; u16_t clock_offset; } __packed; #define BT_HCI_OP_REMOTE_NAME_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x001a) struct bt_hci_cp_remote_name_cancel { bt_addr_t bdaddr; } __packed; struct bt_hci_rp_remote_name_cancel { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_READ_REMOTE_FEATURES BT_OP(BT_OGF_LINK_CTRL, 0x001b) struct bt_hci_cp_read_remote_features { u16_t handle; } __packed; #define BT_HCI_OP_READ_REMOTE_EXT_FEATURES BT_OP(BT_OGF_LINK_CTRL, 0x001c) struct bt_hci_cp_read_remote_ext_features { u16_t handle; u8_t page; } __packed; #define BT_HCI_OP_READ_REMOTE_VERSION_INFO BT_OP(BT_OGF_LINK_CTRL, 0x001d) struct bt_hci_cp_read_remote_version_info { u16_t handle; } __packed; #define BT_HCI_OP_IO_CAPABILITY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002b) struct bt_hci_cp_io_capability_reply { bt_addr_t bdaddr; u8_t capability; u8_t oob_data; u8_t authentication; } __packed; #define BT_HCI_OP_USER_CONFIRM_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002c) #define BT_HCI_OP_USER_CONFIRM_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002d) struct bt_hci_cp_user_confirm_reply { bt_addr_t bdaddr; } __packed; struct bt_hci_rp_user_confirm_reply { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_USER_PASSKEY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002e) struct bt_hci_cp_user_passkey_reply { bt_addr_t bdaddr; bt_u32_t passkey; } __packed; #define BT_HCI_OP_USER_PASSKEY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002f) struct bt_hci_cp_user_passkey_neg_reply { bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_IO_CAPABILITY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x0034) struct bt_hci_cp_io_capability_neg_reply { bt_addr_t bdaddr; u8_t reason; } __packed; #define BT_HCI_OP_SET_EVENT_MASK BT_OP(BT_OGF_BASEBAND, 0x0001) struct bt_hci_cp_set_event_mask { u8_t events[8]; } __packed; #define BT_HCI_OP_RESET BT_OP(BT_OGF_BASEBAND, 0x0003) #define BT_HCI_OP_WRITE_LOCAL_NAME BT_OP(BT_OGF_BASEBAND, 0x0013) struct bt_hci_write_local_name { u8_t local_name[248]; } __packed; #define BT_HCI_OP_WRITE_PAGE_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x0018) #define BT_HCI_OP_WRITE_SCAN_ENABLE BT_OP(BT_OGF_BASEBAND, 0x001a) #define BT_BREDR_SCAN_DISABLED 0x00 #define BT_BREDR_SCAN_INQUIRY 0x01 #define BT_BREDR_SCAN_PAGE 0x02 #define BT_TX_POWER_LEVEL_CURRENT 0x00 #define BT_TX_POWER_LEVEL_MAX 0x01 #define BT_HCI_OP_READ_TX_POWER_LEVEL BT_OP(BT_OGF_BASEBAND, 0x002d) struct bt_hci_cp_read_tx_power_level { u16_t handle; u8_t type; } __packed; struct bt_hci_rp_read_tx_power_level { u8_t status; u16_t handle; s8_t tx_power_level; } __packed; #define BT_HCI_CTL_TO_HOST_FLOW_DISABLE 0x00 #define BT_HCI_CTL_TO_HOST_FLOW_ENABLE 0x01 #define BT_HCI_OP_SET_CTL_TO_HOST_FLOW BT_OP(BT_OGF_BASEBAND, 0x0031) struct bt_hci_cp_set_ctl_to_host_flow { u8_t flow_enable; } __packed; #define BT_HCI_OP_HOST_BUFFER_SIZE BT_OP(BT_OGF_BASEBAND, 0x0033) struct bt_hci_cp_host_buffer_size { u16_t acl_mtu; u8_t sco_mtu; u16_t acl_pkts; u16_t sco_pkts; } __packed; struct bt_hci_handle_count { u16_t handle; u16_t count; } __packed; #define BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS BT_OP(BT_OGF_BASEBAND, 0x0035) struct bt_hci_cp_host_num_completed_packets { u8_t num_handles; struct bt_hci_handle_count h[0]; } __packed; #define BT_HCI_OP_WRITE_INQUIRY_MODE BT_OP(BT_OGF_BASEBAND, 0x0045) struct bt_hci_cp_write_inquiry_mode { u8_t mode; } __packed; #define BT_HCI_OP_WRITE_SSP_MODE BT_OP(BT_OGF_BASEBAND, 0x0056) struct bt_hci_cp_write_ssp_mode { u8_t mode; } __packed; #define BT_HCI_OP_SET_EVENT_MASK_PAGE_2 BT_OP(BT_OGF_BASEBAND, 0x0063) struct bt_hci_cp_set_event_mask_page_2 { u8_t events_page_2[8]; } __packed; #define BT_HCI_OP_LE_WRITE_LE_HOST_SUPP BT_OP(BT_OGF_BASEBAND, 0x006d) struct bt_hci_cp_write_le_host_supp { u8_t le; u8_t simul; } __packed; #define BT_HCI_OP_WRITE_SC_HOST_SUPP BT_OP(BT_OGF_BASEBAND, 0x007a) struct bt_hci_cp_write_sc_host_supp { u8_t sc_support; } __packed; #define BT_HCI_OP_READ_AUTH_PAYLOAD_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x007b) struct bt_hci_cp_read_auth_payload_timeout { u16_t handle; } __packed; struct bt_hci_rp_read_auth_payload_timeout { u8_t status; u16_t handle; u16_t auth_payload_timeout; } __packed; #define BT_HCI_OP_WRITE_AUTH_PAYLOAD_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x007c) struct bt_hci_cp_write_auth_payload_timeout { u16_t handle; u16_t auth_payload_timeout; } __packed; struct bt_hci_rp_write_auth_payload_timeout { u8_t status; u16_t handle; } __packed; /* HCI version from Assigned Numbers */ #define BT_HCI_VERSION_1_0B 0 #define BT_HCI_VERSION_1_1 1 #define BT_HCI_VERSION_1_2 2 #define BT_HCI_VERSION_2_0 3 #define BT_HCI_VERSION_2_1 4 #define BT_HCI_VERSION_3_0 5 #define BT_HCI_VERSION_4_0 6 #define BT_HCI_VERSION_4_1 7 #define BT_HCI_VERSION_4_2 8 #define BT_HCI_VERSION_5_0 9 #define BT_HCI_VERSION_5_1 10 #define BT_HCI_VERSION_5_2 11 #define BT_HCI_OP_READ_LOCAL_VERSION_INFO BT_OP(BT_OGF_INFO, 0x0001) struct bt_hci_rp_read_local_version_info { u8_t status; u8_t hci_version; u16_t hci_revision; u8_t lmp_version; u16_t manufacturer; u16_t lmp_subversion; } __packed; #define BT_HCI_OP_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_INFO, 0x0002) struct bt_hci_rp_read_supported_commands { u8_t status; u8_t commands[64]; } __packed; #define BT_HCI_OP_READ_LOCAL_EXT_FEATURES BT_OP(BT_OGF_INFO, 0x0004) struct bt_hci_cp_read_local_ext_features { u8_t page; }; struct bt_hci_rp_read_local_ext_features { u8_t status; u8_t page; u8_t max_page; u8_t ext_features[8]; } __packed; #define BT_HCI_OP_READ_LOCAL_FEATURES BT_OP(BT_OGF_INFO, 0x0003) struct bt_hci_rp_read_local_features { u8_t status; u8_t features[8]; } __packed; #define BT_HCI_OP_READ_BUFFER_SIZE BT_OP(BT_OGF_INFO, 0x0005) struct bt_hci_rp_read_buffer_size { u8_t status; u16_t acl_max_len; u8_t sco_max_len; u16_t acl_max_num; u16_t sco_max_num; } __packed; #define BT_HCI_OP_READ_BD_ADDR BT_OP(BT_OGF_INFO, 0x0009) struct bt_hci_rp_read_bd_addr { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_READ_RSSI BT_OP(BT_OGF_STATUS, 0x0005) struct bt_hci_cp_read_rssi { u16_t handle; } __packed; struct bt_hci_rp_read_rssi { u8_t status; u16_t handle; s8_t rssi; } __packed; #define BT_HCI_ENCRYPTION_KEY_SIZE_MIN 7 #define BT_HCI_ENCRYPTION_KEY_SIZE_MAX 16 #define BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE BT_OP(BT_OGF_STATUS, 0x0008) struct bt_hci_cp_read_encryption_key_size { u16_t handle; } __packed; struct bt_hci_rp_read_encryption_key_size { u8_t status; u16_t handle; u8_t key_size; } __packed; /* BLE */ #define BT_HCI_OP_LE_SET_EVENT_MASK BT_OP(BT_OGF_LE, 0x0001) struct bt_hci_cp_le_set_event_mask { u8_t events[8]; } __packed; #define BT_HCI_OP_LE_READ_BUFFER_SIZE BT_OP(BT_OGF_LE, 0x0002) struct bt_hci_rp_le_read_buffer_size { u8_t status; u16_t le_max_len; u8_t le_max_num; } __packed; #define BT_HCI_OP_LE_READ_LOCAL_FEATURES BT_OP(BT_OGF_LE, 0x0003) struct bt_hci_rp_le_read_local_features { u8_t status; u8_t features[8]; } __packed; #define BT_HCI_OP_LE_SET_RANDOM_ADDRESS BT_OP(BT_OGF_LE, 0x0005) struct bt_hci_cp_le_set_random_address { bt_addr_t bdaddr; } __packed; /* LE Advertising Types (LE Advertising Parameters Set)*/ #define BT_LE_ADV_IND (__DEPRECATED_MACRO 0x00) #define BT_LE_ADV_DIRECT_IND (__DEPRECATED_MACRO 0x01) #define BT_LE_ADV_SCAN_IND (__DEPRECATED_MACRO 0x02) #define BT_LE_ADV_NONCONN_IND (__DEPRECATED_MACRO 0x03) #define BT_LE_ADV_DIRECT_IND_LOW_DUTY (__DEPRECATED_MACRO 0x04) /* LE Advertising PDU Types. */ #define BT_LE_ADV_SCAN_RSP (__DEPRECATED_MACRO 0x04) #define BT_HCI_ADV_IND 0x00 #define BT_HCI_ADV_DIRECT_IND 0x01 #define BT_HCI_ADV_SCAN_IND 0x02 #define BT_HCI_ADV_NONCONN_IND 0x03 #define BT_HCI_ADV_DIRECT_IND_LOW_DUTY 0x04 #define BT_HCI_ADV_SCAN_RSP 0x04 #define BT_LE_ADV_FP_NO_WHITELIST 0x00 #define BT_LE_ADV_FP_WHITELIST_SCAN_REQ 0x01 #define BT_LE_ADV_FP_WHITELIST_CONN_IND 0x02 #define BT_LE_ADV_FP_WHITELIST_BOTH 0x03 #define BT_HCI_OP_LE_SET_ADV_PARAM BT_OP(BT_OGF_LE, 0x0006) struct bt_hci_cp_le_set_adv_param { u16_t min_interval; u16_t max_interval; u8_t type; u8_t own_addr_type; bt_addr_le_t direct_addr; u8_t channel_map; u8_t filter_policy; } __packed; #define BT_HCI_OP_LE_READ_ADV_CHAN_TX_POWER BT_OP(BT_OGF_LE, 0x0007) struct bt_hci_rp_le_read_chan_tx_power { u8_t status; s8_t tx_power_level; } __packed; #define BT_HCI_OP_LE_SET_ADV_DATA BT_OP(BT_OGF_LE, 0x0008) struct bt_hci_cp_le_set_adv_data { u8_t len; u8_t data[31]; } __packed; #define BT_HCI_OP_LE_SET_SCAN_RSP_DATA BT_OP(BT_OGF_LE, 0x0009) struct bt_hci_cp_le_set_scan_rsp_data { u8_t len; u8_t data[31]; } __packed; #define BT_HCI_LE_ADV_DISABLE 0x00 #define BT_HCI_LE_ADV_ENABLE 0x01 #define BT_HCI_OP_LE_SET_ADV_ENABLE BT_OP(BT_OGF_LE, 0x000a) struct bt_hci_cp_le_set_adv_enable { u8_t enable; } __packed; /* Scan types */ #define BT_HCI_OP_LE_SET_SCAN_PARAM BT_OP(BT_OGF_LE, 0x000b) #define BT_HCI_LE_SCAN_PASSIVE 0x00 #define BT_HCI_LE_SCAN_ACTIVE 0x01 #define BT_HCI_LE_SCAN_FP_NO_WHITELIST 0x00 #define BT_HCI_LE_SCAN_FP_USE_WHITELIST 0x01 struct bt_hci_cp_le_set_scan_param { u8_t scan_type; u16_t interval; u16_t window; u8_t addr_type; u8_t filter_policy; } __packed; #define BT_HCI_OP_LE_SET_SCAN_ENABLE BT_OP(BT_OGF_LE, 0x000c) #define BT_HCI_LE_SCAN_DISABLE 0x00 #define BT_HCI_LE_SCAN_ENABLE 0x01 #define BT_HCI_LE_SCAN_FILTER_DUP_DISABLE 0x00 #define BT_HCI_LE_SCAN_FILTER_DUP_ENABLE 0x01 struct bt_hci_cp_le_set_scan_enable { u8_t enable; u8_t filter_dup; } __packed; #define BT_HCI_OP_LE_CREATE_CONN BT_OP(BT_OGF_LE, 0x000d) #define BT_HCI_LE_CREATE_CONN_FP_DIRECT 0x00 #define BT_HCI_LE_CREATE_CONN_FP_WHITELIST 0x01 struct bt_hci_cp_le_create_conn { u16_t scan_interval; u16_t scan_window; u8_t filter_policy; bt_addr_le_t peer_addr; u8_t own_addr_type; u16_t conn_interval_min; u16_t conn_interval_max; u16_t conn_latency; u16_t supervision_timeout; u16_t min_ce_len; u16_t max_ce_len; } __packed; #define BT_HCI_OP_LE_CREATE_CONN_CANCEL BT_OP(BT_OGF_LE, 0x000e) #define BT_HCI_OP_LE_READ_WL_SIZE BT_OP(BT_OGF_LE, 0x000f) struct bt_hci_rp_le_read_wl_size { u8_t status; u8_t wl_size; } __packed; #define BT_HCI_OP_LE_CLEAR_WL BT_OP(BT_OGF_LE, 0x0010) #define BT_HCI_OP_LE_ADD_DEV_TO_WL BT_OP(BT_OGF_LE, 0x0011) struct bt_hci_cp_le_add_dev_to_wl { bt_addr_le_t addr; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_WL BT_OP(BT_OGF_LE, 0x0012) struct bt_hci_cp_le_rem_dev_from_wl { bt_addr_le_t addr; } __packed; #define BT_HCI_OP_LE_CONN_UPDATE BT_OP(BT_OGF_LE, 0x0013) struct hci_cp_le_conn_update { u16_t handle; u16_t conn_interval_min; u16_t conn_interval_max; u16_t conn_latency; u16_t supervision_timeout; u16_t min_ce_len; u16_t max_ce_len; } __packed; #define BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF BT_OP(BT_OGF_LE, 0x0014) struct bt_hci_cp_le_set_host_chan_classif { u8_t ch_map[5]; } __packed; #define BT_HCI_OP_LE_READ_CHAN_MAP BT_OP(BT_OGF_LE, 0x0015) struct bt_hci_cp_le_read_chan_map { u16_t handle; } __packed; struct bt_hci_rp_le_read_chan_map { u8_t status; u16_t handle; u8_t ch_map[5]; } __packed; #define BT_HCI_OP_LE_READ_REMOTE_FEATURES BT_OP(BT_OGF_LE, 0x0016) struct bt_hci_cp_le_read_remote_features { u16_t handle; } __packed; #define BT_HCI_OP_LE_ENCRYPT BT_OP(BT_OGF_LE, 0x0017) struct bt_hci_cp_le_encrypt { u8_t key[16]; u8_t plaintext[16]; } __packed; struct bt_hci_rp_le_encrypt { u8_t status; u8_t enc_data[16]; } __packed; #define BT_HCI_OP_LE_RAND BT_OP(BT_OGF_LE, 0x0018) struct bt_hci_rp_le_rand { u8_t status; u8_t rand[8]; } __packed; #define BT_HCI_OP_LE_START_ENCRYPTION BT_OP(BT_OGF_LE, 0x0019) struct bt_hci_cp_le_start_encryption { u16_t handle; u64_t rand; u16_t ediv; u8_t ltk[16]; } __packed; #define BT_HCI_OP_LE_LTK_REQ_REPLY BT_OP(BT_OGF_LE, 0x001a) struct bt_hci_cp_le_ltk_req_reply { u16_t handle; u8_t ltk[16]; } __packed; struct bt_hci_rp_le_ltk_req_reply { u8_t status; u16_t handle; } __packed; #define BT_HCI_OP_LE_LTK_REQ_NEG_REPLY BT_OP(BT_OGF_LE, 0x001b) struct bt_hci_cp_le_ltk_req_neg_reply { u16_t handle; } __packed; struct bt_hci_rp_le_ltk_req_neg_reply { u8_t status; u16_t handle; } __packed; #define BT_HCI_OP_LE_READ_SUPP_STATES BT_OP(BT_OGF_LE, 0x001c) struct bt_hci_rp_le_read_supp_states { u8_t status; u8_t le_states[8]; } __packed; #define BT_HCI_OP_LE_RX_TEST BT_OP(BT_OGF_LE, 0x001d) struct bt_hci_cp_le_rx_test { u8_t rx_ch; } __packed; #define BT_HCI_OP_LE_TX_TEST BT_OP(BT_OGF_LE, 0x001e) struct bt_hci_cp_le_tx_test { u8_t tx_ch; u8_t test_data_len; u8_t pkt_payload; } __packed; #define BT_HCI_OP_LE_TEST_END BT_OP(BT_OGF_LE, 0x001f) struct bt_hci_rp_le_test_end { u8_t status; u16_t rx_pkt_count; } __packed; #define BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY BT_OP(BT_OGF_LE, 0x0020) struct bt_hci_cp_le_conn_param_req_reply { u16_t handle; u16_t interval_min; u16_t interval_max; u16_t latency; u16_t timeout; u16_t min_ce_len; u16_t max_ce_len; } __packed; struct bt_hci_rp_le_conn_param_req_reply { u8_t status; u16_t handle; } __packed; #define BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY BT_OP(BT_OGF_LE, 0x0021) struct bt_hci_cp_le_conn_param_req_neg_reply { u16_t handle; u8_t reason; } __packed; struct bt_hci_rp_le_conn_param_req_neg_reply { u8_t status; u16_t handle; } __packed; #define BT_HCI_OP_LE_SET_DATA_LEN BT_OP(BT_OGF_LE, 0x0022) struct bt_hci_cp_le_set_data_len { u16_t handle; u16_t tx_octets; u16_t tx_time; } __packed; struct bt_hci_rp_le_set_data_len { u8_t status; u16_t handle; } __packed; #define BT_HCI_OP_LE_READ_DEFAULT_DATA_LEN BT_OP(BT_OGF_LE, 0x0023) struct bt_hci_rp_le_read_default_data_len { u8_t status; u16_t max_tx_octets; u16_t max_tx_time; } __packed; #define BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN BT_OP(BT_OGF_LE, 0x0024) struct bt_hci_cp_le_write_default_data_len { u16_t max_tx_octets; u16_t max_tx_time; } __packed; #define BT_HCI_OP_LE_P256_PUBLIC_KEY BT_OP(BT_OGF_LE, 0x0025) #define BT_HCI_OP_LE_GENERATE_DHKEY BT_OP(BT_OGF_LE, 0x0026) struct bt_hci_cp_le_generate_dhkey { u8_t key[64]; } __packed; #define BT_HCI_OP_LE_ADD_DEV_TO_RL BT_OP(BT_OGF_LE, 0x0027) struct bt_hci_cp_le_add_dev_to_rl { bt_addr_le_t peer_id_addr; u8_t peer_irk[16]; u8_t local_irk[16]; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_RL BT_OP(BT_OGF_LE, 0x0028) struct bt_hci_cp_le_rem_dev_from_rl { bt_addr_le_t peer_id_addr; } __packed; #define BT_HCI_OP_LE_CLEAR_RL BT_OP(BT_OGF_LE, 0x0029) #define BT_HCI_OP_LE_READ_RL_SIZE BT_OP(BT_OGF_LE, 0x002a) struct bt_hci_rp_le_read_rl_size { u8_t status; u8_t rl_size; } __packed; #define BT_HCI_OP_LE_READ_PEER_RPA BT_OP(BT_OGF_LE, 0x002b) struct bt_hci_cp_le_read_peer_rpa { bt_addr_le_t peer_id_addr; } __packed; struct bt_hci_rp_le_read_peer_rpa { u8_t status; bt_addr_t peer_rpa; } __packed; #define BT_HCI_OP_LE_READ_LOCAL_RPA BT_OP(BT_OGF_LE, 0x002c) struct bt_hci_cp_le_read_local_rpa { bt_addr_le_t peer_id_addr; } __packed; struct bt_hci_rp_le_read_local_rpa { u8_t status; bt_addr_t local_rpa; } __packed; #define BT_HCI_ADDR_RES_DISABLE 0x00 #define BT_HCI_ADDR_RES_ENABLE 0x01 #define BT_HCI_OP_LE_SET_ADDR_RES_ENABLE BT_OP(BT_OGF_LE, 0x002d) struct bt_hci_cp_le_set_addr_res_enable { u8_t enable; } __packed; #define BT_HCI_OP_LE_SET_RPA_TIMEOUT BT_OP(BT_OGF_LE, 0x002e) struct bt_hci_cp_le_set_rpa_timeout { u16_t rpa_timeout; } __packed; #define BT_HCI_OP_LE_READ_MAX_DATA_LEN BT_OP(BT_OGF_LE, 0x002f) struct bt_hci_rp_le_read_max_data_len { u8_t status; u16_t max_tx_octets; u16_t max_tx_time; u16_t max_rx_octets; u16_t max_rx_time; } __packed; #define BT_HCI_LE_PHY_1M 0x01 #define BT_HCI_LE_PHY_2M 0x02 #define BT_HCI_LE_PHY_CODED 0x03 #define BT_HCI_OP_LE_READ_PHY BT_OP(BT_OGF_LE, 0x0030) struct bt_hci_cp_le_read_phy { u16_t handle; } __packed; struct bt_hci_rp_le_read_phy { u8_t status; u16_t handle; u8_t tx_phy; u8_t rx_phy; } __packed; #define BT_HCI_LE_PHY_TX_ANY BIT(0) #define BT_HCI_LE_PHY_RX_ANY BIT(1) #define BT_HCI_LE_PHY_PREFER_1M BIT(0) #define BT_HCI_LE_PHY_PREFER_2M BIT(1) #define BT_HCI_LE_PHY_PREFER_CODED BIT(2) #define BT_HCI_OP_LE_SET_DEFAULT_PHY BT_OP(BT_OGF_LE, 0x0031) struct bt_hci_cp_le_set_default_phy { u8_t all_phys; u8_t tx_phys; u8_t rx_phys; } __packed; #define BT_HCI_LE_PHY_CODED_ANY 0x00 #define BT_HCI_LE_PHY_CODED_S2 0x01 #define BT_HCI_LE_PHY_CODED_S8 0x02 #define BT_HCI_OP_LE_SET_PHY BT_OP(BT_OGF_LE, 0x0032) struct bt_hci_cp_le_set_phy { u16_t handle; u8_t all_phys; u8_t tx_phys; u8_t rx_phys; u16_t phy_opts; } __packed; #define BT_HCI_LE_MOD_INDEX_STANDARD 0x00 #define BT_HCI_LE_MOD_INDEX_STABLE 0x01 #define BT_HCI_OP_LE_ENH_RX_TEST BT_OP(BT_OGF_LE, 0x0033) struct bt_hci_cp_le_enh_rx_test { u8_t rx_ch; u8_t phy; u8_t mod_index; } __packed; /* Extends BT_HCI_LE_PHY */ #define BT_HCI_LE_TX_PHY_CODED_S8 0x03 #define BT_HCI_LE_TX_PHY_CODED_S2 0x04 #define BT_HCI_OP_LE_ENH_TX_TEST BT_OP(BT_OGF_LE, 0x0034) struct bt_hci_cp_le_enh_tx_test { u8_t tx_ch; u8_t test_data_len; u8_t pkt_payload; u8_t phy; } __packed; #define BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR BT_OP(BT_OGF_LE, 0x0035) struct bt_hci_cp_le_set_adv_set_random_addr { u8_t handle; bt_addr_t bdaddr; } __packed; #define BT_HCI_LE_ADV_PROP_CONN BIT(0) #define BT_HCI_LE_ADV_PROP_SCAN BIT(1) #define BT_HCI_LE_ADV_PROP_DIRECT BIT(2) #define BT_HCI_LE_ADV_PROP_HI_DC_CONN BIT(3) #define BT_HCI_LE_ADV_PROP_LEGACY BIT(4) #define BT_HCI_LE_ADV_PROP_ANON BIT(5) #define BT_HCI_LE_ADV_PROP_TX_POWER BIT(6) #define BT_HCI_LE_ADV_SCAN_REQ_ENABLE 1 #define BT_HCI_LE_ADV_SCAN_REQ_DISABLE 0 #define BT_HCI_LE_ADV_TX_POWER_NO_PREF 0x7F #define BT_HCI_OP_LE_SET_EXT_ADV_PARAM BT_OP(BT_OGF_LE, 0x0036) struct bt_hci_cp_le_set_ext_adv_param { u8_t handle; u16_t props; u8_t prim_min_interval[3]; u8_t prim_max_interval[3]; u8_t prim_channel_map; u8_t own_addr_type; bt_addr_le_t peer_addr; u8_t filter_policy; s8_t tx_power; u8_t prim_adv_phy; u8_t sec_adv_max_skip; u8_t sec_adv_phy; u8_t sid; u8_t scan_req_notify_enable; } __packed; struct bt_hci_rp_le_set_ext_adv_param { u8_t status; s8_t tx_power; } __packed; #define BT_HCI_LE_EXT_ADV_OP_INTERM_FRAG 0x00 #define BT_HCI_LE_EXT_ADV_OP_FIRST_FRAG 0x01 #define BT_HCI_LE_EXT_ADV_OP_LAST_FRAG 0x02 #define BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA 0x03 #define BT_HCI_LE_EXT_ADV_OP_UNCHANGED_DATA 0x04 #define BT_HCI_LE_EXT_ADV_FRAG_ENABLED 0x00 #define BT_HCI_LE_EXT_ADV_FRAG_DISABLED 0x01 #define BT_HCI_LE_EXT_ADV_FRAG_MAX_LEN 251 #define BT_HCI_OP_LE_SET_EXT_ADV_DATA BT_OP(BT_OGF_LE, 0x0037) struct bt_hci_cp_le_set_ext_adv_data { u8_t handle; u8_t op; u8_t frag_pref; u8_t len; u8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA BT_OP(BT_OGF_LE, 0x0038) struct bt_hci_cp_le_set_ext_scan_rsp_data { u8_t handle; u8_t op; u8_t frag_pref; u8_t len; u8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_EXT_ADV_ENABLE BT_OP(BT_OGF_LE, 0x0039) struct bt_hci_ext_adv_set { u8_t handle; u16_t duration; u8_t max_ext_adv_evts; } __packed; struct bt_hci_cp_le_set_ext_adv_enable { u8_t enable; u8_t set_num; struct bt_hci_ext_adv_set s[0]; } __packed; #define BT_HCI_OP_LE_READ_MAX_ADV_DATA_LEN BT_OP(BT_OGF_LE, 0x003a) struct bt_hci_rp_le_read_max_adv_data_len { u8_t status; u16_t max_adv_data_len; } __packed; #define BT_HCI_OP_LE_READ_NUM_ADV_SETS BT_OP(BT_OGF_LE, 0x003b) struct bt_hci_rp_le_read_num_adv_sets { u8_t status; u8_t num_sets; } __packed; #define BT_HCI_OP_LE_REMOVE_ADV_SET BT_OP(BT_OGF_LE, 0x003c) struct bt_hci_cp_le_remove_adv_set { u8_t handle; } __packed; #define BT_HCI_OP_CLEAR_ADV_SETS BT_OP(BT_OGF_LE, 0x003d) #define BT_HCI_OP_LE_SET_PER_ADV_PARAM BT_OP(BT_OGF_LE, 0x003e) struct bt_hci_cp_le_set_per_adv_param { u8_t handle; u16_t min_interval; u16_t max_interval; u16_t props; } __packed; #define BT_HCI_OP_LE_SET_PER_ADV_DATA BT_OP(BT_OGF_LE, 0x003f) struct bt_hci_cp_le_set_per_adv_data { u8_t handle; u8_t op; u8_t len; u8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_PER_ADV_ENABLE BT_OP(BT_OGF_LE, 0x0040) struct bt_hci_cp_le_set_per_adv_enable { u8_t enable; u8_t handle; } __packed; #define BT_HCI_OP_LE_SET_EXT_SCAN_PARAM BT_OP(BT_OGF_LE, 0x0041) struct bt_hci_ext_scan_phy { u8_t type; u16_t interval; u16_t window; } __packed; #define BT_HCI_LE_EXT_SCAN_PHY_1M BIT(0) #define BT_HCI_LE_EXT_SCAN_PHY_2M BIT(1) #define BT_HCI_LE_EXT_SCAN_PHY_CODED BIT(2) struct bt_hci_cp_le_set_ext_scan_param { u8_t own_addr_type; u8_t filter_policy; u8_t phys; struct bt_hci_ext_scan_phy p[0]; } __packed; /* Extends BT_HCI_LE_SCAN_FILTER_DUP */ #define BT_HCI_LE_EXT_SCAN_FILTER_DUP_ENABLE_RESET 0x02 #define BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE BT_OP(BT_OGF_LE, 0x0042) struct bt_hci_cp_le_set_ext_scan_enable { u8_t enable; u8_t filter_dup; u16_t duration; u16_t period; } __packed; #define BT_HCI_OP_LE_EXT_CREATE_CONN BT_OP(BT_OGF_LE, 0x0043) struct bt_hci_ext_conn_phy { u16_t scan_interval; u16_t scan_window; u16_t conn_interval_min; u16_t conn_interval_max; u16_t conn_latency; u16_t supervision_timeout; u16_t min_ce_len; u16_t max_ce_len; } __packed; struct bt_hci_cp_le_ext_create_conn { u8_t filter_policy; u8_t own_addr_type; bt_addr_le_t peer_addr; u8_t phys; struct bt_hci_ext_conn_phy p[0]; } __packed; #define BT_HCI_OP_LE_PER_ADV_CREATE_SYNC BT_OP(BT_OGF_LE, 0x0044) struct bt_hci_cp_le_per_adv_create_sync { u8_t filter_policy; u8_t sid; bt_addr_le_t addr; u16_t skip; u16_t sync_timeout; u8_t unused; } __packed; #define BT_HCI_OP_LE_PER_ADV_CREATE_SYNC_CANCEL BT_OP(BT_OGF_LE, 0x0045) #define BT_HCI_OP_LE_PER_ADV_TERMINATE_SYNC BT_OP(BT_OGF_LE, 0x0046) struct bt_hci_cp_le_per_adv_terminate_sync { u16_t handle; } __packed; #define BT_HCI_OP_LE_ADD_DEV_TO_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0047) struct bt_hci_cp_le_add_dev_to_per_adv_list { bt_addr_le_t addr; u8_t sid; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0048) struct bt_hci_cp_le_rem_dev_from_per_adv_list { bt_addr_le_t addr; u8_t sid; } __packed; #define BT_HCI_OP_LE_CLEAR_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0049) #define BT_HCI_OP_LE_READ_PER_ADV_LIST_SIZE BT_OP(BT_OGF_LE, 0x004a) struct bt_hci_rp_le_read_per_adv_list_size { u8_t status; u8_t list_size; } __packed; #define BT_HCI_OP_LE_READ_TX_POWER BT_OP(BT_OGF_LE, 0x004b) struct bt_hci_rp_le_read_tx_power { u8_t status; s8_t min_tx_power; s8_t max_tx_power; } __packed; #define BT_HCI_OP_LE_READ_RF_PATH_COMP BT_OP(BT_OGF_LE, 0x004c) struct bt_hci_rp_le_read_rf_path_comp { u8_t status; s16_t tx_path_comp; s16_t rx_path_comp; } __packed; #define BT_HCI_OP_LE_WRITE_RF_PATH_COMP BT_OP(BT_OGF_LE, 0x004d) struct bt_hci_cp_le_write_rf_path_comp { s16_t tx_path_comp; s16_t rx_path_comp; } __packed; #define BT_HCI_LE_PRIVACY_MODE_NETWORK 0x00 #define BT_HCI_LE_PRIVACY_MODE_DEVICE 0x01 #define BT_HCI_OP_LE_SET_PRIVACY_MODE BT_OP(BT_OGF_LE, 0x004e) struct bt_hci_cp_le_set_privacy_mode { bt_addr_le_t id_addr; u8_t mode; } __packed; /* Event definitions */ #define BT_HCI_EVT_UNKNOWN 0x00 #define BT_HCI_EVT_VENDOR 0xff #define BT_HCI_EVT_INQUIRY_COMPLETE 0x01 struct bt_hci_evt_inquiry_complete { u8_t status; } __packed; #define BT_HCI_EVT_CONN_COMPLETE 0x03 struct bt_hci_evt_conn_complete { u8_t status; u16_t handle; bt_addr_t bdaddr; u8_t link_type; u8_t encr_enabled; } __packed; #define BT_HCI_EVT_CONN_REQUEST 0x04 struct bt_hci_evt_conn_request { bt_addr_t bdaddr; u8_t dev_class[3]; u8_t link_type; } __packed; #define BT_HCI_EVT_DISCONN_COMPLETE 0x05 struct bt_hci_evt_disconn_complete { u8_t status; u16_t handle; u8_t reason; } __packed; #define BT_HCI_EVT_AUTH_COMPLETE 0x06 struct bt_hci_evt_auth_complete { u8_t status; u16_t handle; } __packed; #define BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE 0x07 struct bt_hci_evt_remote_name_req_complete { u8_t status; bt_addr_t bdaddr; u8_t name[248]; } __packed; #define BT_HCI_EVT_ENCRYPT_CHANGE 0x08 struct bt_hci_evt_encrypt_change { u8_t status; u16_t handle; u8_t encrypt; } __packed; #define BT_HCI_EVT_REMOTE_FEATURES 0x0b struct bt_hci_evt_remote_features { u8_t status; u16_t handle; u8_t features[8]; } __packed; #define BT_HCI_EVT_REMOTE_VERSION_INFO 0x0c struct bt_hci_evt_remote_version_info { u8_t status; u16_t handle; u8_t version; u16_t manufacturer; u16_t subversion; } __packed; #define BT_HCI_EVT_CMD_COMPLETE 0x0e struct bt_hci_evt_cmd_complete { u8_t ncmd; u16_t opcode; } __packed; struct bt_hci_evt_cc_status { u8_t status; } __packed; #define BT_HCI_EVT_CMD_STATUS 0x0f struct bt_hci_evt_cmd_status { u8_t status; u8_t ncmd; u16_t opcode; } __packed; #define BT_HCI_EVT_ROLE_CHANGE 0x12 struct bt_hci_evt_role_change { u8_t status; bt_addr_t bdaddr; u8_t role; } __packed; #define BT_HCI_EVT_NUM_COMPLETED_PACKETS 0x13 struct bt_hci_evt_num_completed_packets { u8_t num_handles; struct bt_hci_handle_count h[0]; } __packed; #define BT_HCI_EVT_PIN_CODE_REQ 0x16 struct bt_hci_evt_pin_code_req { bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_LINK_KEY_REQ 0x17 struct bt_hci_evt_link_key_req { bt_addr_t bdaddr; } __packed; /* Link Key types */ #define BT_LK_COMBINATION 0x00 #define BT_LK_LOCAL_UNIT 0x01 #define BT_LK_REMOTE_UNIT 0x02 #define BT_LK_DEBUG_COMBINATION 0x03 #define BT_LK_UNAUTH_COMBINATION_P192 0x04 #define BT_LK_AUTH_COMBINATION_P192 0x05 #define BT_LK_CHANGED_COMBINATION 0x06 #define BT_LK_UNAUTH_COMBINATION_P256 0x07 #define BT_LK_AUTH_COMBINATION_P256 0x08 #define BT_HCI_EVT_LINK_KEY_NOTIFY 0x18 struct bt_hci_evt_link_key_notify { bt_addr_t bdaddr; u8_t link_key[16]; u8_t key_type; } __packed; /* Overflow link types */ #define BT_OVERFLOW_LINK_SYNCH 0x00 #define BT_OVERFLOW_LINK_ACL 0x01 #define BT_HCI_EVT_DATA_BUF_OVERFLOW 0x1a struct bt_hci_evt_data_buf_overflow { u8_t link_type; } __packed; #define BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI 0x22 struct bt_hci_evt_inquiry_result_with_rssi { bt_addr_t addr; u8_t pscan_rep_mode; u8_t reserved; u8_t cod[3]; u16_t clock_offset; s8_t rssi; } __packed; #define BT_HCI_EVT_REMOTE_EXT_FEATURES 0x23 struct bt_hci_evt_remote_ext_features { u8_t status; u16_t handle; u8_t page; u8_t max_page; u8_t features[8]; } __packed; #define BT_HCI_EVT_SYNC_CONN_COMPLETE 0x2c struct bt_hci_evt_sync_conn_complete { u8_t status; u16_t handle; bt_addr_t bdaddr; u8_t link_type; u8_t tx_interval; u8_t retansmission_window; u16_t rx_pkt_length; u16_t tx_pkt_length; u8_t air_mode; } __packed; #define BT_HCI_EVT_EXTENDED_INQUIRY_RESULT 0x2f struct bt_hci_evt_extended_inquiry_result { u8_t num_reports; bt_addr_t addr; u8_t pscan_rep_mode; u8_t reserved; u8_t cod[3]; u16_t clock_offset; s8_t rssi; u8_t eir[240]; } __packed; #define BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE 0x30 struct bt_hci_evt_encrypt_key_refresh_complete { u8_t status; u16_t handle; } __packed; #define BT_HCI_EVT_IO_CAPA_REQ 0x31 struct bt_hci_evt_io_capa_req { bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_IO_CAPA_RESP 0x32 struct bt_hci_evt_io_capa_resp { bt_addr_t bdaddr; u8_t capability; u8_t oob_data; u8_t authentication; } __packed; #define BT_HCI_EVT_USER_CONFIRM_REQ 0x33 struct bt_hci_evt_user_confirm_req { bt_addr_t bdaddr; bt_u32_t passkey; } __packed; #define BT_HCI_EVT_USER_PASSKEY_REQ 0x34 struct bt_hci_evt_user_passkey_req { bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_SSP_COMPLETE 0x36 struct bt_hci_evt_ssp_complete { u8_t status; bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_USER_PASSKEY_NOTIFY 0x3b struct bt_hci_evt_user_passkey_notify { bt_addr_t bdaddr; bt_u32_t passkey; } __packed; #define BT_HCI_EVT_LE_META_EVENT 0x3e struct bt_hci_evt_le_meta_event { u8_t subevent; } __packed; #define BT_HCI_EVT_AUTH_PAYLOAD_TIMEOUT_EXP 0x57 struct bt_hci_evt_auth_payload_timeout_exp { u16_t handle; } __packed; #define BT_HCI_ROLE_MASTER 0x00 #define BT_HCI_ROLE_SLAVE 0x01 #define BT_HCI_EVT_LE_CONN_COMPLETE 0x01 struct bt_hci_evt_le_conn_complete { u8_t status; u16_t handle; u8_t role; bt_addr_le_t peer_addr; u16_t interval; u16_t latency; u16_t supv_timeout; u8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_ADVERTISING_REPORT 0x02 struct bt_hci_evt_le_advertising_info { u8_t evt_type; bt_addr_le_t addr; u8_t length; u8_t data[0]; } __packed; struct bt_hci_evt_le_advertising_report { u8_t num_reports; struct bt_hci_evt_le_advertising_info adv_info[0]; } __packed; #define BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE 0x03 struct bt_hci_evt_le_conn_update_complete { u8_t status; u16_t handle; u16_t interval; u16_t latency; u16_t supv_timeout; } __packed; #define BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE 0x04 struct bt_hci_evt_le_remote_feat_complete { u8_t status; u16_t handle; u8_t features[8]; } __packed; #define BT_HCI_EVT_LE_LTK_REQUEST 0x05 struct bt_hci_evt_le_ltk_request { u16_t handle; u64_t rand; u16_t ediv; } __packed; #define BT_HCI_EVT_LE_CONN_PARAM_REQ 0x06 struct bt_hci_evt_le_conn_param_req { u16_t handle; u16_t interval_min; u16_t interval_max; u16_t latency; u16_t timeout; } __packed; #define BT_HCI_EVT_LE_DATA_LEN_CHANGE 0x07 struct bt_hci_evt_le_data_len_change { u16_t handle; u16_t max_tx_octets; u16_t max_tx_time; u16_t max_rx_octets; u16_t max_rx_time; } __packed; #define BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE 0x08 struct bt_hci_evt_le_p256_public_key_complete { u8_t status; u8_t key[64]; } __packed; #define BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE 0x09 struct bt_hci_evt_le_generate_dhkey_complete { u8_t status; u8_t dhkey[32]; } __packed; #define BT_HCI_EVT_LE_ENH_CONN_COMPLETE 0x0a struct bt_hci_evt_le_enh_conn_complete { u8_t status; u16_t handle; u8_t role; bt_addr_le_t peer_addr; bt_addr_t local_rpa; bt_addr_t peer_rpa; u16_t interval; u16_t latency; u16_t supv_timeout; u8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_DIRECT_ADV_REPORT 0x0b struct bt_hci_evt_le_direct_adv_info { u8_t evt_type; bt_addr_le_t addr; bt_addr_le_t dir_addr; s8_t rssi; } __packed; struct bt_hci_evt_le_direct_adv_report { u8_t num_reports; struct bt_hci_evt_le_direct_adv_info direct_adv_info[0]; } __packed; #define BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE 0x0c struct bt_hci_evt_le_phy_update_complete { u8_t status; u16_t handle; u8_t tx_phy; u8_t rx_phy; } __packed; #define BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT 0x0d #define BT_HCI_LE_ADV_EVT_TYPE_CONN BIT(0) #define BT_HCI_LE_ADV_EVT_TYPE_SCAN BIT(1) #define BT_HCI_LE_ADV_EVT_TYPE_DIRECT BIT(2) #define BT_HCI_LE_ADV_EVT_TYPE_SCAN_RSP BIT(3) #define BT_HCI_LE_ADV_EVT_TYPE_LEGACY BIT(4) #define BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS(ev_type) (((ev_type) >> 5) & 0x03) #define BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_COMPLETE 0 #define BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_PARTIAL 1 #define BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_INCOMPLETE 2 struct bt_hci_evt_le_ext_advertising_info { u16_t evt_type; bt_addr_le_t addr; u8_t prim_phy; u8_t sec_phy; u8_t sid; s8_t tx_power; s8_t rssi; u16_t interval; bt_addr_le_t direct_addr; u8_t length; u8_t data[0]; } __packed; struct bt_hci_evt_le_ext_advertising_report { u8_t num_reports; struct bt_hci_evt_le_ext_advertising_info adv_info[0]; } __packed; #define BT_HCI_EVT_LE_PER_ADV_SYNC_ESTABLISHED 0x0e struct bt_hci_evt_le_per_adv_sync_established { u8_t status; u16_t handle; u8_t sid; bt_addr_le_t adv_addr; u8_t phy; u16_t interval; u8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_PER_ADVERTISING_REPORT 0x0f struct bt_hci_evt_le_per_advertising_report { u16_t handle; s8_t tx_power; s8_t rssi; u8_t unused; u8_t data_status; u8_t length; u8_t data[0]; } __packed; #define BT_HCI_EVT_LE_PER_ADV_SYNC_LOST 0x10 struct bt_hci_evt_le_per_adv_sync_lost { u16_t handle; } __packed; #define BT_HCI_EVT_LE_SCAN_TIMEOUT 0x11 #define BT_HCI_EVT_LE_ADV_SET_TERMINATED 0x12 struct bt_hci_evt_le_adv_set_terminated { u8_t status; u8_t adv_handle; u16_t conn_handle; u8_t num_completed_ext_adv_evts; } __packed; #define BT_HCI_EVT_LE_SCAN_REQ_RECEIVED 0x13 struct bt_hci_evt_le_scan_req_received { u8_t handle; bt_addr_le_t addr; } __packed; #define BT_HCI_LE_CHAN_SEL_ALGO_1 0x00 #define BT_HCI_LE_CHAN_SEL_ALGO_2 0x01 #define BT_HCI_EVT_LE_CHAN_SEL_ALGO 0x14 struct bt_hci_evt_le_chan_sel_algo { u16_t handle; u8_t chan_sel_algo; } __packed; /* Event mask bits */ #define BT_EVT_BIT(n) (1ULL << (n)) #define BT_EVT_MASK_INQUIRY_COMPLETE BT_EVT_BIT(0) #define BT_EVT_MASK_CONN_COMPLETE BT_EVT_BIT(2) #define BT_EVT_MASK_CONN_REQUEST BT_EVT_BIT(3) #define BT_EVT_MASK_DISCONN_COMPLETE BT_EVT_BIT(4) #define BT_EVT_MASK_AUTH_COMPLETE BT_EVT_BIT(5) #define BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE BT_EVT_BIT(6) #define BT_EVT_MASK_ENCRYPT_CHANGE BT_EVT_BIT(7) #define BT_EVT_MASK_REMOTE_FEATURES BT_EVT_BIT(10) #define BT_EVT_MASK_REMOTE_VERSION_INFO BT_EVT_BIT(11) #define BT_EVT_MASK_HARDWARE_ERROR BT_EVT_BIT(15) #define BT_EVT_MASK_ROLE_CHANGE BT_EVT_BIT(17) #define BT_EVT_MASK_PIN_CODE_REQ BT_EVT_BIT(21) #define BT_EVT_MASK_LINK_KEY_REQ BT_EVT_BIT(22) #define BT_EVT_MASK_LINK_KEY_NOTIFY BT_EVT_BIT(23) #define BT_EVT_MASK_DATA_BUFFER_OVERFLOW BT_EVT_BIT(25) #define BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI BT_EVT_BIT(33) #define BT_EVT_MASK_REMOTE_EXT_FEATURES BT_EVT_BIT(34) #define BT_EVT_MASK_SYNC_CONN_COMPLETE BT_EVT_BIT(43) #define BT_EVT_MASK_EXTENDED_INQUIRY_RESULT BT_EVT_BIT(46) #define BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE BT_EVT_BIT(47) #define BT_EVT_MASK_IO_CAPA_REQ BT_EVT_BIT(48) #define BT_EVT_MASK_IO_CAPA_RESP BT_EVT_BIT(49) #define BT_EVT_MASK_USER_CONFIRM_REQ BT_EVT_BIT(50) #define BT_EVT_MASK_USER_PASSKEY_REQ BT_EVT_BIT(51) #define BT_EVT_MASK_SSP_COMPLETE BT_EVT_BIT(53) #define BT_EVT_MASK_USER_PASSKEY_NOTIFY BT_EVT_BIT(58) #define BT_EVT_MASK_LE_META_EVENT BT_EVT_BIT(61) /* Page 2 */ #define BT_EVT_MASK_PHY_LINK_COMPLETE BT_EVT_BIT(0) #define BT_EVT_MASK_CH_SELECTED_COMPLETE BT_EVT_BIT(1) #define BT_EVT_MASK_DISCONN_PHY_LINK_COMPLETE BT_EVT_BIT(2) #define BT_EVT_MASK_PHY_LINK_LOSS_EARLY_WARN BT_EVT_BIT(3) #define BT_EVT_MASK_PHY_LINK_RECOVERY BT_EVT_BIT(4) #define BT_EVT_MASK_LOG_LINK_COMPLETE BT_EVT_BIT(5) #define BT_EVT_MASK_DISCONN_LOG_LINK_COMPLETE BT_EVT_BIT(6) #define BT_EVT_MASK_FLOW_SPEC_MODIFY_COMPLETE BT_EVT_BIT(7) #define BT_EVT_MASK_NUM_COMPLETE_DATA_BLOCKS BT_EVT_BIT(8) #define BT_EVT_MASK_AMP_START_TEST BT_EVT_BIT(9) #define BT_EVT_MASK_AMP_TEST_END BT_EVT_BIT(10) #define BT_EVT_MASK_AMP_RX_REPORT BT_EVT_BIT(11) #define BT_EVT_MASK_AMP_SR_MODE_CHANGE_COMPLETE BT_EVT_BIT(12) #define BT_EVT_MASK_AMP_STATUS_CHANGE BT_EVT_BIT(13) #define BT_EVT_MASK_TRIGG_CLOCK_CAPTURE BT_EVT_BIT(14) #define BT_EVT_MASK_SYNCH_TRAIN_COMPLETE BT_EVT_BIT(15) #define BT_EVT_MASK_SYNCH_TRAIN_RX BT_EVT_BIT(16) #define BT_EVT_MASK_CL_SLAVE_BC_RX BT_EVT_BIT(17) #define BT_EVT_MASK_CL_SLAVE_BC_TIMEOUT BT_EVT_BIT(18) #define BT_EVT_MASK_TRUNC_PAGE_COMPLETE BT_EVT_BIT(19) #define BT_EVT_MASK_SLAVE_PAGE_RSP_TIMEOUT BT_EVT_BIT(20) #define BT_EVT_MASK_CL_SLAVE_BC_CH_MAP_CHANGE BT_EVT_BIT(21) #define BT_EVT_MASK_INQUIRY_RSP_NOT BT_EVT_BIT(22) #define BT_EVT_MASK_AUTH_PAYLOAD_TIMEOUT_EXP BT_EVT_BIT(23) #define BT_EVT_MASK_SAM_STATUS_CHANGE BT_EVT_BIT(24) #define BT_EVT_MASK_LE_CONN_COMPLETE BT_EVT_BIT(0) #define BT_EVT_MASK_LE_ADVERTISING_REPORT BT_EVT_BIT(1) #define BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE BT_EVT_BIT(2) #define BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE BT_EVT_BIT(3) #define BT_EVT_MASK_LE_LTK_REQUEST BT_EVT_BIT(4) #define BT_EVT_MASK_LE_CONN_PARAM_REQ BT_EVT_BIT(5) #define BT_EVT_MASK_LE_DATA_LEN_CHANGE BT_EVT_BIT(6) #define BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE BT_EVT_BIT(7) #define BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE BT_EVT_BIT(8) #define BT_EVT_MASK_LE_ENH_CONN_COMPLETE BT_EVT_BIT(9) #define BT_EVT_MASK_LE_DIRECT_ADV_REPORT BT_EVT_BIT(10) #define BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE BT_EVT_BIT(11) #define BT_EVT_MASK_LE_EXT_ADVERTISING_REPORT BT_EVT_BIT(12) #define BT_EVT_MASK_LE_PER_ADV_SYNC_ESTABLISHED BT_EVT_BIT(13) #define BT_EVT_MASK_LE_PER_ADVERTISING_REPORT BT_EVT_BIT(14) #define BT_EVT_MASK_LE_PER_ADV_SYNC_LOST BT_EVT_BIT(15) #define BT_EVT_MASK_LE_SCAN_TIMEOUT BT_EVT_BIT(16) #define BT_EVT_MASK_LE_ADV_SET_TERMINATED BT_EVT_BIT(17) #define BT_EVT_MASK_LE_SCAN_REQ_RECEIVED BT_EVT_BIT(18) #define BT_EVT_MASK_LE_CHAN_SEL_ALGO BT_EVT_BIT(19) /** Allocate a HCI command buffer. * * This function allocates a new buffer for a HCI command. It is given * the OpCode (encoded e.g. using the BT_OP macro) and the total length * of the parameters. Upon successful return the buffer is ready to have * the parameters encoded into it. * * @param opcode Command OpCode. * @param param_len Length of command parameters. * * @return Newly allocated buffer. */ struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len); /** Send a HCI command asynchronously. * * This function is used for sending a HCI command asynchronously. It can * either be called for a buffer created using bt_hci_cmd_create(), or * if the command has no parameters a NULL can be passed instead. The * sending of the command will happen asynchronously, i.e. upon successful * return from this function the caller only knows that it was queued * successfully. * * If synchronous behavior, and retrieval of the Command Complete parameters * is desired, the bt_hci_cmd_send_sync() API should be used instead. * * @param opcode Command OpCode. * @param buf Command buffer or NULL (if no parameters). * * @return 0 on success or negative error value on failure. */ int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf); /** Send a HCI command synchronously. * * This function is used for sending a HCI command synchronously. It can * either be called for a buffer created using bt_hci_cmd_create(), or * if the command has no parameters a NULL can be passed instead. * * The function will block until a Command Status or a Command Complete * event is returned. If either of these have a non-zero status the function * will return a negative error code and the response reference will not * be set. If the command completed successfully and a non-NULL rsp parameter * was given, this parameter will be set to point to a buffer containing * the response parameters. * * @param opcode Command OpCode. * @param buf Command buffer or NULL (if no parameters). * @param rsp Place to store a reference to the command response. May * be NULL if the caller is not interested in the response * parameters. If non-NULL is passed the caller is responsible * for calling net_buf_unref() on the buffer when done parsing * it. * * @return 0 on success or negative error value on failure. */ int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, struct net_buf **rsp); /** @brief Get connection handle for a connection. * * @param conn Connection object. * @param conn_handle Place to store the Connection handle. * * @return 0 on success or negative error value on failure. */ int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle); /** @typedef bt_hci_vnd_evt_cb_t * @brief Callback type for vendor handling of HCI Vendor-Specific Events. * * A function of this type is registered with bt_hci_register_vnd_evt_cb() * and will be called for any HCI Vendor-Specific Event. * * @param buf Buffer containing event parameters. * * @return true if the function handles the event or false to defer the * handling of this event back to the stack. */ typedef bool bt_hci_vnd_evt_cb_t(struct net_buf_simple *buf); /** Register user callback for HCI Vendor-Specific Events * * @param cb Callback to be called when the stack receives a * HCI Vendor-Specific Event. * * @return 0 on success or negative error value on failure. */ int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb); #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_HCI_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/hci.h
C
apache-2.0
56,671
/** @file * @brief Bluetooth HCI driver API. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __BT_HCI_DRIVER_H #define __BT_HCI_DRIVER_H /** * @brief HCI drivers * @defgroup bt_hci_driver HCI drivers * @ingroup bluetooth * @{ */ #include <stdbool.h> #include <net/buf.h> #include <bluetooth/buf.h> #ifdef __cplusplus extern "C" { #endif enum { /* The host should never send HCI_Reset */ BT_QUIRK_NO_RESET = BIT(0), }; /** * @brief Check if an HCI event is high priority or not. * * Helper for the HCI driver to know which events are ok to be passed * through the RX thread and which must be given to bt_recv_prio() from * another context (e.g. ISR). If this function returns true it's safe * to pass the event through the RX thread, however if it returns false * then this risks a deadlock. * * @param evt HCI event code. * * @return true if the event can be processed in the RX thread, false * if it cannot. */ static inline bool bt_hci_evt_is_prio(u8_t evt) { switch (evt) { case BT_HCI_EVT_CMD_COMPLETE: case BT_HCI_EVT_CMD_STATUS: #if defined(CONFIG_BT_CONN) case BT_HCI_EVT_NUM_COMPLETED_PACKETS: #endif return true; default: return false; } } /** * @brief Receive data from the controller/HCI driver. * * This is the main function through which the HCI driver provides the * host with data from the controller. The buffer needs to have its type * set with the help of bt_buf_set_type() before calling this API. This API * should not be used for so-called high priority HCI events, which should * instead be delivered to the host stack through bt_recv_prio(). * * @param buf Network buffer containing data from the controller. * * @return 0 on success or negative error number on failure. */ int bt_recv(struct net_buf *buf); /** * @brief Receive high priority data from the controller/HCI driver. * * This is the same as bt_recv(), except that it should be used for * so-called high priority HCI events. There's a separate * bt_hci_evt_is_prio() helper that can be used to identify which events * are high priority. * * As with bt_recv(), the buffer needs to have its type set with the help of * bt_buf_set_type() before calling this API. The only exception is so called * high priority HCI events which should be delivered to the host stack through * bt_recv_prio() instead. * * @param buf Network buffer containing data from the controller. * * @return 0 on success or negative error number on failure. */ int bt_recv_prio(struct net_buf *buf); /** Possible values for the 'bus' member of the bt_hci_driver struct */ enum bt_hci_driver_bus { BT_HCI_DRIVER_BUS_VIRTUAL = 0, BT_HCI_DRIVER_BUS_USB = 1, BT_HCI_DRIVER_BUS_PCCARD = 2, BT_HCI_DRIVER_BUS_UART = 3, BT_HCI_DRIVER_BUS_RS232 = 4, BT_HCI_DRIVER_BUS_PCI = 5, BT_HCI_DRIVER_BUS_SDIO = 6, BT_HCI_DRIVER_BUS_SPI = 7, BT_HCI_DRIVER_BUS_I2C = 8, }; /** * @brief Abstraction which represents the HCI transport to the controller. * * This struct is used to represent the HCI transport to the Bluetooth * controller. */ struct bt_hci_driver { /** Name of the driver */ const char *name; /** Bus of the transport (BT_HCI_DRIVER_BUS_*) */ enum bt_hci_driver_bus bus; /** Specific controller quirks. These are set by the HCI driver * and acted upon by the host. They can either be statically * set at buildtime, or set at runtime before the HCI driver's * open() callback returns. */ bt_u32_t quirks; /** * @brief Open the HCI transport. * * Opens the HCI transport for operation. This function must not * return until the transport is ready for operation, meaning it * is safe to start calling the send() handler. * * If the driver uses its own RX thread, i.e. * CONFIG_BT_RECV_IS_RX_THREAD is set, then this * function is expected to start that thread. * * @return 0 on success or negative error number on failure. */ int (*open)(void); /** * @brief Send HCI buffer to controller. * * Send an HCI command or ACL data to the controller. The exact * type of the data can be checked with the help of bt_buf_get_type(). * * @note This function must only be called from a cooperative thread. * * @param buf Buffer containing data to be sent to the controller. * * @return 0 on success or negative error number on failure. */ int (*send)(struct net_buf *buf); }; /** * @brief Register a new HCI driver to the Bluetooth stack. * * This needs to be called before any application code runs. The bt_enable() * API will fail if there is no driver registered. * * @param drv A bt_hci_driver struct representing the driver. * * @return 0 on success or negative error number on failure. */ int bt_hci_driver_register(const struct bt_hci_driver *drv); #ifdef __cplusplus } #endif /** * @} */ #endif /* __BT_HCI_DRIVER_H */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/hci_driver.h
C
apache-2.0
4,977
/** @file * @brief Bluetooth Host Control Interface status codes. */ /* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_HCI_STATUS_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_HCI_STATUS_H_ #ifdef __cplusplus extern "C" { #endif /** HCI Error Codes, BT Core Spec v5.2 [Vol 1, Part F]. */ #define BT_HCI_ERR_SUCCESS 0x00 #define BT_HCI_ERR_UNKNOWN_CMD 0x01 #define BT_HCI_ERR_UNKNOWN_CONN_ID 0x02 #define BT_HCI_ERR_HW_FAILURE 0x03 #define BT_HCI_ERR_PAGE_TIMEOUT 0x04 #define BT_HCI_ERR_AUTH_FAIL 0x05 #define BT_HCI_ERR_PIN_OR_KEY_MISSING 0x06 #define BT_HCI_ERR_MEM_CAPACITY_EXCEEDED 0x07 #define BT_HCI_ERR_CONN_TIMEOUT 0x08 #define BT_HCI_ERR_CONN_LIMIT_EXCEEDED 0x09 #define BT_HCI_ERR_SYNC_CONN_LIMIT_EXCEEDED 0x0a #define BT_HCI_ERR_CONN_ALREADY_EXISTS 0x0b #define BT_HCI_ERR_CMD_DISALLOWED 0x0c #define BT_HCI_ERR_INSUFFICIENT_RESOURCES 0x0d #define BT_HCI_ERR_INSUFFICIENT_SECURITY 0x0e #define BT_HCI_ERR_BD_ADDR_UNACCEPTABLE 0x0f #define BT_HCI_ERR_CONN_ACCEPT_TIMEOUT 0x10 #define BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL 0x11 #define BT_HCI_ERR_INVALID_PARAM 0x12 #define BT_HCI_ERR_REMOTE_USER_TERM_CONN 0x13 #define BT_HCI_ERR_REMOTE_LOW_RESOURCES 0x14 #define BT_HCI_ERR_REMOTE_POWER_OFF 0x15 #define BT_HCI_ERR_LOCALHOST_TERM_CONN 0x16 #define BT_HCI_ERR_REPEATED_ATTEMPTS 0x17 #define BT_HCI_ERR_PAIRING_NOT_ALLOWED 0x18 #define BT_HCI_ERR_UNKNOWN_LMP_PDU 0x19 #define BT_HCI_ERR_UNSUPP_REMOTE_FEATURE 0x1a #define BT_HCI_ERR_SCO_OFFSET_REJECTED 0x1b #define BT_HCI_ERR_SCO_INTERVAL_REJECTED 0x1c #define BT_HCI_ERR_SCO_AIR_MODE_REJECTED 0x1d #define BT_HCI_ERR_INVALID_LL_PARAM 0x1e #define BT_HCI_ERR_UNSPECIFIED 0x1f #define BT_HCI_ERR_UNSUPP_LL_PARAM_VAL 0x20 #define BT_HCI_ERR_ROLE_CHANGE_NOT_ALLOWED 0x21 #define BT_HCI_ERR_LL_RESP_TIMEOUT 0x22 #define BT_HCI_ERR_LL_PROC_COLLISION 0x23 #define BT_HCI_ERR_LMP_PDU_NOT_ALLOWED 0x24 #define BT_HCI_ERR_ENC_MODE_NOT_ACCEPTABLE 0x25 #define BT_HCI_ERR_LINK_KEY_CANNOT_BE_CHANGED 0x26 #define BT_HCI_ERR_REQUESTED_QOS_NOT_SUPPORTED 0x27 #define BT_HCI_ERR_INSTANT_PASSED 0x28 #define BT_HCI_ERR_PAIRING_NOT_SUPPORTED 0x29 #define BT_HCI_ERR_DIFF_TRANS_COLLISION 0x2a #define BT_HCI_ERR_QOS_UNACCEPTABLE_PARAM 0x2c #define BT_HCI_ERR_QOS_REJECTED 0x2d #define BT_HCI_ERR_CHAN_ASSESS_NOT_SUPPORTED 0x2e #define BT_HCI_ERR_INSUFF_SECURITY 0x2f #define BT_HCI_ERR_PARAM_OUT_OF_MANDATORY_RANGE 0x30 #define BT_HCI_ERR_ROLE_SWITCH_PENDING 0x32 #define BT_HCI_ERR_RESERVED_SLOT_VIOLATION 0x34 #define BT_HCI_ERR_ROLE_SWITCH_FAILED 0x35 #define BT_HCI_ERR_EXT_INQ_RESP_TOO_LARGE 0x36 #define BT_HCI_ERR_SIMPLE_PAIR_NOT_SUPP_BY_HOST 0x37 #define BT_HCI_ERR_HOST_BUSY_PAIRING 0x38 #define BT_HCI_ERR_CONN_REJECTED_DUE_TO_NO_CHAN 0x39 #define BT_HCI_ERR_CONTROLLER_BUSY 0x3a #define BT_HCI_ERR_UNACCEPT_CONN_PARAM 0x3b #define BT_HCI_ERR_ADV_TIMEOUT 0x3c #define BT_HCI_ERR_TERM_DUE_TO_MIC_FAIL 0x3d #define BT_HCI_ERR_CONN_FAIL_TO_ESTAB 0x3e #define BT_HCI_ERR_MAC_CONN_FAILED 0x3f #define BT_HCI_ERR_CLOCK_ADJUST_REJECTED 0x40 #define BT_HCI_ERR_SUBMAP_NOT_DEFINED 0x41 #define BT_HCI_ERR_UNKNOWN_ADV_IDENTIFIER 0x42 #define BT_HCI_ERR_LIMIT_REACHED 0x43 #define BT_HCI_ERR_OP_CANCELLED_BY_HOST 0x44 #define BT_HCI_ERR_PACKET_TOO_LONG 0x45 #define BT_HCI_ERR_AUTHENTICATION_FAIL __DEPRECATED_MACRO BT_HCI_ERR_AUTH_FAIL #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_HCI_STATUS_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/hci_err.h
C
apache-2.0
4,076
/** @file * @brief Bluetooth HCI RAW channel handling */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_HCI_RAW_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_HCI_RAW_H_ /** * @brief HCI RAW channel * @defgroup hci_raw HCI RAW channel * @ingroup bluetooth * @{ */ #ifdef __cplusplus extern "C" { #endif #if defined(CONFIG_BT_CTLR_TX_BUFFER_SIZE) #define BT_L2CAP_MTU (CONFIG_BT_CTLR_TX_BUFFER_SIZE - BT_L2CAP_HDR_SIZE) #else #define BT_L2CAP_MTU 65 /* 64-byte public key + opcode */ #endif /* CONFIG_BT_CTLR */ /** Data size needed for ACL buffers */ #define BT_BUF_ACL_SIZE BT_L2CAP_BUF_SIZE(BT_L2CAP_MTU) #if defined(CONFIG_BT_CTLR_TX_BUFFERS) #define BT_HCI_ACL_COUNT CONFIG_BT_CTLR_TX_BUFFERS #else #define BT_HCI_ACL_COUNT 6 #endif #define BT_BUF_TX_SIZE MAX(BT_BUF_RX_SIZE, BT_BUF_ACL_SIZE) /** @brief Send packet to the Bluetooth controller * * Send packet to the Bluetooth controller. Caller needs to * implement netbuf pool. * * @param buf netbuf packet to be send * * @return Zero on success or (negative) error code otherwise. */ int bt_send(struct net_buf *buf); enum { /** Passthrough mode * * While in this mode the buffers are passed as is between the stack * and the driver. */ BT_HCI_RAW_MODE_PASSTHROUGH = 0x00, /** H:4 mode * * While in this mode H:4 headers will added into the buffers * according to the buffer type when coming from the stack and will be * removed and used to set the buffer type. */ BT_HCI_RAW_MODE_H4 = 0x01, }; /** @brief Set Bluetooth RAW channel mode * * Set access mode of Bluetooth RAW channel. * * @param mode Access mode. * * @return Zero on success or (negative) error code otherwise. */ int bt_hci_raw_set_mode(u8_t mode); /** @brief Get Bluetooth RAW channel mode * * Get access mode of Bluetooth RAW channel. * * @return Access mode. */ u8_t bt_hci_raw_get_mode(void); #define BT_HCI_ERR_EXT_HANDLED 0xff /** Helper macro to define a command extension * * @param _op Opcode of the command. * @param _min_len Minimal length of the command. * @param _func Handler function to be called. */ #define BT_HCI_RAW_CMD_EXT(_op, _min_len, _func) \ { \ .op = _op, \ .min_len = _min_len, \ .func = _func, \ } struct bt_hci_raw_cmd_ext { /** Opcode of the command */ u16_t op; /** Minimal length of the command */ size_t min_len; /** Handler function. * * Handler function to be called when a command is intercepted. * * @param buf Buffer containing the command. * * @return HCI Status code or BT_HCI_ERR_EXT_HANDLED if command has * been handled already and a response has been sent as oppose to * BT_HCI_ERR_SUCCESS which just indicates that the command can be * sent to the controller to be processed. */ u8_t (*func)(struct net_buf *buf); }; /** @brief Register Bluetooth RAW command extension table * * Register Bluetooth RAW channel command extension table, opcodes in this * table are intercepted to sent to the handler function. * * @param cmds Pointer to the command extension table. * @param size Size of the command extension table. */ void bt_hci_raw_cmd_ext_register(struct bt_hci_raw_cmd_ext *cmds, size_t size); /** @brief Enable Bluetooth RAW channel: * * Enable Bluetooth RAW HCI channel. * * @param rx_queue netbuf queue where HCI packets received from the Bluetooth * controller are to be queued. The queue is defined in the caller while * the available buffers pools are handled in the stack. * * @return Zero on success or (negative) error code otherwise. */ int bt_enable_raw(struct kfifo *rx_queue); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_HCI_RAW_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/hci_raw.h
C
apache-2.0
3,775
/* hci_vs.h - Bluetooth Host Control Interface Vendor Specific definitions */ /* * Copyright (c) 2017-2018 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_HCI_VS_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_HCI_VS_H_ #include <bluetooth/hci.h> #ifdef __cplusplus extern "C" { #endif #define BT_VS_CMD_BIT_VERSION 0 #define BT_VS_CMD_BIT_SUP_CMD 1 #define BT_VS_CMD_BIT_SUP_FEAT 2 #define BT_VS_CMD_BIT_SET_EVT_MASK 3 #define BT_VS_CMD_BIT_RESET 4 #define BT_VS_CMD_BIT_WRITE_BDADDR 5 #define BT_VS_CMD_BIT_SET_TRACE_ENABLE 6 #define BT_VS_CMD_BIT_READ_BUILD_INFO 7 #define BT_VS_CMD_BIT_READ_STATIC_ADDRS 8 #define BT_VS_CMD_BIT_READ_KEY_ROOTS 9 #define BT_VS_CMD_BIT_READ_CHIP_TEMP 10 #define BT_VS_CMD_BIT_READ_HOST_STACK_CMD 11 #define BT_VS_CMD_BIT_SET_SCAN_REP_ENABLE 12 #define BT_VS_CMD_BIT_WRITE_TX_POWER 13 #define BT_VS_CMD_BIT_READ_TX_POWER 14 #define BT_VS_CMD_SUP_FEAT(cmd) BT_LE_FEAT_TEST(cmd, \ BT_VS_CMD_BIT_SUP_FEAT) #define BT_VS_CMD_READ_STATIC_ADDRS(cmd) BT_LE_FEAT_TEST(cmd, \ BT_VS_CMD_BIT_READ_STATIC_ADDRS) #define BT_VS_CMD_READ_KEY_ROOTS(cmd) BT_LE_FEAT_TEST(cmd, \ BT_VS_CMD_BIT_READ_KEY_ROOTS) #define BT_HCI_VS_HW_PLAT_INTEL 0x0001 #define BT_HCI_VS_HW_PLAT_NORDIC 0x0002 #define BT_HCI_VS_HW_PLAT_NXP 0x0003 #define BT_HCI_VS_HW_VAR_NORDIC_NRF51X 0x0001 #define BT_HCI_VS_HW_VAR_NORDIC_NRF52X 0x0002 #define BT_HCI_VS_HW_VAR_NORDIC_NRF53X 0x0003 #define BT_HCI_VS_FW_VAR_STANDARD_CTLR 0x0001 #define BT_HCI_VS_FW_VAR_VS_CTLR 0x0002 #define BT_HCI_VS_FW_VAR_FW_LOADER 0x0003 #define BT_HCI_VS_FW_VAR_RESCUE_IMG 0x0004 #define BT_HCI_OP_VS_READ_VERSION_INFO BT_OP(BT_OGF_VS, 0x0001) struct bt_hci_rp_vs_read_version_info { u8_t status; u16_t hw_platform; u16_t hw_variant; u8_t fw_variant; u8_t fw_version; u16_t fw_revision; bt_u32_t fw_build; } __packed; #define BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_VS, 0x0002) struct bt_hci_rp_vs_read_supported_commands { u8_t status; u8_t commands[64]; } __packed; #define BT_HCI_OP_VS_READ_SUPPORTED_FEATURES BT_OP(BT_OGF_VS, 0x0003) struct bt_hci_rp_vs_read_supported_features { u8_t status; u8_t features[8]; } __packed; #define BT_HCI_OP_VS_SET_EVENT_MASK BT_OP(BT_OGF_VS, 0x0004) struct bt_hci_cp_vs_set_event_mask { u8_t event_mask[8]; } __packed; #define BT_HCI_VS_RESET_SOFT 0x00 #define BT_HCI_VS_RESET_HARD 0x01 #define BT_HCI_OP_VS_RESET BT_OP(BT_OGF_VS, 0x0005) struct bt_hci_cp_vs_reset { u8_t type; } __packed; #define BT_HCI_OP_VS_WRITE_BD_ADDR BT_OP(BT_OGF_VS, 0x0006) struct bt_hci_cp_vs_write_bd_addr { bt_addr_t bdaddr; } __packed; #define BT_HCI_VS_TRACE_DISABLED 0x00 #define BT_HCI_VS_TRACE_ENABLED 0x01 #define BT_HCI_VS_TRACE_HCI_EVTS 0x00 #define BT_HCI_VS_TRACE_VDC 0x01 #define BT_HCI_OP_VS_SET_TRACE_ENABLE BT_OP(BT_OGF_VS, 0x0007) struct bt_hci_cp_vs_set_trace_enable { u8_t enable; u8_t type; } __packed; #define BT_HCI_OP_VS_READ_BUILD_INFO BT_OP(BT_OGF_VS, 0x0008) struct bt_hci_rp_vs_read_build_info { u8_t status; u8_t info[0]; } __packed; struct bt_hci_vs_static_addr { bt_addr_t bdaddr; u8_t ir[16]; } __packed; #define BT_HCI_OP_VS_READ_STATIC_ADDRS BT_OP(BT_OGF_VS, 0x0009) struct bt_hci_rp_vs_read_static_addrs { u8_t status; u8_t num_addrs; struct bt_hci_vs_static_addr a[0]; } __packed; #define BT_HCI_OP_VS_READ_KEY_HIERARCHY_ROOTS BT_OP(BT_OGF_VS, 0x000a) struct bt_hci_rp_vs_read_key_hierarchy_roots { u8_t status; u8_t ir[16]; u8_t er[16]; } __packed; #define BT_HCI_OP_VS_READ_CHIP_TEMP BT_OP(BT_OGF_VS, 0x000b) struct bt_hci_rp_vs_read_chip_temp { u8_t status; s8_t temps; } __packed; struct bt_hci_vs_cmd { u16_t vendor_id; u16_t opcode_base; } __packed; #define BT_HCI_VS_VID_ANDROID 0x0001 #define BT_HCI_VS_VID_MICROSOFT 0x0002 #define BT_HCI_OP_VS_READ_HOST_STACK_CMDS BT_OP(BT_OGF_VS, 0x000c) struct bt_hci_rp_vs_read_host_stack_cmds { u8_t status; u8_t num_cmds; struct bt_hci_vs_cmd c[0]; } __packed; #define BT_HCI_VS_SCAN_REQ_REPORTS_DISABLED 0x00 #define BT_HCI_VS_SCAN_REQ_REPORTS_ENABLED 0x01 #define BT_HCI_OP_VS_SET_SCAN_REQ_REPORTS BT_OP(BT_OGF_VS, 0x000d) struct bt_hci_cp_vs_set_scan_req_reports { u8_t enable; } __packed; #define BT_HCI_VS_LL_HANDLE_TYPE_ADV 0x00 #define BT_HCI_VS_LL_HANDLE_TYPE_SCAN 0x01 #define BT_HCI_VS_LL_HANDLE_TYPE_CONN 0x02 #define BT_HCI_VS_LL_TX_POWER_LEVEL_NO_PREF 0x7F #define BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL BT_OP(BT_OGF_VS, 0x000e) struct bt_hci_cp_vs_write_tx_power_level { u8_t handle_type; u16_t handle; s8_t tx_power_level; } __packed; struct bt_hci_rp_vs_write_tx_power_level { u8_t status; u8_t handle_type; u16_t handle; s8_t selected_tx_power; } __packed; #define BT_HCI_OP_VS_READ_TX_POWER_LEVEL BT_OP(BT_OGF_VS, 0x000f) struct bt_hci_cp_vs_read_tx_power_level { u8_t handle_type; u16_t handle; } __packed; struct bt_hci_rp_vs_read_tx_power_level { u8_t status; u8_t handle_type; u16_t handle; s8_t tx_power_level; } __packed; #define BT_HCI_OP_VS_READ_USB_TRANSPORT_MODE BT_OP(BT_OGF_VS, 0x0010) struct bt_hci_rp_vs_read_usb_transport_mode { u8_t status; u8_t num_supported_modes; u8_t supported_mode[0]; } __packed; #define BT_HCI_VS_USB_H2_MODE 0x00 #define BT_HCI_VS_USB_H4_MODE 0x01 #define BT_HCI_OP_VS_SET_USB_TRANSPORT_MODE BT_OP(BT_OGF_VS, 0x0011) struct bt_hci_cp_vs_set_usb_transport_mode { u8_t mode; } __packed; /* Events */ struct bt_hci_evt_vs { u8_t subevent; } __packed; #define BT_HCI_EVT_VS_FATAL_ERROR 0x02 struct bt_hci_evt_vs_fatal_error { u64_t pc; u8_t err_info[0]; } __packed; #define BT_HCI_VS_TRACE_LMP_TX 0x01 #define BT_HCI_VS_TRACE_LMP_RX 0x02 #define BT_HCI_VS_TRACE_LLCP_TX 0x03 #define BT_HCI_VS_TRACE_LLCP_RX 0x04 #define BT_HCI_VS_TRACE_LE_CONN_IND 0x05 #define BT_HCI_EVT_VS_TRACE_INFO 0x03 struct bt_hci_evt_vs_trace_info { u8_t type; u8_t data[0]; } __packed; #define BT_HCI_EVT_VS_SCAN_REQ_RX 0x04 struct bt_hci_evt_vs_scan_req_rx { bt_addr_le_t addr; s8_t rssi; } __packed; /* Event mask bits */ #define BT_EVT_MASK_VS_FATAL_ERROR BT_EVT_BIT(1) #define BT_EVT_MASK_VS_TRACE_INFO BT_EVT_BIT(2) #define BT_EVT_MASK_VS_SCAN_REQ_RX BT_EVT_BIT(3) /* Mesh HCI commands */ #define BT_HCI_MESH_REVISION 0x01 #define BT_HCI_OP_VS_MESH BT_OP(BT_OGF_VS, 0x0042) #define BT_HCI_MESH_EVT_PREFIX 0xF0 struct bt_hci_cp_mesh { u8_t opcode; } __packed; #define BT_HCI_OC_MESH_GET_OPTS 0x00 struct bt_hci_rp_mesh_get_opts { u8_t status; u8_t opcode; u8_t revision; u8_t ch_map; s8_t min_tx_power; s8_t max_tx_power; u8_t max_scan_filter; u8_t max_filter_pattern; u8_t max_adv_slot; u8_t max_tx_window; u8_t evt_prefix_len; u8_t evt_prefix; } __packed; #define BT_HCI_MESH_PATTERN_LEN_MAX 0x0f #define BT_HCI_OC_MESH_SET_SCAN_FILTER 0x01 struct bt_hci_mesh_pattern { u8_t pattern_len; u8_t pattern[0]; } __packed; struct bt_hci_cp_mesh_set_scan_filter { u8_t scan_filter; u8_t filter_dup; u8_t num_patterns; struct bt_hci_mesh_pattern patterns[0]; } __packed; struct bt_hci_rp_mesh_set_scan_filter { u8_t status; u8_t opcode; u8_t scan_filter; } __packed; #define BT_HCI_OC_MESH_ADVERTISE 0x02 struct bt_hci_cp_mesh_advertise { u8_t adv_slot; u8_t own_addr_type; bt_addr_t random_addr; u8_t ch_map; s8_t tx_power; u8_t min_tx_delay; u8_t max_tx_delay; u8_t retx_count; u8_t retx_interval; u8_t scan_delay; u16_t scan_duration; u8_t scan_filter; u8_t data_len; u8_t data[31]; } __packed; struct bt_hci_rp_mesh_advertise { u8_t status; u8_t opcode; u8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_ADVERTISE_TIMED 0x03 struct bt_hci_cp_mesh_advertise_timed { u8_t adv_slot; u8_t own_addr_type; bt_addr_t random_addr; u8_t ch_map; s8_t tx_power; u8_t retx_count; u8_t retx_interval; bt_u32_t instant; u16_t tx_delay; u16_t tx_window; u8_t data_len; u8_t data[31]; } __packed; struct bt_hci_rp_mesh_advertise_timed { u8_t status; u8_t opcode; u8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_ADVERTISE_CANCEL 0x04 struct bt_hci_cp_mesh_advertise_cancel { u8_t adv_slot; } __packed; struct bt_hci_rp_mesh_advertise_cancel { u8_t status; u8_t opcode; u8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_SET_SCANNING 0x05 struct bt_hci_cp_mesh_set_scanning { u8_t enable; u8_t ch_map; u8_t scan_filter; } __packed; struct bt_hci_rp_mesh_set_scanning { u8_t status; u8_t opcode; } __packed; /* Events */ struct bt_hci_evt_mesh { u8_t prefix; u8_t subevent; } __packed; #define BT_HCI_EVT_MESH_ADV_COMPLETE 0x00 struct bt_hci_evt_mesh_adv_complete { u8_t adv_slot; } __packed; #define BT_HCI_EVT_MESH_SCANNING_REPORT 0x01 struct bt_hci_evt_mesh_scan_report { bt_addr_le_t addr; u8_t chan; s8_t rssi; bt_u32_t instant; u8_t data_len; u8_t data[0]; } __packed; struct bt_hci_evt_mesh_scanning_report { u8_t num_reports; struct bt_hci_evt_mesh_scan_report reports[0]; } __packed; #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_HCI_VS_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/hci_vs.h
C
apache-2.0
10,365
/** @file * @brief Handsfree Profile handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_HFP_HF_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_HFP_HF_H_ /** * @brief Hands Free Profile (HFP) * @defgroup bt_hfp Hands Free Profile (HFP) * @ingroup bluetooth * @{ */ #include <bluetooth/bluetooth.h> #ifdef __cplusplus extern "C" { #endif /* AT Commands */ enum bt_hfp_hf_at_cmd { BT_HFP_HF_ATA, BT_HFP_HF_AT_CHUP, }; /* * Command complete types for the application */ #define HFP_HF_CMD_OK 0 #define HFP_HF_CMD_ERROR 1 #define HFP_HF_CMD_CME_ERROR 2 #define HFP_HF_CMD_UNKNOWN_ERROR 4 /** @brief HFP HF Command completion field */ struct bt_hfp_hf_cmd_complete { /* Command complete status */ u8_t type; /* CME error number to be added */ u8_t cme; }; /** @brief HFP profile application callback */ struct bt_hfp_hf_cb { /** HF connected callback to application * * If this callback is provided it will be called whenever the * connection completes. * * @param conn Connection object. */ void (*connected)(struct bt_conn *conn); /** HF disconnected callback to application * * If this callback is provided it will be called whenever the * connection gets disconnected, including when a connection gets * rejected or cancelled or any error in SLC establisment. * * @param conn Connection object. */ void (*disconnected)(struct bt_conn *conn); /** HF indicator Callback * * This callback provides service indicator value to the application * * @param conn Connection object. * @param value service indicator value received from the AG. */ void (*service)(struct bt_conn *conn, bt_u32_t value); /** HF indicator Callback * * This callback provides call indicator value to the application * * @param conn Connection object. * @param value call indicator value received from the AG. */ void (*call)(struct bt_conn *conn, bt_u32_t value); /** HF indicator Callback * * This callback provides call setup indicator value to the application * * @param conn Connection object. * @param value call setup indicator value received from the AG. */ void (*call_setup)(struct bt_conn *conn, bt_u32_t value); /** HF indicator Callback * * This callback provides call held indicator value to the application * * @param conn Connection object. * @param value call held indicator value received from the AG. */ void (*call_held)(struct bt_conn *conn, bt_u32_t value); /** HF indicator Callback * * This callback provides signal indicator value to the application * * @param conn Connection object. * @param value signal indicator value received from the AG. */ void (*signal)(struct bt_conn *conn, bt_u32_t value); /** HF indicator Callback * * This callback provides roaming indicator value to the application * * @param conn Connection object. * @param value roaming indicator value received from the AG. */ void (*roam)(struct bt_conn *conn, bt_u32_t value); /** HF indicator Callback * * This callback battery service indicator value to the application * * @param conn Connection object. * @param value battery indicator value received from the AG. */ void (*battery)(struct bt_conn *conn, bt_u32_t value); /** HF incoming call Ring indication callback to application * * If this callback is provided it will be called whenever there * is an incoming call. * * @param conn Connection object. */ void (*ring_indication)(struct bt_conn *conn); /** HF notify command completed callback to application * * The command sent from the application is notified about its status * * @param conn Connection object. * @param cmd structure contains status of the command including cme. */ void (*cmd_complete_cb)(struct bt_conn *conn, struct bt_hfp_hf_cmd_complete *cmd); }; /** @brief Register HFP HF profile * * Register Handsfree profile callbacks to monitor the state and get the * required HFP details to display. * * @param cb callback structure. * * @return 0 in case of success or negative value in case of error. */ int bt_hfp_hf_register(struct bt_hfp_hf_cb *cb); /** @brief Handsfree client Send AT * * Send specific AT commands to handsfree client profile. * * @param conn Connection object. * @param cmd AT command to be sent. * * @return 0 in case of success or negative value in case of error. */ int bt_hfp_hf_send_cmd(struct bt_conn *conn, enum bt_hfp_hf_at_cmd cmd); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_HFP_HF_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/hfp_hf.h
C
apache-2.0
4,700
/** @file * @brief Bluetooth L2CAP handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_L2CAP_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_L2CAP_H_ /** * @brief L2CAP * @defgroup bt_l2cap L2CAP * @ingroup bluetooth * @{ */ #include <atomic.h> #include <bluetooth/buf.h> #include <bluetooth/conn.h> #include <bluetooth/hci.h> #ifdef __cplusplus extern "C" { #endif /** L2CAP header size, used for buffer size calculations */ #define BT_L2CAP_HDR_SIZE 4 /** @def BT_L2CAP_BUF_SIZE * * @brief Helper to calculate needed outgoing buffer size, useful e.g. for * creating buffer pools. * * @param mtu Needed L2CAP MTU. * * @return Needed buffer size to match the requested L2CAP MTU. */ #define BT_L2CAP_BUF_SIZE(mtu) (BT_BUF_RESERVE + \ BT_HCI_ACL_HDR_SIZE + BT_L2CAP_HDR_SIZE + \ (mtu)) struct bt_l2cap_chan; /** @typedef bt_l2cap_chan_destroy_t * @brief Channel destroy callback * * @param chan Channel object. */ typedef void (*bt_l2cap_chan_destroy_t)(struct bt_l2cap_chan *chan); /** @brief Life-span states of L2CAP CoC channel. * * Used only by internal APIs dealing with setting channel to proper state * depending on operational context. */ typedef enum bt_l2cap_chan_state { /** Channel disconnected */ BT_L2CAP_DISCONNECTED, /** Channel in connecting state */ BT_L2CAP_CONNECT, /** Channel in config state, BR/EDR specific */ BT_L2CAP_CONFIG, /** Channel ready for upper layer traffic on it */ BT_L2CAP_CONNECTED, /** Channel in disconnecting state */ BT_L2CAP_DISCONNECT, } __packed bt_l2cap_chan_state_t; /** @brief Status of L2CAP channel. */ typedef enum bt_l2cap_chan_status { /** Channel output status */ BT_L2CAP_STATUS_OUT, /** @brief Channel shutdown status * * Once this status is notified it means the channel will no longer be * able to transmit or receive data. */ BT_L2CAP_STATUS_SHUTDOWN, /** @brief Channel encryption pending status */ BT_L2CAP_STATUS_ENCRYPT_PENDING, /* Total number of status - must be at the end of the enum */ BT_L2CAP_NUM_STATUS, } __packed bt_l2cap_chan_status_t; /** @brief L2CAP Channel structure. */ struct bt_l2cap_chan { /** Channel connection reference */ struct bt_conn *conn; /** Channel operations reference */ const struct bt_l2cap_chan_ops *ops; sys_snode_t node; bt_l2cap_chan_destroy_t destroy; /* Response Timeout eXpired (RTX) timer */ struct k_delayed_work rtx_work; ATOMIC_DEFINE(status, BT_L2CAP_NUM_STATUS); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) bt_l2cap_chan_state_t state; /** Remote PSM to be connected */ u16_t psm; /** Helps match request context during CoC */ u8_t ident; bt_security_t required_sec_level; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ }; /** @brief LE L2CAP Endpoint structure. */ struct bt_l2cap_le_endpoint { /** Endpoint CID */ u16_t cid; /** Endpoint Maximum Transmission Unit */ u16_t mtu; /** Endpoint Maximum PDU payload Size */ u16_t mps; /** Endpoint initial credits */ u16_t init_credits; /** Endpoint credits */ atomic_t credits; }; /** @brief LE L2CAP Channel structure. */ struct bt_l2cap_le_chan { /** Common L2CAP channel reference object */ struct bt_l2cap_chan chan; /** Channel Receiving Endpoint */ struct bt_l2cap_le_endpoint rx; /** Channel Transmission Endpoint */ struct bt_l2cap_le_endpoint tx; /** Channel Transmission queue */ struct kfifo tx_queue; /** Channel Pending Transmission buffer */ struct net_buf *tx_buf; /** Channel Transmission work */ struct k_work tx_work; /** Segment SDU packet from upper layer */ struct net_buf *_sdu; u16_t _sdu_len; struct k_work rx_work; struct kfifo rx_queue; }; /** @def BT_L2CAP_LE_CHAN(_ch) * @brief Helper macro getting container object of type bt_l2cap_le_chan * address having the same container chan member address as object in question. * * @param _ch Address of object of bt_l2cap_chan type * * @return Address of in memory bt_l2cap_le_chan object type containing * the address of in question object. */ #define BT_L2CAP_LE_CHAN(_ch) CONTAINER_OF(_ch, struct bt_l2cap_le_chan, chan) /** @brief BREDR L2CAP Endpoint structure. */ struct bt_l2cap_br_endpoint { /** Endpoint CID */ u16_t cid; /** Endpoint Maximum Transmission Unit */ u16_t mtu; }; /** @brief BREDR L2CAP Channel structure. */ struct bt_l2cap_br_chan { /** Common L2CAP channel reference object */ struct bt_l2cap_chan chan; /** Channel Receiving Endpoint */ struct bt_l2cap_br_endpoint rx; /** Channel Transmission Endpoint */ struct bt_l2cap_br_endpoint tx; /* For internal use only */ atomic_t flags[1]; }; /** @brief L2CAP Channel operations structure. */ struct bt_l2cap_chan_ops { /** @brief Channel connected callback * * If this callback is provided it will be called whenever the * connection completes. * * @param chan The channel that has been connected */ void (*connected)(struct bt_l2cap_chan *chan); /** @brief Channel disconnected callback * * If this callback is provided it will be called whenever the * channel is disconnected, including when a connection gets * rejected. * * @param chan The channel that has been Disconnected */ void (*disconnected)(struct bt_l2cap_chan *chan); /** @brief Channel encrypt_change callback * * If this callback is provided it will be called whenever the * security level changed (indirectly link encryption done) or * authentication procedure fails. In both cases security initiator * and responder got the final status (HCI status) passed by * related to encryption and authentication events from local host's * controller. * * @param chan The channel which has made encryption status changed. * @param status HCI status of performed security procedure caused * by channel security requirements. The value is populated * by HCI layer and set to 0 when success and to non-zero (reference to * HCI Error Codes) when security/authentication failed. */ void (*encrypt_change)(struct bt_l2cap_chan *chan, u8_t hci_status); /** @brief Channel alloc_buf callback * * If this callback is provided the channel will use it to allocate * buffers to store incoming data. * * @param chan The channel requesting a buffer. * * @return Allocated buffer. */ struct net_buf *(*alloc_buf)(struct bt_l2cap_chan *chan); /** @brief Channel recv callback * * @param chan The channel receiving data. * @param buf Buffer containing incoming data. * * @return 0 in case of success or negative value in case of error. * @return -EINPROGRESS in case where user has to confirm once the data * has been processed by calling * @ref bt_l2cap_chan_recv_complete passing back * the buffer received with its original user_data * which contains the number of segments/credits * used by the packet. */ int (*recv)(struct bt_l2cap_chan *chan, struct net_buf *buf); /** @brief Channel sent callback * * If this callback is provided it will be called whenever a SDU has * been completely sent. * * @param chan The channel which has sent data. */ void (*sent)(struct bt_l2cap_chan *chan); /** @brief Channel status callback * * If this callback is provided it will be called whenever the * channel status changes. * * @param chan The channel which status changed * @param status The channel status */ void (*status)(struct bt_l2cap_chan *chan, atomic_t *status); /* @brief Channel released callback * * If this callback is set it is called when the stack has release all * references to the channel object. */ void (*released)(struct bt_l2cap_chan *chan); }; /** @def BT_L2CAP_CHAN_SEND_RESERVE * @brief Headroom needed for outgoing buffers */ #define BT_L2CAP_CHAN_SEND_RESERVE (BT_BUF_RESERVE + 4 + 4) /** @brief L2CAP Server structure. */ struct bt_l2cap_server { /** @brief Server PSM. * * Possible values: * 0 A dynamic value will be auto-allocated when * bt_l2cap_server_register() is called. * * 0x0001-0x007f Standard, Bluetooth SIG-assigned fixed values. * * 0x0080-0x00ff Dynamically allocated. May be pre-set by the * application before server registration (not * recommended however), or auto-allocated by the * stack if the app gave 0 as the value. */ u16_t psm; /** Required minimim security level */ bt_security_t sec_level; /** @brief Server accept callback * * This callback is called whenever a new incoming connection requires * authorization. * * @param conn The connection that is requesting authorization * @param chan Pointer to received the allocated channel * * @return 0 in case of success or negative value in case of error. * @return -ENOMEM if no available space for new channel. * @return -EACCES if application did not authorize the connection. * @return -EPERM if encryption key size is too short. */ int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); sys_snode_t node; }; /** @brief Register L2CAP server. * * Register L2CAP server for a PSM, each new connection is authorized using * the accept() callback which in case of success shall allocate the channel * structure to be used by the new connection. * * For fixed, SIG-assigned PSMs (in the range 0x0001-0x007f) the PSM should * be assigned to server->psm before calling this API. For dynamic PSMs * (in the range 0x0080-0x00ff) server->psm may be pre-set to a given value * (this is however not recommended) or be left as 0, in which case upon * return a newly allocated value will have been assigned to it. For * dynamically allocated values the expectation is that it's exposed through * a GATT service, and that's how L2CAP clients discover how to connect to * the server. * * @param server Server structure. * * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_server_register(struct bt_l2cap_server *server); /** @brief Register L2CAP server on BR/EDR oriented connection. * * Register L2CAP server for a PSM, each new connection is authorized using * the accept() callback which in case of success shall allocate the channel * structure to be used by the new connection. * * @param server Server structure. * * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_br_server_register(struct bt_l2cap_server *server); /** @brief Connect Enhanced Credit Based L2CAP channels * * Connect up to 5 L2CAP channels by PSM, once the connection is completed * each channel connected() callback will be called. If the connection is * rejected disconnected() callback is called instead. * * @param conn Connection object. * @param chans Array of channel objects. * @param psm Channel PSM to connect to. * * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_ecred_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan **chans, u16_t psm); /** @brief Connect L2CAP channel * * Connect L2CAP channel by PSM, once the connection is completed channel * connected() callback will be called. If the connection is rejected * disconnected() callback is called instead. * Channel object passed (over an address of it) as second parameter shouldn't * be instantiated in application as standalone. Instead of, application should * create transport dedicated L2CAP objects, i.e. type of bt_l2cap_le_chan for * LE and/or type of bt_l2cap_br_chan for BR/EDR. Then pass to this API * the location (address) of bt_l2cap_chan type object which is a member * of both transport dedicated objects. * * @param conn Connection object. * @param chan Channel object. * @param psm Channel PSM to connect to. * * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm); /** @brief Disconnect L2CAP channel * * Disconnect L2CAP channel, if the connection is pending it will be * canceled and as a result the channel disconnected() callback is called. * Regarding to input parameter, to get details see reference description * to bt_l2cap_chan_connect() API above. * * @param chan Channel object. * * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan); /** @brief Send data to L2CAP channel * * Send data from buffer to the channel. If credits are not available, buf will * be queued and sent as and when credits are received from peer. * Regarding to first input parameter, to get details see reference description * to bt_l2cap_chan_connect() API above. * * @return Bytes sent in case of success or negative value in case of error. */ int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf); /** @brief Complete receiving L2CAP channel data * * Complete the reception of incoming data. This shall only be called if the * channel recv callback has returned -EINPROGRESS to process some incoming * data. The buffer shall contain the original user_data as that is used for * storing the credits/segments used by the packet. * * @param chan Channel object. * @param buf Buffer containing the data. * * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_L2CAP_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/l2cap.h
C
apache-2.0
13,892
/** @file * @brief Bluetooth RFCOMM handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_RFCOMM_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_RFCOMM_H_ /** * @brief RFCOMM * @defgroup bt_rfcomm RFCOMM * @ingroup bluetooth * @{ */ #include <bluetooth/buf.h> #include <bluetooth/conn.h> #ifdef __cplusplus extern "C" { #endif /* RFCOMM channels (1-30): pre-allocated for profiles to avoid conflicts */ enum { BT_RFCOMM_CHAN_HFP_HF = 1, BT_RFCOMM_CHAN_HFP_AG, BT_RFCOMM_CHAN_HSP_AG, BT_RFCOMM_CHAN_HSP_HS, BT_RFCOMM_CHAN_SPP, }; struct bt_rfcomm_dlc; /** @brief RFCOMM DLC operations structure. */ struct bt_rfcomm_dlc_ops { /** DLC connected callback * * If this callback is provided it will be called whenever the * connection completes. * * @param dlc The dlc that has been connected */ void (*connected)(struct bt_rfcomm_dlc *dlc); /** DLC disconnected callback * * If this callback is provided it will be called whenever the * dlc is disconnected, including when a connection gets * rejected or cancelled (both incoming and outgoing) * * @param dlc The dlc that has been Disconnected */ void (*disconnected)(struct bt_rfcomm_dlc *dlc); /** DLC recv callback * * @param dlc The dlc receiving data. * @param buf Buffer containing incoming data. */ void (*recv)(struct bt_rfcomm_dlc *dlc, struct net_buf *buf); }; /** @brief Role of RFCOMM session and dlc. Used only by internal APIs */ typedef enum bt_rfcomm_role { BT_RFCOMM_ROLE_ACCEPTOR, BT_RFCOMM_ROLE_INITIATOR } __packed bt_rfcomm_role_t; /** @brief RFCOMM DLC structure. */ struct bt_rfcomm_dlc { /* Response Timeout eXpired (RTX) timer */ struct k_delayed_work rtx_work; /* Queue for outgoing data */ struct kfifo tx_queue; /* TX credits, Reuse as a binary sem for MSC FC if CFC is not enabled */ struct k_sem tx_credits; struct bt_rfcomm_session *session; struct bt_rfcomm_dlc_ops *ops; struct bt_rfcomm_dlc *_next; bt_security_t required_sec_level; bt_rfcomm_role_t role; u16_t mtu; u8_t dlci; u8_t state; u8_t rx_credit; /* Stack & kernel data for TX thread */ struct k_thread tx_thread; BT_STACK(stack, 256); }; struct bt_rfcomm_server { /** Server Channel */ u8_t channel; /** Server accept callback * * This callback is called whenever a new incoming connection requires * authorization. * * @param conn The connection that is requesting authorization * @param dlc Pointer to received the allocated dlc * * @return 0 in case of success or negative value in case of error. */ int (*accept)(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc); struct bt_rfcomm_server *_next; }; /** @brief Register RFCOMM server * * Register RFCOMM server for a channel, each new connection is authorized * using the accept() callback which in case of success shall allocate the dlc * structure to be used by the new connection. * * @param server Server structure. * * @return 0 in case of success or negative value in case of error. */ int bt_rfcomm_server_register(struct bt_rfcomm_server *server); /** @brief Connect RFCOMM channel * * Connect RFCOMM dlc by channel, once the connection is completed dlc * connected() callback will be called. If the connection is rejected * disconnected() callback is called instead. * * @param conn Connection object. * @param dlc Dlc object. * @param channel Server channel to connect to. * * @return 0 in case of success or negative value in case of error. */ int bt_rfcomm_dlc_connect(struct bt_conn *conn, struct bt_rfcomm_dlc *dlc, u8_t channel); /** @brief Send data to RFCOMM * * Send data from buffer to the dlc. Length should be less than or equal to * mtu. * * @param dlc Dlc object. * @param buf Data buffer. * * @return Bytes sent in case of success or negative value in case of error. */ int bt_rfcomm_dlc_send(struct bt_rfcomm_dlc *dlc, struct net_buf *buf); /** @brief Disconnect RFCOMM dlc * * Disconnect RFCOMM dlc, if the connection is pending it will be * canceled and as a result the dlc disconnected() callback is called. * * @param dlc Dlc object. * * @return 0 in case of success or negative value in case of error. */ int bt_rfcomm_dlc_disconnect(struct bt_rfcomm_dlc *dlc); /** @brief Allocate the buffer from pool after reserving head room for RFCOMM, * L2CAP and ACL headers. * * @param pool Which pool to take the buffer from. * * @return New buffer. */ struct net_buf *bt_rfcomm_create_pdu(struct net_buf_pool *pool); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_RFCOMM_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/rfcomm.h
C
apache-2.0
4,866
/** @file * @brief Service Discovery Protocol handling. */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_SDP_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_SDP_H_ /** * @brief Service Discovery Protocol (SDP) * @defgroup bt_sdp Service Discovery Protocol (SDP) * @ingroup bluetooth * @{ */ #include <bluetooth/uuid.h> #include <bluetooth/conn.h> #ifdef __cplusplus extern "C" { #endif /* * All definitions are based on Bluetooth Assigned Numbers * of the Bluetooth Specification */ /* * Service class identifiers of standard services and service groups */ #define BT_SDP_SDP_SERVER_SVCLASS 0x1000 #define BT_SDP_BROWSE_GRP_DESC_SVCLASS 0x1001 #define BT_SDP_PUBLIC_BROWSE_GROUP 0x1002 #define BT_SDP_SERIAL_PORT_SVCLASS 0x1101 #define BT_SDP_LAN_ACCESS_SVCLASS 0x1102 #define BT_SDP_DIALUP_NET_SVCLASS 0x1103 #define BT_SDP_IRMC_SYNC_SVCLASS 0x1104 #define BT_SDP_OBEX_OBJPUSH_SVCLASS 0x1105 #define BT_SDP_OBEX_FILETRANS_SVCLASS 0x1106 #define BT_SDP_IRMC_SYNC_CMD_SVCLASS 0x1107 #define BT_SDP_HEADSET_SVCLASS 0x1108 #define BT_SDP_CORDLESS_TELEPHONY_SVCLASS 0x1109 #define BT_SDP_AUDIO_SOURCE_SVCLASS 0x110a #define BT_SDP_AUDIO_SINK_SVCLASS 0x110b #define BT_SDP_AV_REMOTE_TARGET_SVCLASS 0x110c #define BT_SDP_ADVANCED_AUDIO_SVCLASS 0x110d #define BT_SDP_AV_REMOTE_SVCLASS 0x110e #define BT_SDP_AV_REMOTE_CONTROLLER_SVCLASS 0x110f #define BT_SDP_INTERCOM_SVCLASS 0x1110 #define BT_SDP_FAX_SVCLASS 0x1111 #define BT_SDP_HEADSET_AGW_SVCLASS 0x1112 #define BT_SDP_WAP_SVCLASS 0x1113 #define BT_SDP_WAP_CLIENT_SVCLASS 0x1114 #define BT_SDP_PANU_SVCLASS 0x1115 #define BT_SDP_NAP_SVCLASS 0x1116 #define BT_SDP_GN_SVCLASS 0x1117 #define BT_SDP_DIRECT_PRINTING_SVCLASS 0x1118 #define BT_SDP_REFERENCE_PRINTING_SVCLASS 0x1119 #define BT_SDP_IMAGING_SVCLASS 0x111a #define BT_SDP_IMAGING_RESPONDER_SVCLASS 0x111b #define BT_SDP_IMAGING_ARCHIVE_SVCLASS 0x111c #define BT_SDP_IMAGING_REFOBJS_SVCLASS 0x111d #define BT_SDP_HANDSFREE_SVCLASS 0x111e #define BT_SDP_HANDSFREE_AGW_SVCLASS 0x111f #define BT_SDP_DIRECT_PRT_REFOBJS_SVCLASS 0x1120 #define BT_SDP_REFLECTED_UI_SVCLASS 0x1121 #define BT_SDP_BASIC_PRINTING_SVCLASS 0x1122 #define BT_SDP_PRINTING_STATUS_SVCLASS 0x1123 #define BT_SDP_HID_SVCLASS 0x1124 #define BT_SDP_HCR_SVCLASS 0x1125 #define BT_SDP_HCR_PRINT_SVCLASS 0x1126 #define BT_SDP_HCR_SCAN_SVCLASS 0x1127 #define BT_SDP_CIP_SVCLASS 0x1128 #define BT_SDP_VIDEO_CONF_GW_SVCLASS 0x1129 #define BT_SDP_UDI_MT_SVCLASS 0x112a #define BT_SDP_UDI_TA_SVCLASS 0x112b #define BT_SDP_AV_SVCLASS 0x112c #define BT_SDP_SAP_SVCLASS 0x112d #define BT_SDP_PBAP_PCE_SVCLASS 0x112e #define BT_SDP_PBAP_PSE_SVCLASS 0x112f #define BT_SDP_PBAP_SVCLASS 0x1130 #define BT_SDP_MAP_MSE_SVCLASS 0x1132 #define BT_SDP_MAP_MCE_SVCLASS 0x1133 #define BT_SDP_MAP_SVCLASS 0x1134 #define BT_SDP_GNSS_SVCLASS 0x1135 #define BT_SDP_GNSS_SERVER_SVCLASS 0x1136 #define BT_SDP_MPS_SC_SVCLASS 0x113a #define BT_SDP_MPS_SVCLASS 0x113b #define BT_SDP_PNP_INFO_SVCLASS 0x1200 #define BT_SDP_GENERIC_NETWORKING_SVCLASS 0x1201 #define BT_SDP_GENERIC_FILETRANS_SVCLASS 0x1202 #define BT_SDP_GENERIC_AUDIO_SVCLASS 0x1203 #define BT_SDP_GENERIC_TELEPHONY_SVCLASS 0x1204 #define BT_SDP_UPNP_SVCLASS 0x1205 #define BT_SDP_UPNP_IP_SVCLASS 0x1206 #define BT_SDP_UPNP_PAN_SVCLASS 0x1300 #define BT_SDP_UPNP_LAP_SVCLASS 0x1301 #define BT_SDP_UPNP_L2CAP_SVCLASS 0x1302 #define BT_SDP_VIDEO_SOURCE_SVCLASS 0x1303 #define BT_SDP_VIDEO_SINK_SVCLASS 0x1304 #define BT_SDP_VIDEO_DISTRIBUTION_SVCLASS 0x1305 #define BT_SDP_HDP_SVCLASS 0x1400 #define BT_SDP_HDP_SOURCE_SVCLASS 0x1401 #define BT_SDP_HDP_SINK_SVCLASS 0x1402 #define BT_SDP_GENERIC_ACCESS_SVCLASS 0x1800 #define BT_SDP_GENERIC_ATTRIB_SVCLASS 0x1801 #define BT_SDP_APPLE_AGENT_SVCLASS 0x2112 /* * Attribute identifier codes */ #define BT_SDP_SERVER_RECORD_HANDLE 0x0000 /* * Possible values for attribute-id are listed below. * See SDP Spec, section "Service Attribute Definitions" for more details. */ #define BT_SDP_ATTR_RECORD_HANDLE 0x0000 #define BT_SDP_ATTR_SVCLASS_ID_LIST 0x0001 #define BT_SDP_ATTR_RECORD_STATE 0x0002 #define BT_SDP_ATTR_SERVICE_ID 0x0003 #define BT_SDP_ATTR_PROTO_DESC_LIST 0x0004 #define BT_SDP_ATTR_BROWSE_GRP_LIST 0x0005 #define BT_SDP_ATTR_LANG_BASE_ATTR_ID_LIST 0x0006 #define BT_SDP_ATTR_SVCINFO_TTL 0x0007 #define BT_SDP_ATTR_SERVICE_AVAILABILITY 0x0008 #define BT_SDP_ATTR_PROFILE_DESC_LIST 0x0009 #define BT_SDP_ATTR_DOC_URL 0x000a #define BT_SDP_ATTR_CLNT_EXEC_URL 0x000b #define BT_SDP_ATTR_ICON_URL 0x000c #define BT_SDP_ATTR_ADD_PROTO_DESC_LIST 0x000d #define BT_SDP_ATTR_GROUP_ID 0x0200 #define BT_SDP_ATTR_IP_SUBNET 0x0200 #define BT_SDP_ATTR_VERSION_NUM_LIST 0x0200 #define BT_SDP_ATTR_SUPPORTED_FEATURES_LIST 0x0200 #define BT_SDP_ATTR_GOEP_L2CAP_PSM 0x0200 #define BT_SDP_ATTR_SVCDB_STATE 0x0201 #define BT_SDP_ATTR_MPSD_SCENARIOS 0x0200 #define BT_SDP_ATTR_MPMD_SCENARIOS 0x0201 #define BT_SDP_ATTR_MPS_DEPENDENCIES 0x0202 #define BT_SDP_ATTR_SERVICE_VERSION 0x0300 #define BT_SDP_ATTR_EXTERNAL_NETWORK 0x0301 #define BT_SDP_ATTR_SUPPORTED_DATA_STORES_LIST 0x0301 #define BT_SDP_ATTR_DATA_EXCHANGE_SPEC 0x0301 #define BT_SDP_ATTR_NETWORK 0x0301 #define BT_SDP_ATTR_FAX_CLASS1_SUPPORT 0x0302 #define BT_SDP_ATTR_REMOTE_AUDIO_VOLUME_CONTROL 0x0302 #define BT_SDP_ATTR_MCAP_SUPPORTED_PROCEDURES 0x0302 #define BT_SDP_ATTR_FAX_CLASS20_SUPPORT 0x0303 #define BT_SDP_ATTR_SUPPORTED_FORMATS_LIST 0x0303 #define BT_SDP_ATTR_FAX_CLASS2_SUPPORT 0x0304 #define BT_SDP_ATTR_AUDIO_FEEDBACK_SUPPORT 0x0305 #define BT_SDP_ATTR_NETWORK_ADDRESS 0x0306 #define BT_SDP_ATTR_WAP_GATEWAY 0x0307 #define BT_SDP_ATTR_HOMEPAGE_URL 0x0308 #define BT_SDP_ATTR_WAP_STACK_TYPE 0x0309 #define BT_SDP_ATTR_SECURITY_DESC 0x030a #define BT_SDP_ATTR_NET_ACCESS_TYPE 0x030b #define BT_SDP_ATTR_MAX_NET_ACCESSRATE 0x030c #define BT_SDP_ATTR_IP4_SUBNET 0x030d #define BT_SDP_ATTR_IP6_SUBNET 0x030e #define BT_SDP_ATTR_SUPPORTED_CAPABILITIES 0x0310 #define BT_SDP_ATTR_SUPPORTED_FEATURES 0x0311 #define BT_SDP_ATTR_SUPPORTED_FUNCTIONS 0x0312 #define BT_SDP_ATTR_TOTAL_IMAGING_DATA_CAPACITY 0x0313 #define BT_SDP_ATTR_SUPPORTED_REPOSITORIES 0x0314 #define BT_SDP_ATTR_MAS_INSTANCE_ID 0x0315 #define BT_SDP_ATTR_SUPPORTED_MESSAGE_TYPES 0x0316 #define BT_SDP_ATTR_PBAP_SUPPORTED_FEATURES 0x0317 #define BT_SDP_ATTR_MAP_SUPPORTED_FEATURES 0x0317 #define BT_SDP_ATTR_SPECIFICATION_ID 0x0200 #define BT_SDP_ATTR_VENDOR_ID 0x0201 #define BT_SDP_ATTR_PRODUCT_ID 0x0202 #define BT_SDP_ATTR_VERSION 0x0203 #define BT_SDP_ATTR_PRIMARY_RECORD 0x0204 #define BT_SDP_ATTR_VENDOR_ID_SOURCE 0x0205 #define BT_SDP_ATTR_HID_DEVICE_RELEASE_NUMBER 0x0200 #define BT_SDP_ATTR_HID_PARSER_VERSION 0x0201 #define BT_SDP_ATTR_HID_DEVICE_SUBCLASS 0x0202 #define BT_SDP_ATTR_HID_COUNTRY_CODE 0x0203 #define BT_SDP_ATTR_HID_VIRTUAL_CABLE 0x0204 #define BT_SDP_ATTR_HID_RECONNECT_INITIATE 0x0205 #define BT_SDP_ATTR_HID_DESCRIPTOR_LIST 0x0206 #define BT_SDP_ATTR_HID_LANG_ID_BASE_LIST 0x0207 #define BT_SDP_ATTR_HID_SDP_DISABLE 0x0208 #define BT_SDP_ATTR_HID_BATTERY_POWER 0x0209 #define BT_SDP_ATTR_HID_REMOTE_WAKEUP 0x020a #define BT_SDP_ATTR_HID_PROFILE_VERSION 0x020b #define BT_SDP_ATTR_HID_SUPERVISION_TIMEOUT 0x020c #define BT_SDP_ATTR_HID_NORMALLY_CONNECTABLE 0x020d #define BT_SDP_ATTR_HID_BOOT_DEVICE 0x020e /* * These identifiers are based on the SDP spec stating that * "base attribute id of the primary (universal) language must be 0x0100" * * Other languages should have their own offset; e.g.: * #define XXXLangBase yyyy * #define AttrServiceName_XXX 0x0000+XXXLangBase */ #define BT_SDP_PRIMARY_LANG_BASE 0x0100 #define BT_SDP_ATTR_SVCNAME_PRIMARY (0x0000 + BT_SDP_PRIMARY_LANG_BASE) #define BT_SDP_ATTR_SVCDESC_PRIMARY (0x0001 + BT_SDP_PRIMARY_LANG_BASE) #define BT_SDP_ATTR_PROVNAME_PRIMARY (0x0002 + BT_SDP_PRIMARY_LANG_BASE) /* * The Data representation in SDP PDUs (pps 339, 340 of BT SDP Spec) * These are the exact data type+size descriptor values * that go into the PDU buffer. * * The datatype (leading 5bits) + size descriptor (last 3 bits) * is 8 bits. The size descriptor is critical to extract the * right number of bytes for the data value from the PDU. * * For most basic types, the datatype+size descriptor is * straightforward. However for constructed types and strings, * the size of the data is in the next "n" bytes following the * 8 bits (datatype+size) descriptor. Exactly what the "n" is * specified in the 3 bits of the data size descriptor. * * TextString and URLString can be of size 2^{8, 16, 32} bytes * DataSequence and DataSequenceAlternates can be of size 2^{8, 16, 32} * The size are computed post-facto in the API and are not known apriori */ #define BT_SDP_DATA_NIL 0x00 #define BT_SDP_UINT8 0x08 #define BT_SDP_UINT16 0x09 #define BT_SDP_UINT32 0x0a #define BT_SDP_UINT64 0x0b #define BT_SDP_UINT128 0x0c #define BT_SDP_INT8 0x10 #define BT_SDP_INT16 0x11 #define BT_SDP_INT32 0x12 #define BT_SDP_INT64 0x13 #define BT_SDP_INT128 0x14 #define BT_SDP_UUID_UNSPEC 0x18 #define BT_SDP_UUID16 0x19 #define BT_SDP_UUID32 0x1a #define BT_SDP_UUID128 0x1c #define BT_SDP_TEXT_STR_UNSPEC 0x20 #define BT_SDP_TEXT_STR8 0x25 #define BT_SDP_TEXT_STR16 0x26 #define BT_SDP_TEXT_STR32 0x27 #define BT_SDP_BOOL 0x28 #define BT_SDP_SEQ_UNSPEC 0x30 #define BT_SDP_SEQ8 0x35 #define BT_SDP_SEQ16 0x36 #define BT_SDP_SEQ32 0x37 #define BT_SDP_ALT_UNSPEC 0x38 #define BT_SDP_ALT8 0x3d #define BT_SDP_ALT16 0x3e #define BT_SDP_ALT32 0x3f #define BT_SDP_URL_STR_UNSPEC 0x40 #define BT_SDP_URL_STR8 0x45 #define BT_SDP_URL_STR16 0x46 #define BT_SDP_URL_STR32 0x47 #define BT_SDP_TYPE_DESC_MASK 0xf8 #define BT_SDP_SIZE_DESC_MASK 0x07 #define BT_SDP_SIZE_INDEX_OFFSET 5 /** @brief SDP Generic Data Element Value. */ struct bt_sdp_data_elem { u8_t type; bt_u32_t data_size; bt_u32_t total_size; const void *data; }; /** @brief SDP Attribute Value. */ struct bt_sdp_attribute { u16_t id; /* Attribute ID */ struct bt_sdp_data_elem val; /* Attribute data */ }; /** @brief SDP Service Record Value. */ struct bt_sdp_record { bt_u32_t handle; /* Redundant, for quick ref */ struct bt_sdp_attribute *attrs; /* Base addr of attr array */ size_t attr_count; /* Number of attributes */ u8_t index; /* Index of the record in LL */ struct bt_sdp_record *next; }; /* * --------------------------------------------------- ------------------ * | Service Hdl | Attr list ptr | Attr count | Next | -> | Service Hdl | ... * --------------------------------------------------- ------------------ */ /** @def BT_SDP_ARRAY_8 * @brief Declare an array of 8-bit elements in an attribute. */ #define BT_SDP_ARRAY_8(...) ((u8_t[]) {__VA_ARGS__}) /** @def BT_SDP_ARRAY_16 * @brief Declare an array of 16-bit elements in an attribute. */ #define BT_SDP_ARRAY_16(...) ((u16_t[]) {__VA_ARGS__}) /** @def BT_SDP_ARRAY_32 * @brief Declare an array of 32-bit elements in an attribute. */ #define BT_SDP_ARRAY_32(...) ((bt_u32_t[]) {__VA_ARGS__}) /** @def BT_SDP_TYPE_SIZE * @brief Declare a fixed-size data element header. * * @param _type Data element header containing type and size descriptors. */ #define BT_SDP_TYPE_SIZE(_type) .type = _type, \ .data_size = BIT(_type & BT_SDP_SIZE_DESC_MASK), \ .total_size = BIT(_type & BT_SDP_SIZE_DESC_MASK) + 1 /** @def BT_SDP_TYPE_SIZE_VAR * @brief Declare a variable-size data element header. * * @param _type Data element header containing type and size descriptors. * @param _size The actual size of the data. */ #define BT_SDP_TYPE_SIZE_VAR(_type, _size) .type = _type, \ .data_size = _size, \ .total_size = BIT((_type & BT_SDP_SIZE_DESC_MASK) - \ BT_SDP_SIZE_INDEX_OFFSET) + _size + 1 /** @def BT_SDP_DATA_ELEM_LIST * @brief Declare a list of data elements. */ #define BT_SDP_DATA_ELEM_LIST(...) ((struct bt_sdp_data_elem[]) {__VA_ARGS__}) /** @def BT_SDP_NEW_SERVICE * @brief SDP New Service Record Declaration Macro. * * Helper macro to declare a new service record. * Default attributes: Record Handle, Record State, * Language Base, Root Browse Group * */ #define BT_SDP_NEW_SERVICE \ { \ BT_SDP_ATTR_RECORD_HANDLE, \ { BT_SDP_TYPE_SIZE(BT_SDP_UINT32), BT_SDP_ARRAY_32(0) } \ }, \ { \ BT_SDP_ATTR_RECORD_STATE, \ { BT_SDP_TYPE_SIZE(BT_SDP_UINT32), BT_SDP_ARRAY_32(0) } \ }, \ { \ BT_SDP_ATTR_LANG_BASE_ATTR_ID_LIST, \ { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 9), \ BT_SDP_DATA_ELEM_LIST( \ { BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_8('n', 'e') }, \ { BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(106) }, \ { BT_SDP_TYPE_SIZE(BT_SDP_UINT16), \ BT_SDP_ARRAY_16(BT_SDP_PRIMARY_LANG_BASE) } \ ), \ } \ }, \ { \ BT_SDP_ATTR_BROWSE_GRP_LIST, \ { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), \ BT_SDP_DATA_ELEM_LIST( \ { BT_SDP_TYPE_SIZE(BT_SDP_UUID16), \ BT_SDP_ARRAY_16(BT_SDP_PUBLIC_BROWSE_GROUP) }, \ ), \ } \ } /** @def BT_SDP_LIST * @brief Generic SDP List Attribute Declaration Macro. * * Helper macro to declare a list attribute. * * @param _att_id List Attribute ID. * @param _data_elem_seq Data element sequence for the list. * @param _type_size SDP type and size descriptor. */ #define BT_SDP_LIST(_att_id, _type_size, _data_elem_seq) \ { \ _att_id, { _type_size, _data_elem_seq } \ } /** @def BT_SDP_SERVICE_ID * @brief SDP Service ID Attribute Declaration Macro. * * Helper macro to declare a service ID attribute. * * @param _uuid Service ID 16bit UUID. */ #define BT_SDP_SERVICE_ID(_uuid) \ { \ BT_SDP_ATTR_SERVICE_ID, \ { BT_SDP_TYPE_SIZE(BT_SDP_UUID16), &((struct bt_uuid_16) _uuid) } \ } /** @def BT_SDP_SERVICE_NAME * @brief SDP Name Attribute Declaration Macro. * * Helper macro to declare a service name attribute. * * @param _name Service name as a string (up to 256 chars). */ #define BT_SDP_SERVICE_NAME(_name) \ { \ BT_SDP_ATTR_SVCNAME_PRIMARY, \ { BT_SDP_TYPE_SIZE_VAR(BT_SDP_TEXT_STR8, (sizeof(_name)-1)), _name } \ } /** @def BT_SDP_SUPPORTED_FEATURES * @brief SDP Supported Features Attribute Declaration Macro. * * Helper macro to declare supported features of a profile/protocol. * * @param _features Feature mask as 16bit unsigned integer. */ #define BT_SDP_SUPPORTED_FEATURES(_features) \ { \ BT_SDP_ATTR_SUPPORTED_FEATURES, \ { BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(_features) } \ } /** @def BT_SDP_RECORD * @brief SDP Service Declaration Macro. * * Helper macro to declare a service. * * @param _attrs List of attributes for the service record. */ #define BT_SDP_RECORD(_attrs) \ { \ .attrs = _attrs, \ .attr_count = ARRAY_SIZE((_attrs)), \ } /* Server API */ /** @brief Register a Service Record. * * Register a Service Record. Applications can make use of * macros such as BT_SDP_DECLARE_SERVICE, BT_SDP_LIST, * BT_SDP_SERVICE_ID, BT_SDP_SERVICE_NAME, etc. * A service declaration must start with BT_SDP_NEW_SERVICE. * * @param service Service record declared using BT_SDP_DECLARE_SERVICE. * * @return 0 in case of success or negative value in case of error. */ int bt_sdp_register_service(struct bt_sdp_record *service); /* Client API */ /** @brief Generic SDP Client Query Result data holder */ struct bt_sdp_client_result { /* buffer containing unparsed SDP record result for given UUID */ struct net_buf *resp_buf; /* flag pointing that there are more result chunks for given UUID */ bool next_record_hint; /* Reference to UUID object on behalf one discovery was started */ const struct bt_uuid *uuid; }; /** @brief Helper enum to be used as return value of bt_sdp_discover_func_t. * The value informs the caller to perform further pending actions or stop them. */ enum { BT_SDP_DISCOVER_UUID_STOP = 0, BT_SDP_DISCOVER_UUID_CONTINUE, }; /** @typedef bt_sdp_discover_func_t * * @brief Callback type reporting to user that there is a resolved result * on remote for given UUID and the result record buffer can be used by user * for further inspection. * * A function of this type is given by the user to the bt_sdp_discover_params * object. It'll be called on each valid record discovery completion for given * UUID. When UUID resolution gives back no records then NULL is passed * to the user. Otherwise user can get valid record(s) and then the internal * hint 'next record' is set to false saying the UUID resolution is complete or * the hint can be set by caller to true meaning that next record is available * for given UUID. * The returned function value allows the user to control retrieving follow-up * resolved records if any. If the user doesn't want to read more resolved * records for given UUID since current record data fulfills its requirements * then should return BT_SDP_DISCOVER_UUID_STOP. Otherwise returned value means * more subcall iterations are allowable. * * @param conn Connection object identifying connection to queried remote. * @param result Object pointing to logical unparsed SDP record collected on * base of response driven by given UUID. * * @return BT_SDP_DISCOVER_UUID_STOP in case of no more need to read next * record data and continue discovery for given UUID. By returning * BT_SDP_DISCOVER_UUID_CONTINUE user allows this discovery continuation. */ typedef u8_t (*bt_sdp_discover_func_t) (struct bt_conn *conn, struct bt_sdp_client_result *result); /** @brief Main user structure used in SDP discovery of remote. */ struct bt_sdp_discover_params { sys_snode_t _node; /** UUID (service) to be discovered on remote SDP entity */ const struct bt_uuid *uuid; /** Discover callback to be called on resolved SDP record */ bt_sdp_discover_func_t func; /** Memory buffer enabled by user for SDP query results */ struct net_buf_pool *pool; }; /** @brief Allows user to start SDP discovery session. * * The function performs SDP service discovery on remote server driven by user * delivered discovery parameters. Discovery session is made as soon as * no SDP transaction is ongoing between peers and if any then this one * is queued to be processed at discovery completion of previous one. * On the service discovery completion the callback function will be * called to get feedback to user about findings. * * @param conn Object identifying connection to remote. * @param params SDP discovery parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_sdp_discover(struct bt_conn *conn, const struct bt_sdp_discover_params *params); /** @brief Release waiting SDP discovery request. * * It can cancel valid waiting SDP client request identified by SDP discovery * parameters object. * * @param conn Object identifying connection to remote. * @param params SDP discovery parameters. * * @return 0 in case of success or negative value in case of error. */ int bt_sdp_discover_cancel(struct bt_conn *conn, const struct bt_sdp_discover_params *params); /* Helper types & functions for SDP client to get essential data from server */ /** @brief Protocols to be asked about specific parameters */ enum bt_sdp_proto { BT_SDP_PROTO_RFCOMM = 0x0003, BT_SDP_PROTO_L2CAP = 0x0100, }; /** @brief Give to user parameter value related to given stacked protocol UUID. * * API extracts specific parameter associated with given protocol UUID * available in Protocol Descriptor List attribute. * * @param buf Original buffered raw record data. * @param proto Known protocol to be checked like RFCOMM or L2CAP. * @param param On success populated by found parameter value. * * @return 0 on success when specific parameter associated with given protocol * value is found, or negative if error occurred during processing. */ int bt_sdp_get_proto_param(const struct net_buf *buf, enum bt_sdp_proto proto, u16_t *param); /** @brief Get profile version. * * Helper API extracting remote profile version number. To get it proper * generic profile parameter needs to be selected usually listed in SDP * Interoperability Requirements section for given profile specification. * * @param buf Original buffered raw record data. * @param profile Profile family identifier the profile belongs. * @param version On success populated by found version number. * * @return 0 on success, negative value if error occurred during processing. */ int bt_sdp_get_profile_version(const struct net_buf *buf, u16_t profile, u16_t *version); /** @brief Get SupportedFeatures attribute value * * Allows if exposed by remote retrieve SupportedFeature attribute. * * @param buf Buffer holding original raw record data from remote. * @param features On success object to be populated with SupportedFeature * mask. * * @return 0 on success if feature found and valid, negative in case any error */ int bt_sdp_get_features(const struct net_buf *buf, u16_t *features); #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_SDP_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/sdp.h
C
apache-2.0
22,925
/** * @file testing.h * @brief Internal API for Bluetooth testing. */ /* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_TESTING_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_TESTING_H_ #if defined(CONFIG_BT_MESH) #include <bluetooth/mesh.h> #endif /* CONFIG_BT_MESH */ /** * @brief Bluetooth testing * @defgroup bt_test_cb Bluetooth testing callbacks * @ingroup bluetooth * @{ */ #ifdef __cplusplus extern "C" { #endif /** @brief Bluetooth Testing callbacks structure. * * Callback structure to be used for Bluetooth testing purposes. * Allows access to Bluetooth stack internals, not exposed by public API. */ struct bt_test_cb { #if defined(CONFIG_BT_MESH) void (*mesh_net_recv)(u8_t ttl, u8_t ctl, u16_t src, u16_t dst, const void *payload, size_t payload_len); void (*mesh_model_bound)(u16_t addr, struct bt_mesh_model *model, u16_t key_idx); void (*mesh_model_unbound)(u16_t addr, struct bt_mesh_model *model, u16_t key_idx); void (*mesh_prov_invalid_bearer)(u8_t opcode); void (*mesh_trans_incomp_timer_exp)(void); #endif /* CONFIG_BT_MESH */ sys_snode_t node; }; /** Register callbacks for Bluetooth testing purposes * * @param cb bt_test_cb callback structure */ void bt_test_cb_register(struct bt_test_cb *cb); /** Unregister callbacks for Bluetooth testing purposes * * @param cb bt_test_cb callback structure */ void bt_test_cb_unregister(struct bt_test_cb *cb); /** Send Friend Subscription List Add message. * * Used by Low Power node to send the group address for which messages are to * be stored by Friend node. * * @param group Group address * * @return Zero on success or (negative) error code otherwise. */ int bt_test_mesh_lpn_group_add(u16_t group); /** Send Friend Subscription List Remove message. * * Used by Low Power node to remove the group addresses from Friend node * subscription list. Messages sent to those addresses will not be stored * by Friend node. * * @param groups Group addresses * @param groups_count Group addresses count * * @return Zero on success or (negative) error code otherwise. */ int bt_test_mesh_lpn_group_remove(u16_t *groups, size_t groups_count); /** Clear replay protection list cache. * * @return Zero on success or (negative) error code otherwise. */ int bt_test_mesh_rpl_clear(void); /** * @} */ #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_BLUETOOTH_TESTING_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/testing.h
C
apache-2.0
2,491
/** @file * @brief Bluetooth UUID handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_UUID_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_UUID_H_ /** * @brief UUIDs * @defgroup bt_uuid UUIDs * @ingroup bluetooth * @{ */ #include <misc/util.h> #ifdef __cplusplus extern "C" { #endif /** @brief Bluetooth UUID types */ enum { BT_UUID_TYPE_16, BT_UUID_TYPE_32, BT_UUID_TYPE_128, }; /** @brief This is a 'tentative' type and should be used as a pointer only */ struct bt_uuid { u8_t type; }; struct bt_uuid_16 { struct bt_uuid uuid; u16_t val; }; struct bt_uuid_32 { struct bt_uuid uuid; bt_u32_t val; }; struct bt_uuid_128 { struct bt_uuid uuid; u8_t val[16]; }; #define BT_UUID_INIT_16(value) \ { \ .uuid = { BT_UUID_TYPE_16 }, \ .val = (value), \ } #define BT_UUID_INIT_32(value) \ { \ .uuid = { BT_UUID_TYPE_32 }, \ .val = (value), \ } #define BT_UUID_INIT_128(value...) \ { \ .uuid = { BT_UUID_TYPE_128 }, \ .val = { value }, \ } #define BT_UUID_DECLARE_16(value) \ ((struct bt_uuid *) ((struct bt_uuid_16[]) {BT_UUID_INIT_16(value)})) #define BT_UUID_DECLARE_32(value) \ ((struct bt_uuid *) ((struct bt_uuid_32[]) {BT_UUID_INIT_32(value)})) #define BT_UUID_DECLARE_128(value...) \ ((struct bt_uuid *) ((struct bt_uuid_128[]) {BT_UUID_INIT_128(value)})) #define BT_UUID_16(__u) CONTAINER_OF(__u, struct bt_uuid_16, uuid) #define BT_UUID_32(__u) CONTAINER_OF(__u, struct bt_uuid_32, uuid) #define BT_UUID_128(__u) CONTAINER_OF(__u, struct bt_uuid_128, uuid) /** * @brief Encode 128 bit UUID into an array values * * Helper macro to initialize a 128-bit UUID value from the UUID format. * Can be combined with BT_UUID_DECLARE_128 to declare a 128-bit UUID from * the readable form of UUIDs. * * Example for how to declare the UUID `6E400001-B5A3-F393-E0A9-E50E24DCCA9E` * * @code * BT_UUID_DECLARE_128( * BT_UUID_128_ENCODE(0x6E400001, 0xB5A3, 0xF393, 0xE0A9, 0xE50E24DCCA9E)) * @endcode * * Just replace the hyphen by the comma and add `0x` prefixes. * * @param w32 First part of the UUID (32 bits) * @param w1 Second part of the UUID (16 bits) * @param w2 Third part of the UUID (16 bits) * @param w3 Fourth part of the UUID (16 bits) * @param w48 Fifth part of the UUID (48 bits) * * @return The comma separated values for UUID 128 initializer that * may be used directly as an argument for * @ref BT_UUID_INIT_128 or @ref BT_UUID_DECLARE_128 */ #define BT_UUID_128_ENCODE(w32, w1, w2, w3, w48) \ (((w48) >> 0) & 0xFF), \ (((w48) >> 8) & 0xFF), \ (((w48) >> 16) & 0xFF), \ (((w48) >> 24) & 0xFF), \ (((w48) >> 32) & 0xFF), \ (((w48) >> 40) & 0xFF), \ (((w3) >> 0) & 0xFF), \ (((w3) >> 8) & 0xFF), \ (((w2) >> 0) & 0xFF), \ (((w2) >> 8) & 0xFF), \ (((w1) >> 0) & 0xFF), \ (((w1) >> 8) & 0xFF), \ (((w32) >> 0) & 0xFF), \ (((w32) >> 8) & 0xFF), \ (((w32) >> 16) & 0xFF), \ (((w32) >> 24) & 0xFF) /** @def BT_UUID_STR_LEN * * @brief Recommended length of user string buffer for Bluetooth UUID. * * @details The recommended length guarantee the output of UUID * conversion will not lose valuable information about the UUID being * processed. If the length of the UUID is known the string can be shorter. */ #define BT_UUID_STR_LEN 37 /** @def BT_UUID_GAP * @brief Generic Access */ #define BT_UUID_GAP BT_UUID_DECLARE_16(0x1800) /** @def BT_UUID_GATT * @brief Generic Attribute */ #define BT_UUID_GATT BT_UUID_DECLARE_16(0x1801) /** @def BT_UUID_CTS * @brief Current Time Service */ #define BT_UUID_CTS BT_UUID_DECLARE_16(0x1805) /** @def BT_UUID_HTS * @brief Health Thermometer Service */ #define BT_UUID_HTS BT_UUID_DECLARE_16(0x1809) /** @def BT_UUID_DIS * @brief Device Information Service */ #define BT_UUID_DIS BT_UUID_DECLARE_16(0x180a) /** @def BT_UUID_HRS * @brief Heart Rate Service */ #define BT_UUID_HRS BT_UUID_DECLARE_16(0x180d) /** @def BT_UUID_BAS * @brief Battery Service */ #define BT_UUID_BAS BT_UUID_DECLARE_16(0x180f) /** @def BT_UUID_HIDS * @brief HID Service */ #define BT_UUID_HIDS BT_UUID_DECLARE_16(0x1812) /** @def BT_UUID_CSC * @brief Cycling Speed and Cadence Service */ #define BT_UUID_CSC BT_UUID_DECLARE_16(0x1816) /** @def BT_UUID_ESS * @brief Environmental Sensing Service */ #define BT_UUID_ESS BT_UUID_DECLARE_16(0x181a) /** @def BT_UUID_IPSS * @brief IP Support Service */ #define BT_UUID_IPSS BT_UUID_DECLARE_16(0x1820) /** @def BT_UUID_OTS * @brief Object Transfer Service */ #define BT_UUID_OTS BT_UUID_DECLARE_16(0x1825) /** @def BT_UUID_MESH_PROV * @brief Mesh Provisioning Service */ #define BT_UUID_MESH_PROV BT_UUID_DECLARE_16(0x1827) /** @def BT_UUID_MESH_PROXY * @brief Mesh Proxy Service */ #define BT_UUID_MESH_PROXY BT_UUID_DECLARE_16(0x1828) /** @def BT_UUID_GATT_PRIMARY * @brief GATT Primary Service */ #define BT_UUID_GATT_PRIMARY BT_UUID_DECLARE_16(0x2800) /** @def BT_UUID_GATT_SECONDARY * @brief GATT Secondary Service */ #define BT_UUID_GATT_SECONDARY BT_UUID_DECLARE_16(0x2801) /** @def BT_UUID_GATT_INCLUDE * @brief GATT Include Service */ #define BT_UUID_GATT_INCLUDE BT_UUID_DECLARE_16(0x2802) /** @def BT_UUID_GATT_CHRC * @brief GATT Characteristic */ #define BT_UUID_GATT_CHRC BT_UUID_DECLARE_16(0x2803) /** @def BT_UUID_GATT_CEP * @brief GATT Characteristic Extended Properties */ #define BT_UUID_GATT_CEP BT_UUID_DECLARE_16(0x2900) /** @def BT_UUID_GATT_CUD * @brief GATT Characteristic User Description */ #define BT_UUID_GATT_CUD BT_UUID_DECLARE_16(0x2901) /** @def BT_UUID_GATT_CCC * @brief GATT Client Characteristic Configuration */ #define BT_UUID_GATT_CCC BT_UUID_DECLARE_16(0x2902) /** @def BT_UUID_GATT_SCC * @brief GATT Server Characteristic Configuration */ #define BT_UUID_GATT_SCC BT_UUID_DECLARE_16(0x2903) /** @def BT_UUID_GATT_CPF * @brief GATT Characteristic Presentation Format */ #define BT_UUID_GATT_CPF BT_UUID_DECLARE_16(0x2904) /** @def BT_UUID_VALID_RANGE * @brief Valid Range Descriptor */ #define BT_UUID_VALID_RANGE BT_UUID_DECLARE_16(0x2906) /** @def BT_UUID_HIDS_EXT_REPORT * @brief HID External Report Descriptor */ #define BT_UUID_HIDS_EXT_REPORT BT_UUID_DECLARE_16(0x2907) /** @def BT_UUID_HIDS_REPORT_REF * @brief HID Report Reference Descriptor */ #define BT_UUID_HIDS_REPORT_REF BT_UUID_DECLARE_16(0x2908) /** @def BT_UUID_ES_CONFIGURATION * @brief Environmental Sensing Configuration Descriptor */ #define BT_UUID_ES_CONFIGURATION BT_UUID_DECLARE_16(0x290b) /** @def BT_UUID_ES_MEASUREMENT * @brief Environmental Sensing Measurement Descriptor */ #define BT_UUID_ES_MEASUREMENT BT_UUID_DECLARE_16(0x290c) /** @def BT_UUID_ES_TRIGGER_SETTING * @brief Environmental Sensing Trigger Setting Descriptor */ #define BT_UUID_ES_TRIGGER_SETTING BT_UUID_DECLARE_16(0x290d) /** @def BT_UUID_GAP_DEVICE_NAME * @brief GAP Characteristic Device Name */ #define BT_UUID_GAP_DEVICE_NAME BT_UUID_DECLARE_16(0x2a00) /** @def BT_UUID_GAP_APPEARANCE * @brief GAP Characteristic Appearance */ #define BT_UUID_GAP_APPEARANCE BT_UUID_DECLARE_16(0x2a01) /** @def BT_UUID_GAP_PPCP * @brief GAP Characteristic Peripheral Preferred Connection Parameters */ #define BT_UUID_GAP_PPCP BT_UUID_DECLARE_16(0x2a04) /** @def BT_UUID_GATT_SC * @brief GATT Characteristic Service Changed */ #define BT_UUID_GATT_SC BT_UUID_DECLARE_16(0x2a05) /** @def BT_UUID_BAS_BATTERY_LEVEL * @brief BAS Characteristic Battery Level */ #define BT_UUID_BAS_BATTERY_LEVEL BT_UUID_DECLARE_16(0x2a19) /** @def BT_UUID_HTS_MEASUREMENT * @brief HTS Characteristic Measurement Value */ #define BT_UUID_HTS_MEASUREMENT BT_UUID_DECLARE_16(0x2a1c) /** @def BT_UUID_HIDS_BOOT_KB_IN_REPORT * @brief HID Characteristic Boot Keyboard Input Report */ #define BT_UUID_HIDS_BOOT_KB_IN_REPORT BT_UUID_DECLARE_16(0x2a22) /** @def BT_UUID_DIS_SYSTEM_ID * @brief DIS Characteristic System ID */ #define BT_UUID_DIS_SYSTEM_ID BT_UUID_DECLARE_16(0x2a23) /** @def BT_UUID_DIS_MODEL_NUMBER * @brief DIS Characteristic Model Number String */ #define BT_UUID_DIS_MODEL_NUMBER BT_UUID_DECLARE_16(0x2a24) /** @def BT_UUID_DIS_SERIAL_NUMBER * @brief DIS Characteristic Serial Number String */ #define BT_UUID_DIS_SERIAL_NUMBER BT_UUID_DECLARE_16(0x2a25) /** @def BT_UUID_DIS_FIRMWARE_REVISION * @brief DIS Characteristic Firmware Revision String */ #define BT_UUID_DIS_FIRMWARE_REVISION BT_UUID_DECLARE_16(0x2a26) /** @def BT_UUID_DIS_HARDWARE_REVISION * @brief DIS Characteristic Hardware Revision String */ #define BT_UUID_DIS_HARDWARE_REVISION BT_UUID_DECLARE_16(0x2a27) /** @def BT_UUID_DIS_SOFTWARE_REVISION * @brief DIS Characteristic Software Revision String */ #define BT_UUID_DIS_SOFTWARE_REVISION BT_UUID_DECLARE_16(0x2a28) /** @def BT_UUID_DIS_MANUFACTURER_NAME * @brief DIS Characteristic Manufacturer Name String */ #define BT_UUID_DIS_MANUFACTURER_NAME BT_UUID_DECLARE_16(0x2a29) /** @def BT_UUID_DIS_PNP_ID * @brief DIS Characteristic PnP ID */ #define BT_UUID_DIS_PNP_ID BT_UUID_DECLARE_16(0x2a50) /** @def BT_UUID_CTS_CURRENT_TIME * @brief CTS Characteristic Current Time */ #define BT_UUID_CTS_CURRENT_TIME BT_UUID_DECLARE_16(0x2a2b) /** @def BT_UUID_MAGN_DECLINATION * @brief Magnetic Declination Characteristic */ #define BT_UUID_MAGN_DECLINATION BT_UUID_DECLARE_16(0x2a2c) /** @def BT_UUID_HIDS_BOOT_KB_OUT_REPORT * @brief HID Boot Keyboard Output Report Characteristic */ #define BT_UUID_HIDS_BOOT_KB_OUT_REPORT BT_UUID_DECLARE_16(0x2a32) /** @def BT_UUID_HIDS_BOOT_MOUSE_IN_REPORT * @brief HID Boot Mouse Input Report Characteristic */ #define BT_UUID_HIDS_BOOT_MOUSE_IN_REPORT BT_UUID_DECLARE_16(0x2a33) /** @def BT_UUID_HRS_MEASUREMENT * @brief HRS Characteristic Measurement Interval */ #define BT_UUID_HRS_MEASUREMENT BT_UUID_DECLARE_16(0x2a37) /** @def BT_UUID_HRS_BODY_SENSOR * @brief HRS Characteristic Body Sensor Location */ #define BT_UUID_HRS_BODY_SENSOR BT_UUID_DECLARE_16(0x2a38) /** @def BT_UUID_HRS_CONTROL_POINT * @brief HRS Characteristic Control Point */ #define BT_UUID_HRS_CONTROL_POINT BT_UUID_DECLARE_16(0x2a39) /** @def BT_UUID_HIDS_INFO * @brief HID Information Characteristic */ #define BT_UUID_HIDS_INFO BT_UUID_DECLARE_16(0x2a4a) /** @def BT_UUID_HIDS_REPORT_MAP * @brief HID Report Map Characteristic */ #define BT_UUID_HIDS_REPORT_MAP BT_UUID_DECLARE_16(0x2a4b) /** @def BT_UUID_HIDS_CTRL_POINT * @brief HID Control Point Characteristic */ #define BT_UUID_HIDS_CTRL_POINT BT_UUID_DECLARE_16(0x2a4c) /** @def BT_UUID_HIDS_REPORT * @brief HID Report Characteristic */ #define BT_UUID_HIDS_REPORT BT_UUID_DECLARE_16(0x2a4d) /** @def BT_UUID_HIDS_PROTOCOL_MODE * @brief HID Protocol Mode Characteristic */ #define BT_UUID_HIDS_PROTOCOL_MODE BT_UUID_DECLARE_16(0x2a4e) /** @def BT_UUID_CSC_MEASUREMENT * @brief CSC Measurement Characteristic */ #define BT_UUID_CSC_MEASUREMENT BT_UUID_DECLARE_16(0x2a5b) /** @def BT_UUID_CSC_FEATURE * @brief CSC Feature Characteristic */ #define BT_UUID_CSC_FEATURE BT_UUID_DECLARE_16(0x2a5c) /** @def BT_UUID_SENSOR_LOCATION * @brief Sensor Location Characteristic */ #define BT_UUID_SENSOR_LOCATION BT_UUID_DECLARE_16(0x2a5d) /** @def BT_UUID_SC_CONTROL_POINT * @brief SC Control Point Characteristic */ #define BT_UUID_SC_CONTROL_POINT BT_UUID_DECLARE_16(0x2a55) /** @def BT_UUID_ELEVATION * @brief Elevation Characteristic */ #define BT_UUID_ELEVATION BT_UUID_DECLARE_16(0x2a6c) /** @def BT_UUID_PRESSURE * @brief Pressure Characteristic */ #define BT_UUID_PRESSURE BT_UUID_DECLARE_16(0x2a6d) /** @def BT_UUID_TEMPERATURE * @brief Temperature Characteristic */ #define BT_UUID_TEMPERATURE BT_UUID_DECLARE_16(0x2a6e) /** @def BT_UUID_HUMIDITY * @brief Humidity Characteristic */ #define BT_UUID_HUMIDITY BT_UUID_DECLARE_16(0x2a6f) /** @def BT_UUID_TRUE_WIND_SPEED * @brief True Wind Speed Characteristic */ #define BT_UUID_TRUE_WIND_SPEED BT_UUID_DECLARE_16(0x2a70) /** @def BT_UUID_TRUE_WIND_DIR * @brief True Wind Direction Characteristic */ #define BT_UUID_TRUE_WIND_DIR BT_UUID_DECLARE_16(0x2a71) /** @def BT_UUID_APPARENT_WIND_SPEED * @brief Apparent Wind Speed Characteristic */ #define BT_UUID_APPARENT_WIND_SPEED BT_UUID_DECLARE_16(0x2a72) /** @def BT_UUID_APPARENT_WIND_DIR * @brief Apparent Wind Direction Characteristic */ #define BT_UUID_APPARENT_WIND_DIR BT_UUID_DECLARE_16(0x2a73) /** @def BT_UUID_GUST_FACTOR * @brief Gust Factor Characteristic */ #define BT_UUID_GUST_FACTOR BT_UUID_DECLARE_16(0x2a74) /** @def BT_UUID_POLLEN_CONCENTRATION * @brief Pollen Concentration Characteristic */ #define BT_UUID_POLLEN_CONCENTRATION BT_UUID_DECLARE_16(0x2a75) /** @def BT_UUID_UV_INDEX * @brief UV Index Characteristic */ #define BT_UUID_UV_INDEX BT_UUID_DECLARE_16(0x2a76) /** @def BT_UUID_IRRADIANCE * @brief Irradiance Characteristic */ #define BT_UUID_IRRADIANCE BT_UUID_DECLARE_16(0x2a77) /** @def BT_UUID_RAINFALL * @brief Rainfall Characteristic */ #define BT_UUID_RAINFALL BT_UUID_DECLARE_16(0x2a78) /** @def BT_UUID_WIND_CHILL * @brief Wind Chill Characteristic */ #define BT_UUID_WIND_CHILL BT_UUID_DECLARE_16(0x2a79) /** @def BT_UUID_HEAT_INDEX * @brief Heat Index Characteristic */ #define BT_UUID_HEAT_INDEX BT_UUID_DECLARE_16(0x2a7a) /** @def BT_UUID_DEW_POINT * @brief Dew Point Characteristic */ #define BT_UUID_DEW_POINT BT_UUID_DECLARE_16(0x2a7b) /** @def BT_UUID_DESC_VALUE_CHANGED * @brief Descriptor Value Changed Characteristic */ #define BT_UUID_DESC_VALUE_CHANGED BT_UUID_DECLARE_16(0x2a7d) /** @def BT_UUID_MAGN_FLUX_DENSITY_2D * @brief Magnetic Flux Density - 2D Characteristic */ #define BT_UUID_MAGN_FLUX_DENSITY_2D BT_UUID_DECLARE_16(0x2aa0) /** @def BT_UUID_MAGN_FLUX_DENSITY_3D * @brief Magnetic Flux Density - 3D Characteristic */ #define BT_UUID_MAGN_FLUX_DENSITY_3D BT_UUID_DECLARE_16(0x2aa1) /** @def BT_UUID_BAR_PRESSURE_TREND * @brief Barometric Pressure Trend Characteristic */ #define BT_UUID_BAR_PRESSURE_TREND BT_UUID_DECLARE_16(0x2aa3) /** @def BT_UUID_CENTRAL_ADDR_RES * @brief Central Address Resolution Characteristic */ #define BT_UUID_CENTRAL_ADDR_RES BT_UUID_DECLARE_16(0x2aa6) /** @def BT_UUID_OTS_FEATURE * @brief OTS Feature Characteristic */ #define BT_UUID_OTS_FEATURE BT_UUID_DECLARE_16(0x2abd) /** @def BT_UUID_OTS_NAME * @brief OTS Object Name Characteristic */ #define BT_UUID_OTS_NAME BT_UUID_DECLARE_16(0x2abe) /** @def BT_UUID_OTS_TYPE * @brief OTS Object Type Characteristic */ #define BT_UUID_OTS_TYPE BT_UUID_DECLARE_16(0x2abf) /** @def BT_UUID_OTS_SIZE * @brief OTS Object Size Characteristic */ #define BT_UUID_OTS_SIZE BT_UUID_DECLARE_16(0x2ac0) /** @def BT_UUID_OTS_FIRST_CREATED * @brief OTS Object First-Created Characteristic */ #define BT_UUID_OTS_FIRST_CREATED BT_UUID_DECLARE_16(0x2ac1) /** @def BT_UUID_OTS_LAST_MODIFIED * @brief OTS Object Last-Modified Characteristic */ #define BT_UUID_OTS_LAST_MODIFIED BT_UUID_DECLARE_16(0x2ac2) /** @def BT_UUID_OTS_ID * @brief OTS Object ID Characteristic */ #define BT_UUID_OTS_ID BT_UUID_DECLARE_16(0x2ac3) /** @def BT_UUID_OTS_PROPERTIES * @brief OTS Object Properties Characteristic */ #define BT_UUID_OTS_PROPERTIES BT_UUID_DECLARE_16(0x2ac4) /** @def BT_UUID_OTS_ACTION_CP * @brief OTS Object Action Control Point Characteristic */ #define BT_UUID_OTS_ACTION_CP BT_UUID_DECLARE_16(0x2ac5) /** @def BT_UUID_OTS_LIST_CP * @brief OTS Object List Control Point Characteristic */ #define BT_UUID_OTS_LIST_CP BT_UUID_DECLARE_16(0x2ac6) /** @def BT_UUID_OTS_LIST_FILTER * @brief OTS Object List Filter Characteristic */ #define BT_UUID_OTS_LIST_FILTER BT_UUID_DECLARE_16(0x2ac7) /** @def BT_UUID_OTS_CHANGED * @brief OTS Object Changed Characteristic */ #define BT_UUID_OTS_CHANGED BT_UUID_DECLARE_16(0x2ac8) /** @def BT_UUID_MESH_PROV_DATA_IN * @brief Mesh Provisioning Data In */ #define BT_UUID_MESH_PROV_DATA_IN BT_UUID_DECLARE_16(0x2adb) /** @def BT_UUID_MESH_PROV_DATA_OUT * @brief Mesh Provisioning Data Out */ #define BT_UUID_MESH_PROV_DATA_OUT BT_UUID_DECLARE_16(0x2adc) /** @def BT_UUID_MESH_PROXY_DATA_IN * @brief Mesh Proxy Data In */ #define BT_UUID_MESH_PROXY_DATA_IN BT_UUID_DECLARE_16(0x2add) /** @def BT_UUID_MESH_PROXY_DATA_OUT * @brief Mesh Proxy Data Out */ #define BT_UUID_MESH_PROXY_DATA_OUT BT_UUID_DECLARE_16(0x2ade) /** @def BT_UUID_GATT_CLIENT_FEATURES * @brief Client Supported Features */ #define BT_UUID_GATT_CLIENT_FEATURES BT_UUID_DECLARE_16(0x2b29) /** @def BT_UUID_GATT_DB_HASH * @brief Database Hash */ #define BT_UUID_GATT_DB_HASH BT_UUID_DECLARE_16(0x2b2a) /** @def BT_UUID_GATT_SERVER_FEATURES * @brief Server Supported Features */ #define BT_UUID_GATT_SERVER_FEATURES BT_UUID_DECLARE_16(0x2b3a) /* * Protocol UUIDs */ #define BT_UUID_SDP BT_UUID_DECLARE_16(0x0001) #define BT_UUID_UDP BT_UUID_DECLARE_16(0x0002) #define BT_UUID_RFCOMM BT_UUID_DECLARE_16(0x0003) #define BT_UUID_TCP BT_UUID_DECLARE_16(0x0004) #define BT_UUID_TCS_BIN BT_UUID_DECLARE_16(0x0005) #define BT_UUID_TCS_AT BT_UUID_DECLARE_16(0x0006) #define BT_UUID_ATT BT_UUID_DECLARE_16(0x0007) #define BT_UUID_OBEX BT_UUID_DECLARE_16(0x0008) #define BT_UUID_IP BT_UUID_DECLARE_16(0x0009) #define BT_UUID_FTP BT_UUID_DECLARE_16(0x000a) #define BT_UUID_HTTP BT_UUID_DECLARE_16(0x000c) #define BT_UUID_BNEP BT_UUID_DECLARE_16(0x000f) #define BT_UUID_UPNP BT_UUID_DECLARE_16(0x0010) #define BT_UUID_HIDP BT_UUID_DECLARE_16(0x0011) #define BT_UUID_HCRP_CTRL BT_UUID_DECLARE_16(0x0012) #define BT_UUID_HCRP_DATA BT_UUID_DECLARE_16(0x0014) #define BT_UUID_HCRP_NOTE BT_UUID_DECLARE_16(0x0016) #define BT_UUID_AVCTP BT_UUID_DECLARE_16(0x0017) #define BT_UUID_AVDTP BT_UUID_DECLARE_16(0x0019) #define BT_UUID_CMTP BT_UUID_DECLARE_16(0x001b) #define BT_UUID_UDI BT_UUID_DECLARE_16(0x001d) #define BT_UUID_MCAP_CTRL BT_UUID_DECLARE_16(0x001e) #define BT_UUID_MCAP_DATA BT_UUID_DECLARE_16(0x001f) #define BT_UUID_L2CAP BT_UUID_DECLARE_16(0x0100) /** @brief Compare Bluetooth UUIDs. * * Compares 2 Bluetooth UUIDs, if the types are different both UUIDs are * first converted to 128 bits format before comparing. * * @param u1 First Bluetooth UUID to compare * @param u2 Second Bluetooth UUID to compare * * @return negative value if @a u1 < @a u2, 0 if @a u1 == @a u2, else positive */ int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2); /** @brief Create a bt_uuid from a little-endian data buffer. * * Create a bt_uuid from a little-endian data buffer. The data_len parameter * is used to determine whether the UUID is in 16, 32 or 128 bit format * (length 2, 4 or 16). Note: 32 bit format is not allowed over the air. * * @param uuid Pointer to the bt_uuid variable * @param data pointer to UUID stored in little-endian data buffer * @param data_len length of the UUID in the data buffer * * @return true if the data was valid and the UUID was successfully created. */ bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len); #define CONFIG_BT_DEBUG #if defined(CONFIG_BT_DEBUG) /** @brief Convert Bluetooth UUID to string. * * Converts Bluetooth UUID to string. * UUID can be in any format, 16-bit, 32-bit or 128-bit. * * @param uuid Bluetooth UUID * @param str pointer where to put converted string * @param len length of str * * @return N/A */ void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len); /** @brief Convert Bluetooth UUID to string in place. * * Converts Bluetooth UUID to string in place. UUID has to be in 16 bits or * 128 bits format. * * @param uuid Bluetooth UUID * * @return String representation of the UUID given */ const char *bt_uuid_str(const struct bt_uuid *uuid); #else static inline void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len) { if (len > 0) { str[0] = '\0'; } } static inline const char *bt_uuid_str(const struct bt_uuid *uuid) { return ""; } #endif /* CONFIG_BT_DEBUG */ #ifdef __cplusplus } #endif /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_UUID_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/bluetooth/uuid.h
C
apache-2.0
21,813
/* * Copyright (c) 2010-2014 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_TOOLCHAIN_COMMON_H_ #define ZEPHYR_INCLUDE_TOOLCHAIN_COMMON_H_ #include <misc/__assert.h> /** * @file * @brief Common toolchain abstraction * * Macros to abstract compiler capabilities (common to all toolchains). */ /* Abstract use of extern keyword for compatibility between C and C++ */ #ifdef __cplusplus #define EXTERN_C extern "C" #else #define EXTERN_C extern #endif /* Use TASK_ENTRY_CPP to tag task entry points defined in C++ files. */ #ifdef __cplusplus #define TASK_ENTRY_CPP extern "C" #endif /* * Generate a reference to an external symbol. * The reference indicates to the linker that the symbol is required * by the module containing the reference and should be included * in the image if the module is in the image. * * The assembler directive ".set" is used to define a local symbol. * No memory is allocated, and the local symbol does not appear in * the symbol table. */ #ifdef _ASMLANGUAGE #define REQUIRES(sym) .set sym ## _Requires, sym #else #define REQUIRES(sym) __asm__ (".set " # sym "_Requires, " # sym "\n\t"); #endif #ifdef _ASMLANGUAGE #define SECTION .section #endif /* * If the project is being built for speed (i.e. not for minimum size) then * align functions and branches in executable sections to improve performance. */ #ifdef _ASMLANGUAGE #if defined(CONFIG_X86) #ifdef PERF_OPT #define PERFOPT_ALIGN .balign 16 #else #define PERFOPT_ALIGN .balign 1 #endif #elif defined(CONFIG_ARM) #define PERFOPT_ALIGN .balign 4 #elif defined(CONFIG_ARC) #define PERFOPT_ALIGN .balign 4 #elif defined(CONFIG_NIOS2) || defined(CONFIG_RISCV) || \ defined(CONFIG_XTENSA) #define PERFOPT_ALIGN .balign 4 #elif defined(CONFIG_ARCH_POSIX) #else #error Architecture unsupported #endif #define GC_SECTION(sym) SECTION .text.##sym, "ax" #endif /* _ASMLANGUAGE */ /* force inlining a function */ #if !defined(_ASMLANGUAGE) #ifdef CONFIG_COVERAGE /* * The always_inline attribute forces a function to be inlined, * even ignoring -fno-inline. So for code coverage, do not * force inlining of these functions to keep their bodies around * so their number of executions can be counted. * * Note that "inline" is kept here for kobject_hash.c and * priv_stacks_hash.c. These are built without compiler flags * used for coverage. ALWAYS_INLINE cannot be empty as compiler * would complain about unused functions. Attaching unused * attribute would result in their text sections ballon more than * 10 times in size, as those functions are kept in text section. * So just keep "inline" here. */ #define ALWAYS_INLINE inline #else #define ALWAYS_INLINE inline __attribute__((always_inline)) #endif #endif #define Z_STRINGIFY(x) #x #define STRINGIFY(s) Z_STRINGIFY(s) /* concatenate the values of the arguments into one */ #define _DO_CONCAT(x, y) x ## y #define _CONCAT(x, y) _DO_CONCAT(x, y) /* Additionally used as a sentinel by gen_syscalls.py to identify what * functions are system calls * * Note POSIX unit tests don't still generate the system call stubs, so * until https://github.com/zephyrproject-rtos/zephyr/issues/5006 is * fixed via possibly #4174, we introduce this hack -- which will * disallow us to test system calls in POSIX unit testing (currently * not used). */ #ifndef ZTEST_UNITTEST #define __syscall static inline #else #define __syscall #endif /* #ifndef ZTEST_UNITTEST */ /* Definitions for struct declaration tags. These are sentinel values used by * parse_syscalls.py to gather a list of names of struct declarations that * have these tags applied for them. */ /* Indicates this is a driver subsystem */ #define __subsystem /* Indicates this is a network socket object */ #define __net_socket #ifndef BUILD_ASSERT /* Compile-time assertion that makes the build to fail. * Common implementation swallows the message. */ #define BUILD_ASSERT(EXPR, MSG...) \ enum _CONCAT(__build_assert_enum, __COUNTER__) { \ _CONCAT(__build_assert, __COUNTER__) = 1 / !!(EXPR) \ } #endif #ifndef BUILD_ASSERT_MSG #define BUILD_ASSERT_MSG(EXPR, MSG) __DEPRECATED_MACRO BUILD_ASSERT(EXPR, MSG) #endif /* * This is meant to be used in conjunction with __in_section() and similar * where scattered structure instances are concatened together by the linker * and walked by the code at run time just like a contiguous array of such * structures. * * Assemblers and linkers may insert alignment padding by default whose * size is larger than the natural alignment for those structures when * gathering various section segments together, messing up the array walk. * To prevent this, we need to provide an explicit alignment not to rely * on the default that might just work by luck. * * Alignment statements in linker scripts are not sufficient as * the assembler may add padding by itself to each segment when switching * between sections within the same file even if it merges many such segments * into a single section in the end. */ #define Z_DECL_ALIGN(type) __aligned(__alignof(type)) type /* * Convenience helper combining __in_section() and Z_DECL_ALIGN(). * The section name is the struct type prepended with an underscore. * The subsection is "static" and the subsubsection is the variable name. */ #define Z_STRUCT_SECTION_ITERABLE(struct_type, name) \ Z_DECL_ALIGN(struct struct_type) name \ __in_section(_##struct_type, static, name) // __used /* * Itterator for structure instances gathered by Z_STRUCT_SECTION_ITERABLE(). * The linker must provide a _<struct_type>_list_start symbol and a * _<struct_type>_list_end symbol to mark the start and the end of the * list of struct objects to iterate over. */ #define Z_STRUCT_SECTION_FOREACH(struct_type, iterator) \ extern struct struct_type _CONCAT(_##struct_type, _list_start)[]; \ extern struct struct_type _CONCAT(_##struct_type, _list_end)[]; \ for (struct struct_type *iterator = \ _CONCAT(_##struct_type, _list_start); \ ({ __ASSERT(iterator <= _CONCAT(_##struct_type, _list_end), \ "unexpected list end location"); \ iterator < _CONCAT(_##struct_type, _list_end); }); \ iterator++) #endif /* ZEPHYR_INCLUDE_TOOLCHAIN_COMMON_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/common/common.h
C
apache-2.0
6,405
/** @file * @brief Bluetooth subsystem logging helpers. */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __BT_LOG_H #define __BT_LOG_H #include <ble_os.h> #include <bluetooth/bluetooth.h> #include <bluetooth/uuid.h> #include <bluetooth/hci.h> #ifdef __cplusplus extern "C" { #endif #if !defined(BT_DBG_ENABLED) #define BT_DBG_ENABLED 1 #endif #if defined(CONFIG_BT_DEBUG_LOG) #if !defined(SYS_LOG_DOMAIN) #define SYS_LOG_DOMAIN "bt" #endif #define SYS_LOG_LEVEL SYS_LOG_LEVEL_DEBUG #define BT_DBG(fmt, ...) \ if (BT_DBG_ENABLED) { \ SYS_LOG_DBG("(%p) " fmt, k_current_get(), \ ##__VA_ARGS__); \ } #define BT_ERR(fmt, ...) SYS_LOG_ERR(fmt, ##__VA_ARGS__) #define BT_WARN(fmt, ...) SYS_LOG_WRN(fmt, ##__VA_ARGS__) #define BT_INFO(fmt, ...) SYS_LOG_INF(fmt, ##__VA_ARGS__) /* Enabling debug increases stack size requirement considerably */ #define BT_STACK_DEBUG_EXTRA 300 #else #include <ulog/ulog.h> #define BT_DBG(fmt, ...) \ if (BT_DBG_ENABLED) { \ LOGD("[DBG]",fmt"\n", ##__VA_ARGS__); \ } #define BT_ERR(fmt, ...) LOGE("[ERR]",fmt"\n", ##__VA_ARGS__) #define BT_WARN(fmt, ...) LOGW("[WARN]",fmt"\n", ##__VA_ARGS__) #define BT_INFO(fmt, ...) LOGI("[INFO]",fmt"\n", ##__VA_ARGS__) #define BT_STACK_DEBUG_EXTRA 0 #endif #define BT_ASSERT(cond) if (!(cond)) { \ BT_ERR("assert: '" #cond "' failed"); \ k_oops(); \ } #define BT_ASSERT_MSG(cond, fmt, ...) if (!(cond)) { \ BT_ERR(fmt, ##__VA_ARGS__); \ BT_ERR("assert: '" #cond "' failed"); \ k_oops(); \ } #define BT_HEXDUMP_DBG(_data, _length, _str) \ aos_log_hexdump(_str, (char *)_data, _length) /* NOTE: These helper functions always encodes into the same buffer storage. * It is the responsibility of the user of this function to copy the information * in this string if needed. * * NOTE: These functions are not thread-safe! */ const char *bt_hex_real(const void *buf, size_t len); const char *bt_addr_str_real(const bt_addr_t *addr); const char *bt_addr_le_str_real(const bt_addr_le_t *addr); const char *bt_uuid_str_real(const struct bt_uuid *uuid); /* NOTE: log_strdup does not guarantee a duplication of the string. * It is therefore still the responsibility of the user to handle the * restrictions in the underlying function call. */ #define bt_hex(buf, len) log_strdup(bt_hex_real(buf, len)) #define bt_addr_str(addr) log_strdup(bt_addr_str_real(addr)) #define bt_addr_le_str(addr) log_strdup(bt_addr_le_str_real(addr)) #define bt_uuid_str(uuid) log_strdup(bt_uuid_str_real(uuid)) void hextostring(const uint8_t *source, char *dest, int len); u8_t stringtohex(char *str, u8_t *out, u8_t count); #ifdef __cplusplus } #endif #endif /* __BT_LOG_H */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/common/log.h
C
apache-2.0
2,807
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SETTINGS_H_ #define __SETTINGS_H_ #include <misc/util.h> #include <misc/slist.h> #include <stdint.h> #include <common/common.h> #ifdef __cplusplus extern "C" { #endif #ifndef CONFIG_SETTINGS_DYNAMIC_HANDLERS #define CONFIG_SETTINGS_DYNAMIC_HANDLERS #endif /** * @defgroup file_system_storage File System Storage * @{ * @} */ /** * @defgroup settings Settings * @ingroup file_system_storage * @{ */ #define SETTINGS_MAX_DIR_DEPTH 8 /* max depth of settings tree */ #define SETTINGS_MAX_NAME_LEN (8 * SETTINGS_MAX_DIR_DEPTH) #define SETTINGS_MAX_VAL_LEN 256 #define SETTINGS_NAME_SEPARATOR '/' #define SETTINGS_NAME_END '=' /* pleace for settings additions: * up to 7 separators, '=', '\0' */ #define SETTINGS_EXTRA_LEN ((SETTINGS_MAX_DIR_DEPTH - 1) + 2) /** * Function used to read the data from the settings storage in * h_set handler implementations. * * @param[in] cb_arg arguments for the read function. Appropriate cb_arg is * transferred to h_set handler implementation by * the backend. * @param[out] data the destination buffer * @param[in] len length of read * * @return positive: Number of bytes read, 0: key-value pair is deleted. * On error returns -ERRNO code. */ typedef ssize_t (*settings_read_cb)(void *cb_arg, void *data, size_t len); /** * @struct settings_handler * Config handlers for subtree implement a set of handler functions. * These are registered using a call to @ref settings_register. */ struct settings_handler { char *name; /**< Name of subtree. */ int (*h_get)(const char *key, char *val, int val_len_max); /**< Get values handler of settings items identified by keyword names. * * Parameters: * - key[in] the name with skipped part that was used as name in * handler registration * - val[out] buffer to receive value. * - val_len_max[in] size of that buffer. * * Return: length of data read on success, negative on failure. */ int (*h_set)(const char *key, size_t len, settings_read_cb read_cb, void *cb_arg); /**< Set value handler of settings items identified by keyword names. * * Parameters: * - key[in] the name with skipped part that was used as name in * handler registration * - len[in] the size of the data found in the backend. * - read_cb[in] function provided to read the data from the backend. * - cb_arg[in] arguments for the read function provided by the * backend. * * Return: 0 on success, non-zero on failure. */ int (*h_commit)(void); /**< This handler gets called after settings has been loaded in full. * User might use it to apply setting to the application. * * Return: 0 on success, non-zero on failure. */ int (*h_export)(int (*export_func)(const char *name, const void *val, size_t val_len)); /**< This gets called to dump all current settings items. * * This happens when @ref settings_save tries to save the settings. * Parameters: * - export_func: the pointer to the internal function which appends * a single key-value pair to persisted settings. Don't store * duplicated value. The name is subtree/key string, val is the string * with value. * * @remarks The User might limit a implementations of handler to serving * only one keyword at one call - what will impose limit to get/set * values using full subtree/key name. * * Return: 0 on success, non-zero on failure. */ sys_snode_t node; /**< Linked list node info for module internal usage. */ }; /** * @struct settings_handler_static * Config handlers without the node element, used for static handlers. * These are registered using a call to SETTINGS_REGISTER_STATIC(). */ struct settings_handler_static { char *name; /**< Name of subtree. */ int (*h_get)(const char *key, char *val, int val_len_max); /**< Get values handler of settings items identified by keyword names. * * Parameters: * - key[in] the name with skipped part that was used as name in * handler registration * - val[out] buffer to receive value. * - val_len_max[in] size of that buffer. * * Return: length of data read on success, negative on failure. */ int (*h_set)(const char *key, size_t len, settings_read_cb read_cb, void *cb_arg); /**< Set value handler of settings items identified by keyword names. * * Parameters: * - key[in] the name with skipped part that was used as name in * handler registration * - len[in] the size of the data found in the backend. * - read_cb[in] function provided to read the data from the backend. * - cb_arg[in] arguments for the read function provided by the * backend. * * Return: 0 on success, non-zero on failure. */ int (*h_commit)(void); /**< This handler gets called after settings has been loaded in full. * User might use it to apply setting to the application. */ int (*h_export)(int (*export_func)(const char *name, const void *val, size_t val_len)); /**< This gets called to dump all current settings items. * * This happens when @ref settings_save tries to save the settings. * Parameters: * - export_func: the pointer to the internal function which appends * a single key-value pair to persisted settings. Don't store * duplicated value. The name is subtree/key string, val is the string * with value. * * @remarks The User might limit a implementations of handler to serving * only one keyword at one call - what will impose limit to get/set * values using full subtree/key name. * * Return: 0 on success, non-zero on failure. */ }; /** * Define a static handler for settings items * * @param _hname handler name * @param _tree subtree name * @param _get get routine (can be NULL) * @param _set set routine (can be NULL) * @param _commit commit routine (can be NULL) * @param _export export routine (can be NULL) * * This creates a variable _hname prepended by settings_handler_. * */ #define SETTINGS_STATIC_HANDLER_DEFINE(_hname, _tree, _get, _set, _commit, \ _export) \ const Z_STRUCT_SECTION_ITERABLE(settings_handler_static, \ settings_handler_ ## _hname) = { \ .name = _tree, \ .h_get = _get, \ .h_set = _set, \ .h_commit = _commit, \ .h_export = _export, \ } #define SETTINGS_HANDLER_DEFINE(_hname, _tree, _get, _set, _commit, \ _export) \ static struct settings_handler settings_handler_##_hname = { \ .name = _tree, \ .h_get = _get, \ .h_set = _set, \ .h_commit = _commit, \ .h_export = _export, \ }; \ settings_register(& settings_handler_ ## _hname); /** * Initialization of settings and backend * * Can be called at application startup. * In case the backend is a FS Remember to call it after the FS was mounted. * For FCB backend it can be called without such a restriction. * * @return 0 on success, non-zero on failure. */ int settings_subsys_init(void); /** * Register a handler for settings items stored in RAM. * * @param cf Structure containing registration info. * * @return 0 on success, non-zero on failure. */ int settings_register(struct settings_handler *cf); /** * Load serialized items from registered persistence sources. Handlers for * serialized item subtrees registered earlier will be called for encountered * values. * * @return 0 on success, non-zero on failure. */ int settings_load(void); /** * Load limited set of serialized items from registered persistence sources. * Handlers for serialized item subtrees registered earlier will be called for * encountered values that belong to the subtree. * * @param[in] subtree name of the subtree to be loaded. * @return 0 on success, non-zero on failure. */ int settings_load_subtree(const char *subtree); /** * Callback function used for direct loading. * Used by @ref settings_load_subtree_direct function. * * @param[in] key the name with skipped part that was used as name in * handler registration * @param[in] len the size of the data found in the backend. * @param[in] read_cb function provided to read the data from the backend. * @param[in,out] cb_arg arguments for the read function provided by the * backend. * @param[in,out] param parameter given to the * @ref settings_load_subtree_direct function. * * - key[in] the name with skipped part that was used as name in * handler registration * - len[in] the size of the data found in the backend. * - read_cb[in] function provided to read the data from the backend. * - cb_arg[in] arguments for the read function provided by the * backend. * * @return When nonzero value is returned, further subtree searching is stopped. * Use with care as some settings backends would iterate through old * values, and the current value is returned last. */ typedef int (*settings_load_direct_cb)( const char *key, size_t len, settings_read_cb read_cb, void *cb_arg, void *param); /** * Load limited set of serialized items using given callback. * * This function bypasses the normal data workflow in settings module. * All the settings values that are found are passed to the given callback. * * @note * This function does not call commit function. * It works as a blocking function, so it is up to the user to call * any kind of commit function when this operation ends. * * @param[in] subtree subtree name of the subtree to be loaded. * @param[in] cb pointer to the callback function. * @param[in,out] param parameter to be passed when callback * function is called. * @return 0 on success, non-zero on failure. */ int settings_load_subtree_direct( const char *subtree, settings_load_direct_cb cb, void *param); /** * Save currently running serialized items. All serialized items which are * different from currently persisted values will be saved. * * @return 0 on success, non-zero on failure. */ int settings_save(void); /** * Write a single serialized value to persisted storage (if it has * changed value). * * @param name Name/key of the settings item. * @param value Pointer to the value of the settings item. This value will * be transferred to the @ref settings_handler::h_export handler implementation. * @param val_len Length of the value. * * @return 0 on success, non-zero on failure. */ int settings_save_one(const char *name, const void *value, size_t val_len); /** * Delete a single serialized in persisted storage. * * Deleting an existing key-value pair in the settings mean * to set its value to NULL. * * @param name Name/key of the settings item. * * @return 0 on success, non-zero on failure. */ int settings_delete(const char *name); /** * Call commit for all settings handler. This should apply all * settings which has been set, but not applied yet. * * @return 0 on success, non-zero on failure. */ int settings_commit(void); /** * Call commit for settings handler that belong to subtree. * This should apply all settings which has been set, but not applied yet. * * @param[in] subtree name of the subtree to be committed. * * @return 0 on success, non-zero on failure. */ int settings_commit_subtree(const char *subtree); /** * @} settings */ /** * @defgroup settings_backend Settings backend interface * @ingroup settings * @{ */ /* * API for config storage */ struct settings_store_itf; /** * Backend handler node for storage handling. */ struct settings_store { sys_snode_t cs_next; /**< Linked list node info for internal usage. */ const struct settings_store_itf *cs_itf; /**< Backend handler structure. */ }; /** * Arguments for data loading. * Holds all parameters that changes the way data should be loaded from backend. */ struct settings_load_arg { /** * @brief Name of the subtree to be loaded * * If NULL, all values would be loaded. */ const char *subtree; /** * @brief Pointer to the callback function. * * If NULL then matching registered function would be used. */ settings_load_direct_cb cb; /** * @brief Parameter for callback function * * Parameter to be passed to the callback function. */ void *param; }; /** * Backend handler functions. * Sources are registered using a call to @ref settings_src_register. * Destinations are registered using a call to @ref settings_dst_register. */ struct settings_store_itf { int (*csi_load)(struct settings_store *cs, const struct settings_load_arg *arg); /**< Loads values from storage limited to subtree defined by subtree. * * Parameters: * - cs - Corresponding backend handler node, * - arg - Structure that holds additional data for data loading. * * @note * Backend is expected not to provide duplicates of the entities. * It means that if the backend does not contain any functionality to * really delete old keys, it has to filter out old entities and call * load callback only on the final entity. */ int (*csi_save_start)(struct settings_store *cs); /**< Handler called before an export operation. * * Parameters: * - cs - Corresponding backend handler node */ int (*csi_save)(struct settings_store *cs, const char *name, const char *value, size_t val_len); /**< Save a single key-value pair to storage. * * Parameters: * - cs - Corresponding backend handler node * - name - Key in string format * - value - Binary value * - val_len - Length of value in bytes. */ int (*csi_save_end)(struct settings_store *cs); /**< Handler called after an export operation. * * Parameters: * - cs - Corresponding backend handler node */ }; /** * Register a backend handler acting as source. * * @param cs Backend handler node containing handler information. * */ void settings_src_register(struct settings_store *cs); /** * Register a backend handler acting as destination. * * @param cs Backend handler node containing handler information. * */ void settings_dst_register(struct settings_store *cs); /* * API for handler lookup */ /** * Parses a key to an array of elements and locate corresponding module handler. * * @param[in] name in string format * @param[out] next remaining of name after matched handler * * @return settings_handler_static on success, NULL on failure. */ struct settings_handler_static *settings_parse_and_lookup(const char *name, const char **next); /** * Calls settings handler. * * @param[in] name The name of the data found in the backend. * @param[in] len The size of the data found in the backend. * @param[in] read_cb Function provided to read the data from * the backend. * @param[in,out] read_cb_arg Arguments for the read function provided by * the backend. * @param[in,out] load_arg Arguments for data loading. * * @return 0 or negative error code */ int settings_call_set_handler(const char *name, size_t len, settings_read_cb read_cb, void *read_cb_arg, const struct settings_load_arg *load_arg); /** * @} */ /** * @defgroup settings_name_proc Settings name processing * @brief API for const name processing * @ingroup settings * @{ */ /** * Compares the start of name with a key * * @param[in] name in string format * @param[in] key comparison string * @param[out] next pointer to remaining of name, when the remaining part * starts with a separator the separator is removed from next * * Some examples: * settings_name_steq("bt/btmesh/iv", "b", &next) returns 1, next="t/btmesh/iv" * settings_name_steq("bt/btmesh/iv", "bt", &next) returns 1, next="btmesh/iv" * settings_name_steq("bt/btmesh/iv", "bt/", &next) returns 0, next=NULL * settings_name_steq("bt/btmesh/iv", "bta", &next) returns 0, next=NULL * * REMARK: This routine could be simplified if the settings_handler names * would include a separator at the end. * * @return 0: no match * 1: match, next can be used to check if match is full */ int settings_name_steq(const char *name, const char *key, const char **next); /** * determine the number of characters before the first separator * * @param[in] name in string format * @param[out] next pointer to remaining of name (excluding separator) * * @return index of the first separator, in case no separator was found this * is the size of name * */ int settings_name_next(const char *name, const char **next); /** * @} */ #ifdef CONFIG_SETTINGS_RUNTIME /** * @defgroup settings_rt Settings subsystem runtime * @brief API for runtime settings * @ingroup settings * @{ */ /** * Set a value with a specific key to a module handler. * * @param name Key in string format. * @param data Binary value. * @param len Value length in bytes. * * @return 0 on success, non-zero on failure. */ int settings_runtime_set(const char *name, const void *data, size_t len); /** * Get a value corresponding to a key from a module handler. * * @param name Key in string format. * @param data Returned binary value. * @param len requested value length in bytes. * * @return length of data read on success, negative on failure. */ int settings_runtime_get(const char *name, void *data, size_t len); /** * Apply settings in a module handler. * * @param name Key in string format. * * @return 0 on success, non-zero on failure. */ int settings_runtime_commit(const char *name); /** * @} */ #endif /* CONFIG_SETTINGS_RUNTIME */ #ifdef __cplusplus } #endif #endif /* __SETTINGS_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/include/settings/settings.h
C
apache-2.0
18,037
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <ble_os.h> #include <misc/util.h> #include <misc/dlist.h> //#include <aos/aos.h> //yulong removed // #include "aos/debug.h" #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BLUETOOTH_DEBUG_CORE) #include <common/log.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include "atomic.h" #define OSAL_RHINO #ifdef OSAL_RHINO #include <k_default_config.h> #include <k_types.h> #include <k_err.h> #include <k_sys.h> #include <k_list.h> #include <k_ringbuf.h> #include <k_obj.h> #include <k_sem.h> #include <k_queue.h> #include <k_buf_queue.h> #include <k_stats.h> #include <k_time.h> #include <k_task.h> #include <port.h> #include "bt_errno.h" #endif void k_queue_init(struct k_queue *queue) { int stat; stat = krhino_sem_create(&queue->sem, "ble", 0); if (stat) { //SYS_LOG_ERR("buf queue exhausted\n"); } sys_slist_init(&queue->queue_list); sys_dlist_init(&queue->poll_events); } static inline void handle_poll_events(struct k_queue *queue, bt_u32_t state) { _handle_obj_poll_events(&queue->poll_events, state); } void k_queue_cancel_wait(struct k_queue *queue) { krhino_sem_give(&queue->sem); handle_poll_events(queue, K_POLL_STATE_NOT_READY); } void k_queue_insert(struct k_queue *queue, void *prev, void *node) { unsigned int key; key = irq_lock(); sys_slist_append(&queue->queue_list, node); irq_unlock(key); krhino_sem_give(&queue->sem); handle_poll_events(queue, K_POLL_STATE_DATA_AVAILABLE); } long long k_now_ms() { return aos_now_ms(); } void k_queue_append(struct k_queue *queue, void *data) { k_queue_insert(queue, NULL, data); } void k_queue_prepend(struct k_queue *queue, void *data) { k_queue_insert(queue, NULL, data); } void k_queue_append_list(struct k_queue *queue, void *head, void *tail) { struct net_buf *buf_tail = (struct net_buf *)head; for (buf_tail = (struct net_buf *)head; buf_tail; buf_tail = buf_tail->frags) { k_queue_append(queue, buf_tail); } handle_poll_events(queue, K_POLL_STATE_DATA_AVAILABLE); } void *k_queue_get(struct k_queue *queue, int32_t timeout) { int ret; void *msg = NULL; tick_t ticks; if (timeout == K_FOREVER) { ticks = RHINO_WAIT_FOREVER; } else { ticks = krhino_ms_to_ticks(timeout); } ret = krhino_sem_take(&queue->sem, ticks); if (ret) { return NULL; } else { unsigned int key; key = irq_lock(); msg = sys_slist_get(&queue->queue_list); irq_unlock(key); return msg; } } int k_queue_is_empty(struct k_queue *queue) { return (int)sys_slist_is_empty(&queue->queue_list); } int k_queue_count(struct k_queue *queue) { return queue->sem.count; } int k_sem_init(struct k_sem *sem, unsigned int initial_count, unsigned int limit) { int ret; if (NULL == sem) { BT_ERR("sem is NULL\n"); return -EINVAL; } ret = krhino_sem_create(&sem->sem, "ble", initial_count); if (ret != 0) BT_ERR("%s failed: %d", __func__, ret); sys_dlist_init(&sem->poll_events); return ret; } int k_sem_take(struct k_sem *sem, uint32_t timeout) { tick_t ticks; int ret; if (timeout == K_FOREVER) { ticks = RHINO_WAIT_FOREVER; } else { ticks = krhino_ms_to_ticks(timeout); } ret = krhino_sem_take(&sem->sem, ticks); if (ret != 0) { // aos_debug_backtrace_now(NULL); BT_ERR("%s failed: %d", __func__, ret); } return ret; } int k_sem_give(struct k_sem *sem) { int ret; if (NULL == sem) { BT_ERR("sem is NULL\n"); return -EINVAL; } ret = krhino_sem_give(&sem->sem); if (ret != 0) { BT_ERR("%s failed: %d", __func__, ret); } return 0; } int k_sem_delete(struct k_sem *sem) { if (NULL == sem) { BT_ERR("sem is NULL\n"); return -EINVAL; } krhino_sem_del(&sem->sem); return 0; } unsigned int k_sem_count_get(struct k_sem *sem) { #ifdef OSAL_RHINO sem_count_t count; krhino_sem_count_get(&sem->sem, &count); return (int)count; #endif return 0; } void k_mutex_init(struct k_mutex *mutex) { int stat; if (NULL == mutex) { BT_ERR("mutex is NULL\n"); return; } stat = krhino_mutex_create(&mutex->mutex, "ble"); if (stat) { BT_ERR("mutex buffer over\n"); } sys_dlist_init(&mutex->poll_events); return; } int k_mutex_lock(struct k_mutex *mutex, bt_s32_t timeout) { tick_t ticks; int ret; if (timeout == K_FOREVER) { ticks = RHINO_WAIT_FOREVER; } else { ticks = krhino_ms_to_ticks(timeout); } ret = krhino_mutex_lock(&mutex->mutex, ticks); if (ret != 0) { BT_ERR("%s failed: %d", __func__, ret); } return ret; } void k_mutex_unlock(struct k_mutex *mutex) { int ret; if (NULL == mutex) { BT_ERR("mutex is NULL\n"); return; } ret = krhino_mutex_unlock(&mutex->mutex); if (ret != 0) { BT_ERR("%s failed: %d", __func__, ret); } } int64_t k_uptime_get() { return krhino_sys_time_get(); } uint32_t k_uptime_get_32() { return (uint32_t)krhino_sys_time_get(); } int k_thread_spawn(struct k_thread *thread, const char *name, uint32_t *stack, uint32_t stack_size, \ k_thread_entry_t fn, void *arg, int prio) { int ret; if (stack == NULL || thread == NULL) { BT_ERR("thread || stack is NULL"); return -1; } ret = krhino_task_create(&thread->task, name, arg, prio, 0, stack, stack_size, fn, 1); if (ret) { BT_ERR("creat task %s fail %d\n", name, ret); return ret; } return ret; } int k_yield(void) { return 0; } unsigned int irq_lock(void) { CPSR_ALLOC(); RHINO_CPU_INTRPT_DISABLE(); return cpsr; } void irq_unlock(unsigned int key) { CPSR_ALLOC(); cpsr = key; RHINO_CPU_INTRPT_ENABLE(); } void _SysFatalErrorHandler(unsigned int reason, const void *pEsf) {}; void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args) { int ret; ASSERT(timer, "timer is NULL"); BT_DBG("timer %p,handle %p,args %p", timer, handle, args); timer->handler = handle; timer->args = args; timer->timeout = 0; ret = krhino_timer_create(&timer->timer, "AOS", (timer_cb_t)(timer->handler), krhino_ms_to_ticks(1000), 0, args, 0); if (ret) { BT_DBG("fail to create a timer"); } } void k_timer_start(k_timer_t *timer, uint32_t timeout) { int ret; ASSERT(timer, "timer is NULL"); BT_DBG("timer %p,timeout %u", timer, timeout); timer->timeout = timeout; timer->start_ms = aos_now_ms(); ret = krhino_timer_stop(&timer->timer); if (ret) { BT_ERR("fail to stop timer"); } ret = krhino_timer_change(&timer->timer, krhino_ms_to_ticks(timeout), 0); if (ret) { BT_ERR("fail to change timeout"); } ret = krhino_timer_start(&timer->timer); if (ret) { BT_ERR("fail to start timer"); } } void k_timer_stop(k_timer_t *timer) { int ret; ASSERT(timer, "timer is NULL"); /** * Timer may be reused, so its timeout value * should be cleared when stopped. */ if (!timer->timeout) { return; } BT_DBG("timer %p", timer); ret = krhino_timer_stop(&timer->timer); if (ret) { BT_ERR("fail to stop timer"); } timer->timeout = 0; } void k_sleep(int32_t duration) { aos_msleep(duration); } void *k_current_get(void) { void *task; task = krhino_cur_task_get(); return task; } bool k_timer_is_started(k_timer_t *timer) { ASSERT(timer, "timer is NULL"); return timer->timeout ? true : false; } const char *log_strdup(const char *str) { return str; } void *k_malloc(bt_u32_t size) { return aos_malloc(size); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/aos_port.c
C
apache-2.0
7,993
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdint.h> #include <ble_os.h> #include "work.h" #include "misc/util.h" extern struct k_work_q g_work_queue; extern void process_events(struct k_poll_event *ev, int count); extern int bt_conn_prepare_events(struct k_poll_event events[]); void scheduler_loop(struct k_poll_event *events) { struct k_work *work; uint32_t now; int ev_count; int delayed_ms = 0; while (1) { ev_count = 0; delayed_ms = K_FOREVER; if (k_queue_is_empty(&g_work_queue.queue) == 0) { work = k_queue_first_entry(&g_work_queue.queue); now = k_uptime_get_32(); delayed_ms = 0; if (now < (work->start_ms + work->timeout)) { delayed_ms = work->start_ms + work->timeout - now; } if (delayed_ms == 0) { delayed_ms = 1; } } events[0].state = K_POLL_STATE_NOT_READY; ev_count = 1; if (IS_ENABLED(CONFIG_BT_CONN)) { ev_count += bt_conn_prepare_events(&events[ev_count]); } k_poll(events, ev_count, delayed_ms); process_events(events, ev_count); if (k_queue_is_empty(&g_work_queue.queue) == 0) { work = k_queue_first_entry(&g_work_queue.queue); now = k_uptime_get_32(); if (now >= (work->start_ms + work->timeout)) { k_queue_remove(&g_work_queue.queue, work); if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING) && work->handler) { work->handler(work); } } } k_sleep(10); } }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/event_scheduler.c
C
apache-2.0
1,708
/* * Copyright (c) 2015 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _DEVICE_H_ #define _DEVICE_H_ //#include <kernel.h> /** * @brief Device Driver APIs * @defgroup io_interfaces Device Driver APIs * @{ * @} */ /** * @brief Device Model APIs * @defgroup device_model Device Model APIs * @{ */ #include <ble_types/types.h> // #include <common.h> #ifdef __cplusplus extern "C" { #endif #define CONFIG_CLOCK_CONTROL_NRF5_K32SRC_DRV_NAME "nrf5k32srcclockcontrol" #define CONFIG_CLOCK_CONTROL_NRF5_M16SRC_DRV_NAME "nrf5m16srcclockcontrol" static const int _INIT_LEVEL_PRE_KERNEL_1 = 1; static const int _INIT_LEVEL_PRE_KERNEL_2 = 1; static const int _INIT_LEVEL_POST_KERNEL = 1; static const int _INIT_LEVEL_APPLICATION = 1; /** * @brief Runtime device structure (In memory) Per driver instance * @param device_config Build time config information * @param driver_api pointer to structure containing the API functions for * the device type. This pointer is filled in by the driver at init time. * @param driver_data driver instance data. For driver use only */ struct device { struct device_config *config; const void *driver_api; void *driver_data; }; /** * @brief Static device information (In ROM) Per driver instance * * @param name name of the device * @param init init function for the driver * @param config_info address of driver instance config information */ struct device_config { char *name; int (*init)(struct device *device); #ifdef CONFIG_DEVICE_POWER_MANAGEMENT int (*device_pm_control)(struct device *device, bt_u32_t command, void *context); #endif const void *config_info; }; /** * @def DEVICE_INIT * * @brief Create device object and set it up for boot time initialization. * * @details This macro defines a device object that is automatically * configured by the kernel during system initialization. * * @param dev_name Device name. * * @param drv_name The name this instance of the driver exposes to * the system. * * @param init_fn Address to the init function of the driver. * * @param data Pointer to the device's configuration data. * * @param cfg_info The address to the structure containing the * configuration information for this instance of the driver. * * @param level The initialization level at which configuration occurs. * Must be one of the following symbols, which are listed in the order * they are performed by the kernel: * \n * \li PRE_KERNEL_1: Used for devices that have no dependencies, such as those * that rely solely on hardware present in the processor/SOC. These devices * cannot use any kernel services during configuration, since they are not * yet available. * \n * \li PRE_KERNEL_2: Used for devices that rely on the initialization of devices * initialized as part of the PRIMARY level. These devices cannot use any * kernel services during configuration, since they are not yet available. * \n * \li POST_KERNEL: Used for devices that require kernel services during * configuration. * \n * \li APPLICATION: Used for application components (i.e. non-kernel components) * that need automatic configuration. These devices can use all services * provided by the kernel during configuration. * * @param prio The initialization priority of the device, relative to * other devices of the same initialization level. Specified as an integer * value in the range 0 to 99; lower values indicate earlier initialization. * Must be a decimal integer literal without leading zeroes or sign (e.g. 32), * or an equivalent symbolic name (e.g. \#define MY_INIT_PRIO 32); symbolic * expressions are *not* permitted * (e.g. CONFIG_KERNEL_INIT_PRIORITY_DEFAULT + 5). */ /** * @def DEVICE_AND_API_INIT * * @brief Create device object and set it up for boot time initialization, * with the option to set driver_api. * * @copydetails DEVICE_INIT * @param api Provides an initial pointer to the API function struct * used by the driver. Can be NULL. * @details The driver api is also set here, eliminating the need to do that * during initialization. */ #define _DO_CONCAT(x, y) x ## y #define _CONCAT(x, y) _DO_CONCAT(x, y) #define _STRINGIFY(x) #x #define STRINGIFY(s) _STRINGIFY(s) #ifndef CONFIG_DEVICE_POWER_MANAGEMENT #define DEVICE_AND_API_INIT(dev_name, drv_name, init_fn, data, cfg_info, \ level, prio, api) \ \ static struct device_config _CONCAT(__config_, dev_name) __used \ __attribute__((__section__(".devconfig.init"))) = { \ .name = drv_name, .init = (init_fn), \ .config_info = (cfg_info) \ }; \ static struct device _CONCAT(__device_, dev_name) __used \ __attribute__((__section__(".init_" #level STRINGIFY(prio)))) = { \ .config = &_CONCAT(__config_, dev_name), \ .driver_api = api, \ .driver_data = data \ } #define DEVICE_DEFINE(dev_name, drv_name, init_fn, pm_control_fn, \ data, cfg_info, level, prio, api) \ DEVICE_AND_API_INIT(dev_name, drv_name, init_fn, data, cfg_info, \ level, prio, api) #else /** * @def DEVICE_DEFINE * * @brief Create device object and set it up for boot time initialization, * with the option to device_pm_control. * * @copydetails DEVICE_AND_API_INIT * @param pm_control_fn Pointer to device_pm_control function. * Can be empty function (device_pm_control_nop) if not implemented. */ #define DEVICE_DEFINE(dev_name, drv_name, init_fn, pm_control_fn, \ data, cfg_info, level, prio, api) \ \ static struct device_config _CONCAT(__config_, dev_name) __used \ __attribute__((__section__(".devconfig.init"))) = { \ .name = drv_name, .init = (init_fn), \ .device_pm_control = (pm_control_fn), \ .config_info = (cfg_info) \ }; \ static struct device _CONCAT(__device_, dev_name) __used \ __attribute__((__section__(".init_" #level STRINGIFY(prio)))) = { \ .config = &_CONCAT(__config_, dev_name), \ .driver_api = api, \ .driver_data = data \ } /* * Use the default device_pm_control for devices that do not call the * DEVICE_DEFINE macro so that caller of hook functions * need not check device_pm_control != NULL. */ #define DEVICE_AND_API_INIT(dev_name, drv_name, init_fn, data, cfg_info, \ level, prio, api) \ DEVICE_DEFINE(dev_name, drv_name, init_fn, \ device_pm_control_nop, data, cfg_info, level, \ prio, api) #endif #define DEVICE_INIT(dev_name, drv_name, init_fn, data, cfg_info, level, prio) \ DEVICE_AND_API_INIT(dev_name, drv_name, init_fn, data, cfg_info, \ level, prio, NULL) /** * @def DEVICE_NAME_GET * * @brief Expands to the full name of a global device object * * @details Return the full name of a device object symbol created by * DEVICE_INIT(), using the dev_name provided to DEVICE_INIT(). * * It is meant to be used for declaring extern symbols pointing on device * objects before using the DEVICE_GET macro to get the device object. * * @param name The same as dev_name provided to DEVICE_INIT() * * @return The expanded name of the device object created by DEVICE_INIT() */ #define DEVICE_NAME_GET(name) (_CONCAT(__device_, name)) /** * @def DEVICE_GET * * @brief Obtain a pointer to a device object by name * * @details Return the address of a device object created by * DEVICE_INIT(), using the dev_name provided to DEVICE_INIT(). * * @param name The same as dev_name provided to DEVICE_INIT() * * @return A pointer to the device object created by DEVICE_INIT() */ #define DEVICE_GET(name) (&DEVICE_NAME_GET(name)) /** @def DEVICE_DECLARE * * @brief Declare a static device object * * This macro can be used at the top-level to declare a device, such * that DEVICE_GET() may be used before the full declaration in * DEVICE_INIT(). * * This is often useful when configuring interrupts statically in a * device's init or per-instance config function, as the init function * itself is required by DEVICE_INIT() and use of DEVICE_GET() * inside it creates a circular dependency. * * @param name Device name */ #define DEVICE_DECLARE(name) static struct device DEVICE_NAME_GET(name) struct device; #ifdef CONFIG_DEVICE_POWER_MANAGEMENT /** * @brief Device Power Management APIs * @defgroup device_power_management_api Device Power Management APIs * @ingroup power_management_api * @{ */ /** * @} */ /** @def DEVICE_PM_ACTIVE_STATE * * @brief device is in ACTIVE power state * * @details Normal operation of the device. All device context is retained. */ #define DEVICE_PM_ACTIVE_STATE 1 /** @def DEVICE_PM_LOW_POWER_STATE * * @brief device is in LOW power state * * @details Device context is preserved by the HW and need not be * restored by the driver. */ #define DEVICE_PM_LOW_POWER_STATE 2 /** @def DEVICE_PM_SUSPEND_STATE * * @brief device is in SUSPEND power state * * @details Most device context is lost by the hardware. * Device drivers must save and restore or reinitialize any context * lost by the hardware */ #define DEVICE_PM_SUSPEND_STATE 3 /** @def DEVICE_PM_OFF_STATE * * @brief device is in OFF power state * * @details - Power has been fully removed from the device. * The device context is lost when this state is entered, so the OS * software will reinitialize the device when powering it back on */ #define DEVICE_PM_OFF_STATE 4 /* Constants defining support device power commands */ #define DEVICE_PM_SET_POWER_STATE 1 #define DEVICE_PM_GET_POWER_STATE 2 #endif void _sys_device_do_config_level(int level); /** * @brief Retrieve the device structure for a driver by name * * @details Device objects are created via the DEVICE_INIT() macro and * placed in memory by the linker. If a driver needs to bind to another driver * it can use this function to retrieve the device structure of the lower level * driver by the name the driver exposes to the system. * * @param name device name to search for. * * @return pointer to device structure; NULL if not found or cannot be used. */ struct device *device_get_binding(const char *name); /** * @brief Device Power Management APIs * @defgroup device_power_management_api Device Power Management APIs * @ingroup power_management_api * @{ */ /** * @brief Indicate that the device is in the middle of a transaction * * Called by a device driver to indicate that it is in the middle of a * transaction. * * @param busy_dev Pointer to device structure of the driver instance. */ void device_busy_set(struct device *busy_dev); /** * @brief Indicate that the device has completed its transaction * * Called by a device driver to indicate the end of a transaction. * * @param busy_dev Pointer to device structure of the driver instance. */ void device_busy_clear(struct device *busy_dev); #ifdef CONFIG_DEVICE_POWER_MANAGEMENT /* * Device PM functions */ /** * @brief No-op function to initialize unimplemented hook * * This function should be used to initialize device hook * for which a device has no PM operations. * * @param unused_device Unused * @param unused_ctrl_command Unused * @param unused_context Unused * * @retval 0 Always returns 0 */ int device_pm_control_nop(struct device *unused_device, bt_u32_t unused_ctrl_command, void *unused_context); /** * @brief Call the set power state function of a device * * Called by the application or power management service to let the device do * required operations when moving to the required power state * Note that devices may support just some of the device power states * @param device Pointer to device structure of the driver instance. * @param device_power_state Device power state to be set * * @retval 0 If successful. * @retval Errno Negative errno code if failure. */ static inline int device_set_power_state(struct device *device, bt_u32_t device_power_state) { return device->config->device_pm_control(device, DEVICE_PM_SET_POWER_STATE, &device_power_state); } /** * @brief Call the get power state function of a device * * This function lets the caller know the current device * power state at any time. This state will be one of the defined * power states allowed for the devices in that system * * @param device pointer to device structure of the driver instance. * @param device_power_state Device power state to be filled by the device * * @retval 0 If successful. * @retval Errno Negative errno code if failure. */ static inline int device_get_power_state(struct device *device, bt_u32_t *device_power_state) { return device->config->device_pm_control(device, DEVICE_PM_GET_POWER_STATE, device_power_state); } /** * @brief Gets the device structure list array and device count * * Called by the Power Manager application to get the list of * device structures associated with the devices in the system. * The PM app would use this list to create its own sorted list * based on the order it wishes to suspend or resume the devices. * * @param device_list Pointer to receive the device list array * @param device_count Pointer to receive the device count */ void device_list_get(struct device **device_list, int *device_count); /** * @brief Check if any device is in the middle of a transaction * * Called by an application to see if any device is in the middle * of a critical transaction that cannot be interrupted. * * @retval 0 if no device is busy * @retval -EBUSY if any device is busy */ int device_any_busy_check(void); /** * @brief Check if a specific device is in the middle of a transaction * * Called by an application to see if a particular device is in the * middle of a critical transaction that cannot be interrupted. * * @param chk_dev Pointer to device structure of the specific device driver * the caller is interested in. * @retval 0 if the device is not busy * @retval -EBUSY if the device is busy */ int device_busy_check(struct device *chk_dev); #endif /** * @} */ #ifdef __cplusplus } #endif /** * @} */ #endif /* _DEVICE_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/include/bt_device.h
C
apache-2.0
15,031
/** * @file bt_errno.h * @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef AOS_ERRNO_H_BT #define AOS_ERRNO_H_BT #ifdef __cplusplus extern "C" { #endif /** * @addtogroup aos_errno errno * Define standard errno. * * @{ */ //#if defined(__GNUC__)&&!defined(__CC_ARM)||defined(_WIN32) #if 0 #include <bt_errno.h> #else /* Define standard errno for __CC_ARM and __ICCARM__ */ #define EPERM 1 /**< Operation not permitted */ #define ENOENT 2 /**< No such file or directory */ #define ESRCH 3 /**< No such process */ #define EINTR 4 /**< Interrupted system call */ #define EIO 5 /**< I/O error */ #define ENXIO 6 /**< No such device or address */ #define E2BIG 7 /**< Arg list too long */ #define ENOEXEC 8 /**< Exec format error */ #define EBADF 9 /**< Bad file number */ #define ECHILD 10 /**< No child processes */ #define EAGAIN 11 /**< Try again */ #ifdef ENOMEM #undef ENOMEM #endif #define ENOMEM 12 /**< Out of memory */ #define EACCES 13 /**< Permission denied */ #define EFAULT 14 /**< Bad address */ #define ENOTBLK 15 /**< Block device required */ #define EBUSY 16 /**< Device or resource busy */ #define EEXIST 17 /**< File exists */ #define EXDEV 18 /**< Cross-device link */ #define ENODEV 19 /**< No such device */ #define ENOTDIR 20 /**< Not a directory */ #define EISDIR 21 /**< Is a directory */ #ifdef EINVAL #undef EINVAL #endif #define EINVAL 22 /**< Invalid argument */ #define ENFILE 23 /**< File table overflow */ #define EMFILE 24 /**< Too many open files */ #define ENOTTY 25 /**< Not a typewriter */ #define ETXTBSY 26 /**< Text file busy */ #define EFBIG 27 /**< File too large */ #define ENOSPC 28 /**< No space left on device */ #define ESPIPE 29 /**< Illegal seek */ #define EROFS 30 /**< Read-only file system */ #define EMLINK 31 /**< Too many links */ #define EPIPE 32 /**< Broken pipe */ #ifdef EDOM #undef EDOM #define EDOM 33 /**< Math argument out of domain of func */ #endif #ifdef ERANGE #undef ERANGE #define ERANGE 34 /**< Math result not representable */ #endif #define EDEADLK 35 /**< Resource deadlock would occur */ #define ENAMETOOLONG 36 /**< File name too long */ #define ENOLCK 37 /**< No record locks available */ #define ENOSYS 38 /**< Function not implemented */ #define ENOTEMPTY 39 /**< Directory not empty */ #define ELOOP 40 /**< Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /**< Operation would block */ #define ENOMSG 42 /**< No message of desired type */ #define EIDRM 43 /**< Identifier removed */ #define ECHRNG 44 /**< Channel number out of range */ #define EL2NSYNC 45 /**<* Level 2 not synchronized */ #define EL3HLT 46 /**< Level 3 halted */ #define EL3RST 47 /**< Level 3 reset */ #define ELNRNG 48 /**< Link number out of range */ #define EUNATCH 49 /**< Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /**< Level 2 halted */ #define EBADE 52 /**< Invalid exchange */ #define EBADR 53 /**< Invalid request descriptor */ #define EXFULL 54 /**< Exchange full */ #define ENOANO 55 /**< No anode */ #define EBADRQC 56 /**< Invalid request code */ #define EBADSLT 57 /**< Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /**< Bad font file format */ #define ENOSTR 60 /**< Device not a stream */ #define ENODATA 61 /**< No data available */ #define ETIME 62 /**< Timer expired */ #define ENOSR 63 /**< Out of streams resources */ #define ENONET 64 /**< Machine is not on the network */ #define ENOPKG 65 /**< Package not installed */ #define EREMOTE 66 /**< Object is remote */ #define ENOLINK 67 /**< Link has been severed */ #define EADV 68 /**< Advertise error */ #define ESRMNT 69 /**< Srmount error */ #define ECOMM 70 /**< Communication error on send */ #define EPROTO 71 /**< Protocol error */ #define EMULTIHOP 72 /**< Multihop attempted */ #define EDOTDOT 73 /**< RFS specific error */ #define EBADMSG 74 /**< Not a data message */ #define EOVERFLOW 75 /**< Value too large for defined data type */ #define ENOTUNIQ 76 /**< Name not unique on network */ #define EBADFD 77 /**< File descriptor in bad state */ #define EREMCHG 78 /**< Remote address changed */ #define ELIBACC 79 /**< Can not access a needed shared library */ #define ELIBBAD 80 /**< Accessing a corrupted shared library */ #define ELIBSCN 81 /**< .lib section in a.out corrupted */ #define ELIBMAX 82 /**< Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /**< Cannot exec a shared library directly */ #ifdef EILSEQ #undef EILSEQ #endif #define EILSEQ 84 /**< Illegal byte sequence */ #define ERESTART 85 /**< Interrupted system call should be restarted */ #define ESTRPIPE 86 /**< Streams pipe error */ #define EUSERS 87 /**< Too many users */ #define ENOTSOCK 88 /**< Socket operation on non-socket */ #define EDESTADDRREQ 89 /**< Destination address required */ #define EMSGSIZE 90 /**< Message too long */ #define EPROTOTYPE 91 /**< Protocol wrong type for socket */ #define ENOPROTOOPT 92 /**< Protocol not available */ #define EPROTONOSUPPORT 93 /**< Protocol not supported */ #define ESOCKTNOSUPPORT 94 /**< Socket type not supported */ #define EOPNOTSUPP 95 /**< Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /**< Protocol family not supported */ #define EAFNOSUPPORT 97 /**< Address family not supported by protocol */ #define EADDRINUSE 98 /**< Address already in use */ #define EADDRNOTAVAIL 99 /**< Cannot assign requested address */ #define ENETDOWN 100 /**< Network is down */ #define ENETUNREACH 101 /**< Network is unreachable */ #define ENETRESET 102 /**< Network dropped connection because of reset */ #define ECONNABORTED 103 /**< Software caused connection abort */ #define ECONNRESET 104 /**< Connection reset by peer */ #define ENOBUFS 105 /**<* No buffer space available */ #define EISCONN 106 /**< Transport endpoint is already connected */ #define ENOTCONN 107 /**< Transport endpoint is not connected */ #define ESHUTDOWN 108 /**< Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /**< Too many references: cannot splice */ #define ETIMEDOUT 110 /**< Connection timed out */ #define ECONNREFUSED 111 /**< Connection refused */ #define EHOSTDOWN 112 /**< Host is down */ #define EHOSTUNREACH 113 /**< No route to host */ #define EALREADY 114 /**< Operation already in progress */ #define EINPROGRESS 115 /**< Operation now in progress */ #define ESTALE 116 /**< Stale NFS file handle */ #define EUCLEAN 117 /**< Structure needs cleaning */ #define ENOTNAM 118 /**< Not a XENIX named type file */ #define ENAVAIL 119 /**< No XENIX semaphores available */ #define EISNAM 120 /**< Is a named type file */ #define EREMOTEIO 121 /**< Remote I/O error */ #define EDQUOT 122 /**< Quota exceeded */ #define ENOMEDIUM 123 /**< No medium found */ #define EMEDIUMTYPE 124 /**< Wrong medium type */ #define ENOTSUP 134 /* Not supported */ #define ECANCELED 140 /* Operation canceled */ #define ENSROK 0 /**< DNS server returned answer with no data */ #define ENSRNODATA 160 /**< DNS server returned answer with no data */ #define ENSRFORMERR 161 /**< DNS server claims query was misformatted */ #define ENSRSERVFAIL 162 /**< DNS server returned general failure */ #define ENSRNOTFOUND 163 /**< Domain name not found */ #define ENSRNOTIMP 164 /**< DNS server does not implement requested operation */ #define ENSRREFUSED 165 /**< DNS server refused query */ #define ENSRBADQUERY 166 /**< Misformatted DNS query */ #define ENSRBADNAME 167 /**< Misformatted domain name */ #define ENSRBADFAMILY 168 /**< Unsupported address family */ #define ENSRBADRESP 169 /**< Misformatted DNS reply */ #define ENSRCONNREFUSED 170 /**< Could not contact DNS servers */ #define ENSRTIMEOUT 171 /**< Timeout while contacting DNS servers */ #define ENSROF 172 /**< End of file */ #define ENSRFILE 173 /**< Error reading file */ #define ENSRNOMEM 174 /**< Out of memory */ #define ENSRDESTRUCTION 175 /**< Application terminated lookup */ #define ENSRQUERYDOMAINTOOLONG 176 /**< Domain name is too long */ #define ENSRCNAMELOOP 177 /**< Domain name is too long */ #endif /* defined(__GNUC__)&&!defined(__CC_ARM)||defined(_WIN32) */ /** * Redefine the errno, Only use in framework/app */ #ifdef BUILD_BIN #undef set_errno #define set_errno(err) do { if (err) { errno = (err); } } while(0) #else /* BUILD_BIN */ #ifdef BUILD_APP /** * Get system errno. * * @return int: return system errno for app bin. */ extern int get_errno(void); /** * Set system errno. * * @param[in] err err to set into system. * * @return none. */ extern void set_errno(int err); #undef errno #define errno get_errno() /* Get system errno, unique copy for system */ #endif /* BUILD_APP */ #endif /* BUILD_BIN */ /** @} */ #ifdef __cplusplus } #endif #endif /* AOS_ERRNO_H */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/include/bt_errno.h
C
apache-2.0
9,989
/* * Copyright (c) 2015 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _INIT_H_ #define _INIT_H_ #include <bt_device.h> // #include <toolchain.h> #ifdef __cplusplus extern "C" { #endif /* * System initialization levels. The PRE_KERNEL_1 and PRE_KERNEL_2 levels are * executed in the kernel's initialization context, which uses the interrupt * stack. The remaining levels are executed in the kernel's main task. */ #define _SYS_INIT_LEVEL_PRE_KERNEL_1 0 #define _SYS_INIT_LEVEL_PRE_KERNEL_2 1 #define _SYS_INIT_LEVEL_POST_KERNEL 2 #define _SYS_INIT_LEVEL_APPLICATION 3 /* Counter use to avoid issues if two or more system devices are declared * in the same C file with the same init function */ #define _SYS_NAME(init_fn) _CONCAT(_CONCAT(sys_init_, init_fn), __COUNTER__) /** * @def SYS_INIT * * @brief Run an initialization function at boot at specified priority * * @details This macro lets you run a function at system boot. * * @param init_fn Pointer to the boot function to run * * @param level The initialization level, See DEVICE_INIT for details. * * @param prio Priority within the selected initialization level. See * DEVICE_INIT for details. */ #define SYS_INIT(init_fn, level, prio) \ DEVICE_INIT(_SYS_NAME(init_fn), "", init_fn, NULL, NULL, level, prio) /** * @def SYS_DEVICE_DEFINE * * @brief Run an initialization function at boot at specified priority, * and define device PM control function. * * @copydetails SYS_INIT * @param pm_control_fn Pointer to device_pm_control function. * Can be empty function (device_pm_control_nop) if not implemented. * @param drv_name Name of this system device */ #define SYS_DEVICE_DEFINE(drv_name, init_fn, pm_control_fn, level, prio) \ DEVICE_DEFINE(_SYS_NAME(init_fn), drv_name, init_fn, pm_control_fn, \ NULL, NULL, level, prio, NULL) #ifdef __cplusplus } #endif #endif /* _INIT_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/include/init.h
C
apache-2.0
1,939
/* * Copyright (c) 2017 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * * @brief Kernel asynchronous event polling interface. * * This polling mechanism allows waiting on multiple events concurrently, * either events triggered directly, or from kernel objects or other kernel * constructs. */ #include <stdio.h> #include <ble_os.h> #include <ble_types/types.h> #include <misc/slist.h> #include <misc/dlist.h> #include <misc/__assert.h> struct event_cb { sys_dlist_t next; struct k_poll_event *events; int num_events; struct k_sem sem; }; static sys_dlist_t event_cb_list = SYS_DLIST_STATIC_INIT(&event_cb_list); static volatile int event_cb_counter = 0; static uint8_t is_poll_init = 0; void k_poll_event_init(struct k_poll_event *event, bt_u32_t type, int mode, void *obj) { __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY, "only NOTIFY_ONLY mode is supported\n"); __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n"); __ASSERT(obj, "must provide an object\n"); event->poller = NULL; /* event->tag is left uninitialized: the user will set it if needed */ event->type = type; event->state = K_POLL_STATE_NOT_READY; event->mode = mode; event->unused = 0; event->obj = obj; } static inline void set_event_state(struct k_poll_event *event, bt_u32_t state) { event->poller = NULL; event->state |= state; } extern int has_tx_sem(struct k_poll_event *event); extern void event_callback(uint8_t event_type); static int _signal_poll_event(struct k_poll_event *event, bt_u32_t state, int *must_reschedule) { *must_reschedule = 0; if (event->type != K_POLL_TYPE_DATA_AVAILABLE || has_tx_sem(event)) { set_event_state(event, state); event_callback(K_POLL_TYPE_FIFO_DATA_AVAILABLE); } return 0; } void _handle_obj_poll_events(sys_dlist_t *events, bt_u32_t state) { struct k_poll_event *poll_event; int must_reschedule; poll_event = (struct k_poll_event *)sys_dlist_get(events); if (poll_event) { (void)_signal_poll_event(poll_event, state, &must_reschedule); } } /* must be called with interrupts locked */ static inline int is_condition_met(struct k_poll_event *event, bt_u32_t *state) { switch (event->type) { case K_POLL_TYPE_DATA_AVAILABLE: if (has_tx_sem(event) == 0) { return 0; } if (!k_queue_is_empty(event->queue)) { *state = K_POLL_STATE_FIFO_DATA_AVAILABLE; return 1; } break; case K_POLL_TYPE_SIGNAL: if (event->signal->signaled) { *state = K_POLL_STATE_SIGNALED; return 1; } break; case K_POLL_TYPE_DATA_RECV: if (event->signal->signaled) { *state = K_POLL_STATE_DATA_RECV; event->signal->signaled = 0; return 1; } break; default: __ASSERT(0, "invalid event type (0x%x)\n", event->type); break; } return 0; } static inline void add_event(sys_dlist_t *events, struct k_poll_event *event, struct _poller *poller) { sys_dlist_append(events, &event->_node); } /* must be called with interrupts locked */ static inline int register_event(struct k_poll_event *event, struct _poller * poller) { switch (event->type) { case K_POLL_TYPE_DATA_AVAILABLE: __ASSERT(event->queue, "invalid queue\n"); add_event(&event->queue->poll_events, event, poller); break; case K_POLL_TYPE_SIGNAL: __ASSERT(event->signal, "invalid poll signal\n"); add_event(&event->signal->poll_events, event, poller); break; case K_POLL_TYPE_DATA_RECV: __ASSERT(event->queue, "invalid queue\n"); add_event(&event->signal->poll_events, event, poller); break; default: __ASSERT(0, "invalid event type\n"); break; } event->poller = poller; return 0; } /* must be called with interrupts locked */ static inline void clear_event_registration(struct k_poll_event *event) { event->poller = NULL; switch (event->type) { case K_POLL_TYPE_DATA_AVAILABLE: __ASSERT(event->queue, "invalid queue\n"); sys_dlist_remove(&event->_node); break; case K_POLL_TYPE_SIGNAL: __ASSERT(event->signal, "invalid poll signal\n"); sys_dlist_remove(&event->_node); break; case K_POLL_TYPE_DATA_RECV: __ASSERT(event->queue, "invalid queue\n"); sys_dlist_remove(&event->_node); break; default: __ASSERT(0, "invalid event type\n"); break; } } /* must be called with interrupts locked */ static inline void clear_event_registrations(struct k_poll_event *events, int last_registered, unsigned int key) { for (; last_registered >= 0; last_registered--) { clear_event_registration(&events[last_registered]); irq_unlock(key); key = irq_lock(); } } static bool polling_events(struct k_poll_event *events, int num_events, bt_s32_t timeout, int *last_registered) { bool polling = true; unsigned int key; for (int ii = 0; ii < num_events; ii++) { bt_u32_t state; key = irq_lock(); if (is_condition_met(&events[ii], &state)) { set_event_state(&events[ii], state); polling = false; } else if (timeout != K_NO_WAIT && polling) { register_event(&events[ii], NULL); ++(*last_registered); } irq_unlock(key); } return polling; } void event_callback(uint8_t event_type) { sys_dnode_t *event_next; sys_dnode_t *event_next_save; //struct k_poll_event *events; unsigned int key; key = irq_lock(); SYS_DLIST_FOR_EACH_NODE_SAFE(&event_cb_list, event_next, event_next_save) { for (int i = 0; i < ((struct event_cb *)event_next)->num_events; i++) { if (((struct event_cb *)event_next)->events[i].type == event_type || event_type == K_POLL_TYPE_EARLIER_WORK) { k_sem_give(&((struct event_cb *)event_next)->sem); break; } } } irq_unlock(key); } int k_poll(struct k_poll_event *events, int num_events, bt_s32_t timeout) { int last_registered = -1; unsigned int key; bool polling = true; static struct event_cb eventcb; /* find events whose condition is already fulfilled */ #if 0 polling = polling_events(events, num_events, timeout, &last_registered); if (polling == false) { goto exit; } #endif if (!is_poll_init) { k_sem_init(&eventcb.sem, 0, 1); sys_dlist_append(&event_cb_list, (sys_dnode_t *)&eventcb); event_cb_counter++; is_poll_init = 1; } eventcb.events = events; eventcb.num_events = num_events; polling = polling_events(events, num_events, timeout, &last_registered); if (polling == false) { goto exit; } k_sem_take(&eventcb.sem, timeout); last_registered = -1; polling_events(events, num_events, K_NO_WAIT, &last_registered); exit: //sys_dlist_remove((sys_dnode_t *)&eventcb); //k_sem_delete(&eventcb.sem); key = irq_lock(); clear_event_registrations(events, last_registered, key); irq_unlock(key); return 0; } void k_poll_signal_raise(struct k_poll_signal *signal, int result) { signal->result = result; signal->signaled = 1U; _handle_obj_poll_events(&signal->poll_events, K_POLL_STATE_SIGNALED); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/poll.c
C
apache-2.0
7,970
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <common/log.h> #include "bt_errno.h" struct k_work_q g_work_queue; extern void event_callback(uint8_t event_type); static void k_work_submit_to_queue(struct k_work_q *work_q, struct k_work *work) { sys_snode_t *node = NULL; struct k_work *delayed_work = NULL; struct k_work *prev_delayed_work = NULL; //uint32_t now = k_uptime_get_32(); if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) { SYS_SLIST_FOR_EACH_NODE(&g_work_queue.queue.queue_list, node) { delayed_work = (struct k_work *)node; if ((work->timeout + work->start_ms) < (delayed_work->start_ms + delayed_work->timeout)) { break; } prev_delayed_work = delayed_work; } sys_slist_insert(&g_work_queue.queue.queue_list, (sys_snode_t *)prev_delayed_work, (sys_snode_t *)work); delayed_work = k_queue_first_entry(&g_work_queue.queue); if (delayed_work && (k_uptime_get_32() <= delayed_work->start_ms + delayed_work->timeout)) { event_callback(K_POLL_TYPE_EARLIER_WORK); } } } static void k_work_rm_from_queue(struct k_work_q *work_q, struct k_work *work) { k_queue_remove(&work_q->queue, work); } int k_work_q_start(void) { k_queue_init(&g_work_queue.queue); return 0; } int k_work_init(struct k_work *work, k_work_handler_t handler) { atomic_clear_bit(work->flags, K_WORK_STATE_PENDING); work->handler = handler; work->start_ms = 0; work->timeout = 0; return 0; } void k_work_submit(struct k_work *work) { k_delayed_work_submit((struct k_delayed_work *)work, 0); } void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler) { k_work_init(&work->work, handler); } int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay) { int err = 0; int key = irq_lock(); if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) { k_delayed_work_cancel(work); } work->work.start_ms = k_uptime_get_32(); work->work.timeout = delay; k_work_submit_to_queue(&g_work_queue, (struct k_work *)work); //done: irq_unlock(key); return err; } int k_delayed_work_cancel(struct k_delayed_work *work) { int key = irq_lock(); work->work.timeout = 0; atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING); k_work_rm_from_queue(&g_work_queue, (struct k_work *)work); irq_unlock(key); return 0; } bt_s32_t k_delayed_work_remaining_get(struct k_delayed_work *work) { int32_t remain; if (work == NULL) { return 0; } remain = work->work.timeout - (k_uptime_get_32() - work->work.start_ms); if (remain < 0) { remain = 0; } return remain; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/aos/work.c
C
apache-2.0
2,841
/* * Copyright (c) 2016 Intel Corporation * Copyright (c) 2011-2014 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file Atomic ops in pure C * * This module provides the atomic operators for processors * which do not support native atomic operations. * * The atomic operations are guaranteed to be atomic with respect * to interrupt service routines, and to operations performed by peer * processors. * * (originally from x86's atomic.c) */ #include <ble_os.h> #include <atomic.h> /** * * @brief Atomic compare-and-set primitive * * This routine provides the compare-and-set operator. If the original value at * <target> equals <oldValue>, then <newValue> is stored at <target> and the * function returns 1. * * If the original value at <target> does not equal <oldValue>, then the store * is not done and the function returns 0. * * The reading of the original value at <target>, the comparison, * and the write of the new value (if it occurs) all happen atomically with * respect to both interrupts and accesses of other processors to <target>. * * @param target address to be tested * @param old_value value to compare against * @param new_value value to compare against * @return Returns 1 if <new_value> is written, 0 otherwise. */ int atomic_cas(atomic_t *target, atomic_val_t old_value, atomic_val_t new_value) { unsigned int key; int ret = 0; key = irq_lock(); if (*target == old_value) { *target = new_value; ret = 1; } irq_unlock(key); return ret; } /** * * @brief Atomic addition primitive * * This routine provides the atomic addition operator. The <value> is * atomically added to the value at <target>, placing the result at <target>, * and the old value from <target> is returned. * * @param target memory location to add to * @param value the value to add * * @return The previous value from <target> */ atomic_val_t atomic_add(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target += value; irq_unlock(key); return ret; } /** * * @brief Atomic subtraction primitive * * This routine provides the atomic subtraction operator. The <value> is * atomically subtracted from the value at <target>, placing the result at * <target>, and the old value from <target> is returned. * * @param target the memory location to subtract from * @param value the value to subtract * * @return The previous value from <target> */ atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target -= value; irq_unlock(key); return ret; } /** * * @brief Atomic increment primitive * * @param target memory location to increment * * This routine provides the atomic increment operator. The value at <target> * is atomically incremented by 1, and the old value from <target> is returned. * * @return The value from <target> before the increment */ atomic_val_t atomic_inc(atomic_t *target) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; (*target)++; irq_unlock(key); return ret; } /** * * @brief Atomic decrement primitive * * @param target memory location to decrement * * This routine provides the atomic decrement operator. The value at <target> * is atomically decremented by 1, and the old value from <target> is returned. * * @return The value from <target> prior to the decrement */ atomic_val_t atomic_dec(atomic_t *target) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; (*target)--; irq_unlock(key); return ret; } /** * * @brief Atomic get primitive * * @param target memory location to read from * * This routine provides the atomic get primitive to atomically read * a value from <target>. It simply does an ordinary load. Note that <target> * is expected to be aligned to a 4-byte boundary. * * @return The value read from <target> */ atomic_val_t atomic_get(const atomic_t *target) { return *target; } /** * * @brief Atomic get-and-set primitive * * This routine provides the atomic set operator. The <value> is atomically * written at <target> and the previous value at <target> is returned. * * @param target the memory location to write to * @param value the value to write * * @return The previous value from <target> */ atomic_val_t atomic_set(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target = value; irq_unlock(key); return ret; } /** * * @brief Atomic clear primitive * * This routine provides the atomic clear operator. The value of 0 is atomically * written at <target> and the previous value at <target> is returned. (Hence, * atomic_clear(pAtomicVar) is equivalent to atomic_set(pAtomicVar, 0).) * * @param target the memory location to write * * @return The previous value from <target> */ atomic_val_t atomic_clear(atomic_t *target) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target = 0; irq_unlock(key); return ret; } /** * * @brief Atomic bitwise inclusive OR primitive * * This routine provides the atomic bitwise inclusive OR operator. The <value> * is atomically bitwise OR'ed with the value at <target>, placing the result * at <target>, and the previous value at <target> is returned. * * @param target the memory location to be modified * @param value the value to OR * * @return The previous value from <target> */ atomic_val_t atomic_or(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target |= value; irq_unlock(key); return ret; } /** * * @brief Atomic bitwise exclusive OR (XOR) primitive * * This routine provides the atomic bitwise exclusive OR operator. The <value> * is atomically bitwise XOR'ed with the value at <target>, placing the result * at <target>, and the previous value at <target> is returned. * * @param target the memory location to be modified * @param value the value to XOR * * @return The previous value from <target> */ atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target ^= value; irq_unlock(key); return ret; } /** * * @brief Atomic bitwise AND primitive * * This routine provides the atomic bitwise AND operator. The <value> is * atomically bitwise AND'ed with the value at <target>, placing the result * at <target>, and the previous value at <target> is returned. * * @param target the memory location to be modified * @param value the value to AND * * @return The previous value from <target> */ atomic_val_t atomic_and(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target &= value; irq_unlock(key); return ret; } /** * * @brief Atomic bitwise NAND primitive * * This routine provides the atomic bitwise NAND operator. The <value> is * atomically bitwise NAND'ed with the value at <target>, placing the result * at <target>, and the previous value at <target> is returned. * * @param target the memory location to be modified * @param value the value to NAND * * @return The previous value from <target> */ atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value) { unsigned int key; atomic_val_t ret; key = irq_lock(); ret = *target; *target = ~(*target & value); irq_unlock(key); return ret; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/atomic_c.c
C
apache-2.0
7,853
/* buf.c - Buffer management */ /* * Copyright (c) 2015 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <stdio.h> #include <bt_errno.h> #include <stddef.h> #include <string.h> #include <ble_os.h> #include <misc/byteorder.h> #include <stdlib.h> #include <net/buf.h> #include <misc/util.h> #include "common/log.h" #ifdef CONFIG_BT_USE_MM #include <umm_heap.h> #include <mm.h> #endif #if defined(CONFIG_NET_BUF_LOG) #define SYS_LOG_DOMAIN "net/buf" #define SYS_LOG_LEVEL CONFIG_SYS_LOG_NET_BUF_LEVEL #include <logging/yoc_syslog.h> #define NET_BUF_DBG(fmt, ...) SYS_LOG_DBG("(%p) " fmt, k_current_get(), \ ##__VA_ARGS__) #define NET_BUF_ERR(fmt, ...) SYS_LOG_ERR(fmt, ##__VA_ARGS__) #define NET_BUF_WARN(fmt, ...) SYS_LOG_WRN(fmt, ##__VA_ARGS__) #define NET_BUF_INFO(fmt, ...) SYS_LOG_INF(fmt, ##__VA_ARGS__) #define NET_BUF_ASSERT(cond) do { if (!(cond)) { \ NET_BUF_ERR("assert: '" #cond "' failed"); \ } } while (0) #else #define NET_BUF_DBG(fmt, ...) #define NET_BUF_ERR(fmt, ...) #define NET_BUF_WARN(fmt, ...) #define NET_BUF_INFO(fmt, ...) #define NET_BUF_ASSERT(cond) #endif /* CONFIG_NET_BUF_LOG */ #if CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0 #define WARN_ALLOC_INTERVAL K_SECONDS(CONFIG_NET_BUF_WARN_ALLOC_INTERVAL) #else #define WARN_ALLOC_INTERVAL K_FOREVER #endif #define MAX_POOL_LIST_SIZE (15) /* Linker-defined symbol bound to the static pool structs */ //extern struct net_buf_pool _net_buf_pool_list[]; //extern struct net_buf_pool _net_buf_pool_list_end[]; static struct net_buf_pool* net_buf_pool_list[MAX_POOL_LIST_SIZE] = {0}; static struct net_buf_pool** net_buf_pool_list_end = net_buf_pool_list; int net_buf_pool_init(struct net_buf_pool *pool) { if (net_buf_pool_list_end >= net_buf_pool_list + MAX_POOL_LIST_SIZE) { return -1; } k_lifo_init(&pool->free); *net_buf_pool_list_end = pool; net_buf_pool_list_end++; return 0; } struct net_buf_pool *net_buf_pool_get(int id) { return net_buf_pool_list[id]; } static int pool_id(struct net_buf_pool *pool) { int i = 0; for (i = 0; net_buf_pool_list[i] && i < net_buf_pool_list_end - net_buf_pool_list; i++) { if (net_buf_pool_list[i] == pool) { return i; } } return -1; } int net_buf_pool_is_free(int id) { struct net_buf_pool *pool = net_buf_pool_get(id); return (pool->buf_count == pool->uninit_count + k_lifo_num_get(&pool->free)); } int net_buf_poll_is_all_free() { int count = net_buf_pool_list_end - net_buf_pool_list; while(count) { if (!net_buf_pool_is_free(count - 1)) { return 0; } count--; } return 1; } int net_buf_id(struct net_buf *buf) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); return buf - pool->__bufs; } static inline struct net_buf *pool_get_uninit(struct net_buf_pool *pool, u16_t uninit_count) { struct net_buf *buf; buf = &pool->__bufs[pool->buf_count - uninit_count]; buf->pool_id = pool_id(pool); return buf; } void net_buf_reset(struct net_buf *buf) { __ASSERT_NO_MSG(buf->flags == 0U); __ASSERT_NO_MSG(buf->frags == NULL); net_buf_simple_reset(&buf->b); } static u8_t *generic_data_ref(struct net_buf *buf, u8_t *data) { u8_t *ref_count; ref_count = data - 1; (*ref_count)++; return data; } static u8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size, k_timeout_t timeout) { #if 0 struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id); struct k_mem_pool *pool = buf_pool->alloc->alloc_data; struct k_mem_block block; u8_t *ref_count; /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */ if (k_mem_pool_alloc(pool, &block, sizeof(struct k_mem_block_id) + 1 + *size, timeout)) { return NULL; } /* save the block descriptor info at the start of the actual block */ memcpy(block.data, &block.id, sizeof(block.id)); ref_count = (u8_t *)block.data + sizeof(block.id); *ref_count = 1U; /* Return pointer to the byte following the ref count */ return ref_count + 1; #endif return NULL; } static void mem_pool_data_unref(struct net_buf *buf, u8_t *data) { #if 0 struct k_mem_block_id id; u8_t *ref_count; ref_count = data - 1; if (--(*ref_count)) { return; } /* Need to copy to local variable due to alignment */ memcpy(&id, ref_count - sizeof(id), sizeof(id)); k_mem_pool_free_id(&id); #endif } const struct net_buf_data_cb net_buf_var_cb = { .alloc = mem_pool_data_alloc, .ref = generic_data_ref, .unref = mem_pool_data_unref, }; static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, k_timeout_t timeout) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; *size = MIN(fixed->data_size, *size); #ifdef CONFIG_BT_USE_MM bt_u32_t *ref_count; unsigned int key; key = irq_lock(); ref_count = mm_malloc(USR_HEAP, sizeof(*ref_count) + *size, __builtin_return_address(0)); irq_unlock(key); if (!ref_count) { return NULL; } *ref_count = 1; return (u8_t *)(ref_count + 1); #else return fixed->data_pool + fixed->data_size * net_buf_id(buf); #endif } static void fixed_data_unref(struct net_buf *buf, u8_t *data) { /* Nothing needed for fixed-size data pools */ #ifdef CONFIG_BT_USE_MM bt_u32_t *ref_count; ref_count = (bt_u32_t *)(data - sizeof(*ref_count)); if (--(*ref_count)) { return; } unsigned int key; key = irq_lock(); mm_free(USR_HEAP, ref_count, __builtin_return_address(0)); irq_unlock(key); #endif } const struct net_buf_data_cb net_buf_fixed_cb = { .alloc = fixed_data_alloc, .unref = fixed_data_unref, }; #if (CONFIG_HEAP_MEM_POOL_SIZE > 0) static u8_t *heap_data_alloc(struct net_buf *buf, size_t *size, k_timeout_t timeout) { u8_t *ref_count; ref_count = malloc(1 + *size); if (!ref_count) { return NULL; } *ref_count = 1U; return ref_count + 1; } static void heap_data_unref(struct net_buf *buf, u8_t *data) { u8_t *ref_count; ref_count = data - 1; if (--(*ref_count)) { return; } k_free(ref_count); } static const struct net_buf_data_cb net_buf_heap_cb = { .alloc = heap_data_alloc, .ref = generic_data_ref, .unref = heap_data_unref, }; const struct net_buf_data_alloc net_buf_heap_alloc = { .cb = &net_buf_heap_cb, }; #endif /* CONFIG_HEAP_MEM_POOL_SIZE > 0 */ static u8_t *data_alloc(struct net_buf *buf, size_t *size, k_timeout_t timeout) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); return pool->alloc->cb->alloc(buf, size, timeout); } static u8_t *data_ref(struct net_buf *buf, u8_t *data) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); return pool->alloc->cb->ref(buf, data); } static void data_unref(struct net_buf *buf, u8_t *data) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); if (buf->flags & NET_BUF_EXTERNAL_DATA) { return; } pool->alloc->cb->unref(buf, data); } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size, k_timeout_t timeout, const char *func, int line) #else struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, k_timeout_t timeout) #endif { bt_u32_t alloc_start = k_uptime_get_32(); struct net_buf *buf; unsigned int key; __ASSERT_NO_MSG(pool); NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool, size, timeout); /* We need to lock interrupts temporarily to prevent race conditions * when accessing pool->uninit_count. */ key = irq_lock(); /* If there are uninitialized buffers we're guaranteed to succeed * with the allocation one way or another. */ if (pool->uninit_count) { u16_t uninit_count; /* If this is not the first access to the pool, we can * be opportunistic and try to fetch a previously used * buffer from the LIFO with K_NO_WAIT. */ if (pool->uninit_count < pool->buf_count) { buf = k_lifo_get(&pool->free, K_NO_WAIT); if (buf) { irq_unlock(key); goto success; } } uninit_count = pool->uninit_count--; irq_unlock(key); buf = pool_get_uninit(pool, uninit_count); goto success; } irq_unlock(key); #if defined(CONFIG_NET_BUF_LOG) && SYS_LOG_LEVEL >= SYS_LOG_LEVEL_WARNING if (timeout == K_FOREVER) { bt_u32_t ref = k_uptime_get_32(); buf = k_lifo_get(&pool->free, K_NO_WAIT); while (!buf) { #if defined(CONFIG_NET_BUF_POOL_USAGE) NET_BUF_WARN("%s():%d: Pool %s low on buffers.", func, line, pool->name); #else NET_BUF_WARN("%s():%d: Pool %p low on buffers.", func, line, pool); #endif buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL); #if defined(CONFIG_NET_BUF_POOL_USAGE) NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs", func, line, pool->name, (k_uptime_get_32() - ref) / MSEC_PER_SEC); #else NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs", func, line, pool, (k_uptime_get_32() - ref) / MSEC_PER_SEC); #endif } } else { buf = k_lifo_get(&pool->free, timeout); } #else buf = k_lifo_get(&pool->free, timeout); #endif if (!buf) { NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line); return NULL; } success: NET_BUF_DBG("allocated buf %p", buf); if (size) { if (timeout != K_NO_WAIT && timeout != K_FOREVER) { bt_u32_t diff = k_uptime_get_32() - alloc_start; timeout -= MIN(timeout, diff); } buf->__buf = data_alloc(buf, &size, timeout); if (!buf->__buf) { NET_BUF_ERR("%s():%d: Failed to allocate data", func, line); net_buf_destroy(buf); return NULL; } NET_BUF_ASSERT(req_size <= size); } else { buf->__buf = NULL; } buf->ref = 1U; buf->flags = 0U; buf->frags = NULL; buf->size = size; net_buf_reset(buf); #if defined(CONFIG_NET_BUF_POOL_USAGE) pool->avail_count--; __ASSERT_NO_MSG(pool->avail_count >= 0); #endif return buf; } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool, k_timeout_t timeout, const char *func, int line) { const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func, line); } #else struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, k_timeout_t timeout) { const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; return net_buf_alloc_len(pool, fixed->data_size, timeout); } #endif #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool, void *data, size_t size, k_timeout_t timeout, const char *func, int line) #else struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, void *data, size_t size, k_timeout_t timeout) #endif { struct net_buf *buf; #if defined(CONFIG_NET_BUF_LOG) buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line); #else buf = net_buf_alloc_len(pool, 0, timeout); #endif if (!buf) { return NULL; } net_buf_simple_init_with_data(&buf->b, data, size); buf->flags = NET_BUF_EXTERNAL_DATA; return buf; } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_get_debug(struct kfifo *fifo, k_timeout_t timeout, const char *func, int line) #else struct net_buf *net_buf_get(struct kfifo *fifo, k_timeout_t timeout) #endif { struct net_buf *buf, *frag; NET_BUF_DBG("%s():%d: fifo %p", func, line, fifo); buf = k_fifo_get(fifo, timeout); if (!buf) { return NULL; } NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo); /* Get any fragments belonging to this buffer */ for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) { frag->frags = k_fifo_get(fifo, K_NO_WAIT); __ASSERT_NO_MSG(frag->frags); /* The fragments flag is only for FIFO-internal usage */ frag->flags &= ~NET_BUF_FRAGS; } /* Mark the end of the fragment list */ frag->frags = NULL; return buf; } void net_buf_simple_init_with_data(struct net_buf_simple *buf, void *data, size_t size) { buf->__buf = data; buf->data = data; buf->size = size; buf->len = size; } void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve) { __ASSERT_NO_MSG(buf); __ASSERT_NO_MSG(buf->len == 0U); NET_BUF_DBG("buf %p reserve %zu", buf, reserve); buf->data = buf->__buf + reserve; } void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf) { struct net_buf *tail; unsigned int key; __ASSERT_NO_MSG(list); __ASSERT_NO_MSG(buf); for (tail = buf; tail->frags; tail = tail->frags) { tail->flags |= NET_BUF_FRAGS; } key = irq_lock(); sys_slist_append_list(list, &buf->node, &tail->node); irq_unlock(key); } struct net_buf *net_buf_slist_get(sys_slist_t *list) { struct net_buf *buf, *frag; unsigned int key; __ASSERT_NO_MSG(list); key = irq_lock(); buf = (void *)sys_slist_get(list); irq_unlock(key); if (!buf) { return NULL; } /* Get any fragments belonging to this buffer */ for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) { key = irq_lock(); frag->frags = (void *)sys_slist_get(list); irq_unlock(key); __ASSERT_NO_MSG(frag->frags); /* The fragments flag is only for list-internal usage */ frag->flags &= ~NET_BUF_FRAGS; } /* Mark the end of the fragment list */ frag->frags = NULL; return buf; } void net_buf_put(struct kfifo *fifo, struct net_buf *buf) { struct net_buf *tail; if(NULL == fifo){ BT_WARN("fifo is NULL"); return; } if(NULL == buf){ BT_WARN("buf is NULL"); return; } if(NULL == fifo || NULL == buf){ BT_WARN("fifo is NULL"); return; } __ASSERT_NO_MSG(fifo); __ASSERT_NO_MSG(buf); for (tail = buf; tail->frags; tail = tail->frags) { tail->flags |= NET_BUF_FRAGS; } k_fifo_put(fifo, buf); } #if defined(CONFIG_NET_BUF_LOG) void net_buf_unref_debug(struct net_buf *buf, const char *func, int line) #else void net_buf_unref(struct net_buf *buf) #endif { __ASSERT_NO_MSG(buf); while (buf) { struct net_buf *frags = buf->frags; struct net_buf_pool *pool; u8_t flags = buf->flags; #if defined(CONFIG_NET_BUF_LOG) if (!buf->ref) { NET_BUF_ERR("%s():%d: buf %p double free", func, line, buf); return; } #endif NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref, buf->pool_id, buf->frags); if (--buf->ref > 0) { return; } if (buf->__buf) { data_unref(buf, buf->__buf); buf->__buf = NULL; } buf->data = NULL; buf->frags = NULL; pool = net_buf_pool_get(buf->pool_id); #if defined(CONFIG_NET_BUF_POOL_USAGE) pool->avail_count++; __ASSERT_NO_MSG(pool->avail_count <= pool->buf_count); #endif if (pool->destroy) { pool->destroy(buf); } else { net_buf_destroy(buf); } if (!flags) { return; } buf = frags; } } struct net_buf *net_buf_ref(struct net_buf *buf) { __ASSERT_NO_MSG(buf); NET_BUF_DBG("buf %p (old) ref %u pool_id %u", buf, buf->ref, buf->pool_id); buf->ref++; return buf; } struct net_buf *net_buf_clone(struct net_buf *buf, k_timeout_t timeout) { bt_u32_t alloc_start = k_uptime_get_32(); struct net_buf_pool *pool; struct net_buf *clone; __ASSERT_NO_MSG(buf); pool = net_buf_pool_get(buf->pool_id); clone = net_buf_alloc_len(pool, 0, timeout); if (!clone) { return NULL; } /* If the pool supports data referencing use that. Otherwise * we need to allocate new data and make a copy. */ if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) { clone->__buf = data_ref(buf, buf->__buf); clone->data = buf->data; clone->len = buf->len; clone->size = buf->size; } else { size_t size = buf->size; if (timeout != K_NO_WAIT && timeout != K_FOREVER) { bt_u32_t diff = k_uptime_get_32() - alloc_start; timeout -= MIN(timeout, diff); } clone->__buf = data_alloc(clone, &size, timeout); if (!clone->__buf || size < buf->size) { net_buf_destroy(clone); return NULL; } clone->size = size; clone->data = clone->__buf + net_buf_headroom(buf); net_buf_add_mem(clone, buf->data, buf->len); } return clone; } struct net_buf *net_buf_frag_last(struct net_buf *buf) { __ASSERT_NO_MSG(buf); while (buf->frags) { buf = buf->frags; } return buf; } void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag) { __ASSERT_NO_MSG(parent); __ASSERT_NO_MSG(frag); if (parent->frags) { net_buf_frag_last(frag)->frags = parent->frags; } /* Take ownership of the fragment reference */ parent->frags = frag; } struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag) { __ASSERT_NO_MSG(frag); if (!head) { return net_buf_ref(frag); } net_buf_frag_insert(net_buf_frag_last(head), frag); return head; } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_frag_del_debug(struct net_buf *parent, struct net_buf *frag, const char *func, int line) #else struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag) #endif { struct net_buf *next_frag; __ASSERT_NO_MSG(frag); if (parent) { __ASSERT_NO_MSG(parent->frags); __ASSERT_NO_MSG(parent->frags == frag); parent->frags = frag->frags; } next_frag = frag->frags; frag->frags = NULL; #if defined(CONFIG_NET_BUF_LOG) net_buf_unref_debug(frag, func, line); #else net_buf_unref(frag); #endif return next_frag; } size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src, size_t offset, size_t len) { struct net_buf *frag; size_t to_copy; size_t copied; len = MIN(len, dst_len); frag = src; /* find the right fragment to start copying from */ while (frag && offset >= frag->len) { offset -= frag->len; frag = frag->frags; } /* traverse the fragment chain until len bytes are copied */ copied = 0; while (frag && len > 0) { to_copy = MIN(len, frag->len - offset); memcpy((u8_t *)dst + copied, frag->data + offset, to_copy); copied += to_copy; /* to_copy is always <= len */ len -= to_copy; frag = frag->frags; /* after the first iteration, this value will be 0 */ offset = 0; } return copied; } /* This helper routine will append multiple bytes, if there is no place for * the data in current fragment then create new fragment and add it to * the buffer. It assumes that the buffer has at least one fragment. */ size_t net_buf_append_bytes(struct net_buf *buf, size_t len, const void *value, k_timeout_t timeout, net_buf_allocator_cb allocate_cb, void *user_data) { struct net_buf *frag = net_buf_frag_last(buf); size_t added_len = 0; const u8_t *value8 = value; do { u16_t count = MIN(len, net_buf_tailroom(frag)); net_buf_add_mem(frag, value8, count); len -= count; added_len += count; value8 += count; if (len == 0) { return added_len; } frag = allocate_cb(timeout, user_data); if (!frag) { return added_len; } net_buf_frag_add(buf, frag); } while (1); /* Unreachable */ return 0; } #if defined(CONFIG_NET_BUF_SIMPLE_LOG) #define NET_BUF_SIMPLE_DBG(fmt, ...) NET_BUF_DBG(fmt, ##__VA_ARGS__) #define NET_BUF_SIMPLE_ERR(fmt, ...) NET_BUF_ERR(fmt, ##__VA_ARGS__) #define NET_BUF_SIMPLE_WARN(fmt, ...) NET_BUF_WARN(fmt, ##__VA_ARGS__) #define NET_BUF_SIMPLE_INFO(fmt, ...) NET_BUF_INFO(fmt, ##__VA_ARGS__) #else #define NET_BUF_SIMPLE_DBG(fmt, ...) #define NET_BUF_SIMPLE_ERR(fmt, ...) #define NET_BUF_SIMPLE_WARN(fmt, ...) #define NET_BUF_SIMPLE_INFO(fmt, ...) #endif /* CONFIG_NET_BUF_SIMPLE_LOG */ void net_buf_simple_clone(const struct net_buf_simple *original, struct net_buf_simple *clone) { memcpy(clone, original, sizeof(struct net_buf_simple)); } void *net_buf_simple_add(struct net_buf_simple *buf, size_t len) { u8_t *tail = net_buf_simple_tail(buf); NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); __ASSERT_NO_MSG(net_buf_simple_tailroom(buf) >= len); buf->len += len; return tail; } void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, size_t len) { NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); return memcpy(net_buf_simple_add(buf, len), mem, len); } u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val) { u8_t *u8; NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val); u8 = net_buf_simple_add(buf, 1); *u8 = val; return u8; } void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_le16(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_be16(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_le24(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_le24(val, net_buf_simple_add(buf, 3)); } void net_buf_simple_add_be24(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_be24(val, net_buf_simple_add(buf, 3)); } void net_buf_simple_add_le32(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_le32(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_be32(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_be32(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_le48(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_le48(val, net_buf_simple_add(buf, 6)); } void net_buf_simple_add_be48(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_be48(val, net_buf_simple_add(buf, 6)); } void net_buf_simple_add_le64(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_le64(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_be64(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_be64(val, net_buf_simple_add(buf, sizeof(val))); } void *net_buf_simple_push(struct net_buf_simple *buf, size_t len) { NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); __ASSERT_NO_MSG(net_buf_simple_headroom(buf) >= len); buf->data -= len; buf->len += len; return buf->data; } void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_le16(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_be16(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val) { u8_t *data = net_buf_simple_push(buf, 1); *data = val; } void net_buf_simple_push_le24(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_le24(val, net_buf_simple_push(buf, 3)); } void net_buf_simple_push_be24(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_be24(val, net_buf_simple_push(buf, 3)); } void net_buf_simple_push_le32(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_le32(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_be32(struct net_buf_simple *buf, bt_u32_t val) { NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); sys_put_be32(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_le48(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_le48(val, net_buf_simple_push(buf, 6)); } void net_buf_simple_push_be48(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_be48(val, net_buf_simple_push(buf, 6)); } void net_buf_simple_push_le64(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_le64(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_be64(struct net_buf_simple *buf, u64_t val) { NET_BUF_SIMPLE_DBG("buf %p val %" PRIu64, buf, val); sys_put_be64(val, net_buf_simple_push(buf, sizeof(val))); } void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len) { NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); __ASSERT_NO_MSG(buf->len >= len); buf->len -= len; return buf->data += len; } void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len) { void *data = buf->data; NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); __ASSERT_NO_MSG(buf->len >= len); buf->len -= len; buf->data += len; return data; } u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf) { u8_t val; val = buf->data[0]; net_buf_simple_pull(buf, 1); return val; } u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf) { u16_t val; val = UNALIGNED_GET((u16_t *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_le16_to_cpu(val); } u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf) { u16_t val; val = UNALIGNED_GET((u16_t *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_be16_to_cpu(val); } bt_u32_t net_buf_simple_pull_le24(struct net_buf_simple *buf) { struct uint24 { bt_u32_t u24:24; } __packed val; val = UNALIGNED_GET((struct uint24 *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_le24_to_cpu(val.u24); } bt_u32_t net_buf_simple_pull_be24(struct net_buf_simple *buf) { struct uint24 { bt_u32_t u24:24; } __packed val; val = UNALIGNED_GET((struct uint24 *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_be24_to_cpu(val.u24); } bt_u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf) { bt_u32_t val; val = UNALIGNED_GET((bt_u32_t *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_le32_to_cpu(val); } bt_u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf) { bt_u32_t val; val = UNALIGNED_GET((bt_u32_t *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_be32_to_cpu(val); } u64_t net_buf_simple_pull_le48(struct net_buf_simple *buf) { struct uint48 { u64_t u48:48; } __packed val; val = UNALIGNED_GET((struct uint48 *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_le48_to_cpu(val.u48); } u64_t net_buf_simple_pull_be48(struct net_buf_simple *buf) { struct uint48 { u64_t u48:48; } __packed val; val = UNALIGNED_GET((struct uint48 *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_be48_to_cpu(val.u48); } u64_t net_buf_simple_pull_le64(struct net_buf_simple *buf) { u64_t val; val = UNALIGNED_GET((u64_t *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_le64_to_cpu(val); } u64_t net_buf_simple_pull_be64(struct net_buf_simple *buf) { u64_t val; val = UNALIGNED_GET((u64_t *)buf->data); net_buf_simple_pull(buf, sizeof(val)); return sys_be64_to_cpu(val); } size_t net_buf_simple_headroom(struct net_buf_simple *buf) { return buf->data - buf->__buf; } size_t net_buf_simple_tailroom(struct net_buf_simple *buf) { return buf->size - net_buf_simple_headroom(buf) - buf->len; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/buf.c
C
apache-2.0
27,174
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ble_os.h> #include <string.h> #include <misc/util.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BLUETOOTH_DEBUG_CORE) #include <bluetooth/log.h> #include "mbox.h" struct timer *g_timer_list; #if defined(__cplusplus) extern "C" { #endif int k_mbox_new(k_mbox_t **mb, int size) { k_mbox_t *mbox; UNUSED(size); mbox = (k_mbox_t *)malloc(sizeof(k_mbox_t)); if (mbox == NULL) { return ERR_MEM; } memset(mbox, 0, sizeof(k_mbox_t)); mbox->first = mbox->last = 0; k_sem_init(&mbox->not_empty, 0, 1); k_sem_init(&mbox->not_full, 0, 1); k_sem_init(&mbox->mutex, 1, 1); mbox->wait_send = 0; *mb = mbox; BT_DBG("k_mbox_new: mbox 0x%lx\n", mbox); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* Deallocates a mailbox. If there are messages still present in the mailbox when the mailbox is deallocated, it is an indication of a programming error in lwIP and the developer should be notified. */ void k_mbox_free(k_mbox_t *mb) { if (mb != NULL) { k_mbox_t *mbox = mb; k_sem_take(&mbox->mutex, K_FOREVER); k_sem_delete(&mbox->not_empty); k_sem_delete(&mbox->not_full); k_sem_delete(&mbox->mutex); BT_DBG("sys_mbox_free: mbox 0x%lx\n", mbox); free(mbox); } } /*-----------------------------------------------------------------------------------*/ /* void sys_mbox_post(k_mbox_t *mbox, void *msg) Posts the "msg" to the mailbox. This function have to block until the "msg" is really posted. */ void k_mbox_post(k_mbox_t *mb, void *msg) { u8_t first; k_mbox_t *mbox; if (NULL == mb) { BT_ERR("invaild mbox"); return; } mbox = mb; k_sem_take(&mbox->mutex, K_FOREVER); BT_DBG("sys_mbox_post: mbox %p msg %p\n", (void *)mbox, (void *)msg); while ((mbox->last + 1) >= (mbox->first + K_MBOX_SIZE)) { mbox->wait_send++; k_sem_give(&mbox->mutex); k_sem_take(&mbox->not_full, K_FOREVER); k_sem_take(&mbox->mutex, K_FOREVER); mbox->wait_send--; } mbox->msgs[mbox->last % K_MBOX_SIZE] = msg; if (mbox->last == mbox->first) { first = 1; } else { first = 0; } mbox->last++; if (first) { k_sem_give(&mbox->not_empty); } k_sem_give(&mbox->mutex); } /* err_t k_mbox_trypost(k_mbox_t *mbox, void *msg) Try to post the "msg" to the mailbox. Returns ERR_MEM if this one is full, else, ERR_OK if the "msg" is posted. */ int k_mbox_trypost(k_mbox_t *mb, void *msg) { u8_t first; k_mbox_t *mbox; if (NULL == mb) { BT_ERR("invaild mbox"); return ERR_MEM; } mbox = mb; k_sem_take(&mbox->mutex, K_FOREVER); BT_DBG("k_mbox_trypost: mbox %p msg %p\n", (void *)mbox, (void *)msg); if ((mbox->last + 1) >= (mbox->first + K_MBOX_SIZE)) { k_sem_give(&mbox->mutex); return ERR_MEM; } mbox->msgs[mbox->last % K_MBOX_SIZE] = msg; if (mbox->last == mbox->first) { first = 1; } else { first = 0; } mbox->last++; if (first) { k_sem_give(&mbox->not_empty); } k_sem_give(&mbox->mutex); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* Blocks the thread until a message arrives in the mailbox, but does not block the thread longer than "timeout" milliseconds (similar to the sys_arch_sem_wait() function). The "msg" argument is a result parameter that is set by the function (i.e., by doing "*msg = ptr"). The "msg" parameter maybe NULL to indicate that the message should be dropped. The return values are the same as for the sys_arch_sem_wait() function: Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a timeout. Note that a function with a similar name, sys_mbox_fetch(), is implemented by lwIP. */ int k_mbox_fetch(k_mbox_t *mb, void **msg, uint32_t timeout) { uint32_t time_needed = 0; k_mbox_t *mbox; if (NULL == mb) { BT_ERR("invaild mbox"); return ERR_MEM; } mbox = mb; BT_DBG("mbox %p\n", mbox); /* The mutex lock is quick so we don't bother with the timeout stuff here. */ k_sem_take(&mbox->mutex, K_FOREVER); BT_DBG("mutex taken\n"); while (mbox->first == mbox->last) { k_sem_give(&mbox->mutex); /* We block while waiting for a mail to arrive in the mailbox. We must be prepared to timeout. */ if (timeout != 0) { time_needed = k_sem_take(&mbox->not_empty, timeout); if (time_needed == SYS_ARCH_TIMEOUT) { return SYS_ARCH_TIMEOUT; } } else { k_sem_take(&mbox->not_empty, K_FOREVER); } k_sem_take(&mbox->mutex, K_FOREVER); } if (msg != NULL) { BT_DBG("sys_mbox_fetch: mbox %p msg %p\n", (void *)mbox, *msg); *msg = mbox->msgs[mbox->first % K_MBOX_SIZE]; } else { BT_DBG("sys_mbox_fetch: mbox %p, null msg\n", (void *)mbox); } mbox->first++; if (mbox->wait_send) { k_sem_give(&mbox->not_full); } k_sem_give(&mbox->mutex); return time_needed; } /* uint32_t sys_arch_mbox_tryfetch(k_mbox_t *mbox, void **msg) similar to sys_arch_mbox_fetch, however if a message is not present in the mailbox, it immediately returns with the code SYS_MBOX_EMPTY. */ int k_mbox_tryfetch(k_mbox_t *mb, void **msg) { k_mbox_t *mbox; if (NULL == mb) { BT_ERR("invaild mbox"); return ERR_MEM; } mbox = mb; k_sem_take(&mbox->mutex, K_FOREVER); if (mbox->first == mbox->last) { k_sem_give(&mbox->mutex); return SYS_MBOX_EMPTY; } if (msg != NULL) { BT_DBG("k_mbox_tryfetch: mbox %p msg %p\n", (void *)mbox, *msg); *msg = mbox->msgs[mbox->first % K_MBOX_SIZE]; } else { BT_DBG("k_mbox_tryfetch: mbox %p, null msg\n", (void *)mbox); } mbox->first++; if (mbox->wait_send) { k_sem_give(&mbox->not_full); } k_sem_give(&mbox->mutex); return 0; } #if defined(__cplusplus) } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/mbox.c
C
apache-2.0
6,874
# SPDX-License-Identifier: Apache-2.0 add_subdirectory(src) zephyr_include_directories( include )
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/CMakeLists.txt
CMake
apache-2.0
103
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SETTINGS_FCB_H_ #define __SETTINGS_FCB_H_ #include <fs/fcb.h> #include "settings/settings.h" #ifdef __cplusplus extern "C" { #endif struct settings_fcb { struct settings_store cf_store; struct fcb cf_fcb; }; extern int settings_fcb_src(struct settings_fcb *cf); extern int settings_fcb_dst(struct settings_fcb *cf); void settings_mount_fcb_backend(struct settings_fcb *cf); #ifdef __cplusplus } #endif #endif /* __SETTINGS_FCB_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/include/settings/settings_fcbf.h
C
apache-2.0
582
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SETTINGS_FILE_H_ #define __SETTINGS_FILE_H_ #include "settings/settings.h" #ifdef __cplusplus extern "C" { #endif #define SETTINGS_FILE_NAME_MAX 32 /* max length for settings filename */ struct settings_file { struct settings_store cf_store; const char *cf_name; /* filename */ int cf_maxlines; /* max # of lines before compressing */ int cf_lines; /* private */ }; /* register file to be source of settings */ int settings_file_src(struct settings_file *cf); /* settings saves go to a file */ int settings_file_dst(struct settings_file *cf); void settings_mount_fs_backend(struct settings_file *cf); #ifdef __cplusplus } #endif #endif /* __SETTINGS_FILE_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/include/settings/settings_filef.h
C
apache-2.0
816
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SETTINGS_KV_H_ #define __SETTINGS_KV_H_ #include "settings/settings.h" #ifdef __cplusplus extern "C" { #endif struct settings_kv { struct settings_store cf_store; const char *name; /* filename */ }; /* register file to be source of settings */ int settings_kv_src(struct settings_kv *cf); /* settings saves go to a file */ int settings_kv_dst(struct settings_kv *cf); #ifdef __cplusplus } #endif #endif /* __SETTINGS_KV_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/include/settings/settings_kv.h
C
apache-2.0
576
/* * Copyright (c) 2019 Laczen * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SETTINGS_NVS_H_ #define __SETTINGS_NVS_H_ #include <fs/nvs.h> #include "settings/settings.h" #ifdef __cplusplus extern "C" { #endif /* In the NVS backend, each setting is stored in two NVS entries: * 1. setting's name * 2. setting's value * * The NVS entry ID for the setting's value is determined implicitly based on * the ID of the NVS entry for the setting's name, once that is found. The * difference between name and value ID is constant and equal to * NVS_NAME_ID_OFFSET. * * Setting's name entries start from NVS_NAMECNT_ID + 1. The entry at * NVS_NAMECNT_ID is used to store the largest name ID in use. * * Deleted records will not be found, only the last record will be * read. */ #define NVS_NAMECNT_ID 0x8000 #define NVS_NAME_ID_OFFSET 0x4000 struct settings_nvs { struct settings_store cf_store; struct nvs_fs cf_nvs; u16_t last_name_id; const char *flash_dev_name; }; /* register nvs to be a source of settings */ int settings_nvs_src(struct settings_nvs *cf); /* register nvs to be the destination of settings */ int settings_nvs_dst(struct settings_nvs *cf); /* Initialize a nvs backend. */ int settings_nvs_backend_init(struct settings_nvs *cf); #ifdef __cplusplus } #endif #endif /* __SETTINGS_NVS_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/include/settings/settings_nvs.h
C
apache-2.0
1,385
# SPDX-License-Identifier: Apache-2.0 zephyr_sources( settings_store.c settings.c settings_init.c settings_line.c ) zephyr_sources_ifdef(CONFIG_SETTINGS_FS settings_file.c) zephyr_sources_ifdef(CONFIG_SETTINGS_FCB settings_fcb.c)
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/CMakeLists.txt
CMake
apache-2.0
242
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include <bt_errno.h> #include <ble_os.h> #include "settings/settings.h" #include "settings_priv.h" #include <ble_types/types.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_SETTINGS) #include <common/log.h> /* mbedtls-base64 lib encodes data to null-terminated string */ #define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1) #if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS) sys_slist_t settings_handlers; #endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */ // K_MUTEX_DEFINE(settings_lock); struct k_mutex settings_lock; void settings_store_init(void); void settings_init(void) { k_mutex_init(&settings_lock); #if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS) sys_slist_init(&settings_handlers); #endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */ settings_store_init(); } #if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS) int settings_register(struct settings_handler *handler) { int rc = 0; #if 0 Z_STRUCT_SECTION_FOREACH(settings_handler_static, ch) { if (strcmp(handler->name, ch->name) == 0) { return -EEXIST; } } #endif k_mutex_lock(&settings_lock, K_FOREVER); struct settings_handler *ch; SYS_SLIST_FOR_EACH_CONTAINER(&settings_handlers, ch, node) { if (strcmp(handler->name, ch->name) == 0) { rc = -EEXIST; goto end; } } sys_slist_append(&settings_handlers, &handler->node); end: k_mutex_unlock(&settings_lock); return rc; } #endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */ int settings_name_steq(const char *name, const char *key, const char **next) { if (next) { *next = NULL; } if ((!name) || (!key)) { return 0; } /* name might come from flash directly, in flash the name would end * with '=' or '\0' depending how storage is done. Flash reading is * limited to what can be read */ while ((*key != '\0') && (*key == *name) && (*name != '\0') && (*name != SETTINGS_NAME_END)) { key++; name++; } if (*key != '\0') { return 0; } if (*name == SETTINGS_NAME_SEPARATOR) { if (next) { *next = name + 1; } return 1; } if ((*name == SETTINGS_NAME_END) || (*name == '\0')) { return 1; } return 0; } int settings_name_next(const char *name, const char **next) { int rc = 0; if (next) { *next = NULL; } if (!name) { return 0; } /* name might come from flash directly, in flash the name would end * with '=' or '\0' depending how storage is done. Flash reading is * limited to what can be read */ while ((*name != '\0') && (*name != SETTINGS_NAME_END) && (*name != SETTINGS_NAME_SEPARATOR)) { rc++; name++; } if (*name == SETTINGS_NAME_SEPARATOR) { if (next) { *next = name + 1; } return rc; } return rc; } struct settings_handler_static *settings_parse_and_lookup(const char *name, const char **next) { struct settings_handler_static *bestmatch; const char *tmpnext; bestmatch = NULL; if (next) { *next = NULL; } #if 0 Z_STRUCT_SECTION_FOREACH(settings_handler_static, ch) { if (!settings_name_steq(name, ch->name, &tmpnext)) { continue; } if (!bestmatch) { bestmatch = ch; if (next) { *next = tmpnext; } continue; } if (settings_name_steq(ch->name, bestmatch->name, NULL)) { bestmatch = ch; if (next) { *next = tmpnext; } } } #endif #if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS) struct settings_handler *ch; SYS_SLIST_FOR_EACH_CONTAINER(&settings_handlers, ch, node) { if (!settings_name_steq(name, ch->name, &tmpnext)) { continue; } if (!bestmatch) { bestmatch = (struct settings_handler_static *)ch; if (next) { *next = tmpnext; } continue; } if (settings_name_steq(ch->name, bestmatch->name, NULL)) { bestmatch = (struct settings_handler_static *)ch; if (next) { *next = tmpnext; } } } #endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */ return bestmatch; } int settings_call_set_handler(const char *name, size_t len, settings_read_cb read_cb, void *read_cb_arg, const struct settings_load_arg *load_arg) { int rc; const char *name_key = name; if (load_arg && load_arg->subtree && !settings_name_steq(name, load_arg->subtree, &name_key)) { return 0; } if (load_arg && load_arg->cb) { rc = load_arg->cb(name_key, len, read_cb, read_cb_arg, load_arg->param); } else { struct settings_handler_static *ch; ch = settings_parse_and_lookup(name, &name_key); if (!ch) { return 0; } rc = ch->h_set(name_key, len, read_cb, read_cb_arg); if (rc != 0) { BT_ERR("set-value failure. key: %s error(%d)", log_strdup(name), rc); /* Ignoring the error */ rc = 0; } else { BT_DBG("set-value OK. key: %s", log_strdup(name)); } } return rc; } int settings_commit(void) { return settings_commit_subtree(NULL); } int settings_commit_subtree(const char *subtree) { int rc; int rc2; rc = 0; #if 0 Z_STRUCT_SECTION_FOREACH(settings_handler_static, ch) { if (subtree && !settings_name_steq(ch->name, subtree, NULL)) { continue; } if (ch->h_commit) { rc2 = ch->h_commit(); if (!rc) { rc = rc2; } } } #endif #if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS) struct settings_handler *ch; SYS_SLIST_FOR_EACH_CONTAINER(&settings_handlers, ch, node) { if (subtree && !settings_name_steq(ch->name, subtree, NULL)) { continue; } if (ch->h_commit) { rc2 = ch->h_commit(); if (!rc) { rc = rc2; } } } #endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */ return rc; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings.c
C
apache-2.0
5,656
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <stdbool.h> #include <fs/fcb.h> #include <string.h> #include <assert.h> #include "settings/settings.h" #include "settings/settings_fcb.h" #include "settings_priv.h" #include <logging/log.h> LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL); #define SETTINGS_FCB_VERS 1 int settings_backend_init(void); void settings_mount_fcb_backend(struct settings_fcb *cf); static int settings_fcb_load(struct settings_store *cs, const struct settings_load_arg *arg); static int settings_fcb_save(struct settings_store *cs, const char *name, const char *value, size_t val_len); static const struct settings_store_itf settings_fcb_itf = { .csi_load = settings_fcb_load, .csi_save = settings_fcb_save, }; int settings_fcb_src(struct settings_fcb *cf) { int rc; cf->cf_fcb.f_version = SETTINGS_FCB_VERS; cf->cf_fcb.f_scratch_cnt = 1; while (1) { rc = fcb_init(FLASH_AREA_ID(storage), &cf->cf_fcb); if (rc) { return -EINVAL; } /* * Check if system was reset in middle of emptying a sector. * This situation is recognized by checking if the scratch block * is missing. */ if (fcb_free_sector_cnt(&cf->cf_fcb) < 1) { rc = flash_area_erase(cf->cf_fcb.fap, cf->cf_fcb.f_active.fe_sector->fs_off, cf->cf_fcb.f_active.fe_sector->fs_size); if (rc) { return -EIO; } } else { break; } } cf->cf_store.cs_itf = &settings_fcb_itf; settings_src_register(&cf->cf_store); return 0; } int settings_fcb_dst(struct settings_fcb *cf) { cf->cf_store.cs_itf = &settings_fcb_itf; settings_dst_register(&cf->cf_store); return 0; } /** * @brief Check if there is any duplicate of the current setting * * This function checks if there is any duplicated data further in the buffer. * * @param cf FCB handler * @param entry_ctx Current entry context * @param name The name of the current entry * * @retval false No duplicates found * @retval true Duplicate found */ static bool settings_fcb_check_duplicate(struct settings_fcb *cf, const struct fcb_entry_ctx *entry_ctx, const char * const name) { struct fcb_entry_ctx entry2_ctx = *entry_ctx; while (fcb_getnext(&cf->cf_fcb, &entry2_ctx.loc) == 0) { char name2[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1]; size_t name2_len; if (settings_line_name_read(name2, sizeof(name2), &name2_len, &entry2_ctx)) { LOG_ERR("failed to load line"); continue; } name2[name2_len] = '\0'; if (!strcmp(name, name2)) { return true; } } return false; } static int read_entry_len(const struct fcb_entry_ctx *entry_ctx, off_t off) { if (off >= entry_ctx->loc.fe_data_len) { return 0; } return entry_ctx->loc.fe_data_len - off; } static int settings_fcb_load_priv(struct settings_store *cs, line_load_cb cb, void *cb_arg, bool filter_duplicates) { struct settings_fcb *cf = (struct settings_fcb *)cs; struct fcb_entry_ctx entry_ctx = { {.fe_sector = NULL, .fe_elem_off = 0}, .fap = cf->cf_fcb.fap }; int rc; while ((rc = fcb_getnext(&cf->cf_fcb, &entry_ctx.loc)) == 0) { char name[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1]; size_t name_len; int rc; bool pass_entry = true; rc = settings_line_name_read(name, sizeof(name), &name_len, (void *)&entry_ctx); if (rc) { LOG_ERR("Failed to load line name: %d", rc); continue; } name[name_len] = '\0'; if (filter_duplicates && (!read_entry_len(&entry_ctx, name_len+1) || settings_fcb_check_duplicate(cf, &entry_ctx, name))) { pass_entry = false; } /*name, val-read_cb-ctx, val-off*/ /* take into account '=' separator after the name */ if (pass_entry) { cb(name, &entry_ctx, name_len + 1, cb_arg); } } if (rc == -ENOTSUP) { rc = 0; } return 0; } static int settings_fcb_load(struct settings_store *cs, const struct settings_load_arg *arg) { return settings_fcb_load_priv( cs, settings_line_load_cb, (void *)arg, true); } static int read_handler(void *ctx, off_t off, char *buf, size_t *len) { struct fcb_entry_ctx *entry_ctx = ctx; if (off >= entry_ctx->loc.fe_data_len) { *len = 0; return 0; } if ((off + *len) > entry_ctx->loc.fe_data_len) { *len = entry_ctx->loc.fe_data_len - off; } return flash_area_read(entry_ctx->fap, FCB_ENTRY_FA_DATA_OFF(entry_ctx->loc) + off, buf, *len); } static void settings_fcb_compress(struct settings_fcb *cf) { int rc; struct fcb_entry_ctx loc1; struct fcb_entry_ctx loc2; char name1[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN]; char name2[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN]; int copy; u8_t rbs; rc = fcb_append_to_scratch(&cf->cf_fcb); if (rc) { return; /* XXX */ } rbs = flash_area_align(cf->cf_fcb.fap); loc1.fap = cf->cf_fcb.fap; loc1.loc.fe_sector = NULL; loc1.loc.fe_elem_off = 0U; while (fcb_getnext(&cf->cf_fcb, &loc1.loc) == 0) { if (loc1.loc.fe_sector != cf->cf_fcb.f_oldest) { break; } size_t val1_off; rc = settings_line_name_read(name1, sizeof(name1), &val1_off, &loc1); if (rc) { continue; } if (val1_off + 1 == loc1.loc.fe_data_len) { /* Lack of a value so the record is a deletion-record */ /* No sense to copy empty entry from */ /* the oldest sector */ continue; } loc2 = loc1; copy = 1; while (fcb_getnext(&cf->cf_fcb, &loc2.loc) == 0) { size_t val2_off; rc = settings_line_name_read(name2, sizeof(name2), &val2_off, &loc2); if (rc) { continue; } if ((val1_off == val2_off) && !memcmp(name1, name2, val1_off)) { copy = 0; break; } } if (!copy) { continue; } /* * Can't find one. Must copy. */ rc = fcb_append(&cf->cf_fcb, loc1.loc.fe_data_len, &loc2.loc); if (rc) { continue; } rc = settings_line_entry_copy(&loc2, 0, &loc1, 0, loc1.loc.fe_data_len); if (rc) { continue; } rc = fcb_append_finish(&cf->cf_fcb, &loc2.loc); if (rc != 0) { LOG_ERR("Failed to finish fcb_append (%d)", rc); } } rc = fcb_rotate(&cf->cf_fcb); if (rc != 0) { LOG_ERR("Failed to fcb rotate (%d)", rc); } } static size_t get_len_cb(void *ctx) { struct fcb_entry_ctx *entry_ctx = ctx; return entry_ctx->loc.fe_data_len; } static int write_handler(void *ctx, off_t off, char const *buf, size_t len) { struct fcb_entry_ctx *entry_ctx = ctx; return flash_area_write(entry_ctx->fap, FCB_ENTRY_FA_DATA_OFF(entry_ctx->loc) + off, buf, len); } /* ::csi_save implementation */ static int settings_fcb_save_priv(struct settings_store *cs, const char *name, const char *value, size_t val_len) { struct settings_fcb *cf = (struct settings_fcb *)cs; struct fcb_entry_ctx loc; int len; int rc; int i; u8_t wbs; if (!name) { return -EINVAL; } wbs = cf->cf_fcb.f_align; len = settings_line_len_calc(name, val_len); for (i = 0; i < cf->cf_fcb.f_sector_cnt; i++) { rc = fcb_append(&cf->cf_fcb, len, &loc.loc); if (rc != -ENOSPC) { break; } /* FCB can compress up to cf->cf_fcb.f_sector_cnt - 1 times. */ if (i < (cf->cf_fcb.f_sector_cnt - 1)) { settings_fcb_compress(cf); } } if (rc) { return -EINVAL; } loc.fap = cf->cf_fcb.fap; rc = settings_line_write(name, value, val_len, 0, (void *)&loc); if (rc != -EIO) { i = fcb_append_finish(&cf->cf_fcb, &loc.loc); if (!rc) { rc = i; } } return rc; } static int settings_fcb_save(struct settings_store *cs, const char *name, const char *value, size_t val_len) { struct settings_line_dup_check_arg cdca; if (val_len > 0 && value == NULL) { return -EINVAL; } /* * Check if we're writing the same value again. */ cdca.name = name; cdca.val = (char *)value; cdca.is_dup = 0; cdca.val_len = val_len; settings_fcb_load_priv(cs, settings_line_dup_check_cb, &cdca, false); if (cdca.is_dup == 1) { return 0; } return settings_fcb_save_priv(cs, name, (char *)value, val_len); } void settings_mount_fcb_backend(struct settings_fcb *cf) { u8_t rbs; rbs = cf->cf_fcb.f_align; settings_line_io_init(read_handler, write_handler, get_len_cb, rbs); } int settings_backend_init(void) { static struct flash_sector settings_fcb_area[CONFIG_SETTINGS_FCB_NUM_AREAS + 1]; static struct settings_fcb config_init_settings_fcb = { .cf_fcb.f_magic = CONFIG_SETTINGS_FCB_MAGIC, .cf_fcb.f_sectors = settings_fcb_area, }; bt_u32_t cnt = sizeof(settings_fcb_area) / sizeof(settings_fcb_area[0]); int rc; const struct flash_area *fap; rc = flash_area_get_sectors(FLASH_AREA_ID(storage), &cnt, settings_fcb_area); if (rc == -ENODEV) { return rc; } else if (rc != 0 && rc != -ENOMEM) { k_panic(); } config_init_settings_fcb.cf_fcb.f_sector_cnt = cnt; rc = settings_fcb_src(&config_init_settings_fcb); if (rc != 0) { rc = flash_area_open(FLASH_AREA_ID(storage), &fap); if (rc == 0) { rc = flash_area_erase(fap, 0, fap->fa_size); flash_area_close(fap); } if (rc != 0) { k_panic(); } else { rc = settings_fcb_src(&config_init_settings_fcb); } } if (rc != 0) { k_panic(); } rc = settings_fcb_dst(&config_init_settings_fcb); if (rc != 0) { k_panic(); } settings_mount_fcb_backend(&config_init_settings_fcb); return rc; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_fcb.c
C
apache-2.0
9,375
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <stdbool.h> #include <assert.h> #include <ble_os.h> #include <fs/fs.h> #include "settings/settings.h" #include "settings/settings_file.h" #include "settings_priv.h" #include <logging/log.h> LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL); int settings_backend_init(void); void settings_mount_fs_backend(struct settings_file *cf); static int settings_file_load(struct settings_store *cs, const struct settings_load_arg *arg); static int settings_file_save(struct settings_store *cs, const char *name, const char *value, size_t val_len); static const struct settings_store_itf settings_file_itf = { .csi_load = settings_file_load, .csi_save = settings_file_save, }; /* * Register a file to be a source of configuration. */ int settings_file_src(struct settings_file *cf) { if (!cf->cf_name) { return -EINVAL; } cf->cf_store.cs_itf = &settings_file_itf; settings_src_register(&cf->cf_store); return 0; } /* * Register a file to be a destination of configuration. */ int settings_file_dst(struct settings_file *cf) { if (!cf->cf_name) { return -EINVAL; } cf->cf_store.cs_itf = &settings_file_itf; settings_dst_register(&cf->cf_store); return 0; } /** * @brief Check if there is any duplicate of the current setting * * This function checks if there is any duplicated data further in the buffer. * * @param entry_ctx Current entry context * @param name The name of the current entry * * @retval false No duplicates found * @retval true Duplicate found */ static bool settings_file_check_duplicate( const struct line_entry_ctx *entry_ctx, const char * const name) { struct line_entry_ctx entry2_ctx = *entry_ctx; /* Searching the duplicates */ while (settings_next_line_ctx(&entry2_ctx) == 0) { char name2[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1]; size_t name2_len; if (entry2_ctx.len == 0) { break; } if (settings_line_name_read(name2, sizeof(name2), &name2_len, &entry2_ctx)) { continue; } name2[name2_len] = '\0'; if (!strcmp(name, name2)) { return true; } } return false; } static int read_entry_len(const struct line_entry_ctx *entry_ctx, off_t off) { if (off >= entry_ctx->len) { return 0; } return entry_ctx->len - off; } static int settings_file_load_priv(struct settings_store *cs, line_load_cb cb, void *cb_arg, bool filter_duplicates) { struct settings_file *cf = (struct settings_file *)cs; struct fs_file_t file; int lines; int rc; struct line_entry_ctx entry_ctx = { .stor_ctx = (void *)&file, .seek = 0, .len = 0 /* unknown length */ }; lines = 0; rc = fs_open(&file, cf->cf_name); if (rc != 0) { return -EINVAL; } while (1) { char name[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1]; size_t name_len; bool pass_entry = true; rc = settings_next_line_ctx(&entry_ctx); if (rc || entry_ctx.len == 0) { break; } rc = settings_line_name_read(name, sizeof(name), &name_len, &entry_ctx); if (rc || name_len == 0) { break; } name[name_len] = '\0'; if (filter_duplicates && (!read_entry_len(&entry_ctx, name_len+1) || settings_file_check_duplicate(&entry_ctx, name))) { pass_entry = false; } /*name, val-read_cb-ctx, val-off*/ /* take into account '=' separator after the name */ if (pass_entry) { cb(name, (void *)&entry_ctx, name_len + 1, cb_arg); } lines++; } rc = fs_close(&file); cf->cf_lines = lines; return rc; } /* * Called to load configuration items. */ static int settings_file_load(struct settings_store *cs, const struct settings_load_arg *arg) { return settings_file_load_priv(cs, settings_line_load_cb, (void *)arg, true); } static void settings_tmpfile(char *dst, const char *src, char *pfx) { int len; int pfx_len; len = strlen(src); pfx_len = strlen(pfx); if (len + pfx_len >= SETTINGS_FILE_NAME_MAX) { len = SETTINGS_FILE_NAME_MAX - pfx_len - 1; } memcpy(dst, src, len); memcpy(dst + len, pfx, pfx_len); dst[len + pfx_len] = '\0'; } static int settings_file_create_or_replace(struct fs_file_t *zfp, const char *file_name) { struct fs_dirent entry; if (fs_stat(file_name, &entry) == 0) { if (entry.type == FS_DIR_ENTRY_FILE) { if (fs_unlink(file_name)) { return -EIO; } } else { return -EISDIR; } } return fs_open(zfp, file_name); } /* * Try to compress configuration file by keeping unique names only. */ static int settings_file_save_and_compress(struct settings_file *cf, const char *name, const char *value, size_t val_len) { int rc, rc2; struct fs_file_t rf; struct fs_file_t wf; char tmp_file[SETTINGS_FILE_NAME_MAX]; char name1[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN]; char name2[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN]; struct line_entry_ctx loc1 = { .stor_ctx = &rf, .seek = 0, .len = 0 /* unknown length */ }; struct line_entry_ctx loc2; struct line_entry_ctx loc3 = { .stor_ctx = &wf }; int copy; int lines; size_t new_name_len; size_t val1_off; if (fs_open(&rf, cf->cf_name) != 0) { return -ENOEXEC; } settings_tmpfile(tmp_file, cf->cf_name, ".cmp"); if (settings_file_create_or_replace(&wf, tmp_file)) { fs_close(&rf); return -ENOEXEC; } lines = 0; new_name_len = strlen(name); while (1) { rc = settings_next_line_ctx(&loc1); if (rc || loc1.len == 0) { /* try to amend new value to the commpresed file */ break; } rc = settings_line_name_read(name1, sizeof(name1), &val1_off, &loc1); if (rc) { /* try to process next line */ continue; } if (val1_off + 1 == loc1.len) { /* Lack of a value so the record is a deletion-record */ /* No sense to copy empty entry from */ /* the oldest sector */ continue; } /* avoid copping value which will be overwritten by new value*/ if ((val1_off == new_name_len) && !memcmp(name1, name, val1_off)) { continue; } loc2 = loc1; copy = 1; while (1) { size_t val2_off; rc = settings_next_line_ctx(&loc2); if (rc || loc2.len == 0) { /* try to amend new value to */ /* the commpresed file */ break; } rc = settings_line_name_read(name2, sizeof(name2), &val2_off, &loc2); if (rc) { /* try to process next line */ continue; } if ((val1_off == val2_off) && !memcmp(name1, name2, val1_off)) { copy = 0; /* newer version doesn't exist */ break; } } if (!copy) { continue; } loc2 = loc1; loc2.len += 2; loc2.seek -= 2; rc = settings_line_entry_copy(&loc3, 0, &loc2, 0, loc2.len); if (rc) { /* compressed file might be corrupted */ goto end_rolback; } lines++; } /* at last store the new value */ rc = settings_line_write(name, value, val_len, 0, &loc3); if (rc) { /* compressed file might be corrupted */ goto end_rolback; } rc = fs_close(&wf); rc2 = fs_close(&rf); if (rc == 0 && rc2 == 0 && fs_unlink(cf->cf_name) == 0) { if (fs_rename(tmp_file, cf->cf_name)) { return -ENOENT; } cf->cf_lines = lines + 1; } else { rc = -EIO; } /* * XXX at settings_file_load(), look for .cmp if actual file does not * exist. */ return 0; end_rolback: (void)fs_close(&wf); if (fs_close(&rf) == 0) { (void)fs_unlink(tmp_file); } return -EIO; } static int settings_file_save_priv(struct settings_store *cs, const char *name, const char *value, size_t val_len) { struct settings_file *cf = (struct settings_file *)cs; struct line_entry_ctx entry_ctx; struct fs_file_t file; int rc2; int rc; if (!name) { return -EINVAL; } if (cf->cf_maxlines && (cf->cf_lines + 1 >= cf->cf_maxlines)) { /* * Compress before config file size exceeds * the max number of lines. */ return settings_file_save_and_compress(cf, name, value, val_len); } /* * Open the file to add this one value. */ rc = fs_open(&file, cf->cf_name); if (rc == 0) { rc = fs_seek(&file, 0, FS_SEEK_END); if (rc == 0) { entry_ctx.stor_ctx = &file; rc = settings_line_write(name, value, val_len, 0, (void *)&entry_ctx); if (rc == 0) { cf->cf_lines++; } } rc2 = fs_close(&file); if (rc == 0) { rc = rc2; } } return rc; } /* * Called to save configuration. */ static int settings_file_save(struct settings_store *cs, const char *name, const char *value, size_t val_len) { struct settings_line_dup_check_arg cdca; if (val_len > 0 && value == NULL) { return -EINVAL; } /* * Check if we're writing the same value again. */ cdca.name = name; cdca.val = (char *)value; cdca.is_dup = 0; cdca.val_len = val_len; settings_file_load_priv(cs, settings_line_dup_check_cb, &cdca, false); if (cdca.is_dup == 1) { return 0; } return settings_file_save_priv(cs, name, (char *)value, val_len); } static int read_handler(void *ctx, off_t off, char *buf, size_t *len) { struct line_entry_ctx *entry_ctx = ctx; struct fs_file_t *file = entry_ctx->stor_ctx; ssize_t r_len; int rc; /* 0 is reserved for reding the length-field only */ if (entry_ctx->len != 0) { if (off >= entry_ctx->len) { *len = 0; return 0; } if ((off + *len) > entry_ctx->len) { *len = entry_ctx->len - off; } } rc = fs_seek(file, entry_ctx->seek + off, FS_SEEK_SET); if (rc) { goto end; } r_len = fs_read(file, buf, *len); if (r_len >= 0) { *len = r_len; rc = 0; } else { rc = r_len; } end: return rc; } static size_t get_len_cb(void *ctx) { struct line_entry_ctx *entry_ctx = ctx; return entry_ctx->len; } static int write_handler(void *ctx, off_t off, char const *buf, size_t len) { struct line_entry_ctx *entry_ctx = ctx; struct fs_file_t *file = entry_ctx->stor_ctx; int rc; /* append to file only */ rc = fs_seek(file, 0, FS_SEEK_END); if (rc == 0) { rc = fs_write(file, buf, len); if (rc > 0) { rc = 0; } } return rc; } void settings_mount_fs_backend(struct settings_file *cf) { settings_line_io_init(read_handler, write_handler, get_len_cb, 1); } int settings_backend_init(void) { static struct settings_file config_init_settings_file = { .cf_name = CONFIG_SETTINGS_FS_FILE, .cf_maxlines = CONFIG_SETTINGS_FS_MAX_LINES }; int rc; rc = settings_file_src(&config_init_settings_file); if (rc) { k_panic(); } rc = settings_file_dst(&config_init_settings_file); if (rc) { k_panic(); } settings_mount_fs_backend(&config_init_settings_file); /* * Must be called after root FS has been initialized. */ rc = fs_mkdir(CONFIG_SETTINGS_FS_DIR); /* * The following lines mask the file exist error. */ if (rc == -EEXIST) { rc = 0; } return rc; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_file.c
C
apache-2.0
10,829
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <stdio.h> #include <stdbool.h> #include <bt_errno.h> #include "settings/settings.h" //#include "settings/settings_files.h" #include <ble_os.h> bool settings_subsys_initialized; void settings_init(void); int settings_backend_init(void); int settings_subsys_init(void) { int err = 0; if (settings_subsys_initialized) { return 0; } settings_init(); err = settings_backend_init(); /* func rises kernel panic once error */ if (!err) { settings_subsys_initialized = true; } return err; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_init.c
C
apache-2.0
667
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <assert.h> #include <ble_os.h> #include <aos/kv.h> #include <bt_errno.h> #include "settings/settings.h" #include "settings/settings_kv.h" #include "settings_priv.h" #define BT_DBG_ENABLED 0 #include "common/log.h" static int settings_kv_load(struct settings_store *cs, const struct settings_load_arg *arg); static int settings_kv_save(struct settings_store *cs, const char *name, const char *value, size_t val_len); static struct settings_store_itf settings_kv_itf = { .csi_load = settings_kv_load, .csi_save = settings_kv_save, }; int settings_kv_src(struct settings_kv *cf) { if (!cf->name) { return -EINVAL; } cf->cf_store.cs_itf = &settings_kv_itf; settings_src_register(&cf->cf_store); return 0; } int settings_kv_dst(struct settings_kv *cf) { if (!cf->name) { return -EINVAL; } cf->cf_store.cs_itf = &settings_kv_itf; settings_dst_register(&cf->cf_store); return 0; } struct settings_kv_read_arg_t { char *val; uint16_t val_size; }; static ssize_t _settings_kv_read_cb(void *cb_arg, void *data, size_t len) { struct settings_kv_read_arg_t *read_arg = cb_arg; size_t read_len = 0; BT_DBG("cb_arg %p, read_arg->val %p, read_arg->val_size %d, data %p, len %d", cb_arg, read_arg?read_arg->val:0, read_arg?read_arg->val_size:0, data, len); if (data && read_arg && read_arg->val && read_arg->val_size && len >= read_arg->val_size) { read_len = len > read_arg->val_size? read_arg->val_size : len; memcpy(data, read_arg->val, read_len); return read_len; } return -1; } static void _settings_kv_load(char *key, char *val, uint16_t val_size, void *arg) { const char *kv_prefix = "bt/"; struct settings_kv_read_arg_t read_arg = {0}; if (0 == strncmp(kv_prefix, key, 3)) { BT_DBG("%s,size %d", key, val_size); read_arg.val = val; read_arg.val_size = val_size; settings_call_set_handler(key, val_size, _settings_kv_read_cb, &read_arg, arg); } } /* * Called to load configuration items. cb must be called for every configuration * item found. */ static int settings_kv_load(struct settings_store *cs, const struct settings_load_arg *arg) { #ifdef CONFIG_BT_SETTINGS #if 0 //remove for build error extern void __kv_foreach(void (*func)(char *key, char *val, uint16_t val_size, void *arg), void *arg); __kv_foreach(_settings_kv_load, (void *)arg); #endif #endif return 0; } /* * Called to save configuration. */ static int settings_kv_save(struct settings_store *cs, const char *name, const char *value, size_t val_len) { int rc; if (!name) { return -EINVAL; } //delete key if (value == NULL) { aos_kv_del(name); return 0; } rc = aos_kv_set(name, (void *)value, val_len, 1); if (rc < 0) { BT_ERR("update key fail %s,%s", name, value); return -EIO; } printf("setting update %s, %s\n", name, value); return 0; } int settings_backend_init(void) { static struct settings_kv config_init_settings_kv = { .name = "btsetting", }; settings_kv_src(&config_init_settings_kv); settings_kv_dst(&config_init_settings_kv); return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_kv.c
C
apache-2.0
3,418
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <ctype.h> #include <string.h> #include "settings/settings.h" #include "settings_priv.h" #include "bt_errno.h" #ifdef CONFIG_SETTINGS_USE_BASE64 #include "base64.h" #endif //#include <logging/log.h> //LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL); struct settings_io_cb_s { int (*read_cb)(void *ctx, off_t off, char *buf, size_t *len); int (*write_cb)(void *ctx, off_t off, char const *buf, size_t len); size_t (*get_len_cb)(void *ctx); u8_t rwbs; } static settings_io_cb; #define MAX_ENC_BLOCK_SIZE 4 int settings_line_write(const char *name, const char *value, size_t val_len, off_t w_loc, void *cb_arg) { size_t w_size, rem, add; #ifdef CONFIG_SETTINGS_USE_BASE64 /* minimal buffer for encoding base64 + EOL*/ char enc_buf[MAX_ENC_BLOCK_SIZE + 1]; char *p_enc = enc_buf; size_t enc_len = 0; #endif bool done; char w_buf[16]; /* write buff, must be aligned either to minimal */ /* base64 encoding size and write-block-size */ int rc; u8_t wbs = settings_io_cb.rwbs; #ifdef CONFIG_SETTINGS_ENCODE_LEN u16_t len_field; #endif rem = strlen(name); #ifdef CONFIG_SETTINGS_ENCODE_LEN len_field = settings_line_len_calc(name, val_len); memcpy(w_buf, &len_field, sizeof(len_field)); w_size = 0; add = sizeof(len_field) % wbs; if (add) { w_size = wbs - add; if (rem < w_size) { w_size = rem; } memcpy(w_buf + sizeof(len_field), name, w_size); name += w_size; rem -= w_size; } w_size += sizeof(len_field); if (w_size % wbs == 0) { rc = settings_io_cb.write_cb(cb_arg, w_loc, w_buf, w_size); if (rc) { return -EIO; } } /* The Alternative to condition above mean that `rem == 0` as `name` */ /* must have been consumed */ #endif w_size = rem - rem % wbs; rem %= wbs; rc = settings_io_cb.write_cb(cb_arg, w_loc, name, w_size); w_loc += w_size; name += w_size; w_size = rem; if (rem) { memcpy(w_buf, name, rem); } w_buf[rem] = '='; w_size++; rem = val_len; done = false; while (1) { while (w_size < sizeof(w_buf)) { #ifdef CONFIG_SETTINGS_USE_BASE64 if (enc_len) { add = MIN(enc_len, sizeof(w_buf) - w_size); memcpy(&w_buf[w_size], p_enc, add); enc_len -= add; w_size += add; p_enc += add; } else { #endif if (rem) { #ifdef CONFIG_SETTINGS_USE_BASE64 add = MIN(rem, MAX_ENC_BLOCK_SIZE/4*3); rc = base64_encode(enc_buf, sizeof(enc_buf), &enc_len, value, add); if (rc) { return -EINVAL; } value += add; rem -= add; p_enc = enc_buf; #else add = MIN(rem, sizeof(w_buf) - w_size); memcpy(&w_buf[w_size], value, add); value += add; rem -= add; w_size += add; #endif } else { add = (w_size) % wbs; if (add) { add = wbs - add; memset(&w_buf[w_size], '\0', add); w_size += add; } done = true; break; } #ifdef CONFIG_SETTINGS_USE_BASE64 } #endif } rc = settings_io_cb.write_cb(cb_arg, w_loc, w_buf, w_size); if (rc) { return -EIO; } if (done) { break; } w_loc += w_size; w_size = 0; } return 0; } #ifdef CONFIG_SETTINGS_ENCODE_LEN int settings_next_line_ctx(struct line_entry_ctx *entry_ctx) { size_t len_read; u16_t readout; int rc; entry_ctx->seek += entry_ctx->len; /* to begin of nex line */ entry_ctx->len = 0; /* ask read handler to ignore len */ rc = settings_line_raw_read(0, (char *)&readout, sizeof(readout), &len_read, entry_ctx); if (rc == 0) { if (len_read != sizeof(readout)) { if (len_read != 0) { rc = -ESPIPE; } } else { entry_ctx->seek += sizeof(readout); entry_ctx->len = readout; } } return rc; } #endif int settings_line_len_calc(const char *name, size_t val_len) { int len; #ifdef CONFIG_SETTINGS_USE_BASE64 /* <enc(value)> */ len = val_len/3*4 + ((val_len%3) ? 4 : 0); #else /* <evalue> */ len = val_len; #endif /* <name>=<enc(value)> */ len += strlen(name) + 1; return len; } /** * Read RAW settings line entry data until a char from the storage. * * @param seek offset form the line beginning. * @param[out] out buffer for name * @param[in] len_req size of <p>out</p> buffer * @param[out] len_read length of read name * @param[in] until_char pointer on char value until which all line data will * be read. If Null entire data will be read. * @param[in] cb_arg settings line storage context expected by the * <p>read_cb</p> implementation * * @retval 0 on success, * -ERCODE on storage errors */ static int settings_line_raw_read_until(off_t seek, char *out, size_t len_req, size_t *len_read, char const *until_char, void *cb_arg) { size_t rem_size, len; char temp_buf[16]; /* buffer for fit read-block-size requirements */ size_t exp_size, read_size; u8_t rbs = settings_io_cb.rwbs; off_t off; int rc; if (len_req == 0) { return -EINVAL; } rem_size = len_req; while (rem_size) { off = seek / rbs * rbs; read_size = sizeof(temp_buf); exp_size = read_size; rc = settings_io_cb.read_cb(cb_arg, off, temp_buf, &read_size); if (rc) { return -EIO; } off = seek - off; len = read_size - off; len = MIN(rem_size, len); if (until_char != NULL) { char *pend; pend = memchr(&temp_buf[off], *until_char, len); if (pend != NULL) { len = pend - &temp_buf[off]; rc = 1; /* will cause loop expiration */ } } memcpy(out, &temp_buf[off], len); rem_size -= len; if (exp_size > read_size || rc) { break; } out += len; seek += len; } *len_read = len_req - rem_size; if (until_char != NULL) { return (rc) ? 0 : 1; } return 0; } int settings_line_raw_read(off_t seek, char *out, size_t len_req, size_t *len_read, void *cb_arg) { return settings_line_raw_read_until(seek, out, len_req, len_read, NULL, cb_arg); } #ifdef CONFIG_SETTINGS_USE_BASE64 /* off from value begin */ int settings_line_val_read(off_t val_off, off_t off, char *out, size_t len_req, size_t *len_read, void *cb_arg) { char enc_buf[16 + 1]; char dec_buf[sizeof(enc_buf)/4 * 3 + 1]; size_t rem_size, read_size, exp_size, clen, olen; off_t seek_begin, off_begin; int rc; rem_size = len_req; while (rem_size) { seek_begin = off / 3 * 4; off_begin = seek_begin / 4 * 3; read_size = rem_size / 3 * 4; read_size += (rem_size % 3 != 0 || off_begin != off) ? 4 : 0; read_size = MIN(read_size, sizeof(enc_buf) - 1); exp_size = read_size; rc = settings_line_raw_read(val_off + seek_begin, enc_buf, read_size, &read_size, cb_arg); if (rc) { return rc; } enc_buf[read_size] = 0; /* breaking guaranteed */ read_size = strlen(enc_buf); if (read_size == 0) { /* a NULL value (deleted entry) */ *len_read = 0; return 0; } if (read_size % 4) { /* unexpected use case - an encoding problem */ return -EINVAL; } rc = base64_decode(dec_buf, sizeof(dec_buf), &olen, enc_buf, read_size); if (rc) { return rc; } dec_buf[olen] = 0; clen = MIN(olen + off_begin - off, rem_size); memcpy(out, &dec_buf[off - off_begin], clen); rem_size -= clen; if (exp_size > read_size || olen < read_size/4*3) { break; } out += clen; off += clen; } *len_read = len_req - rem_size; return 0; } #else /* off from value begin */ int settings_line_val_read(off_t val_off, off_t off, char *out, size_t len_req, size_t *len_read, void *cb_arg) { return settings_line_raw_read(val_off + off, out, len_req, len_read, cb_arg); } #endif size_t settings_line_val_get_len(off_t val_off, void *read_cb_ctx) { size_t len; len = settings_io_cb.get_len_cb(read_cb_ctx); #ifdef CONFIG_SETTINGS_USE_BASE64 u8_t raw[2]; int rc; size_t len_base64 = len - val_off; /* don't care about lack of alignmet to 4 B */ /* entire value redout call will return error anyway */ if (len_base64 >= 4) { /* read last 2 B of base64 */ rc = settings_line_raw_read(len - 2, raw, 2, &len, read_cb_ctx); if (rc || len != 2) { /* very unexpected error */ if (rc != 0) { LOG_ERR("Failed to read the storage (%d)", rc); } return 0; } len = (len_base64 / 4) * 3; /* '=' is the padding of Base64 */ if (raw[0] == '=') { len -= 2; } else if (raw[1] == '=') { len--; } return len; } else { return 0; } #else return len - val_off; #endif } /** * @param line_loc offset of the settings line, expect that it is aligned to rbs physically. * @param seek offset form the line beginning. * @retval 0 : read proper name * 1 : when read unproper name * -ERCODE for storage errors */ int settings_line_name_read(char *out, size_t len_req, size_t *len_read, void *cb_arg) { char const until_char = '='; return settings_line_raw_read_until(0, out, len_req, len_read, &until_char, cb_arg); } int settings_line_entry_copy(void *dst_ctx, off_t dst_off, void *src_ctx, off_t src_off, size_t len) { int rc; char buf[16]; size_t chunk_size; while (len) { chunk_size = MIN(len, sizeof(buf)); rc = settings_io_cb.read_cb(src_ctx, src_off, buf, &chunk_size); if (rc) { break; } rc = settings_io_cb.write_cb(dst_ctx, dst_off, buf, chunk_size); if (rc) { break; } src_off += chunk_size; dst_off += chunk_size; len -= chunk_size; } return rc; } void settings_line_io_init(int (*read_cb)(void *ctx, off_t off, char *buf, size_t *len), int (*write_cb)(void *ctx, off_t off, char const *buf, size_t len), size_t (*get_len_cb)(void *ctx), u8_t io_rwbs) { settings_io_cb.read_cb = read_cb; settings_io_cb.write_cb = write_cb; settings_io_cb.get_len_cb = get_len_cb; settings_io_cb.rwbs = io_rwbs; } /* val_off - offset of value-string within line entries */ static int settings_line_cmp(char const *val, size_t val_len, void *val_read_cb_ctx, off_t val_off) { size_t len_read, exp_len; size_t rem; char buf[16]; int rc; off_t off = 0; if (val_len == 0) { return -EINVAL; } for (rem = val_len; rem > 0; rem -= len_read) { len_read = exp_len = MIN(sizeof(buf), rem); rc = settings_line_val_read(val_off, off, buf, len_read, &len_read, val_read_cb_ctx); if (rc) { break; } if (len_read != exp_len) { rc = 1; break; } rc = memcmp(val, buf, len_read); if (rc) { break; } val += len_read; off += len_read; } return rc; } int settings_line_dup_check_cb(const char *name, void *val_read_cb_ctx, off_t off, void *cb_arg) { struct settings_line_dup_check_arg *cdca; size_t len_read; cdca = (struct settings_line_dup_check_arg *)cb_arg; if (strcmp(name, cdca->name)) { return 0; } len_read = settings_line_val_get_len(off, val_read_cb_ctx); if (len_read != cdca->val_len) { cdca->is_dup = 0; } else if (len_read == 0) { cdca->is_dup = 1; } else { if (!settings_line_cmp(cdca->val, cdca->val_len, val_read_cb_ctx, off)) { cdca->is_dup = 1; } else { cdca->is_dup = 0; } } return 0; } static ssize_t settings_line_read_cb(void *cb_arg, void *data, size_t len) { struct settings_line_read_value_cb_ctx *value_context = cb_arg; size_t len_read; int rc; rc = settings_line_val_read(value_context->off, 0, data, len, &len_read, value_context->read_cb_ctx); if (rc == 0) { return len_read; } return -1; } int settings_line_load_cb(const char *name, void *val_read_cb_ctx, off_t off, void *cb_arg) { size_t len; struct settings_line_read_value_cb_ctx value_ctx; struct settings_load_arg *arg = cb_arg; value_ctx.read_cb_ctx = val_read_cb_ctx; value_ctx.off = off; len = settings_line_val_get_len(off, val_read_cb_ctx); return settings_call_set_handler(name, len, settings_line_read_cb, &value_ctx, arg); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_line.c
C
apache-2.0
11,825
/* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ int settings_backend_init(void) { return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_none.c
C
apache-2.0
144
/* * Copyright (c) 2019 Laczen * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <string.h> #include "settings/settings.h" #include "settings/settings_nvs.h" #include "settings_priv.h" #include <storage/flash_map.h> #include <logging/log.h> LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL); struct settings_nvs_read_fn_arg { struct nvs_fs *fs; u16_t id; }; static int settings_nvs_load(struct settings_store *cs, const struct settings_load_arg *arg); static int settings_nvs_save(struct settings_store *cs, const char *name, const char *value, size_t val_len); static struct settings_store_itf settings_nvs_itf = { .csi_load = settings_nvs_load, .csi_save = settings_nvs_save, }; static ssize_t settings_nvs_read_fn(void *back_end, void *data, size_t len) { struct settings_nvs_read_fn_arg *rd_fn_arg; ssize_t rc; rd_fn_arg = (struct settings_nvs_read_fn_arg *)back_end; rc = nvs_read(rd_fn_arg->fs, rd_fn_arg->id, data, len); if (rc > (ssize_t)len) { /* nvs_read signals that not all bytes were read * align read len to what was requested */ rc = len; } return rc; } int settings_nvs_src(struct settings_nvs *cf) { cf->cf_store.cs_itf = &settings_nvs_itf; settings_src_register(&cf->cf_store); return 0; } int settings_nvs_dst(struct settings_nvs *cf) { cf->cf_store.cs_itf = &settings_nvs_itf; settings_dst_register(&cf->cf_store); return 0; } static int settings_nvs_load(struct settings_store *cs, const struct settings_load_arg *arg) { int ret = 0; struct settings_nvs *cf = (struct settings_nvs *)cs; struct settings_nvs_read_fn_arg read_fn_arg; char name[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1]; char buf; ssize_t rc1, rc2; u16_t name_id = NVS_NAMECNT_ID; name_id = cf->last_name_id + 1; while (1) { name_id--; if (name_id == NVS_NAMECNT_ID) { break; } /* In the NVS backend, each setting item is stored in two NVS * entries one for the setting's name and one with the * setting's value. */ rc1 = nvs_read(&cf->cf_nvs, name_id, &name, sizeof(name)); rc2 = nvs_read(&cf->cf_nvs, name_id + NVS_NAME_ID_OFFSET, &buf, sizeof(buf)); if ((rc1 <= 0) && (rc2 <= 0)) { continue; } if ((rc1 <= 0) || (rc2 <= 0)) { /* Settings item is not stored correctly in the NVS. * NVS entry for its name or value is either missing * or deleted. Clean dirty entries to make space for * future settings item. */ if (name_id == cf->last_name_id) { cf->last_name_id--; nvs_write(&cf->cf_nvs, NVS_NAMECNT_ID, &cf->last_name_id, sizeof(u16_t)); } nvs_delete(&cf->cf_nvs, name_id); nvs_delete(&cf->cf_nvs, name_id + NVS_NAME_ID_OFFSET); continue; } /* Found a name, this might not include a trailing \0 */ name[rc1] = '\0'; read_fn_arg.fs = &cf->cf_nvs; read_fn_arg.id = name_id + NVS_NAME_ID_OFFSET; ret = settings_call_set_handler( name, rc2, settings_nvs_read_fn, &read_fn_arg, (void *)arg); if (ret) { break; } } return ret; } static int settings_nvs_save(struct settings_store *cs, const char *name, const char *value, size_t val_len) { struct settings_nvs *cf = (struct settings_nvs *)cs; char rdname[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1]; u16_t name_id, write_name_id; bool delete, write_name; int rc = 0; if (!name) { return -EINVAL; } /* Find out if we are doing a delete */ delete = ((value == NULL) || (val_len == 0)); name_id = cf->last_name_id + 1; write_name_id = cf->last_name_id + 1; write_name = true; while (1) { name_id--; if (name_id == NVS_NAMECNT_ID) { break; } rc = nvs_read(&cf->cf_nvs, name_id, &rdname, sizeof(rdname)); if (rc < 0) { /* Error or entry not found */ if (rc == -ENOENT) { write_name_id = name_id; } continue; } rdname[rc] = '\0'; if (strcmp(name, rdname)) { continue; } if ((delete) && (name_id == cf->last_name_id)) { cf->last_name_id--; rc = nvs_write(&cf->cf_nvs, NVS_NAMECNT_ID, &cf->last_name_id, sizeof(u16_t)); if (rc < 0) { /* Error: can't to store * the largest name ID in use. */ return rc; } } if (delete) { rc = nvs_delete(&cf->cf_nvs, name_id); if (rc >= 0) { rc = nvs_delete(&cf->cf_nvs, name_id + NVS_NAME_ID_OFFSET); } if (rc < 0) { return rc; } return 0; } write_name_id = name_id; write_name = false; break; } if (delete) { return 0; } /* No free IDs left. */ if (write_name_id == NVS_NAMECNT_ID + NVS_NAME_ID_OFFSET) { return -ENOMEM; } /* write the value */ rc = nvs_write(&cf->cf_nvs, write_name_id + NVS_NAME_ID_OFFSET, value, val_len); /* write the name if required */ if (write_name) { rc = nvs_write(&cf->cf_nvs, write_name_id, name, strlen(name)); if (rc < 0) { return rc; } } /* update the last_name_id and write to flash if required*/ if (write_name_id > cf->last_name_id) { cf->last_name_id = write_name_id; rc = nvs_write(&cf->cf_nvs, NVS_NAMECNT_ID, &cf->last_name_id, sizeof(u16_t)); } if (rc < 0) { return rc; } return 0; } /* Initialize the nvs backend. */ int settings_nvs_backend_init(struct settings_nvs *cf) { int rc; u16_t last_name_id; rc = nvs_init(&cf->cf_nvs, cf->flash_dev_name); if (rc) { return rc; } rc = nvs_read(&cf->cf_nvs, NVS_NAMECNT_ID, &last_name_id, sizeof(last_name_id)); if (rc < 0) { cf->last_name_id = NVS_NAMECNT_ID; } else { cf->last_name_id = last_name_id; } LOG_DBG("Initialized"); return 0; } int settings_backend_init(void) { static struct settings_nvs default_settings_nvs; int rc; u16_t cnt = 0; size_t nvs_sector_size, nvs_size = 0; const struct flash_area *fa; struct flash_sector hw_flash_sector; bt_u32_t sector_cnt = 1; rc = flash_area_open(FLASH_AREA_ID(storage), &fa); if (rc) { return rc; } rc = flash_area_get_sectors(FLASH_AREA_ID(storage), &sector_cnt, &hw_flash_sector); if (rc == -ENODEV) { return rc; } else if (rc != 0 && rc != -ENOMEM) { k_panic(); } nvs_sector_size = CONFIG_SETTINGS_NVS_SECTOR_SIZE_MULT * hw_flash_sector.fs_size; if (nvs_sector_size > UINT16_MAX) { return -EDOM; } while (cnt < CONFIG_SETTINGS_NVS_SECTOR_COUNT) { nvs_size += nvs_sector_size; if (nvs_size > fa->fa_size) { break; } cnt++; } /* define the nvs file system using the page_info */ default_settings_nvs.cf_nvs.sector_size = nvs_sector_size; default_settings_nvs.cf_nvs.sector_count = cnt; default_settings_nvs.cf_nvs.offset = fa->fa_off; default_settings_nvs.flash_dev_name = fa->fa_dev_name; rc = settings_nvs_backend_init(&default_settings_nvs); if (rc) { return rc; } rc = settings_nvs_src(&default_settings_nvs); if (rc) { return rc; } rc = settings_nvs_dst(&default_settings_nvs); return rc; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_nvs.c
C
apache-2.0
6,920
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SETTINGS_PRIV_H_ #define __SETTINGS_PRIV_H_ #include <ble_types/types.h> #include <misc/slist.h> #include <bt_errno.h> #include <settings/settings.h> #ifdef __cplusplus extern "C" { #endif int settings_cli_register(void); int settings_nmgr_register(void); struct mgmt_cbuf; int settings_cbor_line(struct mgmt_cbuf *cb, char *name, int nlen, char *value, int vlen); void settings_line_io_init(int (*read_cb)(void *ctx, off_t off, char *buf, size_t *len), int (*write_cb)(void *ctx, off_t off, char const *buf, size_t len), size_t (*get_len_cb)(void *ctx), u8_t io_rwbs); int settings_line_write(const char *name, const char *value, size_t val_len, off_t w_loc, void *cb_arg); /* Get len of record without alignment to write-block-size */ int settings_line_len_calc(const char *name, size_t val_len); int settings_line_dup_check_cb(const char *name, void *val_read_cb_ctx, off_t off, void *cb_arg); int settings_line_load_cb(const char *name, void *val_read_cb_ctx, off_t off, void *cb_arg); typedef int (*line_load_cb)(const char *name, void *val_read_cb_ctx, off_t off, void *cb_arg); struct settings_line_read_value_cb_ctx { void *read_cb_ctx; off_t off; }; struct settings_line_dup_check_arg { const char *name; const char *val; size_t val_len; int is_dup; }; #ifdef CONFIG_SETTINGS_ENCODE_LEN /* in storage line contex */ struct line_entry_ctx { void *stor_ctx; off_t seek; /* offset of id-value pair within the file */ size_t len; /* len of line without len value */ }; int settings_next_line_ctx(struct line_entry_ctx *entry_ctx); #endif /** * Read RAW settings line entry data from the storage. * * @param seek offset form the line beginning. * @param[out] out buffer for name * @param[in] len_req size of <p>out</p> buffer * @param[out] len_read length of read name * @param[in] cb_arg settings line storage context expected by the * <p>read_cb</p> implementatio * * @retval 0 on success, * -ERCODE on storage errors */ int settings_line_raw_read(off_t seek, char *out, size_t len_req, size_t *len_read, void *cb_arg); /* * @param val_off offset of the value-string. * @param off from val_off (so within the value-string) */ int settings_line_val_read(off_t val_off, off_t off, char *out, size_t len_req, size_t *len_read, void *cb_arg); /** * Read the settings line entry name from the storage. * * @param[out] out buffer for name * @param[in] len_req size of <p>out</p> buffer * @param[out] len_read length of read name * @param[in] cb_arg settings line storage context expected by the * <p>read_cb</p> implementation * * @retval 0 on read proper name, * 1 on when read improper name, * -ERCODE on storage errors */ int settings_line_name_read(char *out, size_t len_req, size_t *len_read, void *cb_arg); size_t settings_line_val_get_len(off_t val_off, void *read_cb_ctx); int settings_line_entry_copy(void *dst_ctx, off_t dst_off, void *src_ctx, off_t src_off, size_t len); void settings_line_io_init(int (*read_cb)(void *ctx, off_t off, char *buf, size_t *len), int (*write_cb)(void *ctx, off_t off, char const *buf, size_t len), size_t (*get_len_cb)(void *ctx), u8_t io_rwbs); /* * API for config storage. */ typedef void (*load_cb)(char *name, void *val_read_cb_ctx, off_t off, void *cb_arg); extern sys_slist_t settings_load_srcs; extern sys_slist_t settings_handlers; extern struct settings_store *settings_save_dst; #ifdef __cplusplus } #endif #endif /* __SETTINGS_PRIV_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_priv.h
C
apache-2.0
3,711
/* Copyright (c) 2019 Laczen * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <string.h> #include <sys/util.h> #include <settings/settings.h> #include "settings_priv.h" struct read_cb_arg { const void *data; size_t len; }; static ssize_t settings_runtime_read_cb(void *cb_arg, void *data, size_t len) { struct read_cb_arg *arg = (struct read_cb_arg *)cb_arg; memcpy(data, arg->data, MIN(arg->len, len)); return MIN(arg->len, len); } int settings_runtime_set(const char *name, const void *data, size_t len) { struct settings_handler_static *ch; const char *name_key; struct read_cb_arg arg; ch = settings_parse_and_lookup(name, &name_key); if (!ch) { return -EINVAL; } arg.data = data; arg.len = len; return ch->h_set(name_key, len, settings_runtime_read_cb, (void *)&arg); } int settings_runtime_get(const char *name, void *data, size_t len) { struct settings_handler_static *ch; const char *name_key; ch = settings_parse_and_lookup(name, &name_key); if (!ch) { return -EINVAL; } return ch->h_get(name_key, data, len); } int settings_runtime_commit(const char *name) { struct settings_handler_static *ch; const char *name_key; ch = settings_parse_and_lookup(name, &name_key); if (!ch) { return -EINVAL; } if (ch->h_commit) { return ch->h_commit(); } else { return 0; } }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_runtime.c
C
apache-2.0
1,351
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2015 Runtime Inc * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <stdio.h> #include <ble_types/types.h> #include <stddef.h> #include <sys/types.h> #include <bt_errno.h> #include <misc/__assert.h> #include <ble_os.h> #include "settings/settings.h" #include "settings_priv.h" // #include <logging/log.h> // LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL); sys_slist_t settings_load_srcs; struct settings_store *settings_save_dst; extern struct k_mutex settings_lock; void settings_src_register(struct settings_store *cs) { sys_slist_append(&settings_load_srcs, &cs->cs_next); } void settings_dst_register(struct settings_store *cs) { settings_save_dst = cs; } int settings_load(void) { printf("enter %s\n", __func__); return settings_load_subtree(NULL); } int settings_load_subtree(const char *subtree) { struct settings_store *cs; int rc; const struct settings_load_arg arg = { .subtree = subtree }; /* * for every config store * load config * apply config * commit all */ k_mutex_lock(&settings_lock, K_FOREVER); SYS_SLIST_FOR_EACH_CONTAINER(&settings_load_srcs, cs, cs_next) { cs->cs_itf->csi_load(cs, &arg); } rc = settings_commit_subtree(subtree); k_mutex_unlock(&settings_lock); return rc; } int settings_load_subtree_direct( const char *subtree, settings_load_direct_cb cb, void *param) { struct settings_store *cs; const struct settings_load_arg arg = { .subtree = subtree, .cb = cb, .param = param }; /* * for every config store * load config * apply config * commit all */ k_mutex_lock(&settings_lock, K_FOREVER); SYS_SLIST_FOR_EACH_CONTAINER(&settings_load_srcs, cs, cs_next) { cs->cs_itf->csi_load(cs, &arg); } k_mutex_unlock(&settings_lock); return 0; } /* * Append a single value to persisted config. Don't store duplicate value. */ int settings_save_one(const char *name, const void *value, size_t val_len) { int rc; struct settings_store *cs; cs = settings_save_dst; if (!cs) { return -ENOENT; } k_mutex_lock(&settings_lock, K_FOREVER); rc = cs->cs_itf->csi_save(cs, name, (char *)value, val_len); k_mutex_unlock(&settings_lock); return rc; } int settings_delete(const char *name) { return settings_save_one(name, NULL, 0); } int settings_save(void) { struct settings_store *cs; int rc; int rc2; cs = settings_save_dst; if (!cs) { return -ENOENT; } if (cs->cs_itf->csi_save_start) { cs->cs_itf->csi_save_start(cs); } rc = 0; #if 0 Z_STRUCT_SECTION_FOREACH(settings_handler_static, ch) { if (ch->h_export) { rc2 = ch->h_export(settings_save_one); if (!rc) { rc = rc2; } } } #endif #if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS) struct settings_handler *ch; SYS_SLIST_FOR_EACH_CONTAINER(&settings_handlers, ch, node) { if (ch->h_export) { rc2 = ch->h_export(settings_save_one); if (!rc) { rc = rc2; } } } #endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */ if (cs->cs_itf->csi_save_end) { cs->cs_itf->csi_save_end(cs); } return rc; } void settings_store_init(void) { sys_slist_init(&settings_load_srcs); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/settings/src/settings_store.c
C
apache-2.0
3,219
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ble_os.h> #include "timer.h" #include <misc/util.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BLUETOOTH_DEBUG_CORE) #include <bluetooth/log.h> struct mtimer *g_timer_list; #if defined(__cplusplus) extern "C" { #endif #define LOCK_HCI_CORE() #define UNLOCK_HCI_CORE() struct mtimer *mtimer_start(uint32_t msecs, timeout_handler handler, void *arg) { struct mtimer *timer_new, *t; timer_new = (struct mtimer *)malloc(sizeof(struct mtimer)); if (timer_new == NULL) { BT_ERR("timer maloc fail"); return NULL; } #if NO_SYS now = sys_now(); if (next_timeout == NULL) { diff = 0; timeouts_last_time = now; } else { diff = now - timeouts_last_time; } #endif timer_new->next = NULL; timer_new->h = handler; timer_new->arg = arg; #if NO_SYS timer_new->time = msecs + diff; #else timer_new->time = msecs; #endif if (g_timer_list == NULL) { g_timer_list = timer_new; return timer_new; } if (g_timer_list->time > msecs) { g_timer_list->time -= msecs; timer_new->next = g_timer_list; g_timer_list = timer_new; } else { for (t = g_timer_list; t != NULL; t = t->next) { timer_new->time -= t->time; if (t->next == NULL || t->next->time > timer_new->time) { if (t->next != NULL) { t->next->time -= timer_new->time; } timer_new->next = t->next; t->next = timer_new; break; } } } return timer_new; } void mtimer_stop(struct mtimer *timer) { struct mtimer *prev_t, *t; if (g_timer_list == NULL) { return; } for (t = g_timer_list, prev_t = NULL; t != NULL; prev_t = t, t = t->next) { if (t == timer) { /* We have a match */ /* Unlink from previous in list */ if (prev_t == NULL) { g_timer_list = t->next; } else { prev_t->next = t->next; } /* If not the last one, add time of this one back to next */ if (t->next != NULL) { t->next->time += t->time; } free(t); return; } } return; } void mtimer_mbox_fetch(k_mbox_t *mbox, void **msg) { bt_u32_t time_needed; struct mtimer *tmptimeout; timeout_handler handler; void *arg; again: if (!g_timer_list) { time_needed = k_mbox_fetch(mbox, msg, 0); } else { if (g_timer_list->time > 0) { time_needed = k_mbox_fetch(mbox, msg, g_timer_list->time); } else { time_needed = SYS_ARCH_TIMEOUT; } if (time_needed == SYS_ARCH_TIMEOUT) { /* If time == SYS_ARCH_TIMEOUT, a timeout occurred before a message could be fetched. We should now call the timeout handler and deallocate the memory allocated for the timeout. */ tmptimeout = g_timer_list; g_timer_list = tmptimeout->next; handler = tmptimeout->h; arg = tmptimeout->arg; free(tmptimeout); if (handler != NULL) { /*lock the core before calling the timeout handler function. */ LOCK_HCI_CORE(); handler(arg); UNLOCK_HCI_CORE(); } /* We try again to fetch a message from the mbox. */ goto again; } else { if (!g_timer_list) { return; } /* If time != SYS_ARCH_TIMEOUT, a message was received before the timeout occured. The time variable is set to the number of milliseconds we waited for the message. */ if (time_needed < g_timer_list->time) { g_timer_list->time -= time_needed; } else { g_timer_list->time = 0; } } } } #if defined(__cplusplus) } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/core/timer.c
C
apache-2.0
4,674
/* * Copyright (c) 2011-2014 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief Debug aid * * * The __ASSERT() macro can be used inside kernel code. * * Assertions are enabled by setting the __ASSERT_ON symbol to a non-zero value. * There are two ways to do this: * a) Use the ASSERT and ASSERT_LEVEL kconfig options * b) Add "CFLAGS += -D__ASSERT_ON=<level>" at the end of a project's Makefile * The Makefile method takes precedence over the kconfig option if both are * used. * * Specifying an assertion level of 1 causes the compiler to issue warnings that * the kernel contains debug-type __ASSERT() statements; this reminder is issued * since assertion code is not normally present in a final product. Specifying * assertion level 2 suppresses these warnings. * * The __ASSERT_EVAL() macro can also be used inside kernel code. * * It makes use of the __ASSERT() macro, but has some extra flexibility. It * allows the developer to specify different actions depending whether the * __ASSERT() macro is enabled or not. This can be particularly useful to * prevent the compiler from generating comments (errors, warnings or remarks) * about variables that are only used with __ASSERT() being assigned a value, * but otherwise unused when the __ASSERT() macro is disabled. * * Consider the following example: * * int x; * * x = foo (); * __ASSERT (x != 0, "foo() returned zero!"); * * If __ASSERT() is disabled, then 'x' is assigned a value, but never used. * This type of situation can be resolved using the __ASSERT_EVAL() macro. * * __ASSERT_EVAL ((void) foo(), * int x = foo(), * x != 0, * "foo() returned zero!"); * * The first parameter tells __ASSERT_EVAL() what to do if __ASSERT() is * disabled. The second parameter tells __ASSERT_EVAL() what to do if * __ASSERT() is enabled. The third and fourth parameters are the parameters * it passes to __ASSERT(). * * The __ASSERT_NO_MSG() macro can be used to perform an assertion that reports * the failed test and its location, but lacks additional debugging information * provided to assist the user in diagnosing the problem; its use is * discouraged. */ #ifndef ___ASSERT__H_ #define ___ASSERT__H_ #include <stdio.h> #ifdef CONFIG_ASSERT #ifndef __ASSERT_ON #define __ASSERT_ON CONFIG_ASSERT_LEVEL #endif #endif #ifdef CONFIG_FORCE_NO_ASSERT #undef __ASSERT_ON #define __ASSERT_ON 0 #endif #if defined(CONFIG_ASSERT_VERBOSE) #define __ASSERT_PRINT(fmt, ...) printk(fmt, ##__VA_ARGS__) #else /* CONFIG_ASSERT_VERBOSE */ #define __ASSERT_PRINT(fmt, ...) #endif /* CONFIG_ASSERT_VERBOSE */ #ifdef CONFIG_ASSERT_NO_MSG_INFO #define __ASSERT_MSG_INFO(fmt, ...) #else /* CONFIG_ASSERT_NO_MSG_INFO */ #define __ASSERT_MSG_INFO(fmt, ...) __ASSERT_PRINT("\t" fmt "\n", ##__VA_ARGS__) #endif /* CONFIG_ASSERT_NO_MSG_INFO */ #if !defined(CONFIG_ASSERT_NO_COND_INFO) && !defined(CONFIG_ASSERT_NO_FILE_INFO) #define __ASSERT_LOC(test) \ __ASSERT_PRINT("ASSERTION FAIL [%s] @ %s:%d\n", \ Z_STRINGIFY(test), \ __FILE__, __LINE__) #endif #if defined(CONFIG_ASSERT_NO_COND_INFO) && !defined(CONFIG_ASSERT_NO_FILE_INFO) #define __ASSERT_LOC(test) \ __ASSERT_PRINT("ASSERTION FAIL @ %s:%d\n", \ __FILE__, __LINE__) #endif #if !defined(CONFIG_ASSERT_NO_COND_INFO) && defined(CONFIG_ASSERT_NO_FILE_INFO) #define __ASSERT_LOC(test) \ __ASSERT_PRINT("ASSERTION FAIL [%s]\n", \ Z_STRINGIFY(test)) #endif #if defined(CONFIG_ASSERT_NO_COND_INFO) && defined(CONFIG_ASSERT_NO_FILE_INFO) #define __ASSERT_LOC(test) \ __ASSERT_PRINT("ASSERTION FAIL\n") #endif #ifdef __ASSERT_ON #if (__ASSERT_ON < 0) || (__ASSERT_ON > 2) #error "Invalid __ASSERT() level: must be between 0 and 2" #endif #if __ASSERT_ON #include <misc/printk.h> #ifdef __cplusplus extern "C" { #endif #ifdef CONFIG_ASSERT_NO_FILE_INFO void assert_post_action(void); #define __ASSERT_POST_ACTION() assert_post_action() #else /* CONFIG_ASSERT_NO_FILE_INFO */ void assert_post_action(const char *file, unsigned int line); #define __ASSERT_POST_ACTION() assert_post_action(__FILE__, __LINE__) #endif /* CONFIG_ASSERT_NO_FILE_INFO */ #ifdef __cplusplus } #endif #define __ASSERT_NO_MSG(test) \ do { \ if (!(test)) { \ __ASSERT_LOC(test); \ __ASSERT_POST_ACTION(); \ } \ } while (false) #define __ASSERT(test, fmt, ...) \ do { \ if (!(test)) { \ __ASSERT_LOC(test); \ __ASSERT_MSG_INFO(fmt, ##__VA_ARGS__); \ __ASSERT_POST_ACTION(); \ } \ } while (false) #define __ASSERT_EVAL(expr1, expr2, test, fmt, ...) \ do { \ expr2; \ __ASSERT(test, fmt, ##__VA_ARGS__); \ } while (0) #if (__ASSERT_ON == 1) #warning "__ASSERT() statements are ENABLED" #endif #else #define __ASSERT(test, fmt, ...) { } #define __ASSERT_EVAL(expr1, expr2, test, fmt, ...) expr1 #define __ASSERT_NO_MSG(test) { } #endif #else #define __ASSERT(test, fmt, ...) { } #define __ASSERT_EVAL(expr1, expr2, test, fmt, ...) expr1 #define __ASSERT_NO_MSG(test) { } #endif #endif /* ZEPHYR_INCLUDE_SYS___ASSERT_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/include/misc/__assert.h
C
apache-2.0
5,836
/** @file * @brief Byte order helpers. */ /* * Copyright (c) 2015-2016, Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __BYTEORDER_H__ #define __BYTEORDER_H__ #include <ble_types/types.h> #include <stddef.h> #include <misc/__assert.h> /* Internal helpers only used by the sys_* APIs further below */ #define __bswap_16(x) ((u16_t) ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))) #define __bswap_24(x) ((bt_u32_t) ((((x) >> 16) & 0xff) | \ (((x)) & 0xff00) | \ (((x) & 0xff) << 16))) #define __bswap_32(x) ((bt_u32_t) ((((x) >> 24) & 0xff) | \ (((x) >> 8) & 0xff00) | \ (((x) & 0xff00) << 8) | \ (((x) & 0xff) << 24))) #define __bswap_48(x) ((u64_t) ((((x) >> 40) & 0xff) | \ (((x) >> 24) & 0xff00) | \ (((x) >> 8) & 0xff0000) | \ (((x) & 0xff0000) << 8) | \ (((x) & 0xff00) << 24) | \ (((x) & 0xff) << 40))) #define __bswap_64(x) ((u64_t) ((((x) >> 56) & 0xff) | \ (((x) >> 40) & 0xff00) | \ (((x) >> 24) & 0xff0000) | \ (((x) >> 8) & 0xff000000) | \ (((x) & 0xff000000) << 8) | \ (((x) & 0xff0000) << 24) | \ (((x) & 0xff00) << 40) | \ (((x) & 0xff) << 56))) /** @def sys_le16_to_cpu * @brief Convert 16-bit integer from little-endian to host endianness. * * @param val 16-bit integer in little-endian format. * * @return 16-bit integer in host endianness. */ /** @def sys_cpu_to_le16 * @brief Convert 16-bit integer from host endianness to little-endian. * * @param val 16-bit integer in host endianness. * * @return 16-bit integer in little-endian format. */ /** @def sys_le24_to_cpu * @brief Convert 24-bit integer from little-endian to host endianness. * * @param val 24-bit integer in little-endian format. * * @return 24-bit integer in host endianness. */ /** @def sys_cpu_to_le24 * @brief Convert 24-bit integer from host endianness to little-endian. * * @param val 24-bit integer in host endianness. * * @return 24-bit integer in little-endian format. */ /** @def sys_le32_to_cpu * @brief Convert 32-bit integer from little-endian to host endianness. * * @param val 32-bit integer in little-endian format. * * @return 32-bit integer in host endianness. */ /** @def sys_cpu_to_le32 * @brief Convert 32-bit integer from host endianness to little-endian. * * @param val 32-bit integer in host endianness. * * @return 32-bit integer in little-endian format. */ /** @def sys_le48_to_cpu * @brief Convert 48-bit integer from little-endian to host endianness. * * @param val 48-bit integer in little-endian format. * * @return 48-bit integer in host endianness. */ /** @def sys_cpu_to_le48 * @brief Convert 48-bit integer from host endianness to little-endian. * * @param val 48-bit integer in host endianness. * * @return 48-bit integer in little-endian format. */ /** @def sys_be16_to_cpu * @brief Convert 16-bit integer from big-endian to host endianness. * * @param val 16-bit integer in big-endian format. * * @return 16-bit integer in host endianness. */ /** @def sys_cpu_to_be16 * @brief Convert 16-bit integer from host endianness to big-endian. * * @param val 16-bit integer in host endianness. * * @return 16-bit integer in big-endian format. */ /** @def sys_be24_to_cpu * @brief Convert 24-bit integer from big-endian to host endianness. * * @param val 24-bit integer in big-endian format. * * @return 24-bit integer in host endianness. */ /** @def sys_cpu_to_be24 * @brief Convert 24-bit integer from host endianness to big-endian. * * @param val 24-bit integer in host endianness. * * @return 24-bit integer in big-endian format. */ /** @def sys_be32_to_cpu * @brief Convert 32-bit integer from big-endian to host endianness. * * @param val 32-bit integer in big-endian format. * * @return 32-bit integer in host endianness. */ /** @def sys_cpu_to_be32 * @brief Convert 32-bit integer from host endianness to big-endian. * * @param val 32-bit integer in host endianness. * * @return 32-bit integer in big-endian format. */ /** @def sys_be48_to_cpu * @brief Convert 48-bit integer from big-endian to host endianness. * * @param val 48-bit integer in big-endian format. * * @return 48-bit integer in host endianness. */ /** @def sys_cpu_to_be48 * @brief Convert 48-bit integer from host endianness to big-endian. * * @param val 48-bit integer in host endianness. * * @return 48-bit integer in big-endian format. */ #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define sys_le16_to_cpu(val) (val) #define sys_cpu_to_le16(val) (val) #define sys_le24_to_cpu(val) (val) #define sys_cpu_to_le24(val) (val) #define sys_le32_to_cpu(val) (val) #define sys_cpu_to_le32(val) (val) #define sys_le48_to_cpu(val) (val) #define sys_cpu_to_le48(val) (val) #define sys_le64_to_cpu(val) (val) #define sys_cpu_to_le64(val) (val) #define sys_be16_to_cpu(val) __bswap_16(val) #define sys_cpu_to_be16(val) __bswap_16(val) #define sys_be24_to_cpu(val) __bswap_24(val) #define sys_cpu_to_be24(val) __bswap_24(val) #define sys_be32_to_cpu(val) __bswap_32(val) #define sys_cpu_to_be32(val) __bswap_32(val) #define sys_be48_to_cpu(val) __bswap_48(val) #define sys_cpu_to_be48(val) __bswap_48(val) #define sys_be64_to_cpu(val) __bswap_64(val) #define sys_cpu_to_be64(val) __bswap_64(val) #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define sys_le16_to_cpu(val) __bswap_16(val) #define sys_cpu_to_le16(val) __bswap_16(val) #define sys_le24_to_cpu(val) __bswap_24(val) #define sys_cpu_to_le24(val) __bswap_24(val) #define sys_le32_to_cpu(val) __bswap_32(val) #define sys_cpu_to_le32(val) __bswap_32(val) #define sys_le48_to_cpu(val) __bswap_48(val) #define sys_cpu_to_le48(val) __bswap_48(val) #define sys_le64_to_cpu(val) __bswap_64(val) #define sys_cpu_to_le64(val) __bswap_64(val) #define sys_be16_to_cpu(val) (val) #define sys_cpu_to_be16(val) (val) #define sys_be24_to_cpu(val) (val) #define sys_cpu_to_be24(val) (val) #define sys_be32_to_cpu(val) (val) #define sys_cpu_to_be32(val) (val) #define sys_be48_to_cpu(val) (val) #define sys_cpu_to_be48(val) (val) #define sys_be64_to_cpu(val) (val) #define sys_cpu_to_be64(val) (val) #else #error "Unknown byte order" #endif /** * @brief Put a 16-bit integer as big-endian to arbitrary location. * * Put a 16-bit integer, originally in host endianness, to a * potentially unaligned memory location in big-endian format. * * @param val 16-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_be16(u16_t val, u8_t dst[2]) { dst[0] = val >> 8; dst[1] = val; } /** * @brief Put a 24-bit integer as big-endian to arbitrary location. * * Put a 24-bit integer, originally in host endianness, to a * potentially unaligned memory location in big-endian format. * * @param val 24-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_be24(bt_u32_t val, u8_t dst[3]) { dst[0] = val >> 16; sys_put_be16(val, &dst[1]); } /** * @brief Put a 32-bit integer as big-endian to arbitrary location. * * Put a 32-bit integer, originally in host endianness, to a * potentially unaligned memory location in big-endian format. * * @param val 32-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_be32(bt_u32_t val, u8_t dst[4]) { sys_put_be16(val >> 16, dst); sys_put_be16(val, &dst[2]); } /** * @brief Put a 48-bit integer as big-endian to arbitrary location. * * Put a 48-bit integer, originally in host endianness, to a * potentially unaligned memory location in big-endian format. * * @param val 48-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_be48(u64_t val, u8_t dst[6]) { sys_put_be16(val >> 32, dst); sys_put_be32(val, &dst[2]); } /** * @brief Put a 64-bit integer as big-endian to arbitrary location. * * Put a 64-bit integer, originally in host endianness, to a * potentially unaligned memory location in big-endian format. * * @param val 64-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_be64(u64_t val, u8_t dst[8]) { sys_put_be32(val >> 32, dst); sys_put_be32(val, &dst[4]); } /** * @brief Put a 16-bit integer as little-endian to arbitrary location. * * Put a 16-bit integer, originally in host endianness, to a * potentially unaligned memory location in little-endian format. * * @param val 16-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_le16(u16_t val, u8_t dst[2]) { dst[0] = val; dst[1] = val >> 8; } /** * @brief Put a 24-bit integer as little-endian to arbitrary location. * * Put a 24-bit integer, originally in host endianness, to a * potentially unaligned memory location in littel-endian format. * * @param val 24-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_le24(bt_u32_t val, u8_t dst[3]) { sys_put_le16(val, dst); dst[2] = val >> 16; } /** * @brief Put a 32-bit integer as little-endian to arbitrary location. * * Put a 32-bit integer, originally in host endianness, to a * potentially unaligned memory location in little-endian format. * * @param val 32-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_le32(bt_u32_t val, u8_t dst[4]) { sys_put_le16(val, dst); sys_put_le16(val >> 16, &dst[2]); } /** * @brief Put a 48-bit integer as little-endian to arbitrary location. * * Put a 48-bit integer, originally in host endianness, to a * potentially unaligned memory location in little-endian format. * * @param val 48-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_le48(u64_t val, u8_t dst[6]) { sys_put_le32(val, dst); sys_put_le16(val >> 32, &dst[4]); } /** * @brief Put a 64-bit integer as little-endian to arbitrary location. * * Put a 64-bit integer, originally in host endianness, to a * potentially unaligned memory location in little-endian format. * * @param val 64-bit integer in host endianness. * @param dst Destination memory address to store the result. */ static inline void sys_put_le64(u64_t val, u8_t dst[8]) { sys_put_le32(val, dst); sys_put_le32(val >> 32, &dst[4]); } /** * @brief Get a 16-bit integer stored in big-endian format. * * Get a 16-bit integer, stored in big-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the big-endian 16-bit integer to get. * * @return 16-bit integer in host endianness. */ static inline u16_t sys_get_be16(const u8_t src[2]) { return ((u16_t)src[0] << 8) | src[1]; } /** * @brief Get a 24-bit integer stored in big-endian format. * * Get a 24-bit integer, stored in big-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the big-endian 24-bit integer to get. * * @return 24-bit integer in host endianness. */ static inline bt_u32_t sys_get_be24(const u8_t src[3]) { return ((bt_u32_t)src[0] << 16) | sys_get_be16(&src[1]); } /** * @brief Get a 32-bit integer stored in big-endian format. * * Get a 32-bit integer, stored in big-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the big-endian 32-bit integer to get. * * @return 32-bit integer in host endianness. */ static inline bt_u32_t sys_get_be32(const u8_t src[4]) { return ((bt_u32_t)sys_get_be16(&src[0]) << 16) | sys_get_be16(&src[2]); } /** * @brief Get a 48-bit integer stored in big-endian format. * * Get a 48-bit integer, stored in big-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the big-endian 48-bit integer to get. * * @return 48-bit integer in host endianness. */ static inline u64_t sys_get_be48(const u8_t src[6]) { return ((u64_t)sys_get_be32(&src[0]) << 32) | sys_get_be16(&src[4]); } /** * @brief Get a 64-bit integer stored in big-endian format. * * Get a 64-bit integer, stored in big-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the big-endian 64-bit integer to get. * * @return 64-bit integer in host endianness. */ static inline u64_t sys_get_be64(const u8_t src[8]) { return ((u64_t)sys_get_be32(&src[0]) << 32) | sys_get_be32(&src[4]); } /** * @brief Get a 16-bit integer stored in little-endian format. * * Get a 16-bit integer, stored in little-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the little-endian 16-bit integer to get. * * @return 16-bit integer in host endianness. */ static inline u16_t sys_get_le16(const u8_t src[2]) { return ((u16_t)src[1] << 8) | src[0]; } /** * @brief Get a 24-bit integer stored in big-endian format. * * Get a 24-bit integer, stored in big-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the big-endian 24-bit integer to get. * * @return 24-bit integer in host endianness. */ static inline bt_u32_t sys_get_le24(const u8_t src[3]) { return ((bt_u32_t)src[2] << 16) | sys_get_le16(&src[0]); } /** * @brief Get a 32-bit integer stored in little-endian format. * * Get a 32-bit integer, stored in little-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the little-endian 32-bit integer to get. * * @return 32-bit integer in host endianness. */ static inline bt_u32_t sys_get_le32(const u8_t src[4]) { return ((bt_u32_t)sys_get_le16(&src[2]) << 16) | sys_get_le16(&src[0]); } /** * @brief Get a 48-bit integer stored in little-endian format. * * Get a 48-bit integer, stored in little-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the little-endian 48-bit integer to get. * * @return 48-bit integer in host endianness. */ static inline u64_t sys_get_le48(const u8_t src[6]) { return ((u64_t)sys_get_le32(&src[2]) << 32) | sys_get_le16(&src[0]); } /** * @brief Get a 64-bit integer stored in little-endian format. * * Get a 64-bit integer, stored in little-endian format in a potentially * unaligned memory location, and convert it to the host endianness. * * @param src Location of the little-endian 64-bit integer to get. * * @return 64-bit integer in host endianness. */ static inline u64_t sys_get_le64(const u8_t src[8]) { return ((u64_t)sys_get_le32(&src[4]) << 32) | sys_get_le32(&src[0]); } /** * @brief Swap one buffer content into another * * Copy the content of src buffer into dst buffer in reversed order, * i.e.: src[n] will be put in dst[end-n] * Where n is an index and 'end' the last index in both arrays. * The 2 memory pointers must be pointing to different areas, and have * a minimum size of given length. * * @param dst A valid pointer on a memory area where to copy the data in * @param src A valid pointer on a memory area where to copy the data from * @param length Size of both dst and src memory areas */ static inline void sys_memcpy_swap(void *dst, const void *src, size_t length) { u8_t *pdst = (u8_t *)dst; const u8_t *psrc = (const u8_t *)src; __ASSERT(((psrc < pdst && (psrc + length) <= pdst) || (psrc > pdst && (pdst + length) <= psrc)), "Source and destination buffers must not overlap"); psrc += length - 1; for (; length > 0; length--) { *pdst++ = *psrc--; } } /** * @brief Swap buffer content * * In-place memory swap, where final content will be reversed. * I.e.: buf[n] will be put in buf[end-n] * Where n is an index and 'end' the last index of buf. * * @param buf A valid pointer on a memory area to swap * @param length Size of buf memory area */ static inline void sys_mem_swap(void *buf, size_t length) { size_t i; for (i = 0; i < (length/2); i++) { u8_t tmp = ((u8_t *)buf)[i]; ((u8_t *)buf)[i] = ((u8_t *)buf)[length - 1 - i]; ((u8_t *)buf)[length - 1 - i] = tmp; } } #endif /* __BYTEORDER_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/include/misc/byteorder.h
C
apache-2.0
16,716
/* printk.h - low-level debug output */ /* * Copyright (c) 2010-2012, 2014 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _PRINTK_H_ #define _PRINTK_H_ #include <stddef.h> #include <stdarg.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif #ifndef ARG_UNUSED #define ARG_UNUSED(x) (void)(x) #endif /** * * @brief Print kernel debugging message. * * This routine prints a kernel debugging message to the system console. * Output is send immediately, without any mutual exclusion or buffering. * * A basic set of conversion specifier characters are supported: * - signed decimal: \%d, \%i * - unsigned decimal: \%u * - unsigned hexadecimal: \%x (\%X is treated as \%x) * - pointer: \%p * - string: \%s * - character: \%c * - percent: \%\% * * Field width (with or without leading zeroes) is supported. * Length attributes h, hh, l, ll and z are supported. However, integral * values with %lld and %lli are only printed if they fit in a long * otherwise 'ERR' is printed. Full 64-bit values may be printed with %llx. * Flags and precision attributes are not supported. * * @param fmt Format string. * @param ... Optional list of format arguments. * * @return N/A */ #ifdef CONFIG_PRINTK extern __printf_like(1, 2) int printk(const char *fmt, ...); extern __printf_like(1, 0) int vprintk(const char *fmt, va_list ap); extern __printf_like(3, 4) int snprintk(char *str, size_t size, const char *fmt, ...); extern __printf_like(3, 0) int vsnprintk(char *str, size_t size, const char *fmt, va_list ap); extern __printf_like(3, 0) void _vprintk(int (*out)(int, void *), void *ctx, const char *fmt, va_list ap); #else static inline int printk(const char *fmt, ...) { ARG_UNUSED(fmt); return 0; } static inline int vprintk(const char *fmt, va_list ap) { ARG_UNUSED(fmt); ARG_UNUSED(ap); return 0; } #define snprintk snprintf static inline int vsnprintk(char *str, size_t size, const char *fmt, va_list ap) { ARG_UNUSED(str); ARG_UNUSED(size); ARG_UNUSED(fmt); ARG_UNUSED(ap); return 0; } #endif #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/include/misc/printk.h
C
apache-2.0
2,149
/** * @file stack.h * Stack usage analysis helpers */ /* * Copyright (c) 2015 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _MISC_STACK_H_ #define _MISC_STACK_H_ #include <misc/printk.h> #if defined(CONFIG_INIT_STACKS) static inline size_t stack_unused_space_get(const char *stack, size_t size) { size_t unused = 0; int i; /* TODO Currently all supported platforms have stack growth down and * there is no Kconfig option to configure it so this always build * "else" branch. When support for platform with stack direction up * (or configurable direction) is added this check should be confirmed * that correct Kconfig option is used. */ #if defined(STACK_GROWS_UP) for (i = size - 1; i >= 0; i--) { if ((unsigned char)stack[i] == 0xaa) { unused++; } else { break; } } #else for (i = 0; i < size; i++) { if ((unsigned char)stack[i] == 0xaa) { unused++; } else { break; } } #endif return unused; } #else static inline size_t stack_unused_space_get(const char *stack, size_t size) { return 0; } #endif #if defined(CONFIG_INIT_STACKS) && defined(CONFIG_PRINTK) static inline void stack_analyze(const char *name, const char *stack, unsigned int size) { unsigned int pcnt, unused = 0; unused = stack_unused_space_get(stack, size); /* Calculate the real size reserved for the stack */ pcnt = ((size - unused) * 100) / size; printk("%s (real size %u):\tunused %u\tusage %u / %u (%u %%)\n", name, size, unused, size - unused, size, pcnt); } #else static inline void stack_analyze(const char *name, const char *stack, unsigned int size) { } #endif #define STACK_ANALYZE(name, sym) \ stack_analyze(name, K_THREAD_STACK_BUFFER(sym), \ K_THREAD_STACK_SIZEOF(sym)) #endif /* _MISC_STACK_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_host/port/include/misc/stack.h
C
apache-2.0
1,796