blob: 1cecc228bd0b01f341dd5ceb401b85b607c7985d [file] [log] [blame]
/*
* Copyright (c) 2017 Nordic Semiconductor ASA
* Copyright (c) 2015 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <sys/util.h>
#include <bluetooth/addr.h>
#include <bluetooth/crypto.h>
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;
}
int bt_addr_from_str(const char *str, bt_addr_t *addr)
{
int i, j;
uint8_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;
}