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
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <signal.h> #include <time.h> #include <pthread.h> #include <fcntl.h> #include <inttypes.h> #include <sys/prctl.h> #include <sys/time.h> #include <poll.h> #include "amp_platform.h" #include "aos_system.h" #include "aos/kernel.h" #include "aos_network.h" #include "ulog/ulog.h" #define _SYSINFO_DEVICE_NAME "aos-linux" #define SYSINFO_VERSION "0.0.1" typedef struct { timer_t timer; void (*cb)(void *,void *); void *user_data; uint32_t ms; uint32_t repeat; } osal_timer_inner_t; void aos_putchar(char c) { printf("%c", c); } void aos_reboot(void) { exit(0); } int aos_get_hz(void) { return 100; } const char *aos_version_get(void) { return SYSINFO_VERSION; } struct targ { const char *name; void (*fn)(void *); void *arg; }; static void *dfl_entry(void *arg) { struct targ *targ = arg; void (*fn)(void *) = targ->fn; void *farg = targ->arg; prctl(PR_SET_NAME, (unsigned long)targ->name, 0, 0, 0); free(targ); fn(farg); return 0; } int aos_task_new(const char *name, void (*fn)(void *), void *arg, size_t stack_size) { int ret; pthread_t th; struct targ *targ = malloc(sizeof(*targ)); targ->name = strdup(name); targ->fn = fn; targ->arg = arg; ret = pthread_create(&th, NULL, dfl_entry, targ); if (ret == 0) { ret = pthread_detach(th); } return ret; } aos_status_t aos_task_new_ext(aos_task_t *task, const char *name, void (*fn)(void *), void *arg, size_t stack_size, int32_t prio) { return aos_task_new(name, fn, arg, stack_size); } void aos_task_exit(int code) { pthread_exit((void *)code); } const char *aos_task_name(void) { static char name[16]; prctl(PR_GET_NAME, (unsigned long)name, 0, 0, 0); return name; } int aos_task_key_create(aos_task_key_t *key) { return pthread_key_create(key, NULL); } void aos_task_key_delete(aos_task_key_t key) { pthread_key_delete(key); } int aos_task_setspecific(aos_task_key_t key, void *vp) { return pthread_setspecific(key, vp); } void *aos_task_getspecific(aos_task_key_t key) { return pthread_getspecific(key); } aos_status_t aos_mutex_new(aos_mutex_t *mutex) { pthread_mutex_t *mtx = malloc(sizeof(*mtx)); pthread_mutex_init(mtx, NULL); *mutex = mtx; return 0; } void aos_mutex_free(aos_mutex_t *mutex) { pthread_mutex_destroy(*mutex); free(*mutex); } int aos_mutex_lock(aos_mutex_t *mutex, unsigned int timeout) { if (mutex) { pthread_mutex_lock(*mutex); } return 0; } int aos_mutex_unlock(aos_mutex_t *mutex) { if (mutex) { pthread_mutex_unlock(*mutex); } return 0; } bool aos_mutex_is_valid(aos_mutex_t *mutex) { return *mutex != NULL; } #include <semaphore.h> aos_status_t aos_sem_new(aos_sem_t *sem, uint32_t count) { sem_t *s = malloc(sizeof(*s)); sem_init(s, 0, count); *sem = s; return 0; } void aos_sem_free(aos_sem_t *sem) { if (sem == NULL) { return; } sem_destroy(*sem); free(*sem); } int aos_sem_wait(aos_sem_t *sem, unsigned int timeout) { int sec; int nsec; if (sem == NULL) { return -EINVAL; } if (timeout == AOS_WAIT_FOREVER) { return sem_wait(*sem); } else if (timeout == 0) { return sem_trywait(*sem); } struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); sec = timeout / 1000; nsec = (timeout % 1000) * 1000000; ts.tv_nsec += nsec; sec += (ts.tv_nsec / 1000000000); ts.tv_nsec %= 1000000000; ts.tv_sec += sec; return sem_timedwait(*sem, &ts); } void aos_sem_signal(aos_sem_t *sem) { if (sem == NULL) { return; } sem_post(*sem); } bool aos_sem_is_valid(aos_sem_t *sem) { return sem && *sem != NULL; } void aos_sem_signal_all(aos_sem_t *sem) { sem_post(*sem); } struct queue { int fds[2]; void *buf; int size; int msg_size; }; aos_status_t aos_queue_new(aos_queue_t *queue, void *buf, size_t size, size_t max_msg) { struct queue *q = malloc(sizeof(*q) + size); pipe(q->fds); q->buf = q + sizeof(*q); q->size = size; q->msg_size = max_msg; *queue = q; return 0; } void aos_queue_free(aos_queue_t *queue) { struct queue *q = *queue; close(q->fds[0]); close(q->fds[1]); free(q); } aos_status_t aos_queue_send(aos_queue_t *queue, void *msg, size_t size) { struct queue *q = *queue; write(q->fds[1], msg, size); return 0; } aos_status_t aos_queue_recv(aos_queue_t *queue, uint32_t ms, void *msg, size_t *size) { struct queue *q = *queue; struct pollfd rfd = { .fd = q->fds[0], .events = POLLIN, }; poll(&rfd, 1, ms); if (rfd.revents & POLLIN) { int len = read(q->fds[0], msg, q->msg_size); *size = len; return len < 0 ? -1 : 0; } return -1; } bool aos_queue_is_valid(aos_queue_t *queue) { return *queue != NULL; } static void timer_common_cb(union sigval arg) { osal_timer_inner_t *amp_timer = (osal_timer_inner_t *)arg.sival_ptr; if (amp_timer && amp_timer->cb) { amp_timer->cb(amp_timer, amp_timer->user_data); } } aos_status_t aos_timer_create(aos_timer_t *timer, void (*fn)(void *, void *), void *arg, uint32_t ms, uint32_t options) { struct sigevent ent; osal_timer_inner_t *amp_timer = NULL; /* check parameter */ if (fn == NULL) { return -1; } amp_timer = aos_malloc(sizeof(osal_timer_inner_t)); if (!amp_timer) { return -1; } memset(amp_timer, 0, sizeof(osal_timer_inner_t)); /* Init */ memset(&ent, 0x00, sizeof(struct sigevent)); /* create a timer */ ent.sigev_notify = SIGEV_THREAD; ent.sigev_notify_function = (void (*)(union sigval))timer_common_cb; ent.sigev_value.sival_ptr = amp_timer; if (timer_create(CLOCK_MONOTONIC, &ent, &amp_timer->timer) != 0) { aos_free(amp_timer); return -1; } amp_timer->cb = fn; amp_timer->ms = ms; amp_timer->user_data = arg; amp_timer->repeat = (options & AOS_TIMER_REPEAT) ? 1 : 0; *timer = amp_timer; return 0; } void aos_timer_free(aos_timer_t *timer) { int ret = 0; osal_timer_inner_t *amp_timer = NULL; /* check parameter */ if (timer == NULL) { return; } amp_timer = (osal_timer_inner_t *)*timer; if (!amp_timer) return; ret = timer_delete(amp_timer->timer); aos_free(amp_timer); return; } int aos_timer_start(aos_timer_t *timer) { struct itimerspec ts; osal_timer_inner_t *amp_timer = NULL; /* check parameter */ if (timer == NULL) { return -1; } amp_timer = (osal_timer_inner_t *)*timer; if (amp_timer->repeat) { /* it_value=0: stop timer */ ts.it_interval.tv_sec = amp_timer->ms / 1000; ts.it_interval.tv_nsec = (amp_timer->ms % 1000) * 1000000; } else { /* it_interval=0: timer run only once */ ts.it_interval.tv_sec = 0;; ts.it_interval.tv_nsec = 0; } /* it_value=0: stop timer */ ts.it_value.tv_sec = amp_timer->ms / 1000; ts.it_value.tv_nsec = (amp_timer->ms % 1000) * 1000000; return timer_settime(amp_timer->timer, 0, &ts, NULL); } int aos_timer_stop(aos_timer_t *timer) { struct itimerspec ts; osal_timer_inner_t *amp_timer = NULL; /* check parameter */ if (timer == NULL) { return -1; } amp_timer = (osal_timer_inner_t *)*timer; /* it_interval=0: timer run only once */ ts.it_interval.tv_sec = 0; ts.it_interval.tv_nsec = 0; /* it_value=0: stop timer */ ts.it_value.tv_sec = 0; ts.it_value.tv_nsec = 0; return timer_settime(amp_timer->timer, 0, &ts, NULL); } void *aos_zalloc(size_t size) { return calloc(size, 1); } void *aos_malloc(size_t size) { return malloc(size); } void *aos_calloc(size_t nitems, size_t size) { return calloc(nitems, size); } void *aos_realloc(void *mem, size_t size) { return realloc(mem, size); } void aos_alloc_trace(void *addr, size_t allocator) {} void aos_free(void *mem) { free(mem); } static struct timeval sys_start_time; uint64_t aos_now(void) { struct timeval tv; long long ns; gettimeofday(&tv, NULL); timersub(&tv, &sys_start_time, &tv); ns = tv.tv_sec * 1000000LL + tv.tv_usec; return ns * 1000LL; } uint64_t aos_now_ms(void) { struct timeval tv; long long ms; gettimeofday(&tv, NULL); timersub(&tv, &sys_start_time, &tv); ms = tv.tv_sec * 1000LL + tv.tv_usec / 1000; return ms; } aos_status_t aos_now_time_str(char *buffer, size_t len) { if (buffer != NULL && len > 0) { struct timeval curTime; gettimeofday(&curTime, NULL); memset(buffer, 0, len); strftime(buffer, len, "%m-%d %H:%M:%S", localtime(&curTime.tv_sec)); if ((int)(len - strlen(buffer) - 1) > 0) { const int milli = curTime.tv_usec / 1000; char msStr[8] = {0}; snprintf(msStr, sizeof(msStr), ".%03d", milli); strncat(buffer, msStr, len - strlen(buffer) - 1); } } return 0; } void aos_msleep(uint32_t ms) { usleep(ms * 1000); } void aos_init(void) { gettimeofday(&sys_start_time, NULL); } void aos_start(void) { while (1) { usleep(1000 * 1000 * 100); } } #include <sys/types.h> #include <dirent.h> void dumpsys_task_func(void) { DIR *proc = opendir("/proc/self/task"); while (1) { struct dirent *ent = readdir(proc); if (!ent) { break; } if (ent->d_name[0] == '.') { continue; } char fn[128]; snprintf(fn, sizeof fn, "/proc/self/task/%s/comm", ent->d_name); FILE *fp = fopen(fn, "r"); if (!fp) { continue; } bzero(fn, sizeof fn); fread(fn, sizeof(fn) - 1, 1, fp); fclose(fp); printf("%8s - %s", ent->d_name, fn); } closedir(proc); } void aos_printf(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); fflush(stdout); } int aos_snprintf(char *str, const int len, const char *fmt, ...) { va_list args; int rc; va_start(args, fmt); rc = vsnprintf(str, len, fmt, args); va_end(args); return rc; } int aos_vsnprintf(char *str, const int len, const char *format, va_list ap) { return vsnprintf(str, len, format, ap); } const char *aos_get_system_version(void) { return SYSINFO_VERSION; } const char *aos_get_platform_type(void) { return _SYSINFO_DEVICE_NAME; } int aos_get_ip(char *ip) { return 0; } int aos_get_mac_addr(unsigned char mac[8]) { // TODO: ? return 0; } int aos_network_status_registercb(void (*cb)(int status, void *), void *arg) { // TODO: ? return 0; } int aos_get_network_status(void) { // TODO: ? return 1; } const char *aos_get_device_name(void) { return "linux"; } int amp_heap_memory_info(amp_heap_info_t *heap_info) { return 0; } int aos_system_init(void) { return 0; } const char *aos_get_module_hardware_version(void) { return "Module_Hardware_version"; } const char *aos_get_module_software_version(void) { return "Module_Software_version"; } int32_t aos_rand(void) { return rand(); } void aos_srand(uint32_t seed) { srand(seed); }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/aos_system.c
C
apache-2.0
11,664
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <netmgr.h> #include <netmgr_wifi.h> #include <aos/list.h> #include <uservice/uservice.h> #define KV_VAL_LENGTH 32 struct hdl_info; typedef struct hdl_info { slist_t next; char* file_name; netmgr_hdl_t hdl; netmgr_type_t type; } hdl_info_t; #define TAG "netmgr_service" static slist_t g_hdl_list_head; int netmgr_wifi_set_ip_mode(netmgr_wifi_ip_mode_t mode); netmgr_wifi_ip_mode_t netmgr_wifi_get_ip_mode(void); int netmgr_wifi_get_ip_stat(char* ip_addr, char* mask, char* gw, char* dns_server); void netmgr_wifi_auto_reconnect(int enable); int netmgr_wifi_get_wifi_state(); int netmgr_wifi_set_static_ip_stat(const char* ip_addr, const char* mask, const char* gw, const char* dns_server); int event_service_init(utask_t *task) { return 0; } static int add_hdl_info(int fd, char* file_name, netmgr_type_t type) { hdl_info_t* cur; printf("%s:%d\n", __func__, __LINE__); cur = malloc(sizeof(hdl_info_t)); if(cur == NULL) { return -1; } memset(cur, 0, sizeof(hdl_info_t)); printf("%s:%d\n", __func__, __LINE__); cur->hdl = fd; cur->file_name = strdup(file_name); cur->type = type; slist_add_tail(&cur->next, &g_hdl_list_head); return 0; } static int del_hdl_by_name(char* file_name) { hdl_info_t* cur; int found = 0; slist_for_each_entry(&g_hdl_list_head, cur, hdl_info_t, next) { if(strcmp(cur->file_name, file_name) == 0) { found = 1; break; } } if(1 == found) { free(cur->file_name); slist_del(&cur->next, &g_hdl_list_head); return 0; } else { return -1; } } static netmgr_hdl_t get_hdl_by_name(char* file_name) { hdl_info_t* cur; int found = 0; slist_for_each_entry(&g_hdl_list_head, cur, hdl_info_t, next) { if(strcmp(cur->file_name, file_name) == 0) { found = 1; break; } } if(1 == found) { return cur->hdl; } else { return -1; } } /** * @brief create & init the netmgr uservice * @param [in] task * @return */ int netmgr_service_init(utask_t *task) { return 0; } /** * @brief destroy & uninit the netmgr uservice * @return */ void netmgr_service_deinit() { } int netmgr_add_dev(const char* name) { return 0; } netmgr_hdl_t netmgr_get_dev(const char* name) { return get_hdl_by_name((char *)name); } int netmgr_set_ifconfig(netmgr_hdl_t hdl, netmgr_ifconfig_info_t* info) { return 0; } int netmgr_get_ifconfig(netmgr_hdl_t hdl, netmgr_ifconfig_info_t* info) { if(info != NULL) { info->dhcp_en = true; //return netmgr_wifi_get_ip_stat(info->ip_addr, info->mask, info->gw, info->dns_server); info->ip_addr[0] = 1; info->ip_addr[2] = 2; return 0; } else { return -1; } return 0; } void netmgr_set_auto_reconnect(netmgr_hdl_t hdl, bool enable) { } int netmgr_get_config(netmgr_hdl_t hdl, netmgr_config_t* config) { return 0; } int netmgr_del_config(netmgr_hdl_t hdl, netmgr_del_config_t* config) { return 0; } netmgr_conn_state_t netmgr_get_state(netmgr_hdl_t hdl) { return 0; } int netmgr_connect(netmgr_hdl_t hdl, netmgr_connect_params_t* params) { aos_printf("wifi connect begin...\n"); aos_printf("ssid %s, password %s\n", params->params.wifi_params.ssid, params->params.wifi_params.pwd); aos_msleep(5000); aos_printf("wifi connected\n"); return 0; } int netmgr_disconnect(netmgr_hdl_t hdl) { return 0; } int netmgr_save_config(netmgr_hdl_t hdl) { return 0; } int netmgr_set_connect_params(netmgr_hdl_t hdl, netmgr_connect_params_t* params) { //TODO return 0; } int netmgr_set_msg_cb(netmgr_hdl_t hdl, netmgr_msg_cb_t cb) { return 0; } int netmgr_del_msg_cb(netmgr_hdl_t hdl, netmgr_msg_cb_t cb) { return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/aos_wifi.c
C
apache-2.0
3,979
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/errno.h> #include "aos_hal_adc.h" int32_t aos_hal_adc_init(adc_dev_t *adc) { if(NULL == adc) { printf("parameter is invalid!\n\r"); return -1; } printf("[%s] sampling_cycle = %d \r\n", __FUNCTION__, adc->config.sampling_cycle); return 0; } int32_t aos_hal_adc_raw_value_get(adc_dev_t *adc, uint32_t *output, uint32_t timeout) { printf ("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_adc_finalize(adc_dev_t *adc) { printf ("[%s] \r\n", __FUNCTION__); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_adc.c
C
apache-2.0
620
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/errno.h> #include "aos_hal_dac.h" int32_t aos_hal_dac_init(dac_dev_t *dac) { if(NULL == dac) { printf("parameter is invalid!\n\r"); return -1; } printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_dac_start(dac_dev_t *dac, uint32_t channel) { printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_dac_stop(dac_dev_t *dac, uint32_t channel) { printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_dac_set_value(dac_dev_t *dac, uint32_t channel, uint32_t data) { printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_dac_get_value(dac_dev_t *dac, uint32_t channel) { printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_dac_finalize(dac_dev_t *dac) { printf("[%s] \r\n", __FUNCTION__); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_dac.c
C
apache-2.0
920
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <termio.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <signal.h> #include "aos_hal_gpio.h" #ifdef CONFIG_GPIO_NUM #define PLATFORM_GPIO_NUM CONFIG_GPIO_NUM #else #define PLATFORM_GPIO_NUM 40 #endif static uint8_t gpio_value[PLATFORM_GPIO_NUM * 2] = { 0 }; int32_t aos_hal_gpio_init(gpio_dev_t *gpio) { memset(gpio_value, 0, PLATFORM_GPIO_NUM * 2); return 0; } int32_t aos_hal_gpio_output_high(gpio_dev_t *gpio) { gpio_value[gpio->port] = 1; return 0; } int32_t aos_hal_gpio_output_low(gpio_dev_t *gpio) { gpio_value[gpio->port] = 0; return 0; } int32_t aos_hal_gpio_output_toggle(gpio_dev_t *gpio) { return 0; } int32_t aos_hal_gpio_input_get(gpio_dev_t *gpio, uint32_t *value) { *value = gpio_value[gpio->port]; return 0; } static gpio_irq_handler_t irq_handler = NULL; static void *irq_arg = NULL; static void linux_sig_handler(void *arg) { printf("recv signal SIGUSR1\n"); irq_handler(irq_arg); } int32_t aos_hal_gpio_enable_irq(gpio_dev_t *gpio, gpio_irq_trigger_t trigger, gpio_irq_handler_t handler, void *arg) { irq_handler = handler; irq_arg = arg; struct sigaction sa_usr; sa_usr.sa_flags = 0; sa_usr.sa_handler = linux_sig_handler; sigaction(SIGUSR1, &sa_usr, NULL); return 0; } int32_t aos_hal_gpio_disable_irq(gpio_dev_t *gpio) { return 0; } int32_t aos_hal_gpio_clear_irq(gpio_dev_t *gpio) { return aos_hal_gpio_disable_irq(gpio); } int32_t aos_hal_gpio_finalize(gpio_dev_t *gpio) { return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_gpio.c
C
apache-2.0
1,629
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <aos/errno.h> #include "aos_hal_i2c.h" #define BUF_LEN 16 uint8_t buf[BUF_LEN]; int32_t aos_hal_i2c_init(i2c_dev_t *i2c) { if(NULL == i2c) { printf("parameter is invalid!\n\r"); return -1; } memset(buf, 0, BUF_LEN); printf("[%s] freq = %d slave_addr = 0x%X\r\n", __FUNCTION__, i2c->config.freq, i2c->config.dev_addr); return 0; } int32_t aos_hal_i2c_master_send(i2c_dev_t *i2c, uint16_t dev_addr, const uint8_t *data, uint16_t size, uint32_t timeout) { uint32_t i; printf("[%s] \r\n", __FUNCTION__); for (i = 0; i < size; i++) { buf[i] = data[i]; printf("[%d] 0x%x \r\n", i, buf[i]); } return 0; } int32_t aos_hal_i2c_master_recv(i2c_dev_t *i2c, uint16_t dev_addr, uint8_t *data, uint16_t size, uint32_t timeout) { uint32_t i; printf("[%s] \r\n", __FUNCTION__); for (i = 0; i < size; i++) { data[i] = buf[i]; printf("[%d] 0x%x \r\n", i, data[i]); } return 0; } int32_t aos_hal_i2c_slave_send(i2c_dev_t *i2c, const uint8_t *data, uint16_t size, uint32_t timeout) { printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_i2c_slave_recv(i2c_dev_t *i2c, uint8_t *data, uint16_t size, uint32_t timeout) { printf("[%s] \r\n", __FUNCTION__); return 0; } int32_t aos_hal_i2c_mem_write(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t mem_addr, uint16_t mem_addr_size, const uint8_t *data, uint16_t size, uint32_t timeout) { uint32_t i; printf("[%s] \r\n", __FUNCTION__); for (i = 0; i < size; i++) { buf[i] = data[i]; printf("[%d] 0x%x \r\n", i, buf[i]); } return 0; } int32_t aos_hal_i2c_mem_read(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t mem_addr, uint16_t mem_addr_size, uint8_t *data, uint16_t size, uint32_t timeout) { uint32_t i; printf("[%s] \r\n", __FUNCTION__); for (i = 0; i < size; i++) { data[i] = buf[i]; printf("[%d] 0x%x \r\n", i, data[i]); } return 0; } int32_t aos_hal_i2c_finalize(i2c_dev_t *i2c) { printf("[%s] \r\n", __FUNCTION__); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_i2c.c
C
apache-2.0
2,363
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <sys/ioctl.h> #include "aos_hal_lcd.h" int32_t aos_hal_lcd_init(void) { printf("aos_hal_lcd_init done\n"); return 0; } int32_t aos_hal_lcd_uninit(void) { printf("aos_hal_lcd_uninit done\n"); return 0; } int32_t aos_hal_lcd_show(int x, int y, int w, int h, uint8_t *buf, bool rotate) { printf("aos_hal_lcd_show x: %d, y: %d, w: %d, h: %d, rotate: %d\n", x, y, w, h, rotate); for (int i; i < w * h * 2; i++) printf("buf: 0x%x", buf[i]); return 0; } int32_t aos_hal_lcd_fill(int x, int y, int w, int h, uint32_t color) { printf("aos_hal_lcd_fill x: %d, y: %d, w: %d, h: %d, color: 0x%x\n", x, y, w, h, color); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_lcd.c
C
apache-2.0
802
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> int hal_cmu_get_crystal_freq() { return 260000; } int hal_fast_sys_timer_get() { return 10000; } size_t cpu_intrpt_save(void) { } void cpu_intrpt_restore(size_t cpsr) { }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_onewire.c
C
apache-2.0
268
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/errno.h> #include "aos_hal_pwm.h" int32_t aos_hal_pwm_init(pwm_dev_t *pwm) { printf ("[%s] freq = %d \r\n", __FUNCTION__, pwm->config.freq); printf ("[%s] duty_cycle = %d \r\n", __FUNCTION__, pwm->config.duty_cycle); return 0; } int32_t aos_hal_pwm_start(pwm_dev_t *pwm) { printf ("[%s] freq = %d \r\n", __FUNCTION__, pwm->port); return 0; } int32_t aos_hal_pwm_stop(pwm_dev_t *pwm) { printf ("[%s] freq = %d \r\n", __FUNCTION__, pwm->port); return 0; } int32_t aos_hal_pwm_para_chg(pwm_dev_t *pwm, pwm_config_t para) { printf ("[%s] freq = %d \r\n", __FUNCTION__, para.freq); printf ("[%s] duty_cycle = %d \r\n", __FUNCTION__, para.duty_cycle); return 0; } int32_t aos_hal_pwm_finalize(pwm_dev_t *pwm) { printf ("[%s]\r\n", __FUNCTION__); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_pwm.c
C
apache-2.0
906
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include "aos_hal_rtc.h" rtc_time_t time_save; int32_t aos_hal_rtc_init(rtc_dev_t *rtc) { time_save.year = 97; time_save.month = 10; time_save.date = 3; time_save.hr = 10; time_save.min = 20; time_save.sec = 45; return 0; } int32_t aos_hal_rtc_get_time(rtc_dev_t *rtc, rtc_time_t *time) { time->year = time_save.year; time->month = time_save.month; time->date = time_save.date; time->hr = time_save.hr; time->min = time_save.min; time->sec = time_save.sec; return 0; } int32_t aos_hal_rtc_set_time(rtc_dev_t *rtc, const rtc_time_t *time) { time_save.year = time->year; time_save.month = time->month; time_save.date = time->date; time_save.hr = time->hr; time_save.min = time->min; time_save.sec = time->sec; return 0; } int32_t aos_hal_rtc_finalize(rtc_dev_t *rtc) { time_save.year = 0; time_save.month = 0; time_save.date = 0; time_save.hr = 0; time_save.min = 0; time_save.sec = 0; return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_rtc.c
C
apache-2.0
1,105
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include "aos_hal_timer.h" #include <sys/types.h> #include <sys/time.h> #include <signal.h> #include <time.h> static void timer_common_cb(union sigval arg) { timer_dev_t *amp_timer = (timer_dev_t *)arg.sival_ptr; if (amp_timer && amp_timer->config.cb) { amp_timer->config.cb(amp_timer->config.arg); } } int32_t aos_hal_timer_init(timer_dev_t *tim) { struct sigevent ent; timer_t *timer = aos_malloc(sizeof(timer_t)); memset(&ent, 0x00, sizeof(struct sigevent)); /* create a timer */ ent.sigev_notify = SIGEV_THREAD; ent.sigev_notify_function = (void (*)(union sigval))timer_common_cb; ent.sigev_value.sival_ptr = tim; if (timer_create(CLOCK_MONOTONIC, &ent, timer) != 0) { aos_free(timer); return -1; } tim->priv = timer; return 0; } int32_t aos_hal_timer_start(timer_dev_t *tim) { struct itimerspec ts; /* check parameter */ if (tim == NULL) { return -1; } if (tim->config.reload_mode == TIMER_RELOAD_AUTO) { /* it_value=0: stop timer */ ts.it_interval.tv_sec = tim->config.period / 1000000; ts.it_interval.tv_nsec = (tim->config.period % 1000000) * 1000; } else { /* it_interval=0: timer run only once */ ts.it_interval.tv_sec = 0;; ts.it_interval.tv_nsec = 0; } /* it_value=0: stop timer */ ts.it_value.tv_sec = tim->config.period / 1000000; ts.it_value.tv_nsec = (tim->config.period % 1000000) * 1000; return timer_settime(*(timer_t *)tim->priv, 0, &ts, NULL); } void aos_hal_timer_stop(timer_dev_t *tim) { struct itimerspec ts; /* check parameter */ if (tim == NULL) { return; } /* it_interval=0: timer run only once */ ts.it_interval.tv_sec = 0; ts.it_interval.tv_nsec = 0; /* it_value=0: stop timer */ ts.it_value.tv_sec = 0; ts.it_value.tv_nsec = 0; timer_settime(*(timer_t *)tim->priv, 0, &ts, NULL); return ; } int32_t aos_hal_timer_finalize(timer_dev_t *tim) { int ret = 0; /* check parameter */ if (tim == NULL) { return -1; } ret = timer_delete(*(timer_t *)tim->priv); aos_free(tim->priv); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_timer.c
C
apache-2.0
2,302
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdint.h> #include <errno.h> #include <execinfo.h> #include <stdlib.h> #include <stdio.h> #include <sys/select.h> #include <termios.h> #include <unistd.h> #include <semaphore.h> #include <pthread.h> #include <signal.h> #include <sys/time.h> #include <time.h> #include "aos_hal_uart.h" int32_t aos_hal_uart_callback(uart_dev_t *uart, void (*cb)(int, void *, uint16_t, void *), void *args) { return 0; } typedef unsigned char UINT8; /* Unsigned 8 bit quantity */ typedef signed char INT8; /* Signed 8 bit quantity */ typedef unsigned short UINT16; /* Unsigned 16 bit quantity */ typedef signed short INT16; /* Signed 16 bit quantity */ typedef uint32_t UINT32; /* Unsigned 32 bit quantity */ typedef int32_t INT32; /* Signed 32 bit quantity */ static struct termios term_orig; #define MAX_UART_NUM 1 enum _uart_status_e { _UART_STATUS_CLOSED = 0, _UART_STATUS_OPENED, }; typedef struct { uint8_t uart; uint8_t status; pthread_t threaid; pthread_mutex_t mutex; } _uart_drv_t; static _uart_drv_t _uart_drv[MAX_UART_NUM]; extern int32_t uart_read_byte(uint8_t *rx_byte); extern void uart_write_byte(uint8_t byte); extern uint8_t uart_is_tx_fifo_empty(void); extern uint8_t uart_is_tx_fifo_full(void); extern void uart_set_tx_stop_end_int(uint8_t set); static void exit_cleanup(void) { tcsetattr(0, TCSANOW, &term_orig); } int32_t aos_hal_uart_init(uart_dev_t *uart) { setvbuf(stdout, NULL, _IONBF, 0); int err_num; _uart_drv_t *pdrv = &_uart_drv[0]; struct termios term_vi; if (pdrv->status == _UART_STATUS_CLOSED) { pdrv->status = _UART_STATUS_OPENED; tcgetattr(0, &term_orig); term_vi = term_orig; term_vi.c_lflag &= (~ICANON & ~ECHO); // leave ISIG ON- allow intr's term_vi.c_iflag &= (~IXON & ~ICRNL); tcsetattr(0, TCSANOW, &term_vi); atexit(exit_cleanup); err_num = pthread_mutex_init(&pdrv->mutex, NULL); if (0 != err_num) { perror("create mutex failed\n"); return -1; } } else { return -1; } return 0; } int32_t aos_hal_uart_finalize(uart_dev_t *uart) { _uart_drv_t *pdrv = &_uart_drv[uart->port]; pthread_mutex_destroy(&pdrv->mutex); pdrv->status = _UART_STATUS_CLOSED; tcsetattr(0, TCSANOW, &term_orig); return 0; } int32_t aos_hal_uart_send(uart_dev_t *uart, const void *data, uint32_t size, uint32_t timeout) { uint32_t i = 0; _uart_drv_t *pdrv = &_uart_drv[uart->port]; pthread_mutex_lock(&pdrv->mutex); for (i = 0; i < size; i++) { putchar(((uint8_t *)data)[i]); } pthread_mutex_unlock(&pdrv->mutex); return 0; } int aaa = 0; int32_t aos_hal_uart_recv_poll(uart_dev_t *uart, void *data, uint32_t expect_size, uint32_t *recv_size) { fd_set fdset; int ret; char nbuf; char *read_buf = data; (void *)uart; if (data == NULL || recv_size == NULL) { return -1; } *recv_size = 0; /* Obtain the size of the packet and put it into the "len" variable. */ int readlen = read(0, &nbuf, 1); if (readlen > 0) { *(char *)data = nbuf; *recv_size = 1; return 0; } return -1; } int32_t aos_hal_uart_recv_II(uart_dev_t *uart, void *data, uint32_t expect_size, uint32_t *recv_size, uint32_t timeout) { fd_set fdset; int ret; char nbuf; char *read_buf = data; struct timeval st; time_t t_begin, t_now; (void *)uart; t_begin = clock(); if (data == NULL || recv_size == NULL) { return -1; } *recv_size = 0; while (1) { t_now = clock(); if (difftime(t_now, t_begin) > timeout) { break; } usleep(10); FD_ZERO(&fdset); FD_SET(0, &fdset); /* Wait for a packet to arrive. */ st.tv_sec = 0; st.tv_usec = 100; ret = select(1, &fdset, NULL, NULL, &st); if (ret == 1) { /* Obtain the size of the packet and put it into the "len" variable. */ int readlen = read(0, &nbuf, 1); if (readlen < 0) { perror("cli read eror"); continue; } /* Handle incoming packet. */ read_buf[*recv_size] = nbuf; *recv_size += 1; if (*recv_size >= expect_size) { break; } } } return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_uart.c
C
apache-2.0
4,562
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/errno.h> #include "aos_hal_wdg.h" int32_t aos_hal_wdg_init(wdg_dev_t *wdg) { if(NULL == wdg ) { printf("parameter is invalid!\n\r"); return -1; } printf ("[%s] timeout = %d \r\n", __FUNCTION__, wdg->config.timeout); return 0; } void aos_hal_wdg_reload(wdg_dev_t *wdg) { printf ("[%s] \r\n", __FUNCTION__); return; } int32_t aos_hal_wdg_finalize(wdg_dev_t *wdg) { printf ("[%s] \r\n", __FUNCTION__); return 0; }
YifuLiu/AliOS-Things
components/amp_adapter/platform/linux/peripheral/aos_hal_wdg.c
C
apache-2.0
564
/** * @file vfs.h * @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef AOS_VFS_H #define AOS_VFS_H #include <stddef.h> #include <stdint.h> #include <unistd.h> #include <time.h> #include <sys/stat.h> #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif /** @addtogroup aos_vfs VFS * VFS AOS API. * * @{ */ /** * @brief aos_utimbuf structure describes the filesystem inode's * last access time and last modification time. */ struct aos_utimbuf { time_t actime; /**< time of last access */ time_t modtime; /**< time of last modification */ }; struct aos_statfs { long f_type; /**< fs type */ long f_bsize; /**< optimized transport block size */ long f_blocks; /**< total blocks */ long f_bfree; /**< available blocks */ long f_bavail; /**< number of blocks that non-super users can acquire */ long f_files; /**< total number of file nodes */ long f_ffree; /**< available file nodes */ long f_fsid; /**< fs id */ long f_namelen; /**< max file name length */ }; struct aos_stat { uint16_t st_mode; /**< mode of file */ uint32_t st_size; /**< bytes of file */ time_t st_actime; /**< time of last access */ time_t st_modtime; /**< time of last modification */ }; typedef struct { int32_t d_ino; /**< file number */ uint8_t d_type; /**< type of file */ char d_name[]; /**< file name */ } aos_dirent_t; typedef struct { int32_t dd_vfs_fd; /**< file index in vfs */ int32_t dd_rsv; /**< Reserved */ } aos_dir_t; typedef const struct file_ops file_ops_t; typedef const struct fs_ops fs_ops_t; union inode_ops_t { const file_ops_t *i_ops; /**< char driver operations */ const fs_ops_t *i_fops; /**< FS operations */ }; typedef struct { union inode_ops_t ops; /**< inode operations */ void *i_arg; /**< per inode private data */ char *i_name; /**< name of inode */ int i_flags; /**< flags for inode */ uint8_t type; /**< type for inode */ uint8_t refs; /**< refs for inode */ } inode_t; typedef struct { inode_t *node; /**< node for file */ void *f_arg; /**< f_arg for file */ size_t offset; /**< offset for file */ } file_t; typedef void (*poll_notify_t)(void *pollfd, void *arg); /** * @brief file_ops structure defines the file operation handles */ struct file_ops { int (*open)(inode_t *node, file_t *fp); int (*close)(file_t *fp); ssize_t (*read)(file_t *fp, void *buf, size_t nbytes); ssize_t (*write)(file_t *fp, const void *buf, size_t nbytes); int (*ioctl)(file_t *fp, int cmd, unsigned long arg); int (*poll)(file_t *fp, int flag, poll_notify_t notify, void *fd, void *arg); uint32_t (*lseek)(file_t *fp, int64_t off, int32_t whence); int (*stat)(file_t *fp, const char *path, struct aos_stat *st); void* (*mmap)(file_t *fp, size_t len); int (*access)(file_t *fp, const char *path, int amode); }; /** * @brief fs_ops structures defines the filesystem operation handles */ struct fs_ops { int (*open)(file_t *fp, const char *path, int flags); int (*close)(file_t *fp); ssize_t (*read)(file_t *fp, char *buf, size_t len); ssize_t (*write)(file_t *fp, const char *buf, size_t len); off_t (*lseek)(file_t *fp, off_t off, int whence); int (*sync)(file_t *fp); int (*stat)(file_t *fp, const char *path, struct aos_stat *st); int (*fstat)(file_t *fp, struct aos_stat *st); int (*link)(file_t *fp, const char *path1, const char *path2); int (*unlink)(file_t *fp, const char *path); int (*remove)(file_t *fp, const char *path); int (*rename)(file_t *fp, const char *oldpath, const char *newpath); aos_dir_t *(*opendir)(file_t *fp, const char *path); aos_dirent_t *(*readdir)(file_t *fp, aos_dir_t *dir); int (*closedir)(file_t *fp, aos_dir_t *dir); int (*mkdir)(file_t *fp, const char *path); int (*rmdir)(file_t *fp, const char *path); void (*rewinddir)(file_t *fp, aos_dir_t *dir); long (*telldir)(file_t *fp, aos_dir_t *dir); void (*seekdir)(file_t *fp, aos_dir_t *dir, long loc); int (*ioctl)(file_t *fp, int cmd, unsigned long arg); int (*statfs)(file_t *fp, const char *path, struct aos_statfs *suf); int (*access)(file_t *fp, const char *path, int amode); long (*pathconf)(file_t *fp, const char *path, int name); long (*fpathconf)(file_t *fp, int name); int (*utime)(file_t *fp, const char *path, const struct aos_utimbuf *times); }; /** * @brief aos_vfs_init() initializes vfs system. * * @param[in] NULL * * @return On success, return new file descriptor. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_vfs_init(void); /** * @brief aos_open() opens the file or device by its @path. * * @param[in] path the path of the file or device to open. * @param[in] flags the mode of open operation. * * @return On success, return new file descriptor. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_open(const char *path, int flags); /** * @brief aos_close() closes the file or device associated with file * descriptor @fd. * * @param[in] fd the file descriptor of the file or device. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_close(int fd); /** * @brief aos_read() attempts to read up to @nbytes bytes from file * descriptor @fd into the buffer starting at @buf. * * @param[in] fd the file descriptor of the file or device. * @param[out] buf the buffer to read bytes into. * @param[in] nbytes the number of bytes to read. * * @return On success, the number of bytes is returned (0 indicates end * of file) and the file position is advanced by this number. * On error, negative error code is returned to indicate the cause * of the error. */ ssize_t aos_read(int fd, void *buf, size_t nbytes); /** * @brief aos_write() writes up to @nbytes bytes from the buffer starting * at @buf to the file referred to by the file descriptor @fd. * * @param[in] fd the file descriptor of the file or device. * @param[in] buf the buffer to write bytes from. * @param[in] nbytes the number of bytes to write. * * @return On success, the number of bytes written is returned, adn the file * position is advanced by this number.. * On error, negative error code is returned to indicate the cause * of the error. */ ssize_t aos_write(int fd, const void *buf, size_t nbytes); /** * @brief aos_ioctl() manipulates the underlying device parameters of special * files. In particular, many operating characteristics of character * special filse may be controlled with aos_iotcl() requests. The argumnet * @fd must be an open file descriptor. * * @param[in] fd the file descriptior of the file or device. * @param[in] cmd A device-dependent request code. * @param[in] arg Argument to the request code, which is interpreted according * to the request code. * * @return Usually, on success 0 is returned. Some requests use the return * value as an output parameter and return a nonnegative value on success. * On error, neagtive error code is returned to indicate the cause * of the error. */ int aos_ioctl(int fd, int cmd, unsigned long arg); /** * @brief aos_do_pollfd() is a wildcard API for executing the particular poll events * * @param[in] fd The file descriptor of the file or device * @param[in] flag The flag of the polling * @param[in] notify The polling notify callback * @param[in] fds A pointer to the array of pollfd * @param[in] arg The arguments of the polling * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_do_pollfd(int fd, int flag, poll_notify_t notify, void *fds, void *arg); /** * @brief aos_lseek() repositions the file offset of the open file * description associated with the file descriptor @fd to the * argument @offset according to the directive @whence as follows: * * SEEK_SET: The file offset is set to @offset bytes. * SEEK_CUR: The file offset is set to its current location * plus @offset bytes. * SEEK_END: The file offset is set to the size of the file * plus @offset bytes. * * @param[in] fd The file descriptor of the file. * @param[in] offset The offset relative to @whence directive. * @param[in] whence The start position where to seek. * * @return On success, return the resulting offset location as measured * in bytes from the beginning of the file. * On error, neagtive error code is returned to indicate the cause * of the error. */ off_t aos_lseek(int fd, off_t offset, int whence); /** * @brief aos_sync causes the pending modifications of the specified file to * be written to the underlying filesystems. * * @param[in] fd the file descriptor of the file. * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_sync(int fd); /** * @brief aos_allsync causes all pending modifications to filesystem metadata * and cached file data to be written to the underlying filesystems. * * @return none */ void aos_allsync(void); /** * @brief aos_stat() return information about a file pointed to by @path * in the buffer pointed to by @st. * * @param[in] path The path of the file to be quried. * @param[out] st The buffer to receive information. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_stat(const char *path, struct aos_stat *st); /** * @brief aos_fstat() return information about a file specified by the file * descriptor @fd in the buffer pointed to by @st. * * @note aos_fstat() is identical to aos_stat(), except that the file about * which information is to be retrieved is specified by the file * descriptor @fd. * * @param[in] fd The file descriptor of the file to be quired. * @param[out] st The buffer to receive information. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_fstat(int fd, struct aos_stat *st); /** * @brief aos_link() creates a new link @newpath to an existing file @oldpath. * * @note If @newpath exists, it will not be ovrewritten. * * @param[in] oldpath The old path * @param[in] newpath The new path to be created * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_link(const char *oldpath, const char *newpath); /** * @brief aos_unlink() deletes a name from the filesystem. * * @param[in] path The path of the file to be deleted. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_unlink(const char *path); /** * @brief aos_remove() deletes a name from the filesystem. * * @param[in] path The path of the file to be deleted. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_remove(const char *path); /** * @brief aos_rename() renames a file, moving it between directories * if required. * * @param[in] oldpath The old path of the file to rename. * @param[in] newpath The new path to rename the file to. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_rename(const char *oldpath, const char *newpath); /** * @brief aos_opendir() opens a directory stream corresponding to the * directory @path, and returns a pointer to the directory stream. * The stream is positioned at the first entry in the directory. * * @param[in] path the path of the directory to open. * * @return On success, return a point of directory stream. * On error, NULL is returned. */ aos_dir_t *aos_opendir(const char *path); /** * @brief aos_closedir() closes the directory stream associated with * @dir. A successful call to aos_closedir() also closes the * underlying file descriptor associated with @dir. The directory * stream descriptor @dir is not available after this call. * * @param[in] dir The directory stream descriptor to be closed. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_closedir(aos_dir_t *dir); /** * @brief aos_readdir() returns a pointer to an @aos_dirent_t representing * the next directory entry in the directory stream pointed to by * @dir. It returns Null on reaching the end of the directory stream * or if an error occurred. * * @param[in] dir The directory stream descriptor to read. * * @return On success, aos_readdir() returns a pointer to an @aos_dirent_t * structure. If the end of the directory stream is reached, NULL is * returned. * On error, NULL is returned. */ aos_dirent_t *aos_readdir(aos_dir_t *dir); /** * @brief aos_mkdir() attempts to create a directory named @path * * @param[in] path The name of directory to be created. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_mkdir(const char *path); /** * @brief aos_rmdir() deletes a directory, which must be emtpy. * * @param[in] path The directory to be deleted. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_rmdir(const char *path); /** * @brief aos_rewinddir() resets the position of the directory stream @dir * to the beginning of the directory. * * @param[in] dir The directory stream descriptor pointer. * * @return none. */ void aos_rewinddir(aos_dir_t *dir); /** * @brief aos_telldir() returns the current location associated with the * directory stream @dir. * * @param[in] dir The directory stream descriptor pointer. * * @return On success, aos_telldir() returns the current location in the * directory stream. * On error, negative error code is returned to indicate the cause * of the error. */ long aos_telldir(aos_dir_t *dir); /** * @brief aos_seekdir() sets the location in the directory stram from * which the next aos_readdir() call will start. The @loc argument * should be a value returnned by a previous call to aos_telldir(). * * @param[in] dir The directory stream descriptor pointer. * @param[in] loc The location in the directory stream from which the next * aos_readdir() call will start. * * @return none. */ void aos_seekdir(aos_dir_t *dir, long loc); /** * @brief aos_statfs() gets information about a mounted filesystem. * * @param[in] path The path name of any file within the mounted filessytem. * @param[out] buf Buffer points to an aos_statfs structure to receive * filesystem information. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_statfs(const char *path, struct aos_statfs *buf); /** * @brief aos_access() checks whether the calling process can access the * file @path. * * @param[in] path The path of the file. * @param[in] mode Specifies the accessibility check(s) to be performed, and * is either the value of F_OK, or a mask consisting of the * bitwise OR of one or more of R_OK, W_OK, and X_OK. F_OK * tests for the existence of the file. R_OK, W_OK and X_OK * tests whether the file exists and grants read, write, and * execute permissions, repectively. * * @return On success (all requested permissions granted, or mode is F_OK and * the file exists), 0 is returned. * On error (at least one bit in mode asked for a permission that is * denied, or mode is F_OK and the file does not exist, or some other * error occurred), negative error code is returned to indicate the * cause of the error. */ int aos_access(const char *path, int amode); /** * @brief aos_chdir() changes the current working directory of the calling * process to the directory specified in @path. * * @param[in] path The path to change to. * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_chdir(const char *path); /** * @brief aos_getcwd() return a null-terminated string containing an absolute * pathname that is the current working directory of the calling process. * The pathname is returned as the function result and via the argument * @buf, if present. * aos_getcwd() function copies an absolute pathname of the current * working directory to the array pointed by @buf, which is of length @size. * * If the length of the absolute pathname of the current working directory, * including the terminating null byte, exceeds @size bytes, NULL is returned. * * @param[out] buf The buffer to receive the current working directory pathname. * @param[in] size The size of buffer. * * @return On success, aos_getcwd() returns a pointer to a string containing * the pathname of the current working directory. * On error, NULL is returned. */ char *aos_getcwd(char *buf, size_t size); /** * @brief aos_pathconf() gets a value for configuration option @name for the * filename @path. * * @param[in] path The path name to quire * @param[in] name The configuration option * * @return On error, negative error code is returned to indicate the cause * of the error. * On success, if @name corresponds to an option, a positive value is * returned if the option is supported. */ long aos_pathconf(const char *path, int name); /** * @brief aos_fpathconf() gets a value for the cofiguration option @name for * the open file descriptor @fd. * * @param[in] fd The open file descriptor to quire * @param[in] name The configuration option * * @return On success, if @name corresponds to an option, a positive value is * returned if the option is supported. * On error, negative error code is returned to indicate the cause * of the error. */ long aos_fpathconf(int fd, int name); /** * @brief aos_utime() changes teh access and modification times of the inode * specified by @path to the actime and modtime fields of the @times * respectively. * If @times is NULL, then the access and modification times of the file * are set to the current time. * * @param[in] path Path name of the inode to operate. * @param[in] times Buffer pointer to structure aos_utimbuf whose actime * and modtime fields will be set to the inode @path. * * @return 0 on success, negative error code on failure */ int aos_utime(const char *path, const struct aos_utimbuf *times); /** * @brief aos_vfs_fd_offset_get() gets VFS fd offset * * @return VFS fd offset */ int aos_vfs_fd_offset_get(void); /** * @brief aos_fcntl() change the nature of the opened file * * @param[in] fd The open file descriptor to quire * @param[in] cmd The configuration command. * @param[in] val The configuration value. * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_fcntl(int fd, int cmd, int val); /** * @brief Bind driver to the file or device * * @param[in] path The path of the file or device * @param[in] ops The driver operations to bind * @param[in] arg The arguments of the driver operations * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_register_driver(const char *path, file_ops_t *ops, void *arg); /** * @brief Unbind driver from the file or device * * @param[in] path The path of the file or device * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_unregister_driver(const char *path); /** * @brief aos_register_fs() mounts filesystem to the path * * @param[in] path The mount point path * @param[in] ops The filesystem operations * @param[in] arg The arguments of the filesystem operations * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_register_fs(const char *path, fs_ops_t* ops, void *arg); /** * @brief aos_unregister_fs() unmounts the filesystem * * @param[in] path The mount point path * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_unregister_fs(const char *path); /* adapter tmp */ //typedef struct aos_stat stat; /** @} */ #ifdef __cplusplus } #endif #endif /* AOS_VFS_H */
YifuLiu/AliOS-Things
components/amp_adapter/portfiles/aos/vfs.h
C
apache-2.0
22,284
/** * @file vfs.h * @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef AOS_VFS_H #define AOS_VFS_H #include <stddef.h> #include <stdint.h> #include <unistd.h> #include <time.h> #include <sys/stat.h> #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif /** @addtogroup aos_vfs VFS * VFS AOS API. * * @{ */ /** * @brief aos_utimbuf structure describes the filesystem inode's * last access time and last modification time. */ struct aos_utimbuf { time_t actime; /**< time of last access */ time_t modtime; /**< time of last modification */ }; struct aos_statfs { long f_type; /**< fs type */ long f_bsize; /**< optimized transport block size */ long f_blocks; /**< total blocks */ long f_bfree; /**< available blocks */ long f_bavail; /**< number of blocks that non-super users can acquire */ long f_files; /**< total number of file nodes */ long f_ffree; /**< available file nodes */ long f_fsid; /**< fs id */ long f_namelen; /**< max file name length */ }; struct aos_stat { uint16_t st_mode; /**< mode of file */ uint32_t st_size; /**< bytes of file */ time_t st_actime; /**< time of last access */ time_t st_modtime; /**< time of last modification */ }; typedef struct { int32_t d_ino; /**< file number */ uint8_t d_type; /**< type of file */ char d_name[]; /**< file name */ } aos_dirent_t; typedef struct { int32_t dd_vfs_fd; /**< file index in vfs */ int32_t dd_rsv; /**< Reserved */ } aos_dir_t; typedef const struct file_ops file_ops_t; typedef const struct fs_ops fs_ops_t; union inode_ops_t { const file_ops_t *i_ops; /**< char driver operations */ const fs_ops_t *i_fops; /**< FS operations */ }; typedef struct { union inode_ops_t ops; /**< inode operations */ void *i_arg; /**< per inode private data */ char *i_name; /**< name of inode */ int i_flags; /**< flags for inode */ uint8_t type; /**< type for inode */ uint8_t refs; /**< refs for inode */ } inode_t; typedef struct { inode_t *node; /**< node for file */ void *f_arg; /**< f_arg for file */ size_t offset; /**< offset for file */ } file_t; typedef void (*poll_notify_t)(void *pollfd, void *arg); /** * @brief file_ops structure defines the file operation handles */ struct file_ops { int (*open)(inode_t *node, file_t *fp); int (*close)(file_t *fp); ssize_t (*read)(file_t *fp, void *buf, size_t nbytes); ssize_t (*write)(file_t *fp, const void *buf, size_t nbytes); int (*ioctl)(file_t *fp, int cmd, unsigned long arg); int (*poll)(file_t *fp, int flag, poll_notify_t notify, void *fd, void *arg); uint32_t (*lseek)(file_t *fp, int64_t off, int32_t whence); int (*stat)(file_t *fp, const char *path, struct aos_stat *st); void* (*mmap)(file_t *fp, size_t len); int (*access)(file_t *fp, const char *path, int amode); }; /** * @brief fs_ops structures defines the filesystem operation handles */ struct fs_ops { int (*open)(file_t *fp, const char *path, int flags); int (*close)(file_t *fp); ssize_t (*read)(file_t *fp, char *buf, size_t len); ssize_t (*write)(file_t *fp, const char *buf, size_t len); off_t (*lseek)(file_t *fp, off_t off, int whence); int (*sync)(file_t *fp); int (*stat)(file_t *fp, const char *path, struct aos_stat *st); int (*fstat)(file_t *fp, struct aos_stat *st); int (*link)(file_t *fp, const char *path1, const char *path2); int (*unlink)(file_t *fp, const char *path); int (*remove)(file_t *fp, const char *path); int (*rename)(file_t *fp, const char *oldpath, const char *newpath); aos_dir_t *(*opendir)(file_t *fp, const char *path); aos_dirent_t *(*readdir)(file_t *fp, aos_dir_t *dir); int (*closedir)(file_t *fp, aos_dir_t *dir); int (*mkdir)(file_t *fp, const char *path); int (*rmdir)(file_t *fp, const char *path); void (*rewinddir)(file_t *fp, aos_dir_t *dir); long (*telldir)(file_t *fp, aos_dir_t *dir); void (*seekdir)(file_t *fp, aos_dir_t *dir, long loc); int (*ioctl)(file_t *fp, int cmd, unsigned long arg); int (*statfs)(file_t *fp, const char *path, struct aos_statfs *suf); int (*access)(file_t *fp, const char *path, int amode); long (*pathconf)(file_t *fp, const char *path, int name); long (*fpathconf)(file_t *fp, int name); int (*utime)(file_t *fp, const char *path, const struct aos_utimbuf *times); }; /** * @brief aos_vfs_init() initializes vfs system. * * @param[in] NULL * * @return On success, return new file descriptor. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_vfs_init(void); /** * @brief aos_open() opens the file or device by its @path. * * @param[in] path the path of the file or device to open. * @param[in] flags the mode of open operation. * * @return On success, return new file descriptor. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_open(const char *path, int flags); /** * @brief aos_close() closes the file or device associated with file * descriptor @fd. * * @param[in] fd the file descriptor of the file or device. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_close(int fd); /** * @brief aos_read() attempts to read up to @nbytes bytes from file * descriptor @fd into the buffer starting at @buf. * * @param[in] fd the file descriptor of the file or device. * @param[out] buf the buffer to read bytes into. * @param[in] nbytes the number of bytes to read. * * @return On success, the number of bytes is returned (0 indicates end * of file) and the file position is advanced by this number. * On error, negative error code is returned to indicate the cause * of the error. */ ssize_t aos_read(int fd, void *buf, size_t nbytes); /** * @brief aos_write() writes up to @nbytes bytes from the buffer starting * at @buf to the file referred to by the file descriptor @fd. * * @param[in] fd the file descriptor of the file or device. * @param[in] buf the buffer to write bytes from. * @param[in] nbytes the number of bytes to write. * * @return On success, the number of bytes written is returned, adn the file * position is advanced by this number.. * On error, negative error code is returned to indicate the cause * of the error. */ ssize_t aos_write(int fd, const void *buf, size_t nbytes); /** * @brief aos_ioctl() manipulates the underlying device parameters of special * files. In particular, many operating characteristics of character * special filse may be controlled with aos_iotcl() requests. The argumnet * @fd must be an open file descriptor. * * @param[in] fd the file descriptior of the file or device. * @param[in] cmd A device-dependent request code. * @param[in] arg Argument to the request code, which is interpreted according * to the request code. * * @return Usually, on success 0 is returned. Some requests use the return * value as an output parameter and return a nonnegative value on success. * On error, neagtive error code is returned to indicate the cause * of the error. */ int aos_ioctl(int fd, int cmd, unsigned long arg); /** * @brief aos_do_pollfd() is a wildcard API for executing the particular poll events * * @param[in] fd The file descriptor of the file or device * @param[in] flag The flag of the polling * @param[in] notify The polling notify callback * @param[in] fds A pointer to the array of pollfd * @param[in] arg The arguments of the polling * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_do_pollfd(int fd, int flag, poll_notify_t notify, void *fds, void *arg); /** * @brief aos_lseek() repositions the file offset of the open file * description associated with the file descriptor @fd to the * argument @offset according to the directive @whence as follows: * * SEEK_SET: The file offset is set to @offset bytes. * SEEK_CUR: The file offset is set to its current location * plus @offset bytes. * SEEK_END: The file offset is set to the size of the file * plus @offset bytes. * * @param[in] fd The file descriptor of the file. * @param[in] offset The offset relative to @whence directive. * @param[in] whence The start position where to seek. * * @return On success, return the resulting offset location as measured * in bytes from the beginning of the file. * On error, neagtive error code is returned to indicate the cause * of the error. */ off_t aos_lseek(int fd, off_t offset, int whence); /** * @brief aos_sync causes the pending modifications of the specified file to * be written to the underlying filesystems. * * @param[in] fd the file descriptor of the file. * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_sync(int fd); /** * @brief aos_allsync causes all pending modifications to filesystem metadata * and cached file data to be written to the underlying filesystems. * * @return none */ void aos_allsync(void); /** * @brief aos_stat() return information about a file pointed to by @path * in the buffer pointed to by @st. * * @param[in] path The path of the file to be quried. * @param[out] st The buffer to receive information. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_stat(const char *path, struct aos_stat *st); /** * @brief aos_fstat() return information about a file specified by the file * descriptor @fd in the buffer pointed to by @st. * * @note aos_fstat() is identical to aos_stat(), except that the file about * which information is to be retrieved is specified by the file * descriptor @fd. * * @param[in] fd The file descriptor of the file to be quired. * @param[out] st The buffer to receive information. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_fstat(int fd, struct aos_stat *st); /** * @brief aos_link() creates a new link @newpath to an existing file @oldpath. * * @note If @newpath exists, it will not be ovrewritten. * * @param[in] oldpath The old path * @param[in] newpath The new path to be created * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_link(const char *oldpath, const char *newpath); /** * @brief aos_unlink() deletes a name from the filesystem. * * @param[in] path The path of the file to be deleted. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_unlink(const char *path); /** * @brief aos_remove() deletes a name from the filesystem. * * @param[in] path The path of the file to be deleted. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_remove(const char *path); /** * @brief aos_rename() renames a file, moving it between directories * if required. * * @param[in] oldpath The old path of the file to rename. * @param[in] newpath The new path to rename the file to. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_rename(const char *oldpath, const char *newpath); /** * @brief aos_opendir() opens a directory stream corresponding to the * directory @path, and returns a pointer to the directory stream. * The stream is positioned at the first entry in the directory. * * @param[in] path the path of the directory to open. * * @return On success, return a point of directory stream. * On error, NULL is returned. */ aos_dir_t *aos_opendir(const char *path); /** * @brief aos_closedir() closes the directory stream associated with * @dir. A successful call to aos_closedir() also closes the * underlying file descriptor associated with @dir. The directory * stream descriptor @dir is not available after this call. * * @param[in] dir The directory stream descriptor to be closed. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_closedir(aos_dir_t *dir); /** * @brief aos_readdir() returns a pointer to an @aos_dirent_t representing * the next directory entry in the directory stream pointed to by * @dir. It returns Null on reaching the end of the directory stream * or if an error occurred. * * @param[in] dir The directory stream descriptor to read. * * @return On success, aos_readdir() returns a pointer to an @aos_dirent_t * structure. If the end of the directory stream is reached, NULL is * returned. * On error, NULL is returned. */ aos_dirent_t *aos_readdir(aos_dir_t *dir); /** * @brief aos_mkdir() attempts to create a directory named @path * * @param[in] path The name of directory to be created. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_mkdir(const char *path); /** * @brief aos_rmdir() deletes a directory, which must be emtpy. * * @param[in] path The directory to be deleted. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_rmdir(const char *path); /** * @brief aos_rewinddir() resets the position of the directory stream @dir * to the beginning of the directory. * * @param[in] dir The directory stream descriptor pointer. * * @return none. */ void aos_rewinddir(aos_dir_t *dir); /** * @brief aos_telldir() returns the current location associated with the * directory stream @dir. * * @param[in] dir The directory stream descriptor pointer. * * @return On success, aos_telldir() returns the current location in the * directory stream. * On error, negative error code is returned to indicate the cause * of the error. */ long aos_telldir(aos_dir_t *dir); /** * @brief aos_seekdir() sets the location in the directory stram from * which the next aos_readdir() call will start. The @loc argument * should be a value returnned by a previous call to aos_telldir(). * * @param[in] dir The directory stream descriptor pointer. * @param[in] loc The location in the directory stream from which the next * aos_readdir() call will start. * * @return none. */ void aos_seekdir(aos_dir_t *dir, long loc); /** * @brief aos_statfs() gets information about a mounted filesystem. * * @param[in] path The path name of any file within the mounted filessytem. * @param[out] buf Buffer points to an aos_statfs structure to receive * filesystem information. * * @return On success, return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_statfs(const char *path, struct aos_statfs *buf); /** * @brief aos_access() checks whether the calling process can access the * file @path. * * @param[in] path The path of the file. * @param[in] mode Specifies the accessibility check(s) to be performed, and * is either the value of F_OK, or a mask consisting of the * bitwise OR of one or more of R_OK, W_OK, and X_OK. F_OK * tests for the existence of the file. R_OK, W_OK and X_OK * tests whether the file exists and grants read, write, and * execute permissions, repectively. * * @return On success (all requested permissions granted, or mode is F_OK and * the file exists), 0 is returned. * On error (at least one bit in mode asked for a permission that is * denied, or mode is F_OK and the file does not exist, or some other * error occurred), negative error code is returned to indicate the * cause of the error. */ int aos_access(const char *path, int amode); /** * @brief aos_chdir() changes the current working directory of the calling * process to the directory specified in @path. * * @param[in] path The path to change to. * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_chdir(const char *path); /** * @brief aos_getcwd() return a null-terminated string containing an absolute * pathname that is the current working directory of the calling process. * The pathname is returned as the function result and via the argument * @buf, if present. * aos_getcwd() function copies an absolute pathname of the current * working directory to the array pointed by @buf, which is of length @size. * * If the length of the absolute pathname of the current working directory, * including the terminating null byte, exceeds @size bytes, NULL is returned. * * @param[out] buf The buffer to receive the current working directory pathname. * @param[in] size The size of buffer. * * @return On success, aos_getcwd() returns a pointer to a string containing * the pathname of the current working directory. * On error, NULL is returned. */ char *aos_getcwd(char *buf, size_t size); /** * @brief aos_pathconf() gets a value for configuration option @name for the * filename @path. * * @param[in] path The path name to quire * @param[in] name The configuration option * * @return On error, negative error code is returned to indicate the cause * of the error. * On success, if @name corresponds to an option, a positive value is * returned if the option is supported. */ long aos_pathconf(const char *path, int name); /** * @brief aos_fpathconf() gets a value for the cofiguration option @name for * the open file descriptor @fd. * * @param[in] fd The open file descriptor to quire * @param[in] name The configuration option * * @return On success, if @name corresponds to an option, a positive value is * returned if the option is supported. * On error, negative error code is returned to indicate the cause * of the error. */ long aos_fpathconf(int fd, int name); /** * @brief aos_utime() changes teh access and modification times of the inode * specified by @path to the actime and modtime fields of the @times * respectively. * If @times is NULL, then the access and modification times of the file * are set to the current time. * * @param[in] path Path name of the inode to operate. * @param[in] times Buffer pointer to structure aos_utimbuf whose actime * and modtime fields will be set to the inode @path. * * @return 0 on success, negative error code on failure */ int aos_utime(const char *path, const struct aos_utimbuf *times); /** * @brief aos_vfs_fd_offset_get() gets VFS fd offset * * @return VFS fd offset */ int aos_vfs_fd_offset_get(void); /** * @brief aos_fcntl() change the nature of the opened file * * @param[in] fd The open file descriptor to quire * @param[in] cmd The configuration command. * @param[in] val The configuration value. * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_fcntl(int fd, int cmd, int val); /** * @brief Bind driver to the file or device * * @param[in] path The path of the file or device * @param[in] ops The driver operations to bind * @param[in] arg The arguments of the driver operations * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_register_driver(const char *path, file_ops_t *ops, void *arg); /** * @brief Unbind driver from the file or device * * @param[in] path The path of the file or device * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_unregister_driver(const char *path); /** * @brief aos_register_fs() mounts filesystem to the path * * @param[in] path The mount point path * @param[in] ops The filesystem operations * @param[in] arg The arguments of the filesystem operations * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_register_fs(const char *path, fs_ops_t* ops, void *arg); /** * @brief aos_unregister_fs() unmounts the filesystem * * @param[in] path The mount point path * * @return On success return 0. * On error, negative error code is returned to indicate the cause * of the error. */ int aos_unregister_fs(const char *path); /* adapter tmp */ //typedef struct aos_stat stat; /** @} */ #ifdef __cplusplus } #endif #endif /* AOS_VFS_H */
YifuLiu/AliOS-Things
components/amp_adapter/vfs.h
C
apache-2.0
22,284
Import('defconfig') defconfig.library_yaml()
YifuLiu/AliOS-Things
components/ble_host/SConscript
Python
apache-2.0
45
#include <stdlib.h> #include <string.h> #include <stdio.h> //#include <aos/osal_debug.h> #include <aos/ble.h> #include <yoc/bas.h> #define TAG "BAS" enum { BAS_IDX_SVC, BAS_IDX_LEVEL_CHAR, BAS_IDX_LEVEL_VAL, BAS_IDX_LEVEL_CCC, BAS_IDX_MAX, }; static slist_t bas_list = {NULL}; gatt_service bas_service; static gatt_attr_t bas_attrs[BAS_IDX_MAX] = { [BAS_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(UUID_BAS), [BAS_IDX_LEVEL_CHAR] = GATT_CHAR_DEFINE(UUID_BAS_BATTERY_LEVEL, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_NOTIFY), [BAS_IDX_LEVEL_VAL] = GATT_CHAR_VAL_DEFINE(UUID_BAS_BATTERY_LEVEL, GATT_PERM_READ), [BAS_IDX_LEVEL_CCC] = GATT_CHAR_CCC_DEFINE(), }; static inline bas_t *get_bas(uint16_t bas_svc_handle) { slist_t *tmp; bas_t *node; slist_for_each_entry_safe(&bas_list, tmp, node, bas_t, next) { if (node->bas_svc_handle == bas_svc_handle) { return node; } } return NULL; } static void event_char_read(ble_event_en event, void *event_data) { evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data; bas_t *bas = get_bas(e->char_handle - BAS_IDX_LEVEL_VAL); if (bas == NULL) { return; } e->data = &bas->battery_level; e->len = 1; } static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; slist_t *tmp; bas_t *node; slist_for_each_entry_safe(&bas_list, tmp, node, bas_t, next) { if (e->connected == CONNECTED) { node->conn_handle = e->conn_handle; } else { node->conn_handle = 0xFFFF; } } } static void event_char_ccc_change(ble_event_en event, void *event_data) { evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data; bas_t *bas = get_bas(e->char_handle - BAS_IDX_LEVEL_CCC); if (bas == NULL) { return; } bas->ccc = e->ccc_value; } static int bas_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_CHAR_READ: event_char_read(event, event_data); break; case EVENT_GATT_CHAR_CCC_CHANGE: event_char_ccc_change(event, event_data); break; default: break; } return 0; } static ble_event_cb_t ble_cb = { .callback = bas_event_callback, }; bas_handle_t bas_init(bas_t *bas) { int ret = 0; if (bas == NULL) { return NULL; } ret = ble_stack_event_register(&ble_cb); if (ret) { goto err; } ret = ble_stack_gatt_registe_service(&bas_service, bas_attrs, BLE_ARRAY_NUM(bas_attrs)); if (ret < 0) { goto err; } bas->conn_handle = 0xFFFF; bas->bas_svc_handle = ret; bas->battery_level = 0xFF; bas->ccc = 0; slist_add(&bas->next, &bas_list); return bas; err: ///free(bas); return NULL; } int bas_level_update(bas_handle_t handle, uint8_t level) { if (handle == NULL) { return -BLE_STACK_ERR_NULL; } bas_t *bas = handle; if (level != bas->battery_level) { bas->battery_level = level; if (bas->conn_handle != 0xFFFF && bas->ccc == CCC_VALUE_NOTIFY) { return ble_stack_gatt_notificate(bas->conn_handle, bas->bas_svc_handle + BAS_IDX_LEVEL_VAL, &level, 1); } } return 0; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/bas.c
C
apache-2.0
3,613
## # Copyright (C) 2017 C-SKY Microsystems Co., 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. ## L_PATH := $(call cur-dir) include $(DEFINE_LOCAL) L_MODULE := libble_profile L_CFLAGS += -Wall L_INCS += $(L_PATH) kernel/protocols/bluetooth/include L_SRCS := hids.c bas.c dis.c ibeacons.c hrs.c uart_client.c uart_server.c ota_server.c ifeq ($(CONFIG_BT), y) include $(BUILD_MODULE) endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/build.mk
Makefile
apache-2.0
927
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <string.h> #include <stdio.h> //#include <aos/osal_debug.h> #include <aos/ble.h> #include <yoc/dis.h> #define TAG "DIS" enum { DIS_IDX_SVC, DIS_IDX_MANU_NUM_CHAR, DIS_IDX_MANU_NUM_VAL, DIS_IDX_MODEL_NUM_CHAR, DIS_IDX_MODEL_NUM_VAL, DIS_IDX_SER_NUM_CHAR, DIS_IDX_SER_NUM_VAL, DIS_IDX_HW_REV_CHAR, DIS_IDX_HW_REV_VAL, DIS_IDX_FW_REV_CHAR, DIS_IDX_FW_REV_VAL, DIS_IDX_SW_REV_CHAR, DIS_IDX_SW_REV_VAL, DIS_IDX_SYS_ID_CHAR, DIS_IDX_SYS_ID_VAL, DIS_IDX_REGU_LIST_CHAR, DIS_IDX_REGU_LIST_VAL, DIS_IDX_PNP_ID_CHAR, DIS_IDX_PNP_ID_VAL, DIS_IDX_MAX, }; typedef struct _dis_t { uint16_t conn_handle; dis_info_t *info; uint16_t dis_svc_handle; uint16_t manu_num_char_val_handle; uint16_t model_num_char_val_handle; uint16_t ser_num_char_val_handle; uint16_t hw_rev_char_val_handle; uint16_t fw_rev_char_val_handle; uint16_t sw_rev_char_val_handle; uint16_t regu_list_char_val_handle; uint16_t sys_id_char_val_handle; uint16_t pnp_id_char_val_handle; } dis_t; dis_t g_dis; gatt_service dis_service; static gatt_attr_t dis_attrs[DIS_IDX_MAX] = { [DIS_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(UUID_DIS), [DIS_IDX_MANU_NUM_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_MANUFACTURER_NAME, GATT_CHRC_PROP_READ), [DIS_IDX_MANU_NUM_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_MANUFACTURER_NAME, GATT_PERM_READ), [DIS_IDX_MODEL_NUM_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_MODEL_NUMBER, GATT_CHRC_PROP_READ), [DIS_IDX_MODEL_NUM_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_MODEL_NUMBER, GATT_PERM_READ), [DIS_IDX_SER_NUM_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_SERIAL_NUMBER, GATT_CHRC_PROP_READ), [DIS_IDX_SER_NUM_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_SERIAL_NUMBER, GATT_PERM_READ), [DIS_IDX_HW_REV_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_HARDWARE_REVISION, GATT_CHRC_PROP_READ), [DIS_IDX_HW_REV_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_HARDWARE_REVISION, GATT_PERM_READ), [DIS_IDX_FW_REV_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_FIRMWARE_REVISION, GATT_CHRC_PROP_READ), [DIS_IDX_FW_REV_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_FIRMWARE_REVISION, GATT_PERM_READ), [DIS_IDX_SW_REV_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_SOFTWARE_REVISION, GATT_CHRC_PROP_READ), [DIS_IDX_SW_REV_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_SOFTWARE_REVISION, GATT_PERM_READ), [DIS_IDX_SYS_ID_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_SYSTEM_ID, GATT_CHRC_PROP_READ), [DIS_IDX_SYS_ID_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_SYSTEM_ID, GATT_PERM_READ), [DIS_IDX_REGU_LIST_CHAR] = GATT_CHAR_DEFINE(UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST, GATT_CHRC_PROP_READ), [DIS_IDX_REGU_LIST_VAL] = GATT_CHAR_VAL_DEFINE(UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST, GATT_PERM_READ), [DIS_IDX_PNP_ID_CHAR] = GATT_CHAR_DEFINE(UUID_DIS_PNP_ID, GATT_CHRC_PROP_READ), [DIS_IDX_PNP_ID_VAL] = GATT_CHAR_VAL_DEFINE(UUID_DIS_PNP_ID, GATT_PERM_READ), }; static inline void read_dis_info(evt_data_gatt_char_read_t *e, void *data, uint16_t len) { if (data == NULL || len == 0) { return ; } e->data = data; e->len = len; } static inline void read_pnp_id(evt_data_gatt_char_read_t *e, pnp_id_t *pnp_id) { static uint8_t data[7] = {0}; if (e && pnp_id) { data[0] = pnp_id->vendor_id_source; memcpy(&data[1], &pnp_id->vendor_id, 6); e->data = data; e->len = 7; } } static void event_char_read(ble_event_en event, void *event_data) { evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data; if (e->char_handle < g_dis.dis_svc_handle || e->char_handle >= g_dis.dis_svc_handle + DIS_IDX_MAX) { return; } uint16_t dis_char_idx = e->char_handle - g_dis.dis_svc_handle; switch (dis_char_idx) { case DIS_IDX_MANU_NUM_VAL: read_dis_info(e, g_dis.info->manufacturer_name, strlen(g_dis.info->manufacturer_name)); break; case DIS_IDX_MODEL_NUM_VAL: read_dis_info(e, g_dis.info->model_number, strlen(g_dis.info->model_number)); break; case DIS_IDX_SER_NUM_VAL: read_dis_info(e, g_dis.info->serial_number, strlen(g_dis.info->serial_number)); break; case DIS_IDX_HW_REV_VAL: read_dis_info(e, g_dis.info->hardware_revison, strlen(g_dis.info->hardware_revison)); break; case DIS_IDX_FW_REV_VAL: read_dis_info(e, g_dis.info->firmware_revision, strlen(g_dis.info->firmware_revision)); break; case DIS_IDX_SW_REV_VAL: read_dis_info(e, g_dis.info->software_revision, strlen(g_dis.info->software_revision)); break; case DIS_IDX_SYS_ID_VAL: read_dis_info(e, g_dis.info->system_id, g_dis.info->system_id ? sizeof(*g_dis.info->system_id) : 0); break; case DIS_IDX_REGU_LIST_VAL: read_dis_info(e, g_dis.info->regu_cert_data_list ? g_dis.info->regu_cert_data_list->list : NULL, g_dis.info->regu_cert_data_list ? g_dis.info->regu_cert_data_list->list_len : 0); break; case DIS_IDX_PNP_ID_VAL: { read_pnp_id(e, g_dis.info->pnp_id); } break; } if (e->char_handle == g_dis.manu_num_char_val_handle) { read_dis_info(e, g_dis.info->manufacturer_name, strlen(g_dis.info->manufacturer_name)); } else if (e->char_handle == g_dis.model_num_char_val_handle) { read_dis_info(e, g_dis.info->model_number, strlen(g_dis.info->model_number)); } else if (e->char_handle == g_dis.ser_num_char_val_handle) { read_dis_info(e, g_dis.info->serial_number, strlen(g_dis.info->serial_number)); } else if (e->char_handle == g_dis.hw_rev_char_val_handle) { read_dis_info(e, g_dis.info->hardware_revison, strlen(g_dis.info->hardware_revison)); } else if (e->char_handle == g_dis.fw_rev_char_val_handle) { read_dis_info(e, g_dis.info->firmware_revision, strlen(g_dis.info->firmware_revision)); } else if (e->char_handle == g_dis.sw_rev_char_val_handle) { read_dis_info(e, g_dis.info->software_revision, strlen(g_dis.info->software_revision)); } else if (e->char_handle == g_dis.sys_id_char_val_handle) { read_dis_info(e, g_dis.info->system_id, sizeof(*g_dis.info->system_id)); } else if (e->char_handle == g_dis.regu_list_char_val_handle) { read_dis_info(e, g_dis.info->regu_cert_data_list->list, g_dis.info->regu_cert_data_list->list_len); } else if (e->char_handle == g_dis.pnp_id_char_val_handle) { read_dis_info(e, g_dis.info->pnp_id, sizeof(*g_dis.info->pnp_id)); } } static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; if (e->connected == CONNECTED) { g_dis.conn_handle = e->conn_handle; } else { g_dis.conn_handle = 0xFFFF; } } static int dis_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_CHAR_READ: event_char_read(event, event_data); break; default: break; } return 0; } static ble_event_cb_t ble_cb = { .callback = dis_event_callback, }; dis_handle_t dis_init(dis_info_t *info) { int ret = 0; if (g_dis.info) { return 0; } memset(&g_dis, 0xFF, sizeof(g_dis)); g_dis.info = NULL; ret = ble_stack_event_register(&ble_cb); if (ret) { goto err; } ret = ble_stack_gatt_registe_service(&dis_service,dis_attrs, DIS_IDX_MAX); if (ret < 0) { goto err; } g_dis.dis_svc_handle = ret; #if 0 if (info->manufacturer_name) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_MANU_NUM_CHAR], 2); if (ret < 0) { goto err; } g_dis.manu_num_char_val_handle = ret + 1; } if (info->model_number) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_MODEL_NUM_CHAR], 2); if (ret < 0) { goto err; } g_dis.model_num_char_val_handle = ret + 1; } if (info->serial_number) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_SER_NUM_CHAR], 2); if (ret < 0) { goto err; } g_dis.ser_num_char_val_handle = ret + 1; } if (info->hardware_revison) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_HW_REV_CHAR], 2); if (ret < 0) { goto err; } g_dis.hw_rev_char_val_handle = ret + 1; } if (info->firmware_revision) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_FW_REV_CHAR], 2); if (ret < 0) { goto err; } g_dis.fw_rev_char_val_handle = ret + 1; } if (info->software_revision) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_SW_REV_CHAR], 2); if (ret < 0) { goto err; } g_dis.sw_rev_char_val_handle = ret + 1; } if (info->system_id) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_SYS_ID_CHAR], 2); if (ret < 0) { goto err; } g_dis.sys_id_char_val_handle = ret + 1; } if (info->regu_cert_data_list) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_REGU_LIST_CHAR], 2); if (ret < 0) { goto err; } g_dis.regu_list_char_val_handle = ret + 1; } if (info->pnp_id) { ret = ble_stack_gatt_registe_service(&bas_attrs[DIS_IDX_PNP_ID_CHAR], 2); if (ret < 0) { goto err; } g_dis.pnp_id_char_val_handle = ret + 1; } #endif g_dis.info = info; return &g_dis; err: //LOGE(TAG, "dis init err %d\n", ret); return NULL; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/dis.c
C
apache-2.0
10,045
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <string.h> #include <stdio.h> //#include <aos/osal_debug.h> #include <aos/ble.h> #include <yoc/hids.h> #define TAG "HIDS" typedef struct hids_info_t { uint16_t bcdHID; uint8_t countryCode; uint8_t flags; } hids_info_t; typedef struct hids_report_ref_t { uint8_t id; uint8_t type; } hids_report_ref_t; enum { HIDS_INPUT = 0x01, HIDS_OUTPUT = 0x02, HIDS_FEATURE = 0x03, }; enum { HIDS_REMOTE_WAKE = 0x01, HIDS_NORMALLY_CONNECTABLE = 0x02, }; static hids_info_t g_hids_info = { 0x0101, 0x00, HIDS_NORMALLY_CONNECTABLE | HIDS_REMOTE_WAKE, }; static hids_report_ref_t report_input_ref = { 0x00, HIDS_INPUT, }; static hids_report_ref_t report_output_ref = { 0x00, HIDS_OUTPUT, }; //static hids_report_ref_t report_feature_ref = { // 0x00, // HIDS_FEATURE, //}; typedef struct reportdata_array { uint8_t *map_array; uint16_t map_len; int8_t s_flag; } data_report_array; static data_report_array data_in_out[] = { {NULL, 0, -1}, //REPORT_MAP {NULL, 0, -1}, //REPORT_INPUT {NULL, 0, -1}, //REPORT_OUTPUT }; gatt_service hids_service; static uint8_t *get_data_map_data(uint8_t u_type); static uint16_t get_data_map_len(uint8_t u_type); typedef struct _hids_t { uint16_t conn_handle; uint16_t svc_handle; uint16_t input_ccc; uint16_t boot_input_ccc; uint8_t protocol_mode; } hids_t; hids_t g_hids = {0}; typedef struct _register_hids_event_ { int16_t idx; hids_event_cb cb; } register_hids_event ; register_hids_event hids_event_arr[HIDS_IDX_MAX] = {0}; //static struct bt_gatt_ccc_cfg_t ccc_data1[2] = {}; //static struct bt_gatt_ccc_cfg_t ccc_data2[2] = {}; gatt_attr_t hids_attrs[] = { GATT_PRIMARY_SERVICE_DEFINE(UUID_HIDS), /* REPORT MAP */ GATT_CHAR_DEFINE(UUID_HIDS_REPORT_MAP, GATT_CHRC_PROP_READ), GATT_CHAR_VAL_DEFINE(UUID_HIDS_REPORT_MAP, GATT_PERM_READ), /* REPORT INPUT */ GATT_CHAR_DEFINE(UUID_HIDS_REPORT, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_NOTIFY), GATT_CHAR_VAL_DEFINE(UUID_HIDS_REPORT, GATT_PERM_READ | GATT_PERM_READ_AUTHEN), GATT_CHAR_DESCRIPTOR_DEFINE(UUID_HIDS_REPORT_REF, GATT_PERM_READ), GATT_CHAR_CCC_DEFINE(), /* REPORT OUTPUT */ GATT_CHAR_DEFINE(UUID_HIDS_REPORT, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP), GATT_CHAR_VAL_DEFINE(UUID_HIDS_REPORT, GATT_PERM_READ | GATT_PERM_READ_AUTHEN | GATT_PERM_WRITE), GATT_CHAR_DESCRIPTOR_DEFINE(UUID_HIDS_REPORT_REF, GATT_PERM_READ), #if 0 /* REPORT FEATURE */ GATT_CHAR_DEFINE(UUID_HIDS_REPORT, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE), GATT_CHAR_VAL_DEFINE(UUID_HIDS_REPORT, GATT_PERM_READ | GATT_PERM_READ_ENCRYPT | GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPT), GATT_CHAR_DESCRIPTOR_DEFINE(UUID_HIDS_REPORT_REF, GATT_PERM_READ), #endif /* Boot Keyboard Input Report */ GATT_CHAR_DEFINE(UUID_HIDS_BOOT_KB_IN_REPORT, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_NOTIFY), GATT_CHAR_VAL_DEFINE(UUID_HIDS_BOOT_KB_IN_REPORT, GATT_PERM_READ | GATT_PERM_READ_AUTHEN | GATT_PERM_WRITE), GATT_CHAR_CCC_DEFINE(), /* Boot Keyboard Output Report */ GATT_CHAR_DEFINE(UUID_HIDS_BOOT_KB_OUT_REPORT, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP), GATT_CHAR_VAL_DEFINE(UUID_HIDS_BOOT_KB_OUT_REPORT, GATT_PERM_READ | GATT_PERM_READ_AUTHEN | GATT_PERM_WRITE), // /* HID Information */ GATT_CHAR_DEFINE(UUID_HIDS_INFO, GATT_CHRC_PROP_READ), GATT_CHAR_VAL_DEFINE(UUID_HIDS_INFO, GATT_PERM_READ), /* HID Control Point */ GATT_CHAR_DEFINE(UUID_HIDS_CTRL_POINT, GATT_CHRC_PROP_WRITE_WITHOUT_RESP), GATT_CHAR_VAL_DEFINE(UUID_HIDS_CTRL_POINT, GATT_PERM_WRITE), /* Protocol Mode *///low power Suspend mode ,0x00 Boot Protocol Mode 0x01 report protocol mode GATT_CHAR_DEFINE(UUID_HIDS_PROTOCOL_MODE, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE_WITHOUT_RESP), GATT_CHAR_VAL_DEFINE(UUID_HIDS_PROTOCOL_MODE, GATT_PERM_READ | GATT_PERM_WRITE), }; static void read_report(evt_data_gatt_char_read_t *e, void *data, uint16_t len) { e->data = data; e->len = len; } static void event_char_read(ble_event_en event, void *event_data) { evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data; if (g_hids.conn_handle == 0xFFFF || e->char_handle < g_hids.svc_handle || e->char_handle >= g_hids.svc_handle + HIDS_IDX_MAX) { return; } uint16_t hids_char_idx = e->char_handle - g_hids.svc_handle; switch (hids_char_idx) { case HIDS_IDX_REPORT_MAP_VAL: read_report(e, get_data_map_data(REPORT_MAP), get_data_map_len(REPORT_MAP)); break; case HIDS_IDX_REPORT_INPUT_VAL: read_report(e, get_data_map_data(REPORT_INPUT), get_data_map_len(REPORT_INPUT)); break; case HIDS_IDX_REPORT_INPUT_REF: read_report(e, &report_input_ref, sizeof(report_input_ref)); break; case HIDS_IDX_REPORT_OUTPUT_VAL: read_report(e, get_data_map_data(REPORT_OUTPUT), get_data_map_len(REPORT_OUTPUT)); break; case HIDS_IDX_REPORT_OUTPUT_REF: read_report(e, &report_output_ref, sizeof(report_output_ref)); break; case HIDS_IDX_INFO_VAL: read_report(e, &g_hids_info, sizeof(g_hids_info)); break; case HIDS_IDX_PROTOCOL_MODE_VAL: read_report(e, &g_hids.protocol_mode, 1); break; default: //LOGI(TAG, "unhandle event:%x\r\n\r\n", hids_char_idx); break; } } int init_hids_call_func(int32_t idx, hids_event_cb cb_event) { if (idx < 0 || idx >= HIDS_IDX_MAX) { return -1; } if (hids_event_arr[idx].cb != NULL) { hids_event_arr[idx].cb = cb_event; } return 0; } int execute_hids_call_func(int32_t idx, void *event_data) { if (idx < 0 || idx >= HIDS_IDX_MAX) { return -1; } if (hids_event_arr[idx].cb != NULL) { hids_event_arr[idx].cb(idx, event_data); } return 0; } static void event_char_write(ble_event_en event, void *event_data) { evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data; int ires = 0; if (g_hids.conn_handle == 0xFFFF || e->char_handle < g_hids.svc_handle || e->char_handle >= g_hids.svc_handle + HIDS_IDX_MAX) { return; } uint16_t hids_char_idx = e->char_handle - g_hids.svc_handle; switch (hids_char_idx) { case HIDS_IDX_REPORT_OUTPUT_VAL: ires = execute_hids_call_func(HIDS_IDX_REPORT_OUTPUT_VAL, e); break; case HIDS_IDX_BOOT_KB_INPUT_REPORT_VAL: ires = execute_hids_call_func(HIDS_IDX_BOOT_KB_INPUT_REPORT_VAL, e); break; case HIDS_IDX_BOOT_KB_OUTPUT_REPORT_VAL: ires = execute_hids_call_func(HIDS_IDX_BOOT_KB_OUTPUT_REPORT_VAL, e); break; case HIDS_IDX_CTRL_VAL: //LOGI(TAG, "control cmd %d, %s\n", e->data[0], e->data[0] == 0x00 ? " Suspend" : // "Exit Suspend"); ires = execute_hids_call_func(HIDS_IDX_CTRL_VAL, e); break; case HIDS_IDX_PROTOCOL_MODE_VAL: g_hids.protocol_mode = e->data[0]; break; default: break; } if (ires != 0) { //LOGI(TAG, "event_char_write execute err\r\n"); } } static void event_char_ccc_change(ble_event_en event, void *event_data) { evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data; if (g_hids.conn_handle == 0xFFFF || e->char_handle < g_hids.svc_handle || e->char_handle >= g_hids.svc_handle + HIDS_IDX_MAX) { return; } uint16_t hids_char_idx = e->char_handle - g_hids.svc_handle; switch (hids_char_idx) { case HIDS_IDX_REPORT_INPUT_CCC: g_hids.input_ccc = e->ccc_value; break; case HIDS_IDX_BOOT_KB_INPUT_REPORT_CCC: g_hids.boot_input_ccc = e->ccc_value; break; } } static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; if (e->connected == CONNECTED) { g_hids.conn_handle = e->conn_handle; } else { g_hids.conn_handle = 0xFFFF; } } static int hids_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GATT_CHAR_READ: event_char_read(event, event_data); break; case EVENT_GATT_CHAR_WRITE: event_char_write(event, event_data); break; case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_CHAR_CCC_CHANGE: event_char_ccc_change(event, event_data); break; default: break; } return 0; } static ble_event_cb_t ble_cb = { .callback = hids_event_callback, }; hids_handle_t hids_init(uint8_t mode) { int ret = 0; ret = ble_stack_event_register(&ble_cb); if (ret) { return NULL; } ret = ble_stack_gatt_registe_service(&hids_service,hids_attrs, BLE_ARRAY_NUM(hids_attrs)); if (ret < 0) { return NULL; } g_hids.conn_handle = 0xFFFF; g_hids.svc_handle = ret; g_hids.protocol_mode = mode; memset(hids_event_arr, 0x0, sizeof(hids_event_arr)); return &g_hids; } int hids_notify_send(hids_handle_t handle, uint8_t *key_code, uint16_t us_len) { hids_t *hids = handle; if (handle == NULL) { return -BLE_STACK_ERR_NULL; } if (hids->protocol_mode == HIDS_REPORT_PROTOCOL_MODE && hids->input_ccc == CCC_VALUE_NOTIFY) { ble_stack_gatt_notificate(hids->conn_handle, hids->svc_handle + HIDS_IDX_REPORT_INPUT_VAL, key_code, us_len); } return 0; } int hids_key_send(hids_handle_t handle, uint8_t *key_code, uint16_t us_len) { hids_t *hids = handle; if (handle == NULL) { return -BLE_STACK_ERR_NULL; } ble_stack_gatt_notificate(hids->conn_handle, hids->svc_handle + HIDS_IDX_REPORT_INPUT_VAL, key_code, us_len); return 0; } int set_data_map(uint8_t u_data[], uint16_t len, uint8_t u_type) { if (u_type >= REPORT_MAX) { return -1; } //data_in_out[u_type].map_array = (uint8_t *)malloc(sizeof(uint8_t) * len); //if (data_in_out[u_type].map_array == NULL) { // return -1; //} data_in_out[u_type].map_array = u_data; data_in_out[u_type].map_len = len; data_in_out[u_type].s_flag = 0; return 0; } static uint8_t *get_data_map_data(uint8_t u_type) { if (u_type >= REPORT_MAX) { return NULL; } if (data_in_out[u_type].s_flag == -1) { return NULL; } return (uint8_t *)data_in_out[u_type].map_array; } static uint16_t get_data_map_len(uint8_t u_type) { if (u_type >= REPORT_MAX) { return -1; } if ((data_in_out[u_type].s_flag == -1) || (data_in_out[u_type].map_len > 512)) { return -1; } return data_in_out[u_type].map_len; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/hids.c
C
apache-2.0
11,256
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <string.h> #include <stdio.h> //#include <aos/osal_debug.h> #include <aos/ble.h> #include <yoc/hrs.h> #define TAG "HRS" enum { HRS_IDX_SVC, HRS_IDX_MEA_CHAR, HRS_IDX_MEA_VAL, HRS_IDX_MEA_CCC, HRS_IDX_BODY_CHAR, HRS_IDX_BODY_VAL, HRS_IDX_CONTROL_CHAR, HRS_IDX_CONTROL_VAL, HRS_IDX_MAX, }; static slist_t hrs_list = {NULL}; gatt_service hrs_service; //static struct bt_gatt_ccc_cfg_t ccc_data[2] = {}; static gatt_attr_t hrs_attrs[HRS_IDX_MAX] = { [HRS_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(UUID_HRS), [HRS_IDX_MEA_CHAR] = GATT_CHAR_DEFINE(UUID_HRS_MEASUREMENT, GATT_CHRC_PROP_NOTIFY), [HRS_IDX_MEA_VAL] = GATT_CHAR_VAL_DEFINE(UUID_HRS_MEASUREMENT, GATT_PERM_NONE), [HRS_IDX_MEA_CCC] = GATT_CHAR_CCC_DEFINE(), [HRS_IDX_BODY_CHAR] = GATT_CHAR_DEFINE(UUID_HRS_BODY_SENSOR, GATT_CHRC_PROP_READ), [HRS_IDX_BODY_VAL] = GATT_CHAR_VAL_DEFINE(UUID_HRS_BODY_SENSOR, GATT_PERM_NONE), [HRS_IDX_CONTROL_CHAR] = GATT_CHAR_DEFINE(UUID_HRS_CONTROL_POINT, GATT_CHRC_PROP_WRITE), [HRS_IDX_CONTROL_VAL] = GATT_CHAR_VAL_DEFINE(UUID_HRS_CONTROL_POINT, GATT_PERM_NONE), }; static inline hrs_t *get_hrs(uint16_t hrs_svc_handle) { slist_t *tmp; hrs_t *node; slist_for_each_entry_safe(&hrs_list, tmp, node, hrs_t, next) { if (node->hrs_svc_handle == hrs_svc_handle) { return node; } } return NULL; } static void event_char_read(ble_event_en event, void *event_data) { evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data; hrs_t *hrs = get_hrs(e->char_handle - HRS_IDX_MEA_VAL); if (hrs == NULL) { return; } LOGD(TAG, "event_char_read conn handle %d char handle 0x%04x, len %d, offset %d", e->conn_handle, e->char_handle, e->len, e->offset); e->data = &hrs->hrs_mea_level; e->len = 1; } static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; slist_t *tmp; hrs_t *node; slist_for_each_entry_safe(&hrs_list, tmp, node, hrs_t, next) { if (e->connected == CONNECTED) { node->conn_handle = e->conn_handle; } else { node->conn_handle = 0xFFFF; } } } static void event_char_ccc_change(ble_event_en event, void *event_data) { evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data; hrs_t *hrs = get_hrs(e->char_handle - HRS_IDX_MEA_CCC); if (hrs == NULL) { return; } hrs->mea_ccc = e->ccc_value; } static int hrs_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_CHAR_READ: event_char_read(event, event_data); break; case EVENT_GATT_CHAR_CCC_CHANGE: event_char_ccc_change(event, event_data); break; default: break; } return 0; } static ble_event_cb_t ble_cb = { .callback = hrs_event_callback, }; hrs_handle_t hrs_init(hrs_t *hrs) { int ret = 0; if (hrs == NULL) { return NULL; } ret = ble_stack_event_register(&ble_cb); if (ret) { goto err; } ret = ble_stack_gatt_registe_service(&hrs_service,hrs_attrs, BLE_ARRAY_NUM(hrs_attrs)); if (ret < 0) { goto err; } hrs->conn_handle = 0xFFFF; hrs->hrs_svc_handle = ret; hrs->hrs_mea_level = 0xFF; hrs->mea_ccc = 0; slist_add(&hrs->next, &hrs_list); return hrs; err: return NULL; } int hrs_measure_level_update(hrs_handle_t handle, uint8_t *data, uint8_t length) { if (handle == NULL) { return -BLE_STACK_ERR_NULL; } hrs_t *hrs = handle; if (data[1] != hrs->hrs_mea_level) { hrs->hrs_mea_level = data[1]; if (hrs->conn_handle != 0xFFFF && hrs->mea_ccc == CCC_VALUE_NOTIFY) { LOGD(TAG, "data:%x", data[1]); return ble_stack_gatt_notificate(hrs->conn_handle, hrs->hrs_svc_handle + HRS_IDX_MEA_VAL, data, length); } } return 0; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/hrs.c
C
apache-2.0
4,362
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <string.h> #include <stdio.h> //#include <aos/osal_debug.h> #include <aos/ble.h> #include <yoc/ibeacons.h> uint8_t BEACON_TYPE[2] = {0X02, 0X15} ; //define by apple for all Proximity Beacons,Cant not change, union u { beacon_info init_becons; uint8_t data[25]; } uu; static uint8_t *ibeacon_Init(uint8_t _id[2], uint8_t _uuid[16], uint8_t _major[2], uint8_t _minor[2], uint8_t _measure_power) { int i; uu.init_becons.id[0] = _id[0]; uu.init_becons.id[1] = _id[1]; uu.init_becons.type[0] = BEACON_TYPE[0]; uu.init_becons.type[1] = BEACON_TYPE[1]; for (i = 0; i < 16; i++) { uu.init_becons.uuid[i] = _uuid[i]; } uu.init_becons.major[0] = _major[0]; uu.init_becons.major[1] = _major[1]; uu.init_becons.minor[0] = _minor[0]; uu.init_becons.minor[1] = _minor[1]; uu.init_becons.measure_power = _measure_power; return uu.data;//(uint8_t *)usdata; } int ibeacon_start(uint8_t _id[2], uint8_t _uuid[16], uint8_t _major[2], uint8_t _minor[2], uint8_t _measure_power, char *_sd) { int ret; ad_data_t sd[1] = {0}; ad_data_t ad[2] = {0}; uint8_t flag = AD_FLAG_GENERAL | AD_FLAG_NO_BREDR; ad[0].type = AD_DATA_TYPE_FLAGS; ad[0].data = (uint8_t *)&flag; ad[0].len = 1; ad[1].type = AD_DATA_TYPE_MANUFACTURER_DATA; ad[1].data = (uint8_t *)ibeacon_Init(_id, _uuid, _major, _minor, _measure_power); ad[1].len = sizeof(beacon_info); //SD DATA sd[0].type = AD_DATA_TYPE_NAME_COMPLETE; sd[0].data = (uint8_t *)_sd; sd[0].len = strlen(_sd); adv_param_t param = { ADV_NONCONN_IND, ad, sd, BLE_ARRAY_NUM(ad), BLE_ARRAY_NUM(sd), ADV_FAST_INT_MIN_2, ADV_FAST_INT_MIN_2, }; ret = ble_stack_adv_start(&param); return ret; } int ibeacon_stop(void) { int ret; ret = ble_stack_adv_stop(); return ret; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/ibeacons.c
C
apache-2.0
2,015
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef _BT_BAS_H_ #define _BT_BAS_H_ #include "aos/list.h" typedef struct _bas_t { uint16_t conn_handle; uint16_t bas_svc_handle; int16_t ccc; uint8_t battery_level; slist_t next; } bas_t; typedef bas_t *bas_handle_t; bas_handle_t bas_init(bas_t *bas); int bas_level_update(bas_handle_t handle, uint8_t level); #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/bas.h
C
apache-2.0
407
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef _BT_DIS_H_ #define _BT_DIS_H_ typedef void *dis_handle_t; typedef struct system_id_t { uint64_t manufacturer_id; /* manufacturer-defined identifier */ uint32_t organizationally_unique_id; /* Organizationally Unique Identifier (OUI). */ } system_id_t; typedef struct regulatory_cert_data_list_t { uint8_t *list; /* Pointer the byte array containing the encoded opaque structure based on IEEE 11073-20601 specification. */ uint8_t list_len; /* Length of the byte array. */ } regulatory_cert_data_list_t; enum { VEND_ID_SOURCE_BLUTTOOTH_SIG = 0x01, VEND_ID_SOURCE_USB = 0x02, }; typedef struct pnp_id_t { uint8_t vendor_id_source; /* Vendor ID Source, VEND_ID_SOURCE_BLUTTOOTH_SIG or VEND_ID_SOURCE_USB*/ uint16_t vendor_id; /* Vendor ID. */ uint16_t product_id; /* Product ID. */ uint16_t product_version; /* Product Version. */ } pnp_id_t; typedef struct dis_info_t { char *manufacturer_name; /* Manufacturer Name String */ char *model_number; /* Model Number String */ char *serial_number; /* Serial Number String */ char *hardware_revison; /* Hardware Revision String */ char *firmware_revision; /* Firmware Revision String */ char *software_revision; /* Software Revision String */ system_id_t *system_id; /* System ID */ regulatory_cert_data_list_t *regu_cert_data_list; /* IEEE 11073-20601 Regulatory Certification Data List */ pnp_id_t *pnp_id; /* PnP ID */ } dis_info_t; dis_handle_t dis_init(dis_info_t *info); #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/dis.h
C
apache-2.0
1,840
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef _BT_HIDS_H_ #define _BT_HIDS_H_ typedef void *hids_handle_t; hids_handle_t hids_init(uint8_t mode); int set_data_map(uint8_t u_data[], uint16_t len, uint8_t u_type); int hids_key_send(hids_handle_t handle, uint8_t *key_code, uint16_t us_len); int hids_notify_send(hids_handle_t handle, uint8_t *key_code, uint16_t us_len); typedef enum { HIDS_IDX_SVC, HIDS_IDX_REPORT_MAP_CHAR, HIDS_IDX_REPORT_MAP_VAL, HIDS_IDX_REPORT_INPUT_CHAR, HIDS_IDX_REPORT_INPUT_VAL, HIDS_IDX_REPORT_INPUT_REF, HIDS_IDX_REPORT_INPUT_CCC, HIDS_IDX_REPORT_OUTPUT_CHAR, HIDS_IDX_REPORT_OUTPUT_VAL, HIDS_IDX_REPORT_OUTPUT_REF, //HIDS_IDX_REPORT_FEATURE_CHAR, //HIDS_IDX_REPORT_FEATURE_VAL, //HIDS_IDX_REPORT_FEATURE_DES, HIDS_IDX_BOOT_KB_INPUT_REPORT_CHAR, HIDS_IDX_BOOT_KB_INPUT_REPORT_VAL, HIDS_IDX_BOOT_KB_INPUT_REPORT_CCC, HIDS_IDX_BOOT_KB_OUTPUT_REPORT_CHAR, HIDS_IDX_BOOT_KB_OUTPUT_REPORT_VAL, HIDS_IDX_INFO_CHAR, HIDS_IDX_INFO_VAL, HIDS_IDX_CTRL_CHAR, HIDS_IDX_CTRL_VAL, HIDS_IDX_PROTOCOL_MODE_CHAR, HIDS_IDX_PROTOCOL_MODE_VAL, HIDS_IDX_MAX, } hids_event_e; typedef void (*hids_event_cb)(hids_event_e event, void *event_data); //Event call back. int init_hids_call_func(int32_t idx, hids_event_cb cb_event); enum { REPORT_MAP = 0x00, REPORT_INPUT = 0x01, REPORT_OUTPUT = 0x02, //REPORT_FEATURE = 0x03, REPORT_MAX, }; enum { HIDS_BOOT_PROTOCOL_MODE = 0x00, HIDS_REPORT_PROTOCOL_MODE = 0x01, }; #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/hids.h
C
apache-2.0
1,595
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef _BT_HRS_H_ #define _BT_HRS_H_ #include "aos/list.h" typedef struct _hrs_t { uint16_t conn_handle; uint16_t hrs_svc_handle; int16_t mea_ccc; uint8_t hrs_mea_flag; uint8_t hrs_mea_level; slist_t next; } hrs_t; typedef hrs_t *hrs_handle_t; hrs_handle_t hrs_init(hrs_t *hrs); int hrs_measure_level_update(hrs_handle_t handle, uint8_t *data, uint8_t length); #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/hrs.h
C
apache-2.0
463
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef _BT_IBECONS_H_ #define _BT_IBECONS_H_ typedef struct _beacon_info { uint8_t id[2]; uint8_t type[2]; uint8_t uuid[16]; uint8_t major[2]; uint8_t minor[2]; uint8_t measure_power; } beacon_info; int ibeacon_start(uint8_t _id[2], uint8_t _uuid[16], uint8_t _major[2], uint8_t _minor[2], uint8_t _measure_power, char *_sd); int ibeacon_stop(void); #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/ibeacons.h
C
apache-2.0
475
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef _TAG_BLE_OTA_ #define _TAG_BLE_OTA_ #include <stdint.h> typedef enum { OTA_ST_IDLE = 0, OTA_ST_START, OTA_ST_REQUEST, OTA_ST_DL, OTA_ST_FLASH, OTA_ST_STOP, OTA_ST_COMPLETE, } ota_state_en; typedef void (*ota_event_callback_t)(ota_state_en ota_state); int ble_ota_init(ota_event_callback_t cb); void ble_ota_process(); #endif /* _TAG_BLE_OTA_ */ /******************************** END OF FILE *********************************/
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/ota_server.h
C
apache-2.0
534
#ifndef _UART_CLIENT_H #define _UART_CLIENT_H #include <aos/ble.h> #include <stdio.h> #include "yoc/uart_profile.h" typedef struct client_config { uint8_t conn_def_on; uint8_t auto_conn_mac_size; dev_addr_t *auto_conn_mac; dev_addr_t temp_conn_dev_set; conn_param_t *temp_conn_param; } client_config; typedef struct _uart_profile_handler { dev_addr_t peer_addr; uint8_t notify_enabled; uint16_t uart_handle; uint16_t uart_end_handle; uint16_t uart_char_handle; uint16_t uart_ccc_handle; } uart_profile_handler; typedef struct _uart_client { client_config client_conf; uart_profile_handler uart_profile; } uart_client; typedef struct _ble_uart_client_t { int16_t conn_handle; //uint16_t uart_svc_handle; uart_rx_data_cb uart_recv; ble_event_cb uart_event_callback; conn_param_t *conn_param; uint8_t conn_update_def_on: 1; uint8_t update_param_flag: 1; uint8_t mtu_exchanged: 1; uint16_t mtu; uart_client client_data; } ble_uart_client_t; uart_handle_t uart_client_init(ble_uart_client_t *service); int uart_client_scan_start(); dev_addr_t *found_dev_get(); int uart_client_conn(dev_addr_t *conn_mac, conn_param_t *conn_param); int uart_client_disconn(uart_handle_t handle); int uart_client_send(uart_handle_t handle, const char *data, int length, bt_uart_send_cb *cb); int uart_client_conn_param_update(uart_handle_t handle, conn_param_t *param); #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/uart_client.h
C
apache-2.0
1,463
#ifndef _UART_PROFILE_H #define _UART_PROFILE_H #include <aos/ble.h> #include <stdio.h> #define YOC_UART_SERVICE_UUID UUID128_DECLARE(0x7e,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93) #define YOC_UART_RX_UUID UUID128_DECLARE(0x7e,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9,0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x94) #define YOC_UART_TX_UUID UUID128_DECLARE(0x7e,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x95) #define RX_MAX_LEN 244 typedef struct _bt_uart_send_cb { void (*start)(int err, void *cb_data); void (*end)(int err, void *cb_data); } bt_uart_send_cb; //typedef void (*uart_service_init_cb)(int err); typedef int (*ble_event_cb)(ble_event_en, void *); typedef int (*uart_rx_data_cb)(const uint8_t *, int); typedef void *uart_handle_t; #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/uart_profile.h
C
apache-2.0
829
#ifndef _UART_SERVER_H #define _UART_SERVER_H #include <aos/ble.h> #include <stdio.h> #include "yoc/uart_profile.h" typedef struct _uart_server { uint8_t adv_def_on; adv_param_t *advParam; ccc_value_en tx_ccc_value; } uart_server; typedef struct _ble_uart_server_t { int16_t conn_handle; uint16_t uart_svc_handle; uart_rx_data_cb uart_recv; ble_event_cb uart_event_callback; conn_param_t *conn_param; uint8_t conn_update_def_on: 1; uint8_t update_param_flag: 1; uint8_t mtu_exchanged: 1; uint16_t mtu; uart_server server_data; } ble_uart_server_t; uart_handle_t uart_server_init(ble_uart_server_t *service); int uart_server_send(uart_handle_t handle, const char *data, int length, bt_uart_send_cb *cb); int uart_server_disconn(uart_handle_t handle); int uart_server_adv_control(uint8_t adv_on, adv_param_t *adv_param); int uart_server_conn_param_update(uart_handle_t handle, conn_param_t *param); #endif
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/include/yoc/uart_server.h
C
apache-2.0
969
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ //#include <aos/osal_debug.h> #include <aos/kernel.h> #include <aos/ble.h> #include <aos/gatt.h> //#include <yoc/partition.h> #include <yoc/ota_server.h> #define OTA_PACKET_SIZE (8192) #define OTA_PACKET_START (0xFF) #define OTA_PACKET_END (0xFE) #ifndef MIN # define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif enum ota_cmd { OTA_CMD_START = 0x01, OTA_CMD_STOP = 0x02, OTA_CMD_REQUEST = 0x03, OTA_CMD_COMPLETE = 0x04, }; typedef struct _ota_start_t { uint32_t cmd: 8; uint32_t firmware_size: 24; uint16_t packet_size; uint8_t timeout; } ota_start_t; struct ota_rx_t { uint8_t rx_buf[OTA_PACKET_SIZE]; uint16_t rx_len; uint16_t expect_len; uint16_t packet_id; uint16_t packet_crc; }; static struct ota_rx_t ota_rx = {0}; static struct ota_ctrl_t { ota_state_en st; uint32_t firmware_size; uint16_t packet_size; uint8_t timeout; uint16_t expect_packet_count; uint16_t recv_packet_count; uint8_t retry_count; aos_timer_t timer; ota_event_callback_t cb; } ota_ctrl; #define TAG "OTA" #define YOC_OTA_SERVICE_UUID \ UUID128_DECLARE(0x7e, 0x31, 0x35, 0xd4, 0x12, 0xf3, 0x11, 0xe9, 0xab, 0x14, 0xd6, 0x63, 0xbd, \ 0x87, 0x3d, 0x93) #define YOC_OTA_RX_UUID \ UUID128_DECLARE(0x7e, 0x31, 0x35, 0xd4, 0x12, 0xf3, 0x11, 0xe9, 0xab, 0x14, 0xd6, 0x63, 0xbd, \ 0x87, 0x3d, 0x94) #define YOC_OTA_TX_UUID \ UUID128_DECLARE(0x7e, 0x31, 0x35, 0xd4, 0x12, 0xf3, 0x11, 0xe9, 0xab, 0x14, 0xd6, 0x63, 0xbd, \ 0x87, 0x3d, 0x95) static int16_t g_yoc_ota_handle = -1; static int16_t g_conn_hanlde = -1; static int16_t g_tx_ccc_value = 0; static char rx_char_des[] = "YoC OTA RX"; static char tx_char_des[] = "YoC OTA TX"; enum { YOC_OTA_IDX_SVC, YOC_OTA_IDX_RX_CHAR, YOC_OTA_IDX_RX_VAL, YOC_OTA_IDX_RX_DES, YOC_OTA_IDX_TX_CHAR, YOC_OTA_IDX_TX_VAL, YOC_OTA_IDX_TX_CCC, YOC_OTA_IDX_TX_DES, YOC_OTA_IDX_MAX, }; //static struct bt_gatt_ccc_cfg_t ccc_data[2] = {}; static gatt_service uart_service; static gatt_attr_t uart_attrs[YOC_OTA_IDX_MAX] = { [YOC_OTA_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(YOC_OTA_SERVICE_UUID), [YOC_OTA_IDX_RX_CHAR] = GATT_CHAR_DEFINE(YOC_OTA_RX_UUID, GATT_CHRC_PROP_WRITE_WITHOUT_RESP), [YOC_OTA_IDX_RX_VAL] = GATT_CHAR_VAL_DEFINE(YOC_OTA_RX_UUID, GATT_PERM_READ | GATT_PERM_WRITE), [YOC_OTA_IDX_RX_DES] = GATT_CHAR_CUD_DEFINE(rx_char_des, GATT_PERM_READ), [YOC_OTA_IDX_TX_CHAR] = GATT_CHAR_DEFINE(YOC_OTA_TX_UUID, GATT_CHRC_PROP_NOTIFY | GATT_CHRC_PROP_READ), [YOC_OTA_IDX_TX_VAL] = GATT_CHAR_VAL_DEFINE(YOC_OTA_TX_UUID, GATT_PERM_READ), [YOC_OTA_IDX_TX_CCC] = GATT_CHAR_CCC_DEFINE(), [YOC_OTA_IDX_TX_DES] = GATT_CHAR_CUD_DEFINE(tx_char_des, GATT_PERM_READ), }; static partition_t ota_partition_handle = -1; static partition_info_t *ota_partition_info; extern uint16_t crc16(uint16_t sedd, const volatile void *p_data, uint32_t size); static void ota_status_change(int state) { ota_ctrl.st = state; if (ota_ctrl.cb) { ota_ctrl.cb(state); } LOGD(TAG, "%d->%d", ota_ctrl.st, state); } static void ota_reset() { ota_ctrl.st = 0; ota_ctrl.firmware_size = 0; ota_ctrl.packet_size = 0; ota_ctrl.timeout = 0; ota_ctrl.expect_packet_count = 0; ota_ctrl.recv_packet_count = 0; ota_ctrl.retry_count = 0; aos_timer_stop(&ota_ctrl.timer); memset(&ota_rx, 0, sizeof(ota_rx)); } static void ota_reset_rx() { memset(&ota_rx, 0, sizeof(ota_rx)); } static int ota_partition_erase() { if (partition_erase(ota_partition_handle, 0, (ota_partition_info->length + ota_partition_info->sector_size - 1) / ota_partition_info->sector_size) < 0) { LOGE(TAG, "erase addr:%x\n"); return -1; } LOGD(TAG, "erase length %d block %d succeed", ota_partition_info->length, (ota_partition_info->length + ota_partition_info->sector_size - 1) / ota_partition_info->sector_size); return 0; } static int ota_partition_write(uint8_t *buffer, int length, int offset) { if (partition_write(ota_partition_handle, offset + (ota_partition_info->sector_size << 1), (void *)buffer, length) >= 0) { LOGD(TAG, "write addr:%x length:%x\n", offset, length); return length; } LOGE(TAG, "write addr fail:%x length:%x\n", offset, length); return -1; } static inline uint32_t ota_partition_size() { return ota_partition_info->length - (ota_partition_info->sector_size << 1); } static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; if (e->connected == CONNECTED) { g_conn_hanlde = e->conn_handle; } else { g_conn_hanlde = -1; ota_reset(); ota_partition_erase(); ota_status_change(OTA_ST_IDLE); } } static inline int ota_recv_data(const uint8_t *data, uint16_t len) { if (!data || !len || !ota_rx.expect_len) { return -1; } uint16_t cp_size = MIN(ota_rx.expect_len - ota_rx.rx_len, len); memcpy(ota_rx.rx_buf + ota_rx.rx_len, data, cp_size); ota_rx.rx_len += cp_size; if (ota_rx.rx_len >= ota_rx.expect_len) { aos_timer_stop(&ota_ctrl.timer); } /* the last data */ if (ota_rx.rx_len >= ota_rx.expect_len) { uint16_t crc = crc16(0, ota_rx.rx_buf, ota_rx.rx_len); if (crc == ota_rx.packet_crc) { ota_status_change(OTA_ST_FLASH); } else { LOGE(TAG, "crc err %x %x", crc, ota_rx.packet_crc); ota_status_change(OTA_ST_REQUEST); } } if (ota_rx.rx_len > ota_rx.expect_len) { LOGE(TAG, "ota packet err len %d,cp size %d, rx len %d expect len %d", len, cp_size , ota_ctrl.expect_packet_count, ota_rx.rx_len, ota_rx.expect_len); ota_status_change(OTA_ST_REQUEST); } return 0; } void event_char_write(ble_event_en event, void *event_data) { evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data; int16_t hande_offset = 0; if (g_conn_hanlde != e->conn_handle) { return; } if (e->char_handle > g_yoc_ota_handle && e->char_handle < g_yoc_ota_handle + YOC_OTA_IDX_MAX) { hande_offset = e->char_handle - g_yoc_ota_handle; } else { return; } switch (hande_offset) { case YOC_OTA_IDX_RX_VAL: { switch (ota_ctrl.st) { case OTA_ST_IDLE: { /* ota start */ if (e->len == 9 && e->data[0] == OTA_PACKET_START && e->data[1] == OTA_CMD_START && e->data[e->len - 1] == OTA_PACKET_END) { uint32_t firmware_size = e->data[2] << 16 | e->data[3] << 8 | e->data[4]; uint16_t packet_size = e->data[5] << 8 | e->data[6]; uint8_t timeout = e->data[7]; if (firmware_size > ota_partition_size() || packet_size > OTA_PACKET_SIZE) { LOGE(TAG, "unsupport ota param %d %d", firmware_size, packet_size); return; } ota_ctrl.firmware_size = firmware_size; ota_ctrl.packet_size = packet_size; ota_ctrl.timeout = timeout; /* ota data formate */ /* |head | packet id | crc16 | firmware | tail | */ /* |2Bytes| 2bytes |2bytes |firmware size| 2Bytes| */ ota_ctrl.expect_packet_count = (firmware_size + packet_size - 1) / packet_size; LOGI(TAG, "ota start firmware size %d packet size %d timeout %d expect packet count %d", firmware_size, packet_size, timeout, ota_ctrl.expect_packet_count); ota_status_change(OTA_ST_START); } else { LOGE(TAG, "unkonw packet, drop %d", e->len); } break; } case OTA_ST_DL: { /* ota stop */ if (e->len == 3 && e->data[0] == OTA_PACKET_START && e->data[1] == OTA_CMD_STOP && e->data[2] == OTA_PACKET_END) { LOGI(TAG, "ota stop"); ota_reset(); ota_status_change(OTA_ST_STOP); } /* ota complete */ else if (e->len == 3 && e->data[0] == OTA_PACKET_START && e->data[1] == OTA_CMD_COMPLETE && e->data[2] == OTA_PACKET_END) { LOGI(TAG, "ota complelte"); ota_status_change(OTA_ST_COMPLETE); } /* ota data */ else if (e->len > 6 && e->data[0] == OTA_PACKET_START && e->data[1] == OTA_PACKET_END && ota_rx.expect_len == 0) { uint16_t packet_id = e->data[2] << 8 | e->data[3]; uint16_t packet_crc = e->data[4] << 8 | e->data[5]; if (packet_id >= ota_ctrl.expect_packet_count) { LOGE(TAG, "packet id overflow, drop %d\n", packet_id); return; } if (packet_id == ota_ctrl.expect_packet_count - 1) { ota_rx.expect_len = ota_ctrl.firmware_size % ota_ctrl.packet_size; } else { ota_rx.expect_len = ota_ctrl.packet_size; } ota_rx.packet_id = packet_id; ota_rx.packet_crc = packet_crc; ota_recv_data(e->data + 6, e->len - 6); } else if (ota_rx.expect_len) { ota_recv_data(e->data, e->len); } break; } default: LOGE(TAG, "invaild st %d\n", ota_ctrl.st); break; } } break; } e->len = 0; return; } void event_char_read(ble_event_en event, void *event_data) { evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data; int16_t hande_offset = 0; if (g_conn_hanlde == e->conn_handle) { if (e->char_handle > g_yoc_ota_handle) { hande_offset = e->char_handle - g_yoc_ota_handle; } else { return; } switch (hande_offset) { case YOC_OTA_IDX_RX_VAL: memcpy(e->data, ota_rx.rx_buf, MIN(e->len, sizeof(ota_rx.rx_buf))); e->len = MIN(e->len, sizeof(ota_rx.rx_buf)); return; case YOC_OTA_IDX_RX_DES: memcpy(e->data, rx_char_des, MIN(e->len, strlen(rx_char_des))); e->len = MIN(e->len, strlen(rx_char_des)); return; case YOC_OTA_IDX_TX_DES: memcpy(e->data, tx_char_des, MIN(e->len, strlen(tx_char_des))); e->len = MIN(e->len, strlen(tx_char_des)); return; } } e->len = 0; return; } void event_char_ccc_change(ble_event_en event, void *event_data) { evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data; if (e->char_handle != g_yoc_ota_handle + YOC_OTA_IDX_TX_CCC) { return; } g_tx_ccc_value = e->ccc_value; LOGD(TAG, "ccc %d %d\n", e->char_handle, e->ccc_value); } static void mtu_exchange(ble_event_en event, void *event_data) { evt_data_gatt_mtu_exchange_t *e = (evt_data_gatt_mtu_exchange_t *)event_data; if (e->err == 0) { LOGD(TAG, "mtu get %d", ble_stack_gatt_mtu_get(e->conn_handle)); } else { LOGE(TAG, "mtu exchange fail, %d", e->err); } } static int event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_CHAR_READ: event_char_read(event, event_data); break; case EVENT_GATT_CHAR_WRITE: event_char_write(event, event_data); break; case EVENT_GATT_CHAR_CCC_CHANGE: event_char_ccc_change(event, event_data); break; case EVENT_GATT_MTU_EXCHANGE: mtu_exchange(event, event_data); break; default: break; } return 0; } static ble_event_cb_t ble_ota_cb = { .callback = event_callback, }; static inline int ota_request(uint32_t offset) { LOGI(TAG, "request %d", offset); ota_reset_rx(); aos_timer_change(&ota_ctrl.timer, ota_ctrl.timeout * 1000); aos_timer_start(&ota_ctrl.timer); static uint8_t send_buf[6] = {0xff, 0x03, 0x00, 0x00, 0x00, 0xfe}; send_buf[2] = offset >> 16 & 0xFF; send_buf[3] = offset >> 8 & 0xFF; send_buf[4] = offset >> 0 & 0xFF; return ble_stack_gatt_notificate(g_conn_hanlde, g_yoc_ota_handle + YOC_OTA_IDX_TX_VAL, send_buf, sizeof(send_buf)); } void ble_ota_process() { if (g_conn_hanlde == -1) { return; } switch (ota_ctrl.st) { case OTA_ST_START: { /* ota start response */ if (g_tx_ccc_value != CCC_VALUE_NOTIFY) { aos_msleep(10); ota_status_change(OTA_ST_START); } else { conn_param_t param = { 0x06, 0x06, 0, 100, }; ble_stack_connect_param_update(g_conn_hanlde, &param); uint8_t send_buf[4] = {0xff, 0x01, 0x01, 0xfe}; ble_stack_gatt_notificate(g_conn_hanlde, g_yoc_ota_handle + YOC_OTA_IDX_TX_VAL, send_buf, sizeof(send_buf)); ota_status_change(OTA_ST_REQUEST); } } break; case OTA_ST_REQUEST: { uint32_t offset; offset = ota_ctrl.packet_size * ota_ctrl.recv_packet_count; ota_ctrl.retry_count++; if (ota_ctrl.retry_count > 10) { LOGE(TAG, "out of max try count %d", ota_ctrl.retry_count); ota_reset(); ota_status_change(OTA_ST_IDLE); ble_stack_disconnect(g_conn_hanlde); return; } ota_request(offset); ota_status_change(OTA_ST_DL); } break; case OTA_ST_FLASH: { ota_ctrl.retry_count = 0; ota_partition_write(ota_rx.rx_buf, ota_rx.rx_len, ota_ctrl.recv_packet_count * ota_ctrl.packet_size); ota_ctrl.recv_packet_count++; if (ota_ctrl.recv_packet_count < ota_ctrl.expect_packet_count) { ota_status_change(OTA_ST_REQUEST); } else { LOGI(TAG, "all packet recv, %d", ota_ctrl.recv_packet_count); ota_status_change(OTA_ST_COMPLETE); } } break; case OTA_ST_STOP: { LOGI(TAG, "ota stop"); /* may disconnect */ ota_status_change(OTA_ST_IDLE); } break; case OTA_ST_COMPLETE: { LOGI(TAG, "ota reboot"); /* may disconnect */ /* ota start response */ uint8_t send_buf[4] = {0xff, 0x04, 0x00, 0xfe}; ble_stack_gatt_notificate(g_conn_hanlde, g_yoc_ota_handle + YOC_OTA_IDX_TX_VAL, send_buf, sizeof(send_buf)); extern void mdelay(uint32_t ms); mdelay(100); aos_reboot(); } break; default: break; } } static void ota_timeout(void *arg1, void *arg2) { ota_reset_rx(); ota_status_change(OTA_ST_REQUEST); LOGW(TAG, "timeout"); } int ble_ota_init(ota_event_callback_t cb) { int ret; init_param_t init = { .dev_name = NULL, .dev_addr = NULL, .conn_num_max = 1, }; ble_stack_init(&init); ble_stack_event_register(&ble_ota_cb); ret = ble_stack_gatt_registe_service(&uart_service, uart_attrs, BLE_ARRAY_NUM(uart_attrs)); if (ret < 0) { return 0; } g_yoc_ota_handle = ret; if (ota_partition_handle < 0) { ota_partition_handle = partition_open("misc"); if (ota_partition_handle < 0) { LOGD(TAG, "ota partition open fail %d", ret); } ota_partition_info = hal_flash_get_info(ota_partition_handle); } aos_timer_new_ext(&ota_ctrl.timer, ota_timeout, NULL, 1000, 0, 0); ota_reset(); ota_partition_erase(); ota_ctrl.cb = cb; return 0; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/ota_server.c
C
apache-2.0
17,204
#include <stdio.h> #include <bt_errno.h> #include <ble_os.h> //#include <aos/osal_debug.h> #include <aos/kernel.h> #include <aos/ble.h> //#include <aos/aos.h> #include "yoc/uart_client.h" #define UUID_COMPARE_LENGTH 10 #define MAX_DEV_SURVIVE_TIME 10000 //ms enum { DISC_IDLE = 0, DISC_SRV, DISC_CHAR, DISC_DES, }; typedef struct _report_dev { dev_addr_t addr; long long time_found; } report_dev; typedef struct { uint8_t front; uint8_t rear; uint8_t length; report_dev dev[10]; } dev_data_queue; typedef struct _bt_uuid { uint8_t type; } bt_uuid; struct bt_uuid_128 { bt_uuid uuid; uint16_t val[16]; }; static ble_uart_client_t *g_uart_dev = NULL; static dev_data_queue g_dev_list; static client_config *g_cli_config = NULL; static uint8_t g_disconn_flag = 0; static dev_addr_t g_conn_last; static uint8_t g_conn_same_flag = 0; static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; ble_uart_client_t *node = g_uart_dev; if (!node) { return; } if (e->connected == CONNECTED) { ble_stack_gatt_mtu_exchange(e->conn_handle); node->conn_handle = e->conn_handle; connect_info_t info = {0}; ble_stack_connect_info_get(e->conn_handle, &info); if (!memcmp(&info.peer_addr, &g_conn_last, sizeof(dev_addr_t))) { g_conn_same_flag = 1; } else { memcpy(&g_conn_last, &info.peer_addr, sizeof(dev_addr_t)); } } else { node->conn_handle = -1; } node->uart_event_callback(event, event_data); } static void mtu_exchange(ble_event_en event, void *event_data) { evt_data_gatt_mtu_exchange_t *e = (evt_data_gatt_mtu_exchange_t *)event_data; ble_uart_client_t *node = g_uart_dev; if (!node) { return; } if (e->err == 0) { if (node->conn_handle == e->conn_handle) { node->mtu_exchanged = 1; node->mtu = ble_stack_gatt_mtu_get(node->conn_handle); if (!g_conn_same_flag) { ble_stack_gatt_discovery_primary(node->conn_handle, YOC_UART_SERVICE_UUID, 0x0001, 0xFFFF); } else { uint8_t ccc_enable = CCC_VALUE_NOTIFY; int ret = ble_stack_gatt_write_response(e->conn_handle, node->client_data.uart_profile.uart_ccc_handle, &ccc_enable, sizeof(ccc_enable), 0); if (ret < 0) { return; } node->client_data.uart_profile.notify_enabled = 1; if ((node->update_param_flag || node->conn_update_def_on) && node->conn_param != NULL) { ble_stack_connect_param_update(node->conn_handle, (conn_param_t *)node->conn_param); } } } node->uart_event_callback(event, event_data); } } int find_uart_uuid_by_ad(uint8_t *data, uint16_t len) { uint8_t *pdata = data; ad_data_t ad = {0}; uint8_t uuid_temp[16] = {0x7e, 0x31, 0x35, 0xd4, 0x12, 0xf3, 0x11, 0xe9, 0xab, 0x14, 0xd6, 0x63, 0xbd, 0x87, 0x3d, 0x93}; while (len) { if (pdata[0] == 0) { return -1; } if (len < pdata[0] + 1) { return -1; }; ad.len = pdata[0] - 1; ad.type = pdata[1]; ad.data = &pdata[2]; if (ad.type == AD_DATA_TYPE_UUID128_ALL && ad.len == 16) { if (!memcmp(ad.data, uuid_temp, 10)) { return 0; } } len -= (pdata[0] + 1); pdata += (pdata[0] + 1); } return -1; } static bool is_dev_data_queue_empty(dev_data_queue *queue) { return queue->front == queue->rear; } static bool is_dev_data_queue_full(dev_data_queue *queue) { if ((queue->rear + 1) % 10 == queue->front) { return true; } else { return false; } } static report_dev *get_dev_data(dev_data_queue *queue) { if (is_dev_data_queue_empty(queue)) { return NULL; } else { report_dev *data = &queue->dev[queue->front]; queue->front = (queue->front + 1) % 10; return data; } } static int put_dev_data(dev_data_queue *queue, dev_addr_t *dev) { if (!queue || !dev) { return -1; } if (is_dev_data_queue_full(queue)) { return -1; } for (int i = queue->front; i < queue->rear ; i++) { if (!memcmp(&queue->dev[i].addr, dev, sizeof(dev_addr_t))) { return 0; } } memcpy(&queue->dev[queue->rear].addr, dev, sizeof(dev_addr_t)); queue->dev[queue->rear].time_found = aos_now_ms(); queue->rear = (queue->rear + 1) % 10; return 0; } dev_addr_t *found_dev_get() { report_dev *dev = NULL; long long time_now = 0; long long survive_time = 0; do { dev = get_dev_data(&g_dev_list); if (dev) { time_now = aos_now_ms(); survive_time = time_now - dev->time_found; } } while (dev && survive_time > MAX_DEV_SURVIVE_TIME); if (!dev) { return NULL; } else { return &dev->addr; } } static void device_find(ble_event_en event, void *event_data) { int ret = -1; int uuid_peer = -1; evt_data_gap_dev_find_t ee; evt_data_gap_dev_find_t *e; uint8_t find_dev = 0; memcpy(&ee, event_data, sizeof(evt_data_gap_dev_find_t));//// e = &ee; conn_param_t param = { 0x06, //interval min 7.5ms 0x06, //interval max 7.5ms 0, 100, //supervision timeout 1s }; if (!g_cli_config) { return; } if (e->adv_type != ADV_IND) { return; } if (e->adv_len > 31) { return; } uuid_peer = find_uart_uuid_by_ad(e->adv_data, e->adv_len); if (uuid_peer < 0) { return; } put_dev_data(&g_dev_list, &e->dev_addr); if (g_disconn_flag) { return; } if (!g_cli_config->conn_def_on) { if (!memcmp(&g_cli_config->temp_conn_dev_set, &e->dev_addr, sizeof(g_cli_config->temp_conn_dev_set))) { find_dev = 1; } } else { if (g_cli_config->auto_conn_mac_size > 0) { for (int i = 0; i < g_cli_config->auto_conn_mac_size; i++) { if (!memcmp((uint8_t *)&g_cli_config->auto_conn_mac[i], (uint8_t *)&e->dev_addr, sizeof(dev_addr_t))) { find_dev = 1; break; } } } else if (!uuid_peer) { find_dev = 1; } } if (find_dev) { ble_stack_scan_stop(); ret = ble_stack_connect(&e->dev_addr, &param, 0); if (ret < 0) { uart_client_scan_start(); return; } } } static uint8_t UUID_EQUAL_LEN(uuid_t *uuid1, uuid_t *uuid2, uint8_t comp_len) { if (UUID_TYPE(uuid1) != UUID_TYPE(uuid2)) { return false; } comp_len = comp_len < UUID_LEN(uuid1) ? comp_len : UUID_LEN(uuid1); return (0 == memcmp(&((struct bt_uuid_128 *)uuid1)->val, &((struct bt_uuid_128 *)uuid2)->val, comp_len)); } static void service_discovery(ble_event_en event, void *event_data) { int ret; static uint8_t discovery_state = 0; ble_uart_client_t *uart = g_uart_dev; if (!uart) { return; } if (event == EVENT_GATT_DISCOVERY_COMPLETE) { evt_data_gatt_discovery_complete_t *e = event_data; if (discovery_state == DISC_SRV) { ble_stack_gatt_discovery_char(e->conn_handle, YOC_UART_RX_UUID, uart->client_data.uart_profile.uart_handle + 1, uart->client_data.uart_profile.uart_end_handle); } else if (discovery_state == DISC_CHAR) { ble_stack_gatt_discovery_descriptor(e->conn_handle, UUID_GATT_CCC, uart->client_data.uart_profile.uart_char_handle + 1, 0xffff); } else if (discovery_state == DISC_DES) { uint8_t ccc_enable = CCC_VALUE_NOTIFY; ret = ble_stack_gatt_write_response(e->conn_handle, uart->client_data.uart_profile.uart_ccc_handle, &ccc_enable, sizeof(ccc_enable), 0); if (ret < 0) { return; } uart->client_data.uart_profile.notify_enabled = 1; if ((uart->update_param_flag || uart->conn_update_def_on) && uart->conn_param != NULL) { ble_stack_connect_param_update(uart->conn_handle, (conn_param_t *)uart->conn_param); } return; } } if (event == EVENT_GATT_DISCOVERY_SVC) { evt_data_gatt_discovery_svc_t *e = event_data; discovery_state = DISC_SRV; if (UUID_EQUAL_LEN(&e->uuid, YOC_UART_SERVICE_UUID, UUID_COMPARE_LENGTH)) { uart->client_data.uart_profile.uart_handle = e->start_handle; uart->client_data.uart_profile.uart_end_handle = e->end_handle; } } if (event == EVENT_GATT_DISCOVERY_CHAR) { evt_data_gatt_discovery_char_t *e = event_data; uart->client_data.uart_profile.uart_char_handle = e->val_handle; discovery_state = DISC_CHAR; } if (event == EVENT_GATT_DISCOVERY_CHAR_DES) { evt_data_gatt_discovery_char_des_t *e = event_data; uart->client_data.uart_profile.uart_ccc_handle = e->attr_handle; discovery_state = DISC_DES; } } static void event_notify(ble_event_en event, void *event_data) { evt_data_gatt_notify_t *e = (evt_data_gatt_notify_t *)event_data; ble_uart_client_t *uart = g_uart_dev; if (!uart) { return; } if (uart->conn_handle == e->conn_handle) { e->len = e->len < RX_MAX_LEN ? e->len : RX_MAX_LEN; uart->uart_recv(e->data, e->len); } } static int uart_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_MTU_EXCHANGE: mtu_exchange(event, event_data); break; case EVENT_GAP_DEV_FIND: device_find(event, event_data); break; case EVENT_GATT_DISCOVERY_SVC: case EVENT_GATT_DISCOVERY_CHAR: case EVENT_GATT_DISCOVERY_CHAR_DES: case EVENT_GATT_DISCOVERY_COMPLETE: service_discovery(event, event_data); break; case EVENT_GATT_CHAR_CCC_CHANGE: { break; } case EVENT_GATT_NOTIFY: { event_notify(event, event_data); break; } default: break; } return 0; } int uart_client_scan_start() { int ret; scan_param_t param = { SCAN_PASSIVE, SCAN_FILTER_DUP_ENABLE, SCAN_FAST_INTERVAL, SCAN_FAST_WINDOW, }; ret = ble_stack_scan_start(&param); if (ret) { return ret; } return 0; } static ble_event_cb_t ble_cb = { .callback = uart_event_callback, }; int uart_client_send(uart_handle_t handle, const char *data, int length, bt_uart_send_cb *cb) { uint32_t count = length; int ret = 0; uint16_t wait_timer = 0; ble_uart_client_t *uart = handle; if (data == NULL || length <= 0 || !uart || uart->conn_handle < 0 || !uart->client_data.uart_profile.notify_enabled) { return -1; } if (cb != NULL && cb->start != NULL) { cb->start(0, NULL); } while (count) { uint16_t send_count = (uart->mtu - 3) < count ? (uart->mtu - 3) : count; ret = ble_stack_gatt_write_no_response(uart->conn_handle, uart->client_data.uart_profile.uart_handle + 2, (uint8_t *)data, send_count, 0); if (ret == -ENOMEM) { wait_timer++; if (wait_timer >= 500) { return -1; } aos_msleep(1); continue; } if (ret) { if (cb != NULL && cb->end != NULL) { cb->end(ret, NULL); } return ret; } data += send_count; count -= send_count; } if (cb != NULL && cb->end != NULL) { cb->end(0, NULL); } return 0; } int uart_client_conn(dev_addr_t *conn_mac, conn_param_t *conn_param) { if (!g_cli_config) { return -1; } memcpy(g_cli_config->temp_conn_dev_set.val, conn_mac->val, sizeof(g_cli_config->temp_conn_dev_set.val)); g_cli_config->temp_conn_dev_set.type = conn_mac->type; if (conn_param) { g_cli_config->temp_conn_param = conn_param; } g_disconn_flag = 0; return 0; } int uart_client_disconn(uart_handle_t handle) { ble_uart_client_t *uart = handle; if (!uart) { return -1; } if (ble_stack_disconnect(uart->conn_handle)) { return -1; } uart->client_data.client_conf.conn_def_on = 0; g_disconn_flag = 1; return 0; } uart_handle_t uart_client_init(ble_uart_client_t *service) { int ret = 0; if (service == NULL) { return NULL; } ret = ble_stack_event_register(&ble_cb); if (ret) { return NULL; } service->conn_handle = -1; g_cli_config = &service->client_data.client_conf; g_uart_dev = service; g_dev_list.front = 0; g_dev_list.rear = 0; g_dev_list.length = 10; return service; } int uart_client_conn_param_update(uart_handle_t handle, conn_param_t *param) { ble_uart_client_t *uart = (ble_uart_client_t *)handle; if (!uart) { return -1; } uart->conn_param->interval_min = param->interval_min; uart->conn_param->interval_max = param->interval_max; uart->conn_param->latency = param->latency; uart->conn_param->timeout = param->timeout; if (uart->conn_handle < 0) { uart->update_param_flag = 1; } else { return ble_stack_connect_param_update(uart->conn_handle, param); } return 0; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/uart_client.c
C
apache-2.0
13,864
#include <aos/kernel.h> //#include <aos/osal_debug.h> #include <aos/ble.h> #include <bt_errno.h> #include "yoc/uart_server.h" enum { YOC_UART_IDX_SVC, YOC_UART_IDX_RX_CHAR, YOC_UART_IDX_RX_VAL, YOC_UART_IDX_RX_DES, YOC_UART_IDX_TX_CHAR, YOC_UART_IDX_TX_VAL, YOC_UART_IDX_TX_CCC, YOC_UART_IDX_TX_DES, YOC_UART_IDX_MAX, }; //static struct bt_gatt_ccc_cfg_t ccc_data[2] = {}; static gatt_service g_uart_profile; extern uint8_t llState; static ble_uart_server_t *g_uart_dev = NULL; static char rx_char_des[] = "YoC UART RX"; static char tx_char_des[] = "YoC UART TX"; gatt_attr_t uart_attrs[YOC_UART_IDX_MAX] = { [YOC_UART_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(YOC_UART_SERVICE_UUID), [YOC_UART_IDX_RX_CHAR] = GATT_CHAR_DEFINE(YOC_UART_RX_UUID, GATT_CHRC_PROP_WRITE), [YOC_UART_IDX_RX_VAL] = GATT_CHAR_VAL_DEFINE(YOC_UART_RX_UUID, GATT_PERM_READ | GATT_PERM_WRITE), [YOC_UART_IDX_RX_DES] = GATT_CHAR_CUD_DEFINE(rx_char_des, GATT_PERM_READ), [YOC_UART_IDX_TX_CHAR] = GATT_CHAR_DEFINE(YOC_UART_TX_UUID, GATT_CHRC_PROP_NOTIFY | GATT_CHRC_PROP_READ), [YOC_UART_IDX_TX_VAL] = GATT_CHAR_VAL_DEFINE(YOC_UART_TX_UUID, GATT_PERM_READ), [YOC_UART_IDX_TX_CCC] = GATT_CHAR_CCC_DEFINE(), [YOC_UART_IDX_TX_DES] = GATT_CHAR_CUD_DEFINE(tx_char_des, GATT_PERM_READ), }; static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; ble_uart_server_t *node = g_uart_dev; if (!node) { return; } if (e->connected == CONNECTED) { node->conn_handle = e->conn_handle; } else { node->conn_handle = -1; } node->uart_event_callback(event, event_data); } static void mtu_exchange(ble_event_en event, void *event_data) { evt_data_gatt_mtu_exchange_t *e = (evt_data_gatt_mtu_exchange_t *)event_data; ble_uart_server_t *node = g_uart_dev; if (!node) { return; } if (e->err == 0) { if (node->conn_handle == e->conn_handle) { node->mtu_exchanged = 1; node->mtu = ble_stack_gatt_mtu_get(node->conn_handle); } conn_param_t param = { 0x08, //interval min 20ms 0x08, //interval max 20ms 0, 100, //supervision timeout 1s }; ble_stack_connect_param_update(e->conn_handle, &param); node->uart_event_callback(event, event_data); } } static void event_char_ccc_change(ble_event_en event, void *event_data) { evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data; ble_uart_server_t *uart = g_uart_dev; if (!uart) { return; } uart->server_data.tx_ccc_value = e->ccc_value; if ((uart->update_param_flag || uart->conn_update_def_on) && uart->conn_param != NULL) { ble_stack_connect_param_update(uart->conn_handle, (conn_param_t *)uart->conn_param); } } static void event_char_write(ble_event_en event, void *event_data) { evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data; ble_uart_server_t *uart = g_uart_dev; if (!uart) { return; } e->len = e->len < RX_MAX_LEN ? e->len : RX_MAX_LEN; uart->uart_recv(e->data, e->len); e->len = 0; return; } int uart_server_disconn(uart_handle_t handle) { ble_uart_server_t *uart = (ble_uart_server_t *)handle; if (!uart) { return -1; } if (ble_stack_disconnect(uart->conn_handle)) { return -1; } return 0; } static int uart_event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GATT_MTU_EXCHANGE: mtu_exchange(event, event_data); break; case EVENT_GATT_CHAR_CCC_CHANGE: event_char_ccc_change(event, event_data); break; case EVENT_GATT_CHAR_WRITE: event_char_write(event, event_data); break; default: break; } return 0; } static ble_event_cb_t ble_cb = { .callback = uart_event_callback, }; int uart_server_send(uart_handle_t handle, const char *data, int length, bt_uart_send_cb *cb) { uint32_t count = length; uint16_t wait_timer = 0; int ret = 0; ble_uart_server_t *uart = (ble_uart_server_t *)handle; if (!data || !length || !uart || uart->conn_handle < 0 || uart->server_data.tx_ccc_value != CCC_VALUE_NOTIFY) { return -1; } if (cb != NULL && cb->start != NULL) { cb->start(0, NULL); } while (count) { uint16_t send_count = (uart->mtu - 3) < count ? (uart->mtu - 3) : count; ret = ble_stack_gatt_notificate(uart->conn_handle, uart->uart_svc_handle + YOC_UART_IDX_TX_VAL, (uint8_t *)data, send_count); if (ret == -ENOMEM) { wait_timer++; if (wait_timer >= 100) { cb->end(-1, NULL); return -1; } aos_msleep(1); continue; } if (ret) { if (cb != NULL && cb->end != NULL) { cb->end(ret, NULL); } return ret; } data += send_count; count -= send_count; } if (cb != NULL && cb->end != NULL) { cb->end(0, NULL); } return 0; } uart_handle_t uart_server_init(ble_uart_server_t *service) { int ret = 0; int g_yoc_uart_handle = -1; if (service == NULL) { return NULL; } ret = ble_stack_event_register(&ble_cb); if (ret) { return NULL; } g_yoc_uart_handle = ble_stack_gatt_registe_service(&g_uart_profile, uart_attrs, BLE_ARRAY_NUM(uart_attrs)); if (g_yoc_uart_handle < 0) { return NULL; } service->uart_svc_handle = g_yoc_uart_handle; service->conn_handle = -1; g_uart_dev = service; return service; } int uart_server_adv_control(uint8_t adv_on, adv_param_t *adv_param) { int ret = 0; ble_stack_adv_stop(); if (adv_on) { if (adv_param == NULL) { return -1; } else { ret = ble_stack_adv_start(adv_param); if (ret) { return ret; } } } return 0; } int uart_server_conn_param_update(uart_handle_t handle, conn_param_t *param) { ble_uart_server_t *uart = (ble_uart_server_t *)handle; if (!uart) { return -1; } uart->conn_param->interval_min = param->interval_min; uart->conn_param->interval_max = param->interval_max; uart->conn_param->latency = param->latency; uart->conn_param->timeout = param->timeout; if (uart->conn_handle < 0) { uart->update_param_flag = 1; } else { return ble_stack_connect_param_update(uart->conn_handle, param); } return 0; }
YifuLiu/AliOS-Things
components/ble_host/ble_profiles/uart_server.c
C
apache-2.0
6,961
/* * 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 <misc/byteorder.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/conn.h> #include <tinycrypt/constants.h> #include <tinycrypt/hmac_prng.h> #include <tinycrypt/aes.h> #include <tinycrypt/utils.h> #include <tinycrypt/cmac_mode.h> #include <tinycrypt/ccm_mode.h> #define BT_DBG_ENABLED 0 #include "common/log.h" #include "host/hci_core.h" #include "hci_api.h" #include "bt_crypto.h" #define __BT_CRYPTO_WEAK__ __attribute__((weak)) static struct tc_hmac_prng_struct prng; static int prng_reseed(struct tc_hmac_prng_struct *h) { u8_t seed[32]; s64_t extra; int ret, i; for (i = 0; i < (sizeof(seed) / 8); i++) { #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_rp_le_rand *rp; struct net_buf *rsp; ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); if (ret) { return ret; } rp = (void *)rsp->data; memcpy(&seed[i * 8], rp->rand, 8); net_buf_unref(rsp); #else hci_api_le_rand(&seed[i * 8]); #endif } extra = k_uptime_get(); ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra, sizeof(extra)); if (ret == TC_CRYPTO_FAIL) { BT_ERR("Failed to re-seed PRNG"); return -EIO; } return 0; } __BT_CRYPTO_WEAK__ int prng_init(void) { u8_t rand[8]; int ret; #if !defined(CONFIG_BT_USE_HCI_API) struct bt_hci_rp_le_rand *rp; struct net_buf *rsp; ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); if (ret) { return ret; } rp = (void *)rsp->data; memcpy(rand, rp, 8); #else hci_api_le_rand(rand); #endif ret = tc_hmac_prng_init(&prng, rand, sizeof(rand)); if (ret == TC_CRYPTO_FAIL) { BT_ERR("Failed to initialize PRNG"); return -EIO; } /* re-seed is needed after init */ return prng_reseed(&prng); } __BT_CRYPTO_WEAK__ int bt_crypto_rand(void *buf, size_t len) { int ret; ret = tc_hmac_prng_generate(buf, len, &prng); if (ret == TC_HMAC_PRNG_RESEED_REQ) { ret = prng_reseed(&prng); if (ret) { return ret; } ret = tc_hmac_prng_generate(buf, len, &prng); } if (ret == TC_CRYPTO_SUCCESS) { return 0; } return -EIO; } __BT_CRYPTO_WEAK__ int bt_crypto_encrypt_le(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) { struct tc_aes_key_sched_struct s; u8_t tmp[16]; BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16)); sys_memcpy_swap(tmp, key, 16); if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) { return -EINVAL; } sys_memcpy_swap(tmp, plaintext, 16); if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) { return -EINVAL; } sys_mem_swap(enc_data, 16); BT_DBG("enc_data %s", bt_hex(enc_data, 16)); return 0; } __BT_CRYPTO_WEAK__ int bt_crypto_encrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) { struct tc_aes_key_sched_struct s; BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16)); if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) { return -EINVAL; } if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) { return -EINVAL; } BT_DBG("enc_data %s", bt_hex(enc_data, 16)); return 0; } __BT_CRYPTO_WEAK__ int bt_crypto_decrypt_be(const u8_t key[16], const u8_t enc_data[16], u8_t dec_data[16]) { struct tc_aes_key_sched_struct s; if (tc_aes128_set_decrypt_key(&s, key) == TC_CRYPTO_FAIL) { return -EINVAL; } if (tc_aes_decrypt(dec_data, enc_data, &s) == TC_CRYPTO_FAIL) { return -EINVAL; } BT_DBG("dec_data %s", bt_hex(dec_data, 16)); return 0; } /* bt_crypto_cmac_* functions is modified from tinycrypt cmac_mode.c. the aes function is replaced by bt_encrypt_be which call aes ctypto from controller. */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * gf_wrap -- In our implementation, GF(2^128) is represented as a 16 byte * array with byte 0 the most significant and byte 15 the least significant. * High bit carry reduction is based on the primitive polynomial * * X^128 + X^7 + X^2 + X + 1, * * which leads to the reduction formula X^128 = X^7 + X^2 + X + 1. Indeed, * since 0 = (X^128 + X^7 + X^2 + 1) mod (X^128 + X^7 + X^2 + X + 1) and since * addition of polynomials with coefficients in Z/Z(2) is just XOR, we can * add X^128 to both sides to get * * X^128 = (X^7 + X^2 + X + 1) mod (X^128 + X^7 + X^2 + X + 1) * * and the coefficients of the polynomial on the right hand side form the * string 1000 0111 = 0x87, which is the value of gf_wrap. * * This gets used in the following way. Doubling in GF(2^128) is just a left * shift by 1 bit, except when the most significant bit is 1. In the latter * case, the relation X^128 = X^7 + X^2 + X + 1 says that the high order bit * that overflows beyond 128 bits can be replaced by addition of * X^7 + X^2 + X + 1 <--> 0x87 to the low order 128 bits. Since addition * in GF(2^128) is represented by XOR, we therefore only have to XOR 0x87 * into the low order byte after a left shift when the starting high order * bit is 1. */ static const unsigned char gf_wrap = 0x87; /* * assumes: out != NULL and points to a GF(2^n) value to receive the * doubled value; * in != NULL and points to a 16 byte GF(2^n) value * to double; * the in and out buffers do not overlap. * effects: doubles the GF(2^n) value pointed to by "in" and places * the result in the GF(2^n) value pointed to by "out." */ static void gf_double(uint8_t *out, uint8_t *in) { /* start with low order byte */ uint8_t *x = in + (16 - 1); /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */ uint8_t carry = (in[0] >> 7) ? gf_wrap : 0; out += (16 - 1); for (;;) { *out-- = (*x << 1) ^ carry; if (x == in) { break; } carry = *x-- >> 7; } } __BT_CRYPTO_WEAK__ int bt_crypto_cmac_setup(struct bt_crypto_cmac_t *ctx, const uint8_t key[16]) { if (NULL == ctx || NULL == key) { return -1; } memset(ctx, 0, sizeof(*ctx)); memcpy(ctx->aes_key, key, 16); memset(ctx->iv, 0, 16); bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, ctx->iv); gf_double(ctx->K1, ctx->iv); gf_double(ctx->K2, ctx->K1); memset(ctx->iv, 0, 16); memset(ctx->leftover, 0, 16); ctx->leftover_offset = 0; ctx->countdown = ((uint64_t)1 << 48); return 0; } __BT_CRYPTO_WEAK__ int bt_crypto_cmac_update(struct bt_crypto_cmac_t *ctx, const uint8_t *data, uint16_t data_length) { unsigned int i; /* input sanity check: */ if (ctx == NULL) { return -1; } if (data_length == 0) { return 0; } if (data == NULL) { return -1; } if (ctx->countdown == 0) { return -1; } ctx->countdown--; if (ctx->leftover_offset > 0) { /* last data added to s didn't end on a 16 byte boundary */ size_t remaining_space = 16 - ctx->leftover_offset; if (data_length < remaining_space) { /* still not enough data to encrypt this time either */ memcpy(&ctx->leftover[ctx->leftover_offset], data, data_length); ctx->leftover_offset += data_length; return 0; } /* leftover block is now full; encrypt it first */ memcpy(&ctx->leftover[ctx->leftover_offset], data, remaining_space); data_length -= remaining_space; data += remaining_space; ctx->leftover_offset = 0; for (i = 0; i < 16; ++i) { ctx->iv[i] ^= ctx->leftover[i]; } bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, ctx->iv); } /* CBC encrypt each (except the last) of the data blocks */ while (data_length > 16) { for (i = 0; i < 16; ++i) { ctx->iv[i] ^= data[i]; } bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, ctx->iv); data += 16; data_length -= 16; } if (data_length > 0) { /* save leftover data for next time */ memcpy(ctx->leftover, data, data_length); ctx->leftover_offset = data_length; } return 0; } __BT_CRYPTO_WEAK__ int bt_crypto_cmac_finish(struct bt_crypto_cmac_t *ctx, uint8_t out[16]) { uint8_t *k; unsigned int i; if (ctx == NULL || out == NULL) { return -1; } if (ctx->leftover_offset == 16) { /* the last message block is a full-sized block */ k = (uint8_t *) ctx->K1; } else { /* the final message block is not a full-sized block */ size_t remaining = 16 - ctx->leftover_offset; memset(&ctx->leftover[ctx->leftover_offset], 0, remaining); ctx->leftover[ctx->leftover_offset] = 0x80; k = (uint8_t *) ctx->K2; } for (i = 0; i < 16; ++i) { ctx->iv[i] ^= ctx->leftover[i] ^ k[i]; } bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, out); memset(ctx, 0, sizeof(*ctx)); return 0; } __BT_CRYPTO_WEAK__ int bt_crypto_aes_cmac(const u8_t key[16], struct bt_crypto_sg *sg, size_t sg_len, u8_t mac[16]) { struct tc_aes_key_sched_struct sched; struct tc_cmac_struct state; if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) { return -EIO; } for (; sg_len; sg_len--, sg++) { if (tc_cmac_update(&state, sg->data, sg->len) == TC_CRYPTO_FAIL) { return -EIO; } } if (tc_cmac_final(mac, &state) == TC_CRYPTO_FAIL) { return -EIO; } return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/bt_crypto.c
C
apache-2.0
11,565
## # Copyright (C) 2017 C-SKY Microsystems Co., 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. ## L_PATH := $(call cur-dir) include $(DEFINE_LOCAL) L_MODULE := libbt_crypto L_CFLAGS := -Wall L_INCS += $(L_PATH)/../bt_host/port/include $(L_PATH)/../bt_host/port/aos/include \ $(L_PATH)/../bt_host/host $(L_PATH)/../crypto $(L_PATH)/../bt_host/ L_INCS += $(L_PATH)/include $(L_PATH)/tinycrypt/include L_SRCS += bt_crypto.c include $(BUILD_MODULE) $(call include-all-subdir-makefiles,$(L_PATH))
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/build.mk
Makefile
apache-2.0
1,037
/* * Copyright (C) 2017 C-SKY Microsystems Co., 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. */ struct bt_crypto_sg { const void *data; size_t len; }; struct bt_crypto_cmac_t { uint8_t iv[16]; uint8_t K1[16]; uint8_t K2[16]; uint8_t leftover[16]; unsigned int keyid; unsigned int leftover_offset; uint8_t aes_key[16]; uint64_t countdown; }; int bt_crypto_cmac_setup(struct bt_crypto_cmac_t *ctx, const uint8_t key[16]); int bt_crypto_cmac_update(struct bt_crypto_cmac_t *ctx, const uint8_t *data, uint16_t data_length); int bt_crypto_cmac_finish(struct bt_crypto_cmac_t *ctx, uint8_t out[16]); int bt_crypto_aes_cmac(const uint8_t key[16], struct bt_crypto_sg *sg, size_t sg_len, uint8_t mac[16]); int bt_crypto_rand(void *buf, size_t len); int bt_crypto_encrypt_le(const uint8_t key[16], const uint8_t plaintext[16], uint8_t enc_data[16]); int bt_crypto_encrypt_be(const uint8_t key[16], const uint8_t plaintext[16], uint8_t enc_data[16]); int bt_crypto_decrypt_be(const uint8_t key[16], const uint8_t plaintext[16], uint8_t enc_data[16]);
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/include/bt_crypto.h
C
apache-2.0
1,637
subdir-ccflags-y +=-I$(srctree)/ext/lib/crypto/tinycrypt/include obj-$(CONFIG_TINYCRYPT) := source/utils.o obj-$(CONFIG_TINYCRYPT_ECC_DH) += source/ecc_dh.o source/ecc.o obj-$(CONFIG_TINYCRYPT_ECC_DSA) += source/ecc_dsa.o source/ecc.o obj-$(CONFIG_TINYCRYPT_AES) += source/aes_decrypt.o source/aes_encrypt.o obj-$(CONFIG_TINYCRYPT_AES_CBC) += source/cbc_mode.o obj-$(CONFIG_TINYCRYPT_AES_CTR) += source/ctr_mode.o obj-$(CONFIG_TINYCRYPT_AES_CCM) += source/ccm_mode.o obj-$(CONFIG_TINYCRYPT_AES_CMAC) += source/cmac_mode.o obj-$(CONFIG_TINYCRYPT_SHA256) += source/sha256.o obj-$(CONFIG_TINYCRYPT_SHA256_HMAC) += source/hmac.o obj-$(CONFIG_TINYCRYPT_SHA256_HMAC_PRNG) += source/hmac_prng.o obj-$(CONFIG_TINYCRYPT_CTR_PRNG) += source/ctr_prng.o
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/Makefile
Makefile
apache-2.0
743
## # Copyright (C) 2017 C-SKY Microsystems Co., 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.crg/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. ## L_PATH := $(call cur-dir) include $(DEFINE_LOCAL) L_MODULE := libtinycrypt L_CFLAGS := -Wall L_INCS += $(L_PATH)/include L_SRCS += source/utils.c \ source/sha256.c \ source/hmac.c \ source/hmac_prng.c \ source/aes_encrypt.c \ source/aes_decrypt.c \ source/ecc_dh.c \ source/ecc.c \ source/cmac_mode.c include $(BUILD_MODULE)
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/build.mk
Makefile
apache-2.0
988
/* aes.h - TinyCrypt interface to an AES-128 implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to an AES-128 implementation. * * Overview: AES-128 is a NIST approved block cipher specified in * FIPS 197. Block ciphers are deterministic algorithms that * perform a transformation specified by a symmetric key in fixed- * length data sets, also called blocks. * * Security: AES-128 provides approximately 128 bits of security. * * Usage: 1) call tc_aes128_set_encrypt/decrypt_key to set the key. * * 2) call tc_aes_encrypt/decrypt to process the data. */ #ifndef __TC_AES_H__ #define __TC_AES_H__ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define Nb (4) /* number of columns (32-bit words) comprising the state */ #define Nk (4) /* number of 32-bit words comprising the key */ #define Nr (10) /* number of rounds */ #define TC_AES_BLOCK_SIZE (Nb*Nk) #define TC_AES_KEY_SIZE (Nb*Nk) typedef struct tc_aes_key_sched_struct { unsigned int words[Nb*(Nr+1)]; } *TCAesKeySched_t; /** * @brief Set AES-128 encryption key * Uses key k to initialize s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: s == NULL or k == NULL * @note This implementation skips the additional steps required for keys * larger than 128 bits, and must not be used for AES-192 or * AES-256 key schedule -- see FIPS 197 for details * @param s IN/OUT -- initialized struct tc_aes_key_sched_struct * @param k IN -- points to the AES key */ int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k); /** * @brief AES-128 Encryption procedure * Encrypts contents of in buffer into out buffer under key; * schedule s * @note Assumes s was initialized by aes_set_encrypt_key; * out and in point to 16 byte buffers * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: out == NULL or in == NULL or s == NULL * @param out IN/OUT -- buffer to receive ciphertext block * @param in IN -- a plaintext block to encrypt * @param s IN -- initialized AES key schedule */ int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s); /** * @brief Set the AES-128 decryption key * Uses key k to initialize s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: s == NULL or k == NULL * @note This is the implementation of the straightforward inverse cipher * using the cipher documented in FIPS-197 figure 12, not the * equivalent inverse cipher presented in Figure 15 * @warning This routine skips the additional steps required for keys larger * than 128, and must not be used for AES-192 or AES-256 key * schedule -- see FIPS 197 for details * @param s IN/OUT -- initialized struct tc_aes_key_sched_struct * @param k IN -- points to the AES key */ int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k); /** * @brief AES-128 Encryption procedure * Decrypts in buffer into out buffer under key schedule s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: out is NULL or in is NULL or s is NULL * @note Assumes s was initialized by aes_set_encrypt_key * out and in point to 16 byte buffers * @param out IN/OUT -- buffer to receive ciphertext block * @param in IN -- a plaintext block to encrypt * @param s IN -- initialized AES key schedule */ int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s); #ifdef __cplusplus } #endif #endif /* __TC_AES_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/aes.h
C
apache-2.0
5,330
/* cbc_mode.h - TinyCrypt interface to a CBC mode implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to a CBC mode implementation. * * Overview: CBC (for "cipher block chaining") mode is a NIST approved mode of * operation defined in SP 800-38a. It can be used with any block * cipher to provide confidentiality of strings whose lengths are * multiples of the block_size of the underlying block cipher. * TinyCrypt hard codes AES as the block cipher. * * Security: CBC mode provides data confidentiality given that the maximum * number q of blocks encrypted under a single key satisfies * q < 2^63, which is not a practical constraint (it is considered a * good practice to replace the encryption when q == 2^56). CBC mode * provides NO data integrity. * * CBC mode assumes that the IV value input into the * tc_cbc_mode_encrypt is randomly generated. The TinyCrypt library * provides HMAC-PRNG module, which generates suitable IVs. Other * methods for generating IVs are acceptable, provided that the * values of the IVs generated appear random to any adversary, * including someone with complete knowledge of the system design. * * The randomness property on which CBC mode's security depends is * the unpredictability of the IV. Since it is unpredictable, this * means in practice that CBC mode requires that the IV is stored * somehow with the ciphertext in order to recover the plaintext. * * TinyCrypt CBC encryption prepends the IV to the ciphertext, * because this affords a more efficient (few buffers) decryption. * Hence tc_cbc_mode_encrypt assumes the ciphertext buffer is always * 16 bytes larger than the plaintext buffer. * * Requires: AES-128 * * Usage: 1) call tc_cbc_mode_encrypt to encrypt data. * * 2) call tc_cbc_mode_decrypt to decrypt data. * */ #ifndef __TC_CBC_MODE_H__ #define __TC_CBC_MODE_H__ #include <tinycrypt/aes.h> #ifdef __cplusplus extern "C" { #endif /** * @brief CBC encryption procedure * CBC encrypts inlen bytes of the in buffer into the out buffer * using the encryption key schedule provided, prepends iv to out * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * in == NULL or * ctr == NULL or * sched == NULL or * inlen == 0 or * (inlen % TC_AES_BLOCK_SIZE) != 0 or * (outlen % TC_AES_BLOCK_SIZE) != 0 or * outlen != inlen + TC_AES_BLOCK_SIZE * @note Assumes: - sched has been configured by aes_set_encrypt_key * - iv contains a 16 byte random string * - out buffer is large enough to hold the ciphertext + iv * - out buffer is a contiguous buffer * - in holds the plaintext and is a contiguous buffer * - inlen gives the number of bytes in the in buffer * @param out IN/OUT -- buffer to receive the ciphertext * @param outlen IN -- length of ciphertext buffer in bytes * @param in IN -- plaintext to encrypt * @param inlen IN -- length of plaintext buffer in bytes * @param iv IN -- the IV for the this encrypt/decrypt * @param sched IN -- AES key schedule for this encrypt */ int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched); /** * @brief CBC decryption procedure * CBC decrypts inlen bytes of the in buffer into the out buffer * using the provided encryption key schedule * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * in == NULL or * sched == NULL or * inlen == 0 or * outlen == 0 or * (inlen % TC_AES_BLOCK_SIZE) != 0 or * (outlen % TC_AES_BLOCK_SIZE) != 0 or * outlen != inlen + TC_AES_BLOCK_SIZE * @note Assumes:- in == iv + ciphertext, i.e. the iv and the ciphertext are * contiguous. This allows for a very efficient decryption * algorithm that would not otherwise be possible * - sched was configured by aes_set_decrypt_key * - out buffer is large enough to hold the decrypted plaintext * and is a contiguous buffer * - inlen gives the number of bytes in the in buffer * @param out IN/OUT -- buffer to receive decrypted data * @param outlen IN -- length of plaintext buffer in bytes * @param in IN -- ciphertext to decrypt, including IV * @param inlen IN -- length of ciphertext buffer in bytes * @param iv IN -- the IV for the this encrypt/decrypt * @param sched IN -- AES key schedule for this decrypt * */ int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched); #ifdef __cplusplus } #endif #endif /* __TC_CBC_MODE_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/cbc_mode.h
C
apache-2.0
6,846
/* ccm_mode.h - TinyCrypt interface to a CCM mode implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to a CCM mode implementation. * * Overview: CCM (for "Counter with CBC-MAC") mode is a NIST approved mode of * operation defined in SP 800-38C. * * TinyCrypt CCM implementation accepts: * * 1) Both non-empty payload and associated data (it encrypts and * authenticates the payload and also authenticates the associated * data); * 2) Non-empty payload and empty associated data (it encrypts and * authenticates the payload); * 3) Non-empty associated data and empty payload (it degenerates to * an authentication mode on the associated data). * * TinyCrypt CCM implementation accepts associated data of any length * between 0 and (2^16 - 2^8) bytes. * * Security: The mac length parameter is an important parameter to estimate the * security against collision attacks (that aim at finding different * messages that produce the same authentication tag). TinyCrypt CCM * implementation accepts any even integer between 4 and 16, as * suggested in SP 800-38C. * * RFC-3610, which also specifies CCM, presents a few relevant * security suggestions, such as: it is recommended for most * applications to use a mac length greater than 8. Besides, the * usage of the same nonce for two different messages which are * encrypted with the same key destroys the security of CCM mode. * * Requires: AES-128 * * Usage: 1) call tc_ccm_config to configure. * * 2) call tc_ccm_mode_encrypt to encrypt data and generate tag. * * 3) call tc_ccm_mode_decrypt to decrypt data and verify tag. */ #ifndef __TC_CCM_MODE_H__ #define __TC_CCM_MODE_H__ #include <tinycrypt/aes.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /* max additional authenticated size in bytes: 2^16 - 2^8 = 65280 */ #define TC_CCM_AAD_MAX_BYTES 0xff00 /* max message size in bytes: 2^(8L) = 2^16 = 65536 */ #define TC_CCM_PAYLOAD_MAX_BYTES 0x10000 /* struct tc_ccm_mode_struct represents the state of a CCM computation */ typedef struct tc_ccm_mode_struct { TCAesKeySched_t sched; /* AES key schedule */ uint8_t *nonce; /* nonce required by CCM */ unsigned int mlen; /* mac length in bytes (parameter t in SP-800 38C) */ } *TCCcmMode_t; /** * @brief CCM configuration procedure * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * c == NULL or * sched == NULL or * nonce == NULL or * mlen != {4, 6, 8, 10, 12, 16} * @param c -- CCM state * @param sched IN -- AES key schedule * @param nonce IN - nonce * @param nlen -- nonce length in bytes * @param mlen -- mac length in bytes (parameter t in SP-800 38C) */ int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, unsigned int nlen, unsigned int mlen); /** * @brief CCM tag generation and encryption procedure * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * c == NULL or * ((plen > 0) and (payload == NULL)) or * ((alen > 0) and (associated_data == NULL)) or * (alen >= TC_CCM_AAD_MAX_BYTES) or * (plen >= TC_CCM_PAYLOAD_MAX_BYTES) or * (olen < plen + maclength) * * @param out OUT -- encrypted data * @param olen IN -- output length in bytes * @param associated_data IN -- associated data * @param alen IN -- associated data length in bytes * @param payload IN -- payload * @param plen IN -- payload length in bytes * @param c IN -- CCM state * * @note: out buffer should be at least (plen + c->mlen) bytes long. * * @note: The sequence b for encryption is formatted as follows: * b = [FLAGS | nonce | counter ], where: * FLAGS is 1 byte long * nonce is 13 bytes long * counter is 2 bytes long * The byte FLAGS is composed by the following 8 bits: * 0-2 bits: used to represent the value of q-1 * 3-7 btis: always 0's * * @note: The sequence b for authentication is formatted as follows: * b = [FLAGS | nonce | length(mac length)], where: * FLAGS is 1 byte long * nonce is 13 bytes long * length(mac length) is 2 bytes long * The byte FLAGS is composed by the following 8 bits: * 0-2 bits: used to represent the value of q-1 * 3-5 bits: mac length (encoded as: (mlen-2)/2) * 6: Adata (0 if alen == 0, and 1 otherwise) * 7: always 0 */ int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c); /** * @brief CCM decryption and tag verification procedure * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * c == NULL or * ((plen > 0) and (payload == NULL)) or * ((alen > 0) and (associated_data == NULL)) or * (alen >= TC_CCM_AAD_MAX_BYTES) or * (plen >= TC_CCM_PAYLOAD_MAX_BYTES) or * (olen < plen - c->mlen) * * @param out OUT -- decrypted data * @param associated_data IN -- associated data * @param alen IN -- associated data length in bytes * @param payload IN -- payload * @param plen IN -- payload length in bytes * @param c IN -- CCM state * * @note: out buffer should be at least (plen - c->mlen) bytes long. * * @note: The sequence b for encryption is formatted as follows: * b = [FLAGS | nonce | counter ], where: * FLAGS is 1 byte long * nonce is 13 bytes long * counter is 2 bytes long * The byte FLAGS is composed by the following 8 bits: * 0-2 bits: used to represent the value of q-1 * 3-7 btis: always 0's * * @note: The sequence b for authentication is formatted as follows: * b = [FLAGS | nonce | length(mac length)], where: * FLAGS is 1 byte long * nonce is 13 bytes long * length(mac length) is 2 bytes long * The byte FLAGS is composed by the following 8 bits: * 0-2 bits: used to represent the value of q-1 * 3-5 bits: mac length (encoded as: (mlen-2)/2) * 6: Adata (0 if alen == 0, and 1 otherwise) * 7: always 0 */ int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c); #ifdef __cplusplus } #endif #endif /* __TC_CCM_MODE_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ccm_mode.h
C
apache-2.0
8,547
/* cmac_mode.h -- interface to a CMAC implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to a CMAC implementation. * * Overview: CMAC is defined NIST in SP 800-38B, and is the standard algorithm * for computing a MAC using a block cipher. It can compute the MAC * for a byte string of any length. It is distinguished from CBC-MAC * in the processing of the final message block; CMAC uses a * different technique to compute the final message block is full * size or only partial, while CBC-MAC uses the same technique for * both. This difference permits CMAC to be applied to variable * length messages, while all messages authenticated by CBC-MAC must * be the same length. * * Security: AES128-CMAC mode of operation offers 64 bits of security against * collision attacks. Note however that an external attacker cannot * generate the tags him/herself without knowing the MAC key. In this * sense, to attack the collision property of AES128-CMAC, an * external attacker would need the cooperation of the legal user to * produce an exponentially high number of tags (e.g. 2^64) to * finally be able to look for collisions and benefit from them. As * an extra precaution, the current implementation allows to at most * 2^48 calls to the tc_cmac_update function before re-calling * tc_cmac_setup (allowing a new key to be set), as suggested in * Appendix B of SP 800-38B. * * Requires: AES-128 * * Usage: This implementation provides a "scatter-gather" interface, so that * the CMAC value can be computed incrementally over a message * scattered in different segments throughout memory. Experience shows * this style of interface tends to minimize the burden of programming * correctly. Like all symmetric key operations, it is session * oriented. * * To begin a CMAC session, use tc_cmac_setup to initialize a struct * tc_cmac_struct with encryption key and buffer. Our implementation * always assume that the AES key to be the same size as the block * cipher block size. Once setup, this data structure can be used for * many CMAC computations. * * Once the state has been setup with a key, computing the CMAC of * some data requires three steps: * * (1) first use tc_cmac_init to initialize a new CMAC computation. * (2) next mix all of the data into the CMAC computation state using * tc_cmac_update. If all of the data resides in a single data * segment then only one tc_cmac_update call is needed; if data * is scattered throughout memory in n data segments, then n calls * will be needed. CMAC IS ORDER SENSITIVE, to be able to detect * attacks that swap bytes, so the order in which data is mixed * into the state is critical! * (3) Once all of the data for a message has been mixed, use * tc_cmac_final to compute the CMAC tag value. * * Steps (1)-(3) can be repeated as many times as you want to CMAC * multiple messages. A practical limit is 2^48 1K messages before you * have to change the key. * * Once you are done computing CMAC with a key, it is a good idea to * destroy the state so an attacker cannot recover the key; use * tc_cmac_erase to accomplish this. */ #ifndef __TC_CMAC_MODE_H__ #define __TC_CMAC_MODE_H__ #include <tinycrypt/aes.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /* padding for last message block */ #define TC_CMAC_PADDING 0x80 /* struct tc_cmac_struct represents the state of a CMAC computation */ typedef struct tc_cmac_struct { /* initialization vector */ uint8_t iv[TC_AES_BLOCK_SIZE]; /* used if message length is a multiple of block_size bytes */ uint8_t K1[TC_AES_BLOCK_SIZE]; /* used if message length isn't a multiple block_size bytes */ uint8_t K2[TC_AES_BLOCK_SIZE]; /* where to put bytes that didn't fill a block */ uint8_t leftover[TC_AES_BLOCK_SIZE]; /* identifies the encryption key */ unsigned int keyid; /* next available leftover location */ unsigned int leftover_offset; /* AES key schedule */ TCAesKeySched_t sched; /* calls to tc_cmac_update left before re-key */ uint64_t countdown; } *TCCmacState_t; /** * @brief Configures the CMAC state to use the given AES key * @return returns TC_CRYPTO_SUCCESS (1) after having configured the CMAC state * returns TC_CRYPTO_FAIL (0) if: * s == NULL or * key == NULL * * @param s IN/OUT -- the state to set up * @param key IN -- the key to use * @param sched IN -- AES key schedule */ int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched); /** * @brief Erases the CMAC state * @return returns TC_CRYPTO_SUCCESS (1) after having configured the CMAC state * returns TC_CRYPTO_FAIL (0) if: * s == NULL * * @param s IN/OUT -- the state to erase */ int tc_cmac_erase(TCCmacState_t s); /** * @brief Initializes a new CMAC computation * @return returns TC_CRYPTO_SUCCESS (1) after having initialized the CMAC state * returns TC_CRYPTO_FAIL (0) if: * s == NULL * * @param s IN/OUT -- the state to initialize */ int tc_cmac_init(TCCmacState_t s); /** * @brief Incrementally computes CMAC over the next data segment * @return returns TC_CRYPTO_SUCCESS (1) after successfully updating the CMAC state * returns TC_CRYPTO_FAIL (0) if: * s == NULL or * if data == NULL when dlen > 0 * * @param s IN/OUT -- the CMAC state * @param data IN -- the next data segment to MAC * @param dlen IN -- the length of data in bytes */ int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t dlen); /** * @brief Generates the tag from the CMAC state * @return returns TC_CRYPTO_SUCCESS (1) after successfully generating the tag * returns TC_CRYPTO_FAIL (0) if: * tag == NULL or * s == NULL * * @param tag OUT -- the CMAC tag * @param s IN -- CMAC state */ int tc_cmac_final(uint8_t *tag, TCCmacState_t s); #ifdef __cplusplus } #endif #endif /* __TC_CMAC_MODE_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/cmac_mode.h
C
apache-2.0
8,080
/* constants.h - TinyCrypt interface to constants */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to constants. * */ #ifndef __TC_CONSTANTS_H__ #define __TC_CONSTANTS_H__ #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #ifndef NULL #define NULL ((void *)0) #endif #define TC_CRYPTO_SUCCESS 1 #define TC_CRYPTO_FAIL 0 #define TC_ZERO_BYTE 0x00 #ifdef __cplusplus } #endif #endif /* __TC_CONSTANTS_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/constants.h
C
apache-2.0
2,024
/* ctr_mode.h - TinyCrypt interface to CTR mode */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to CTR mode. * * Overview: CTR (pronounced "counter") mode is a NIST approved mode of * operation defined in SP 800-38a. It can be used with any * block cipher to provide confidentiality of strings of any * length. TinyCrypt hard codes AES128 as the block cipher. * * Security: CTR mode achieves confidentiality only if the counter value is * never reused with a same encryption key. If the counter is * repeated, than an adversary might be able to defeat the scheme. * * A usual method to ensure different counter values refers to * initialize the counter in a given value (0, for example) and * increases it every time a new block is enciphered. This naturally * leaves to a limitation on the number q of blocks that can be * enciphered using a same key: q < 2^(counter size). * * TinyCrypt uses a counter of 32 bits. This means that after 2^32 * block encryptions, the counter will be reused (thus losing CBC * security). 2^32 block encryptions should be enough for most of * applications targeting constrained devices. Applications intended * to encrypt a larger number of blocks must replace the key after * 2^32 block encryptions. * * CTR mode provides NO data integrity. * * Requires: AES-128 * * Usage: 1) call tc_ctr_mode to process the data to encrypt/decrypt. * */ #ifndef __TC_CTR_MODE_H__ #define __TC_CTR_MODE_H__ #include <tinycrypt/aes.h> #include <tinycrypt/constants.h> #ifdef __cplusplus extern "C" { #endif /** * @brief CTR mode encryption/decryption procedure. * CTR mode encrypts (or decrypts) inlen bytes from in buffer into out buffer * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * out == NULL or * in == NULL or * ctr == NULL or * sched == NULL or * inlen == 0 or * outlen == 0 or * inlen != outlen * @note Assumes:- The current value in ctr has NOT been used with sched * - out points to inlen bytes * - in points to inlen bytes * - ctr is an integer counter in littleEndian format * - sched was initialized by aes_set_encrypt_key * @param out OUT -- produced ciphertext (plaintext) * @param outlen IN -- length of ciphertext buffer in bytes * @param in IN -- data to encrypt (or decrypt) * @param inlen IN -- length of input data in bytes * @param ctr IN/OUT -- the current counter value * @param sched IN -- an initialized AES key schedule */ int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched); #ifdef __cplusplus } #endif #endif /* __TC_CTR_MODE_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ctr_mode.h
C
apache-2.0
4,629
/* ctr_prng.h - TinyCrypt interface to a CTR-PRNG implementation */ /* * Copyright (c) 2016, Chris Morrison * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to a CTR-PRNG implementation. * * Overview: A pseudo-random number generator (PRNG) generates a sequence * of numbers that have a distribution close to the one expected * for a sequence of truly random numbers. The NIST Special * Publication 800-90A specifies several mechanisms to generate * sequences of pseudo random numbers, including the CTR-PRNG one * which is based on AES. TinyCrypt implements CTR-PRNG with * AES-128. * * Security: A cryptographically secure PRNG depends on the existence of an * entropy source to provide a truly random seed as well as the * security of the primitives used as the building blocks (AES-128 * in this instance). * * Requires: - AES-128 * * Usage: 1) call tc_ctr_prng_init to seed the prng context * * 2) call tc_ctr_prng_reseed to mix in additional entropy into * the prng context * * 3) call tc_ctr_prng_generate to output the pseudo-random data * * 4) call tc_ctr_prng_uninstantiate to zero out the prng context */ #ifndef __TC_CTR_PRNG_H__ #define __TC_CTR_PRNG_H__ #include <tinycrypt/aes.h> #define TC_CTR_PRNG_RESEED_REQ -1 #ifdef __cplusplus extern "C" { #endif typedef struct { /* updated each time another BLOCKLEN_BYTES bytes are produced */ uint8_t V[TC_AES_BLOCK_SIZE]; /* updated whenever the PRNG is reseeded */ struct tc_aes_key_sched_struct key; /* number of requests since initialization/reseeding */ uint64_t reseedCount; } TCCtrPrng_t; /** * @brief CTR-PRNG initialization procedure * Initializes prng context with entropy and personalization string (if any) * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * ctx == NULL, * entropy == NULL, * entropyLen < (TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE) * @note Only the first (TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE) bytes of * both the entropy and personalization inputs are used - * supplying additional bytes has no effect. * @param ctx IN/OUT -- the PRNG context to initialize * @param entropy IN -- entropy used to seed the PRNG * @param entropyLen IN -- entropy length in bytes * @param personalization IN -- personalization string used to seed the PRNG * (may be null) * @param plen IN -- personalization length in bytes * */ int tc_ctr_prng_init(TCCtrPrng_t * const ctx, uint8_t const * const entropy, unsigned int entropyLen, uint8_t const * const personalization, unsigned int pLen); /** * @brief CTR-PRNG reseed procedure * Mixes entropy and additional_input into the prng context * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * ctx == NULL, * entropy == NULL, * entropylen < (TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE) * @note It is better to reseed an existing prng context rather than * re-initialise, so that any existing entropy in the context is * presereved. This offers some protection against undetected failures * of the entropy source. * @note Assumes tc_ctr_prng_init has been called for ctx * @param ctx IN/OUT -- the PRNG state * @param entropy IN -- entropy to mix into the prng * @param entropylen IN -- length of entropy in bytes * @param additional_input IN -- additional input to the prng (may be null) * @param additionallen IN -- additional input length in bytes */ int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, uint8_t const * const entropy, unsigned int entropyLen, uint8_t const * const additional_input, unsigned int additionallen); /** * @brief CTR-PRNG generate procedure * Generates outlen pseudo-random bytes into out buffer, updates prng * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CTR_PRNG_RESEED_REQ (-1) if a reseed is needed * returns TC_CRYPTO_FAIL (0) if: * ctx == NULL, * out == NULL, * outlen >= 2^16 * @note Assumes tc_ctr_prng_init has been called for ctx * @param ctx IN/OUT -- the PRNG context * @param additional_input IN -- additional input to the prng (may be null) * @param additionallen IN -- additional input length in bytes * @param out IN/OUT -- buffer to receive output * @param outlen IN -- size of out buffer in bytes */ int tc_ctr_prng_generate(TCCtrPrng_t * const ctx, uint8_t const * const additional_input, unsigned int additionallen, uint8_t * const out, unsigned int outlen); /** * @brief CTR-PRNG uninstantiate procedure * Zeroes the internal state of the supplied prng context * @return none * @param ctx IN/OUT -- the PRNG context */ void tc_ctr_prng_uninstantiate(TCCtrPrng_t * const ctx); #ifdef __cplusplus } #endif #endif /* __TC_CTR_PRNG_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ctr_prng.h
C
apache-2.0
6,459
/* ecc.h - TinyCrypt interface to common ECC functions */ /* Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to common ECC functions. * * Overview: This software is an implementation of common functions * necessary to elliptic curve cryptography. This implementation uses * curve NIST p-256. * * Security: The curve NIST p-256 provides approximately 128 bits of security. * */ #ifndef __TC_UECC_H__ #define __TC_UECC_H__ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /* Word size (4 bytes considering 32-bits architectures) */ #define uECC_WORD_SIZE 4 /* setting max number of calls to prng: */ #ifndef uECC_RNG_MAX_TRIES #define uECC_RNG_MAX_TRIES 64 #endif /* defining data types to store word and bit counts: */ typedef int8_t wordcount_t; typedef int16_t bitcount_t; /* defining data type for comparison result: */ typedef int8_t cmpresult_t; /* defining data type to store ECC coordinate/point in 32bits words: */ typedef unsigned int uECC_word_t; /* defining data type to store an ECC coordinate/point in 64bits words: */ typedef uint64_t uECC_dword_t; /* defining masks useful for ecc computations: */ #define HIGH_BIT_SET 0x80000000 #define uECC_WORD_BITS 32 #define uECC_WORD_BITS_SHIFT 5 #define uECC_WORD_BITS_MASK 0x01F /* Number of words of 32 bits to represent an element of the the curve p-256: */ #define NUM_ECC_WORDS 8 /* Number of bytes to represent an element of the the curve p-256: */ #define NUM_ECC_BYTES (uECC_WORD_SIZE*NUM_ECC_WORDS) /* structure that represents an elliptic curve (e.g. p256):*/ struct uECC_Curve_t; typedef const struct uECC_Curve_t * uECC_Curve; struct uECC_Curve_t { wordcount_t num_words; wordcount_t num_bytes; bitcount_t num_n_bits; uECC_word_t p[NUM_ECC_WORDS]; uECC_word_t n[NUM_ECC_WORDS]; uECC_word_t G[NUM_ECC_WORDS * 2]; uECC_word_t b[NUM_ECC_WORDS]; void (*double_jacobian)(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * Z1, uECC_Curve curve); void (*x_side)(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve); void (*mmod_fast)(uECC_word_t *result, uECC_word_t *product); }; /* * @brief computes doubling of point ion jacobian coordinates, in place. * @param X1 IN/OUT -- x coordinate * @param Y1 IN/OUT -- y coordinate * @param Z1 IN/OUT -- z coordinate * @param curve IN -- elliptic curve */ void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * Z1, uECC_Curve curve); /* * @brief Computes x^3 + ax + b. result must not overlap x. * @param result OUT -- x^3 + ax + b * @param x IN -- value of x * @param curve IN -- elliptic curve */ void x_side_default(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve); /* * @brief Computes result = product % curve_p * from http://www.nsa.gov/ia/_files/nist-routines.pdf * @param result OUT -- product % curve_p * @param product IN -- value to be reduced mod curve_p */ void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product); /* Bytes to words ordering: */ #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a #define BITS_TO_WORDS(num_bits) \ ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / (uECC_WORD_SIZE * 8)) #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8) /* definition of curve NIST p-256: */ static const struct uECC_Curve_t curve_secp256r1 = { NUM_ECC_WORDS, NUM_ECC_BYTES, 256, /* num_n_bits */ { BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00), BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00), BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF) }, { BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3), BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC), BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF) }, { BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4), BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77), BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8), BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B), BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB), BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B), BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E), BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F) }, { BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B), BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65), BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3), BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A) }, &double_jacobian_default, &x_side_default, &vli_mmod_fast_secp256r1 }; uECC_Curve uECC_secp256r1(void); /* * @brief Generates a random integer in the range 0 < random < top. * Both random and top have num_words words. * @param random OUT -- random integer in the range 0 < random < top * @param top IN -- upper limit * @param num_words IN -- number of words * @return a random integer in the range 0 < random < top */ int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top, wordcount_t num_words); /* uECC_RNG_Function type * The RNG function should fill 'size' random bytes into 'dest'. It should * return 1 if 'dest' was filled with random data, or 0 if the random data could * not be generated. The filled-in values should be either truly random, or from * a cryptographically-secure PRNG. * * A correctly functioning RNG function must be set (using uECC_set_rng()) * before calling uECC_make_key() or uECC_sign(). * * Setting a correctly functioning RNG function improves the resistance to * side-channel attacks for uECC_shared_secret(). * * A correct RNG function is set by default. If you are building on another * POSIX-compliant system that supports /dev/random or /dev/urandom, you can * define uECC_POSIX to use the predefined RNG. */ typedef int(*uECC_RNG_Function)(uint8_t *dest, unsigned int size); /* * @brief Set the function that will be used to generate random bytes. The RNG * function should return 1 if the random data was generated, or 0 if the random * data could not be generated. * * @note On platforms where there is no predefined RNG function, this must be * called before uECC_make_key() or uECC_sign() are used. * * @param rng_function IN -- function that will be used to generate random bytes */ void uECC_set_rng(uECC_RNG_Function rng_function); /* * @brief provides current uECC_RNG_Function. * @return Returns the function that will be used to generate random bytes. */ uECC_RNG_Function uECC_get_rng(void); /* * @brief computes the size of a private key for the curve in bytes. * @param curve IN -- elliptic curve * @return size of a private key for the curve in bytes. */ int uECC_curve_private_key_size(uECC_Curve curve); /* * @brief computes the size of a public key for the curve in bytes. * @param curve IN -- elliptic curve * @return the size of a public key for the curve in bytes. */ int uECC_curve_public_key_size(uECC_Curve curve); /* * @brief Compute the corresponding public key for a private key. * @param private_key IN -- The private key to compute the public key for * @param public_key OUT -- Will be filled in with the corresponding public key * @param curve * @return Returns 1 if key was computed successfully, 0 if an error occurred. */ int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key, uECC_Curve curve); /* * @brief Compute public-key. * @return corresponding public-key. * @param result OUT -- public-key * @param private_key IN -- private-key * @param curve IN -- elliptic curve */ uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, uECC_word_t *private_key, uECC_Curve curve); /* * @brief Regularize the bitcount for the private key so that attackers cannot * use a side channel attack to learn the number of leading zeros. * @return Regularized k * @param k IN -- private-key * @param k0 IN/OUT -- regularized k * @param k1 IN/OUT -- regularized k * @param curve IN -- elliptic curve */ uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0, uECC_word_t *k1, uECC_Curve curve); /* * @brief Point multiplication algorithm using Montgomery's ladder with co-Z * coordinates. See http://eprint.iacr.org/2011/338.pdf. * @note Result may overlap point. * @param result OUT -- returns scalar*point * @param point IN -- elliptic curve point * @param scalar IN -- scalar * @param initial_Z IN -- initial value for z * @param num_bits IN -- number of bits in scalar * @param curve IN -- elliptic curve */ void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point, const uECC_word_t * scalar, const uECC_word_t * initial_Z, bitcount_t num_bits, uECC_Curve curve); /* * @brief Constant-time comparison to zero - secure way to compare long integers * @param vli IN -- very long integer * @param num_words IN -- number of words in the vli * @return 1 if vli == 0, 0 otherwise. */ uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words); /* * @brief Check if 'point' is the point at infinity * @param point IN -- elliptic curve point * @param curve IN -- elliptic curve * @return if 'point' is the point at infinity, 0 otherwise. */ uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve); /* * @brief computes the sign of left - right, in constant time. * @param left IN -- left term to be compared * @param right IN -- right term to be compared * @param num_words IN -- number of words * @return the sign of left - right */ cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words); /* * @brief computes sign of left - right, not in constant time. * @note should not be used if inputs are part of a secret * @param left IN -- left term to be compared * @param right IN -- right term to be compared * @param num_words IN -- number of words * @return the sign of left - right */ cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words); /* * @brief Computes result = (left - right) % mod. * @note Assumes that (left < mod) and (right < mod), and that result does not * overlap mod. * @param result OUT -- (left - right) % mod * @param left IN -- leftright term in modular subtraction * @param right IN -- right term in modular subtraction * @param mod IN -- mod * @param num_words IN -- number of words */ void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words); /* * @brief Computes P' = (x1', y1', Z3), P + Q = (x3, y3, Z3) or * P => P', Q => P + Q * @note assumes Input P = (x1, y1, Z), Q = (x2, y2, Z) * @param X1 IN -- x coordinate of P * @param Y1 IN -- y coordinate of P * @param X2 IN -- x coordinate of Q * @param Y2 IN -- y coordinate of Q * @param curve IN -- elliptic curve */ void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, uECC_Curve curve); /* * @brief Computes (x1 * z^2, y1 * z^3) * @param X1 IN -- previous x1 coordinate * @param Y1 IN -- previous y1 coordinate * @param Z IN -- z value * @param curve IN -- elliptic curve */ void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z, uECC_Curve curve); /* * @brief Check if bit is set. * @return Returns nonzero if bit 'bit' of vli is set. * @warning It is assumed that the value provided in 'bit' is within the * boundaries of the word-array 'vli'. * @note The bit ordering layout assumed for vli is: {31, 30, ..., 0}, * {63, 62, ..., 32}, {95, 94, ..., 64}, {127, 126,..., 96} for a vli consisting * of 4 uECC_word_t elements. */ uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit); /* * @brief Computes result = product % mod, where product is 2N words long. * @param result OUT -- product % mod * @param mod IN -- module * @param num_words IN -- number of words * @warning Currently only designed to work for curve_p or curve_n. */ void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, const uECC_word_t *mod, wordcount_t num_words); /* * @brief Computes modular product (using curve->mmod_fast) * @param result OUT -- (left * right) mod % curve_p * @param left IN -- left term in product * @param right IN -- right term in product * @param curve IN -- elliptic curve */ void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, uECC_Curve curve); /* * @brief Computes result = left - right. * @note Can modify in place. * @param result OUT -- left - right * @param left IN -- left term in subtraction * @param right IN -- right term in subtraction * @param num_words IN -- number of words * @return borrow */ uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words); /* * @brief Constant-time comparison function(secure way to compare long ints) * @param left IN -- left term in comparison * @param right IN -- right term in comparison * @param num_words IN -- number of words * @return Returns 0 if left == right, 1 otherwise. */ uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words); /* * @brief Computes (left * right) % mod * @param result OUT -- (left * right) % mod * @param left IN -- left term in product * @param right IN -- right term in product * @param mod IN -- mod * @param num_words IN -- number of words */ void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words); /* * @brief Computes (1 / input) % mod * @note All VLIs are the same size. * @note See "Euclid's GCD to Montgomery Multiplication to the Great Divide" * @param result OUT -- (1 / input) % mod * @param input IN -- value to be modular inverted * @param mod IN -- mod * @param num_words -- number of words */ void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, const uECC_word_t *mod, wordcount_t num_words); /* * @brief Sets dest = src. * @param dest OUT -- destination buffer * @param src IN -- origin buffer * @param num_words IN -- number of words */ void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, wordcount_t num_words); /* * @brief Computes (left + right) % mod. * @note Assumes that (left < mod) and right < mod), and that result does not * overlap mod. * @param result OUT -- (left + right) % mod. * @param left IN -- left term in addition * @param right IN -- right term in addition * @param mod IN -- mod * @param num_words IN -- number of words */ void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words); /* * @brief Counts the number of bits required to represent vli. * @param vli IN -- very long integer * @param max_words IN -- number of words * @return number of bits in given vli */ bitcount_t uECC_vli_numBits(const uECC_word_t *vli, const wordcount_t max_words); /* * @brief Erases (set to 0) vli * @param vli IN -- very long integer * @param num_words IN -- number of words */ void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words); /* * @brief check if it is a valid point in the curve * @param point IN -- point to be checked * @param curve IN -- elliptic curve * @return 0 if point is valid * @exception returns -1 if it is a point at infinity * @exception returns -2 if x or y is smaller than p, * @exception returns -3 if y^2 != x^3 + ax + b. */ int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve); /* * @brief Check if a public key is valid. * @param public_key IN -- The public key to be checked. * @return returns 0 if the public key is valid * @exception returns -1 if it is a point at infinity * @exception returns -2 if x or y is smaller than p, * @exception returns -3 if y^2 != x^3 + ax + b. * @exception returns -4 if public key is the group generator. * * @note Note that you are not required to check for a valid public key before * using any other uECC functions. However, you may wish to avoid spending CPU * time computing a shared secret or verifying a signature using an invalid * public key. */ int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve); /* * @brief Converts an integer in uECC native format to big-endian bytes. * @param bytes OUT -- bytes representation * @param num_bytes IN -- number of bytes * @param native IN -- uECC native representation */ void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, const unsigned int *native); /* * @brief Converts big-endian bytes to an integer in uECC native format. * @param native OUT -- uECC native representation * @param bytes IN -- bytes representation * @param num_bytes IN -- number of bytes */ void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes, int num_bytes); #ifdef __cplusplus } #endif #endif /* __TC_UECC_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ecc.h
C
apache-2.0
20,332
/* ecc_dh.h - TinyCrypt interface to EC-DH implementation */ /* * Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to EC-DH implementation. * * Overview: This software is an implementation of EC-DH. This implementation * uses curve NIST p-256. * * Security: The curve NIST p-256 provides approximately 128 bits of security. */ #ifndef __TC_ECC_DH_H__ #define __TC_ECC_DH_H__ #include <tinycrypt/ecc.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Create a public/private key pair. * @return returns TC_CRYPTO_SUCCESS (1) if the key pair was generated successfully * returns TC_CRYPTO_FAIL (0) if error while generating key pair * * @param p_public_key OUT -- Will be filled in with the public key. Must be at * least 2 * the curve size (in bytes) long. For curve secp256r1, p_public_key * must be 64 bytes long. * @param p_private_key OUT -- Will be filled in with the private key. Must be as * long as the curve order (for secp256r1, p_private_key must be 32 bytes long). * * @note side-channel countermeasure: algorithm strengthened against timing * attack. * @warning A cryptographically-secure PRNG function must be set (using * uECC_set_rng()) before calling uECC_make_key(). */ int uECC_make_key(uint8_t *p_public_key, uint8_t *p_private_key, uECC_Curve curve); #ifdef ENABLE_TESTS /** * @brief Create a public/private key pair given a specific d. * * @note THIS FUNCTION SHOULD BE CALLED ONLY FOR TEST PURPOSES. Refer to * uECC_make_key() function for real applications. */ int uECC_make_key_with_d(uint8_t *p_public_key, uint8_t *p_private_key, unsigned int *d, uECC_Curve curve); #endif /** * @brief Compute a shared secret given your secret key and someone else's * public key. * @return returns TC_CRYPTO_SUCCESS (1) if the shared secret was computed successfully * returns TC_CRYPTO_FAIL (0) otherwise * * @param p_secret OUT -- Will be filled in with the shared secret value. Must be * the same size as the curve size (for curve secp256r1, secret must be 32 bytes * long. * @param p_public_key IN -- The public key of the remote party. * @param p_private_key IN -- Your private key. * * @warning It is recommended to use the output of uECC_shared_secret() as the * input of a recommended Key Derivation Function (see NIST SP 800-108) in * order to produce a cryptographically secure symmetric key. */ int uECC_shared_secret(const uint8_t *p_public_key, const uint8_t *p_private_key, uint8_t *p_secret, uECC_Curve curve); #ifdef __cplusplus } #endif #endif /* __TC_ECC_DH_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ecc_dh.h
C
apache-2.0
5,553
/* ecc_dh.h - TinyCrypt interface to EC-DSA implementation */ /* * Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief -- Interface to EC-DSA implementation. * * Overview: This software is an implementation of EC-DSA. This implementation * uses curve NIST p-256. * * Security: The curve NIST p-256 provides approximately 128 bits of security. * * Usage: - To sign: Compute a hash of the data you wish to sign (SHA-2 is * recommended) and pass it in to ecdsa_sign function along with your * private key and a random number. You must use a new non-predictable * random number to generate each new signature. * - To verify a signature: Compute the hash of the signed data using * the same hash as the signer and pass it to this function along with * the signer's public key and the signature values (r and s). */ #ifndef __TC_ECC_DSA_H__ #define __TC_ECC_DSA_H__ #include <tinycrypt/ecc.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Generate an ECDSA signature for a given hash value. * @return returns TC_CRYPTO_SUCCESS (1) if the signature generated successfully * returns TC_CRYPTO_FAIL (0) if an error occurred. * * @param p_private_key IN -- Your private key. * @param p_message_hash IN -- The hash of the message to sign. * @param p_hash_size IN -- The size of p_message_hash in bytes. * @param p_signature OUT -- Will be filled in with the signature value. Must be * at least 2 * curve size long (for secp256r1, signature must be 64 bytes long). * * @warning A cryptographically-secure PRNG function must be set (using * uECC_set_rng()) before calling uECC_sign(). * @note Usage: Compute a hash of the data you wish to sign (SHA-2 is * recommended) and pass it in to this function along with your private key. * @note side-channel countermeasure: algorithm strengthened against timing * attack. */ int uECC_sign(const uint8_t *p_private_key, const uint8_t *p_message_hash, unsigned p_hash_size, uint8_t *p_signature, uECC_Curve curve); #ifdef ENABLE_TESTS /* * THIS FUNCTION SHOULD BE CALLED FOR TEST PURPOSES ONLY. * Refer to uECC_sign() function for real applications. */ int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, unsigned int hash_size, uECC_word_t *k, uint8_t *signature, uECC_Curve curve); #endif /** * @brief Verify an ECDSA signature. * @return returns TC_SUCCESS (1) if the signature is valid * returns TC_FAIL (0) if the signature is invalid. * * @param p_public_key IN -- The signer's public key. * @param p_message_hash IN -- The hash of the signed data. * @param p_hash_size IN -- The size of p_message_hash in bytes. * @param p_signature IN -- The signature values. * * @note Usage: Compute the hash of the signed data using the same hash as the * signer and pass it to this function along with the signer's public key and * the signature values (hash_size and signature). */ int uECC_verify(const uint8_t *p_public_key, const uint8_t *p_message_hash, unsigned int p_hash_size, const uint8_t *p_signature, uECC_Curve curve); #ifdef __cplusplus } #endif #endif /* __TC_ECC_DSA_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ecc_dsa.h
C
apache-2.0
6,150
/* uECC_platform_specific.h - Interface to platform specific functions*/ /* Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE.*/ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * uECC_platform_specific.h -- Interface to platform specific functions */ #ifndef __UECC_PLATFORM_SPECIFIC_H_ #define __UECC_PLATFORM_SPECIFIC_H_ /* * The RNG function should fill 'size' random bytes into 'dest'. It should * return 1 if 'dest' was filled with random data, or 0 if the random data could * not be generated. The filled-in values should be either truly random, or from * a cryptographically-secure PRNG. * * A cryptographically-secure PRNG function must be set (using uECC_set_rng()) * before calling uECC_make_key() or uECC_sign(). * * Setting a cryptographically-secure PRNG function improves the resistance to * side-channel attacks for uECC_shared_secret(). * * A correct PRNG function is set by default (default_RNG_defined = 1) and works * for some platforms, such as Unix and Linux. For other platforms, you may need * to provide another PRNG function. */ #define default_RNG_defined 1 int default_CSPRNG(uint8_t *dest, unsigned int size); #endif /* __UECC_PLATFORM_SPECIFIC_H_ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/ecc_platform_specific.h
C
apache-2.0
4,070
/* hmac.h - TinyCrypt interface to an HMAC implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to an HMAC implementation. * * Overview: HMAC is a message authentication code based on hash functions. * TinyCrypt hard codes SHA-256 as the hash function. A message * authentication code based on hash functions is also called a * keyed cryptographic hash function since it performs a * transformation specified by a key in an arbitrary length data * set into a fixed length data set (also called tag). * * Security: The security of the HMAC depends on the length of the key and * on the security of the hash function. Note that HMAC primitives * are much less affected by collision attacks than their * corresponding hash functions. * * Requires: SHA-256 * * Usage: 1) call tc_hmac_set_key to set the HMAC key. * * 2) call tc_hmac_init to initialize a struct hash_state before * processing the data. * * 3) call tc_hmac_update to process the next input segment; * tc_hmac_update can be called as many times as needed to process * all of the segments of the input; the order is important. * * 4) call tc_hmac_final to out put the tag. */ #ifndef __TC_HMAC_H__ #define __TC_HMAC_H__ #include <tinycrypt/sha256.h> #ifdef __cplusplus extern "C" { #endif struct tc_hmac_state_struct { /* the internal state required by h */ struct tc_sha256_state_struct hash_state; /* HMAC key schedule */ uint8_t key[2*TC_SHA256_BLOCK_SIZE]; }; typedef struct tc_hmac_state_struct *TCHmacState_t; /** * @brief HMAC set key procedure * Configures ctx to use key * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if * ctx == NULL or * key == NULL or * key_size == 0 * @param ctx IN/OUT -- the struct tc_hmac_state_struct to initial * @param key IN -- the HMAC key to configure * @param key_size IN -- the HMAC key size */ int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key, unsigned int key_size); /** * @brief HMAC init procedure * Initializes ctx to begin the next HMAC operation * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: ctx == NULL or key == NULL * @param ctx IN/OUT -- struct tc_hmac_state_struct buffer to init */ int tc_hmac_init(TCHmacState_t ctx); /** * @brief HMAC update procedure * Mixes data_length bytes addressed by data into state * @return returns TC_CRYPTO_SUCCCESS (1) * returns TC_CRYPTO_FAIL (0) if: ctx == NULL or key == NULL * @note Assumes state has been initialized by tc_hmac_init * @param ctx IN/OUT -- state of HMAC computation so far * @param data IN -- data to incorporate into state * @param data_length IN -- size of data in bytes */ int tc_hmac_update(TCHmacState_t ctx, const void *data, unsigned int data_length); /** * @brief HMAC final procedure * Writes the HMAC tag into the tag buffer * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * tag == NULL or * ctx == NULL or * key == NULL or * taglen != TC_SHA256_DIGEST_SIZE * @note ctx is erased before exiting. This should never be changed/removed. * @note Assumes the tag bufer is at least sizeof(hmac_tag_size(state)) bytes * state has been initialized by tc_hmac_init * @param tag IN/OUT -- buffer to receive computed HMAC tag * @param taglen IN -- size of tag in bytes * @param ctx IN/OUT -- the HMAC state for computing tag */ int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx); #ifdef __cplusplus } #endif #endif /*__TC_HMAC_H__*/
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/hmac.h
C
apache-2.0
5,455
/* hmac_prng.h - TinyCrypt interface to an HMAC-PRNG implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to an HMAC-PRNG implementation. * * Overview: A pseudo-random number generator (PRNG) generates a sequence * of numbers that have a distribution close to the one expected * for a sequence of truly random numbers. The NIST Special * Publication 800-90A specifies several mechanisms to generate * sequences of pseudo random numbers, including the HMAC-PRNG one * which is based on HMAC. TinyCrypt implements HMAC-PRNG with * certain modifications from the NIST SP 800-90A spec. * * Security: A cryptographically secure PRNG depends on the existence of an * entropy source to provide a truly random seed as well as the * security of the primitives used as the building blocks (HMAC and * SHA256, for TinyCrypt). * * The NIST SP 800-90A standard tolerates a null personalization, * while TinyCrypt requires a non-null personalization. This is * because a personalization string (the host name concatenated * with a time stamp, for example) is easily computed and might be * the last line of defense against failure of the entropy source. * * Requires: - SHA-256 * - HMAC * * Usage: 1) call tc_hmac_prng_init to set the HMAC key and process the * personalization data. * * 2) call tc_hmac_prng_reseed to process the seed and additional * input. * * 3) call tc_hmac_prng_generate to out put the pseudo-random data. */ #ifndef __TC_HMAC_PRNG_H__ #define __TC_HMAC_PRNG_H__ #include <tinycrypt/sha256.h> #include <tinycrypt/hmac.h> #ifdef __cplusplus extern "C" { #endif #define TC_HMAC_PRNG_RESEED_REQ -1 struct tc_hmac_prng_struct { /* the HMAC instance for this PRNG */ struct tc_hmac_state_struct h; /* the PRNG key */ uint8_t key[TC_SHA256_DIGEST_SIZE]; /* PRNG state */ uint8_t v[TC_SHA256_DIGEST_SIZE]; /* calls to tc_hmac_prng_generate left before re-seed */ unsigned int countdown; }; typedef struct tc_hmac_prng_struct *TCHmacPrng_t; /** * @brief HMAC-PRNG initialization procedure * Initializes prng with personalization, disables tc_hmac_prng_generate * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * prng == NULL, * personalization == NULL, * plen > MAX_PLEN * @note Assumes: - personalization != NULL. * The personalization is a platform unique string (e.g., the host * name) and is the last line of defense against failure of the * entropy source * @warning NIST SP 800-90A specifies 3 items as seed material during * initialization: entropy seed, personalization, and an optional * nonce. TinyCrypts requires instead a non-null personalization * (which is easily computed) and indirectly requires an entropy * seed (since the reseed function is mandatorily called after * init) * @param prng IN/OUT -- the PRNG state to initialize * @param personalization IN -- personalization string * @param plen IN -- personalization length in bytes */ int tc_hmac_prng_init(TCHmacPrng_t prng, const uint8_t *personalization, unsigned int plen); /** * @brief HMAC-PRNG reseed procedure * Mixes seed into prng, enables tc_hmac_prng_generate * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * prng == NULL, * seed == NULL, * seedlen < MIN_SLEN, * seendlen > MAX_SLEN, * additional_input != (const uint8_t *) 0 && additionallen == 0, * additional_input != (const uint8_t *) 0 && additionallen > MAX_ALEN * @note Assumes:- tc_hmac_prng_init has been called for prng * - seed has sufficient entropy. * * @param prng IN/OUT -- the PRNG state * @param seed IN -- entropy to mix into the prng * @param seedlen IN -- length of seed in bytes * @param additional_input IN -- additional input to the prng * @param additionallen IN -- additional input length in bytes */ int tc_hmac_prng_reseed(TCHmacPrng_t prng, const uint8_t *seed, unsigned int seedlen, const uint8_t *additional_input, unsigned int additionallen); /** * @brief HMAC-PRNG generate procedure * Generates outlen pseudo-random bytes into out buffer, updates prng * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_HMAC_PRNG_RESEED_REQ (-1) if a reseed is needed * returns TC_CRYPTO_FAIL (0) if: * out == NULL, * prng == NULL, * outlen == 0, * outlen >= MAX_OUT * @note Assumes tc_hmac_prng_init has been called for prng * @param out IN/OUT -- buffer to receive output * @param outlen IN -- size of out buffer in bytes * @param prng IN/OUT -- the PRNG state */ int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng); #ifdef __cplusplus } #endif #endif /* __TC_HMAC_PRNG_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/hmac_prng.h
C
apache-2.0
6,839
/* sha256.h - TinyCrypt interface to a SHA-256 implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to a SHA-256 implementation. * * Overview: SHA-256 is a NIST approved cryptographic hashing algorithm * specified in FIPS 180. A hash algorithm maps data of arbitrary * size to data of fixed length. * * Security: SHA-256 provides 128 bits of security against collision attacks * and 256 bits of security against pre-image attacks. SHA-256 does * NOT behave like a random oracle, but it can be used as one if * the string being hashed is prefix-free encoded before hashing. * * Usage: 1) call tc_sha256_init to initialize a struct * tc_sha256_state_struct before hashing a new string. * * 2) call tc_sha256_update to hash the next string segment; * tc_sha256_update can be called as many times as needed to hash * all of the segments of a string; the order is important. * * 3) call tc_sha256_final to out put the digest from a hashing * operation. */ #ifndef __TC_SHA256_H__ #define __TC_SHA256_H__ #include <stddef.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define TC_SHA256_BLOCK_SIZE (64) #define TC_SHA256_DIGEST_SIZE (32) #define TC_SHA256_STATE_BLOCKS (TC_SHA256_DIGEST_SIZE/4) struct tc_sha256_state_struct { unsigned int iv[TC_SHA256_STATE_BLOCKS]; uint64_t bits_hashed; uint8_t leftover[TC_SHA256_BLOCK_SIZE]; size_t leftover_offset; }; typedef struct tc_sha256_state_struct *TCSha256State_t; /** * @brief SHA256 initialization procedure * Initializes s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if s == NULL * @param s Sha256 state struct */ int tc_sha256_init(TCSha256State_t s); /** * @brief SHA256 update procedure * Hashes data_length bytes addressed by data into state s * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * s == NULL, * s->iv == NULL, * data == NULL * @note Assumes s has been initialized by tc_sha256_init * @warning The state buffer 'leftover' is left in memory after processing * If your application intends to have sensitive data in this * buffer, remind to erase it after the data has been processed * @param s Sha256 state struct * @param data message to hash * @param datalen length of message to hash */ int tc_sha256_update (TCSha256State_t s, const uint8_t *data, size_t datalen); /** * @brief SHA256 final procedure * Inserts the completed hash computation into digest * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * s == NULL, * s->iv == NULL, * digest == NULL * @note Assumes: s has been initialized by tc_sha256_init * digest points to at least TC_SHA256_DIGEST_SIZE bytes * @warning The state buffer 'leftover' is left in memory after processing * If your application intends to have sensitive data in this * buffer, remind to erase it after the data has been processed * @param digest unsigned eight bit integer * @param Sha256 state struct */ int tc_sha256_final(uint8_t *digest, TCSha256State_t s); #ifdef __cplusplus } #endif #endif /* __TC_SHA256_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/sha256.h
C
apache-2.0
5,017
/* utils.h - TinyCrypt interface to platform-dependent run-time operations */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Interface to platform-dependent run-time operations. * */ #ifndef __TC_UTILS_H__ #define __TC_UTILS_H__ #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Copy the the buffer 'from' to the buffer 'to'. * @return returns TC_CRYPTO_SUCCESS (1) * returns TC_CRYPTO_FAIL (0) if: * from_len > to_len. * * @param to OUT -- destination buffer * @param to_len IN -- length of destination buffer * @param from IN -- origin buffer * @param from_len IN -- length of origin buffer */ unsigned int _copy(uint8_t *to, unsigned int to_len, const uint8_t *from, unsigned int from_len); /** * @brief Set the value 'val' into the buffer 'to', 'len' times. * * @param to OUT -- destination buffer * @param val IN -- value to be set in 'to' * @param len IN -- number of times the value will be copied */ void _set(void *to, uint8_t val, unsigned int len); /* * @brief AES specific doubling function, which utilizes * the finite field used by AES. * @return Returns a^2 * * @param a IN/OUT -- value to be doubled */ uint8_t _double_byte(uint8_t a); /* * @brief Constant-time algorithm to compare if two sequences of bytes are equal * @return Returns 0 if equal, and non-zero otherwise * * @param a IN -- sequence of bytes a * @param b IN -- sequence of bytes b * @param size IN -- size of sequences a and b */ int _compare(const uint8_t *a, const uint8_t *b, size_t size); #ifdef __cplusplus } #endif #endif /* __TC_UTILS_H__ */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/include/tinycrypt/utils.h
C
apache-2.0
3,233
/* aes_decrypt.c - TinyCrypt implementation of AES decryption procedure */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/aes.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> static const uint8_t inv_sbox[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) { return tc_aes128_set_encrypt_key(s, k); } #define mult8(a)(_double_byte(_double_byte(_double_byte(a)))) #define mult9(a)(mult8(a)^(a)) #define multb(a)(mult8(a)^_double_byte(a)^(a)) #define multd(a)(mult8(a)^_double_byte(_double_byte(a))^(a)) #define multe(a)(mult8(a)^_double_byte(_double_byte(a))^_double_byte(a)) static inline void mult_row_column(uint8_t *out, const uint8_t *in) { out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]); out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]); out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]); out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]); } static inline void inv_mix_columns(uint8_t *s) { uint8_t t[Nb*Nk]; mult_row_column(t, s); mult_row_column(&t[Nb], s+Nb); mult_row_column(&t[2*Nb], s+(2*Nb)); mult_row_column(&t[3*Nb], s+(3*Nb)); (void)_copy(s, sizeof(t), t, sizeof(t)); } static inline void add_round_key(uint8_t *s, const unsigned int *k) { s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); } static inline void inv_sub_bytes(uint8_t *s) { unsigned int i; for (i = 0; i < (Nb*Nk); ++i) { s[i] = inv_sbox[s[i]]; } } /* * This inv_shift_rows also implements the matrix flip required for * inv_mix_columns, but performs it here to reduce the number of memory * operations. */ static inline void inv_shift_rows(uint8_t *s) { uint8_t t[Nb*Nk]; t[0] = s[0]; t[1] = s[13]; t[2] = s[10]; t[3] = s[7]; t[4] = s[4]; t[5] = s[1]; t[6] = s[14]; t[7] = s[11]; t[8] = s[8]; t[9] = s[5]; t[10] = s[2]; t[11] = s[15]; t[12] = s[12]; t[13] = s[9]; t[14] = s[6]; t[15] = s[3]; (void)_copy(s, sizeof(t), t, sizeof(t)); } int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) { uint8_t state[Nk*Nb]; unsigned int i; if (out == (uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (in == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (s == (TCAesKeySched_t) 0) { return TC_CRYPTO_FAIL; } (void)_copy(state, sizeof(state), in, sizeof(state)); add_round_key(state, s->words + Nb*Nr); for (i = Nr - 1; i > 0; --i) { inv_shift_rows(state); inv_sub_bytes(state); add_round_key(state, s->words + Nb*i); inv_mix_columns(state); } inv_shift_rows(state); inv_sub_bytes(state); add_round_key(state, s->words); (void)_copy(out, sizeof(state), state, sizeof(state)); /*zeroing out the state buffer */ _set(state, TC_ZERO_BYTE, sizeof(state)); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/aes_decrypt.c
C
apache-2.0
6,348
/* aes_encrypt.c - TinyCrypt implementation of AES encryption procedure */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/aes.h> #include <tinycrypt/utils.h> #include <tinycrypt/constants.h> static const uint8_t sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; static inline unsigned int rotword(unsigned int a) { return (((a) >> 24)|((a) << 8)); } #define subbyte(a, o)(sbox[((a) >> (o))&0xff] << (o)) #define subword(a)(subbyte(a, 24)|subbyte(a, 16)|subbyte(a, 8)|subbyte(a, 0)) int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k) { const unsigned int rconst[11] = { 0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000 }; unsigned int i; unsigned int t; if (s == (TCAesKeySched_t) 0) { return TC_CRYPTO_FAIL; } else if (k == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } for (i = 0; i < Nk; ++i) { s->words[i] = (k[Nb*i]<<24) | (k[Nb*i+1]<<16) | (k[Nb*i+2]<<8) | (k[Nb*i+3]); } for (; i < (Nb * (Nr + 1)); ++i) { t = s->words[i-1]; if ((i % Nk) == 0) { t = subword(rotword(t)) ^ rconst[i/Nk]; } s->words[i] = s->words[i-Nk] ^ t; } return TC_CRYPTO_SUCCESS; } static inline void add_round_key(uint8_t *s, const unsigned int *k) { s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); } static inline void sub_bytes(uint8_t *s) { unsigned int i; for (i = 0; i < (Nb * Nk); ++i) { s[i] = sbox[s[i]]; } } #define triple(a)(_double_byte(a)^(a)) static inline void mult_row_column(uint8_t *out, const uint8_t *in) { out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3]; out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3]; out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]); out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]); } static inline void mix_columns(uint8_t *s) { uint8_t t[Nb*Nk]; mult_row_column(t, s); mult_row_column(&t[Nb], s+Nb); mult_row_column(&t[2 * Nb], s + (2 * Nb)); mult_row_column(&t[3 * Nb], s + (3 * Nb)); (void) _copy(s, sizeof(t), t, sizeof(t)); } /* * This shift_rows also implements the matrix flip required for mix_columns, but * performs it here to reduce the number of memory operations. */ static inline void shift_rows(uint8_t *s) { uint8_t t[Nb * Nk]; t[0] = s[0]; t[1] = s[5]; t[2] = s[10]; t[3] = s[15]; t[4] = s[4]; t[5] = s[9]; t[6] = s[14]; t[7] = s[3]; t[8] = s[8]; t[9] = s[13]; t[10] = s[2]; t[11] = s[7]; t[12] = s[12]; t[13] = s[1]; t[14] = s[6]; t[15] = s[11]; (void) _copy(s, sizeof(t), t, sizeof(t)); } int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) { uint8_t state[Nk*Nb]; unsigned int i; if (out == (uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (in == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (s == (TCAesKeySched_t) 0) { return TC_CRYPTO_FAIL; } (void)_copy(state, sizeof(state), in, sizeof(state)); add_round_key(state, s->words); for (i = 0; i < (Nr - 1); ++i) { sub_bytes(state); shift_rows(state); mix_columns(state); add_round_key(state, s->words + Nb*(i+1)); } sub_bytes(state); shift_rows(state); add_round_key(state, s->words + Nb*(i+1)); (void)_copy(out, sizeof(state), state, sizeof(state)); /* zeroing out the state buffer */ _set(state, TC_ZERO_BYTE, sizeof(state)); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/aes_encrypt.c
C
apache-2.0
6,897
/* cbc_mode.c - TinyCrypt implementation of CBC mode encryption & decryption */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/cbc_mode.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) { uint8_t buffer[TC_AES_BLOCK_SIZE]; unsigned int n, m; /* input sanity check: */ if (out == (uint8_t *) 0 || in == (const uint8_t *) 0 || sched == (TCAesKeySched_t) 0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 || outlen != inlen + TC_AES_BLOCK_SIZE) { return TC_CRYPTO_FAIL; } /* copy iv to the buffer */ (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); /* copy iv to the output buffer */ (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); out += TC_AES_BLOCK_SIZE; for (n = m = 0; n < inlen; ++n) { buffer[m++] ^= *in++; if (m == TC_AES_BLOCK_SIZE) { (void)tc_aes_encrypt(buffer, buffer, sched); (void)_copy(out, TC_AES_BLOCK_SIZE, buffer, TC_AES_BLOCK_SIZE); out += TC_AES_BLOCK_SIZE; m = 0; } } return TC_CRYPTO_SUCCESS; } int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) { uint8_t buffer[TC_AES_BLOCK_SIZE]; const uint8_t *p; unsigned int n, m; /* sanity check the inputs */ if (out == (uint8_t *) 0 || in == (const uint8_t *) 0 || sched == (TCAesKeySched_t) 0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 || outlen != inlen - TC_AES_BLOCK_SIZE) { return TC_CRYPTO_FAIL; } /* * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are * contiguous. This allows for a very efficient decryption algorithm * that would not otherwise be possible. */ p = iv; for (n = m = 0; n < inlen; ++n) { if ((n % TC_AES_BLOCK_SIZE) == 0) { (void)tc_aes_decrypt(buffer, in, sched); in += TC_AES_BLOCK_SIZE; m = 0; } *out++ = buffer[m++] ^ *p++; } return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/cbc_mode.c
C
apache-2.0
3,824
/* ccm_mode.c - TinyCrypt implementation of CCM mode */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/ccm_mode.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> #include <stdio.h> int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, unsigned int nlen, unsigned int mlen) { /* input sanity check: */ if (c == (TCCcmMode_t) 0 || sched == (TCAesKeySched_t) 0 || nonce == (uint8_t *) 0) { return TC_CRYPTO_FAIL; } else if (nlen != 13) { return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/ } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) { return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/ } c->mlen = mlen; c->sched = sched; c->nonce = nonce; return TC_CRYPTO_SUCCESS; } /** * Variation of CBC-MAC mode used in CCM. */ static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen, unsigned int flag, TCAesKeySched_t sched) { unsigned int i; if (flag > 0) { T[0] ^= (uint8_t)(dlen >> 8); T[1] ^= (uint8_t)(dlen); dlen += 2; i = 2; } else { i = 0; } while (i < dlen) { T[i++ % (Nb * Nk)] ^= *data++; if (((i % (Nb * Nk)) == 0) || dlen == i) { (void) tc_aes_encrypt(T, T, sched); } } } /** * Variation of CTR mode used in CCM. * The CTR mode used by CCM is slightly different than the conventional CTR * mode (the counter is increased before encryption, instead of after * encryption). Besides, it is assumed that the counter is stored in the last * 2 bytes of the nonce. */ static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) { uint8_t buffer[TC_AES_BLOCK_SIZE]; uint8_t nonce[TC_AES_BLOCK_SIZE]; uint16_t block_num; unsigned int i; /* input sanity check: */ if (out == (uint8_t *) 0 || in == (uint8_t *) 0 || ctr == (uint8_t *) 0 || sched == (TCAesKeySched_t) 0 || inlen == 0 || outlen == 0 || outlen != inlen) { return TC_CRYPTO_FAIL; } /* copy the counter to the nonce */ (void) _copy(nonce, sizeof(nonce), ctr, sizeof(nonce)); /* select the last 2 bytes of the nonce to be incremented */ block_num = (uint16_t) ((nonce[14] << 8)|(nonce[15])); for (i = 0; i < inlen; ++i) { if ((i % (TC_AES_BLOCK_SIZE)) == 0) { block_num++; nonce[14] = (uint8_t)(block_num >> 8); nonce[15] = (uint8_t)(block_num); if (!tc_aes_encrypt(buffer, nonce, sched)) { return TC_CRYPTO_FAIL; } } /* update the output */ *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++; } /* update the counter */ ctr[14] = nonce[14]; ctr[15] = nonce[15]; return TC_CRYPTO_SUCCESS; } int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) { /* input sanity check: */ if ((out == (uint8_t *) 0) || (c == (TCCcmMode_t) 0) || ((plen > 0) && (payload == (uint8_t *) 0)) || ((alen > 0) && (associated_data == (uint8_t *) 0)) || (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ (olen < (plen + c->mlen))) { /* invalid output buffer size */ return TC_CRYPTO_FAIL; } uint8_t b[Nb * Nk]; uint8_t tag[Nb * Nk]; unsigned int i; /* GENERATING THE AUTHENTICATION TAG: */ /* formatting the sequence b for authentication: */ b[0] = ((alen > 0) ? 0x40:0) | (((c->mlen - 2) / 2 << 3)) | (1); for (i = 1; i <= 13; ++i) { b[i] = c->nonce[i - 1]; } b[14] = (uint8_t)(plen >> 8); b[15] = (uint8_t)(plen); /* computing the authentication tag using cbc-mac: */ (void) tc_aes_encrypt(tag, b, c->sched); if (alen > 0) { ccm_cbc_mac(tag, associated_data, alen, 1, c->sched); } if (plen > 0) { ccm_cbc_mac(tag, payload, plen, 0, c->sched); } /* ENCRYPTION: */ /* formatting the sequence b for encryption: */ b[0] = 1; /* q - 1 = 2 - 1 = 1 */ b[14] = b[15] = TC_ZERO_BYTE; /* encrypting payload using ctr mode: */ ccm_ctr_mode(out, plen, payload, plen, b, c->sched); b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/ /* encrypting b and adding the tag to the output: */ (void) tc_aes_encrypt(b, b, c->sched); out += plen; for (i = 0; i < c->mlen; ++i) { *out++ = tag[i] ^ b[i]; } return TC_CRYPTO_SUCCESS; } int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) { /* input sanity check: */ if ((plen <= alen) || (out == (uint8_t *) 0) || (c == (TCCcmMode_t) 0) || ((plen > 0) && (payload == (uint8_t *) 0)) || ((alen > 0) && (associated_data == (uint8_t *) 0)) || (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ (olen < plen - c->mlen)) { /* invalid output buffer size */ return TC_CRYPTO_FAIL; } uint8_t b[Nb * Nk]; uint8_t tag[Nb * Nk]; unsigned int i; /* DECRYPTION: */ /* formatting the sequence b for decryption: */ b[0] = 1; /* q - 1 = 2 - 1 = 1 */ for (i = 1; i < 14; ++i) { b[i] = c->nonce[i - 1]; } b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */ /* decrypting payload using ctr mode: */ ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched); b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */ /* encrypting b and restoring the tag from input: */ (void) tc_aes_encrypt(b, b, c->sched); for (i = 0; i < c->mlen; ++i) { tag[i] = *(payload + plen - c->mlen + i) ^ b[i]; } /* VERIFYING THE AUTHENTICATION TAG: */ /* formatting the sequence b for authentication: */ b[0] = ((alen > 0) ? 0x40:0)|(((c->mlen - 2) / 2 << 3)) | (1); for (i = 1; i < 14; ++i) { b[i] = c->nonce[i - 1]; } b[14] = (uint8_t)((plen - c->mlen) >> 8); b[15] = (uint8_t)(plen - c->mlen); /* computing the authentication tag using cbc-mac: */ (void) tc_aes_encrypt(b, b, c->sched); if (alen > 0) { ccm_cbc_mac(b, associated_data, alen, 1, c->sched); } if (plen > 0) { ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched); } /* comparing the received tag and the computed one: */ if (_compare(b, tag, c->mlen) == 0) { return TC_CRYPTO_SUCCESS; } else { /* erase the decrypted buffer in case of mac validation failure: */ _set(out, 0, plen - c->mlen); return TC_CRYPTO_FAIL; } }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ccm_mode.c
C
apache-2.0
8,131
/* cmac_mode.c - TinyCrypt CMAC mode implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/aes.h> #include <tinycrypt/cmac_mode.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> /* max number of calls until change the key (2^48).*/ const static uint64_t MAX_CALLS = ((uint64_t)1 << 48); /* * gf_wrap -- In our implementation, GF(2^128) is represented as a 16 byte * array with byte 0 the most significant and byte 15 the least significant. * High bit carry reduction is based on the primitive polynomial * * X^128 + X^7 + X^2 + X + 1, * * which leads to the reduction formula X^128 = X^7 + X^2 + X + 1. Indeed, * since 0 = (X^128 + X^7 + X^2 + 1) mod (X^128 + X^7 + X^2 + X + 1) and since * addition of polynomials with coefficients in Z/Z(2) is just XOR, we can * add X^128 to both sides to get * * X^128 = (X^7 + X^2 + X + 1) mod (X^128 + X^7 + X^2 + X + 1) * * and the coefficients of the polynomial on the right hand side form the * string 1000 0111 = 0x87, which is the value of gf_wrap. * * This gets used in the following way. Doubling in GF(2^128) is just a left * shift by 1 bit, except when the most significant bit is 1. In the latter * case, the relation X^128 = X^7 + X^2 + X + 1 says that the high order bit * that overflows beyond 128 bits can be replaced by addition of * X^7 + X^2 + X + 1 <--> 0x87 to the low order 128 bits. Since addition * in GF(2^128) is represented by XOR, we therefore only have to XOR 0x87 * into the low order byte after a left shift when the starting high order * bit is 1. */ const unsigned char gf_wrap = 0x87; /* * assumes: out != NULL and points to a GF(2^n) value to receive the * doubled value; * in != NULL and points to a 16 byte GF(2^n) value * to double; * the in and out buffers do not overlap. * effects: doubles the GF(2^n) value pointed to by "in" and places * the result in the GF(2^n) value pointed to by "out." */ void gf_double(uint8_t *out, uint8_t *in) { /* start with low order byte */ uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1); /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */ uint8_t carry = (in[0] >> 7) ? gf_wrap : 0; out += (TC_AES_BLOCK_SIZE - 1); for (;;) { *out-- = (*x << 1) ^ carry; if (x == in) { break; } carry = *x-- >> 7; } } int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched) { /* input sanity check: */ if (s == (TCCmacState_t) 0 || key == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } /* put s into a known state */ _set(s, 0, sizeof(*s)); s->sched = sched; /* configure the encryption key used by the underlying block cipher */ tc_aes128_set_encrypt_key(s->sched, key); /* compute s->K1 and s->K2 from s->iv using s->keyid */ _set(s->iv, 0, TC_AES_BLOCK_SIZE); tc_aes_encrypt(s->iv, s->iv, s->sched); gf_double (s->K1, s->iv); gf_double (s->K2, s->K1); /* reset s->iv to 0 in case someone wants to compute now */ tc_cmac_init(s); return TC_CRYPTO_SUCCESS; } int tc_cmac_erase(TCCmacState_t s) { if (s == (TCCmacState_t) 0) { return TC_CRYPTO_FAIL; } /* destroy the current state */ _set(s, 0, sizeof(*s)); return TC_CRYPTO_SUCCESS; } int tc_cmac_init(TCCmacState_t s) { /* input sanity check: */ if (s == (TCCmacState_t) 0) { return TC_CRYPTO_FAIL; } /* CMAC starts with an all zero initialization vector */ _set(s->iv, 0, TC_AES_BLOCK_SIZE); /* and the leftover buffer is empty */ _set(s->leftover, 0, TC_AES_BLOCK_SIZE); s->leftover_offset = 0; /* Set countdown to max number of calls allowed before re-keying: */ s->countdown = MAX_CALLS; return TC_CRYPTO_SUCCESS; } int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t data_length) { unsigned int i; /* input sanity check: */ if (s == (TCCmacState_t) 0) { return TC_CRYPTO_FAIL; } if (data_length == 0) { return TC_CRYPTO_SUCCESS; } if (data == (const uint8_t *) 0) { return TC_CRYPTO_FAIL; } if (s->countdown == 0) { return TC_CRYPTO_FAIL; } s->countdown--; if (s->leftover_offset > 0) { /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */ size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset; if (data_length < remaining_space) { /* still not enough data to encrypt this time either */ _copy(&s->leftover[s->leftover_offset], data_length, data, data_length); s->leftover_offset += data_length; return TC_CRYPTO_SUCCESS; } /* leftover block is now full; encrypt it first */ _copy(&s->leftover[s->leftover_offset], remaining_space, data, remaining_space); data_length -= remaining_space; data += remaining_space; s->leftover_offset = 0; for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { s->iv[i] ^= s->leftover[i]; } tc_aes_encrypt(s->iv, s->iv, s->sched); } /* CBC encrypt each (except the last) of the data blocks */ while (data_length > TC_AES_BLOCK_SIZE) { for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { s->iv[i] ^= data[i]; } tc_aes_encrypt(s->iv, s->iv, s->sched); data += TC_AES_BLOCK_SIZE; data_length -= TC_AES_BLOCK_SIZE; } if (data_length > 0) { /* save leftover data for next time */ _copy(s->leftover, data_length, data, data_length); s->leftover_offset = data_length; } return TC_CRYPTO_SUCCESS; } int tc_cmac_final(uint8_t *tag, TCCmacState_t s) { uint8_t *k; unsigned int i; /* input sanity check: */ if (tag == (uint8_t *) 0 || s == (TCCmacState_t) 0) { return TC_CRYPTO_FAIL; } if (s->leftover_offset == TC_AES_BLOCK_SIZE) { /* the last message block is a full-sized block */ k = (uint8_t *) s->K1; } else { /* the final message block is not a full-sized block */ size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset; _set(&s->leftover[s->leftover_offset], 0, remaining); s->leftover[s->leftover_offset] = TC_CMAC_PADDING; k = (uint8_t *) s->K2; } for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { s->iv[i] ^= s->leftover[i] ^ k[i]; } tc_aes_encrypt(tag, s->iv, s->sched); /* erasing state: */ tc_cmac_erase(s); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/cmac_mode.c
C
apache-2.0
7,757
/* ctr_mode.c - TinyCrypt CTR mode implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/constants.h> #include <tinycrypt/ctr_mode.h> #include <tinycrypt/utils.h> int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) { uint8_t buffer[TC_AES_BLOCK_SIZE]; uint8_t nonce[TC_AES_BLOCK_SIZE]; unsigned int block_num; unsigned int i; /* input sanity check: */ if (out == (uint8_t *) 0 || in == (uint8_t *) 0 || ctr == (uint8_t *) 0 || sched == (TCAesKeySched_t) 0 || inlen == 0 || outlen == 0 || outlen != inlen) { return TC_CRYPTO_FAIL; } /* copy the ctr to the nonce */ (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce)); /* select the last 4 bytes of the nonce to be incremented */ block_num = (nonce[12] << 24) | (nonce[13] << 16) | (nonce[14] << 8) | (nonce[15]); for (i = 0; i < inlen; ++i) { if ((i % (TC_AES_BLOCK_SIZE)) == 0) { /* encrypt data using the current nonce */ if (tc_aes_encrypt(buffer, nonce, sched)) { block_num++; nonce[12] = (uint8_t)(block_num >> 24); nonce[13] = (uint8_t)(block_num >> 16); nonce[14] = (uint8_t)(block_num >> 8); nonce[15] = (uint8_t)(block_num); } else { return TC_CRYPTO_FAIL; } } /* update the output */ *out++ = buffer[i%(TC_AES_BLOCK_SIZE)] ^ *in++; } /* update the counter */ ctr[12] = nonce[12]; ctr[13] = nonce[13]; ctr[14] = nonce[14]; ctr[15] = nonce[15]; return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ctr_mode.c
C
apache-2.0
3,113
/* ctr_prng.c - TinyCrypt implementation of CTR-PRNG */ /* * Copyright (c) 2016, Chris Morrison * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/ctr_prng.h> #include <tinycrypt/utils.h> #include <tinycrypt/constants.h> #include <string.h> /* * This PRNG is based on the CTR_DRBG described in Recommendation for Random * Number Generation Using Deterministic Random Bit Generators, * NIST SP 800-90A Rev. 1. * * Annotations to particular steps (e.g. 10.2.1.2 Step 1) refer to the steps * described in that document. * */ /** * @brief Array incrementer * Treats the supplied array as one contiguous number (MSB in arr[0]), and * increments it by one * @return none * @param arr IN/OUT -- array to be incremented * @param len IN -- size of arr in bytes */ static void arrInc(uint8_t arr[], unsigned int len) { unsigned int i; if (0 != arr) { for (i = len; i > 0U; i--) { if (++arr[i-1] != 0U) { break; } } } } /** * @brief CTR PRNG update * Updates the internal state of supplied the CTR PRNG context * increments it by one * @return none * @note Assumes: providedData is (TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE) bytes long * @param ctx IN/OUT -- CTR PRNG state * @param providedData IN -- data used when updating the internal state */ static void tc_ctr_prng_update(TCCtrPrng_t * const ctx, uint8_t const * const providedData) { if (0 != ctx) { /* 10.2.1.2 step 1 */ uint8_t temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; unsigned int len = 0U; /* 10.2.1.2 step 2 */ while (len < sizeof temp) { unsigned int blocklen = sizeof(temp) - len; uint8_t output_block[TC_AES_BLOCK_SIZE]; /* 10.2.1.2 step 2.1 */ arrInc(ctx->V, sizeof ctx->V); /* 10.2.1.2 step 2.2 */ if (blocklen > TC_AES_BLOCK_SIZE) { blocklen = TC_AES_BLOCK_SIZE; } (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key); /* 10.2.1.2 step 2.3/step 3 */ memcpy(&(temp[len]), output_block, blocklen); len += blocklen; } /* 10.2.1.2 step 4 */ if (0 != providedData) { unsigned int i; for (i = 0U; i < sizeof temp; i++) { temp[i] ^= providedData[i]; } } /* 10.2.1.2 step 5 */ (void)tc_aes128_set_encrypt_key(&ctx->key, temp); /* 10.2.1.2 step 6 */ memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE); } } int tc_ctr_prng_init(TCCtrPrng_t * const ctx, uint8_t const * const entropy, unsigned int entropyLen, uint8_t const * const personalization, unsigned int pLen) { int result = TC_CRYPTO_FAIL; unsigned int i; uint8_t personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; uint8_t zeroArr[TC_AES_BLOCK_SIZE] = {0U}; if (0 != personalization) { /* 10.2.1.3.1 step 1 */ unsigned int len = pLen; if (len > sizeof personalization_buf) { len = sizeof personalization_buf; } /* 10.2.1.3.1 step 2 */ memcpy(personalization_buf, personalization, len); } if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) { /* 10.2.1.3.1 step 3 */ memcpy(seed_material, entropy, sizeof seed_material); for (i = 0U; i < sizeof seed_material; i++) { seed_material[i] ^= personalization_buf[i]; } /* 10.2.1.3.1 step 4 */ (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr); /* 10.2.1.3.1 step 5 */ memset(ctx->V, 0x00, sizeof ctx->V); /* 10.2.1.3.1 step 6 */ tc_ctr_prng_update(ctx, seed_material); /* 10.2.1.3.1 step 7 */ ctx->reseedCount = 1U; result = TC_CRYPTO_SUCCESS; } return result; } int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, uint8_t const * const entropy, unsigned int entropyLen, uint8_t const * const additional_input, unsigned int additionallen) { unsigned int i; int result = TC_CRYPTO_FAIL; uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; if (0 != additional_input) { /* 10.2.1.4.1 step 1 */ unsigned int len = additionallen; if (len > sizeof additional_input_buf) { len = sizeof additional_input_buf; } /* 10.2.1.4.1 step 2 */ memcpy(additional_input_buf, additional_input, len); } unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE; if ((0 != ctx) && (entropyLen >= seedlen)) { /* 10.2.1.4.1 step 3 */ memcpy(seed_material, entropy, sizeof seed_material); for (i = 0U; i < sizeof seed_material; i++) { seed_material[i] ^= additional_input_buf[i]; } /* 10.2.1.4.1 step 4 */ tc_ctr_prng_update(ctx, seed_material); /* 10.2.1.4.1 step 5 */ ctx->reseedCount = 1U; result = TC_CRYPTO_SUCCESS; } return result; } int tc_ctr_prng_generate(TCCtrPrng_t * const ctx, uint8_t const * const additional_input, unsigned int additionallen, uint8_t * const out, unsigned int outlen) { /* 2^48 - see section 10.2.1 */ static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL; /* 2^19 bits - see section 10.2.1 */ static const unsigned int MAX_BYTES_PER_REQ = 65536U; unsigned int result = TC_CRYPTO_FAIL; if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) { /* 10.2.1.5.1 step 1 */ if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) { result = TC_CTR_PRNG_RESEED_REQ; } else { uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; if (0 != additional_input) { /* 10.2.1.5.1 step 2 */ unsigned int len = additionallen; if (len > sizeof additional_input_buf) { len = sizeof additional_input_buf; } memcpy(additional_input_buf, additional_input, len); tc_ctr_prng_update(ctx, additional_input_buf); } /* 10.2.1.5.1 step 3 - implicit */ /* 10.2.1.5.1 step 4 */ unsigned int len = 0U; while (len < outlen) { unsigned int blocklen = outlen - len; uint8_t output_block[TC_AES_BLOCK_SIZE]; /* 10.2.1.5.1 step 4.1 */ arrInc(ctx->V, sizeof ctx->V); /* 10.2.1.5.1 step 4.2 */ (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key); /* 10.2.1.5.1 step 4.3/step 5 */ if (blocklen > TC_AES_BLOCK_SIZE) { blocklen = TC_AES_BLOCK_SIZE; } memcpy(&(out[len]), output_block, blocklen); len += blocklen; } /* 10.2.1.5.1 step 6 */ tc_ctr_prng_update(ctx, additional_input_buf); /* 10.2.1.5.1 step 7 */ ctx->reseedCount++; /* 10.2.1.5.1 step 8 */ result = TC_CRYPTO_SUCCESS; } } return result; } void tc_ctr_prng_uninstantiate(TCCtrPrng_t * const ctx) { if (0 != ctx) { memset(ctx->key.words, 0x00, sizeof ctx->key.words); memset(ctx->V, 0x00, sizeof ctx->V); ctx->reseedCount = 0U; } }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ctr_prng.c
C
apache-2.0
7,988
/* ecc.c - TinyCrypt implementation of common ECC functions */ /* * Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/ecc.h> #include <tinycrypt/ecc_platform_specific.h> #include <string.h> /* IMPORTANT: Make sure a cryptographically-secure PRNG is set and the platform * has access to enough entropy in order to feed the PRNG regularly. */ #if default_RNG_defined static uECC_RNG_Function g_rng_function = &default_CSPRNG; #else static uECC_RNG_Function g_rng_function = 0; #endif void uECC_set_rng(uECC_RNG_Function rng_function) { g_rng_function = rng_function; } uECC_RNG_Function uECC_get_rng(void) { return g_rng_function; } int uECC_curve_private_key_size(uECC_Curve curve) { return BITS_TO_BYTES(curve->num_n_bits); } int uECC_curve_public_key_size(uECC_Curve curve) { return 2 * curve->num_bytes; } void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) { wordcount_t i; for (i = 0; i < num_words; ++i) { vli[i] = 0; } } uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words) { uECC_word_t bits = 0; wordcount_t i; for (i = 0; i < num_words; ++i) { bits |= vli[i]; } return (bits == 0); } uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit) { return (vli[bit >> uECC_WORD_BITS_SHIFT] & ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK))); } /* Counts the number of words in vli. */ static wordcount_t vli_numDigits(const uECC_word_t *vli, const wordcount_t max_words) { wordcount_t i; /* Search from the end until we find a non-zero digit. We do it in reverse * because we expect that most digits will be nonzero. */ for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) { } return (i + 1); } bitcount_t uECC_vli_numBits(const uECC_word_t *vli, const wordcount_t max_words) { uECC_word_t i; uECC_word_t digit; wordcount_t num_digits = vli_numDigits(vli, max_words); if (num_digits == 0) { return 0; } digit = vli[num_digits - 1]; for (i = 0; digit; ++i) { digit >>= 1; } return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i); } void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, wordcount_t num_words) { wordcount_t i; for (i = 0; i < num_words; ++i) { dest[i] = src[i]; } } cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) { wordcount_t i; for (i = num_words - 1; i >= 0; --i) { if (left[i] > right[i]) { return 1; } else if (left[i] < right[i]) { return -1; } } return 0; } uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) { uECC_word_t diff = 0; wordcount_t i; for (i = num_words - 1; i >= 0; --i) { diff |= (left[i] ^ right[i]); } return !(diff == 0); } uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond) { return (p_true*(cond)) | (p_false*(!cond)); } /* Computes result = left - right, returning borrow, in constant time. * Can modify in place. */ uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) { uECC_word_t borrow = 0; wordcount_t i; for (i = 0; i < num_words; ++i) { uECC_word_t diff = left[i] - right[i] - borrow; uECC_word_t val = (diff > left[i]); borrow = cond_set(val, borrow, (diff != left[i])); result[i] = diff; } return borrow; } /* Computes result = left + right, returning carry, in constant time. * Can modify in place. */ static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) { uECC_word_t carry = 0; wordcount_t i; for (i = 0; i < num_words; ++i) { uECC_word_t sum = left[i] + right[i] + carry; uECC_word_t val = (sum < left[i]); carry = cond_set(val, carry, (sum != left[i])); result[i] = sum; } return carry; } cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) { uECC_word_t tmp[NUM_ECC_WORDS]; uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words); uECC_word_t equal = uECC_vli_isZero(tmp, num_words); return (!equal - 2 * neg); } /* Computes vli = vli >> 1. */ static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) { uECC_word_t *end = vli; uECC_word_t carry = 0; vli += num_words; while (vli-- > end) { uECC_word_t temp = *vli; *vli = (temp >> 1) | carry; carry = temp << (uECC_WORD_BITS - 1); } } static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, uECC_word_t *r1, uECC_word_t *r2) { uECC_dword_t p = (uECC_dword_t)a * b; uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0; r01 += p; *r2 += (r01 < p); *r1 = r01 >> uECC_WORD_BITS; *r0 = (uECC_word_t)r01; } /* Computes result = left * right. Result must be 2 * num_words long. */ static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) { uECC_word_t r0 = 0; uECC_word_t r1 = 0; uECC_word_t r2 = 0; wordcount_t i, k; /* Compute each digit of result in sequence, maintaining the carries. */ for (k = 0; k < num_words; ++k) { for (i = 0; i <= k; ++i) { muladd(left[i], right[k - i], &r0, &r1, &r2); } result[k] = r0; r0 = r1; r1 = r2; r2 = 0; } for (k = num_words; k < num_words * 2 - 1; ++k) { for (i = (k + 1) - num_words; i < num_words; ++i) { muladd(left[i], right[k - i], &r0, &r1, &r2); } result[k] = r0; r0 = r1; r1 = r2; r2 = 0; } result[num_words * 2 - 1] = r0; } void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) { uECC_word_t carry = uECC_vli_add(result, left, right, num_words); if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) { /* result > mod (result = mod + remainder), so subtract mod to get * remainder. */ uECC_vli_sub(result, result, mod, num_words); } } void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) { uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words); if (l_borrow) { /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x, * we can get the correct result from result + mod (with overflow). */ uECC_vli_add(result, result, mod, num_words); } } /* Computes result = product % mod, where product is 2N words long. */ /* Currently only designed to work for curve_p or curve_n. */ void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, const uECC_word_t *mod, wordcount_t num_words) { uECC_word_t mod_multiple[2 * NUM_ECC_WORDS]; uECC_word_t tmp[2 * NUM_ECC_WORDS]; uECC_word_t *v[2] = {tmp, product}; uECC_word_t index; /* Shift mod so its highest set bit is at the maximum position. */ bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words); wordcount_t word_shift = shift / uECC_WORD_BITS; wordcount_t bit_shift = shift % uECC_WORD_BITS; uECC_word_t carry = 0; uECC_vli_clear(mod_multiple, word_shift); if (bit_shift > 0) { for(index = 0; index < (uECC_word_t)num_words; ++index) { mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry; carry = mod[index] >> (uECC_WORD_BITS - bit_shift); } } else { uECC_vli_set(mod_multiple + word_shift, mod, num_words); } for (index = 1; shift >= 0; --shift) { uECC_word_t borrow = 0; wordcount_t i; for (i = 0; i < num_words * 2; ++i) { uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow; if (diff != v[index][i]) { borrow = (diff > v[index][i]); } v[1 - index][i] = diff; } /* Swap the index if there was no borrow */ index = !(index ^ borrow); uECC_vli_rshift1(mod_multiple, num_words); mod_multiple[num_words - 1] |= mod_multiple[num_words] << (uECC_WORD_BITS - 1); uECC_vli_rshift1(mod_multiple + num_words, num_words); } uECC_vli_set(result, v[index], num_words); } void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) { uECC_word_t product[2 * NUM_ECC_WORDS]; uECC_vli_mult(product, left, right, num_words); uECC_vli_mmod(result, product, mod, num_words); } void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, uECC_Curve curve) { uECC_word_t product[2 * NUM_ECC_WORDS]; uECC_vli_mult(product, left, right, curve->num_words); curve->mmod_fast(result, product); } static void uECC_vli_modSquare_fast(uECC_word_t *result, const uECC_word_t *left, uECC_Curve curve) { uECC_vli_modMult_fast(result, left, left, curve); } #define EVEN(vli) (!(vli[0] & 1)) static void vli_modInv_update(uECC_word_t *uv, const uECC_word_t *mod, wordcount_t num_words) { uECC_word_t carry = 0; if (!EVEN(uv)) { carry = uECC_vli_add(uv, uv, mod, num_words); } uECC_vli_rshift1(uv, num_words); if (carry) { uv[num_words - 1] |= HIGH_BIT_SET; } } void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, const uECC_word_t *mod, wordcount_t num_words) { uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS]; uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS]; cmpresult_t cmpResult; if (uECC_vli_isZero(input, num_words)) { uECC_vli_clear(result, num_words); return; } uECC_vli_set(a, input, num_words); uECC_vli_set(b, mod, num_words); uECC_vli_clear(u, num_words); u[0] = 1; uECC_vli_clear(v, num_words); while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) { if (EVEN(a)) { uECC_vli_rshift1(a, num_words); vli_modInv_update(u, mod, num_words); } else if (EVEN(b)) { uECC_vli_rshift1(b, num_words); vli_modInv_update(v, mod, num_words); } else if (cmpResult > 0) { uECC_vli_sub(a, a, b, num_words); uECC_vli_rshift1(a, num_words); if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) { uECC_vli_add(u, u, mod, num_words); } uECC_vli_sub(u, u, v, num_words); vli_modInv_update(u, mod, num_words); } else { uECC_vli_sub(b, b, a, num_words); uECC_vli_rshift1(b, num_words); if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) { uECC_vli_add(v, v, mod, num_words); } uECC_vli_sub(v, v, u, num_words); vli_modInv_update(v, mod, num_words); } } uECC_vli_set(result, u, num_words); } /* ------ Point operations ------ */ void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * Z1, uECC_Curve curve) { /* t1 = X, t2 = Y, t3 = Z */ uECC_word_t t4[NUM_ECC_WORDS]; uECC_word_t t5[NUM_ECC_WORDS]; wordcount_t num_words = curve->num_words; if (uECC_vli_isZero(Z1, num_words)) { return; } uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */ uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */ uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */ uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */ uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */ uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */ uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */ uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */ uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */ uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */ uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */ if (uECC_vli_testBit(X1, 0)) { uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words); uECC_vli_rshift1(X1, num_words); X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1); } else { uECC_vli_rshift1(X1, num_words); } /* t1 = 3/2*(x1^2 - z1^4) = B */ uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */ uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */ uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */ uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */ uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */ /* t4 = B * (A - x3) - y1^4 = y3: */ uECC_vli_modSub(t4, X1, t4, curve->p, num_words); uECC_vli_set(X1, Z1, num_words); uECC_vli_set(Z1, Y1, num_words); uECC_vli_set(Y1, t4, num_words); } void x_side_default(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve) { uECC_word_t _3[NUM_ECC_WORDS] = {3}; /* -a = 3 */ wordcount_t num_words = curve->num_words; uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */ uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */ uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */ /* r = x^3 - 3x + b: */ uECC_vli_modAdd(result, result, curve->b, curve->p, num_words); } uECC_Curve uECC_secp256r1(void) { return &curve_secp256r1; } void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int*product) { unsigned int tmp[NUM_ECC_WORDS]; int carry; /* t */ uECC_vli_set(result, product, NUM_ECC_WORDS); /* s1 */ tmp[0] = tmp[1] = tmp[2] = 0; tmp[3] = product[11]; tmp[4] = product[12]; tmp[5] = product[13]; tmp[6] = product[14]; tmp[7] = product[15]; carry = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS); carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); /* s2 */ tmp[3] = product[12]; tmp[4] = product[13]; tmp[5] = product[14]; tmp[6] = product[15]; tmp[7] = 0; carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS); carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); /* s3 */ tmp[0] = product[8]; tmp[1] = product[9]; tmp[2] = product[10]; tmp[3] = tmp[4] = tmp[5] = 0; tmp[6] = product[14]; tmp[7] = product[15]; carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); /* s4 */ tmp[0] = product[9]; tmp[1] = product[10]; tmp[2] = product[11]; tmp[3] = product[13]; tmp[4] = product[14]; tmp[5] = product[15]; tmp[6] = product[13]; tmp[7] = product[8]; carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); /* d1 */ tmp[0] = product[11]; tmp[1] = product[12]; tmp[2] = product[13]; tmp[3] = tmp[4] = tmp[5] = 0; tmp[6] = product[8]; tmp[7] = product[10]; carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); /* d2 */ tmp[0] = product[12]; tmp[1] = product[13]; tmp[2] = product[14]; tmp[3] = product[15]; tmp[4] = tmp[5] = 0; tmp[6] = product[9]; tmp[7] = product[11]; carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); /* d3 */ tmp[0] = product[13]; tmp[1] = product[14]; tmp[2] = product[15]; tmp[3] = product[8]; tmp[4] = product[9]; tmp[5] = product[10]; tmp[6] = 0; tmp[7] = product[12]; carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); /* d4 */ tmp[0] = product[14]; tmp[1] = product[15]; tmp[2] = 0; tmp[3] = product[9]; tmp[4] = product[10]; tmp[5] = product[11]; tmp[6] = 0; tmp[7] = product[13]; carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); if (carry < 0) { do { carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS); } while (carry < 0); } else { while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) { carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS); } } } uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve) { return uECC_vli_isZero(point, curve->num_words * 2); } void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z, uECC_Curve curve) { uECC_word_t t1[NUM_ECC_WORDS]; uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */ uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */ uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */ uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */ } /* P = (x1, y1) => 2P, (x2, y2) => P' */ static void XYcZ_initial_double(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, const uECC_word_t * const initial_Z, uECC_Curve curve) { uECC_word_t z[NUM_ECC_WORDS]; wordcount_t num_words = curve->num_words; if (initial_Z) { uECC_vli_set(z, initial_Z, num_words); } else { uECC_vli_clear(z, num_words); z[0] = 1; } uECC_vli_set(X2, X1, num_words); uECC_vli_set(Y2, Y1, num_words); apply_z(X1, Y1, z, curve); curve->double_jacobian(X1, Y1, z, curve); apply_z(X2, Y2, z, curve); } void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, uECC_Curve curve) { /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ uECC_word_t t5[NUM_ECC_WORDS]; wordcount_t num_words = curve->num_words; uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */ uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */ uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */ uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */ uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */ uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */ uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */ uECC_vli_set(X2, t5, num_words); } /* Input P = (x1, y1, Z), Q = (x2, y2, Z) Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3) or P => P - Q, Q => P + Q */ static void XYcZ_addC(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, uECC_Curve curve) { /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ uECC_word_t t5[NUM_ECC_WORDS]; uECC_word_t t6[NUM_ECC_WORDS]; uECC_word_t t7[NUM_ECC_WORDS]; wordcount_t num_words = curve->num_words; uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */ uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */ uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */ uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */ uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */ uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */ uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */ /* t4 = (y2 - y1)*(B - x3) - E = y3: */ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */ uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */ uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */ uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */ /* t2 = (y2+y1)*(x3' - B) - E = y3': */ uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words); uECC_vli_set(X1, t7, num_words); } void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point, const uECC_word_t * scalar, const uECC_word_t * initial_Z, bitcount_t num_bits, uECC_Curve curve) { /* R0 and R1 */ uECC_word_t Rx[2][NUM_ECC_WORDS]; uECC_word_t Ry[2][NUM_ECC_WORDS]; uECC_word_t z[NUM_ECC_WORDS]; bitcount_t i; uECC_word_t nb; wordcount_t num_words = curve->num_words; uECC_vli_set(Rx[1], point, num_words); uECC_vli_set(Ry[1], point + num_words, num_words); XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve); for (i = num_bits - 2; i > 0; --i) { nb = !uECC_vli_testBit(scalar, i); XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); } nb = !uECC_vli_testBit(scalar, 0); XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); /* Find final 1/Z value. */ uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */ uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */ uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */ uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0))*/ /* yP / (xP * Yb * (X1 - X0)) */ uECC_vli_modMult_fast(z, z, point + num_words, curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */ uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve); /* End 1/Z calculation */ XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); apply_z(Rx[0], Ry[0], z, curve); uECC_vli_set(result, Rx[0], num_words); uECC_vli_set(result + num_words, Ry[0], num_words); } uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0, uECC_word_t *k1, uECC_Curve curve) { wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); bitcount_t num_n_bits = curve->num_n_bits; uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) || (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) && uECC_vli_testBit(k0, num_n_bits)); uECC_vli_add(k1, k0, curve->n, num_n_words); return carry; } uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, uECC_word_t *private_key, uECC_Curve curve) { uECC_word_t tmp1[NUM_ECC_WORDS]; uECC_word_t tmp2[NUM_ECC_WORDS]; uECC_word_t *p2[2] = {tmp1, tmp2}; uECC_word_t carry; /* Regularize the bitcount for the private key so that attackers cannot * use a side channel attack to learn the number of leading zeros. */ carry = regularize_k(private_key, tmp1, tmp2, curve); EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve); if (EccPoint_isZero(result, curve)) { return 0; } return 1; } /* Converts an integer in uECC native format to big-endian bytes. */ void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, const unsigned int *native) { wordcount_t i; for (i = 0; i < num_bytes; ++i) { unsigned b = num_bytes - 1 - i; bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)); } } /* Converts big-endian bytes to an integer in uECC native format. */ void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes, int num_bytes) { wordcount_t i; uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE); for (i = 0; i < num_bytes; ++i) { unsigned b = num_bytes - 1 - i; native[b / uECC_WORD_SIZE] |= (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE)); } } int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top, wordcount_t num_words) { uECC_word_t mask = (uECC_word_t)-1; uECC_word_t tries; bitcount_t num_bits = uECC_vli_numBits(top, num_words); if (!g_rng_function) { return 0; } for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) { return 0; } random[num_words - 1] &= mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits)); if (!uECC_vli_isZero(random, num_words) && uECC_vli_cmp(top, random, num_words) == 1) { return 1; } } return 0; } int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) { uECC_word_t tmp1[NUM_ECC_WORDS]; uECC_word_t tmp2[NUM_ECC_WORDS]; wordcount_t num_words = curve->num_words; /* The point at infinity is invalid. */ if (EccPoint_isZero(point, curve)) { return -1; } /* x and y must be smaller than p. */ if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 || uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) { return -2; } uECC_vli_modSquare_fast(tmp1, point + num_words, curve); curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */ /* Make sure that y^2 == x^3 + ax + b */ if (uECC_vli_equal(tmp1, tmp2, num_words) != 0) return -3; return 0; } int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) { uECC_word_t _public[NUM_ECC_WORDS * 2]; uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); uECC_vli_bytesToNative( _public + curve->num_words, public_key + curve->num_bytes, curve->num_bytes); if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) { return -4; } return uECC_valid_point(_public, curve); } int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key, uECC_Curve curve) { uECC_word_t _private[NUM_ECC_WORDS]; uECC_word_t _public[NUM_ECC_WORDS * 2]; uECC_vli_bytesToNative( _private, private_key, BITS_TO_BYTES(curve->num_n_bits)); /* Make sure the private key is in the range [1, n-1]. */ if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) { return 0; } if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) { return 0; } /* Compute public key. */ if (!EccPoint_compute_public_key(_public, _private, curve)) { return 0; } uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); uECC_vli_nativeToBytes( public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words); return 1; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ecc.c
C
apache-2.0
28,286
/* ec_dh.c - TinyCrypt implementation of EC-DH */ /* * Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/constants.h> #include <tinycrypt/ecc.h> #include <tinycrypt/ecc_dh.h> #include <tinycrypt/ecc_platform_specific.h> #include <string.h> #if default_RNG_defined static uECC_RNG_Function g_rng_function = &default_CSPRNG; #else static uECC_RNG_Function g_rng_function = 0; #endif int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key, unsigned int *d, uECC_Curve curve) { uECC_word_t _private[NUM_ECC_WORDS]; uECC_word_t _public[NUM_ECC_WORDS * 2]; /* This function is designed for test purposes-only (such as validating NIST * test vectors) as it uses a provided value for d instead of generating * it uniformly at random. */ memcpy (_private, d, NUM_ECC_BYTES); /* Computing public-key from private: */ if (EccPoint_compute_public_key(_public, _private, curve)) { /* Converting buffers to correct bit order: */ uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private); uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words); /* erasing temporary buffer used to store secret: */ memset(_private, 0, NUM_ECC_BYTES); return 1; } return 0; } int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) { uECC_word_t _random[NUM_ECC_WORDS * 2]; uECC_word_t _private[NUM_ECC_WORDS]; uECC_word_t _public[NUM_ECC_WORDS * 2]; uECC_word_t tries; for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { /* Generating _private uniformly at random: */ uECC_RNG_Function rng_function = uECC_get_rng(); if (!rng_function || !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS*uECC_WORD_SIZE)) { return 0; } /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */ uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits)); /* Computing public-key from private: */ if (EccPoint_compute_public_key(_public, _private, curve)) { /* Converting buffers to correct bit order: */ uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private); uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words); /* erasing temporary buffer that stored secret: */ memset(_private, 0, NUM_ECC_BYTES); return 1; } } return 0; } int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key, uint8_t *secret, uECC_Curve curve) { uECC_word_t _public[NUM_ECC_WORDS * 2]; uECC_word_t _private[NUM_ECC_WORDS]; uECC_word_t tmp[NUM_ECC_WORDS]; uECC_word_t *p2[2] = {_private, tmp}; uECC_word_t *initial_Z = 0; uECC_word_t carry; wordcount_t num_words = curve->num_words; wordcount_t num_bytes = curve->num_bytes; int r; /* Converting buffers to correct bit order: */ uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits)); uECC_vli_bytesToNative(_public, public_key, num_bytes); uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes, num_bytes); /* Regularize the bitcount for the private key so that attackers cannot use a * side channel attack to learn the number of leading zeros. */ carry = regularize_k(_private, _private, tmp, curve); /* If an RNG function was specified, try to get a random initial Z value to * improve protection against side-channel attacks. */ if (g_rng_function) { if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) { r = 0; goto clear_and_out; } initial_Z = p2[carry]; } EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, curve); uECC_vli_nativeToBytes(secret, num_bytes, _public); r = !EccPoint_isZero(_public, curve); clear_and_out: /* erasing temporary buffer used to store secret: */ memset(p2, 0, sizeof(p2)); __asm__ __volatile__("" :: "g"(p2) : "memory"); memset(tmp, 0, sizeof(tmp)); __asm__ __volatile__("" :: "g"(tmp) : "memory"); memset(_private, 0, sizeof(_private)); __asm__ __volatile__("" :: "g"(_private) : "memory"); return r; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ecc_dh.c
C
apache-2.0
7,398
/* ec_dsa.c - TinyCrypt implementation of EC-DSA */ /* Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE.*/ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/constants.h> #include <tinycrypt/ecc.h> #include <tinycrypt/ecc_dsa.h> #include <tinycrypt/ecc_platform_specific.h> #if default_RNG_defined static uECC_RNG_Function g_rng_function = &default_CSPRNG; #else static uECC_RNG_Function g_rng_function = 0; #endif static void bits2int(uECC_word_t *native, const uint8_t *bits, unsigned bits_size, uECC_Curve curve) { unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits); unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits); int shift; uECC_word_t carry; uECC_word_t *ptr; if (bits_size > num_n_bytes) { bits_size = num_n_bytes; } uECC_vli_clear(native, num_n_words); uECC_vli_bytesToNative(native, bits, bits_size); if (bits_size * 8 <= (unsigned)curve->num_n_bits) { return; } shift = bits_size * 8 - curve->num_n_bits; carry = 0; ptr = native + num_n_words; while (ptr-- > native) { uECC_word_t temp = *ptr; *ptr = (temp >> shift) | carry; carry = temp << (uECC_WORD_BITS - shift); } /* Reduce mod curve_n */ if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) { uECC_vli_sub(native, native, curve->n, num_n_words); } } int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uECC_word_t *k, uint8_t *signature, uECC_Curve curve) { uECC_word_t tmp[NUM_ECC_WORDS]; uECC_word_t s[NUM_ECC_WORDS]; uECC_word_t *k2[2] = {tmp, s}; uECC_word_t p[NUM_ECC_WORDS * 2]; uECC_word_t carry; wordcount_t num_words = curve->num_words; wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); bitcount_t num_n_bits = curve->num_n_bits; /* Make sure 0 < k < curve_n */ if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) { return 0; } carry = regularize_k(k, tmp, s, curve); EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve); if (uECC_vli_isZero(p, num_words)) { return 0; } /* If an RNG function was specified, get a random number to prevent side channel analysis of k. */ if (!g_rng_function) { uECC_vli_clear(tmp, num_n_words); tmp[0] = 1; } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) { return 0; } /* Prevent side channel analysis of uECC_vli_modInv() to determine bits of k / the private key by premultiplying by a random number */ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */ uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */ uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */ /* tmp = d: */ uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); s[num_n_words - 1] = 0; uECC_vli_set(s, p, num_words); uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */ bits2int(tmp, message_hash, hash_size, curve); uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */ uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */ if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) { return 0; } uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s); return 1; } int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uint8_t *signature, uECC_Curve curve) { uECC_word_t _random[2*NUM_ECC_WORDS]; uECC_word_t k[NUM_ECC_WORDS]; uECC_word_t tries; for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { /* Generating _random uniformly at random: */ uECC_RNG_Function rng_function = uECC_get_rng(); if (!rng_function || !rng_function((uint8_t *)_random, 2*NUM_ECC_WORDS*uECC_WORD_SIZE)) { return 0; } // computing k as modular reduction of _random (see FIPS 186.4 B.5.1): uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits)); if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature, curve)) { return 1; } } return 0; } static bitcount_t smax(bitcount_t a, bitcount_t b) { return (a > b ? a : b); } int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash, unsigned hash_size, const uint8_t *signature, uECC_Curve curve) { uECC_word_t u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS]; uECC_word_t z[NUM_ECC_WORDS]; uECC_word_t sum[NUM_ECC_WORDS * 2]; uECC_word_t rx[NUM_ECC_WORDS]; uECC_word_t ry[NUM_ECC_WORDS]; uECC_word_t tx[NUM_ECC_WORDS]; uECC_word_t ty[NUM_ECC_WORDS]; uECC_word_t tz[NUM_ECC_WORDS]; const uECC_word_t *points[4]; const uECC_word_t *point; bitcount_t num_bits; bitcount_t i; uECC_word_t _public[NUM_ECC_WORDS * 2]; uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS]; wordcount_t num_words = curve->num_words; wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); rx[num_n_words - 1] = 0; r[num_n_words - 1] = 0; s[num_n_words - 1] = 0; uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes, curve->num_bytes); uECC_vli_bytesToNative(r, signature, curve->num_bytes); uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes); /* r, s must not be 0. */ if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) { return 0; } /* r, s must be < n. */ if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 || uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) { return 0; } /* Calculate u1 and u2. */ uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */ u1[num_n_words - 1] = 0; bits2int(u1, message_hash, hash_size, curve); uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */ uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */ /* Calculate sum = G + Q. */ uECC_vli_set(sum, _public, num_words); uECC_vli_set(sum + num_words, _public + num_words, num_words); uECC_vli_set(tx, curve->G, num_words); uECC_vli_set(ty, curve->G + num_words, num_words); uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */ XYcZ_add(tx, ty, sum, sum + num_words, curve); uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */ apply_z(sum, sum + num_words, z, curve); /* Use Shamir's trick to calculate u1*G + u2*Q */ points[0] = 0; points[1] = curve->G; points[2] = _public; points[3] = sum; num_bits = smax(uECC_vli_numBits(u1, num_n_words), uECC_vli_numBits(u2, num_n_words)); point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) | ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)]; uECC_vli_set(rx, point, num_words); uECC_vli_set(ry, point + num_words, num_words); uECC_vli_clear(z, num_words); z[0] = 1; for (i = num_bits - 2; i >= 0; --i) { uECC_word_t index; curve->double_jacobian(rx, ry, z, curve); index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1); point = points[index]; if (point) { uECC_vli_set(tx, point, num_words); uECC_vli_set(ty, point + num_words, num_words); apply_z(tx, ty, z, curve); uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */ XYcZ_add(tx, ty, rx, ry, curve); uECC_vli_modMult_fast(z, z, tz, curve); } } uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */ apply_z(rx, ry, z, curve); /* v = x1 (mod n) */ if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) { uECC_vli_sub(rx, rx, curve->n, num_n_words); } /* Accept only if v == r. */ return (int)(uECC_vli_equal(rx, r, num_words) == 0); }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ecc_dsa.c
C
apache-2.0
10,496
/* uECC_platform_specific.c - Implementation of platform specific functions*/ /* Copyright (c) 2014, Kenneth MacKay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE.*/ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * uECC_platform_specific.c -- Implementation of platform specific functions */ #if defined(unix) || defined(__linux__) || defined(__unix__) || \ defined(__unix) | (defined(__APPLE__) && defined(__MACH__)) || \ defined(uECC_POSIX) /* Some POSIX-like system with /dev/urandom or /dev/random. */ #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdint.h> #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif int default_CSPRNG(uint8_t *dest, unsigned int size) { /* input sanity check: */ if (dest == (uint8_t *) 0 || (size <= 0)) return 0; int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); if (fd == -1) { fd = open("/dev/random", O_RDONLY | O_CLOEXEC); if (fd == -1) { return 0; } } char *ptr = (char *)dest; size_t left = (size_t) size; while (left > 0) { ssize_t bytes_read = read(fd, ptr, left); if (bytes_read <= 0) { // read failed close(fd); return 0; } left -= bytes_read; ptr += bytes_read; } close(fd); return 1; } #endif /* platform */
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/ecc_platform_specific.c
C
apache-2.0
4,115
/* hmac.c - TinyCrypt implementation of the HMAC algorithm */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/hmac.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> static void rekey(uint8_t *key, const uint8_t *new_key, unsigned int key_size) { const uint8_t inner_pad = (uint8_t) 0x36; const uint8_t outer_pad = (uint8_t) 0x5c; unsigned int i; for (i = 0; i < key_size; ++i) { key[i] = inner_pad ^ new_key[i]; key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i]; } for (; i < TC_SHA256_BLOCK_SIZE; ++i) { key[i] = inner_pad; key[i + TC_SHA256_BLOCK_SIZE] = outer_pad; } } int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key, unsigned int key_size) { /* input sanity check: */ if (ctx == (TCHmacState_t) 0 || key == (const uint8_t *) 0 || key_size == 0) { return TC_CRYPTO_FAIL; } const uint8_t dummy_key[key_size]; struct tc_hmac_state_struct dummy_state; if (key_size <= TC_SHA256_BLOCK_SIZE) { /* * The next three lines consist of dummy calls just to avoid * certain timing attacks. Without these dummy calls, * adversaries would be able to learn whether the key_size is * greater than TC_SHA256_BLOCK_SIZE by measuring the time * consumed in this process. */ (void)tc_sha256_init(&dummy_state.hash_state); (void)tc_sha256_update(&dummy_state.hash_state, dummy_key, key_size); (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE], &dummy_state.hash_state); /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */ rekey(ctx->key, key, key_size); } else { (void)tc_sha256_init(&ctx->hash_state); (void)tc_sha256_update(&ctx->hash_state, key, key_size); (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE], &ctx->hash_state); rekey(ctx->key, &ctx->key[TC_SHA256_DIGEST_SIZE], TC_SHA256_DIGEST_SIZE); } return TC_CRYPTO_SUCCESS; } int tc_hmac_init(TCHmacState_t ctx) { /* input sanity check: */ if (ctx == (TCHmacState_t) 0) { return TC_CRYPTO_FAIL; } (void) tc_sha256_init(&ctx->hash_state); (void) tc_sha256_update(&ctx->hash_state, ctx->key, TC_SHA256_BLOCK_SIZE); return TC_CRYPTO_SUCCESS; } int tc_hmac_update(TCHmacState_t ctx, const void *data, unsigned int data_length) { /* input sanity check: */ if (ctx == (TCHmacState_t) 0) { return TC_CRYPTO_FAIL; } (void)tc_sha256_update(&ctx->hash_state, data, data_length); return TC_CRYPTO_SUCCESS; } int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx) { /* input sanity check: */ if (tag == (uint8_t *) 0 || taglen != TC_SHA256_DIGEST_SIZE || ctx == (TCHmacState_t) 0) { return TC_CRYPTO_FAIL; } (void) tc_sha256_final(tag, &ctx->hash_state); (void)tc_sha256_init(&ctx->hash_state); (void)tc_sha256_update(&ctx->hash_state, &ctx->key[TC_SHA256_BLOCK_SIZE], TC_SHA256_BLOCK_SIZE); (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE); (void)tc_sha256_final(tag, &ctx->hash_state); /* destroy the current state */ _set(ctx, 0, sizeof(*ctx)); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/hmac.c
C
apache-2.0
4,699
/* hmac_prng.c - TinyCrypt implementation of HMAC-PRNG */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/hmac_prng.h> #include <tinycrypt/hmac.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> /* * min bytes in the seed string. * MIN_SLEN*8 must be at least the expected security level. */ static const unsigned int MIN_SLEN = 32; /* * max bytes in the seed string; * SP800-90A specifies a maximum of 2^35 bits (i.e., 2^32 bytes). */ static const unsigned int MAX_SLEN = UINT32_MAX; /* * max bytes in the personalization string; * SP800-90A specifies a maximum of 2^35 bits (i.e., 2^32 bytes). */ static const unsigned int MAX_PLEN = UINT32_MAX; /* * max bytes in the additional_info string; * SP800-90A specifies a maximum of 2^35 bits (i.e., 2^32 bytes). */ static const unsigned int MAX_ALEN = UINT32_MAX; /* * max number of generates between re-seeds; * TinyCrypt accepts up to (2^32 - 1) which is the maximal value of * a 32-bit unsigned int variable, while SP800-90A specifies a maximum of 2^48. */ static const unsigned int MAX_GENS = UINT32_MAX; /* * maximum bytes per generate call; * SP800-90A specifies a maximum up to 2^19. */ static const unsigned int MAX_OUT = (1 << 19); /* * Assumes: prng != NULL, e != NULL, len >= 0. */ static void update(TCHmacPrng_t prng, const uint8_t *e, unsigned int len) { const uint8_t separator0 = 0x00; const uint8_t separator1 = 0x01; /* use current state, e and separator 0 to compute a new prng key: */ (void)tc_hmac_init(&prng->h); (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0)); (void)tc_hmac_update(&prng->h, e, len); (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); /* configure the new prng key into the prng's instance of hmac */ (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); /* use the new key to compute a new state variable v */ (void)tc_hmac_init(&prng->h); (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); /* use current state, e and separator 1 to compute a new prng key: */ (void)tc_hmac_init(&prng->h); (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1)); (void)tc_hmac_update(&prng->h, e, len); (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); /* configure the new prng key into the prng's instance of hmac */ (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); /* use the new key to compute a new state variable v */ (void)tc_hmac_init(&prng->h); (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); } int tc_hmac_prng_init(TCHmacPrng_t prng, const uint8_t *personalization, unsigned int plen) { /* input sanity check: */ if (prng == (TCHmacPrng_t) 0 || personalization == (uint8_t *) 0 || plen > MAX_PLEN) { return TC_CRYPTO_FAIL; } /* put the generator into a known state: */ _set(prng->key, 0x00, sizeof(prng->key)); _set(prng->v, 0x01, sizeof(prng->v)); tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); /* update assumes SOME key has been configured into HMAC */ update(prng, personalization, plen); /* force a reseed before allowing tc_hmac_prng_generate to succeed: */ prng->countdown = 0; return TC_CRYPTO_SUCCESS; } int tc_hmac_prng_reseed(TCHmacPrng_t prng, const uint8_t *seed, unsigned int seedlen, const uint8_t *additional_input, unsigned int additionallen) { /* input sanity check: */ if (prng == (TCHmacPrng_t) 0 || seed == (const uint8_t *) 0 || seedlen < MIN_SLEN || seedlen > MAX_SLEN) { return TC_CRYPTO_FAIL; } if (additional_input != (const uint8_t *) 0) { /* * Abort if additional_input is provided but has inappropriate * length */ if (additionallen == 0 || additionallen > MAX_ALEN) { return TC_CRYPTO_FAIL; } else { /* call update for the seed and additional_input */ update(prng, seed, seedlen); update(prng, additional_input, additionallen); } } else { /* call update only for the seed */ update(prng, seed, seedlen); } /* ... and enable hmac_prng_generate */ prng->countdown = MAX_GENS; return TC_CRYPTO_SUCCESS; } int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng) { unsigned int bufferlen; /* input sanity check: */ if (out == (uint8_t *) 0 || prng == (TCHmacPrng_t) 0 || outlen == 0 || outlen > MAX_OUT) { return TC_CRYPTO_FAIL; } else if (prng->countdown == 0) { return TC_HMAC_PRNG_RESEED_REQ; } prng->countdown--; while (outlen != 0) { /* operate HMAC in OFB mode to create "random" outputs */ (void)tc_hmac_init(&prng->h); (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ? outlen : TC_SHA256_DIGEST_SIZE; (void)_copy(out, bufferlen, prng->v, bufferlen); out += bufferlen; outlen = (outlen > TC_SHA256_DIGEST_SIZE) ? (outlen - TC_SHA256_DIGEST_SIZE) : 0; } /* block future PRNG compromises from revealing past state */ update(prng, prng->v, TC_SHA256_DIGEST_SIZE); return TC_CRYPTO_SUCCESS; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/hmac_prng.c
C
apache-2.0
6,904
/* sha256.c - TinyCrypt SHA-256 crypto hash algorithm implementation */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/sha256.h> #include <tinycrypt/constants.h> #include <tinycrypt/utils.h> static void compress(unsigned int *iv, const uint8_t *data); int tc_sha256_init(TCSha256State_t s) { /* input sanity check: */ if (s == (TCSha256State_t) 0) { return TC_CRYPTO_FAIL; } /* * Setting the initial state values. * These values correspond to the first 32 bits of the fractional parts * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17 * and 19. */ _set((uint8_t *) s, 0x00, sizeof(*s)); s->iv[0] = 0x6a09e667; s->iv[1] = 0xbb67ae85; s->iv[2] = 0x3c6ef372; s->iv[3] = 0xa54ff53a; s->iv[4] = 0x510e527f; s->iv[5] = 0x9b05688c; s->iv[6] = 0x1f83d9ab; s->iv[7] = 0x5be0cd19; return TC_CRYPTO_SUCCESS; } int tc_sha256_update(TCSha256State_t s, const uint8_t *data, size_t datalen) { /* input sanity check: */ if (s == (TCSha256State_t) 0 || data == (void *) 0) { return TC_CRYPTO_FAIL; } else if (datalen == 0) { return TC_CRYPTO_SUCCESS; } while (datalen-- > 0) { s->leftover[s->leftover_offset++] = *(data++); if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) { compress(s->iv, s->leftover); s->leftover_offset = 0; s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3); } } return TC_CRYPTO_SUCCESS; } int tc_sha256_final(uint8_t *digest, TCSha256State_t s) { unsigned int i; /* input sanity check: */ if (digest == (uint8_t *) 0 || s == (TCSha256State_t) 0) { return TC_CRYPTO_FAIL; } s->bits_hashed += (s->leftover_offset << 3); s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */ if (s->leftover_offset > (sizeof(s->leftover) - 8)) { /* there is not room for all the padding in this block */ _set(s->leftover + s->leftover_offset, 0x00, sizeof(s->leftover) - s->leftover_offset); compress(s->iv, s->leftover); s->leftover_offset = 0; } /* add the padding and the length in big-Endian format */ _set(s->leftover + s->leftover_offset, 0x00, sizeof(s->leftover) - 8 - s->leftover_offset); s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed); s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8); s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16); s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24); s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32); s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40); s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48); s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56); /* hash the padding and length */ compress(s->iv, s->leftover); /* copy the iv out to digest */ for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) { unsigned int t = *((unsigned int *) &s->iv[i]); *digest++ = (uint8_t)(t >> 24); *digest++ = (uint8_t)(t >> 16); *digest++ = (uint8_t)(t >> 8); *digest++ = (uint8_t)(t); } /* destroy the current state */ _set(s, 0, sizeof(*s)); return TC_CRYPTO_SUCCESS; } /* * Initializing SHA-256 Hash constant words K. * These values correspond to the first 32 bits of the fractional parts of the * cube roots of the first 64 primes between 2 and 311. */ static const unsigned int k256[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; static inline unsigned int ROTR(unsigned int a, unsigned int n) { return (((a) >> n) | ((a) << (32 - n))); } #define Sigma0(a)(ROTR((a), 2) ^ ROTR((a), 13) ^ ROTR((a), 22)) #define Sigma1(a)(ROTR((a), 6) ^ ROTR((a), 11) ^ ROTR((a), 25)) #define sigma0(a)(ROTR((a), 7) ^ ROTR((a), 18) ^ ((a) >> 3)) #define sigma1(a)(ROTR((a), 17) ^ ROTR((a), 19) ^ ((a) >> 10)) #define Ch(a, b, c)(((a) & (b)) ^ ((~(a)) & (c))) #define Maj(a, b, c)(((a) & (b)) ^ ((a) & (c)) ^ ((b) & (c))) static inline unsigned int BigEndian(const uint8_t **c) { unsigned int n = 0; n = (((unsigned int)(*((*c)++))) << 24); n |= ((unsigned int)(*((*c)++)) << 16); n |= ((unsigned int)(*((*c)++)) << 8); n |= ((unsigned int)(*((*c)++))); return n; } static void compress(unsigned int *iv, const uint8_t *data) { unsigned int a, b, c, d, e, f, g, h; unsigned int s0, s1; unsigned int t1, t2; unsigned int work_space[16]; unsigned int n; unsigned int i; a = iv[0]; b = iv[1]; c = iv[2]; d = iv[3]; e = iv[4]; f = iv[5]; g = iv[6]; h = iv[7]; for (i = 0; i < 16; ++i) { n = BigEndian(&data); t1 = work_space[i] = n; t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i]; t2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } for ( ; i < 64; ++i) { s0 = work_space[(i+1)&0x0f]; s0 = sigma0(s0); s1 = work_space[(i+14)&0x0f]; s1 = sigma1(s1); t1 = work_space[i&0xf] += s0 + s1 + work_space[(i+9)&0xf]; t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i]; t2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } iv[0] += a; iv[1] += b; iv[2] += c; iv[3] += d; iv[4] += e; iv[5] += f; iv[6] += g; iv[7] += h; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/sha256.c
C
apache-2.0
7,416
/* utils.c - TinyCrypt platform-dependent run-time operations */ /* * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tinycrypt/utils.h> #include <tinycrypt/constants.h> #include <string.h> #define MASK_TWENTY_SEVEN 0x1b unsigned int _copy(uint8_t *to, unsigned int to_len, const uint8_t *from, unsigned int from_len) { if (from_len <= to_len) { (void)memcpy(to, from, from_len); return from_len; } else { return TC_CRYPTO_FAIL; } } void _set(void *to, uint8_t val, unsigned int len) { (void)memset(to, val, len); } /* * Doubles the value of a byte for values up to 127. */ uint8_t _double_byte(uint8_t a) { return ((a<<1) ^ ((a>>7) * MASK_TWENTY_SEVEN)); } int _compare(const uint8_t *a, const uint8_t *b, size_t size) { const uint8_t *tempa = a; const uint8_t *tempb = b; uint8_t result = 0; unsigned int i; for (i = 0; i < size; i++) { result |= tempa[i] ^ tempb[i]; } return result; }
YifuLiu/AliOS-Things
components/ble_host/bt_crypto/tinycrypt/source/utils.c
C
apache-2.0
2,491
add_library(subsys__bluetooth INTERFACE) target_include_directories(subsys__bluetooth INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) add_subdirectory(common) add_subdirectory_ifdef(CONFIG_BT_HCI host) add_subdirectory_ifdef(CONFIG_BT_SHELL shell) if(CONFIG_BT_CTLR) if(CONFIG_BT_LL_SW) add_subdirectory(controller) endif() endif() target_link_libraries(subsys__bluetooth INTERFACE zephyr_interface)
YifuLiu/AliOS-Things
components/ble_host/bt_host/CMakeLists.txt
CMake
apache-2.0
403
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <aos/aos.h> #include <aos/log.h> #include <aos/mesh.h> #include <bluetooth/bluetooth.h> #include <bluetooth/mesh.h> #include <tinycrypt/sha256.h> #include <tinycrypt/constants.h> #include "drv_gpio.h" #include "ali_vendormodel_profile.h" #include "ali_vendormodel_profile_config.h" #define printk printf #define PID_STRING_LEN 4 #define DEVICE_NAME_LEN 6 #define STATIC_VALUE_LEN 100 static struct bt_mesh_prov prov; static struct bt_mesh_comp comp; //static struct bt_mesh_model_pub gen_level_pub; struct bt_mesh_model_pub lightness_srv_pub; bt_mesh_opcode_cb_t proc_opcode; //static gpio_pin_handle_t gpio_led1; static struct tc_sha256_state_struct sha256_ctx; static char static_value[STATIC_VALUE_LEN] = { 0x00 }; // pid + ',' + mac + ',' + secret struct onoff_state { u8_t current; u8_t previous; }; static struct onoff_state g_onoff_state; static struct bt_mesh_model_pub health_pub = { .msg = BT_MESH_HEALTH_FAULT_MSG(0), }; struct bt_mesh_model_pub gen_onoff_pub = { .msg = NET_BUF_SIMPLE(2 + 2), }; static void attention_on(struct bt_mesh_model *model) { printk("attention_on()\n"); } static void attention_off(struct bt_mesh_model *model) { printk("attention_off()\n"); } static const struct bt_mesh_health_srv_cb health_srv_cb = { .attn_on = attention_on, .attn_off = attention_off, }; static struct bt_mesh_health_srv health_srv = { .cb = &health_srv_cb, }; static struct bt_mesh_cfg_srv cfg_srv = { .relay = BT_MESH_RELAY_ENABLED, .beacon = BT_MESH_BEACON_ENABLED, #ifdef CONFIG_BT_MESH_FRIEND .frnd = BT_MESH_FRIEND_NOT_SUPPORTED, #else .frnd = BT_MESH_FRIEND_NOT_SUPPORTED, #endif #ifdef CONFIG_BT_MESH_GATT_PROXY .gatt_proxy = BT_MESH_GATT_PROXY_ENABLED, #else .gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED, #endif .default_ttl = 7, /* 3 transmissions with 20ms interval */ .net_transmit = BT_MESH_TRANSMIT(2, 20), .relay_retransmit = BT_MESH_TRANSMIT(2, 20), }; static void gen_onoff_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 1 + 4); //printk("onoff get: addr 0x%04x onoff 0x%02x\n", // model->elem->addr, g_onoff_state.current); bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x04)); net_buf_simple_add_u8(msg, g_onoff_state.current); if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) { printk("Unable to send On Off Status response\n"); } } static void gen_onoff_set_unack(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { struct net_buf_simple *msg = model->pub->msg; int err; g_onoff_state.current = net_buf_simple_pull_u8(buf); //printk("addr 0x%02x state 0x%02x\n", // model->elem->addr, g_onoff_state.current); // turn on/off LED on the nrf52832-pca10040 board if (g_onoff_state.current) { //hal_gpio_output_low(&gpio_led1); } else { //hal_gpio_output_high(&gpio_led1); } /* * If a server has a publish address, it is required to * publish status on a state change * * See Mesh Profile Specification 3.7.6.1.2 * * Only publish if there is an assigned address */ if (g_onoff_state.previous != g_onoff_state.current && model->pub->addr != BT_MESH_ADDR_UNASSIGNED) { printk("publish last 0x%02x cur 0x%02x\n", g_onoff_state.previous, g_onoff_state.current); g_onoff_state.previous = g_onoff_state.current; bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x04)); net_buf_simple_add_u8(msg, g_onoff_state.current); err = bt_mesh_model_publish(model); if (err) { printk("bt_mesh_model_publish err %d\n", err); } } } static void gen_onoff_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { printk("gen_onoff_set\n"); gen_onoff_set_unack(model, ctx, buf); gen_onoff_get(model, ctx, buf); if (proc_opcode != NULL) proc_opcode(1,NULL,0); } const struct bt_mesh_model_op gen_onoff_op[] = { { BT_MESH_MODEL_OP_2(0x82, 0x01), 0, gen_onoff_get }, { BT_MESH_MODEL_OP_2(0x82, 0x02), 2, gen_onoff_set }, { BT_MESH_MODEL_OP_2(0x82, 0x03), 2, gen_onoff_set_unack }, BT_MESH_MODEL_OP_END, }; static void lightness_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_set_unack(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_linear_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_linear_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_linear_set_unack(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_linear_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_last_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_last_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_default_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_default_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_range_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } static void lightness_range_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { } const struct bt_mesh_model_op lightness_srv_op[] = { { BT_MESH_MODEL_OP_2(0x82, 0x4b), 2, lightness_get }, { BT_MESH_MODEL_OP_2(0x82, 0x4c), 2, lightness_set }, { BT_MESH_MODEL_OP_2(0x82, 0x4d), 2, lightness_set_unack }, { BT_MESH_MODEL_OP_2(0x82, 0x4e), 2, lightness_status }, { BT_MESH_MODEL_OP_2(0x82, 0x4f), 2, lightness_linear_get }, { BT_MESH_MODEL_OP_2(0x82, 0x50), 2, lightness_linear_set }, { BT_MESH_MODEL_OP_2(0x82, 0x51), 2, lightness_linear_set_unack }, { BT_MESH_MODEL_OP_2(0x82, 0x52), 2, lightness_linear_status }, { BT_MESH_MODEL_OP_2(0x82, 0x53), 2, lightness_last_get }, { BT_MESH_MODEL_OP_2(0x82, 0x54), 2, lightness_last_status }, { BT_MESH_MODEL_OP_2(0x82, 0x55), 2, lightness_default_get }, { BT_MESH_MODEL_OP_2(0x82, 0x56), 2, lightness_default_status }, { BT_MESH_MODEL_OP_2(0x82, 0x57), 2, lightness_range_get }, { BT_MESH_MODEL_OP_2(0x82, 0x58), 2, lightness_range_status }, BT_MESH_MODEL_OP_END, }; static void vendor_model_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 1 + 4); static u8_t tid = 0; //printk("vendor get: src_addr dst_addr 0x%04x\n",ctx->addr,model->elem->addr); bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_3(VENDOR_OPCODE_STATUS_ACK,CONFIG_MESH_VENDOR_COMPANY_ID)); if (proc_opcode != NULL) proc_opcode(0,buf->data,buf->len); if(tid >= 250) tid = 1; net_buf_simple_add_u8(msg, tid++); net_buf_simple_add_u8(msg, 0x00); net_buf_simple_add_u8(msg, 0x00); net_buf_simple_add_u8(msg, 129); if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) { printk("Unable to send On Off Status response\n"); } } static void vendor_model_set_ack(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 1 + 4); //printk("vendor get: src_addr dst_addr 0x%04x\n",ctx->addr,model->elem->addr); bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_3(VENDOR_OPCODE_STATUS_ACK,CONFIG_MESH_VENDOR_COMPANY_ID)); if (proc_opcode != NULL) proc_opcode(0,buf->data,buf->len); net_buf_simple_add_u8(msg, 0x12); net_buf_simple_add_u8(msg, 0x00); net_buf_simple_add_u8(msg, 0x00); net_buf_simple_add_u8(msg, 129); if (bt_mesh_model_send(model, ctx, msg, NULL, NULL)) { printk("Unable to send On Off Status response\n"); } } static void vendor_model_set_unack(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { //struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 1 + 4); //printk("vendor get: src_addr dst_addr 0x%04x\n",ctx->addr,model->elem->addr); if (proc_opcode != NULL) proc_opcode(0,buf->data,buf->len); } static void vendor_model_indicate(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf) { struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 1 + 4); //printk("vendor indicate: addr 0x%04x\n", model->elem->addr); bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_3(CONFIG_MESH_VENDOR_COMPANY_ID, VENDOR_OPCODE_CONFIME)); if (proc_opcode != NULL) proc_opcode(0,msg->data,msg->len); } static const struct bt_mesh_model_op vendor_model_op[] = { { BT_MESH_MODEL_OP_3(VENDOR_OPCODE_GET_STATUS, CONFIG_MESH_VENDOR_COMPANY_ID), 0, vendor_model_get }, { BT_MESH_MODEL_OP_3(VENDOR_OPCODE_SET_ACK, CONFIG_MESH_VENDOR_COMPANY_ID), 2, vendor_model_set_ack }, { BT_MESH_MODEL_OP_3(VENDOR_OPCODE_SET_UNACK, CONFIG_MESH_VENDOR_COMPANY_ID), 2, vendor_model_set_unack }, //{ BT_MESH_MODEL_OP_3(VENDOR_OPCODE_STATUS_ACK, CONFIG_MESH_VENDOR_COMPANY_ID), 2, vendor_model_status_ack }, { BT_MESH_MODEL_OP_3(VENDOR_OPCODE_INDICATE, CONFIG_MESH_VENDOR_COMPANY_ID), 2, vendor_model_indicate }, //{ BT_MESH_MODEL_OP_3(VENDOR_OPCODE_CONFIME, CONFIG_MESH_VENDOR_COMPANY_ID), 2, vendor_model_set_ack }, BT_MESH_MODEL_OP_END, }; static void hextostring(const uint8_t *source, char *dest, int len) { int i; char tmp[3]; for (i = 0; i < len; i++) { sprintf(tmp, "%02x", (unsigned char)source[i]); memcpy(&dest[i * 2], tmp, 2); } return; } void bt_mesh_profile_calculate_digest(const uint8_t *digest, const uint8_t *pid, const uint8_t *mac_addr, const char *secret) { int ret; char pid_string[16] = ""; char mac_addr_string[16] = ""; // convert the hex byte stream to hex string hextostring(pid, pid_string, PID_STRING_LEN); printk("pid string: %s\n", pid_string); hextostring(mac_addr, mac_addr_string, DEVICE_NAME_LEN); printk("mac_addr_string: %s\n", mac_addr_string); strcat(static_value, pid_string); strcat(static_value, ","); strcat(static_value, mac_addr_string); strcat(static_value, ","); // generally we should ensure the secret lenght won't exceed the STATIC_VALUE_LEN if (strlen(secret) > (STATIC_VALUE_LEN - PID_STRING_LEN - DEVICE_NAME_LEN - 2)) { printk("secret length over size\n"); return; } else { strcat(static_value, secret); } printk("static oob: %s\n", static_value); /* calculate the sha256 of oob info and * fetch the top 16 bytes as static value */ ret = tc_sha256_init(&sha256_ctx); if (ret != TC_CRYPTO_SUCCESS) { printk("sha256 init fail\n"); } ret = tc_sha256_update(&sha256_ctx, (const uint8_t *)static_value, strlen(static_value)); if (ret != TC_CRYPTO_SUCCESS) { printk("sha256 udpate fail\n"); } ret = tc_sha256_final((uint8_t *)digest, &sha256_ctx); if (ret != TC_CRYPTO_SUCCESS) { printk("sha256 final fail\n"); } return; } void bt_mesh_profile_construct_uuid(char *dev_uuid, const uint8_t *pid, const uint8_t *mac_addr) { int i; // all fields in uuid should be in little-endian // CID: Taobao dev_uuid[0] = 0xa8; dev_uuid[1] = 0x01; // PID // Bit0~Bit3: 0001 (broadcast version) // Bit4:1 (one secret pre device) // Bit5: 1 (OTA support) // Bit6~Bit7: 01 (ble 4.0) dev_uuid[2] = 0x71; // Product ID for (i = 0; i < 4; i++) { dev_uuid[3 + i] = pid[3 - i]; } // mac addr (device name) for (i = 0; i < 6; i++) { dev_uuid[7 + i] = mac_addr[5 - i]; } dev_uuid[13] = 0x2; return; } static void bt_mesh_ready(int err) { int ret; if (err) { printk("Bluetooth init failed (err %d)\n", err); return; } ret = bt_mesh_init(&prov, &comp, NULL); if (ret) { printk("Initializing mesh failed (err %d)\n", ret); return; } ret = bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV); if(ret){ printk("%d ret mesh enable\r\n",ret); return; } printk("Bluetooth Mesh initialized\n"); } int bt_mesh_profile_start(void) { int ret = 0; //hci_driver_init(); ret = bt_enable(bt_mesh_ready); if (ret) { printk("Bluetooth init failed (err %d)\n", ret); } return ret; } #if 1 int bt_mesh_profile_prov_init(const uint8_t *dev_uuid, const uint8_t *digest, size_t digest_len, bt_mesh_profile_prov_complete_t prov_complete, bt_mesh_profile_prov_reset_t prov_reset, bt_mesh_profile_prov_link_open_t prov_link_open) #else int bt_mesh_profile_prov_init(const uint8_t *dev_uuid, const uint8_t *digest, size_t digest_len, bt_mesh_evt_t bt_mesh_evt_cb) #endif { prov.uuid = dev_uuid; prov.static_val = digest; prov.static_val_len = digest_len; prov.complete = prov_complete; prov.reset = prov_reset; prov.link_open = prov_link_open; //prov.mesh_evt = bt_mesh_evt_cb; return 0; } static struct bt_mesh_model root_models[CONFIG_MESH_MODEL_NUM] = { BT_MESH_MODEL_CFG_SRV(&cfg_srv), BT_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), //BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_ONOFF_SRV, gen_onoff_op,&gen_onoff_pub, NULL), //BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV, lightness_srv_op,&lightness_srv_pub, NULL), }; static struct bt_mesh_model ali_vendor_models[CONFIG_MESH_VENDOR_MODEL_NUM] = { BT_MESH_MODEL_VND(CONFIG_MESH_VENDOR_COMPANY_ID,CONFIG_MESH_VENDOR_MODEL_SRV, vendor_model_op, NULL, NULL), }; static struct bt_mesh_elem elements[CONFIG_MESH_ELEM_NUM] = { BT_MESH_ELEM(0, root_models, ali_vendor_models, 0xc006), //BT_MESH_ELEM(0, root_models, BT_MESH_MODEL_NONE), }; int bt_mesh_profile_composition_data_init(void) { /* Node composition data used to configure a node while provisioning */ comp.cid = CONFIG_CID_TAOBAO; comp.pid = 0; comp.vid = 1; // firmware version fir ota comp.elem = elements; comp.elem_count = ARRAY_SIZE(elements); return 0; } int bt_mesh_profile_model_init(bt_mesh_opcode_cb_t bt_mesh_opcode_cb) { /* add all supported elements and models from here * configure all light bulb related models for demo */ // configure LED1 pin //gpio_led1.port = CONFIG_BT_MESH_LED_PIN; proc_opcode = bt_mesh_opcode_cb; return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/ali_vendormodel_profile/ali_vendormodel_profile.c
C
apache-2.0
16,915
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef ALI_VENDORMODEL_PROFILE_H_ #define ALI_VENDORMODEL_PROFILE_H_ //#include <bluetooth/mesh.h> /** @brief calculate the digest of static oob info * * Calculate the sha256 of static oob info as AuthValue during * the provisioning process. * * AuthValue = SHA256(Product ID,MAC,Secret); * * @param digest buffer to store the calculated sha256 value. * @param pid product id, allocated from Alibaba. * @param mac_addr device name, allocatd from Alibaba. * @param secret device key, allocated from Alibaba. */ void bt_mesh_profile_calculate_digest(const uint8_t *digest, const uint8_t *pid, const uint8_t *mac_addr, const char *secret); /** @brief construct the new uuid followed Alibaba ble mesh spec * * Construct the new 16bytes uuid followed Alibaba ble mesh spec * * CID: company id (2 bytes) * PID: 1 byte * Product ID: 4 bytes * Mac addr: device name (6 bytes) * RFU * * @param uuid uuid pointer passed in. * @param pid product id, allocatd from Alibaba. * @param mac_addr device name, allocated from Alibaba. */ void bt_mesh_profile_construct_uuid(char *uuid, const uint8_t *pid, const uint8_t *mac_addr); /** @brief Callback for notifying that Bluetooth has been enabled * * @param err zero on success or (negative) error code otherwise */ typedef void (*bt_mesh_profile_ready_cb_t)(int err); /** @brief initialize and start the ble mesh profile. * * Initialize the hci driver, ble mesh stack and start profile. * * @param cb Callback to notify completion or NULL to perform the * enabling synchronously * * @return Zero on success or (negative) error code otherwise. */ int bt_mesh_profile_start(void); /** @brief Provisioning is complete. * * This callback notifies the application that provisioning has * been successfully completed, and that the local node has been * assigned the specified NetKeyIndex and primary element address. * * @param net_idx NetKeyIndex given during provisioning. * @param addr Primary element address. */ typedef void (*bt_mesh_profile_prov_complete_t)(uint16_t net_idx, uint16_t addr); /** @brief Node has been reset. * * This callback notifies the application that the local node * has been reset and needs to be reprovisioned. The node will * not automatically advertise as unprovisioned, rather the * bt_mesh_prov_enable() API needs to be called to enable * unprovisioned advertising on one or more provisioning bearers. */ typedef void (*bt_mesh_profile_prov_reset_t)(void); typedef void (*bt_mesh_profile_prov_link_open_t)(uint8_t status); //typedef void (*bt_mesh_evt_t)(s_bt_mesh_evt bt_mesh_evt); typedef void (*bt_mesh_opcode_cb_t)(uint8_t type,uint8_t *attr_buf,uint8_t attr_len); /** @brief initialize the ble mesh provisioning. * * Initialize the ble mesh provisioning, and select the specific * provisioning bearer (current only PB-GATT bearer is supported). * * @param dev_uuid device uuid get from ble_mesh_profile_construct_uuid() api. * @param digest sha256 value calculate from ble_mesh_profile_calculate_digest() api. * @param digest_len length of digest, always 16 bytes. * @param prov_complete_cb callback for provisioning is complete. * @param prov_reset_cb callback for provisioning is reset. * * @return Zero on success or (negative) error code otherwise. */ #if 1 int bt_mesh_profile_prov_init(const uint8_t *dev_uuid, const uint8_t *digest, size_t digest_len, bt_mesh_profile_prov_complete_t prov_complete_cb, bt_mesh_profile_prov_reset_t prov_reset_cb, bt_mesh_profile_prov_link_open_t prov_link_open_cb); #else int bt_mesh_profile_prov_init(const uint8_t *dev_uuid, const uint8_t *digest, size_t digest_len, bt_mesh_evt_t bt_mesh_evt_cb); #endif /** @brief initialize the supported elements and models. * * Initialize the supported elements and models in the specific product. * * @return Zero on success or (negative) error code otherwise. */ int bt_mesh_profile_model_init(bt_mesh_opcode_cb_t bt_mesh_opcode_cb); /** @brief initialize the composistion data. * * Initialize the composition data (mainly for Composition Data Page 0) * of a node, these information will be used during provisioning. * * @return Zero on success or (negative) error code otherwise. */ int bt_mesh_profile_composition_data_init(void); #endif // ALI_VENDORMODEL_PROFILE_H_
YifuLiu/AliOS-Things
components/ble_host/bt_host/ali_vendormodel_profile/ali_vendormodel_profile.h
C
apache-2.0
4,739
NAME := ali_vendormodel_profile $(NAME)_MBINS_TYPE := kernel $(NAME)_VERSION := 1.0.0 $(NAME)_COMPONENTS := bluetooth.bt_mesh $(NAME)_SOURCES := ali_vendormodel_profile.c GLOBAL_INCLUDES := ./
YifuLiu/AliOS-Things
components/ble_host/bt_host/ali_vendormodel_profile/ali_vendormodel_profile.mk
Makefile
apache-2.0
196
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef ALI_VENDORMODEL_PROFILE_CONFIG_H_ #define ALI_VENDORMODEL_PROFILE_CONFIG_H_ /** * @def CONFIG_MESH_ELEM_NUM * * The specific supported number of elements in product. * */ #define CONFIG_MESH_ELEM_NUM 1 /** * @def CONFIG_MESH_MODLE_NUM * * The specific supported number of models in product. * */ #define CONFIG_MESH_MODEL_NUM 2 /** * @def CONFIG_MESH_VENDOR_MODLE_NUM * * The specific supported number of vendor models in product. * */ #define CONFIG_MESH_VENDOR_COMPANY_ID 0x01a8 #define CONFIG_MESH_VENDOR_MODEL_SRV 0x0000 #define CONFIG_MESH_VENDOR_MODEL_CLI 0x0001 #define VENDOR_OPCODE_GET_STATUS 0xD0 #define VENDOR_OPCODE_SET_ACK 0xD1 #define VENDOR_OPCODE_SET_UNACK 0xD2 #define VENDOR_OPCODE_STATUS_ACK 0xD3 #define VENDOR_OPCODE_INDICATE 0xD4 #define VENDOR_OPCODE_CONFIME 0xD5 #define CONFIG_MESH_VENDOR_MODEL_NUM 1 /** * @def CONFIG_CID_TAOBAO * * The specific company id used for tmall mesh profile. * */ #define CONFIG_CID_TAOBAO 0x01A8 /** * @def CONFIG_BT_MESH_CPRL * * The specific cprl value in the Composition Data Page 0. * */ #ifndef CONFIG_BT_MESH_CRPL #define CONFIG_BT_MESH_CRPL 100 #endif /** * @def CONFIG_BT_MESH_LED_PIN * * The specific LED1 pin number of nrf52832 dev board. * You can change this macro with the desired pin number. * e.g. LED1(P0.13) for nrf52840 pca10056 dev board. * */ #define CONFIG_BT_MESH_LED_PIN 17 #endif // ALI_VENDORMODEL_PRFOILE_CONFIG_H_
YifuLiu/AliOS-Things
components/ble_host/bt_host/ali_vendormodel_profile/ali_vendormodel_profile_config.h
C
apache-2.0
1,568
/* * Copyright (C) 2017 C-SKY Microsystems Co., 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 <string.h> #include <aos/ble.h> //#include <aos/osal_debug.h> #include <string.h> #include <ble_os.h> #include <bluetooth/bluetooth.h> #include "bluetooth/conn.h" //yulong change < to " #include <bluetooth/hci.h> #include <bluetooth/addr.h> //#include "conn.h" // yulong added #include "host/conn_internal.h" #include <bluetooth/gatt.h> #include <settings/settings.h> #include <hci_api.h> #define EVENT_BLE_BASE #define TAG "BLE" #define BLE_LOGD(fmt, ...) LOGD(TAG, "[%s]"fmt,__FUNCTION__, ##__VA_ARGS__) #define BLE_LOGE(fmt, ...) LOGE(TAG, "[%s]"fmt,__FUNCTION__, ##__VA_ARGS__) typedef struct _ble_dev_t { uint8_t is_init; slist_t cb_list; uint8_t io_cap; init_param_t init; } ble_dev_t; struct _params_pool_t { struct bt_gatt_write_params write_params[3]; union { struct bt_uuid_16 uuid16; struct bt_uuid_32 uuid32; struct bt_uuid_128 uuid128; } uuid; struct bt_gatt_discover_params disc_params[1]; struct bt_gatt_read_params read_params[4]; } ble_param_pool = {0}; ble_dev_t ble_dev = {0}; typedef struct _ble_attr_notify_t { struct bt_conn *conn; const uint8_t *data; uint16_t len; int err; } ble_attr_notify_t; void ble_adv_timeout_cb(); static inline uuid_t *uuid_covert(uuid_t *uuid, const struct bt_uuid *btuuid) { uuid->type = btuuid->type; if (btuuid->type == BT_UUID_TYPE_16) { UUID16(uuid) = BT_UUID_16(btuuid)->val; } else if (btuuid->type == BT_UUID_TYPE_32) { UUID32(uuid) = BT_UUID_32(btuuid)->val; } else if (btuuid->type == BT_UUID_TYPE_128) { memcpy(UUID128(uuid), BT_UUID_128(btuuid)->val, 16); } return uuid; } static inline struct bt_uuid *btuuid_covert(struct bt_uuid *btuuid, const uuid_t *uuid) { btuuid->type = uuid->type; if (uuid->type == UUID_TYPE_16) { BT_UUID_16(btuuid)->val = UUID16(uuid); } else if (uuid->type == UUID_TYPE_32) { BT_UUID_32(btuuid)->val = UUID32(uuid); } else if (uuid->type == UUID_TYPE_128) { memcpy(BT_UUID_128(btuuid)->val, UUID128(uuid), 16); } return btuuid; } uint8_t UUID_EQUAL(uuid_t *uuid1, uuid_t *uuid2) { if (UUID_TYPE(uuid1) != UUID_TYPE(uuid2)) { return false; } if (uuid1->type == BT_UUID_TYPE_16) { return (0 == memcmp(&((struct bt_uuid_16 *)uuid1)->val, &((struct bt_uuid_16 *)uuid2)->val, UUID_LEN(uuid1))); } else if (uuid1->type == BT_UUID_TYPE_32) { return (0 == memcmp(&((struct bt_uuid_32 *)uuid1)->val, &((struct bt_uuid_32 *)uuid2)->val, UUID_LEN(uuid1))); } else if (uuid1->type == BT_UUID_TYPE_128) { return (0 == memcmp(&((struct bt_uuid_128 *)uuid1)->val, &((struct bt_uuid_128 *)uuid2)->val, UUID_LEN(uuid1))); } return false; } uint8_t *get_uuid_val(uuid_t *uuid) { if (uuid->type == BT_UUID_TYPE_16) { return (uint8_t *) & ((struct bt_uuid_16 *)uuid)->val; } else if (uuid->type == BT_UUID_TYPE_32) { return (uint8_t *) & ((struct bt_uuid_32 *)uuid)->val; } else if (uuid->type == BT_UUID_TYPE_128) { return (uint8_t *) & ((struct bt_uuid_128 *)uuid)->val; } else { return NULL; } } static int ble_stack_event_callback(ble_event_en event, void *event_data, uint32_t event_len) { slist_t *tmp; ble_event_cb_t *node; slist_for_each_entry_safe(&ble_dev.cb_list, tmp, node, ble_event_cb_t, next) { if (node->callback) { node->callback(event, event_data); } } return 0; } static void connected(struct bt_conn *conn, u8_t err) { evt_data_gap_conn_change_t event_data; event_data.conn_handle = bt_conn_index(conn); if (err) { event_data.err = err; event_data.connected = DISCONNECTED; } else { event_data.err = 0; event_data.connected = CONNECTED; } ble_stack_event_callback(EVENT_GAP_CONN_CHANGE, &event_data, sizeof(event_data)); } static void disconnected(struct bt_conn *conn, u8_t reason) { evt_data_gap_conn_change_t event_data; if (reason == BT_HCI_ERR_ADV_TIMEOUT) { ble_adv_timeout_cb(); } else { event_data.conn_handle = bt_conn_index(conn); event_data.connected = DISCONNECTED; event_data.err = reason; ble_stack_event_callback(EVENT_GAP_CONN_CHANGE, &event_data, sizeof(event_data)); memset(&ble_param_pool, 0, sizeof(ble_param_pool)); } } static bool le_param_req_cb(struct bt_conn *conn, struct bt_le_conn_param *param) { evt_data_gap_conn_param_req_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.param = *(conn_param_t *)param; event_data.accept = 1; ble_stack_event_callback(EVENT_GAP_CONN_PARAM_REQ, &event_data, sizeof(event_data)); if (event_data.accept) { return true; } else { return false; } } static void le_param_update_cb(struct bt_conn *conn, u16_t interval, u16_t latency, u16_t timeout) { evt_data_gap_conn_param_update_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.interval = interval; event_data.latency = latency; event_data.timeout = timeout; ble_stack_event_callback(EVENT_GAP_CONN_PARAM_UPDATE, &event_data, sizeof(event_data)); } #ifdef CONFIG_BT_SMP static void security_changed_cb(struct bt_conn *conn, bt_security_t level, enum bt_security_err err) { evt_data_gap_security_change_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.level = level; event_data.err = err; ble_stack_event_callback(EVENT_GAP_CONN_SECURITY_CHANGE, &event_data, sizeof(event_data)); } #endif static void scan_cb(const bt_addr_le_t *addr, s8_t rssi, u8_t adv_type, struct net_buf_simple *buf) { evt_data_gap_dev_find_t event_data; memcpy(&event_data.dev_addr, addr, sizeof(dev_addr_t)); event_data.adv_type = adv_type; if (buf->len > 31) { return; } memcpy(event_data.adv_data, buf->data, buf->len); event_data.adv_len = buf->len; event_data.rssi = rssi; ble_stack_event_callback(EVENT_GAP_DEV_FIND, &event_data, sizeof(event_data)); } static void auth_passkey_display(struct bt_conn *conn, unsigned int passkey) { char passkey_str[7] = {0}; evt_data_smp_passkey_display_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); snprintf(passkey_str, 7, "%06u", passkey); event_data.conn_handle = bt_conn_index(conn); event_data.passkey = passkey_str; ble_stack_event_callback(EVENT_SMP_PASSKEY_DISPLAY, &event_data, sizeof(event_data)); } static void auth_passkey_confirm(struct bt_conn *conn, unsigned int passkey) { char passkey_str[7] = {0}; evt_data_smp_passkey_confirm_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); snprintf(passkey_str, 7, "%06u", passkey); event_data.conn_handle = bt_conn_index(conn); event_data.passkey = passkey_str; ble_stack_event_callback(EVENT_SMP_PASSKEY_CONFIRM, &event_data, sizeof(event_data)); } static void auth_passkey_entry(struct bt_conn *conn) { evt_data_smp_passkey_enter_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); event_data.conn_handle = bt_conn_index(conn); ble_stack_event_callback(EVENT_SMP_PASSKEY_ENTER, &event_data, sizeof(event_data)); } static void auth_cancel(struct bt_conn *conn) { evt_data_smp_cancel_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); event_data.conn_handle = bt_conn_index(conn); ble_stack_event_callback(EVENT_SMP_CANCEL, &event_data, sizeof(event_data)); } static void auth_pairing_confirm(struct bt_conn *conn) { evt_data_smp_pairing_confirm_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); event_data.conn_handle = bt_conn_index(conn); ble_stack_event_callback(EVENT_SMP_PAIRING_CONFIRM, &event_data, sizeof(event_data)); } static void auth_pairing_complete(struct bt_conn *conn, bool bonded) { evt_data_smp_pairing_complete_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); event_data.conn_handle = bt_conn_index(conn); event_data.bonded = bonded; event_data.err = 0; ble_stack_event_callback(EVENT_SMP_PAIRING_COMPLETE, &event_data, sizeof(event_data)); } static void auth_pairing_failed(struct bt_conn *conn, enum bt_security_err reason) { evt_data_smp_pairing_complete_t event_data; memcpy(&event_data.peer_addr, bt_conn_get_dst(conn), sizeof(dev_addr_t)); event_data.conn_handle = bt_conn_index(conn); event_data.err = reason; ble_stack_event_callback(EVENT_SMP_PAIRING_COMPLETE, &event_data, sizeof(event_data)); } static struct bt_conn_cb conn_callbacks = { .connected = connected, .disconnected = disconnected, .le_param_req = le_param_req_cb, .le_param_updated = le_param_update_cb, #ifdef CONFIG_BT_SMP .identity_resolved = NULL, .security_changed = security_changed_cb, #endif }; static struct bt_conn_auth_cb auth_callbacks = { .cancel = auth_cancel, .pairing_failed = auth_pairing_failed, .pairing_complete = auth_pairing_complete, }; int ble_stack_init(init_param_t *param) { int ret = BLE_STACK_OK; if (param == NULL) { return -BLE_STACK_ERR_NULL; } if (ble_dev.is_init) { return -BLE_STACK_ERR_ALREADY; } hci_h4_driver_init(); ble_dev.init = *param; if (ble_dev.init.dev_addr) { bt_addr_le_t addr = *(bt_addr_le_t *)ble_dev.init.dev_addr; if (addr.type == BT_ADDR_LE_RANDOM) { ret = bt_set_id_addr(&addr); if (ret) { ret = -BLE_STACK_ERR_PARAM; return ret; } } else if (addr.type == BT_ADDR_LE_PUBLIC) { extern int bt_set_bdaddr(const bt_addr_le_t *addr); ret = bt_set_bdaddr(&addr); if (ret) { ret = -BLE_STACK_ERR_PARAM; return ret; } } else if (addr.type == BT_ADDR_LE_PUBLIC_ID) { } else if (addr.type == BT_ADDR_LE_RANDOM_ID) { } else { ret = -BLE_STACK_ERR_PARAM; return ret; } } bt_conn_cb_register(&conn_callbacks); ret = bt_enable(NULL); if (ret) { return ret; } if (ble_dev.init.dev_name) { ret = bt_set_name(ble_dev.init.dev_name); if (ret) { ret = -BLE_STACK_ERR_PARAM; return ret; } } slist_init(&ble_dev.cb_list); ble_stack_setting_load(); #if AOS_COMP_CLI cli_reg_cmd_ble(); #endif ble_dev.is_init = 1; return ret; } int ble_stack_iocapability_set(uint8_t io_cap) { int ret = 0; int data = (io_cap & (IO_CAP_IN_NONE | IO_CAP_IN_YESNO | IO_CAP_IN_KEYBOARD)); if ((data != IO_CAP_IN_NONE) && (data != IO_CAP_IN_YESNO) && (data != IO_CAP_IN_KEYBOARD)) { return -BLE_STACK_ERR_PARAM; } int sdata = (io_cap & (IO_CAP_OUT_DISPLAY | IO_CAP_OUT_NONE)); if ((sdata != IO_CAP_OUT_DISPLAY) && (sdata != IO_CAP_OUT_NONE)) { return -BLE_STACK_ERR_PARAM; } if ((io_cap & IO_CAP_IN_NONE) && (io_cap & IO_CAP_OUT_DISPLAY)) { auth_callbacks.passkey_display = auth_passkey_display; auth_callbacks.cancel = auth_cancel; auth_callbacks.pairing_confirm = auth_pairing_confirm; auth_callbacks.pairing_failed = auth_pairing_failed; auth_callbacks.pairing_complete = auth_pairing_complete; } else if ((io_cap & IO_CAP_IN_YESNO) && (io_cap & IO_CAP_OUT_DISPLAY)) { auth_callbacks.passkey_display = auth_passkey_display; auth_callbacks.passkey_confirm = auth_passkey_confirm; auth_callbacks.cancel = auth_cancel; auth_callbacks.pairing_confirm = auth_pairing_confirm; auth_callbacks.pairing_failed = auth_pairing_failed; auth_callbacks.pairing_complete = auth_pairing_complete; } else if ((io_cap & IO_CAP_IN_KEYBOARD) && (io_cap & IO_CAP_OUT_DISPLAY)) { auth_callbacks.passkey_display = auth_passkey_display; auth_callbacks.passkey_entry = auth_passkey_entry; auth_callbacks.passkey_confirm = auth_passkey_confirm; auth_callbacks.cancel = auth_cancel; auth_callbacks.pairing_confirm = auth_pairing_confirm; auth_callbacks.pairing_failed = auth_pairing_failed; auth_callbacks.pairing_complete = auth_pairing_complete; } else if ((io_cap & IO_CAP_IN_KEYBOARD) && (io_cap & IO_CAP_OUT_NONE)) { auth_callbacks.passkey_entry = auth_passkey_entry; auth_callbacks.passkey_confirm = auth_passkey_confirm; auth_callbacks.cancel = auth_cancel; auth_callbacks.pairing_confirm = auth_pairing_confirm; auth_callbacks.pairing_failed = auth_pairing_failed; auth_callbacks.pairing_complete = auth_pairing_complete; } if (auth_callbacks.cancel != NULL) { ret = bt_conn_auth_cb_register(&auth_callbacks); if (ret) { return ret; } } ble_dev.io_cap = io_cap; return ret; } int ble_stack_event_register(ble_event_cb_t *callback) { if (!ble_dev.is_init) { return -BLE_STACK_ERR_INIT; } if (NULL == callback) { return -BLE_STACK_ERR_NULL; } slist_add(&callback->next, &ble_dev.cb_list); return 0; } int ble_stack_adv_start(adv_param_t *param) { struct bt_le_adv_param p = {0}; if (!ble_dev.is_init) { return -BLE_STACK_ERR_INIT; } if (param == NULL) { return -BLE_STACK_ERR_NULL; } if ((param->ad == NULL || (param->ad != NULL && param->ad_num == 0)) || ((param->sd == NULL && param->sd_num != 0) || (param->sd != NULL && param->sd_num == 0)) ) { return -BLE_STACK_ERR_PARAM; } if (param->channel_map > ADV_DEFAULT_CHAN_MAP) { return -BLE_STACK_ERR_PARAM; } if (param->filter_policy > ADV_FILTER_POLICY_ALL_REQ) { return -BLE_STACK_ERR_PARAM; } if (param->type == ADV_IND || param->type == ADV_DIRECT_IND || param->type == ADV_DIRECT_IND_LOW_DUTY) { p.options |= BT_LE_ADV_OPT_CONNECTABLE; } else if (param->type == ADV_NONCONN_IND || param->type == ADV_SCAN_IND) { p.options |= BT_LE_ADV_OPT_NONE; } else { return -BLE_STACK_ERR_PARAM; } if (param->type == ADV_DIRECT_IND_LOW_DUTY) { p.options |= BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY; } p.options |= BT_LE_ADV_OPT_ONE_TIME; if (ble_dev.init.dev_name) { p.options |= BT_LE_ADV_OPT_USE_NAME; } if (param->filter_policy == ADV_FILTER_POLICY_ALL_REQ) { p.options |= (BT_LE_ADV_OPT_FILTER_SCAN_REQ | BT_LE_ADV_OPT_FILTER_CONN); } else if (param->filter_policy == ADV_FILTER_POLICY_CONN_REQ) { p.options |= BT_LE_ADV_OPT_FILTER_CONN; } else if (param->filter_policy == ADV_FILTER_POLICY_SCAN_REQ) { p.options |= BT_LE_ADV_OPT_FILTER_SCAN_REQ; } p.options |= BT_LE_ADV_OPT_USE_IDENTITY; p.id = 0; p.interval_min = param->interval_min; p.interval_max = param->interval_max; p.channel_map = param->channel_map; if (param->type == ADV_DIRECT_IND_LOW_DUTY || param->type == ADV_DIRECT_IND) { if (!bt_addr_le_cmp((const bt_addr_le_t *)&param->direct_peer_addr, BT_ADDR_LE_ANY)) { return -BLE_STACK_ERR_PARAM; } param->ad = NULL; param->ad_num = 0; param->sd = NULL; param->sd_num = 0; } bt_addr_le_t peer_addr = {0}; if (param->type == ADV_DIRECT_IND_LOW_DUTY || param->type == ADV_DIRECT_IND) { p.peer = &peer_addr; peer_addr.type = param->direct_peer_addr.type; memcpy(peer_addr.a.val, param->direct_peer_addr.val, 6); } return bt_le_adv_start(&p, (struct bt_data *)param->ad, param->ad_num, (struct bt_data *)param->sd, param->sd_num);; } int ble_stack_adv_stop() { int ret; if (!ble_dev.is_init) { return -BLE_STACK_ERR_INIT; } ret = bt_le_adv_stop(); return ret; } int ble_stack_scan_start(const scan_param_t *param) { int ret; struct bt_le_scan_param p = {0}; if (param == NULL) { return -BLE_STACK_ERR_NULL; } if (!ble_dev.is_init) { return -BLE_STACK_ERR_INIT; } if (param->scan_filter > SCAN_FILTER_POLICY_WHITE_LIST) { return -BLE_STACK_ERR_PARAM; } p.type = param->type; p.interval = param->interval; p.window = param->window; if (param->filter_dup == SCAN_FILTER_DUP_ENABLE) { p.options |= BT_LE_SCAN_OPT_FILTER_DUPLICATE; } if (param->scan_filter == SCAN_FILTER_POLICY_WHITE_LIST) { p.options |= BT_LE_SCAN_OPT_FILTER_WHITELIST; } ret = bt_le_scan_start(&p, scan_cb); return ret; } int ble_stack_scan_stop() { int ret; if (!ble_dev.is_init) { return -BLE_STACK_ERR_INIT; } ret = bt_le_scan_stop(); return ret; } static ssize_t gatt_read_handle(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { evt_data_gatt_char_read_t event_data = {0}; event_data.conn_handle = bt_conn_index(conn); event_data.char_handle = attr->handle; event_data.offset = offset; ble_stack_event_callback(EVENT_GATT_CHAR_READ, &event_data, sizeof(event_data)); if (event_data.len < 0) { return event_data.len; } if (event_data.data && event_data.len > 0) { return bt_gatt_attr_read(conn, attr, buf, len, offset, event_data.data, event_data.len); } return 0; } static ssize_t gatt_write_handle(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) { evt_data_gatt_char_write_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.char_handle = attr->handle; event_data.data = buf; event_data.len = len; event_data.offset = offset; event_data.flag = flags; ble_stack_event_callback(EVENT_GATT_CHAR_WRITE, &event_data, sizeof(event_data)); return event_data.len; } static int gatt_cfg_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t value) { evt_data_gatt_char_ccc_write_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.char_handle = attr->handle; event_data.ccc_value = value; event_data.allow_write = true; ble_stack_event_callback(EVENT_GATT_CHAR_CCC_WRITE, &event_data, sizeof(event_data)); return event_data.allow_write? true:false; } static bool gatt_cfg_match(struct bt_conn *conn, const struct bt_gatt_attr *attr) { evt_data_gatt_char_ccc_match_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.char_handle = attr->handle; event_data.is_matched = true; ble_stack_event_callback(EVENT_GATT_CHAR_CCC_MATCH, &event_data, sizeof(event_data)); return event_data.is_matched? true:false; } static void cfg_changed_cb(const struct bt_gatt_attr *attr, u16_t value) { evt_data_gatt_char_ccc_change_t event_data; event_data.char_handle = attr->handle; event_data.ccc_value = value; ble_stack_event_callback(EVENT_GATT_CHAR_CCC_CHANGE, &event_data, sizeof(event_data)); } int uuid_compare(const uuid_t *uuid1, const uuid_t *uuid2) { return bt_uuid_cmp((struct bt_uuid *)uuid1, (struct bt_uuid *)uuid2); } int ble_stack_gatt_registe_service(gatt_service *s, gatt_attr_t attrs[], uint16_t attr_num) { int ret; int i; struct bt_gatt_service *ss; ss = (struct bt_gatt_service *)s; if (!ble_dev.is_init) { return -BLE_STACK_ERR_INIT; } if (attrs == NULL || attr_num == 0) { return -BLE_STACK_ERR_NULL; } ss->attr_count = attr_num; ss->attrs = (struct bt_gatt_attr *)attrs; for (i = 0; i < attr_num; i++) { if (UUID_EQUAL(attrs[i].uuid, UUID_GATT_PRIMARY) || UUID_EQUAL(attrs[i].uuid, UUID_GATT_SECONDARY) || UUID_EQUAL(attrs[i].uuid, UUID_GATT_INCLUDE)) { ss->attrs[i].read = bt_gatt_attr_read_service; } else if (UUID_EQUAL(attrs[i].uuid, UUID_GATT_CHRC)) { if (i + 1 >= attr_num) { return -BLE_STACK_ERR_PARAM; } ss->attrs[i].read = bt_gatt_attr_read_chrc; ss->attrs[i + 1].read = gatt_read_handle; ss->attrs[i + 1].write = gatt_write_handle; i++; } else if (UUID_EQUAL(attrs[i].uuid, UUID_GATT_CCC)) { struct _bt_gatt_ccc *val = NULL; val = (struct _bt_gatt_ccc *)(attrs[i].user_data); val->cfg_changed = cfg_changed_cb; val->cfg_write = gatt_cfg_write; val->cfg_match = gatt_cfg_match; ss->attrs[i].perm = GATT_PERM_READ | GATT_PERM_WRITE; ss->attrs[i].read = bt_gatt_attr_read_ccc; ss->attrs[i].write = bt_gatt_attr_write_ccc; ss->attrs[i].user_data = val; } else if (UUID_EQUAL(attrs[i].uuid, UUID_GATT_CEP)) { ss->attrs[i].read = bt_gatt_attr_read_cep; } else if (UUID_EQUAL(attrs[i].uuid, UUID_GATT_CUD)) { ss->attrs[i].read = gatt_read_handle; ss->attrs[i].write = gatt_write_handle; } else if (UUID_EQUAL(attrs[i].uuid, UUID_GATT_CPF)) { ss->attrs[i].read = bt_gatt_attr_read_cpf; } else { ss->attrs[i].read = gatt_read_handle; ss->attrs[i].write = gatt_write_handle; } } ret = bt_gatt_service_register(ss); if (ret < 0) { return ret; } return ss->attrs[0].handle; } static uint8_t ble_gatt_attr_notify(const struct bt_gatt_attr *attr, void *user_data) { ble_attr_notify_t *notify = (ble_attr_notify_t *)user_data; notify->err = bt_gatt_notify(notify->conn, attr, notify->data, notify->len); return BT_GATT_ITER_STOP; } static void ble_gatt_indicate_cb(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) { evt_data_gatt_indicate_cb_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.char_handle = attr->handle; event_data.err = err; ble_stack_event_callback(EVENT_GATT_INDICATE_CB, &event_data, sizeof(event_data)); } static uint8_t ble_gatt_attr_indicate(const struct bt_gatt_attr *attr, void *user_data) { ble_attr_notify_t *notify = (ble_attr_notify_t *)user_data; static struct bt_gatt_indicate_params param = {0}; param.attr = attr; param.func = ble_gatt_indicate_cb; param.data = notify->data; param.len = notify->len; notify->err = bt_gatt_indicate(notify->conn, &param); return BT_GATT_ITER_STOP; } int ble_stack_gatt_notificate(int16_t conn_handle, uint16_t char_handle, const uint8_t *data, uint16_t len) { ble_attr_notify_t notify; struct bt_conn *conn; if (conn_handle < 0 || data == NULL || len == 0) { return -BLE_STACK_ERR_PARAM; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } notify.conn = conn; notify.data = data; notify.len = len; notify.err = 0; bt_gatt_foreach_attr(char_handle, char_handle, ble_gatt_attr_notify, &notify); if (notify.conn) { bt_conn_unref(notify.conn); } return notify.err; } int ble_stack_gatt_indicate(int16_t conn_handle, int16_t char_handle, const uint8_t *data, uint16_t len) { ble_attr_notify_t notify; struct bt_conn *conn; if (conn_handle < 0 || data == NULL || len == 0) { return -BLE_STACK_ERR_PARAM; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } notify.conn = conn; notify.data = data; notify.len = len; notify.err = 0; bt_gatt_foreach_attr(char_handle, char_handle, ble_gatt_attr_indicate, &notify); if (notify.conn) { bt_conn_unref(notify.conn); } return notify.err; } void ble_adv_timeout_cb() { ble_stack_event_callback(EVENT_GAP_ADV_TIMEOUT, NULL, 0); } void mtu_exchange_cb(struct bt_conn *conn, u8_t err, struct bt_gatt_exchange_params *params) { evt_data_gatt_mtu_exchange_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.err = err; ble_stack_event_callback(EVENT_GATT_MTU_EXCHANGE, &event_data, sizeof(event_data)); } int ble_stack_gatt_mtu_get(int16_t conn_handle) { int ret; struct bt_conn *conn = NULL; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } ret = bt_gatt_get_mtu(conn); if (conn) { bt_conn_unref(conn); } return ret; } int ble_stack_gatt_mtu_exchange(int16_t conn_handle) { static struct bt_gatt_exchange_params params; int ret; struct bt_conn *conn; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } params.func = mtu_exchange_cb; ret = bt_gatt_exchange_mtu(conn, &params); if (conn) { bt_conn_unref(conn); } return ret; } static u8_t discover_func(struct bt_conn *conn, const struct bt_gatt_attr *attr, struct bt_gatt_discover_params *params) { int event = EVENT_STACK_UNKNOWN; union { evt_data_gatt_discovery_svc_t svc; evt_data_gatt_discovery_inc_svc_t svc_inc; evt_data_gatt_discovery_char_t char_c; evt_data_gatt_discovery_char_des_t char_des; evt_data_gatt_discovery_complete_t comp; } event_data; if (attr == NULL) { if (params) { params->func = NULL; } event_data.comp.conn_handle = bt_conn_index(conn); event_data.comp.err = 0; event = EVENT_GATT_DISCOVERY_COMPLETE; ble_stack_event_callback(event, &event_data, sizeof(event_data)); return BT_GATT_ITER_STOP; } if (params->type == BT_GATT_DISCOVER_PRIMARY) { struct bt_gatt_service_val *value = attr->user_data; event_data.svc.conn_handle = bt_conn_index(conn); event_data.svc.start_handle = attr->handle; event_data.svc.end_handle = value->end_handle; uuid_covert(&event_data.svc.uuid, value->uuid); event = EVENT_GATT_DISCOVERY_SVC; } else if (params->type == BT_GATT_DISCOVER_INCLUDE) { struct bt_gatt_include *inc_val = (struct bt_gatt_include *)attr->user_data; event_data.svc_inc.conn_handle = bt_conn_index(conn); event_data.svc_inc.attr_handle = attr->handle; event_data.svc_inc.start_handle = inc_val->start_handle; event_data.svc_inc.end_handle = inc_val->end_handle; uuid_covert(&event_data.svc_inc.uuid, inc_val->uuid); event = EVENT_GATT_DISCOVERY_INC_SVC; } else if (params->type == BT_GATT_DISCOVER_CHARACTERISTIC) { struct bt_gatt_chrc *chrc = (struct bt_gatt_chrc *)attr->user_data; event_data.char_c.conn_handle = bt_conn_index(conn); event_data.char_c.attr_handle = attr->handle; event_data.char_c.val_handle = attr->handle + 1; event_data.char_c.props = chrc->properties; uuid_covert(&event_data.char_c.uuid, chrc->uuid); event = EVENT_GATT_DISCOVERY_CHAR; } else if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) { event_data.char_des.conn_handle = bt_conn_index(conn); event_data.char_des.attr_handle = attr->handle; uuid_covert(&event_data.char_des.uuid, params->uuid); event = EVENT_GATT_DISCOVERY_CHAR_DES; } ble_stack_event_callback(event, &event_data, sizeof(event_data)); return BT_GATT_ITER_CONTINUE; } 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) { int ret; struct bt_conn *conn; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } if (ble_param_pool.disc_params[0].func) { return -BLE_STACK_ERR_ALREADY; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } struct bt_gatt_discover_params *params = &ble_param_pool.disc_params[0]; struct bt_uuid *u; if (uuid) { u = (struct bt_uuid *)&ble_param_pool.uuid; params->uuid = btuuid_covert(u, uuid); } else { params->uuid = NULL; } if (type == GATT_FIND_PRIMARY_SERVICE) { params->type = BT_GATT_DISCOVER_PRIMARY; } else if (type == GATT_FIND_INC_SERVICE) { params->type = BT_GATT_DISCOVER_INCLUDE; } else if (type == GATT_FIND_CHAR) { params->type = BT_GATT_DISCOVER_CHARACTERISTIC; } else if (type == GATT_FIND_CHAR_DESCRIPTOR) { params->type = BT_GATT_DISCOVER_DESCRIPTOR; } else { return -BLE_STACK_ERR_PARAM; } params->start_handle = start_handle; params->end_handle = end_handle; params->func = discover_func; ret = bt_gatt_discover(conn, params); if (ret) { params->func = NULL; } if (conn) { bt_conn_unref(conn); } return ret; } static void gatt_write_cb(struct bt_conn *conn, u8_t err, struct bt_gatt_write_params *params) { if (NULL == params) { return; } evt_data_gatt_write_cb_t event_data; event_data.conn_handle = bt_conn_index(conn); event_data.err = err; event_data.char_handle = params->handle; if (params) { params->func = NULL; } ble_stack_event_callback(EVENT_GATT_CHAR_WRITE_CB, &event_data, sizeof(event_data)); } int ble_stack_gatt_notify_cb(int16_t conn_handle, uint16_t attr_handle, const uint8_t *data, uint16_t len) { evt_data_gatt_notify_t event_data; event_data.conn_handle = conn_handle; event_data.char_handle = attr_handle; event_data.data = data; event_data.len = len; ble_stack_event_callback(EVENT_GATT_NOTIFY, &event_data, sizeof(event_data)); return 0; } 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) { int ret = -BLE_STACK_ERR_INTERNAL; int i; struct bt_gatt_write_params *params = NULL; if ((data == NULL) || (len == 0)) { return -BLE_STACK_ERR_PARAM; } if (conn_handle < 0) { return -BLE_STACK_ERR_CONN; } if (attr_handle <= 0) { return -BLE_STACK_ERR_NULL; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } if (type == GATT_WRITE) { for (i = 0; i < sizeof(ble_param_pool.write_params) / (sizeof(struct bt_gatt_write_params)); i++) { if (ble_param_pool.write_params[i].func == NULL) { break; } } if (i == sizeof(ble_param_pool.write_params) / (sizeof(struct bt_gatt_write_params))) { return -BLE_STACK_ERR_NULL; } params = &ble_param_pool.write_params[i]; params->handle = attr_handle; params->data = data; params->length = len; params->offset = offset; params->func = gatt_write_cb; ret = bt_gatt_write(conn, params); } else if (type == GATT_WRITE_WITHOUT_RESPONSE || type == GATT_WRITE_SINGED) { ret = bt_gatt_write_without_response(conn, attr_handle, data, len, type == GATT_WRITE_SINGED); } if (ret && params) { params->func = NULL; } if (conn) { bt_conn_unref(conn); } return ret; } u8_t gatt_read_cb(struct bt_conn *conn, u8_t err, struct bt_gatt_read_params *params, const void *data, u16_t length) { evt_data_gatt_read_cb_t event_data = {0}; event_data.conn_handle = bt_conn_index(conn); if (err || data == NULL || length == 0) { if (params) { params->func = NULL; } event_data.err = err; event_data.data = NULL; event_data.len = 0; ble_stack_event_callback(EVENT_GATT_CHAR_READ_CB, &event_data, sizeof(event_data)); return BT_GATT_ITER_STOP; } event_data.data = data; event_data.len = length; event_data.err = err; ble_stack_event_callback(EVENT_GATT_CHAR_READ_CB, &event_data, sizeof(event_data)); return BT_GATT_ITER_CONTINUE; } int ble_stack_gatt_read(int16_t conn_handle, uint16_t attr_handle, uint16_t offset) { int ret = -BLE_STACK_ERR_INTERNAL; struct bt_conn *conn; int i; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } for (i = 0; i < sizeof(ble_param_pool.read_params) / (sizeof(struct bt_gatt_read_params)); i++) { if (ble_param_pool.read_params[i].func == NULL) { break; } } if (i == sizeof(ble_param_pool.read_params) / (sizeof(struct bt_gatt_read_params))) { return -BLE_STACK_ERR_NULL; } struct bt_gatt_read_params *params = &ble_param_pool.read_params[i]; params->func = gatt_read_cb; params->handle_count = 1; params->single.handle = attr_handle; params->single.offset = offset; ret = bt_gatt_read(conn, params); if (conn) { bt_conn_unref(conn); } return ret; } int ble_stack_gatt_read_multiple(int16_t conn_handle, uint16_t attr_count, uint16_t attr_handle[]) { int ret = -BLE_STACK_ERR_INTERNAL; //struct bt_gatt_read_params params; struct bt_conn *conn; //uint16_t *attr_list; int i; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } if (attr_handle == NULL || attr_count <= 1) { return -BLE_STACK_ERR_PARAM; } conn = bt_conn_lookup_index(conn_handle); if (conn == NULL) { return -BLE_STACK_ERR_CONN; } for (i = 0; i < sizeof(ble_param_pool.read_params) / (sizeof(struct bt_gatt_read_params)); i++) { if (ble_param_pool.read_params[i].func == NULL) { break; } } if (i == sizeof(ble_param_pool.read_params) / (sizeof(struct bt_gatt_read_params))) { return -BLE_STACK_ERR_NULL; } struct bt_gatt_read_params *params = &ble_param_pool.read_params[i]; params->func = gatt_read_cb; params->handle_count = attr_count; params->handles = attr_handle; ret = bt_gatt_read(conn, params); if (conn) { bt_conn_unref(conn); } return ret; } int ble_stack_get_local_addr(dev_addr_t *addr) { struct bt_le_oob oob; if (addr == NULL) { return -BLE_STACK_ERR_NULL; } bt_le_oob_get_local(0, &oob); memcpy(addr, &oob.addr, sizeof(dev_addr_t)); return 0; } int ble_stack_connect(dev_addr_t *peer_addr, conn_param_t *param, uint8_t auto_connect) { int ret; struct bt_conn *conn = NULL; int16_t conn_handle; bt_addr_le_t peer; struct bt_le_conn_param conn_param; if (peer_addr == NULL) { return -BLE_STACK_ERR_NULL; } #if !defined(CONFIG_BT_WHITELIST) if (auto_connect) { return -BLE_STACK_ERR_PARAM; } #endif if (auto_connect > 1) { return -BLE_STACK_ERR_PARAM; } peer = *(bt_addr_le_t *)peer_addr; if (param) { conn_param = *(struct bt_le_conn_param *)param; if (auto_connect) { #if !defined(CONFIG_BT_WHITELIST) ret = bt_le_set_auto_conn(&peer, &conn_param); if (ret) { return ret; } conn = bt_conn_lookup_addr_le(0, &peer); #endif } else { conn = bt_conn_create_le(&peer, &conn_param); } } else if (!auto_connect) { #if !defined(CONFIG_BT_WHITELIST) ret = bt_le_set_auto_conn(&peer, NULL); if (ret) { return ret; } #endif } else { return -BLE_STACK_ERR_PARAM; } if (conn) { conn_handle = bt_conn_index(conn); bt_conn_unref(conn); return conn_handle; } (void)ret; return -BLE_STACK_ERR_CONN; } int ble_stack_disconnect(int16_t conn_handle) { int ret = -BLE_STACK_ERR_PARAM; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); bt_conn_unref(conn); } return ret; } int ble_stack_connect_info_get(int16_t conn_handle, connect_info_t *info) { if (conn_handle < 0 || NULL == info) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { info->conn_handle = conn_handle; info->role = conn->role; info->interval = conn->le.interval; info->latency = conn->le.latency; info->timeout = conn->le.timeout; if (conn->role == BT_HCI_ROLE_MASTER) { info->local_addr.type = conn->le.init_addr.type; memcpy(info->local_addr.val, conn->le.init_addr.a.val, 6); info->peer_addr.type = conn->le.resp_addr.type; memcpy(info->peer_addr.val, conn->le.resp_addr.a.val, 6); } else { info->local_addr.type = conn->le.resp_addr.type; memcpy(info->local_addr.val, conn->le.resp_addr.a.val, 6); info->peer_addr.type = conn->le.init_addr.type; memcpy(info->peer_addr.val, conn->le.init_addr.a.val, 6); } bt_conn_unref(conn); } else { return -BLE_STACK_ERR_PARAM; } return 0; } int ble_stack_check_conn_params(const conn_param_t *param) { 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 || ((4 * param->timeout) <= ((1 + param->latency) * param->interval_max))) { return false; } return true; } int ble_stack_security(int16_t conn_handle, security_en level) { int ret = -BLE_STACK_ERR_PARAM; struct bt_conn *conn; if (conn_handle < 0) { return ret; } conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_security(conn, level); bt_conn_unref(conn); } return ret; } int ble_stack_connect_param_update(int16_t conn_handle, conn_param_t *param) { int ret = -BLE_STACK_ERR_PARAM; struct bt_conn *conn; if (param == NULL || conn_handle < 0) { return ret; } conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_le_param_update(conn, (struct bt_le_conn_param *)param); bt_conn_unref(conn); } return ret; } int ble_stack_smp_passkey_entry(int16_t conn_handle, uint32_t passkey) { int ret = -BLE_STACK_ERR_PARAM; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_auth_passkey_entry(conn, passkey); bt_conn_unref(conn); } return ret; } int ble_stack_smp_cancel(int16_t conn_handle) { int ret = -BLE_STACK_ERR_PARAM; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_auth_cancel(conn); bt_conn_unref(conn); } return ret; } int ble_stack_smp_passkey_confirm(int16_t conn_handle) { int ret = -BLE_STACK_ERR_PARAM; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_auth_passkey_confirm(conn); bt_conn_unref(conn); } return ret; } int ble_stack_smp_pairing_confirm(int16_t conn_handle) { int ret = -BLE_STACK_ERR_PARAM; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { ret = bt_conn_auth_pairing_confirm(conn); bt_conn_unref(conn); } return ret; } int ble_stack_enc_key_size_get(int16_t conn_handle) { int ret = -BLE_STACK_ERR_PARAM; if (conn_handle < 0) { return -BLE_STACK_ERR_PARAM; } struct bt_conn *conn = bt_conn_lookup_index(conn_handle); if (conn) { #if defined(CONFIG_BT_SMP) ret = bt_conn_enc_key_size(conn); #else ret = 0; #endif bt_conn_unref(conn); } return ret; } int ble_stack_setting_load() { #ifdef CONFIG_BT_SETTINGS int ret = 0; static uint8_t is_setting_loaded = 0; if (is_setting_loaded) { return 0; } ret = settings_load(); if (!ret) { is_setting_loaded = 1; } return ret; #else return 0; #endif } int ble_stack_dev_unpair(dev_addr_t *peer_addr) { bt_addr_le_t peer; if (peer_addr == NULL) { return bt_unpair(0, NULL); } peer = *(bt_addr_le_t *)peer_addr; return bt_unpair(0, &peer); } int ble_stack_white_list_clear() { return bt_le_whitelist_clear(); } int ble_stack_white_list_add(dev_addr_t *peer_addr) { return bt_le_whitelist_add((bt_addr_le_t *)peer_addr); } int ble_stack_white_list_remove(dev_addr_t *peer_addr) { return bt_le_whitelist_rem((bt_addr_le_t *)peer_addr); } int ble_stack_white_list_size() { uint8_t size = 0; int ret; ret = bt_le_whitelist_size(&size); if (ret) { return -ret; } return size; } int ble_stack_set_name(const char *name) { return bt_set_name(name); } char *uuid_str(uuid_t *uuid) { static char uuid_str[37]; uint32_t tmp1, tmp5; uint16_t tmp0, tmp2, tmp3, tmp4; switch (uuid->type) { case UUID_TYPE_16: snprintf(uuid_str, 37, "%04x", UUID16(uuid)); break; case UUID_TYPE_32: snprintf(uuid_str, 37, "%04x", UUID32(uuid)); break; case UUID_TYPE_128: memcpy(&tmp0, &UUID128(uuid)[0], sizeof(tmp0)); memcpy(&tmp1, &UUID128(uuid)[2], sizeof(tmp1)); memcpy(&tmp2, &UUID128(uuid)[6], sizeof(tmp2)); memcpy(&tmp3, &UUID128(uuid)[8], sizeof(tmp3)); memcpy(&tmp4, &UUID128(uuid)[10], sizeof(tmp4)); memcpy(&tmp5, &UUID128(uuid)[12], sizeof(tmp5)); snprintf(uuid_str, 37, "%08x-%04x-%04x-%04x-%08x%04x", tmp5, tmp4, tmp3, tmp2, tmp1, tmp0); break; default: memset(uuid_str, 0, 37); } return uuid_str; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/aos/ble.c
C
apache-2.0
44,036
## # Copyright (C) 2017 C-SKY Microsystems Co., 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.crg/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. ## ifeq ($(CONFIG_BT), y) L_PATH := $(call cur-dir) include $(DEFINE_LOCAL) L_MODULE := libbt_host L_CFLAGS := -Wall include $(L_PATH)/../bt_defconfig #L_CFLAGS := -D__ORDER_LITTLE_ENDIAN__=1 -D__ORDER_BIG_ENDIAN__=2 -D__BYTE_ORDER__=__ORDER_LITTLE_ENDIAN__ L_INCS += $(L_PATH)/../include $(L_PATH)/include $(L_PATH)/port/include $(L_PATH)/../crypto $(L_PATH) $(L_PATH)/include/drivers \ $(L_PATH)/host L_INCS += $(L_PATH)/../bt_crypto/include L_SRCS += port/core/buf.c \ port/core/atomic_c.c \ hci_driver/h4_driver.c ifeq ($(CONFIG_OS_CSI), y) L_SRCS += port/csi/csi_port.c \ port/csi/work.c L_INCS += $(L_PATH)/port/csi else L_SRCS += port/aos/aos_port.c \ port/aos/work.c \ port/aos/poll.c L_INCS += $(L_PATH)/port/aos L_INCS += $(L_PATH)/port/aos/include $(L_PATH)/../../../../csi/csi_kernel/rhino/core/include $(L_PATH)/../../../../csi/csi_kernel/rhino/arch/include endif #L_SRCS += common/dummy.c L_SRCS += common/log.c L_SRCS += common/rpa.c ifeq ($(CONFIG_BT_HCI_RAW), y) L_SRCS += host/hci_raw.c endif ifeq ($(CONFIG_BT_DEBUG_MONITOR), y) L_SRCS += host/monitor.c endif ifeq ($(CONFIG_BT_TINYCRYPT_ECC), y) L_INCS += $(L_PATH)/../bt_crypto/tinycrypt/include L_SRCS += host/hci_ecc.c endif ifeq ($(CONFIG_BT_A2DP), y) L_SRCS += host/a2dp.c endif ifeq ($(CONFIG_BT_AVDTP), y) L_SRCS += host/avdtp.c endif ifeq ($(CONFIG_BT_RFCOMM), y) L_SRCS += host/rfcomm.c endif ifeq ($(CONFIG_BT_TESTING), y) L_SRCS += host/testing.c endif ifeq ($(CONFIG_BT_SETTINGS), y) L_SRCS += host/settings.c endif ifeq ($(CONFIG_BT_BREDR), y) L_SRCS += host/keys_br.c \ host/l2cap_br.c \ host/sdp.c endif ifeq ($(CONFIG_BT_HFP_HF), y) L_SRCS += host/hfp_hf.c \ host/at.c endif ifeq ($(CONFIG_BT_HCI_HOST), y) L_SRCS += host/uuid.c \ host/hci_api.c \ host/hci_core.c L_SRCS += host/crypto.c ifeq ($(CONFIG_BT_CONN), y) L_SRCS += host/conn.c \ host/l2cap.c \ host/att.c \ host/gatt.c ifeq ($(CONFIG_BT_SMP), y) L_SRCS += host/smp.c \ host/keys.c else L_SRCS += host/smp_null.c endif endif endif ifeq ($(CONFIG_SETTINGS), y) L_INCS += $(L_PATH)/port/core/settings/src \ $(L_PATH)/port/core/settings/include L_SRCS += port/core/settings/src/settings_store.c \ port/core/settings/src/settings.c \ port/core/settings/src/settings_init.c \ port/core/settings/src/settings_line.c \ port/core/settings/src/settings_kv.c endif L_SRCS += aos/ble.c include $(BUILD_MODULE) gen_btconfig: @make -C kernel/protocols/bluetooth/ endif L_PATH := $(call cur-dir) L_POSIX_PATH := $(L_PATH) $(call include-all-subdir-makefiles,$(L_PATH))
YifuLiu/AliOS-Things
components/ble_host/bt_host/build.mk
Makefile
apache-2.0
3,284
ccflags-y += -I$(srctree)/subsys/bluetooth obj-y += dummy.o obj-$(CONFIG_BT_DEBUG) += log.o obj-$(CONFIG_BT_RPA) += rpa.o
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/Makefile
Makefile
apache-2.0
123
/* * Copyright (c) 2019 Oticon A/S * * SPDX-License-Identifier: Apache-2.0 */ #include <stddef.h> #include <misc/util.h> u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value) { u8_t divisor = 100; u8_t num_digits = 0; u8_t digit; while (buflen > 0 && divisor > 0) { digit = value / divisor; if (digit != 0 || divisor == 1 || num_digits != 0) { *buf = (char)digit + '0'; buf++; buflen--; num_digits++; } value -= digit * divisor; divisor /= 10; } if (buflen) { *buf = '\0'; } return num_digits; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/dec.c
C
apache-2.0
535
/** * @file dummy.c * Static compilation checks. */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <ble_os.h> #if defined(CONFIG_BT_HCI_HOST) /* The Bluetooth subsystem requires the Tx thread to execute at higher priority * than the Rx thread as the Tx thread needs to process the acknowledgements * before new Rx data is processed. This is a necessity to correctly detect * transaction violations in ATT and SMP protocols. */ BUILD_ASSERT(CONFIG_BT_HCI_TX_PRIO < CONFIG_BT_RX_PRIO); #endif #if defined(CONFIG_BT_CTLR) /* The Bluetooth Controller's priority receive thread priority shall be higher * than the Bluetooth Host's Tx and the Controller's receive thread priority. * This is required in order to dispatch Number of Completed Packets event * before any new data arrives on a connection to the Host threads. */ BUILD_ASSERT(CONFIG_BT_CTLR_RX_PRIO < CONFIG_BT_HCI_TX_PRIO); #endif /* CONFIG_BT_CTLR */ /* Immediate logging is not supported with the software-based Link Layer * since it introduces ISR latency due to outputting log messages with * interrupts disabled. */ #if !defined(CONFIG_TEST) && !defined(CONFIG_ARCH_POSIX) && \ defined(CONFIG_BT_LL_SW_SPLIT) BUILD_ASSERT(!IS_ENABLED(CONFIG_LOG_IMMEDIATE), "Immediate logging not " "supported with the software Link Layer"); #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/dummy.c
C
apache-2.0
1,378
/* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <stddef.h> #include <ble_types/types.h> #include <bt_errno.h> #include <misc/util.h> int char2hex(char c, u8_t *x) { if (c >= '0' && c <= '9') { *x = c - '0'; } else if (c >= 'a' && c <= 'f') { *x = c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { *x = c - 'A' + 10; } else { return -EINVAL; } return 0; } int hex2char(u8_t x, char *c) { if (x <= 9) { *c = x + '0'; } else if (x >= 10 && x <= 15) { *c = x - 10 + 'a'; } else { return -EINVAL; } return 0; } size_t bin2hex(const u8_t *buf, size_t buflen, char *hex, size_t hexlen) { if ((hexlen + 1) < buflen * 2) { return 0; } for (size_t i = 0; i < buflen; i++) { if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) { return 0; } if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) { return 0; } } hex[2 * buflen] = '\0'; return 2 * buflen; } size_t hex2bin(const char *hex, size_t hexlen, u8_t *buf, size_t buflen) { u8_t dec; if (buflen < hexlen / 2 + hexlen % 2) { return 0; } /* if hexlen is uneven, insert leading zero nibble */ if (hexlen % 2) { if (char2hex(hex[0], &dec) < 0) { return 0; } buf[0] = dec; hex++; buf++; } /* regular hex conversion */ for (size_t i = 0; i < hexlen / 2; i++) { if (char2hex(hex[2 * i], &dec) < 0) { return 0; } buf[i] = dec << 4; if (char2hex(hex[2 * i + 1], &dec) < 0) { return 0; } buf[i] += dec; } return hexlen / 2 + hexlen % 2; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/hex.c
C
apache-2.0
1,523
/* log.c - logging helpers */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /* Helper for printk parameters to convert from binary to hex. * We declare multiple buffers so the helper can be used multiple times * in a single printk call. */ #include <stddef.h> #include <ble_types/types.h> #include <ble_os.h> #include <misc/util.h> #include <bluetooth/bluetooth.h> #include <bluetooth/uuid.h> #include <bluetooth/hci.h> const char *bt_hex_real(const void *buf, size_t len) { static const char hex[] = "0123456789abcdef"; static char str[129]; const u8_t *b = buf; size_t i; len = MIN(len, (sizeof(str) - 1) / 2); for (i = 0; i < len; i++) { str[i * 2] = hex[b[i] >> 4]; str[i * 2 + 1] = hex[b[i] & 0xf]; } str[i * 2] = '\0'; return str; } const char *bt_addr_str_real(const bt_addr_t *addr) { static char str[BT_ADDR_STR_LEN]; bt_addr_to_str(addr, str, sizeof(str)); return str; } const char *bt_addr_le_str_real(const bt_addr_le_t *addr) { static char str[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(addr, str, sizeof(str)); return str; } const char *bt_uuid_str_real(const struct bt_uuid *uuid) { static char str[BT_UUID_STR_LEN]; bt_uuid_to_str(uuid, str, sizeof(str)); return str; } void hextostring(const uint8_t *source, char *dest, int len) { int i; char tmp[3]; for (i = 0; i < len; i++) { sprintf(tmp, "%02x", (unsigned char)source[i]); memcpy(&dest[i * 2], tmp, 2); } } u8_t stringtohex(char *str, u8_t *out, u8_t count) { u8_t i = 0, j = 0; u8_t n = 0; memset(out, 0, count); if (strlen(str) != count << 1) { return 0; } while (i < count) { while (j < 2) { n = i * 2 + j; if (str[n] >= 'a' && str[n] <= 'f') { out[i] = out[i] << 4 | (str[n] - 'a' + 10); } else if (str[n] >= 'A' && str[n] <= 'F') { out[i] = out[i] << 4 | (str[n] - 'A' + 10); } else if (str[n] >= '0' && str[n] <= '9') { out[i] = out[i] << 4 | (str[n] - '0'); } else { return 0; } j++; } j = 0; i++; } return count; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/log.c
C
apache-2.0
2,286
/** * @file rpa.c * Resolvable Private Address Generation and Resolution */ /* * 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> #ifndef ENOTSUP #define ENOTSUP 134 /* unsupported*/ #endif #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_RPA) #define LOG_MODULE_NAME bt_rpa #include "common/log.h" #if defined(CONFIG_BT_CTLR) && defined(CONFIG_BT_HOST_CRYPTO) #include "../controller/util/util.h" #include "../controller/hal/ecb.h" #endif /* defined(CONFIG_BT_CTLR) && defined(CONFIG_BT_HOST_CRYPTO) */ #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_CTLR_PRIVACY) static int internal_rand(void *buf, size_t len) { /* Force using controller rand function. */ #if defined(CONFIG_BT_CTLR) && defined(CONFIG_BT_HOST_CRYPTO) return util_rand(buf, len); #else return bt_rand(buf, len); #endif } #endif /* defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_CTLR_PRIVACY) */ static int internal_encrypt_le(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) { /* Force using controller encrypt function if supported. */ #if defined(CONFIG_BT_CTLR) && defined(CONFIG_BT_HOST_CRYPTO) && \ defined(CONFIG_BT_CTLR_LE_ENC) ecb_encrypt(key, plaintext, enc_data, NULL); return 0; #else return bt_encrypt_le(key, plaintext, enc_data); #endif } static int ah(const u8_t irk[16], const u8_t r[3], u8_t out[3]) { u8_t res[16]; int err; BT_DBG("irk %s", bt_hex(irk, 16)); BT_DBG("r %s", bt_hex(r, 3)); /* r' = padding || r */ memcpy(res, r, 3); (void)memset(res + 3, 0, 13); err = bt_encrypt_le(irk, res, res); if (err) { return err; } /* The output of the random address function ah is: * ah(h, r) = e(k, r') mod 2^24 * The output of the security function e is then truncated to 24 bits * by taking the least significant 24 bits of the output of e as the * result of ah. */ memcpy(out, res, 3); return 0; } #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CTLR_PRIVACY) bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr) { u8_t hash[3]; int err; BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr)); err = ah(irk, addr->val + 3, hash); if (err) { return false; } return !memcmp(addr->val, hash, 3); } #endif #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_CTLR_PRIVACY) int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) { int err; err = bt_rand(rpa->val + 3, 3); if (err) { return err; } BT_ADDR_SET_RPA(rpa); err = ah(irk, rpa->val + 3, rpa->val); if (err) { return err; } BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val)); return 0; } #else int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) { return -ENOTSUP; } #endif /* CONFIG_BT_PRIVACY */
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/rpa.c
C
apache-2.0
2,956
/* rpa.h - Bluetooth Resolvable Private Addresses (RPA) generation and * resolution */ /* * Copyright (c) 2017 Nordic Semiconductor ASA * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr); int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa);
YifuLiu/AliOS-Things
components/ble_host/bt_host/common/rpa.h
C
apache-2.0
416
/****************************************************************************** * * Copyright (C) 2016 Realtek 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. * ******************************************************************************/ /****************************************************************************** * * Module Name: * bt_list.c * * Abstract: * To implement list data structure * * Major Change History: * When Who What * -------------------------------------------------------------- * 2010-06-04 W.Bi Created * * Notes: * ******************************************************************************/ #include "bt_list.h" //**************************************************************************** // Structure //**************************************************************************** //**************************************************************************** // FUNCTION //**************************************************************************** //Initialize a list with its header void ListInitializeHeader(PRT_LIST_HEAD ListHead) { ListHead->Next = ListHead; ListHead->Prev = ListHead; } /** Tell whether the list is empty \param [IN] ListHead <RT_LIST_ENTRY> : List header of which to be test */ unsigned char ListIsEmpty(PRT_LIST_HEAD ListHead) { return ListHead->Next == ListHead; } /* Insert a new entry between two known consecutive entries. This is only for internal list manipulation where we know the prev&next entries already @New : New element to be added @Prev: previous element in the list @Next: Next element in the list */ void ListAdd( PRT_LIST_ENTRY New, PRT_LIST_ENTRY Prev, PRT_LIST_ENTRY Next ) { Next->Prev = New; New->Next = Next; New->Prev = Prev; Prev->Next = New; } /** Add a new entry to the list. Insert a new entry after the specified head. This is good for implementing stacks. \param [IN] ListNew <RT_LIST_ENTRY> : new entry to be added \param [IN OUT] ListHead <RT_LIST_ENTRY> : List header after which to add new entry */ void ListAddToHead( PRT_LIST_ENTRY ListNew, PRT_LIST_HEAD ListHead ) { ListAdd(ListNew, ListHead, ListHead->Next); } /** Add a new entry to the list. Insert a new entry before the specified head. This is good for implementing queues. \param [IN] ListNew <RT_LIST_ENTRY> : new entry to be added \param [IN OUT] ListHead <RT_LIST_ENTRY> : List header before which to add new entry */ void ListAddToTail( PRT_LIST_ENTRY ListNew, PRT_LIST_HEAD ListHead ) { ListAdd(ListNew, ListHead->Prev, ListHead); } RT_LIST_ENTRY* ListGetTop( PRT_LIST_HEAD ListHead ) { if (ListIsEmpty(ListHead)) return 0; return ListHead->Next; } RT_LIST_ENTRY* ListGetTail( PRT_LIST_HEAD ListHead ) { if (ListIsEmpty(ListHead)) return 0; return ListHead->Prev; } /** Delete entry from the list Note: ListIsEmpty() on this list entry would not return true, since its state is undefined \param [IN] ListToDelete <RT_LIST_ENTRY> : list entry to be deleted */ void ListDeleteNode(PRT_LIST_ENTRY ListToDelete) { // if (ListToDelete->Next != NULL && ListToDelete->Prev != NULL) { ListToDelete->Next->Prev = ListToDelete->Prev; ListToDelete->Prev->Next = ListToDelete->Next; ListToDelete->Next = ListToDelete->Prev = ListToDelete; } }
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/bt_list.c
C
apache-2.0
4,158
/****************************************************************************** * * Copyright (C) 2016 Realtek 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. * ******************************************************************************/ /****************************************************************************** * * Module Name: * bt_list.h * * Abstract: * To implement list data structure * * Major Change History: * When Who What * -------------------------------------------------------------- * 2010-06-04 W.Bi Created * * Notes: * ******************************************************************************/ #ifndef BT_LIST_H #define BT_LIST_H /** \file bt_list.h \brief Implement bluetooth list data structure. Has referred to Linux list implementation You could add your new list manipulation here. */ /** List entry structure, could be header or node. Prev<-----Header---->Next Every List has an additional header, and list tail will be list header's previous node. You can use list to form a queue or a stack data structure queue: ListAddToTail----->LIST_FOR_EACH iterate--->manipulate on the list entry Stack: ListAddToHead--- >LIST_FOR_EACH iterate--->manipulate on the list entry */ ///RT list structure definition typedef struct _RT_LIST_ENTRY { struct _RT_LIST_ENTRY *Next; ///< Entry's next element struct _RT_LIST_ENTRY *Prev; ///< Entry's previous element } RT_LIST_ENTRY, *PRT_LIST_ENTRY; ///List head would be another name of list entry, and it points to the list header typedef RT_LIST_ENTRY RT_LIST_HEAD, *PRT_LIST_HEAD; /*---------------------------------------------------------------------------------- EXTERNAL FUNCTION ----------------------------------------------------------------------------------*/ ///Initialize a list with its header void ListInitializeHeader(PRT_LIST_HEAD ListHead); /** Add a new entry to the list. Insert a new entry after the specified head. This is good for implementing stacks. \param [IN] ListNew <RT_LIST_ENTRY> : new entry to be added \param [IN OUT] ListHead <RT_LIST_ENTRY> : List header after which to add new entry */ void ListAddToHead(PRT_LIST_ENTRY ListNew, PRT_LIST_HEAD ListHead); /** Add a new entry to the list. Insert a new entry before the specified head. This is good for implementing queues. \param [IN] ListNew <RT_LIST_ENTRY> : new entry to be added \param [IN OUT] ListHead <RT_LIST_ENTRY> : List header before which to add new entry */ void ListAddToTail(PRT_LIST_ENTRY ListNew, PRT_LIST_HEAD ListHead); /** Get entry in the head of the list \param [IN ] ListHead <RT_LIST_ENTRY> : List header \return entry in the head , otherwise NULL */ RT_LIST_ENTRY* ListGetTop(PRT_LIST_HEAD ListHead); /** Get entry in the tail of the list \param [IN ] ListHead <RT_LIST_ENTRY> : List header \return entry in the tail , otherwise NULL */ RT_LIST_ENTRY* ListGetTail( PRT_LIST_HEAD ListHead ); /** Delete entry from the list Note: ListIsEmpty() on this list entry would not return true, since its state is undefined \param [IN] ListToDelete <RT_LIST_ENTRY> : list entry to be deleted */ void ListDeleteNode(PRT_LIST_ENTRY ListToDelete); /** Tell whether the list is empty \param [IN] ListHead <RT_LIST_ENTRY> : List header of which to be test */ unsigned char ListIsEmpty(PRT_LIST_HEAD ListHead); //EXTERN void ListEmpty(PRT_LIST_HEAD ListHead); void ListAdd( PRT_LIST_ENTRY New, PRT_LIST_ENTRY Prev, PRT_LIST_ENTRY Next ); /*---------------------------------------------------------------------------------- MACRO ----------------------------------------------------------------------------------*/ /** Macros to iterate over the list. \param _Iter : struct PRT_LIST_ENTRY type iterator to use as a loop cursor \param _ListHead : List head of which to be iterated */ #define LIST_FOR_EACH(_Iter, _ListHead) \ for ((_Iter) = (_ListHead)->Next; (_Iter) != (_ListHead); (_Iter) = (_Iter)->Next) /** Macros to iterate over the list safely against removal of list entry. If you would delete any list entry from the list while iterating the list, should use this macro \param _Iter : Struct PRT_LIST_ENTRY type iterator to use as a loop cursor \param _Temp : Another Struct PRT_LIST_ENTRY type to use as a temporary storage \param _ListHead : List head of which to be iterated */ #define LIST_FOR_EACH_SAFELY(_Iter, _Temp, _ListHead) \ for ((_Iter) = (_ListHead)->Next, (_Temp) = (_Iter)->Next; (_Iter) != (_ListHead); \ (_Iter) = (_Temp), (_Temp) = (_Iter)->Next) /** Macros to get the struct pointer of this list entry You could make every RT_LIST_ENTRY at the first place of your structure to avoid the macro, which will be dangerouse. Copy from winnt.h. BUG:if offset of field in type larger than 32 bit interger, which is not likely to happen, it will error \param _Ptr : Struct RT_LIST_ENTRY type pointer \param _Type : The type of structure in which the RT_LIST_ENTRY embedded in \param _Field : the name of the RT_LIST_ENTRY within the struct */ #define LIST_ENTRY(_Ptr, _Type, _Field) ((_Type *)((char *)(_Ptr)-(unsigned long)(&((_Type *)0)->_Field))) #endif /*BT_LIST_H*/
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/bt_list.h
C
apache-2.0
6,172
/****************************************************************************** * * Copyright (C) 2016 Realtek 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. * ******************************************************************************/ /****************************************************************************** * * Module Name: * bt_skbuff.c * * Abstract: * Data buffer managerment through whole bluetooth stack. * * Major Change History: * When Who What * -------------------------------------------------------------- * 2010-06-11 W.Bi Created. * * Notes: * To reduce memory copy when pass data buffer to other layers, * RTK_BUFFER is designed referring to linux socket buffer. * But I still wonder its effect, since RTK_BUFFER is much bigger * than original data buffer.RTK_BUFFER will reduce its member if * it would not reach what i had expected. * ******************************************************************************/ #define LOG_TAG "bt_h5" #undef NDEBUG #include <stdlib.h> #include <aos/kernel.h> #include <bt_errno.h> #include "bt_list.h" #include "bt_skbuff.h" #include "string.h" #define IN #define OUT #ifndef false #define false 0 #endif #ifndef ture #define true 1 #endif //**************************************************************************** // CONSTANT DEFINITION //**************************************************************************** ///default header size ///l2cap header(8)+hci acl(4) #define DEFAULT_HEADER_SIZE (8+4) //RTK_BUFFER data buffer alignment #define RTB_ALIGN 4 //do alignment with RTB_ALIGN #define RTB_DATA_ALIGN(_Length) ((_Length + (RTB_ALIGN - 1)) & (~(RTB_ALIGN - 1))) //**************************************************************************** // STRUCTURE DEFINITION //**************************************************************************** typedef struct _RTB_QUEUE_HEAD{ RT_LIST_HEAD List; uint32_t QueueLen; aos_mutex_t Lock; uint8_t Id[RTB_QUEUE_ID_LENGTH]; }RTB_QUEUE_HEAD, *PRTB_QUEUE_HEAD; //**************************************************************************** // FUNCTION //**************************************************************************** /** check whether queue is empty \return : false Queue is not empty TRU Queue is empty */ unsigned char RtbQueueIsEmpty( IN RTB_QUEUE_HEAD* RtkQueueHead ) { //return ListIsEmpty(&RtkQueueHead->List); return RtkQueueHead->QueueLen > 0 ? false : true; } /** Allocate a RTK_BUFFER with specified data length and reserved headroom. If caller does not know actual headroom to reserve for further usage, specify it to zero to use default value. \param [IN] Length <uint32_t> : current data buffer length to allcated \param [IN] HeadRoom <uint32_t> : if caller knows reserved head space, set it; otherwise set 0 to use default value \return pointer to RTK_BUFFER if succeed, null otherwise */ RTK_BUFFER* RtbAllocate( uint32_t Length, uint32_t HeadRoom ) { RTK_BUFFER* Rtb = NULL; ///Rtb buffer length: /// RTK_BUFFER 48 /// HeadRoom HeadRomm or 12 /// Length ///memory size: 48 + Length + 12(default) + 8*2(header for each memory) ---> a multiple of 8 ///example: (48 + 8)+ (300 + 12 + 8) = 372 Rtb = malloc( sizeof(RTK_BUFFER) ); if(Rtb) { uint32_t BufferLen = HeadRoom ? (Length + HeadRoom) : (Length + DEFAULT_HEADER_SIZE); BufferLen = RTB_DATA_ALIGN(BufferLen); Rtb->Head = malloc(BufferLen); if(Rtb->Head) { Rtb->HeadRoom = HeadRoom ? HeadRoom : DEFAULT_HEADER_SIZE; Rtb->Data = Rtb->Head + Rtb->HeadRoom; Rtb->End = Rtb->Data; Rtb->Tail = Rtb->End + Length; Rtb->Length = 0; ListInitializeHeader(&Rtb->List); Rtb->RefCount = 1; return Rtb; } } if (Rtb) { if (Rtb->Head) { free(Rtb->Head); } free(Rtb); } return NULL; } /** Free specified Rtk_buffer \param [IN] RtkBuffer <RTK_BUFFER*> : buffer to free */ void RtbFree( RTK_BUFFER* RtkBuffer ) { if(RtkBuffer) { free(RtkBuffer->Head); free(RtkBuffer); } return; } /** Add a specified length protocal header to the start of data buffer hold by specified rtk_buffer. This function extends used data area of the buffer at the buffer start. \param [IN OUT] RtkBuffer <RTK_BUFFER*> : data buffer to add \param [IN] Length <uint32_t> : header length \return Pointer to the first byte of the extra data is returned */ uint8_t* RtbAddHead( RTK_BUFFER* RtkBuffer, uint32_t Length ) { if ((uint32_t)(RtkBuffer->Data - RtkBuffer->Head) >= Length) { RtkBuffer->Data -= Length; RtkBuffer->Length += Length; RtkBuffer->HeadRoom -= Length; return RtkBuffer->Data; } return NULL; } /** Remove a specified length data from the start of data buffer hold by specified rtk_buffer. This function returns the memory to the headroom. \param [IN OUT] RtkBuffer <RTK_BUFFER*> : data buffer to remove \param [IN] Length <uint32_t> : header length \return Pointer to the next data in the buffer is returned, usually useless */ unsigned char RtbRemoveHead( RTK_BUFFER* RtkBuffer, uint32_t Length ) { if (RtkBuffer->Length >= Length) { RtkBuffer->Data += Length; RtkBuffer->Length -= Length; RtkBuffer->HeadRoom += Length; return true; } return false; } /** Add a specified length protocal header to the end of data buffer hold by specified rtk_buffer. This function extends used data area of the buffer at the buffer end. \param [IN OUT] RtkBuffer <RTK_BUFFER*> : data buffer to add \param [IN] Length <uint32_t> : header length \return Pointer to the first byte of the extra data is returned */ uint8_t* RtbAddTail( RTK_BUFFER* RtkBuffer, uint32_t Length ) { if ((uint32_t)(RtkBuffer->Tail - RtkBuffer->End) >= Length) { uint8_t* Tmp = RtkBuffer->End; RtkBuffer->End += Length; RtkBuffer->Length += Length; return Tmp; } return NULL; } unsigned char RtbRemoveTail( IN OUT RTK_BUFFER * RtkBuffer, IN uint32_t Length ) { if ((uint32_t)(RtkBuffer->End - RtkBuffer->Data) >= Length) { RtkBuffer->End -= Length; RtkBuffer->Length -= Length; return true; } return false; } //**************************************************************************** // RTB list manipulation //**************************************************************************** /** Initialize a rtb queue. \return Initilized rtb queue if succeed, otherwise NULL */ RTB_QUEUE_HEAD* RtbQueueInit( ) { RTB_QUEUE_HEAD* RtbQueue = NULL; RtbQueue = malloc(sizeof(RTB_QUEUE_HEAD)); if(RtbQueue) { aos_mutex_new(&RtbQueue->Lock); ListInitializeHeader(&RtbQueue->List); RtbQueue->QueueLen = 0; return RtbQueue; } //error code comes here if (RtbQueue) { free(RtbQueue); } return NULL; } /** Free a rtb queue. \param [IN] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue */ void RtbQueueFree( RTB_QUEUE_HEAD* RtkQueueHead ) { if (RtkQueueHead) { RtbEmptyQueue(RtkQueueHead); aos_mutex_free(&RtkQueueHead->Lock); free(RtkQueueHead); } } /** Queue specified RtkBuffer into a RtkQueue at list tail. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer to add */ void RtbQueueTail( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* RtkBuffer ) { aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); ListAddToTail(&RtkBuffer->List, &RtkQueueHead->List); RtkQueueHead->QueueLen++; aos_mutex_unlock(&RtkQueueHead->Lock); } /** Queue specified RtkBuffer into a RtkQueue at list Head. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer to add */ void RtbQueueHead( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* RtkBuffer ) { aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); ListAddToHead(&RtkBuffer->List, &RtkQueueHead->List); RtkQueueHead->QueueLen++; aos_mutex_unlock(&RtkQueueHead->Lock); } /** Insert new Rtkbuffer in the old buffer \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] OldRtkBuffer <RTK_BUFFER*> : old rtk buffer \param [IN] NewRtkBuffer <RTK_BUFFER*> : Rtk buffer to add */ void RtbInsertBefore( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* pOldRtkBuffer, IN RTK_BUFFER* pNewRtkBuffer ) { aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); ListAdd(&pNewRtkBuffer->List, pOldRtkBuffer->List.Prev, &pOldRtkBuffer->List); RtkQueueHead->QueueLen++; aos_mutex_unlock(&RtkQueueHead->Lock); } /** check whether the buffer is the last node in the queue */ unsigned char RtbNodeIsLast( IN RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* pRtkBuffer ) { RTK_BUFFER* pBuf; aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); pBuf = (RTK_BUFFER*)RtkQueueHead->List.Prev; if(pBuf == pRtkBuffer) { aos_mutex_unlock(&RtkQueueHead->Lock); return true; } aos_mutex_unlock(&RtkQueueHead->Lock); return false; } /** get the next buffer node after the specified buffer in the queue if the specified buffer is the last node in the queue , return NULL \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer \return node after the specified buffer */ RTK_BUFFER* RtbQueueNextNode( IN RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* pRtkBuffer ) { RTK_BUFFER* pBuf; aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); pBuf = (RTK_BUFFER*)RtkQueueHead->List.Prev; if(pBuf == pRtkBuffer) { aos_mutex_unlock(&RtkQueueHead->Lock); return NULL; ///< if it is already the last node in the queue , return NULL } pBuf = (RTK_BUFFER*)pRtkBuffer->List.Next; aos_mutex_unlock(&RtkQueueHead->Lock); return pBuf; ///< return next node after this node } /** Delete specified RtkBuffer from a RtkQueue. It don't hold spinlock itself, so caller must hold it at someplace. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer to Remove */ void RtbRemoveNode( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* RtkBuffer ) { RtkQueueHead->QueueLen--; ListDeleteNode(&RtkBuffer->List); } /** Get the RtkBuffer which is the head of a RtkQueue \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return head of the RtkQueue , otherwise NULL */ RTK_BUFFER* RtbTopQueue( IN RTB_QUEUE_HEAD* RtkQueueHead ) { RTK_BUFFER* Rtb = NULL; aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); if (RtbQueueIsEmpty(RtkQueueHead)) { aos_mutex_unlock(&RtkQueueHead->Lock); return NULL; } Rtb = (RTK_BUFFER*)RtkQueueHead->List.Next; aos_mutex_unlock(&RtkQueueHead->Lock); return Rtb; } /** Remove a RtkBuffer from specified rtkqueue at list tail. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return removed rtkbuffer if succeed, otherwise NULL */ RTK_BUFFER* RtbDequeueTail( IN OUT RTB_QUEUE_HEAD* RtkQueueHead ) { RTK_BUFFER* Rtb = NULL; aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); if (RtbQueueIsEmpty(RtkQueueHead)) { aos_mutex_unlock(&RtkQueueHead->Lock); return NULL; } Rtb = (RTK_BUFFER*)RtkQueueHead->List.Prev; RtbRemoveNode(RtkQueueHead, Rtb); aos_mutex_unlock(&RtkQueueHead->Lock); return Rtb; } /** Remove a RtkBuffer from specified rtkqueue at list head. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return removed rtkbuffer if succeed, otherwise NULL */ RTK_BUFFER* RtbDequeueHead( IN OUT RTB_QUEUE_HEAD* RtkQueueHead ) { RTK_BUFFER* Rtb = NULL; aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); if (RtbQueueIsEmpty(RtkQueueHead)) { aos_mutex_unlock(&RtkQueueHead->Lock); return NULL; } Rtb = (RTK_BUFFER*)RtkQueueHead->List.Next; RtbRemoveNode(RtkQueueHead, Rtb); aos_mutex_unlock(&RtkQueueHead->Lock); return Rtb; } /** Get current rtb queue's length. \param [IN] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return current queue's length */ signed long RtbGetQueueLen( IN RTB_QUEUE_HEAD* RtkQueueHead ) { return RtkQueueHead->QueueLen; } /** Empty the rtkqueue. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue */ void RtbEmptyQueue( IN OUT RTB_QUEUE_HEAD* RtkQueueHead ) { RTK_BUFFER* Rtb = NULL; aos_mutex_lock(&RtkQueueHead->Lock, AOS_WAIT_FOREVER); while( !RtbQueueIsEmpty(RtkQueueHead)) { Rtb = (RTK_BUFFER*)RtkQueueHead->List.Next; RtbRemoveNode(RtkQueueHead, Rtb); RtbFree(Rtb); } aos_mutex_unlock(&RtkQueueHead->Lock); return; } ///Annie_tmp unsigned char RtbCheckQueueLen(IN RTB_QUEUE_HEAD* RtkQueueHead, IN uint8_t Len) { return RtkQueueHead->QueueLen < Len ? true : false; } /** clone buffer for upper or lower layer, because original buffer should be stored in l2cap \param <RTK_BUFFER* pDataBuffer: original buffer \return cloned buffer */ RTK_BUFFER* RtbCloneBuffer( IN RTK_BUFFER* pDataBuffer ) { RTK_BUFFER* pNewBuffer = NULL; if(pDataBuffer) { pNewBuffer = RtbAllocate(pDataBuffer->Length,0); if(!pNewBuffer) { return NULL; } if(pDataBuffer && pDataBuffer->Data) memcpy(pNewBuffer->Data, pDataBuffer->Data, pDataBuffer->Length); else { RtbFree(pNewBuffer); return NULL; } pNewBuffer->Length = pDataBuffer->Length; } return pNewBuffer; } /*********************************************** // //skb related functions // // // ***********************************************/ uint8_t *hci_skb_get_data(IN sk_buff *skb) { return skb->Data; } uint32_t hci_skb_get_data_length(IN sk_buff *skb) { return skb->Length; } sk_buff *hci_skb_alloc(IN unsigned int len) { sk_buff *skb = (sk_buff *)RtbAllocate(len, 0); return skb; } void hci_skb_free(IN OUT sk_buff **skb) { RtbFree(*skb); *skb = NULL; return; } void hci_skb_unlink(sk_buff *skb, struct _RTB_QUEUE_HEAD *list) { RtbRemoveNode(list, skb); } // increase the date length in sk_buffer by len, // and return the increased header pointer uint8_t *hci_skb_put(OUT sk_buff *skb, IN uint32_t len) { RTK_BUFFER *rtb = (RTK_BUFFER *)skb; return RtbAddTail(rtb, len); } // change skb->len to len // !!! len should less than skb->len void hci_skb_trim(sk_buff *skb, unsigned int len) { RTK_BUFFER *rtb = (RTK_BUFFER *)skb; uint32_t skb_len = hci_skb_get_data_length(skb); RtbRemoveTail(rtb, (skb_len - len)); return; } uint8_t hci_skb_get_pkt_type(sk_buff *skb) { return BT_CONTEXT(skb)->PacketType; } void hci_skb_set_pkt_type(sk_buff *skb, uint8_t pkt_type) { BT_CONTEXT(skb)->PacketType = pkt_type; } // decrease the data length in sk_buffer by len, // and move the content forward to the header. // the data in header will be removed. void hci_skb_pull(OUT sk_buff *skb, IN uint32_t len) { RTK_BUFFER *rtb = (RTK_BUFFER *)skb; RtbRemoveHead(rtb, len); return; } sk_buff *hci_skb_alloc_and_init(IN uint8_t PktType, IN uint8_t *Data, IN uint32_t DataLen) { sk_buff *skb = hci_skb_alloc(DataLen); if (NULL == skb) { return NULL; } memcpy(hci_skb_put(skb, DataLen), Data, DataLen); hci_skb_set_pkt_type(skb, PktType); return skb; } void hci_skb_queue_head(IN RTB_QUEUE_HEAD *skb_head, IN RTK_BUFFER *skb) { RtbQueueHead(skb_head, skb); } void hci_skb_queue_tail(IN RTB_QUEUE_HEAD *skb_head, IN RTK_BUFFER *skb) { RtbQueueTail(skb_head, skb); } RTK_BUFFER *hci_skb_dequeue_head(IN RTB_QUEUE_HEAD *skb_head) { return RtbDequeueHead(skb_head); } RTK_BUFFER *hci_skb_dequeue_tail(IN RTB_QUEUE_HEAD *skb_head) { return RtbDequeueTail(skb_head); } uint32_t hci_skb_queue_get_length(IN RTB_QUEUE_HEAD *skb_head) { return RtbGetQueueLen(skb_head); }
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/bt_skbuff.c
C
apache-2.0
18,069
/****************************************************************************** * * Copyright (C) 2016 Realtek 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. * ******************************************************************************/ /****************************************************************************** * * Module Name: * bt_skbuff.h * * Abstract: * Data buffer managerment through whole bluetooth stack. * * Major Change History: * When Who What * -------------------------------------------------------------- * 2010-06-11 W.Bi Created. * * Notes: * To reduce memory copy when pass data buffer to other layers, * RTK_BUFFER is designed referring to linux socket buffer. * But I still wonder its effect, since RTK_BUFFER is much bigger * than original data buffer.RTK_BUFFER will reduce its member if * it would not reach what i had expected. * ******************************************************************************/ #ifndef BT_SKBUFF_H #define BT_SKBUFF_H #include "bt_list.h" #include <stdint.h> #ifndef EXTERN #define EXTERN #endif #ifndef IN #define IN #endif #ifndef OUT #define OUT #endif /*---------------------------------------------------------------------------------- CONSTANT DEFINITION ----------------------------------------------------------------------------------*/ #define RTK_CONTEXT_SIZE 12 #define RTB_QUEUE_ID_LENGTH 64 struct BT_RTB_CONTEXT{ uint8_t PacketType; uint16_t Handle; }; /*---------------------------------------------------------------------------------- STRUCTURE DEFINITION ----------------------------------------------------------------------------------*/ /** Rtk buffer definition Head -->|<---Data--->|<-----Length------>| <---End _________________________________ |_____________|___________________| |<-headroom->|<--RealDataBuffer-->| Compared to socket buffer, there exists no tail and end pointer and tailroom as tail is rarely used in bluetooth stack \param List : List structure used to list same type rtk buffer and manipulate rtk buffer like list. \param Head : Pointer to truely allocated data buffer. It point to the headroom \param Data : Pointer to real data buffer. \param Length : currently data length \param HeadRoom : Record initialize headroom size. \param RefCount : Reference count. zero means able to be freed, otherwise somebody is handling it. \param Priv : Reserved for multi-device support. Record Hci pointer which will handles this packet \param Contest : Control buffer, put private variables here. */ typedef struct _RTK_BUFFER { RT_LIST_ENTRY List; uint8_t *Head; uint8_t *Data; uint8_t *Tail; uint8_t *End; uint32_t Length; uint32_t HeadRoom; // RT_U16 TailRoom; signed char RefCount; void* Priv; union { uint8_t Context[RTK_CONTEXT_SIZE]; struct BT_RTB_CONTEXT rtb_ctx; }; }RTK_BUFFER, *PRTK_BUFFER; /** RTK_BUFFER Control Buffer Context \param PacketType : HCI data types, Command/Acl/... \param LastFrag : Is Current Acl buffer the last fragment.(0 for no, 1 for yes) \param TxSeq : Current packet tx sequence \param Retries : Current packet retransmission times \param Sar : L2cap control field segmentation and reassembly bits */ ///definition to get rtk_buffer's control buffer context pointer #define BT_CONTEXT(_Rtb) (&((_Rtb)->rtb_ctx)) /** Since RTBs are always used into/from list, so abstract this struct and provide APIs to easy process on RTBs */ typedef struct _RTB_QUEUE_HEAD RTB_QUEUE_HEAD; /*---------------------------------------------------------------------------------- EXTERNAL FUNCTION ----------------------------------------------------------------------------------*/ /** Allocate a RTK_BUFFER with specified data length and reserved headroom. If caller does not know actual headroom to reserve for further usage, specify it to zero to use default value. \param [IN] Length <uint32_t> : current data buffer length to allcated \param [IN] HeadRoom <uint32_t> : if caller knows reserved head space, set it; otherwise set 0 to use default value \return pointer to RTK_BUFFER if succeed, null otherwise */ RTK_BUFFER* RtbAllocate( IN uint32_t Length, IN uint32_t HeadRoom ); /** Free specified Rtk_buffer \param [IN] RtkBuffer <RTK_BUFFER*> : buffer to free */ void RtbFree( IN RTK_BUFFER* RtkBuffer ); /** increament reference count */ void RtbIncreaseRefCount( IN RTK_BUFFER* RtkBuffer ); /** Recycle a rtk_buffer after its usage if specified rtb could if rtb total length is not smaller than specified rtbsize to be recycled for, it will succeeded recycling \param [IN OUT] RtkBuffer <RTK_BUFFER*> : buffer to recycle \param [IN] RtbSize <uint32_t> : size of buffer to be recycled for */ /* BOOLEAN RtbCheckRecycle( IN OUT RTK_BUFFER* RtkBuffer, IN uint32_t RtbSize ); */ /** Add a specified length protocal header to the start of data buffer hold by specified rtk_buffer. This function extends used data area of the buffer at the buffer start. \param [IN OUT] RtkBuffer <RTK_BUFFER*> : data buffer to add \param [IN] Length <uint32_t> : header length \return Pointer to the first byte of the extra data is returned */ uint8_t* RtbAddHead( IN OUT RTK_BUFFER* RtkBuffer, IN uint32_t Length ); /** Remove a specified length data from the start of data buffer hold by specified rtk_buffer. This function returns the memory to the headroom. \param [IN OUT] RtkBuffer <RTK_BUFFER*> : data buffer to remove \param [IN] Length <uint32_t> : header length \return Pointer to the next data in the buffer is returned, usually useless */ unsigned char RtbRemoveHead( IN OUT RTK_BUFFER* RtkBuffer, IN uint32_t Length ); /** Add a specified length protocal header to the end of data buffer hold by specified rtk_buffer. This function extends used data area of the buffer at the buffer end. \param [IN OUT] RtkBuffer <RTK_BUFFER*> : data buffer to add \param [IN] Length <uint32_t> : header length \return Pointer to the first byte of the extra data is returned */ EXTERN uint8_t* RtbAddTail( IN OUT RTK_BUFFER* RtkBuffer, IN uint32_t Length ); /** Remove a specified length data from the end of data buffer hold by specified rtk_buffer. */ EXTERN unsigned char RtbRemoveTail( IN OUT RTK_BUFFER * RtkBuffer, IN uint32_t Length ); /** Initialize a rtb queue. \return Initilized rtb queue if succeed, otherwise NULL */ EXTERN RTB_QUEUE_HEAD* RtbQueueInit( ); /** Free a rtb queue. \param [IN] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue */ EXTERN void RtbQueueFree( RTB_QUEUE_HEAD* RtkQueueHead ); /** Queue specified RtkBuffer into a RtkQueue at list tail. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer to add */ EXTERN void RtbQueueTail( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* RtkBuffer ); /** Queue specified RtkBuffer into a RtkQueue at list Head. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer to add */ EXTERN void RtbQueueHead( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* RtkBuffer ); /** Remove a RtkBuffer from specified rtkqueue at list tail. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return removed rtkbuffer if succeed, otherwise NULL */ EXTERN RTK_BUFFER* RtbDequeueTail( IN OUT RTB_QUEUE_HEAD* RtkQueueHead ); /** Remove a RtkBuffer from specified rtkqueue at list head. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return removed rtkbuffer if succeed, otherwise NULL */ EXTERN RTK_BUFFER* RtbDequeueHead( IN OUT RTB_QUEUE_HEAD* RtkQueueHead ); /** Get current rtb queue's length. \param [IN] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return current queue's length */ EXTERN signed long RtbGetQueueLen( IN RTB_QUEUE_HEAD* RtkQueueHead ); /** Empty the rtkqueue. \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue */ EXTERN void RtbEmptyQueue( IN OUT RTB_QUEUE_HEAD* RtkQueueHead ); /** Get the RtkBuffer which is the head of a RtkQueue \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \return head of the RtkQueue , otherwise NULL */ EXTERN RTK_BUFFER* RtbTopQueue( IN RTB_QUEUE_HEAD* RtkQueueHead ); /** Insert new Rtkbuffer in the old buffer \param [IN OUT] RtkQueueHead <RTB_QUEUE_HEAD*> : Rtk Queue \param [IN] OldRtkBuffer <RTK_BUFFER*> : old rtk buffer \param [IN] NewRtkBuffer <RTK_BUFFER*> : Rtk buffer to add */ EXTERN void RtbInsertBefore( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* pOldRtkBuffer, IN RTK_BUFFER* pNewRtkBuffer ); /** check whether the buffer is the last node in the queue */ EXTERN unsigned char RtbNodeIsLast( IN RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* pRtkBuffer ); /** get the next buffer node after the specified buffer in the queue if the specified buffer is the last node in the queue , return NULL \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk Queue \param [IN] RtkBuffer <RTK_BUFFER*> : Rtk buffer \return node after the specified buffer */ EXTERN RTK_BUFFER* RtbQueueNextNode( IN RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* pRtkBuffer ); /** check whether queue is empty */ /*EXTERN BOOLEAN RtbQueueIsEmpty( IN RTB_QUEUE_HEAD* RtkQueueHead ); */ //annie_tmp EXTERN unsigned char RtbCheckQueueLen( IN RTB_QUEUE_HEAD* RtkQueueHead, IN uint8_t Len ); EXTERN void RtbRemoveNode( IN OUT RTB_QUEUE_HEAD* RtkQueueHead, IN RTK_BUFFER* RtkBuffer ); EXTERN RTK_BUFFER* RtbCloneBuffer( IN RTK_BUFFER* pDataBuffer ); typedef RTK_BUFFER sk_buff; uint8_t *hci_skb_get_data(IN sk_buff *skb); uint32_t hci_skb_get_data_length(IN sk_buff *skb); sk_buff *hci_skb_alloc(IN unsigned int len); void hci_skb_free(IN OUT sk_buff **skb); void hci_skb_unlink(sk_buff *skb, struct _RTB_QUEUE_HEAD *list); uint8_t *hci_skb_put(OUT sk_buff *skb, IN uint32_t len); void hci_skb_trim(sk_buff *skb, unsigned int len); uint8_t hci_skb_get_pkt_type(sk_buff *skb); void hci_skb_set_pkt_type(sk_buff *skb, uint8_t pkt_type); void hci_skb_pull(OUT sk_buff *skb, IN uint32_t len); sk_buff *hci_skb_alloc_and_init(IN uint8_t PktType, IN uint8_t *Data, IN uint32_t DataLen); void hci_skb_queue_head(IN RTB_QUEUE_HEAD *skb_head, IN RTK_BUFFER *skb); void hci_skb_queue_tail(IN RTB_QUEUE_HEAD *skb_head, IN RTK_BUFFER *skb); RTK_BUFFER *hci_skb_dequeue_head(IN RTB_QUEUE_HEAD *skb_head); RTK_BUFFER *hci_skb_dequeue_tail(IN RTB_QUEUE_HEAD *skb_head); uint32_t hci_skb_queue_get_length(IN RTB_QUEUE_HEAD *skb_head); #endif /*BT_SKBUFF_H*/
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/bt_skbuff.h
C
apache-2.0
12,557
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef __BT_VENDOR_DRV_H_ #define __BT_VENDOR_DRV_H_ #include <stdio.h> #include <stdint.h> typedef void (*rx_ind_cb_t)(void); /** * 初始化BT驱动、加载patch、调节Coex,其他厂家IC初始化的操作 * * @return 操作状态,0代表成功,其他值表示失败 */ int bt_vendor_drv_bring_up(void); /** * 设置RX事件回调,BT Driver收到EVENT/ACL数据后,通过此接口通知BT Stack进行读取操作 * @param[in] ready_to_rx 回调函数 * @return 操作状态,0代表成功,其他值表示失败 */ int bt_vendor_drv_set_rx_ind(rx_ind_cb_t ind); /** * 从BT Controller读取EVENT/ACL数据 * @param[out] data 数据保存的起始内存地址 * @param[in] len 期望读取的数据长度 * @return 实际读取的数据长度 */ size_t bt_vendor_drv_rx(uint8_t *data, size_t len); /** * BT Stack通过此接口往Controller发送数据 * @param[in] data 数据的起始内存地址 * @param[in] len 期望发送的数据长度 * @param[in] reserve NULL * @return 实际发送的数据长度 */ size_t bt_vendor_drv_tx(uint8_t *data, size_t len, void *reserve); #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/bt_vendor_drv.h
C
apache-2.0
1,211
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef DEVICES_HCI_H_ #define DEVICES_HCI_H_ #include <stdint.h> //#include <devices/driver.h> typedef enum { HCI_EVENT_READ, } hci_event_t; #define hci_open(name) device_open(name) #define hci_open_id(name, id) device_open_id(name, id) #define hci_close(dev) device_close(dev) typedef void (*hci_event_cb_t)(hci_event_t event, uint32_t size, void *priv); typedef int (*hci_driver_send_cmd_t)(uint16_t opcode, uint8_t* send_data, uint32_t send_len, uint8_t* resp_data, uint32_t *resp_len); #ifndef YULONG_HCI #define YULONG_HCI #endif #ifndef YULONG_HCI /** \brief set hci event \param[in] dev Pointer to device object. \param[in] event data read event callback. \param[in] priv event callback userdata arg. \return 0 on success, else on fail. */ int hci_set_event(aos_dev_t *dev, hci_event_cb_t event, void *priv); /** \brief send hci format data \param[in] dev Pointer to device object. \param[in] data data address to send. \param[in] size data length expected to read. \return send data len. */ int hci_send(aos_dev_t *dev, void *data, uint32_t size); /** \brief recv hci format data \param[in] dev Pointer to device object. \param[in] data data address to read. \param[in] size data length expected to read. \return read data len. */ int hci_recv(aos_dev_t *dev, void* data, uint32_t size); /** \brief start hci driver \param[in] dev Pointer to device object. \param[out] send_cmd sned hci command callback. \return 0 on success, else on fail. */ int hci_start(aos_dev_t *dev, hci_driver_send_cmd_t send_cmd); #endif #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/devices/hci.h
C
apache-2.0
1,755
/* * 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 <bt_errno.h> #include <stddef.h> #include <ble_os.h> #define BT_DBG_ENABLED 0 #include <common/log.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/hci_driver.h> #include "bt_vendor_drv.h" #include <hci_api.h> #include <aos/kernel.h> #define H4_NONE 0x00 #define H4_CMD 0x01 #define H4_ACL 0x02 #define H4_SCO 0x03 #define H4_EVT 0x04 static int h4_open(void); static int h4_send(struct net_buf *buf); static cpu_stack_t hci_rx_task_stack[CONFIG_BT_RX_STACK_SIZE / 4]; static struct bt_hci_driver drv = { .name = "H4", .bus = BT_HCI_DRIVER_BUS_VIRTUAL, .open = h4_open, .send = h4_send, }; static struct rx_t { struct net_buf *buf; uint16_t cur_len; uint16_t remaining; uint16_t discard; uint8_t have_hdr; uint8_t discardable; uint8_t hdr_len; uint8_t type; union { struct bt_hci_evt_hdr evt; struct bt_hci_acl_hdr acl; uint8_t hdr[4]; }; uint8_t ongoing; }; static struct { const struct bt_hci_driver *drv; char *dev_name; // aos_dev_t *dev; ktask_t task; ksem_t sem; struct rx_t rx; } hci_h4 = { &drv, NULL, NULL, }; #ifndef CHIP_HAAS1000 int tg_bt_hal_vendor_bringup() { return bt_vendor_drv_bring_up(); } void tg_bt_hal_hcit_set_rx_ind_callback(rx_ind_cb_t cb) { bt_vendor_drv_set_rx_ind(cb); } size_t tg_bt_hal_hcit_rx(uint8_t *data, size_t len) { return bt_vendor_drv_rx(data, len); } size_t tg_bt_hal_hcit_tx(uint8_t *data, size_t len, void *reserve) { return bt_vendor_drv_tx(data, len, reserve); } #endif static int h4_send(struct net_buf *buf) { int ret = -1; uint8_t type = bt_buf_get_type(buf); uint8_t hcit_type[1]; BT_DBG("%s, type = %d", __func__, type); if (type == BT_BUF_ACL_OUT) { hcit_type[0] = H4_ACL; //g_hci_debug_counter.acl_out_count++; } else if (type == BT_BUF_CMD) { hcit_type[0] = H4_CMD; //g_hci_debug_counter.cmd_out_count++; } else { BT_ERR("Unknown buffer type"); return -1; } #if 1 //send in one packet uint8_t *pBuf; const int data_len = buf->len+1; pBuf = aos_malloc(data_len); if (pBuf == NULL) { BT_ERR("malloc failed"); return -1; } pBuf[0] = hcit_type[0]; memcpy(pBuf+1, buf->data, buf->len); BT_INFO("Send to driver: %s", bt_hex_real(pBuf, data_len)); ret = tg_bt_hal_hcit_tx(pBuf, data_len, NULL); aos_free(pBuf); #else tg_bt_hal_hcit_tx(hcit_type, 1, NULL); BT_DBG("buf %p type %u len %u:%s", buf, type, buf->len, bt_hex(buf->data, buf->len)); const int data_len = buf->len; BT_DBG("payload send"); ret = tg_bt_hal_hcit_tx(buf->data, buf->len, NULL); #endif if (ret > 0 && ret == data_len) { ret = 0; net_buf_unref(buf); } if (ret == -BT_HCI_ERR_MEM_CAPACITY_EXCEEDED) { ret = -ENOMEM; } return ret; } static inline int is_adv_report_event(uint8_t *data, uint16_t len) { return (data[0] == H4_EVT && data[1] == BT_HCI_EVT_LE_META_EVENT && data[3] == BT_HCI_EVT_LE_ADVERTISING_REPORT); } int hci_event_recv(uint8_t *data, uint16_t data_len) { struct net_buf *buf; uint8_t *pdata = data; int32_t len = data_len; struct bt_hci_evt_hdr hdr; uint8_t sub_event = 0; uint8_t discardable = 0; if (pdata == NULL || len == 0) { return -1; } if (*pdata++ != H4_EVT) { goto err; } if (len < 3) { goto err; } hdr.evt = *pdata++; hdr.len = *pdata++; if (len < hdr.len + 3) { goto err; } if (hdr.evt == BT_HCI_EVT_LE_META_EVENT) { sub_event = *pdata++; if (sub_event == BT_HCI_EVT_LE_ADVERTISING_REPORT) { discardable = 1; } } if (hdr.evt == BT_HCI_EVT_CMD_COMPLETE || hdr.evt == BT_HCI_EVT_CMD_STATUS) { buf = bt_buf_get_cmd_complete(0); if (buf == NULL) { //g_hci_debug_counter.event_in_is_null_count++; goto err; } } else { buf = bt_buf_get_rx(BT_BUF_EVT, 0); } if (!buf && discardable) { //g_hci_debug_counter.event_discard_count++; goto err; } if (!buf) { //g_hci_debug_counter.event_in_is_null_count++; goto err; } bt_buf_set_type(buf, BT_BUF_EVT); net_buf_add_mem(buf, ((uint8_t *)(data)) + 1, hdr.len + sizeof(hdr)); BT_DBG("event %s", bt_hex(buf->data, buf->len)); //g_hci_debug_counter.event_in_count++; if (bt_hci_evt_is_prio(hdr.evt)) { bt_recv_prio(buf); } else { bt_recv(buf); } return 0; err: return -1; } int hci_acl_recv(uint8_t *data, uint16_t data_len) { struct net_buf *buf; uint8_t *pdata = data; int32_t len = data_len; uint16_t handle; uint16_t acl_len; if (pdata == NULL || len == 0) { return -1; } if (*pdata++ != H4_ACL) { goto err; } if (len < 5) { goto err; } handle = ((*pdata + 1) << 16) | (*(pdata)); pdata += 2; acl_len = ((*pdata + 1) << 16) | (*(pdata)); pdata += 2; (void)handle; if (len < acl_len + 5) { goto err; } buf = bt_buf_get_rx(BT_BUF_ACL_IN, 0); if (!buf) { //g_hci_debug_counter.hci_in_is_null_count++; goto err; } bt_buf_set_type(buf, BT_BUF_ACL_IN); net_buf_add_mem(buf, data + 1, acl_len + 4); //g_hci_debug_counter.acl_in_count++; BT_DBG("acl %s", bt_hex(buf->data, buf->len)); bt_recv(buf); return 0; err: return -1; } static void _hci_recv_event2(void) { krhino_sem_give(&hci_h4.sem); } static void copy_hdr(struct net_buf *buf) { net_buf_add_mem(buf, hci_h4.rx.hdr, hci_h4.rx.hdr_len); } static void reset_rx(void) { hci_h4.rx.type = H4_NONE; hci_h4.rx.remaining = 0; hci_h4.rx.have_hdr = false; hci_h4.rx.hdr_len = 0; hci_h4.rx.discardable = false; } static uint32_t read_byte(uint8_t *data, uint32_t len) { int32_t read_len; read_len = tg_bt_hal_hcit_rx(data, len); if (read_len == 0) { hci_h4.rx.ongoing = 0; } return read_len; } static inline void h4_get_type(void) { /* Get packet type */ if (read_byte(&hci_h4.rx.type, 1) != 1) { hci_h4.rx.type = H4_NONE; return; } switch (hci_h4.rx.type) { case H4_EVT: hci_h4.rx.remaining = sizeof(hci_h4.rx.evt); hci_h4.rx.hdr_len = hci_h4.rx.remaining; break; case H4_ACL: hci_h4.rx.remaining = sizeof(hci_h4.rx.acl); hci_h4.rx.hdr_len = hci_h4.rx.remaining; break; default: BT_ERR("Unknown H:4 type 0x%02x", hci_h4.rx.type); hci_h4.rx.type = H4_NONE; } } static inline void get_acl_hdr(void) { struct bt_hci_acl_hdr *hdr = &hci_h4.rx.acl; int to_read = sizeof(*hdr) - hci_h4.rx.remaining; hci_h4.rx.remaining -= read_byte((uint8_t *)hdr + to_read, hci_h4.rx.remaining); if (!hci_h4.rx.remaining) { hci_h4.rx.remaining = hdr->len; BT_DBG("Got ACL header. Payload %u bytes", hci_h4.rx.remaining); hci_h4.rx.have_hdr = true; } } static inline void get_evt_hdr(void) { struct bt_hci_evt_hdr *hdr = &hci_h4.rx.evt; int32_t to_read = hci_h4.rx.hdr_len - hci_h4.rx.remaining; hci_h4.rx.remaining -= read_byte((uint8_t *)hdr + to_read, hci_h4.rx.remaining); if (!hci_h4.rx.remaining) { hci_h4.rx.remaining = hdr->len - (hci_h4.rx.hdr_len - sizeof(*hdr)); BT_DBG("Got event header. Payload %u bytes", hdr->len); hci_h4.rx.have_hdr = true; } } static int32_t h4_discard(int32_t len) { uint8_t buf[33]; return read_byte(buf, (len<sizeof(buf)?len:sizeof(buf))); } static inline void read_payload(void) { struct net_buf *buf; bool prio; int read; if (!hci_h4.rx.buf) { if (hci_h4.rx.type == H4_ACL) { hci_h4.rx.buf = buf = bt_buf_get_rx(BT_BUF_ACL_IN, 0); } else { if (hci_h4.rx.evt.evt == BT_HCI_EVT_CMD_COMPLETE || hci_h4.rx.evt.evt == BT_HCI_EVT_CMD_STATUS) { hci_h4.rx.buf = bt_buf_get_cmd_complete(0); } else { hci_h4.rx.buf = buf = bt_buf_get_rx(BT_BUF_EVT, 0); } } if (!hci_h4.rx.buf) { if (hci_h4.rx.discardable) { BT_DBG("Discarding event 0x%02x", hci_h4.rx.evt.evt); hci_h4.rx.discard = hci_h4.rx.remaining; reset_rx(); return; } BT_ERR("Failed to allocate, deferring to rx_thread"); return; } BT_DBG("Allocated h4_dev.rx.buf %p", hci_h4.rx.buf); copy_hdr(hci_h4.rx.buf); hci_h4.rx.cur_len = hci_h4.rx.hdr_len + 1; } read = read_byte(net_buf_tail(hci_h4.rx.buf), hci_h4.rx.remaining); net_buf_add(hci_h4.rx.buf, read); hci_h4.rx.cur_len += read; hci_h4.rx.remaining -= read; BT_DBG("got %d bytes, remaining %u", read, hci_h4.rx.remaining); if (hci_h4.rx.remaining) { return; } prio = ((hci_h4.rx.type == H4_EVT) && bt_hci_evt_is_prio(hci_h4.rx.evt.evt)); buf = hci_h4.rx.buf; hci_h4.rx.buf = NULL; if (hci_h4.rx.type == H4_EVT) { bt_buf_set_type(buf, BT_BUF_EVT); } else { bt_buf_set_type(buf, BT_BUF_ACL_IN); } reset_rx(); if (prio) { BT_DBG("Calling bt_recv_prio(%p)", buf); bt_recv_prio(buf); } else { BT_DBG("Putting buf %p to rx fifo", buf); bt_recv(buf); } } static inline void read_header(void) { switch (hci_h4.rx.type) { case H4_NONE: h4_get_type(); return; case H4_EVT: get_evt_hdr(); break; case H4_ACL: get_acl_hdr(); break; default: reset_rx(); return; } } static void process_rx(void) { BT_DBG("remaining %u discard %u have_hdr %u h4_dev.rx.buf %p", hci_h4.rx.remaining, hci_h4.rx.discard, hci_h4.rx.have_hdr, hci_h4.rx.buf); if (hci_h4.rx.discard) { hci_h4.rx.discard -= h4_discard(hci_h4.rx.discard); return; } if (hci_h4.rx.have_hdr) { read_payload(); } else { read_header(); } } static void recv_data(void) { do { hci_h4.rx.ongoing = 1; process_rx(); } while (hci_h4.rx.ongoing); } static void hci_rx_task(void *arg) { while (1) { krhino_sem_take(&hci_h4.sem, RHINO_WAIT_FOREVER); recv_data(); } } static int h4_open(void) { krhino_sem_create(&hci_h4.sem, "h4", 0); int ret; ret = tg_bt_hal_vendor_bringup(); if (ret != 0) { BT_ERR("vendor chip bringup failed"); return false; } tg_bt_hal_hcit_set_rx_ind_callback(_hci_recv_event2); krhino_task_create(&hci_h4.task, "hci_rx_task", NULL, CONFIG_BT_RX_PRIO, 1, hci_rx_task_stack, CONFIG_BT_RX_STACK_SIZE / 4, (task_entry_t)hci_rx_task, 1); return 0; } int hci_driver_init(char *name) { int ret; ret = bt_hci_driver_register(&drv); if (ret) { return ret; } hci_h4.dev_name = name; return 0; } int hci_h4_driver_init() { hci_driver_init("hci"); return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/h4_driver.c
C
apache-2.0
12,112
/****************************************************************************** * * Copyright (C) 2016 Realtek 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. * ******************************************************************************/ /****************************************************************************** * * Module Name: * hci_h5.c * * Abstract: * Contain HCI transport send/receive functions for UART H5 Interface. * * Major Change History: * When Who What * --------------------------------------------------------------- * 2016-09-23 cc modified * * Notes: * This is designed for UART H5 HCI Interface in Android 6.0. * ******************************************************************************/ #define LOG_TAG "bt_h5_int" #include <stdlib.h> #include <string.h> #include <aos/kernel.h> //#include <aos/osal_debug.h> //remove for build :yulong #include "bt_skbuff.h" #include "bt_list.h" //////////////////#include <devices/hci.h> #include <ble_os.h> #define BT_DBG_ENABLED 0 #include <common/log.h> #include "h5.h" #ifndef YULONG_HCI #define YULONG_HCI #endif #define H5_TRACE_DATA_ENABLE 0 #define STREAM_TO_UINT16(u16, p) {u16 = ((uint16_t)(*(p)) + (((uint16_t)(*((p) + 1))) << 8)); (p) += 2;} /****************************************************************************** ** Constants & Macros ******************************************************************************/ #define DATA_RETRANS_COUNT 40 //40*100 = 4000ms(4s) #define SYNC_RETRANS_COUNT 20 //20*250 = 5000ms(5s) #define CONF_RETRANS_COUNT 20 #define DATA_RETRANS_TIMEOUT_VALUE 1000 //ms #define SYNC_RETRANS_TIMEOUT_VALUE 250 #define CONF_RETRANS_TIMEOUT_VALUE 500 #define WAIT_CT_BAUDRATE_READY_TIMEOUT_VALUE 500 #define H5_HW_INIT_READY_TIMEOUT_VALUE 40000//4 #define HCI_VSC_H5_INIT 0xFCEE /* Maximum numbers of allowed internal ** outstanding command packets at any time */ #define INT_CMD_PKT_MAX_COUNT 8 #define INT_CMD_PKT_IDX_MASK 0x07 //HCI Event codes #define HCI_CONNECTION_COMP_EVT 0x03 #define HCI_DISCONNECTION_COMP_EVT 0x05 #define HCI_COMMAND_COMPLETE_EVT 0x0E #define HCI_COMMAND_STATUS_EVT 0x0F #define HCI_NUM_OF_CMP_PKTS_EVT 0x13 #define HCI_BLE_EVT 0x3E #define PATCH_DATA_FIELD_MAX_SIZE 252 #define READ_DATA_SIZE 16 // HCI data types // #define H5_RELIABLE_PKT 0x01 #define H5_UNRELIABLE_PKT 0x00 #define H5_ACK_PKT 0x00 #define HCI_COMMAND_PKT 0x01 #define HCI_ACLDATA_PKT 0x02 #define HCI_SCODATA_PKT 0x03 #define HCI_EVENT_PKT 0x04 #define H5_VDRSPEC_PKT 0x0E #define H5_LINK_CTL_PKT 0x0F #define H5_HDR_SEQ(hdr) ((hdr)[0] & 0x07) #define H5_HDR_ACK(hdr) (((hdr)[0] >> 3) & 0x07) #define H5_HDR_CRC(hdr) (((hdr)[0] >> 6) & 0x01) #define H5_HDR_RELIABLE(hdr) (((hdr)[0] >> 7) & 0x01) #define H5_HDR_PKT_TYPE(hdr) ((hdr)[1] & 0x0f) #define H5_HDR_LEN(hdr) ((((hdr)[1] >> 4) & 0xff) + ((hdr)[2] << 4)) #define H5_HDR_SIZE 4 #define H5_CFG_SLID_WIN(cfg) ((cfg) & 0x07) #define H5_CFG_OOF_CNTRL(cfg) (((cfg) >> 3) & 0x01) #define H5_CFG_DIC_TYPE(cfg) (((cfg) >> 4) & 0x01) #define H5_CFG_VER_NUM(cfg) (((cfg) >> 5) & 0x07) #define H5_CFG_SIZE 1 #define PACKET_TYPE_TO_INDEX(type) ((type) - 1) /* Callback function for the returned event of internal issued command */ typedef void (*tTIMER_HANDLE_CBACK)(void *timer, void *arg); typedef enum H5_RX_STATE { H5_W4_PKT_DELIMITER, H5_W4_PKT_START, H5_W4_HDR, H5_W4_DATA, H5_W4_CRC } tH5_RX_STATE; typedef enum H5_RX_ESC_STATE { H5_ESCSTATE_NOESC, H5_ESCSTATE_ESC } tH5_RX_ESC_STATE; typedef enum H5_LINK_STATE { H5_UNINITIALIZED, H5_INITIALIZED, H5_ACTIVE } tH5_LINK_STATE; #define H5_EVENT_RX 0x0001 #define H5_EVENT_EXIT 0x0200 static volatile uint8_t h5_retransfer_running = 0; static volatile uint16_t h5_ready_events = 0; static volatile uint8_t h5_data_ready_running = 0; /* Control block for HCISU_H5 */ typedef struct HCI_H5_CB { uint32_t int_cmd_rsp_pending; /* Num of internal cmds pending for ack */ uint8_t sliding_window_size; uint8_t oof_flow_control; uint8_t dic_type; RTB_QUEUE_HEAD *unack; // Unack'ed packets queue RTB_QUEUE_HEAD *rel; // Reliable packets queue RTB_QUEUE_HEAD *unrel; // Unreliable packets queue RTB_QUEUE_HEAD *recv_data; // Unreliable packets queue uint8_t rxseq_txack; // rxseq == txack. // expected rx SeqNumber uint8_t rxack; // Last packet sent by us that the peer ack'ed // uint8_t use_crc; uint8_t is_txack_req; // txack required? Do we need to send ack's to the peer? // // Reliable packet sequence number - used to assign seq to each rel pkt. */ uint8_t msgq_txseq; //next pkt seq uint16_t message_crc; uint32_t rx_count; //expected pkts to recv tH5_RX_STATE rx_state; tH5_RX_ESC_STATE rx_esc_state; tH5_LINK_STATE link_estab_state; sk_buff *rx_skb; sk_buff *data_skb; sk_buff *internal_skb; aos_timer_t *timer_data_retrans; aos_timer_t *timer_sync_retrans; aos_timer_t *timer_conf_retrans; aos_timer_t *timer_wait_ct_baudrate_ready; aos_timer_t *timer_h5_hw_init_ready; uint32_t data_retrans_count; uint32_t sync_retrans_count; uint32_t conf_retrans_count; aos_mutex_t mutex; aos_sem_t cond; aos_task_t thread_data_retrans; aos_mutex_t data_mutex; aos_sem_t data_cond; aos_task_t thread_data_ready_cb; uint8_t cleanuping; #ifndef YULONG_HCI aos_dev_t *hci_dev; #endif } tHCI_H5_CB; static tHCI_H5_CB rtk_h5; static aos_mutex_t h5_wakeup_mutex; extern int g_uart_id; extern int g_bt_dis_pin; /****************************************************************************** ** Variables ******************************************************************************/ /* Num of allowed outstanding HCI CMD packets */ volatile int num_hci_cmd_pkts = 1; /****************************************************************************** ** Static function ******************************************************************************/ static aos_timer_t *OsAllocateTimer(tTIMER_HANDLE_CBACK timer_callback); static int OsStartTimer(aos_timer_t *timerid, int msec, int mode); static int OsStopTimer(aos_timer_t *timerid); static uint16_t h5_wake_up(); static packet_recv h5_int_hal_callbacks; /****************************************************************************** ** Externs ******************************************************************************/ //timer API for retransfer static int h5_alloc_data_retrans_timer(); static int h5_free_data_retrans_timer(); static int h5_stop_data_retrans_timer(); static int h5_start_data_retrans_timer(); static int h5_alloc_sync_retrans_timer(); static int h5_free_sync_retrans_timer(); static int h5_stop_sync_retrans_timer(); static int h5_start_sync_retrans_timer(); static int h5_alloc_conf_retrans_timer(); static int h5_free_conf_retrans_timer(); static int h5_stop_conf_retrans_timer(); static int h5_start_conf_retrans_timer(); static int h5_alloc_wait_controller_baudrate_ready_timer(); static int h5_free_wait_controller_baudrate_ready_timer(); static int h5_start_wait_controller_baudrate_ready_timer(); static int h5_alloc_hw_init_ready_timer(); static int h5_free_hw_init_ready_timer(); static int h5_stop_hw_init_ready_timer(); static int h5_start_hw_init_ready_timer(); static uint32_t hci_h5_receive_msg(uint8_t *byte, uint16_t length); static int h5_enqueue(IN sk_buff *skb); // bite reverse in bytes // 00000001 -> 10000000 // 00000100 -> 00100000 static const uint8_t byte_rev_table[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, }; // reverse bit static __inline uint8_t bit_rev8(uint8_t byte) { return byte_rev_table[byte]; } // reverse bit static __inline uint16_t bit_rev16(uint16_t x) { return (bit_rev8(x & 0xff) << 8) | bit_rev8(x >> 8); } static const uint16_t crc_table[] = { 0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387, 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f }; // Initialise the crc calculator #define H5_CRC_INIT(x) x = 0xffff /** * Add "d" into crc scope, caculate the new crc value * * @param crc crc data * @param d one byte data */ static void h5_crc_update(uint16_t *crc, uint8_t d) { uint16_t reg = *crc; reg = (reg >> 4) ^ crc_table[(reg ^ d) & 0x000f]; reg = (reg >> 4) ^ crc_table[(reg ^ (d >> 4)) & 0x000f]; *crc = reg; } /** * Get crc data. * * @param h5 realtek h5 struct * @return crc data */ static uint16_t h5_get_crc(tHCI_H5_CB *h5) { uint16_t crc = 0; uint8_t *data = hci_skb_get_data(h5->rx_skb) + hci_skb_get_data_length(h5->rx_skb) - 2; crc = data[1] + (data[0] << 8); return crc; } /** * Just add 0xc0 at the end of skb, * we can also use this to add 0xc0 at start while there is no data in skb * * @param skb socket buffer */ static void h5_slip_msgdelim(sk_buff *skb) { const char pkt_delim = 0xc0; memcpy(hci_skb_put(skb, 1), &pkt_delim, 1); } /** * Slip ecode one byte in h5 proto, as follows: * 0xc0 -> 0xdb, 0xdc * 0xdb -> 0xdb, 0xdd * 0x11 -> 0xdb, 0xde * 0x13 -> 0xdb, 0xdf * others will not change * * @param skb socket buffer * @c pure data in the one byte */ static void h5_slip_one_byte(sk_buff *skb, uint8_t unencode_form) { const signed char esc_c0[2] = { 0xdb, 0xdc }; const signed char esc_db[2] = { 0xdb, 0xdd }; const signed char esc_11[2] = { 0xdb, 0xde }; const signed char esc_13[2] = { 0xdb, 0xdf }; switch (unencode_form) { case 0xc0: memcpy(hci_skb_put(skb, 2), &esc_c0, 2); break; case 0xdb: memcpy(hci_skb_put(skb, 2), &esc_db, 2); break; case 0x11: { if (rtk_h5.oof_flow_control) { memcpy(hci_skb_put(skb, 2), &esc_11, 2); } else { memcpy(hci_skb_put(skb, 1), &unencode_form, 1); } } break; case 0x13: { if (rtk_h5.oof_flow_control) { memcpy(hci_skb_put(skb, 2), &esc_13, 2); } else { memcpy(hci_skb_put(skb, 1), &unencode_form, 1); } } break; default: memcpy(hci_skb_put(skb, 1), &unencode_form, 1); } } /** * Decode one byte in h5 proto, as follows: * 0xdb, 0xdc -> 0xc0 * 0xdb, 0xdd -> 0xdb * 0xdb, 0xde -> 0x11 * 0xdb, 0xdf -> 0x13 * others will not change * * @param h5 realtek h5 struct * @byte pure data in the one byte */ static void h5_unslip_one_byte(tHCI_H5_CB *h5, unsigned char byte) { const uint8_t c0 = 0xc0, db = 0xdb; const uint8_t oof1 = 0x11, oof2 = 0x13; uint8_t *hdr = (uint8_t *)hci_skb_get_data(h5->rx_skb); if (H5_ESCSTATE_NOESC == h5->rx_esc_state) { if (0xdb == byte) { h5->rx_esc_state = H5_ESCSTATE_ESC; //h5->rx_count--; } else { memcpy(hci_skb_put(h5->rx_skb, 1), &byte, 1); //Check Pkt Header's CRC enable bit if (H5_HDR_CRC(hdr) && h5->rx_state != H5_W4_CRC) { h5_crc_update(&h5->message_crc, byte); } h5->rx_count--; } } else if (H5_ESCSTATE_ESC == h5->rx_esc_state) { switch (byte) { case 0xdc: memcpy(hci_skb_put(h5->rx_skb, 1), &c0, 1); if (H5_HDR_CRC(hdr) && h5->rx_state != H5_W4_CRC) { h5_crc_update(&h5-> message_crc, 0xc0); } h5->rx_esc_state = H5_ESCSTATE_NOESC; h5->rx_count--; break; case 0xdd: memcpy(hci_skb_put(h5->rx_skb, 1), &db, 1); if (H5_HDR_CRC(hdr) && h5->rx_state != H5_W4_CRC) { h5_crc_update(&h5-> message_crc, 0xdb); } h5->rx_esc_state = H5_ESCSTATE_NOESC; h5->rx_count--; break; case 0xde: memcpy(hci_skb_put(h5->rx_skb, 1), &oof1, 1); if (H5_HDR_CRC(hdr) && h5->rx_state != H5_W4_CRC) { h5_crc_update(&h5-> message_crc, oof1); } h5->rx_esc_state = H5_ESCSTATE_NOESC; h5->rx_count--; break; case 0xdf: memcpy(hci_skb_put(h5->rx_skb, 1), &oof2, 1); if (H5_HDR_CRC(hdr) && h5->rx_state != H5_W4_CRC) { h5_crc_update(&h5-> message_crc, oof2); } h5->rx_esc_state = H5_ESCSTATE_NOESC; h5->rx_count--; break; default: BT_ERR("Error: Invalid byte %02x after esc byte", byte); hci_skb_free(&h5->rx_skb); h5->rx_skb = NULL; h5->rx_state = H5_W4_PKT_DELIMITER; h5->rx_count = 0; break; } } } /** * Prepare h5 packet, packet format as follow: * | LSB 4 octets | 0 ~4095| 2 MSB * |packet header | payload | data integrity check | * * pakcket header fromat is show below: * | LSB 3 bits | 3 bits | 1 bits | 1 bits | * | 4 bits | 12 bits | 8 bits MSB * |sequence number | acknowledgement number | data integrity check present | reliable packet | * |packet type | payload length | header checksum * * @param h5 realtek h5 struct * @param data pure data * @param len the length of data * @param pkt_type packet type * @return socket buff after prepare in h5 proto */ static sk_buff *h5_prepare_pkt(tHCI_H5_CB *h5, uint8_t *data, signed long len, signed long pkt_type) { sk_buff *nskb; uint8_t hdr[4]; uint16_t H5_CRC_INIT(h5_txmsg_crc); int rel, i; //BT_DBG("HCI h5_prepare_pkt"); switch (pkt_type) { case HCI_ACLDATA_PKT: case HCI_COMMAND_PKT: case HCI_EVENT_PKT: rel = H5_RELIABLE_PKT; // reliable break; case H5_ACK_PKT: case H5_VDRSPEC_PKT: case H5_LINK_CTL_PKT: rel = H5_UNRELIABLE_PKT;// unreliable break; default: BT_ERR("Unknown packet type"); return NULL; } // Max len of packet: (original len +4(h5 hdr) +2(crc))*2 // (because bytes 0xc0 and 0xdb are escaped, worst case is // when the packet is all made of 0xc0 and 0xdb :) ) // + 2 (0xc0 delimiters at start and end). nskb = hci_skb_alloc((len + 6) * 2 + 2); if (!nskb) { BT_DBG("nskb is NULL"); return NULL; } //Add SLIP start byte: 0xc0 h5_slip_msgdelim(nskb); // set AckNumber in SlipHeader hdr[0] = h5->rxseq_txack << 3; h5->is_txack_req = 0; //BT_DBG("We request packet no(%u) to card", h5->rxseq_txack); //BT_DBG("Sending packet with seqno %u and wait %u", h5->msgq_txseq, h5->rxseq_txack); if (H5_RELIABLE_PKT == rel) { // set reliable pkt bit and SeqNumber hdr[0] |= 0x80 + h5->msgq_txseq; //BT_DBG("Sending packet with seqno(%u)", h5->msgq_txseq); ++(h5->msgq_txseq); h5->msgq_txseq = (h5->msgq_txseq) & 0x07; } // set DicPresent bit if (h5->use_crc) { hdr[0] |= 0x40; } // set packet type and payload length hdr[1] = ((len << 4) & 0xff) | pkt_type; hdr[2] = (uint8_t)(len >> 4); // set checksum hdr[3] = ~(hdr[0] + hdr[1] + hdr[2]); // Put h5 header */ for (i = 0; i < 4; i++) { h5_slip_one_byte(nskb, hdr[i]); if (h5->use_crc) { h5_crc_update(&h5_txmsg_crc, hdr[i]); } } // Put payload */ for (i = 0; i < len; i++) { h5_slip_one_byte(nskb, data[i]); if (h5->use_crc) { h5_crc_update(&h5_txmsg_crc, data[i]); } } // Put CRC */ if (h5->use_crc) { h5_txmsg_crc = bit_rev16(h5_txmsg_crc); h5_slip_one_byte(nskb, (uint8_t)((h5_txmsg_crc >> 8) & 0x00ff)); h5_slip_one_byte(nskb, (uint8_t)(h5_txmsg_crc & 0x00ff)); } // Add SLIP end byte: 0xc0 h5_slip_msgdelim(nskb); return nskb; } /** * Removed controller acked packet from Host's unacked lists * * @param h5 realtek h5 struct */ static void h5_remove_acked_pkt(tHCI_H5_CB *h5) { RT_LIST_HEAD *Head = NULL; RT_LIST_ENTRY *Iter = NULL, *Temp = NULL; RTK_BUFFER *skb = NULL; int pkts_to_be_removed = 0; int seqno = 0; int i = 0; aos_mutex_lock(&h5_wakeup_mutex, AOS_WAIT_FOREVER); seqno = h5->msgq_txseq; pkts_to_be_removed = RtbGetQueueLen(h5->unack); while (pkts_to_be_removed) { if (h5->rxack == seqno) { break; } pkts_to_be_removed--; seqno = (seqno - 1) & 0x07; } if (h5->rxack != seqno) { BT_DBG("Peer acked invalid packet"); } // remove ack'ed packet from bcsp->unack queue i = 0;// number of pkts has been removed from un_ack queue. Head = (RT_LIST_HEAD *)(h5->unack); LIST_FOR_EACH_SAFELY(Iter, Temp, Head) { skb = LIST_ENTRY(Iter, sk_buff, List); if (i >= pkts_to_be_removed) { break; } hci_skb_unlink(skb, h5->unack); hci_skb_free(&skb); i++; } if (0 == hci_skb_queue_get_length(h5->unack)) { h5_stop_data_retrans_timer(); rtk_h5.data_retrans_count = 0; } if (i != pkts_to_be_removed) { BT_DBG("Removed only (%u) out of (%u) pkts", i, pkts_to_be_removed); } aos_mutex_unlock(&h5_wakeup_mutex); } static void hci_h5_send_sync_req() { //uint16_t bytes_sent = 0; unsigned char h5sync[2] = {0x01, 0x7E}; sk_buff *skb = NULL; skb = hci_skb_alloc_and_init(H5_LINK_CTL_PKT, h5sync, sizeof(h5sync)); if (!skb) { BT_ERR("hci_skb_alloc_and_init fail!"); return; } BT_DBG("H5: --->>>send sync req"); h5_enqueue(skb); h5_wake_up(); return; } static void hci_h5_send_sync_resp() { //uint16_t bytes_sent = 0; unsigned char h5syncresp[2] = {0x02, 0x7D}; sk_buff *skb = NULL; skb = hci_skb_alloc_and_init(H5_LINK_CTL_PKT, h5syncresp, sizeof(h5syncresp)); if (!skb) { BT_ERR("hci_skb_alloc_and_init fail!"); return; } BT_DBG("H5: --->>>send sync resp"); h5_enqueue(skb); h5_wake_up(); return; } static void hci_h5_send_conf_req() { //uint16_t bytes_sent = 0; unsigned char h5conf[3] = {0x03, 0xFC, 0x14}; //unsigned char h5conf[2] = {0x03, 0xFC}; sk_buff *skb = NULL; skb = hci_skb_alloc_and_init(H5_LINK_CTL_PKT, h5conf, sizeof(h5conf)); if (!skb) { BT_ERR("hci_skb_alloc_and_init fail!"); return; } BT_DBG("H5: --->>>send conf req"); h5_enqueue(skb); h5_wake_up(); return; } static void hci_h5_send_conf_resp() { //uint16_t bytes_sent = 0; unsigned char h5confresp[2] = {0x04, 0x7B}; sk_buff *skb = NULL; skb = hci_skb_alloc_and_init(H5_LINK_CTL_PKT, h5confresp, sizeof(h5confresp)); if (!skb) { BT_ERR("hci_skb_alloc_and_init fail!"); return; } BT_DBG("H5: --->>>send conf resp"); h5_enqueue(skb); h5_wake_up(); return; } static void rtk_notify_hw_h5_init_result(uint8_t result) { BT_DBG("rtk_notify_hw_h5_init_result"); uint8_t sync_event[6] = {0x0e, 0x04, 0x03, 0xee, 0xfc, 0x00}; // we need to make a sync event to bt sk_buff *rx_skb; rx_skb = hci_skb_alloc_and_init(HCI_EVENT_PKT, sync_event, sizeof(sync_event)); aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); hci_skb_queue_tail(rtk_h5.recv_data, rx_skb); aos_sem_signal(&rtk_h5.data_cond); aos_mutex_unlock(&rtk_h5.data_mutex); } static sk_buff *h5_dequeue() { sk_buff *skb = NULL; // First of all, check for unreliable messages in the queue, // since they have higher priority aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); if ((skb = (sk_buff *)hci_skb_dequeue_head(rtk_h5.unrel)) != NULL) { sk_buff *nskb = h5_prepare_pkt(&rtk_h5, hci_skb_get_data(skb), hci_skb_get_data_length(skb), hci_skb_get_pkt_type(skb)); if (nskb) { aos_mutex_unlock(&rtk_h5.data_mutex); hci_skb_free(&skb); return nskb; } else { hci_skb_queue_head(rtk_h5.unrel, skb); } } aos_mutex_unlock(&rtk_h5.data_mutex); // Now, try to send a reliable pkt. We can only send a // reliable packet if the number of packets sent but not yet ack'ed // is < than the winsize aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); if (RtbGetQueueLen(rtk_h5.unack) < rtk_h5.sliding_window_size && (skb = (sk_buff *)hci_skb_dequeue_head(rtk_h5.rel)) != NULL) { sk_buff *nskb = h5_prepare_pkt(&rtk_h5, hci_skb_get_data(skb), hci_skb_get_data_length(skb), hci_skb_get_pkt_type(skb)); if (nskb) { hci_skb_queue_tail(rtk_h5.unack, skb); aos_mutex_unlock(&rtk_h5.data_mutex); h5_start_data_retrans_timer(); return nskb; } else { hci_skb_queue_head(rtk_h5.rel, skb); } } aos_mutex_unlock(&rtk_h5.data_mutex); // We could not send a reliable packet, either because there are // none or because there are too many unack'ed packets. Did we receive // any packets we have not acknowledged yet if (rtk_h5.is_txack_req) { // if so, craft an empty ACK pkt and send it on BCSP unreliable // channel sk_buff *nskb = h5_prepare_pkt(&rtk_h5, NULL, 0, H5_ACK_PKT); return nskb; } // We have nothing to send return NULL; } static int h5_enqueue(IN sk_buff *skb) { //Pkt length must be less than 4095 bytes if (hci_skb_get_data_length(skb) > 0xFFF) { BT_ERR("skb len > 0xFFF"); hci_skb_free(&skb); return 0; } switch (hci_skb_get_pkt_type(skb)) { case HCI_ACLDATA_PKT: case HCI_COMMAND_PKT: aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); hci_skb_queue_tail(rtk_h5.rel, skb); aos_mutex_unlock(&rtk_h5.data_mutex); break; case H5_LINK_CTL_PKT: case H5_ACK_PKT: case H5_VDRSPEC_PKT: aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); hci_skb_queue_tail(rtk_h5.unrel, skb);/* 3-wire LinkEstablishment*/ aos_mutex_unlock(&rtk_h5.data_mutex); break; default: hci_skb_free(&skb); break; } return 0; } static uint16_t h5_wake_up() { uint16_t bytes_sent = 0; sk_buff *skb = NULL; uint8_t *data = NULL; uint32_t data_len = 0; aos_mutex_lock(&h5_wakeup_mutex, AOS_WAIT_FOREVER); //BT_DBG("h5_wake_up"); while (NULL != (skb = h5_dequeue())) { data = hci_skb_get_data(skb); data_len = hci_skb_get_data_length(skb); #if H5_TRACE_DATA_ENABLE { uint32_t iTemp; printf("H5 TX: length(%d)\n", data_len); for (iTemp = 0; iTemp < data_len; iTemp++) { printf("0x%x ", data[iTemp]); } printf("\n"); } #endif #ifndef YULONG_HCI //we adopt the hci_drv interface to send data bytes_sent = hci_send(rtk_h5.hci_dev, data, data_len); #endif hci_skb_free(&skb); } aos_mutex_unlock(&h5_wakeup_mutex); return bytes_sent; } static void h5_process_ctl_pkts(void) { //process h5 link establish uint8_t cfg; sk_buff *skb = rtk_h5.rx_skb; unsigned char h5sync[2] = {0x01, 0x7E}, h5syncresp[2] = {0x02, 0x7D}, h5conf[3] = {0x03, 0xFC, 0x14}, h5confresp[2] = {0x04, 0x7B}; if (rtk_h5.link_estab_state == H5_UNINITIALIZED) { //sync if (!memcmp(hci_skb_get_data(skb), h5sync, 2)) { BT_DBG("H5: <<<---recv sync req"); hci_h5_send_sync_resp(); } else if (!memcmp(hci_skb_get_data(skb), h5syncresp, 2)) { BT_DBG("H5: <<<---recv sync resp"); h5_stop_sync_retrans_timer(); rtk_h5.sync_retrans_count = 0; rtk_h5.link_estab_state = H5_INITIALIZED; //send config req hci_h5_send_conf_req(); h5_start_conf_retrans_timer(); } } else if (rtk_h5.link_estab_state == H5_INITIALIZED) { //config if (!memcmp(hci_skb_get_data(skb), h5sync, 0x2)) { BT_DBG("H5: <<<---recv sync req in H5_INITIALIZED"); hci_h5_send_sync_resp(); } else if (!memcmp(hci_skb_get_data(skb), h5conf, 0x2)) { BT_DBG("H5: <<<---recv conf req"); hci_h5_send_conf_resp(); } else if (!memcmp(hci_skb_get_data(skb), h5confresp, 0x2)) { BT_DBG("H5: <<<---recv conf resp"); h5_stop_conf_retrans_timer(); rtk_h5.conf_retrans_count = 0; rtk_h5.link_estab_state = H5_ACTIVE; //notify hw to download patch memcpy(&cfg, hci_skb_get_data(skb) + 2, H5_CFG_SIZE); rtk_h5.sliding_window_size = H5_CFG_SLID_WIN(cfg); rtk_h5.oof_flow_control = H5_CFG_OOF_CNTRL(cfg); rtk_h5.dic_type = H5_CFG_DIC_TYPE(cfg); BT_DBG("rtk_h5.sliding_window_size(%d), oof_flow_control(%d), dic_type(%d)", rtk_h5.sliding_window_size, rtk_h5.oof_flow_control, rtk_h5.dic_type); if (rtk_h5.dic_type) { rtk_h5.use_crc = 1; } rtk_notify_hw_h5_init_result(1); } else { BT_DBG("H5_INITIALIZED receive event, ingnore"); } } else if (rtk_h5.link_estab_state == H5_ACTIVE) { if (!memcmp(hci_skb_get_data(skb), h5sync, 0x2)) { BT_DBG("H5: <<<---recv sync req in H5_ACTIVE"); hci_h5_send_sync_resp(); BT_DBG("H5 : H5_ACTIVE transit to H5_UNINITIALIZED"); rtk_h5.link_estab_state = H5_UNINITIALIZED; hci_h5_send_sync_req(); h5_start_sync_retrans_timer(); } else if (!memcmp(hci_skb_get_data(skb), h5conf, 0x2)) { BT_DBG("H5: <<<---recv conf req in H5_ACTIVE"); hci_h5_send_conf_resp(); } else if (!memcmp(hci_skb_get_data(skb), h5confresp, 0x2)) { BT_DBG("H5: <<<---recv conf resp in H5_ACTIVE, discard"); } else { BT_DBG("H5_ACTIVE receive unknown link control msg, ingnore"); } } } /** * Check if it's a hci frame, if it is, complete it with response or parse the cmd complete event * * @param skb socket buffer * */ static uint8_t hci_recv_frame(sk_buff *skb, uint8_t pkt_type) { uint8_t intercepted = 0; uint32_t data_len = hci_skb_get_data_length(skb); (void)data_len; BT_DBG("UART H5 RX: length = %d", data_len); //we only intercept evt packet here if (pkt_type == HCI_EVENT_PKT) { uint8_t *p; uint8_t event_code; uint16_t opcode; p = (uint8_t *)hci_skb_get_data(skb); event_code = *p++; // BT_DBG("hci_recv_frame event_code(0x%x), len = %d", event_code, len); if (event_code == HCI_COMMAND_COMPLETE_EVT) { num_hci_cmd_pkts = *p++; STREAM_TO_UINT16(opcode, p); if (opcode == HCI_VSC_UPDATE_BAUDRATE) { intercepted = 1; rtk_h5.internal_skb = skb; BT_DBG("CommandCompleteEvent for command h5_start_wait_controller_baudrate_ready_timer (0x%04X)", opcode); h5_start_wait_controller_baudrate_ready_timer(); } } } // BT_DBG("hci_recv_frame intercepted = %d", intercepted); return intercepted; } /** * after rx data is parsed, and we got a rx frame saved in h5->rx_skb, * this routinue is called. * things todo in this function: * 1. check if it's a hci frame, if it is, complete it with response or ack * 2. see the ack number, free acked frame in queue * 3. reset h5->rx_state, set rx_skb to null. * * @param h5 realtek h5 struct * */ static uint8_t h5_complete_rx_pkt(tHCI_H5_CB *h5) { int pass_up = 1; uint8_t *h5_hdr = NULL; uint8_t pkt_type = 0; uint8_t status = 0; h5_hdr = (uint8_t *)hci_skb_get_data(h5->rx_skb); #if H5_TRACE_DATA_ENABLE { uint32_t iTemp; uint32_t data_len = hci_skb_get_data_length(h5->rx_skb); uint8_t *data = (uint8_t *)hci_skb_get_data(h5->rx_skb); printf("H5 RX: length(%d)\n", data_len); for (iTemp = 0; iTemp < data_len; iTemp++) { printf("0x%x ", data[iTemp]); } printf("\n"); } #endif if (H5_HDR_RELIABLE(h5_hdr)) { aos_mutex_lock(&h5_wakeup_mutex, AOS_WAIT_FOREVER); h5->rxseq_txack = H5_HDR_SEQ(h5_hdr) + 1; h5->rxseq_txack %= 8; h5->is_txack_req = 1; aos_mutex_unlock(&h5_wakeup_mutex); // send down an empty ack if needed. h5_wake_up(); } h5->rxack = H5_HDR_ACK(h5_hdr); pkt_type = H5_HDR_PKT_TYPE(h5_hdr); //BT_DBG("h5_complete_rx_pkt, pkt_type = %d", pkt_type); switch (pkt_type) { case HCI_ACLDATA_PKT: pass_up = 1; break; case HCI_EVENT_PKT: pass_up = 1; break; case HCI_SCODATA_PKT: pass_up = 1; break; case HCI_COMMAND_PKT: pass_up = 1; break; case H5_LINK_CTL_PKT: pass_up = 0; break; case H5_ACK_PKT: pass_up = 0; break; default: BT_ERR("Unknown pkt type(%d)", H5_HDR_PKT_TYPE(h5_hdr)); pass_up = 0; break; } // remove h5 header and send packet to hci h5_remove_acked_pkt(h5); if (H5_HDR_PKT_TYPE(h5_hdr) == H5_LINK_CTL_PKT) { hci_skb_pull(h5->rx_skb, H5_HDR_SIZE); h5_process_ctl_pkts(); } // decide if we need to pass up. if (pass_up) { hci_skb_pull(h5->rx_skb, H5_HDR_SIZE); hci_skb_set_pkt_type(h5->rx_skb, pkt_type); //send command or acl data it to bluedroid stack sk_buff *skb_complete_pkt = h5->rx_skb; status = hci_recv_frame(skb_complete_pkt, pkt_type); if (!status) { aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); hci_skb_queue_tail(rtk_h5.recv_data, h5->rx_skb); aos_sem_signal(&rtk_h5.data_cond); aos_mutex_unlock(&rtk_h5.data_mutex); } } else { // free ctl packet hci_skb_free(&h5->rx_skb); } h5->rx_state = H5_W4_PKT_DELIMITER; rtk_h5.rx_skb = NULL; return pkt_type; } /** * Parse the receive data in h5 proto. * * @param h5 realtek h5 struct * @param data point to data received before parse * @param count num of data * @return reserved count */ static uint32_t h5_recv(tHCI_H5_CB *h5, uint8_t *data, int count) { // unsigned char *ptr; uint8_t *ptr; uint8_t *skb_data = NULL; uint8_t *hdr = NULL; bool complete_packet = 0; ptr = (uint8_t *)data; // BT_DBG("count %d rx_state %d rx_count %ld", count, h5->rx_state, h5->rx_count); while (count) { if (h5->rx_count) { if (*ptr == 0xc0) { BT_ERR("short h5 packet %d %d", h5->rx_count, count); hci_skb_free(&h5->rx_skb); h5->rx_state = H5_W4_PKT_START; h5->rx_count = 0; } else { h5_unslip_one_byte(h5, *ptr); } ptr++; count--; continue; } //BT_DBG("h5_recv rx_state=%d", h5->rx_state); switch (h5->rx_state) { case H5_W4_HDR: // check header checksum. see Core Spec V4 "3-wire uart" page 67 skb_data = hci_skb_get_data(h5->rx_skb); hdr = (uint8_t *)skb_data; if ((0xff & (uint8_t) ~(skb_data[0] + skb_data[1] + skb_data[2])) != skb_data[3]) { BT_ERR("h5 hdr checksum error!!!"); hci_skb_free(&h5->rx_skb); h5->rx_state = H5_W4_PKT_DELIMITER; h5->rx_count = 0; continue; } if (H5_HDR_RELIABLE(hdr) && (H5_HDR_SEQ(hdr) != h5->rxseq_txack)) { BT_ERR("Out-of-order %u %u", H5_HDR_SEQ(hdr), h5->rxseq_txack); h5->is_txack_req = 1; h5_wake_up(); hci_skb_free(&h5->rx_skb); h5->rx_state = H5_W4_PKT_DELIMITER; h5->rx_count = 0; continue; } h5->rx_state = H5_W4_DATA; //payload length: May be 0 h5->rx_count = H5_HDR_LEN(hdr); continue; case H5_W4_DATA: hdr = (uint8_t *)hci_skb_get_data(h5->rx_skb); if (H5_HDR_CRC(hdr)) { // pkt with crc / h5->rx_state = H5_W4_CRC; h5->rx_count = 2; } else { h5_complete_rx_pkt(h5); //Send ACK complete_packet = 1; //BT_DBG("--------> H5_W4_DATA ACK\n"); } continue; case H5_W4_CRC: if (bit_rev16(h5->message_crc) != h5_get_crc(h5)) { BT_ERR("Checksum failed, computed(%04x)received(%04x)", bit_rev16(h5->message_crc), h5_get_crc(h5)); hci_skb_free(&h5->rx_skb); h5->rx_state = H5_W4_PKT_DELIMITER; h5->rx_count = 0; continue; } hci_skb_trim(h5->rx_skb, hci_skb_get_data_length(h5->rx_skb) - 2); h5_complete_rx_pkt(h5); complete_packet = 1; continue; case H5_W4_PKT_DELIMITER: switch (*ptr) { case 0xc0: h5->rx_state = H5_W4_PKT_START; break; default: break; } ptr++; count--; break; case H5_W4_PKT_START: switch (*ptr) { case 0xc0: ptr++; count--; break; default: h5->rx_state = H5_W4_HDR; h5->rx_count = 4; h5->rx_esc_state = H5_ESCSTATE_NOESC; H5_CRC_INIT(h5->message_crc); // Do not increment ptr or decrement count // Allocate packet. Max len of a H5 pkt= // 0xFFF (payload) +4 (header) +2 (crc) h5->rx_skb = hci_skb_alloc(0x1005); if (!h5->rx_skb) { h5->rx_state = H5_W4_PKT_DELIMITER; h5->rx_count = 0; return 0; } break; } break; } } return complete_packet; } /****************************************************************************** ** Static functions ******************************************************************************/ static void data_ready_cb_thread(void *arg) { sk_buff *skb; BT_DBG("data_ready_cb_thread started"); while (h5_data_ready_running) { aos_sem_wait(&rtk_h5.data_cond, AOS_WAIT_FOREVER); while ((hci_skb_queue_get_length(rtk_h5.recv_data) == 0)) { aos_sem_wait(&rtk_h5.data_cond, AOS_WAIT_FOREVER); } aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); if ((skb = hci_skb_dequeue_head(rtk_h5.recv_data)) != NULL) { rtk_h5.data_skb = skb; } aos_mutex_unlock(&rtk_h5.data_mutex); int length = hci_skb_get_data_length(rtk_h5.data_skb); if (h5_int_hal_callbacks) { h5_int_hal_callbacks(hci_skb_get_pkt_type(rtk_h5.data_skb), hci_skb_get_data(rtk_h5.data_skb), length); } hci_skb_free(&rtk_h5.data_skb); } } static void data_retransfer_thread(void *arg) { uint16_t events; BT_DBG("data_retransfer_thread started"); while (h5_retransfer_running) { aos_sem_wait(&rtk_h5.cond, AOS_WAIT_FOREVER); events = h5_ready_events; h5_ready_events = 0; if (events & H5_EVENT_RX) { sk_buff *skb; BT_ERR("retransmitting (%u) pkts, retransfer count(%d)", hci_skb_queue_get_length(rtk_h5.unack), rtk_h5.data_retrans_count); if (rtk_h5.data_retrans_count < DATA_RETRANS_COUNT) { while ((skb = hci_skb_dequeue_tail(rtk_h5.unack)) != NULL) { rtk_h5.msgq_txseq = (rtk_h5.msgq_txseq - 1) & 0x07; hci_skb_queue_head(rtk_h5.rel, skb); } rtk_h5.data_retrans_count++; h5_wake_up(); } } else if (events & H5_EVENT_EXIT) { break; } } BT_DBG("data_retransfer_thread exiting"); } static void h5_retransfer_signal_event(uint16_t event) { aos_mutex_lock(&rtk_h5.mutex, AOS_WAIT_FOREVER); h5_ready_events |= event; aos_sem_signal(&rtk_h5.cond); aos_mutex_unlock(&rtk_h5.mutex); } static int create_data_retransfer_thread() { if (h5_retransfer_running) { BT_ERR("create_data_retransfer_thread has been called repeatedly without calling cleanup ?"); } h5_retransfer_running = 1; h5_ready_events = 0; aos_mutex_new(&rtk_h5.mutex); aos_sem_new(&rtk_h5.cond, 0); if (aos_task_new_ext(&rtk_h5.thread_data_retrans, "data_retransfer", (void *)data_retransfer_thread, NULL, 3072, AOS_DEFAULT_APP_PRI + 3) != 0) { BT_ERR("pthread_create thread_data_retrans failed!"); h5_retransfer_running = 0; return -1 ; } return 0; } static int create_data_ready_cb_thread() { if (h5_data_ready_running) { BT_ERR("create_data_ready_cb_thread has been called repeatedly without calling cleanup ?"); } h5_data_ready_running = 1; int ret = aos_mutex_new(&rtk_h5.data_mutex); if (ret != 0) { return -1; } ret = aos_sem_new(&rtk_h5.data_cond, 0); if (ret != 0) { aos_mutex_free(&rtk_h5.data_mutex); return -1; } if (aos_task_new_ext(&rtk_h5.thread_data_ready_cb, "data_ready_cb", (void *)data_ready_cb_thread, NULL, 1024 * 6, AOS_DEFAULT_APP_PRI + 3) != 0) { BT_ERR("pthread_create thread_data_ready_cb failed!"); h5_data_ready_running = 0; aos_mutex_free(&rtk_h5.data_mutex); aos_sem_free(&rtk_h5.data_cond); return -1 ; } return 0; } #ifndef YULONG_HCI static void hci_event(hci_event_t event, uint32_t size, void *priv) { hci_h5_receive_msg(NULL , 0); } #endif static int hci_driver_send_cmd_cb(uint16_t opcode, uint8_t* send_data, uint32_t send_len, uint8_t* resp_data, uint32_t *resp_len) { struct net_buf *buf; struct net_buf *rsp; int err; buf = bt_hci_cmd_create(opcode, send_len); if (!buf) { return - 1; } if (send_len > 0) net_buf_add_mem(buf, send_data, send_len); err = bt_hci_cmd_send_sync(opcode, buf, &rsp); if (err) { goto end; } if (resp_data == NULL) { err = 0; goto end; } if (*resp_len < rsp->len) { err = -1; goto end; } memcpy(resp_data, rsp->data, rsp->len); *resp_len = rsp->len; end: net_buf_unref(buf); return err; } /******************************************************************************* ** ** Function hci_h5_init ** ** Description Initialize H5 module ** ** Returns None ** *******************************************************************************/ static void hci_h5_int_init(packet_recv h5_callbacks) { BT_DBG("hci_h5_int_init"); h5_int_hal_callbacks = h5_callbacks; memset(&rtk_h5, 0, sizeof(tHCI_H5_CB)); /* Per HCI spec., always starts with 1 */ num_hci_cmd_pkts = 1; h5_alloc_data_retrans_timer(); h5_alloc_sync_retrans_timer(); h5_alloc_conf_retrans_timer(); h5_alloc_wait_controller_baudrate_ready_timer(); h5_alloc_hw_init_ready_timer(); aos_mutex_new(&h5_wakeup_mutex); rtk_h5.recv_data = RtbQueueInit(); if (create_data_ready_cb_thread() != 0) { BT_ERR("H5 create_data_ready_cb_thread failed"); } if (create_data_retransfer_thread() != 0) { BT_ERR("H5 create_data_retransfer_thread failed"); } rtk_h5.unack = RtbQueueInit(); rtk_h5.rel = RtbQueueInit(); rtk_h5.unrel = RtbQueueInit(); rtk_h5.rx_state = H5_W4_PKT_DELIMITER; rtk_h5.rx_esc_state = H5_ESCSTATE_NOESC; #ifndef YULONG_HCI rtk_h5.hci_dev = hci_open("hci"); ASSERT(rtk_h5.hci_dev, "hci_open failed"); hci_set_event(rtk_h5.hci_dev, hci_event, NULL); hci_start(rtk_h5.hci_dev, hci_driver_send_cmd_cb); #endif } /******************************************************************************* ** ** Function hci_h5_cleanup ** ** Description Clean H5 module ** ** Returns None ** *******************************************************************************/ static void hci_h5_cleanup(void) { BT_DBG("hci_h5_cleanup"); rtk_h5.cleanuping = 1; h5_free_data_retrans_timer(); h5_free_sync_retrans_timer(); h5_free_conf_retrans_timer(); h5_free_wait_controller_baudrate_ready_timer(); h5_free_hw_init_ready_timer(); if (h5_retransfer_running) { h5_retransfer_running = 0; h5_retransfer_signal_event(H5_EVENT_EXIT); } aos_mutex_free(&rtk_h5.mutex); aos_sem_free(&rtk_h5.cond); RtbQueueFree(rtk_h5.unack); RtbQueueFree(rtk_h5.rel); RtbQueueFree(rtk_h5.unrel); h5_int_hal_callbacks = NULL; rtk_h5.internal_skb = NULL; } /******************************************************************************* ** ** Function hci_h5_receive_msg ** ** Description Construct HCI EVENT/ACL packets and send them to stack once ** complete packet has been received. ** ** Returns Number of read bytes ** *******************************************************************************/ static uint8_t data_buffer[4096] = {0}; static uint32_t hci_h5_receive_msg(uint8_t *byte, uint16_t length) { #ifndef YULONG_HCI uint32_t read_len = hci_recv(rtk_h5.hci_dev, data_buffer, sizeof(data_buffer)); if (read_len > 0) { return h5_recv(&rtk_h5, data_buffer, read_len); } else { return 0; } #else return 0; #endif } /******************************************************************************* ** ** Function hci_h5_send_cmd ** ** Description get cmd data from hal and send cmd ** ** ** Returns bytes send ** *******************************************************************************/ static uint16_t hci_h5_send_cmd(hci_data_type_t type, uint8_t *data, uint16_t length) { sk_buff *skb = NULL; uint16_t opcode; skb = hci_skb_alloc_and_init(type, data, length); if (!skb) { BT_ERR("send cmd hci_skb_alloc_and_init fail!"); return -1; } h5_enqueue(skb); num_hci_cmd_pkts--; /* If this is an internal Cmd packet, the layer_specific field would * have stored with the opcode of HCI command. * Retrieve the opcode from the Cmd packet. */ STREAM_TO_UINT16(opcode, data); BT_DBG("HCI Command opcode(0x%04X)", opcode); if (opcode == 0x0c03) { BT_DBG("RX HCI RESET Command, stop hw init timer"); h5_stop_hw_init_ready_timer(); } h5_wake_up(); return length; } /******************************************************************************* ** ** Function hci_h5_send_acl_data ** ** Description get cmd data from hal and send cmd ** ** ** Returns bytes send ** *******************************************************************************/ static uint16_t hci_h5_send_acl_data(hci_data_type_t type, uint8_t *data, uint16_t length) { sk_buff *skb = NULL; skb = hci_skb_alloc_and_init(type, data, length); if (!skb) { BT_ERR("hci_h5_send_acl_data, alloc skb buffer fail!"); return -1; } h5_enqueue(skb); h5_wake_up(); return length; } /******************************************************************************* ** ** Function hci_h5_send_int_cmd ** ** Description Place the internal commands (issued internally by vendor lib) ** in the tx_q. ** ** Returns 1/0 ** *******************************************************************************/ static uint8_t hci_h5_send_sync_cmd(uint16_t opcode, uint8_t *p_buf, uint16_t length) { if (rtk_h5.link_estab_state == H5_UNINITIALIZED) { if (opcode == HCI_VSC_H5_INIT) { h5_start_hw_init_ready_timer(); hci_h5_send_sync_req(); h5_start_sync_retrans_timer(); } } else if (rtk_h5.link_estab_state == H5_ACTIVE) { BT_DBG("hci_h5_send_sync_cmd(0x%x), link_estab_state = %d", opcode, rtk_h5.link_estab_state); return 0; } return 1; } /*** Timer related functions */ static aos_timer_t *OsAllocateTimer(tTIMER_HANDLE_CBACK timer_callback) { aos_timer_t *timer; int ret; timer = malloc(sizeof(aos_timer_t)); if (timer == NULL) { return NULL; } ret = aos_timer_new_ext(timer, timer_callback, NULL, 0xFFFFFFUL, 0, 0); if (ret == 0) { return timer; } else { BT_ERR(" ret: %d", ret); return NULL; } } static int OsFreeTimer(aos_timer_t *timerid) { aos_timer_free(timerid); free(timerid); return 0; } static int OsStartTimer(aos_timer_t *timerid, int msec, int mode) { int ret; //Set the Timer when to expire through timer_settime if (!aos_timer_is_valid(timerid)) { BT_ERR("%s null\n", __func__); goto end; } ret = aos_timer_stop(timerid); if (ret != 0) { BT_ERR("%s aos_timer_stop %d\n", __func__, ret); // return ret; } if (mode) { ret = aos_timer_change(timerid, msec); } else { ret = aos_timer_change_once(timerid, msec); } if (ret != 0) { BT_ERR("%s aos_timer_change %d\n", __func__, ret); // return ret; } ret = aos_timer_start(timerid); if (ret != 0) { BT_ERR("%s aos_timer_start %d\n", __func__, ret); // return ret; } end: return 0; } static int OsStopTimer(aos_timer_t *timerid) { return aos_timer_stop(timerid); } static void h5_retransfer_timeout_handler(void *timer, void *arg) { BT_DBG("h5_retransfer_timeout_handler"); if (rtk_h5.cleanuping) { BT_ERR("h5_retransfer_timeout_handler H5 is cleanuping, EXIT here!"); return; } h5_retransfer_signal_event(H5_EVENT_RX); } static void h5_sync_retrans_timeout_handler(void *timer, void *arg) { BT_DBG("h5_sync_retrans_timeout_handler"); if (rtk_h5.cleanuping) { BT_ERR("h5_sync_retrans_timeout_handler H5 is cleanuping, EXIT here!"); return; } if (rtk_h5.sync_retrans_count < SYNC_RETRANS_COUNT) { hci_h5_send_sync_req(); rtk_h5.sync_retrans_count ++; } else { h5_stop_sync_retrans_timer(); } } static void h5_conf_retrans_timeout_handler(void *timer, void *arg) { BT_DBG("h5_conf_retrans_timeout_handler"); if (rtk_h5.cleanuping) { BT_ERR("h5_conf_retrans_timeout_handler H5 is cleanuping, EXIT here!"); return; } BT_DBG("Wait H5 Conf Resp timeout, %d times", rtk_h5.conf_retrans_count); if (rtk_h5.conf_retrans_count < CONF_RETRANS_COUNT) { h5_start_conf_retrans_timer(); hci_h5_send_conf_req(); rtk_h5.conf_retrans_count++; } else { h5_stop_conf_retrans_timer(); } } static void h5_wait_controller_baudrate_ready_timeout_handler(void *timer, void *arg) { BT_DBG("h5_wait_ct_baundrate_ready_timeout_handler"); if (rtk_h5.cleanuping) { BT_ERR("h5_wait_controller_baudrate_ready_timeout_handler H5 is cleanuping, EXIT here!"); if (rtk_h5.internal_skb) { hci_skb_free(&rtk_h5.internal_skb); } return; } BT_DBG("No Controller retransfer, baudrate of controller ready"); if (rtk_h5.internal_skb == NULL) { return; } aos_mutex_lock(&rtk_h5.data_mutex, AOS_WAIT_FOREVER); hci_skb_queue_tail(rtk_h5.recv_data, rtk_h5.internal_skb); aos_sem_signal(&rtk_h5.data_cond); aos_mutex_unlock(&rtk_h5.data_mutex); rtk_h5.internal_skb = NULL; } static void h5_hw_init_ready_timeout_handler(void *timer, void *arg) { BT_DBG("h5_hw_init_ready_timeout_handler"); if (rtk_h5.cleanuping) { BT_ERR("H5 is cleanuping, EXIT here!"); return; } BT_DBG("TIMER_H5_HW_INIT_READY timeout, kill restart BT"); } /* ** h5 data retrans timer functions */ static int h5_alloc_data_retrans_timer() { // Create and set the timer when to expire rtk_h5.timer_data_retrans = OsAllocateTimer(h5_retransfer_timeout_handler); return 0; } static int h5_free_data_retrans_timer() { return OsFreeTimer(rtk_h5.timer_data_retrans); } static int h5_start_data_retrans_timer() { return OsStartTimer(rtk_h5.timer_data_retrans, DATA_RETRANS_TIMEOUT_VALUE, 0); } static int h5_stop_data_retrans_timer() { return OsStopTimer(rtk_h5.timer_data_retrans); } /* ** h5 sync retrans timer functions */ static int h5_alloc_sync_retrans_timer() { // Create and set the timer when to expire rtk_h5.timer_sync_retrans = OsAllocateTimer(h5_sync_retrans_timeout_handler); return 0; } static int h5_free_sync_retrans_timer() { return OsFreeTimer(rtk_h5.timer_sync_retrans); } static int h5_start_sync_retrans_timer() { return OsStartTimer(rtk_h5.timer_sync_retrans, SYNC_RETRANS_TIMEOUT_VALUE, 1); } static int h5_stop_sync_retrans_timer() { return OsStopTimer(rtk_h5.timer_sync_retrans); } /* ** h5 config retrans timer functions */ static int h5_alloc_conf_retrans_timer() { // Create and set the timer when to expire rtk_h5.timer_conf_retrans = OsAllocateTimer(h5_conf_retrans_timeout_handler); return 0; } static int h5_free_conf_retrans_timer() { return OsFreeTimer(rtk_h5.timer_conf_retrans); } static int h5_start_conf_retrans_timer() { return OsStartTimer(rtk_h5.timer_conf_retrans, CONF_RETRANS_TIMEOUT_VALUE, 1); } static int h5_stop_conf_retrans_timer() { return OsStopTimer(rtk_h5.timer_conf_retrans); } /* ** h5 wait controller baudrate ready timer functions */ static int h5_alloc_wait_controller_baudrate_ready_timer() { // Create and set the timer when to expire rtk_h5.timer_wait_ct_baudrate_ready = OsAllocateTimer(h5_wait_controller_baudrate_ready_timeout_handler); return 0; } static int h5_free_wait_controller_baudrate_ready_timer() { return OsFreeTimer(rtk_h5.timer_wait_ct_baudrate_ready); } static int h5_start_wait_controller_baudrate_ready_timer() { return OsStartTimer(rtk_h5.timer_wait_ct_baudrate_ready, WAIT_CT_BAUDRATE_READY_TIMEOUT_VALUE, 0); } /* ** h5 hw init ready timer functions */ static int h5_alloc_hw_init_ready_timer() { // Create and set the timer when to expire rtk_h5.timer_h5_hw_init_ready = OsAllocateTimer(h5_hw_init_ready_timeout_handler); return 0; } static int h5_free_hw_init_ready_timer() { return OsFreeTimer(rtk_h5.timer_h5_hw_init_ready); } static int h5_start_hw_init_ready_timer() { return OsStartTimer(rtk_h5.timer_h5_hw_init_ready, H5_HW_INIT_READY_TIMEOUT_VALUE, 0); } static int h5_stop_hw_init_ready_timer() { return OsStopTimer(rtk_h5.timer_h5_hw_init_ready); } const static h5_t hci_h5_int_func = { .h5_int_init = hci_h5_int_init, .h5_int_cleanup = hci_h5_cleanup, .h5_send_cmd = hci_h5_send_cmd, .h5_send_acl_data = hci_h5_send_acl_data, .h5_send_sync_cmd = hci_h5_send_sync_cmd, }; const h5_t *get_h5_interface() { return &hci_h5_int_func; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/h5.c
C
apache-2.0
55,645
/****************************************************************************** * * Copyright (C) 2014 Google, Inc. * * 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. * ******************************************************************************/ #pragma once #include <stdbool.h> #include <stdint.h> //HCI Command opcodes #define HCI_LE_READ_BUFFER_SIZE 0x2002 #define DATA_TYPE_H5 0x05 //HCI VENDOR Command opcode #define HCI_VSC_H5_INIT 0xFCEE #define HCI_VSC_UPDATE_BAUDRATE 0xFC17 #define HCI_VSC_DOWNLOAD_FW_PATCH 0xFC20 #define HCI_VSC_READ_ROM_VERSION 0xFC6D #define HCI_VSC_READ_CHIP_TYPE 0xFC61 #define HCI_VSC_SET_WAKE_UP_DEVICE 0xFC7B #define HCI_VSC_BT_OFF 0xFC28 typedef enum { DATA_TYPE_NONE = 0, DATA_TYPE_COMMAND = 1, DATA_TYPE_ACL = 2, DATA_TYPE_SCO = 3, DATA_TYPE_EVENT = 4 } hci_data_type_t; typedef void (*packet_recv)(hci_data_type_t type, uint8_t *data, uint32_t len); typedef struct h5_t { void (*h5_int_init)(packet_recv h5_callbacks); void (*h5_int_cleanup)(void); uint16_t (*h5_send_cmd)(hci_data_type_t type, uint8_t *data, uint16_t length); uint8_t (*h5_send_sync_cmd)(uint16_t opcode, uint8_t *data, uint16_t length); uint16_t (*h5_send_acl_data)(hci_data_type_t type, uint8_t *data, uint16_t length); } h5_t; const h5_t *get_h5_interface(void);
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/h5.h
C
apache-2.0
1,961
/* * 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 <bt_errno.h> #include <stddef.h> #include <ble_os.h> #define BT_DBG_ENABLED 0 #include <common/log.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/conn.h> #include <bluetooth/hci_driver.h> #include "h5.h" #include "host/hci_core.h" #define H4_NONE 0x00 #define H4_CMD 0x01 #define H4_ACL_UP 0x02 #define H4_SCO 0x03 #define H4_EVT 0x04 #define H4_ACL_DOWN 0x05 #define H5_ACK_PKT 0x00 #define HCI_COMMAND_PKT 0x01 #define HCI_ACLDATA_PKT 0x02 #define HCI_SCODATA_PKT 0x03 #define HCI_EVENT_PKT 0x04 #define H5_VDRSPEC_PKT 0x0E #define H5_LINK_CTL_PKT 0x0F const static h5_t *h5_ctx; extern u16_t bt_hci_get_cmd_opcode(struct net_buf *buf); static int h5_send(struct net_buf *buf) { u16_t opcode; uint8_t type = bt_buf_get_type(buf); BT_DBG("buf %p type %u len %u:%s", buf, type, buf->len, bt_hex(buf->data, buf->len)); switch (type) { case BT_BUF_CMD: opcode = bt_hci_get_cmd_opcode(buf); if (opcode == HCI_VSC_H5_INIT) { h5_ctx->h5_send_sync_cmd(opcode, NULL, buf->len); break; } h5_ctx->h5_send_cmd(HCI_COMMAND_PKT, buf->data, buf->len); break; case BT_BUF_ACL_OUT: h5_ctx->h5_send_acl_data(HCI_ACLDATA_PKT, buf->data, buf->len); break; default: BT_ERR("Unknown buffer type"); return -1; } net_buf_unref(buf); return 0; } static inline int is_adv_report_event(uint8_t *data, uint16_t len) { return (data[0] == H4_EVT && data[1] == BT_HCI_EVT_LE_META_EVENT && data[3] == BT_HCI_EVT_LE_ADVERTISING_REPORT); } int hci_h5_event_recv(uint8_t *data, uint16_t data_len) { struct net_buf *buf; uint8_t *pdata = data; int32_t len = data_len; struct bt_hci_evt_hdr hdr; uint8_t sub_event = 0; uint8_t discardable = 0; if (pdata == NULL || len == 0) { return -1; } if (len < 3) { goto err; } hdr.evt = *pdata++; hdr.len = *pdata++; if (len < hdr.len + 2) { goto err; } if (hdr.evt == BT_HCI_EVT_LE_META_EVENT) { sub_event = *pdata++; if (sub_event == BT_HCI_EVT_LE_ADVERTISING_REPORT) { discardable = 1; } } if (hdr.evt == BT_HCI_EVT_CMD_COMPLETE || hdr.evt == BT_HCI_EVT_CMD_STATUS) { buf = bt_buf_get_cmd_complete(0); if (buf == NULL) { // g_hci_debug_counter.event_in_is_null_count++; goto err; } } else { buf = bt_buf_get_rx(BT_BUF_EVT, 0); } if (!buf && discardable) { // g_hci_debug_counter.event_discard_count++; goto err; } if (!buf) { // g_hci_debug_counter.event_in_is_null_count++; goto err; } bt_buf_set_type(buf, BT_BUF_EVT); net_buf_add_mem(buf, ((uint8_t *)(data)), hdr.len + sizeof(hdr)); BT_DBG("event %s", bt_hex(buf->data, buf->len)); // g_hci_debug_counter.event_in_count++; if (bt_hci_evt_is_prio(hdr.evt)) { bt_recv_prio(buf); } else { bt_recv(buf); } return 0; err: return -1; } int hci_h5_acl_recv(uint8_t *data, uint16_t data_len) { struct net_buf *buf; uint16_t acl_len; if (data == NULL || data_len == 0) { return -1; } if (data_len < 4) { goto err; } acl_len = (data[3] << 8) | data[2]; if (data_len < acl_len + 4) { goto err; } buf = bt_buf_get_rx(BT_BUF_ACL_IN, 0); if (!buf) { // g_hci_debug_counter.hci_in_is_null_count++; goto err; } net_buf_add_mem(buf, data, acl_len + 4); // g_hci_debug_counter.acl_in_count++; bt_recv(buf); return 0; err: return -1; } static void packet_recv_cb(hci_data_type_t type, uint8_t *data, uint32_t len) { switch (type) { case DATA_TYPE_ACL: hci_h5_acl_recv(data, len); break; case DATA_TYPE_EVENT: hci_h5_event_recv(data, len); break; default: break; } return; } static int h5_open(void) { h5_ctx = get_h5_interface(); h5_ctx->h5_int_init(packet_recv_cb); return 0; } static struct bt_hci_driver drv = { .name = "H5", .bus = BT_HCI_DRIVER_BUS_UART, .open = h5_open, .send = h5_send, }; int hci_h5_driver_init() { int ret; ret = bt_hci_driver_register(&drv); if (ret) { return ret; } return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/hci_driver/h5_driver.c
C
apache-2.0
5,197
# SPDX-License-Identifier: Apache-2.0 zephyr_library() zephyr_library_link_libraries(subsys__bluetooth) zephyr_library_sources_ifdef(CONFIG_BT_HCI_RAW hci_raw.c) zephyr_library_sources_ifdef(CONFIG_BT_DEBUG_MONITOR monitor.c) zephyr_library_sources_ifdef(CONFIG_BT_TINYCRYPT_ECC hci_ecc.c) zephyr_library_sources_ifdef(CONFIG_BT_A2DP a2dp.c) zephyr_library_sources_ifdef(CONFIG_BT_AVDTP avdtp.c) zephyr_library_sources_ifdef(CONFIG_BT_RFCOMM rfcomm.c) zephyr_library_sources_ifdef(CONFIG_BT_TESTING testing.c) zephyr_library_sources_ifdef(CONFIG_BT_SETTINGS settings.c) zephyr_library_sources_ifdef(CONFIG_BT_HOST_CCM aes_ccm.c) zephyr_library_sources_ifdef( CONFIG_BT_BREDR keys_br.c l2cap_br.c sdp.c ) zephyr_library_sources_ifdef( CONFIG_BT_HFP_HF hfp_hf.c at.c ) if(CONFIG_BT_HCI_HOST) zephyr_library_sources( uuid.c hci_core.c ) zephyr_library_sources_ifdef( CONFIG_BT_HOST_CRYPTO crypto.c ) if(CONFIG_BT_CONN) zephyr_library_sources( conn.c l2cap.c att.c gatt.c ) if(CONFIG_BT_SMP) zephyr_library_sources( smp.c keys.c ) else() zephyr_library_sources( smp_null.c ) endif() endif() endif()
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/CMakeLists.txt
CMake
apache-2.0
1,323
ccflags-y +=-I$(srctree)/include/drivers ccflags-y +=-I$(srctree)/subsys/bluetooth obj-$(CONFIG_BT_HCI_RAW) += hci_raw.o obj-$(CONFIG_BT_DEBUG_MONITOR) += monitor.o obj-$(CONFIG_BT_TINYCRYPT_ECC) += hci_ecc.o obj-$(CONFIG_BT_INTERNAL_STORAGE) += storage.o ifeq ($(CONFIG_BT_HCI_HOST),y) obj-y += uuid.o hci_core.o ifeq ($(CONFIG_BT_CONN),y) obj-y += conn.o l2cap.o att.o gatt.o ifeq ($(CONFIG_BT_SMP),y) obj-y += smp.o keys.o else obj-y += smp_null.o endif endif obj-$(CONFIG_BT_HOST_CRYPTO) += crypto.o endif obj-$(CONFIG_BT_BREDR) += keys_br.o l2cap_br.o sdp.o obj-$(CONFIG_BT_RFCOMM) += rfcomm.o obj-$(CONFIG_BT_HFP_HF) += at.o hfp_hf.o obj-$(CONFIG_BT_AVDTP) += avdtp.o obj-$(CONFIG_BT_A2DP) += a2dp.o obj-$(CONFIG_BT_MESH) += mesh/
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/Makefile
Makefile
apache-2.0
769
/** @file * @brief Advance Audio Distribution Profile. */ /* * 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 <misc/printk.h> #include <assert.h> #include <bluetooth/bluetooth.h> #include <bluetooth/l2cap.h> #include <bluetooth/avdtp.h> #include <bluetooth/a2dp.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_A2DP) #define LOG_MODULE_NAME bt_a2dp #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "avdtp_internal.h" #include "a2dp_internal.h" #define A2DP_NO_SPACE (-1) struct bt_a2dp { struct bt_avdtp session; }; /* Connections */ static struct bt_a2dp connection[CONFIG_BT_MAX_CONN]; void a2d_reset(struct bt_a2dp *a2dp_conn) { (void)memset(a2dp_conn, 0, sizeof(struct bt_a2dp)); } struct bt_a2dp *get_new_connection(struct bt_conn *conn) { s8_t i, free; free = A2DP_NO_SPACE; if (!conn) { BT_ERR("Invalid Input (err: %d)", -EINVAL); return NULL; } /* Find a space */ for (i = 0; i < CONFIG_BT_MAX_CONN; i++) { if (connection[i].session.br_chan.chan.conn == conn) { BT_DBG("Conn already exists"); return NULL; } if (!connection[i].session.br_chan.chan.conn && free == A2DP_NO_SPACE) { free = i; } } if (free == A2DP_NO_SPACE) { BT_DBG("More connection cannot be supported"); return NULL; } /* Clean the memory area before returning */ a2d_reset(&connection[free]); return &connection[free]; } int a2dp_accept(struct bt_conn *conn, struct bt_avdtp **session) { struct bt_a2dp *a2dp_conn; a2dp_conn = get_new_connection(conn); if (!a2dp_conn) { return -ENOMEM; } *session = &(a2dp_conn->session); BT_DBG("session: %p", &(a2dp_conn->session)); return 0; } /* Callback for incoming requests */ static struct bt_avdtp_ind_cb cb_ind = { /*TODO*/ }; /* The above callback structures need to be packed and passed to AVDTP */ static struct bt_avdtp_event_cb avdtp_cb = { .ind = &cb_ind, .accept = a2dp_accept }; int bt_a2dp_init(void) { int err; /* Register event handlers with AVDTP */ err = bt_avdtp_register(&avdtp_cb); if (err < 0) { BT_ERR("A2DP registration failed"); return err; } BT_DBG("A2DP Initialized successfully."); return 0; } struct bt_a2dp *bt_a2dp_connect(struct bt_conn *conn) { struct bt_a2dp *a2dp_conn; int err; a2dp_conn = get_new_connection(conn); if (!a2dp_conn) { BT_ERR("Cannot allocate memory"); return NULL; } err = bt_avdtp_connect(conn, &(a2dp_conn->session)); if (err < 0) { /* If error occurs, undo the saving and return the error */ a2d_reset(a2dp_conn); BT_DBG("AVDTP Connect failed"); return NULL; } BT_DBG("Connect request sent"); return a2dp_conn; } int bt_a2dp_register_endpoint(struct bt_a2dp_endpoint *endpoint, u8_t media_type, u8_t role) { int err; BT_ASSERT(endpoint); err = bt_avdtp_register_sep(media_type, role, &(endpoint->info)); if (err < 0) { return err; } /* TODO: Register SDP record */ return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/a2dp.c
C
apache-2.0
3,113
/** @file * @brief Advance Audio Distribution Profile Internal header. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /* To be called when first SEP is being registered */ int bt_a2dp_init(void);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/a2dp_internal.h
C
apache-2.0
250
/* * Copyright (c) 2020 Nordic Semiconductor ASA * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <ble_os.h> #include <sys/byteorder.h> #include <bluetooth/crypto.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE) #define LOG_MODULE_NAME bt_aes_ccm #include "common/log.h" static inline void xor16(u8_t *dst, const u8_t *a, const u8_t *b) { dst[0] = a[0] ^ b[0]; dst[1] = a[1] ^ b[1]; dst[2] = a[2] ^ b[2]; dst[3] = a[3] ^ b[3]; dst[4] = a[4] ^ b[4]; dst[5] = a[5] ^ b[5]; dst[6] = a[6] ^ b[6]; dst[7] = a[7] ^ b[7]; dst[8] = a[8] ^ b[8]; dst[9] = a[9] ^ b[9]; dst[10] = a[10] ^ b[10]; dst[11] = a[11] ^ b[11]; dst[12] = a[12] ^ b[12]; dst[13] = a[13] ^ b[13]; dst[14] = a[14] ^ b[14]; dst[15] = a[15] ^ b[15]; } /* pmsg is assumed to have the nonce already present in bytes 1-13 */ static int ccm_calculate_X0(const u8_t key[16], const u8_t *aad, u8_t aad_len, size_t mic_size, u8_t msg_len, u8_t b[16], u8_t X0[16]) { int i, j, err; /* X_0 = e(AppKey, flags || nonce || length) */ b[0] = (((mic_size - 2) / 2) << 3) | ((!!aad_len) << 6) | 0x01; sys_put_be16(msg_len, b + 14); err = bt_encrypt_be(key, b, X0); if (err) { return err; } /* If AAD is being used to authenticate, include it here */ if (aad_len) { sys_put_be16(aad_len, b); for (i = 0; i < sizeof(u16_t); i++) { b[i] = X0[i] ^ b[i]; } j = 0; aad_len += sizeof(u16_t); while (aad_len > 16) { do { b[i] = X0[i] ^ aad[j]; i++, j++; } while (i < 16); aad_len -= 16; i = 0; err = bt_encrypt_be(key, b, X0); if (err) { return err; } } for (; i < aad_len; i++, j++) { b[i] = X0[i] ^ aad[j]; } for (i = aad_len; i < 16; i++) { b[i] = X0[i]; } err = bt_encrypt_be(key, b, X0); if (err) { return err; } } return 0; } static int ccm_auth(const u8_t key[16], u8_t nonce[13], const u8_t *cleartext_msg, size_t msg_len, const u8_t *aad, size_t aad_len, u8_t *mic, size_t mic_size) { u8_t b[16], Xn[16], s0[16]; u16_t blk_cnt, last_blk; int err, j, i; last_blk = msg_len % 16; blk_cnt = (msg_len + 15) / 16; if (!last_blk) { last_blk = 16U; } b[0] = 0x01; memcpy(b + 1, nonce, 13); /* S[0] = e(AppKey, 0x01 || nonce || 0x0000) */ sys_put_be16(0x0000, &b[14]); err = bt_encrypt_be(key, b, s0); if (err) { return err; } ccm_calculate_X0(key, aad, aad_len, mic_size, msg_len, b, Xn); for (j = 0; j < blk_cnt; j++) { /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ if (j + 1 == blk_cnt) { for (i = 0; i < last_blk; i++) { b[i] = Xn[i] ^ cleartext_msg[(j * 16) + i]; } memcpy(&b[i], &Xn[i], 16 - i); } else { xor16(b, Xn, &cleartext_msg[j * 16]); } err = bt_encrypt_be(key, b, Xn); if (err) { return err; } } /* MIC = C_mic ^ X_1 */ for (i = 0; i < mic_size; i++) { mic[i] = s0[i] ^ Xn[i]; } return 0; } static int ccm_crypt(const u8_t key[16], const u8_t nonce[13], const u8_t *in_msg, u8_t *out_msg, size_t msg_len) { u8_t a_i[16], s_i[16]; u16_t last_blk, blk_cnt; size_t i, j; int err; last_blk = msg_len % 16; blk_cnt = (msg_len + 15) / 16; if (!last_blk) { last_blk = 16U; } a_i[0] = 0x01; memcpy(&a_i[1], nonce, 13); for (j = 0; j < blk_cnt; j++) { /* S_1 = e(AppKey, 0x01 || nonce || 0x0001) */ sys_put_be16(j + 1, &a_i[14]); err = bt_encrypt_be(key, a_i, s_i); if (err) { return err; } /* Encrypted = Payload[0-15] ^ C_1 */ if (j < blk_cnt - 1) { xor16(&out_msg[j * 16], s_i, &in_msg[j * 16]); } else { for (i = 0; i < last_blk; i++) { out_msg[(j * 16) + i] = in_msg[(j * 16) + i] ^ s_i[i]; } } } return 0; } int bt_ccm_decrypt(const u8_t key[16], u8_t nonce[13], const u8_t *enc_msg, size_t msg_len, const u8_t *aad, size_t aad_len, u8_t *out_msg, size_t mic_size) { u8_t mic[16]; if (aad_len >= 0xff00 || mic_size > sizeof(mic)) { return -EINVAL; } ccm_crypt(key, nonce, enc_msg, out_msg, msg_len); ccm_auth(key, nonce, out_msg, msg_len, aad, aad_len, mic, mic_size); if (memcmp(mic, enc_msg + msg_len, mic_size)) { return -EBADMSG; } return 0; } int bt_ccm_encrypt(const u8_t key[16], u8_t nonce[13], const u8_t *msg, size_t msg_len, const u8_t *aad, size_t aad_len, u8_t *out_msg, size_t mic_size) { u8_t *mic = out_msg + msg_len; BT_DBG("key %s", bt_hex(key, 16)); BT_DBG("nonce %s", bt_hex(nonce, 13)); BT_DBG("msg (len %zu) %s", msg_len, bt_hex(msg, msg_len)); BT_DBG("aad_len %zu mic_size %zu", aad_len, mic_size); /* Unsupported AAD size */ if (aad_len >= 0xff00 || mic_size > 16) { return -EINVAL; } ccm_auth(key, nonce, out_msg, msg_len, aad, aad_len, mic, mic_size); ccm_crypt(key, nonce, msg, out_msg, msg_len); return 0; }
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/aes_ccm.c
C
apache-2.0
4,803
/** * @file at.c * Generic AT command handling library implementation */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <bt_errno.h> #include <ctype.h> #include <string.h> #include <stdarg.h> #ifdef CONFIG_BT_HFP_HF #include <net/buf.h> #include "at.h" static void next_list(struct at_client *at) { if (at->buf[at->pos] == ',') { at->pos++; } } int at_check_byte(struct net_buf *buf, char check_byte) { const unsigned char *str = buf->data; if (*str != check_byte) { return -EINVAL; } net_buf_pull(buf, 1); return 0; } static void skip_space(struct at_client *at) { while (at->buf[at->pos] == ' ') { at->pos++; } } int at_get_number(struct at_client *at, bt_u32_t *val) { bt_u32_t i; skip_space(at); for (i = 0U, *val = 0U; isdigit((unsigned char)at->buf[at->pos]); at->pos++, i++) { *val = *val * 10U + at->buf[at->pos] - '0'; } if (i == 0U) { return -ENODATA; } next_list(at); return 0; } static bool str_has_prefix(const char *str, const char *prefix) { if (strncmp(str, prefix, strlen(prefix)) != 0) { return false; } return true; } static int at_parse_result(const char *str, struct net_buf *buf, enum at_result *result) { /* Map the result and check for end lf */ if ((!strncmp(str, "OK", 2)) && (at_check_byte(buf, '\n') == 0)) { *result = AT_RESULT_OK; return 0; } if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) { *result = AT_RESULT_ERROR; return 0; } return -ENOMSG; } static int get_cmd_value(struct at_client *at, struct net_buf *buf, char stop_byte, enum at_cmd_state cmd_state) { int cmd_len = 0; u8_t pos = at->pos; const char *str = (char *)buf->data; while (cmd_len < buf->len && at->pos != at->buf_max_len) { if (*str != stop_byte) { at->buf[at->pos++] = *str; cmd_len++; str++; pos = at->pos; } else { cmd_len++; at->buf[at->pos] = '\0'; at->pos = 0U; at->cmd_state = cmd_state; break; } } net_buf_pull(buf, cmd_len); if (pos == at->buf_max_len) { return -ENOBUFS; } return 0; } static int get_response_string(struct at_client *at, struct net_buf *buf, char stop_byte, enum at_state state) { int cmd_len = 0; u8_t pos = at->pos; const char *str = (char *)buf->data; while (cmd_len < buf->len && at->pos != at->buf_max_len) { if (*str != stop_byte) { at->buf[at->pos++] = *str; cmd_len++; str++; pos = at->pos; } else { cmd_len++; at->buf[at->pos] = '\0'; at->pos = 0U; at->state = state; break; } } net_buf_pull(buf, cmd_len); if (pos == at->buf_max_len) { return -ENOBUFS; } return 0; } static void reset_buffer(struct at_client *at) { (void)memset(at->buf, 0, at->buf_max_len); at->pos = 0U; } static int at_state_start(struct at_client *at, struct net_buf *buf) { int err; err = at_check_byte(buf, '\r'); if (err < 0) { return err; } at->state = AT_STATE_START_CR; return 0; } static int at_state_start_cr(struct at_client *at, struct net_buf *buf) { int err; err = at_check_byte(buf, '\n'); if (err < 0) { return err; } at->state = AT_STATE_START_LF; return 0; } static int at_state_start_lf(struct at_client *at, struct net_buf *buf) { reset_buffer(at); if (at_check_byte(buf, '+') == 0) { at->state = AT_STATE_GET_CMD_STRING; return 0; } else if (isalpha(*buf->data)) { at->state = AT_STATE_GET_RESULT_STRING; return 0; } return -ENODATA; } static int at_state_get_cmd_string(struct at_client *at, struct net_buf *buf) { return get_response_string(at, buf, ':', AT_STATE_PROCESS_CMD); } static bool is_cmer(struct at_client *at) { if (strncmp(at->buf, "CME ERROR", 9) == 0) { return true; } return false; } static int at_state_process_cmd(struct at_client *at, struct net_buf *buf) { if (is_cmer(at)) { at->state = AT_STATE_PROCESS_AG_NW_ERR; return 0; } if (at->resp) { at->resp(at, buf); at->resp = NULL; return 0; } at->state = AT_STATE_UNSOLICITED_CMD; return 0; } static int at_state_get_result_string(struct at_client *at, struct net_buf *buf) { return get_response_string(at, buf, '\r', AT_STATE_PROCESS_RESULT); } static bool is_ring(struct at_client *at) { if (strncmp(at->buf, "RING", 4) == 0) { return true; } return false; } static int at_state_process_result(struct at_client *at, struct net_buf *buf) { enum at_cme cme_err; enum at_result result; if (is_ring(at)) { at->state = AT_STATE_UNSOLICITED_CMD; return 0; } if (at_parse_result(at->buf, buf, &result) == 0) { if (at->finish) { /* cme_err is 0 - Is invalid until result is * AT_RESULT_CME_ERROR */ cme_err = 0; at->finish(at, result, cme_err); } } /* Reset the state to process unsolicited response */ at->cmd_state = AT_CMD_START; at->state = AT_STATE_START; return 0; } int cme_handle(struct at_client *at) { enum at_cme cme_err; bt_u32_t val; if (!at_get_number(at, &val) && val <= CME_ERROR_NETWORK_NOT_ALLOWED) { cme_err = val; } else { cme_err = CME_ERROR_UNKNOWN; } if (at->finish) { at->finish(at, AT_RESULT_CME_ERROR, cme_err); } return 0; } static int at_state_process_ag_nw_err(struct at_client *at, struct net_buf *buf) { at->cmd_state = AT_CMD_GET_VALUE; return at_parse_cmd_input(at, buf, NULL, cme_handle, AT_CMD_TYPE_NORMAL); } static int at_state_unsolicited_cmd(struct at_client *at, struct net_buf *buf) { if (at->unsolicited) { return at->unsolicited(at, buf); } return -ENODATA; } /* The order of handler function should match the enum at_state */ static handle_parse_input_t parser_cb[] = { at_state_start, /* AT_STATE_START */ at_state_start_cr, /* AT_STATE_START_CR */ at_state_start_lf, /* AT_STATE_START_LF */ at_state_get_cmd_string, /* AT_STATE_GET_CMD_STRING */ at_state_process_cmd, /* AT_STATE_PROCESS_CMD */ at_state_get_result_string, /* AT_STATE_GET_RESULT_STRING */ at_state_process_result, /* AT_STATE_PROCESS_RESULT */ at_state_process_ag_nw_err, /* AT_STATE_PROCESS_AG_NW_ERR */ at_state_unsolicited_cmd /* AT_STATE_UNSOLICITED_CMD */ }; int at_parse_input(struct at_client *at, struct net_buf *buf) { int ret; while (buf->len) { if (at->state < AT_STATE_START || at->state >= AT_STATE_END) { return -EINVAL; } ret = parser_cb[at->state](at, buf); if (ret < 0) { /* Reset the state in case of error */ at->cmd_state = AT_CMD_START; at->state = AT_STATE_START; return ret; } } return 0; } static int at_cmd_start(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) { if (!str_has_prefix(at->buf, prefix)) { if (type == AT_CMD_TYPE_NORMAL) { at->state = AT_STATE_UNSOLICITED_CMD; } return -ENODATA; } if (type == AT_CMD_TYPE_OTHER) { /* Skip for Other type such as ..RING.. which does not have * values to get processed. */ at->cmd_state = AT_CMD_PROCESS_VALUE; } else { at->cmd_state = AT_CMD_GET_VALUE; } return 0; } static int at_cmd_get_value(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) { /* Reset buffer before getting the values */ reset_buffer(at); return get_cmd_value(at, buf, '\r', AT_CMD_PROCESS_VALUE); } static int at_cmd_process_value(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) { int ret; ret = func(at); at->cmd_state = AT_CMD_STATE_END_LF; return ret; } static int at_cmd_state_end_lf(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) { int err; err = at_check_byte(buf, '\n'); if (err < 0) { return err; } at->cmd_state = AT_CMD_START; at->state = AT_STATE_START; return 0; } /* The order of handler function should match the enum at_cmd_state */ static handle_cmd_input_t cmd_parser_cb[] = { at_cmd_start, /* AT_CMD_START */ at_cmd_get_value, /* AT_CMD_GET_VALUE */ at_cmd_process_value, /* AT_CMD_PROCESS_VALUE */ at_cmd_state_end_lf /* AT_CMD_STATE_END_LF */ }; int at_parse_cmd_input(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) { int ret; while (buf->len) { if (at->cmd_state < AT_CMD_START || at->cmd_state >= AT_CMD_STATE_END) { return -EINVAL; } ret = cmd_parser_cb[at->cmd_state](at, buf, prefix, func, type); if (ret < 0) { return ret; } /* Check for main state, the end of cmd parsing and return. */ if (at->state == AT_STATE_START) { return 0; } } return 0; } int at_has_next_list(struct at_client *at) { return at->buf[at->pos] != '\0'; } int at_open_list(struct at_client *at) { skip_space(at); /* The list shall start with '(' open parenthesis */ if (at->buf[at->pos] != '(') { return -ENODATA; } at->pos++; return 0; } int at_close_list(struct at_client *at) { skip_space(at); if (at->buf[at->pos] != ')') { return -ENODATA; } at->pos++; next_list(at); return 0; } int at_list_get_string(struct at_client *at, char *name, u8_t len) { int i = 0; skip_space(at); if (at->buf[at->pos] != '"') { return -ENODATA; } at->pos++; while (at->buf[at->pos] != '\0' && at->buf[at->pos] != '"') { if (i == len) { return -ENODATA; } name[i++] = at->buf[at->pos++]; } if (i == len) { return -ENODATA; } name[i] = '\0'; if (at->buf[at->pos] != '"') { return -ENODATA; } at->pos++; skip_space(at); next_list(at); return 0; } int at_list_get_range(struct at_client *at, bt_u32_t *min, bt_u32_t *max) { bt_u32_t low, high; int ret; ret = at_get_number(at, &low); if (ret < 0) { return ret; } if (at->buf[at->pos] == '-') { at->pos++; goto out; } if (!isdigit((unsigned char)at->buf[at->pos])) { return -ENODATA; } out: ret = at_get_number(at, &high); if (ret < 0) { return ret; } *min = low; *max = high; next_list(at); return 0; } void at_register_unsolicited(struct at_client *at, at_resp_cb_t unsolicited) { at->unsolicited = unsolicited; } void at_register(struct at_client *at, at_resp_cb_t resp, at_finish_cb_t finish) { at->resp = resp; at->finish = finish; at->state = AT_STATE_START; } #endif
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/at.c
C
apache-2.0
10,264
/** @file at.h * @brief Internal APIs for AT command handling. */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ enum at_result { AT_RESULT_OK, AT_RESULT_ERROR, AT_RESULT_CME_ERROR }; enum at_cme { CME_ERROR_AG_FAILURE = 0, CME_ERROR_NO_CONNECTION_TO_PHONE = 1, CME_ERROR_OPERATION_NOT_ALLOWED = 3, CME_ERROR_OPERATION_NOT_SUPPORTED = 4, CME_ERROR_PH_SIM_PIN_REQUIRED = 5, CME_ERROR_SIM_NOT_INSERTED = 10, CME_ERROR_SIM_PIN_REQUIRED = 11, CME_ERROR_SIM_PUK_REQUIRED = 12, CME_ERROR_SIM_FAILURE = 13, CME_ERROR_SIM_BUSY = 14, CME_ERROR_INCORRECT_PASSWORD = 16, CME_ERROR_SIM_PIN2_REQUIRED = 17, CME_ERROR_SIM_PUK2_REQUIRED = 18, CME_ERROR_MEMORY_FULL = 20, CME_ERROR_INVALID_INDEX = 21, CME_ERROR_MEMORY_FAILURE = 23, CME_ERROR_TEXT_STRING_TOO_LONG = 24, CME_ERROR_INVALID_CHARS_IN_TEXT_STRING = 25, CME_ERROR_DIAL_STRING_TO_LONG = 26, CME_ERROR_INVALID_CHARS_IN_DIAL_STRING = 27, CME_ERROR_NO_NETWORK_SERVICE = 30, CME_ERROR_NETWORK_TIMEOUT = 31, CME_ERROR_NETWORK_NOT_ALLOWED = 32, CME_ERROR_UNKNOWN = 33, }; enum at_state { AT_STATE_START, AT_STATE_START_CR, AT_STATE_START_LF, AT_STATE_GET_CMD_STRING, AT_STATE_PROCESS_CMD, AT_STATE_GET_RESULT_STRING, AT_STATE_PROCESS_RESULT, AT_STATE_PROCESS_AG_NW_ERR, AT_STATE_UNSOLICITED_CMD, AT_STATE_END }; enum at_cmd_state { AT_CMD_START, AT_CMD_GET_VALUE, AT_CMD_PROCESS_VALUE, AT_CMD_STATE_END_LF, AT_CMD_STATE_END }; enum at_cmd_type { AT_CMD_TYPE_NORMAL, AT_CMD_TYPE_UNSOLICITED, AT_CMD_TYPE_OTHER }; struct at_client; /* Callback at_resp_cb_t used to parse response value received for the * particular AT command. Eg: +CIND=<value> */ typedef int (*at_resp_cb_t)(struct at_client *at, struct net_buf *buf); /* Callback at_finish_cb used to monitor the success or failure of the AT * command received from server. * Argument 'cme_err' is valid only when argument 'result' is equal to * AT_RESULT_CME_ERROR */ typedef int (*at_finish_cb_t)(struct at_client *at, enum at_result result, enum at_cme cme_err); typedef int (*parse_val_t)(struct at_client *at); typedef int (*handle_parse_input_t)(struct at_client *at, struct net_buf *buf); typedef int (*handle_cmd_input_t)(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type); struct at_client { char *buf; u8_t pos; u8_t buf_max_len; u8_t state; u8_t cmd_state; at_resp_cb_t resp; at_resp_cb_t unsolicited; at_finish_cb_t finish; }; /* Register the callback functions */ void at_register(struct at_client *at, at_resp_cb_t resp, at_finish_cb_t finish); void at_register_unsolicited(struct at_client *at, at_resp_cb_t unsolicited); int at_get_number(struct at_client *at, bt_u32_t *val); /* This parsing will only works for non-fragmented net_buf */ int at_parse_input(struct at_client *at, struct net_buf *buf); /* This command parsing will only works for non-fragmented net_buf */ int at_parse_cmd_input(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type); int at_check_byte(struct net_buf *buf, char check_byte); int at_list_get_range(struct at_client *at, bt_u32_t *min, bt_u32_t *max); int at_list_get_string(struct at_client *at, char *name, u8_t len); int at_close_list(struct at_client *at); int at_open_list(struct at_client *at); int at_has_next_list(struct at_client *at);
YifuLiu/AliOS-Things
components/ble_host/bt_host/host/at.h
C
apache-2.0
3,735