1 /*
2  * Copyright (c) 2022 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/bluetooth/addr.h>
9 #include <host/keys.h>
10 #include "keys_help_utils.h"
11 
clear_key_pool(void)12 void clear_key_pool(void)
13 {
14 	struct bt_keys *key_pool;
15 
16 	key_pool = bt_keys_get_key_pool();
17 	memset(key_pool, 0x00, sizeof(struct bt_keys) * CONFIG_BT_MAX_PAIRED);
18 }
19 
fill_key_pool_by_id_addr(const struct id_addr_pair src[],int size,struct bt_keys * refs[])20 int fill_key_pool_by_id_addr(const struct id_addr_pair src[], int size, struct bt_keys *refs[])
21 {
22 	uint8_t id;
23 	bt_addr_le_t *addr;
24 	struct id_addr_pair const *params_vector;
25 
26 	if (!check_key_pool_is_empty()) {
27 		printk("'%s' Error ! Keys pool isn't empty\n", __func__);
28 		return -ENOSR;
29 	}
30 
31 	for (size_t it = 0; it < size; it++) {
32 		params_vector = &src[it];
33 		id = params_vector->id;
34 		addr = params_vector->addr;
35 		refs[it] = bt_keys_get_addr(id, addr);
36 		if (refs[it] == NULL) {
37 			printk("'%s' Failed to add key %d to the keys pool\n", __func__, it);
38 			return -ENOBUFS;
39 		}
40 	}
41 
42 	return 0;
43 }
44 
fill_key_pool_by_id_addr_type(const struct id_addr_type src[],int size,struct bt_keys * refs[])45 int fill_key_pool_by_id_addr_type(const struct id_addr_type src[], int size, struct bt_keys *refs[])
46 {
47 	int type;
48 	uint8_t id;
49 	bt_addr_le_t *addr;
50 	struct id_addr_type const *params_vector;
51 
52 	if (!check_key_pool_is_empty()) {
53 		printk("'%s' Error ! Keys pool isn't empty\n", __func__);
54 		return -ENOSR;
55 	}
56 
57 	for (size_t it = 0; it < size; it++) {
58 		params_vector = &src[it];
59 		type = params_vector->type;
60 		id = params_vector->id;
61 		addr = params_vector->addr;
62 		refs[it] = bt_keys_get_type(type, id, addr);
63 		if (refs[it] == NULL) {
64 			printk("'%s' Failed to add key %d to the keys pool\n", __func__, it);
65 			return -ENOBUFS;
66 		}
67 	}
68 
69 	return 0;
70 }
71 
check_key_pool_is_empty(void)72 bool check_key_pool_is_empty(void)
73 {
74 	int i;
75 	struct bt_keys *keys, *key_pool;
76 
77 	key_pool = bt_keys_get_key_pool();
78 	for (i = 0; i < CONFIG_BT_MAX_PAIRED; i++) {
79 		keys = &key_pool[i];
80 		if (bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY)) {
81 			return false;
82 		}
83 	}
84 
85 	return true;
86 }
87