diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3678a5412276377856c3e7fb6479c62b432ff2d1 --- /dev/null +++ b/core/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 2.8) +project (dapcore) + +set(CORE_SRCS common.c config.c dap_client.c dap_server.c) + +add_library(${PROJECT_NAME} STATIC ${CORE_SRCS}) + +target_link_libraries(${PROJECT_NAME} ev) + +set(${PROJECT_NAME}_DEFINITIONS CACHE INTERNAL "${PROJECT_NAME}: Definitions" FORCE) + +set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR} CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE) diff --git a/core/common.c b/core/common.c new file mode 100644 index 0000000000000000000000000000000000000000..f3abfd97214051ada2b9bb664f51ecc3f2a8dba1 --- /dev/null +++ b/core/common.c @@ -0,0 +1,230 @@ +#include <string.h> +#include <stdarg.h> +#include <pthread.h> +#include <stdio.h> +#include <syslog.h> +#include <libconfig.h> +#include <unistd.h> +#include "common.h" +#include "config.h" +#define LAST_ERROR_MAX 255 + +#define LOG_TAG "common" + +char last_error[LAST_ERROR_MAX]={0}; +enum log_level log_level=DEBUG; +FILE * lf=NULL; + +int common_init() +{ + const char * fn = (my_config.log_file)? my_config.log_file : DEF_LOG ; + lf=fopen(fn, "a"); + if(lf==NULL){ + fprintf(stderr,"Can't open log file %s to append\n", fn); + lf=stdout; + return -1; + } + + //printf("Common init\n"); + // lf=fopen("/dev/stdout","a"); + //lf=stdout; + //strcpy(last_error,"undefined"); + log_it(INFO,"Common modules init (%s)", fn); + return 0; +} + +void common_deinit() +{ + if(lf) fclose(lf); +} + +void _log_it(const char * log_tag,enum log_level ll, const char * format,...) +{ +// branch predictor optimization +#if defined(__GNUC__)||defined(__GNUG__)||defined(__clang__) + if (__builtin_expect(!lf,0)) +#else + if (!lf) +#endif + common_init(); + + va_list ap,ap2; + + static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; + + if(ll<log_level) + return; + + pthread_mutex_lock(&mutex); + time_t t=time(NULL); + struct tm* tmp=localtime(&t); + static char s_time[1024]={0}; + strftime(s_time,sizeof(s_time),"%x-%X",tmp); + + va_start(ap,format); + va_copy(ap2,ap); + fprintf(lf,"[%s] ",s_time); + printf("[%s] ",s_time); + /*if(ll>=ERROR){ + vsnprintf(last_error,LAST_ERROR_MAX,format,ap); + }*/ + if(ll==DEBUG){ + fprintf(lf,"[DBG] "); + printf( "\x1b[37;2m[DBG] "); + }else if(ll==INFO){ + fprintf(lf,"[ ] "); + printf("\x1b[32;2m[ ] "); + }else if(ll==NOTICE){ + fprintf(lf,"[ * ] "); + printf("\x1b[32m[ * ] "); + }else if(ll==WARNING){ + fprintf(lf,"[WRN] "); + printf("\x1b[31;2m[WRN] "); + }else if(ll==ERROR){ + fprintf(lf,"[ERR] "); + printf("\x1b[31m[ERR] "); + }else if(ll==CRITICAL){ + fprintf(lf,"[!!!] "); + printf("\x1b[1;5;31m[!!!] "); + } + fprintf(lf,"[%8s]\t",log_tag); + printf("[%8s]\t",log_tag); + + vfprintf(lf,format,ap); + vprintf(format,ap2); + fprintf(lf,"\n"); + printf("\x1b[0m\n"); + va_end(ap); + va_end(ap2); + fflush(lf); + fflush(stdout); + pthread_mutex_unlock(&mutex); +} + +const char * log_error() +{ + return last_error; +} + +#define INT_DIGITS 19 /* enough for 64 bit integer */ + +char *itoa(int i) +{ + /* Room for INT_DIGITS digits, - and '\0' */ + static char buf[INT_DIGITS + 2]; + char *p = buf + INT_DIGITS + 1; /* points to terminating '\0' */ + if (i >= 0) { + do { + *--p = '0' + (i % 10); + i /= 10; + } while (i != 0); + return p; + } + else { /* i < 0 */ + do { + *--p = '0' - (i % 10); + i /= 10; + } while (i != 0); + *--p = '-'; + } + return p; +} + +/** + * @brief time_to_rfc822 Convert time_t to string with RFC822 formatted date and time + * @param out Output buffer + * @param out_size_mac Maximum size of output buffer + * @param t UNIX time + * @return Length of resulting string if ok or lesser than zero if not + */ +int time_to_rfc822(char * out, size_t out_size_max, time_t t) +{ + struct tm *tmp; + tmp=localtime(&t); + if(tmp== NULL){ + log_it(ERROR,"Can't convert data from unix fromat to structured one"); + return -2; + }else{ + int ret; + ret=strftime(out, out_size_max,"%a, %d %b %y %T %z",tmp); + //free(tmp); + if(ret>0){ + return ret; + }else{ + log_it(ERROR,"Can't print formatted time in string"); + return -1; + } + } +} + +/** + * @brief get_select_breaker + * @return + */ +static int breaker_set[2] = { -1, -1 }; +static int initialized = 0; +static struct timespec break_latency = { tv_sec: 0, tv_nsec: 1 * 1000 * 1000 }; +int get_select_breaker() +{ + if (!initialized) + { + if (pipe(breaker_set) < 0) return -1; + else initialized = 1; + } + + return breaker_set[0]; +} + +int send_select_break() +{ + if (!initialized) return -1; + char buffer[1]; + if (write(breaker_set[1], "\0", 1) <= 0) return -1; + nanosleep(&break_latency, NULL); + if (read(breaker_set[0], buffer, 1) <= 0 || buffer[0] != '\0') return -1; + return 0; +} + + +void hexdump(const void* data, size_t size) +{ + char ascii[17]; + size_t i, j; + ascii[16] = '\0'; + for (i = 0; i < size; ++i) { + printf("%02X ", ((unsigned char*)data)[i]); + if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') { + ascii[i % 16] = ((unsigned char*)data)[i]; + } else { + ascii[i % 16] = '.'; + } + if ((i+1) % 8 == 0 || i+1 == size) { + printf(" "); + if ((i+1) % 16 == 0) { + printf("| %s \n", ascii); + } else if (i+1 == size) { + ascii[(i+1) % 16] = '\0'; + if ((i+1) % 16 <= 8) { + printf(" "); + } + for (j = (i+1) % 16; j < 16; ++j) { + printf(" "); + } + printf("| %s \n", ascii); + } + } + } +} + +/** +* @brief get_utc_date_time +* @param buf_out ( not less 20 bytes ) +* @return example: 2017-08-12 13:28:36 +*/ +void get_utc_date_time(char buf_out[]) +{ + struct tm *local; + time_t t = time(NULL); + local = gmtime(&t); + strftime(buf_out, 20, "%Y-%m-%d %H:%M:%S", local); +} diff --git a/core/common.h b/core/common.h new file mode 100644 index 0000000000000000000000000000000000000000..67a47c14ccdd8bcb3f8f16c558ae2af13809ada4 --- /dev/null +++ b/core/common.h @@ -0,0 +1,33 @@ + +#ifndef COMMON_H +#define COMMON_H +#include <stdarg.h> +#include <stddef.h> +#include <stdlib.h> +#include <time.h> + +#define CALLOC(a) ((a *) calloc(1,sizeof(a))) +#define DUP(a) (__typeof(a) ret = memcpy(ret,a,sizeof(*a)) ) + +#define DEF_LOG "/opt/dapserver/log/dapserver.log" +//#define DEF_LOG "/opt/DAP/log/confcall_server.log" + +enum log_level{CRITICAL=5,ERROR=4, WARNING=3,NOTICE=2,INFO=1,DEBUG=0}; +extern enum log_level log_level; + +extern int common_init(); +extern void common_deinit(); + +extern void _log_it(const char * log_tag, enum log_level, const char * format,...); +#define log_it(_log_level,...) _log_it(LOG_TAG,_log_level,##__VA_ARGS__) + +extern const char * log_error(); + +extern char *itoa(int i); +extern int time_to_rfc822(char * out, size_t out_size_max, time_t t); + +extern void get_utc_date_time(char buf_out[]); +extern void hexdump(const void* data, size_t size); +extern int send_select_break(); +extern int get_select_breaker(); +#endif diff --git a/core/uthash.h b/core/uthash.h new file mode 100644 index 0000000000000000000000000000000000000000..775599c9a8c2ce33d06323bbd2da161744b58160 --- /dev/null +++ b/core/uthash.h @@ -0,0 +1,1074 @@ +/* +Copyright (c) 2003-2016, Troy D. Hanson http://troydhanson.github.com/uthash/ +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. + +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. +*/ + +#ifndef UTHASH_H +#define UTHASH_H + +#define UTHASH_VERSION 2.0.1 + +#include <string.h> /* memcmp,strlen */ +#include <stddef.h> /* ptrdiff_t */ +#include <stdlib.h> /* exit() */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#if defined(_MSC_VER) /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define DECLTYPE(x) +#endif +#elif defined(__BORLANDC__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#define DECLTYPE(x) +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + char **_da_dst = (char**)(&(dst)); \ + *_da_dst = (char*)(src); \ +} while (0) +#else +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + (dst) = DECLTYPE(dst)(src); \ +} while (0) +#endif + +/* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */ +#if defined(_WIN32) +#if defined(_MSC_VER) && _MSC_VER >= 1600 +#include <stdint.h> +#elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) +#include <stdint.h> +#else +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#endif +#elif defined(__GNUC__) && !defined(__VXWORKS__) +#include <stdint.h> +#else +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#endif + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ +#endif +#ifndef uthash_malloc +#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef uthash_free +#define uthash_free(ptr,sz) free(ptr) /* free fcn */ +#endif +#ifndef uthash_strlen +#define uthash_strlen(s) strlen(s) +#endif +#ifndef uthash_memcmp +#define uthash_memcmp(a,b,n) memcmp(a,b,n) +#endif + +#ifndef uthash_noexpand_fyi +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#endif +#ifndef uthash_expand_fyi +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ +#endif + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhp */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) +/* calculate the hash handle from element address elp */ +#define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) + +#define HASH_VALUE(keyptr,keylen,hashv) \ +do { \ + HASH_FCN(keyptr, keylen, hashv); \ +} while (0) + +#define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ +do { \ + (out) = NULL; \ + if (head) { \ + unsigned _hf_bkt; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ + } \ + } \ +} while (0) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + unsigned _hf_hashv; \ + HASH_VALUE(keyptr, keylen, _hf_hashv); \ + HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) +#define HASH_BLOOM_MAKE(tbl) \ +do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ + memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ +} while (0) + +#define HASH_BLOOM_FREE(tbl) \ +do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ +} while (0) + +#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) + +#else +#define HASH_BLOOM_MAKE(tbl) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_TEST(tbl,hashv) (1) +#define HASH_BLOOM_BYTELEN 0U +#endif + +#define HASH_MAKE_TABLE(hh,head) \ +do { \ + (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ + sizeof(UT_hash_table)); \ + if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl->buckets, 0, \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ +} while (0) + +#define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ +do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ +} while (0) + +#define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ +do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ +} while (0) + +#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ +do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ +} while (0) + +#define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ +do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ +} while (0) + +#define HASH_APPEND_LIST(hh, head, add) \ +do { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail->next = (add); \ + (head)->hh.tbl->tail = &((add)->hh); \ +} while (0) + +#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (char*) (keyptr); \ + (add)->hh.keylen = (unsigned) (keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + (head) = (add); \ + HASH_MAKE_TABLE(hh, head); \ + } else { \ + void *_hs_iter = (head); \ + (add)->hh.tbl = (head)->hh.tbl; \ + do { \ + if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) \ + break; \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ + if (_hs_iter) { \ + (add)->hh.next = _hs_iter; \ + if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ + HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ + } else { \ + (head) = (add); \ + } \ + HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ + } else { \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + } \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + HASH_FSCK(hh, head); \ +} while (0) + +#define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ +do { \ + unsigned _hs_hashv; \ + HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ +} while (0) + +#define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) + +#define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ + HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) + +#define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (char*) (keyptr); \ + (add)->hh.keylen = (unsigned) (keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + (head) = (add); \ + HASH_MAKE_TABLE(hh, head); \ + } else { \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + HASH_FSCK(hh, head); \ +} while (0) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_hashv; \ + HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ +} while (0) + +#define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) + +#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) + +#define HASH_TO_BKT(hashv,num_bkts,bkt) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1U)); \ +} while (0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh,head,delptr) \ +do { \ + struct UT_hash_handle *_hd_hh_del; \ + if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + head = NULL; \ + } else { \ + unsigned _hd_bkt; \ + _hd_hh_del = &((delptr)->hh); \ + if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ + (head)->hh.tbl->tail = \ + (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho); \ + } \ + if ((delptr)->hh.prev != NULL) { \ + ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ + } else { \ + DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ + } \ + if (_hd_hh_del->next != NULL) { \ + ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ + (head)->hh.tbl->hho))->prev = \ + _hd_hh_del->prev; \ + } \ + HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh,head); \ +} while (0) + + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ + HASH_FIND(hh,head,findstr,(unsigned)uthash_strlen(findstr),out) +#define HASH_ADD_STR(head,strfield,add) \ + HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add) +#define HASH_REPLACE_STR(head,strfield,add,replaced) \ + HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add,replaced) +#define HASH_FIND_INT(head,findint,out) \ + HASH_FIND(hh,head,findint,sizeof(int),out) +#define HASH_ADD_INT(head,intfield,add) \ + HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_REPLACE_INT(head,intfield,add,replaced) \ + HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) +#define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ + HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) +#define HASH_DEL(head,delptr) \ + HASH_DELETE(hh,head,delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh,head) \ +do { \ + struct UT_hash_handle *_thh; \ + if (head) { \ + unsigned _bkt_i; \ + unsigned _count; \ + char *_prev; \ + _count = 0; \ + for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ + unsigned _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char*)(_thh->hh_prev)) { \ + HASH_OOPS("invalid hh_prev %p, actual %p\n", \ + _thh->hh_prev, _prev ); \ + } \ + _bkt_count++; \ + _prev = (char*)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("invalid bucket count %u, actual %u\n", \ + (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid hh item count %u, actual %u\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + /* traverse hh in app order; check next/prev integrity, count */ \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev !=(char*)(_thh->prev)) { \ + HASH_OOPS("invalid prev %p, actual %p\n", \ + _thh->prev, _prev ); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ + (head)->hh.tbl->hho) : NULL ); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid app item count %u, actual %u\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include <unistd.h> to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ +do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ +} while (0) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#endif + +/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ +#ifdef HASH_FUNCTION +#define HASH_FCN HASH_FUNCTION +#else +#define HASH_FCN HASH_JEN +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ +#define HASH_BER(key,keylen,hashv) \ +do { \ + unsigned _hb_keylen=(unsigned)keylen; \ + const unsigned char *_hb_key=(const unsigned char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen-- != 0U) { \ + (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ + } \ +} while (0) + + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key,keylen,hashv) \ +do { \ + unsigned _sx_i; \ + const unsigned char *_hs_key=(const unsigned char*)(key); \ + hashv = 0; \ + for(_sx_i=0; _sx_i < keylen; _sx_i++) { \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + } \ +} while (0) +/* FNV-1a variation */ +#define HASH_FNV(key,keylen,hashv) \ +do { \ + unsigned _fn_i; \ + const unsigned char *_hf_key=(const unsigned char*)(key); \ + hashv = 2166136261U; \ + for(_fn_i=0; _fn_i < keylen; _fn_i++) { \ + hashv = hashv ^ _hf_key[_fn_i]; \ + hashv = hashv * 16777619U; \ + } \ +} while (0) + +#define HASH_OAT(key,keylen,hashv) \ +do { \ + unsigned _ho_i; \ + const unsigned char *_ho_key=(const unsigned char*)(key); \ + hashv = 0; \ + for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ +} while (0) + +#define HASH_JEN_MIX(a,b,c) \ +do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ +} while (0) + +#define HASH_JEN(key,keylen,hashv) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + unsigned const char *_hj_key=(unsigned const char*)(key); \ + hashv = 0xfeedbeefu; \ + _hj_i = _hj_j = 0x9e3779b9u; \ + _hj_k = (unsigned)(keylen); \ + while (_hj_k >= 12U) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12U; \ + } \ + hashv += (unsigned)(keylen); \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ + case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ + case 1: _hj_i += _hj_key[0]; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ +} while (0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#endif + +#if !defined (get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif +#define HASH_SFH(key,keylen,hashv) \ +do { \ + unsigned const char *_sfh_key=(unsigned const char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ + \ + unsigned _sfh_rem = _sfh_len & 3U; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabeu; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0U; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2U*sizeof (uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ +} while (0) + +#ifdef HASH_USING_NO_STRICT_ALIASING +/* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. + * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. + * MurmurHash uses the faster approach only on CPU's where we know it's safe. + * + * Note the preprocessor built-in defines can be emitted using: + * + * gcc -m64 -dM -E - < /dev/null (on gcc) + * cc -## a.c (where a.c is a simple test file) (Sun Studio) + */ +#if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) +#define MUR_GETBLOCK(p,i) p[i] +#else /* non intel */ +#define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL) +#define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) +#define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) +#define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) +#define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) +#if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) +#define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) +#define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) +#define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) +#else /* assume little endian non-intel */ +#define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) +#define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) +#define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) +#endif +#define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ + (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ + (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ + MUR_ONE_THREE(p)))) +#endif +#define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) +#define MUR_FMIX(_h) \ +do { \ + _h ^= _h >> 16; \ + _h *= 0x85ebca6bu; \ + _h ^= _h >> 13; \ + _h *= 0xc2b2ae35u; \ + _h ^= _h >> 16; \ +} while (0) + +#define HASH_MUR(key,keylen,hashv) \ +do { \ + const uint8_t *_mur_data = (const uint8_t*)(key); \ + const int _mur_nblocks = (int)(keylen) / 4; \ + uint32_t _mur_h1 = 0xf88D5353u; \ + uint32_t _mur_c1 = 0xcc9e2d51u; \ + uint32_t _mur_c2 = 0x1b873593u; \ + uint32_t _mur_k1 = 0; \ + const uint8_t *_mur_tail; \ + const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+(_mur_nblocks*4)); \ + int _mur_i; \ + for(_mur_i = -_mur_nblocks; _mur_i!=0; _mur_i++) { \ + _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + \ + _mur_h1 ^= _mur_k1; \ + _mur_h1 = MUR_ROTL32(_mur_h1,13); \ + _mur_h1 = (_mur_h1*5U) + 0xe6546b64u; \ + } \ + _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ + _mur_k1=0; \ + switch((keylen) & 3U) { \ + case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ + case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ + case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + _mur_h1 ^= _mur_k1; \ + } \ + _mur_h1 ^= (uint32_t)(keylen); \ + MUR_FMIX(_mur_h1); \ + hashv = _mur_h1; \ +} while (0) +#endif /* HASH_USING_NO_STRICT_ALIASING */ + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ +do { \ + if ((head).hh_head != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ + } else { \ + (out) = NULL; \ + } \ + while ((out) != NULL) { \ + if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ + if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \ + break; \ + } \ + } \ + if ((out)->hh.hh_next != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ + } else { \ + (out) = NULL; \ + } \ + } \ +} while (0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head,addhh) \ +do { \ + head.count++; \ + (addhh)->hh_next = head.hh_head; \ + (addhh)->hh_prev = NULL; \ + if (head.hh_head != NULL) { (head).hh_head->hh_prev = (addhh); } \ + (head).hh_head=addhh; \ + if ((head.count >= ((head.expand_mult+1U) * HASH_BKT_CAPACITY_THRESH)) \ + && ((addhh)->tbl->noexpand != 1U)) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ +} while (0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(hh,head,hh_del) \ + (head).count--; \ + if ((head).hh_head == hh_del) { \ + (head).hh_head = hh_del->hh_next; \ + } \ + if (hh_del->hh_prev) { \ + hh_del->hh_prev->hh_next = hh_del->hh_next; \ + } \ + if (hh_del->hh_next) { \ + hh_del->hh_next->hh_prev = hh_del->hh_prev; \ + } + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(tbl) \ +do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ + 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ + memset(_he_new_buckets, 0, \ + 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + tbl->ideal_chain_maxlen = \ + (tbl->num_items >> (tbl->log2_num_buckets+1U)) + \ + (((tbl->num_items & ((tbl->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ + tbl->nonideal_items = 0; \ + for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ + { \ + _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh != NULL) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2U, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ + if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ + tbl->nonideal_items++; \ + _he_newbkt->expand_mult = _he_newbkt->count / \ + tbl->ideal_chain_maxlen; \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head != NULL) { _he_newbkt->hh_head->hh_prev = \ + _he_thh; } \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + tbl->num_buckets *= 2U; \ + tbl->log2_num_buckets++; \ + tbl->buckets = _he_new_buckets; \ + tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ + (tbl->ineff_expands+1U) : 0U; \ + if (tbl->ineff_expands > 1U) { \ + tbl->noexpand=1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ +} while (0) + + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) +#define HASH_SRT(hh,head,cmpfcn) \ +do { \ + unsigned _hs_i; \ + unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head != NULL) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping != 0U) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p != NULL) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ + _hs_psize++; \ + _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + if (! (_hs_q) ) { break; } \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize > 0U) || ((_hs_qsize > 0U) && (_hs_q != NULL))) {\ + if (_hs_psize == 0U) { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } else if ( (_hs_qsize == 0U) || (_hs_q == NULL) ) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL){ \ + _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + } \ + _hs_psize--; \ + } else if (( \ + cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ + ) <= 0) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL){ \ + _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail != NULL ) { \ + _hs_tail->next = ((_hs_e != NULL) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e != NULL) { \ + _hs_e->prev = ((_hs_tail != NULL) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail != NULL){ \ + _hs_tail->next = NULL; \ + } \ + if ( _hs_nmerges <= 1U ) { \ + _hs_looping=0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2U; \ + } \ + HASH_FSCK(hh,head); \ + } \ +} while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ +do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt=NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ + ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ + if (src != NULL) { \ + for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh != NULL; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh != NULL) { _last_elt_hh->next = _elt; } \ + if (dst == NULL) { \ + DECLTYPE_ASSIGN(dst,_elt); \ + HASH_MAKE_TABLE(hh_dst,dst); \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst,dst); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if (head != NULL) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)=NULL; \ + } \ +} while (0) + +#define HASH_OVERHEAD(hh,head) \ + ((head != NULL) ? ( \ + (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ + ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ + sizeof(UT_hash_table) + \ + (HASH_BLOOM_BYTELEN))) : 0U) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ + (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ + (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) + +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1u +#define HASH_BLOOM_SIGNATURE 0xb12220f2u + +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + uint8_t bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */ diff --git a/core/utlist.h b/core/utlist.h new file mode 100644 index 0000000000000000000000000000000000000000..9b5534ffbdb07d6504891f1135e9a8d70bfb137f --- /dev/null +++ b/core/utlist.h @@ -0,0 +1,895 @@ +/* +Copyright (c) 2007-2016, Troy D. Hanson http://troydhanson.github.com/uthash/ +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. + +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. +*/ + +#ifndef UTLIST_H +#define UTLIST_H + +#define UTLIST_VERSION 2.0.1 + +#include <assert.h> + +/* + * This file contains macros to manipulate singly and doubly-linked lists. + * + * 1. LL_ macros: singly-linked lists. + * 2. DL_ macros: doubly-linked lists. + * 3. CDL_ macros: circular doubly-linked lists. + * + * To use singly-linked lists, your structure must have a "next" pointer. + * To use doubly-linked lists, your structure must "prev" and "next" pointers. + * Either way, the pointer to the head of the list must be initialized to NULL. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *prev, *next; + * } + * + * struct item *list = NULL: + * + * int main() { + * struct item *item; + * ... allocate and populate item ... + * DL_APPEND(list, item); + * } + * -------------------------------------------------- + * + * For doubly-linked lists, the append and delete macros are O(1) + * For singly-linked lists, append and delete are O(n) but prepend is O(1) + * The sort macro is O(n log(n)) for all types of single/double/circular lists. + */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ code), this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#ifdef _MSC_VER /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define LDECLTYPE(x) decltype(x) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#endif +#elif defined(__ICCARM__) +#define NO_DECLTYPE +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#endif + +/* for VS2008 we use some workarounds to get around the lack of decltype, + * namely, we always reassign our tmp variable to the list head if we need + * to dereference its prev/next pointers, and save/restore the real head.*/ +#ifdef NO_DECLTYPE +#define IF_NO_DECLTYPE(x) x +#define LDECLTYPE(x) char* +#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } +#define _NEXT(elt,list,next) ((char*)((list)->next)) +#define _NEXTASGN(elt,list,to,next) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } +/* #define _PREV(elt,list,prev) ((char*)((list)->prev)) */ +#define _PREVASGN(elt,list,to,prev) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } +#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } +#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } +#else +#define IF_NO_DECLTYPE(x) +#define _SV(elt,list) +#define _NEXT(elt,list,next) ((elt)->next) +#define _NEXTASGN(elt,list,to,next) ((elt)->next)=(to) +/* #define _PREV(elt,list,prev) ((elt)->prev) */ +#define _PREVASGN(elt,list,to,prev) ((elt)->prev)=(to) +#define _RS(list) +#define _CASTASGN(a,b) (a)=(b) +#endif + +/****************************************************************************** + * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * + * Unwieldy variable names used here to avoid shadowing passed-in variables. * + *****************************************************************************/ +#define LL_SORT(list, cmp) \ + LL_SORT2(list, cmp, next) + +#define LL_SORT2(list, cmp, next) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list,next); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e,next); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL,next); _RS(list); \ + } \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ +} while (0) + + +#define DL_SORT(list, cmp) \ + DL_SORT2(list, cmp, prev, next) + +#define DL_SORT2(list, cmp, prev, next) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list,next); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while ((_ls_psize > 0) || ((_ls_qsize > 0) && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } else if ((_ls_qsize == 0) || (!_ls_q)) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e,next); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail,prev); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN((list)->prev, _ls_tail); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL,next); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ +} while (0) + +#define CDL_SORT(list, cmp) \ + CDL_SORT2(list, cmp, prev, next) + +#define CDL_SORT2(list, cmp, prev, next) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); \ + if (_NEXT(_ls_q,list,next) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = _NEXT(_ls_q,list,next); \ + } \ + _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e,next); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail,prev); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN((list)->prev,_ls_tail); \ + _CASTASGN(_tmp,list); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp,next); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ +} while (0) + +/****************************************************************************** + * singly linked list macros (non-circular) * + *****************************************************************************/ +#define LL_PREPEND(head,add) \ + LL_PREPEND2(head,add,next) + +#define LL_PREPEND2(head,add,next) \ +do { \ + (add)->next = (head); \ + (head) = (add); \ +} while (0) + +#define LL_CONCAT(head1,head2) \ + LL_CONCAT2(head1,head2,next) + +#define LL_CONCAT2(head1,head2,next) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head1) { \ + _tmp = (head1); \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(head2); \ + } else { \ + (head1)=(head2); \ + } \ +} while (0) + +#define LL_APPEND(head,add) \ + LL_APPEND2(head,add,next) + +#define LL_APPEND2(head,add,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + (add)->next=NULL; \ + if (head) { \ + _tmp = (head); \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(add); \ + } else { \ + (head)=(add); \ + } \ +} while (0) + +#define LL_DELETE(head,del) \ + LL_DELETE2(head,del,next) + +#define LL_DELETE2(head,del,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (del))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (del)->next; \ + } \ + } \ +} while (0) + +#define LL_COUNT(head,el,counter) \ + LL_COUNT2(head,el,counter,next) \ + +#define LL_COUNT2(head,el,counter,next) \ +do { \ + (counter) = 0; \ + LL_FOREACH2(head,el,next) { ++(counter); } \ +} while (0) + +#define LL_FOREACH(head,el) \ + LL_FOREACH2(head,el,next) + +#define LL_FOREACH2(head,el,next) \ + for ((el) = (head); el; (el) = (el)->next) + +#define LL_FOREACH_SAFE(head,el,tmp) \ + LL_FOREACH_SAFE2(head,el,tmp,next) + +#define LL_FOREACH_SAFE2(head,el,tmp,next) \ + for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) + +#define LL_SEARCH_SCALAR(head,out,field,val) \ + LL_SEARCH_SCALAR2(head,out,field,val,next) + +#define LL_SEARCH_SCALAR2(head,out,field,val,next) \ +do { \ + LL_FOREACH2(head,out,next) { \ + if ((out)->field == (val)) break; \ + } \ +} while (0) + +#define LL_SEARCH(head,out,elt,cmp) \ + LL_SEARCH2(head,out,elt,cmp,next) + +#define LL_SEARCH2(head,out,elt,cmp,next) \ +do { \ + LL_FOREACH2(head,out,next) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while (0) + +#define LL_REPLACE_ELEM2(head, el, add, next) \ +do { \ + LDECLTYPE(head) _tmp; \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (el))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (add); \ + } \ + } \ +} while (0) + +#define LL_REPLACE_ELEM(head, el, add) \ + LL_REPLACE_ELEM2(head, el, add, next) + +#define LL_PREPEND_ELEM2(head, el, add, next) \ +do { \ + if (el) { \ + LDECLTYPE(head) _tmp; \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (el))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (add); \ + } \ + } \ + } else { \ + LL_APPEND2(head, add, next); \ + } \ +} while (0) \ + +#define LL_PREPEND_ELEM(head, el, add) \ + LL_PREPEND_ELEM2(head, el, add, next) + +#define LL_APPEND_ELEM2(head, el, add, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (el)->next = (add); \ + } else { \ + LL_PREPEND2(head, add, next); \ + } \ +} while (0) \ + +#define LL_APPEND_ELEM(head, el, add) \ + LL_APPEND_ELEM2(head, el, add, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef LL_CONCAT2 +#define LL_CONCAT2(head1,head2,next) \ +do { \ + char *_tmp; \ + if (head1) { \ + _tmp = (char*)(head1); \ + while ((head1)->next) { (head1) = (head1)->next; } \ + (head1)->next = (head2); \ + _RS(head1); \ + } else { \ + (head1)=(head2); \ + } \ +} while (0) + +#undef LL_APPEND2 +#define LL_APPEND2(head,add,next) \ +do { \ + if (head) { \ + (add)->next = head; /* use add->next as a temp variable */ \ + while ((add)->next->next) { (add)->next = (add)->next->next; } \ + (add)->next->next=(add); \ + } else { \ + (head)=(add); \ + } \ + (add)->next=NULL; \ +} while (0) + +#undef LL_DELETE2 +#define LL_DELETE2(head,del,next) \ +do { \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + char *_tmp = (char*)(head); \ + while ((head)->next && ((head)->next != (del))) { \ + (head) = (head)->next; \ + } \ + if ((head)->next) { \ + (head)->next = ((del)->next); \ + } \ + _RS(head); \ + } \ +} while (0) + +#undef LL_REPLACE_ELEM2 +#define LL_REPLACE_ELEM2(head, el, add, next) \ +do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->next = head; \ + while ((add)->next->next && ((add)->next->next != (el))) { \ + (add)->next = (add)->next->next; \ + } \ + if ((add)->next->next) { \ + (add)->next->next = (add); \ + } \ + } \ + (add)->next = (el)->next; \ +} while (0) + +#undef LL_PREPEND_ELEM2 +#define LL_PREPEND_ELEM2(head, el, add, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->next = (head); \ + while ((add)->next->next && ((add)->next->next != (el))) { \ + (add)->next = (add)->next->next; \ + } \ + if ((add)->next->next) { \ + (add)->next->next = (add); \ + } \ + } \ + (add)->next = (el); \ + } else { \ + LL_APPEND2(head, add, next); \ + } \ +} while (0) \ + +#endif /* NO_DECLTYPE */ + +/****************************************************************************** + * doubly linked list macros (non-circular) * + *****************************************************************************/ +#define DL_PREPEND(head,add) \ + DL_PREPEND2(head,add,prev,next) + +#define DL_PREPEND2(head,add,prev,next) \ +do { \ + (add)->next = (head); \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev = (add); \ + } else { \ + (add)->prev = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define DL_APPEND(head,add) \ + DL_APPEND2(head,add,prev,next) + +#define DL_APPEND2(head,add,prev,next) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev->next = (add); \ + (head)->prev = (add); \ + (add)->next = NULL; \ + } else { \ + (head)=(add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ +} while (0) + +#define DL_CONCAT(head1,head2) \ + DL_CONCAT2(head1,head2,prev,next) + +#define DL_CONCAT2(head1,head2,prev,next) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head2) { \ + if (head1) { \ + _CASTASGN(_tmp, (head2)->prev); \ + (head2)->prev = (head1)->prev; \ + (head1)->prev->next = (head2); \ + _CASTASGN((head1)->prev, _tmp); \ + } else { \ + (head1)=(head2); \ + } \ + } \ +} while (0) + +#define DL_DELETE(head,del) \ + DL_DELETE2(head,del,prev,next) + +#define DL_DELETE2(head,del,prev,next) \ +do { \ + assert((del)->prev != NULL); \ + if ((del)->prev == (del)) { \ + (head)=NULL; \ + } else if ((del)==(head)) { \ + (del)->next->prev = (del)->prev; \ + (head) = (del)->next; \ + } else { \ + (del)->prev->next = (del)->next; \ + if ((del)->next) { \ + (del)->next->prev = (del)->prev; \ + } else { \ + (head)->prev = (del)->prev; \ + } \ + } \ +} while (0) + +#define DL_COUNT(head,el,counter) \ + DL_COUNT2(head,el,counter,next) \ + +#define DL_COUNT2(head,el,counter,next) \ +do { \ + (counter) = 0; \ + DL_FOREACH2(head,el,next) { ++(counter); } \ +} while (0) + +#define DL_FOREACH(head,el) \ + DL_FOREACH2(head,el,next) + +#define DL_FOREACH2(head,el,next) \ + for ((el) = (head); el; (el) = (el)->next) + +/* this version is safe for deleting the elements during iteration */ +#define DL_FOREACH_SAFE(head,el,tmp) \ + DL_FOREACH_SAFE2(head,el,tmp,next) + +#define DL_FOREACH_SAFE2(head,el,tmp,next) \ + for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) + +/* these are identical to their singly-linked list counterparts */ +#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR +#define DL_SEARCH LL_SEARCH +#define DL_SEARCH_SCALAR2 LL_SEARCH_SCALAR2 +#define DL_SEARCH2 LL_SEARCH2 + +#define DL_REPLACE_ELEM2(head, el, add, prev, next) \ +do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + (add)->next = (el)->next; \ + if ((el)->next == NULL) { \ + (add)->prev = (add); \ + } else { \ + (add)->prev = (el)->prev; \ + (add)->next->prev = (add); \ + } \ + } else { \ + (add)->next = (el)->next; \ + (add)->prev = (el)->prev; \ + (add)->prev->next = (add); \ + if ((el)->next == NULL) { \ + (head)->prev = (add); \ + } else { \ + (add)->next->prev = (add); \ + } \ + } \ +} while (0) + +#define DL_REPLACE_ELEM(head, el, add) \ + DL_REPLACE_ELEM2(head, el, add, prev, next) + +#define DL_PREPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->prev->next = (add); \ + } \ + } else { \ + DL_APPEND2(head, add, prev, next); \ + } \ +} while (0) \ + +#define DL_PREPEND_ELEM(head, el, add) \ + DL_PREPEND_ELEM2(head, el, add, prev, next) + +#define DL_APPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (add)->prev = (el); \ + (el)->next = (add); \ + if ((add)->next) { \ + (add)->next->prev = (add); \ + } else { \ + (head)->prev = (add); \ + } \ + } else { \ + DL_PREPEND2(head, add, prev, next); \ + } \ +} while (0) \ + +#define DL_APPEND_ELEM(head, el, add) \ + DL_APPEND_ELEM2(head, el, add, prev, next) + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#define CDL_APPEND(head,add) \ + CDL_APPEND2(head,add,prev,next) + +#define CDL_APPEND2(head,add,prev,next) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + (head) = (add); \ + } \ +} while (0) + +#define CDL_PREPEND(head,add) \ + CDL_PREPEND2(head,add,prev,next) + +#define CDL_PREPEND2(head,add,prev,next) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define CDL_DELETE(head,del) \ + CDL_DELETE2(head,del,prev,next) + +#define CDL_DELETE2(head,del,prev,next) \ +do { \ + if (((head)==(del)) && ((head)->next == (head))) { \ + (head) = NULL; \ + } else { \ + (del)->next->prev = (del)->prev; \ + (del)->prev->next = (del)->next; \ + if ((del) == (head)) (head)=(del)->next; \ + } \ +} while (0) + +#define CDL_COUNT(head,el,counter) \ + CDL_COUNT2(head,el,counter,next) \ + +#define CDL_COUNT2(head, el, counter,next) \ +do { \ + (counter) = 0; \ + CDL_FOREACH2(head,el,next) { ++(counter); } \ +} while (0) + +#define CDL_FOREACH(head,el) \ + CDL_FOREACH2(head,el,next) + +#define CDL_FOREACH2(head,el,next) \ + for ((el)=(head);el;(el)=(((el)->next==(head)) ? NULL : (el)->next)) + +#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ + CDL_FOREACH_SAFE2(head,el,tmp1,tmp2,prev,next) + +#define CDL_FOREACH_SAFE2(head,el,tmp1,tmp2,prev,next) \ + for ((el) = (head), (tmp1) = (head) ? (head)->prev : NULL; \ + (el) && ((tmp2) = (el)->next, 1); \ + (el) = ((el) == (tmp1) ? NULL : (tmp2))) + +#define CDL_SEARCH_SCALAR(head,out,field,val) \ + CDL_SEARCH_SCALAR2(head,out,field,val,next) + +#define CDL_SEARCH_SCALAR2(head,out,field,val,next) \ +do { \ + CDL_FOREACH2(head,out,next) { \ + if ((out)->field == (val)) break; \ + } \ +} while (0) + +#define CDL_SEARCH(head,out,elt,cmp) \ + CDL_SEARCH2(head,out,elt,cmp,next) + +#define CDL_SEARCH2(head,out,elt,cmp,next) \ +do { \ + CDL_FOREACH2(head,out,next) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while (0) + +#define CDL_REPLACE_ELEM2(head, el, add, prev, next) \ +do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((el)->next == (el)) { \ + (add)->next = (add); \ + (add)->prev = (add); \ + (head) = (add); \ + } else { \ + (add)->next = (el)->next; \ + (add)->prev = (el)->prev; \ + (add)->next->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ + } \ +} while (0) + +#define CDL_REPLACE_ELEM(head, el, add) \ + CDL_REPLACE_ELEM2(head, el, add, prev, next) + +#define CDL_PREPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ + } else { \ + CDL_APPEND2(head, add, prev, next); \ + } \ +} while (0) + +#define CDL_PREPEND_ELEM(head, el, add) \ + CDL_PREPEND_ELEM2(head, el, add, prev, next) + +#define CDL_APPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (add)->prev = (el); \ + (el)->next = (add); \ + (add)->next->prev = (add); \ + } else { \ + CDL_PREPEND2(head, add, prev, next); \ + } \ +} while (0) + +#define CDL_APPEND_ELEM(head, el, add) \ + CDL_APPEND_ELEM2(head, el, add, prev, next) + +#endif /* UTLIST_H */ diff --git a/crypt/CMakeLists.txt b/crypt/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..764bd9b2537ee3ee6cc2b63523db8e6a3b78c28c --- /dev/null +++ b/crypt/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 2.8) +project (dapcrypt) + +set(CRYPT_SRCS enc.c enc_fnam2.c enc_key.c ) + +include_directories("${dapcore_INCLUDE_DIRS}") +add_definitions ("${dapcore_DEFINITIONS}") +add_library(${PROJECT_NAME} STATIC ${CRYPT_SRCS}) + +set(${PROJECT_NAME}_DEFINITIONS CACHE INTERNAL "${PROJECT_NAME}: Definitions" FORCE) +set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR} CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE) diff --git a/crypt/enc.c b/crypt/enc.c new file mode 100644 index 0000000000000000000000000000000000000000..64ab0b387f0872b9ff14df6616b78f8e04a36c98 --- /dev/null +++ b/crypt/enc.c @@ -0,0 +1,541 @@ +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include <time.h> +#include "enc.h" +#include "enc_key.h" +#include "common.h" +#include <openssl/aes.h> +#include <openssl/evp.h> +#include <openssl/pem.h> +#include <openssl/err.h> +#include <openssl/rand.h> + +#define LOG_TAG "enc" + +#include <arpa/inet.h> + +////////////////////////////////////////// BASE64 PART +static size_t b64_get_encodet_size(size_t in_size); +static size_t b64_get_decodet_size(size_t in_size); +static unsigned char b64_byte_decode(unsigned char b); +static unsigned char b64_byte_encode(unsigned char b); + +static void Base64Decode(const char* in, size_t srcLen, unsigned char* out); +static void Base64Encode(const unsigned char* in, size_t srcLen, char* out); + +static size_t b64_get_encodet_size(size_t in_size) +{ + return (in_size/3)*4 + ((in_size%3==1) ?2: (in_size%3==2) ? 3:0); +} + +static size_t b64_get_decodet_size(size_t in_size) +{ + return (in_size/4)*3 + ((in_size%4==2) ?1: (in_size%5==3) ? 2:0); +} + +static unsigned char b64_byte_decode(unsigned char b) +{ + if (( b == '+' ) || (b =='-') ) + return 62; + if( (b == '/' ) || (b == '_') ) + return 63; + if( b <= '9' ) + return (b - '0' + 52); + if(b <= 'Z') + return (b - 'A'); + return (b - 'a' + 26); +} + +static unsigned char b64_byte_encode(unsigned char b) +{ + b &= 0x3f; + if(b <= 25) + return (b +'A'); + if(b <= 51) + return (b - 26 + 'a'); + if(b <= 61) + return (b - 52 + '0'); + if(b == 62) + return '-'; + return '_'; +} + +static void Base64Decode(const char* source, size_t srcLen, unsigned char* out) +{ + unsigned char b1, b2, b3, b4; + const unsigned char* srcBytes = (unsigned char*)source; + unsigned char* dest = out; + + size_t dec_length = b64_get_decodet_size(srcLen); + unsigned char *buffer = (unsigned char*)malloc(dec_length + 1); + buffer[dec_length] = '\0'; + + // walk through the source, taking 4 bytes at a time + size_t source_index = 0; + size_t dest_index = 0; + size_t remaining = srcLen; + for( ; remaining > 3; remaining -= 4 ) { + b1 = b64_byte_decode(srcBytes[source_index++]); + b2 = b64_byte_decode(srcBytes[source_index++]); + b3 = b64_byte_decode(srcBytes[source_index++]); + b4 = b64_byte_decode(srcBytes[source_index++]); + + dest[dest_index++] = (unsigned char)( ( b1 << 2 ) | ( b2 >> 4 ) ); + dest[dest_index++] = (unsigned char)( ( b2 << 4 ) | ( b3 >> 2 ) ); + dest[dest_index++] = (unsigned char)( ( b3 << 6 ) | b4 ); + } + + // process the remaining bytes + b2 = b3 = 0; + if( remaining > 0 ) { + b1 = b64_byte_decode( srcBytes[source_index++] ); + if( remaining > 1 ) + b2 = b64_byte_decode( srcBytes[source_index++] ); + if( remaining == 3 ) + b3 = b64_byte_decode( srcBytes[source_index++] ); + + dest[dest_index++] = (unsigned char)( ( b1 << 2 ) | ( b2 >> 4 ) ); + if( remaining == 3 ) + dest[dest_index++] = (unsigned char)( ( b2 << 4 ) | ( b3 >> 2 ) ); + } +} + +static void Base64Encode(const unsigned char* source, size_t srcLen, char* out) +{ + unsigned char b1, b2, b3; + unsigned char* dest = (unsigned char*)out; + + // walk through the source, taking 3 bytes at a time + size_t source_index = 0; + size_t dest_index = 0; + size_t remaining = srcLen; + for( ; remaining > 2; remaining -= 3 ) { + b1 = source[ source_index++ ]; + b2 = source[ source_index++ ]; + b3 = source[ source_index++ ]; + dest[dest_index++] = b64_byte_encode( (unsigned char)( b1 >> 2 ) ); + dest[dest_index++] = b64_byte_encode( (unsigned char)( ( b1 << 4 ) | ( b2 >> 4 ) ) ); + dest[dest_index++] = b64_byte_encode( (unsigned char)( ( b2 << 2 ) | ( b3 >> 6 ) ) ); + dest[dest_index++] = b64_byte_encode( (unsigned char)b3 ); + } + + // process the remaining bytes + b2 = 0; + if( remaining > 0 ) { + b1 = source[source_index++]; + if( remaining == 2 ) + b2 = source[source_index++]; + + dest[dest_index++] = b64_byte_encode( (unsigned char)( b1 >> 2 ) ); + dest[dest_index++] = b64_byte_encode( (unsigned char)( ( b1 << 4 ) | ( b2 >> 4 ) ) ); + if( remaining == 2 ) + dest[dest_index++] = b64_byte_encode( (unsigned char)( b2 << 2 ) ); + } +} + +size_t enc_base64_encode(const void * in, size_t in_size, char * out) +{ + size_t ret= b64_get_encodet_size(in_size); + Base64Encode((const unsigned char*) in, in_size, out); + out[ret]='\0'; + return ret; +} + +size_t enc_base64_decode(const char *in, size_t in_size, void *out) +{ + Base64Decode(in, in_size, (unsigned char*) out); + return b64_get_decodet_size(in_size); +} +////////////////////////////////////////////////////// end of BASE64 PART + +////////////////////////////////////////// AES PART +#include <openssl/evp.h> +#include <openssl/err.h> +#include <openssl/rand.h> +#include "enc_key.h" +typedef unsigned char KeySchedule[4*(14+1)][4]; + +static int _crypto_inited = 0; + +typedef struct enc_aes_key{ + KeySchedule ks; + unsigned char salt[AES_BLOCK_SIZE*2]; +} enc_aes_key_t; + +#define ENC_AES_KEY(a) ((enc_aes_key_t *)((a)->internal) ) + +/** + * @brief enc_aes_key_new + * @param key + */ +void enc_aes_key_new(struct enc_key * key) +{ + char str[64]; + int i; + for(i=0;i<sizeof(str);i++) + str[i]=64+rand()%30; + str[sizeof(str)-1]=0; + enc_aes_key_create(key,str); +} + +/** + * @brief enc_aes_key_new + * @param key + */ +void enc_aes_key_create(struct enc_key * key, const char *str_key) +{ + key->data_size = strlen(str_key); + key->data= (unsigned char*) malloc(key->data_size); + memcpy(key->data, str_key, key->data_size); + key->internal = calloc(1,sizeof(enc_aes_key_t) ); + key->enc=enc_aes_encode; + key->dec=enc_aes_decode; + +} + +void enc_aes_key_delete(struct enc_key *key) +{ + (void) key; +} + + +size_t enc_aes_decode(struct enc_key* key, const void * in, size_t in_size,void * out) +{ + unsigned char *iv_dec = (unsigned char*)malloc(sizeof(unsigned char) *AES_BLOCK_SIZE); + memset(iv_dec, 0, sizeof(unsigned char) *AES_BLOCK_SIZE); + + AES_KEY dec_key; + AES_set_decrypt_key(key->data, 256, &dec_key); + AES_cbc_encrypt(in, out, in_size, + &dec_key,iv_dec, AES_DECRYPT); + + free(iv_dec); + + return in_size; + +} + +size_t enc_aes_encode(struct enc_key* key, const void * in, size_t in_size,void * out) +{ + size_t ret = (in_size % AES_BLOCK_SIZE) ? ( in_size+ (AES_BLOCK_SIZE- (in_size%AES_BLOCK_SIZE) ) ) : in_size ; + + unsigned char *iv_enc = (unsigned char*) malloc( sizeof(unsigned char) *AES_BLOCK_SIZE); + memset(iv_enc, 0, sizeof(unsigned char) *AES_BLOCK_SIZE); + + AES_KEY enc_key; + AES_set_encrypt_key(key->data, 256, &enc_key); + AES_cbc_encrypt(in, out, in_size, &enc_key, + iv_enc, AES_ENCRYPT); + + free(iv_enc); + return ret; +} + +////////////////////////////////////////// end of AES PART + +/** + * @brief enc_init + * @return + */ +int enc_init() +{ + if (_crypto_inited) + return 0; + _crypto_inited = 1; + + srand(time(NULL)); + + ERR_load_crypto_strings(); + OpenSSL_add_all_algorithms(); + + return 0; +} + + +/** + * @brief enc_code Encode data with key + * @param key_private Private key + * @param buf Input buffer + * @param buf_size Input buffer size + * @param buf_out Output buffer + * @return bytes actualy written in the output buffer + */ +size_t enc_code(struct enc_key * key,const void * buf,const size_t buf_size, void * buf_out, enc_data_type_t data_type_out) +{ + //log_it(NOTICE,"In enc code"); + if(key->enc){ + void *proc_buf; + switch(data_type_out) + { + case ENC_DATA_TYPE_B64:{ + proc_buf=calloc(1,buf_size*2); + }break; + case ENC_DATA_TYPE_RAW:{ + proc_buf=buf_out; + }break; + } + size_t ret=key->enc(key,buf,buf_size,proc_buf); + if(data_type_out==ENC_DATA_TYPE_B64){ + ret=enc_base64_encode(proc_buf,ret,buf_out); + free(proc_buf); + return ret; + } + return ret; + }else{ + return 0; + } +} + +/** + * @brief enc_decode Decode data with key + * @param key_public Public key + * @param buf Input buffer + * @param buf_size Input buffer size + * @param buf_out Output buffer + * @param buf_out_max Maximum size of output buffer + * @return bytes actualy written in the output buffer + */ +size_t enc_decode(struct enc_key * key,const void * buf, const size_t buf_size, void * buf_out, enc_data_type_t data_type_in) +{ + void *proc_buf; + const void *proc_buf_const; + size_t proc_buf_size; + switch(data_type_in){ + case ENC_DATA_TYPE_B64:{ + proc_buf=calloc(1,buf_size); + proc_buf_size= enc_base64_decode((const char*) buf,buf_size,proc_buf); + proc_buf_const=proc_buf; + }break; + case ENC_DATA_TYPE_RAW:{ + proc_buf_const=buf; + proc_buf_size=buf_size; + }break; + } + + if(key->dec){ + size_t ret=key->dec(key,proc_buf_const,proc_buf_size,buf_out); + if(data_type_in==ENC_DATA_TYPE_B64) + free(proc_buf); + return ret; + }else{ + return 0; + } +} + +/** + * @brief read_key_from_bio + * @param bio + * @return + */ +char* read_key_from_bio(BIO * bio) +{ + size_t length = BIO_pending(bio); + char *buff = (char*)malloc((length + 1)*sizeof(char)); + BIO_read(bio, buff, length); + buff[length] = '\0'; + return buff; +} + + +/** + * @brief bioToString + * @param bio + * @param string + * @details make string from bio + * @return + */ + +int bioToString(BIO *bio, unsigned char **string) +{ + + if( bio == NULL) + { + log_it(ERROR,"bioToString() BIO == NULL!"); + return -1; + } + + size_t bioLength = BIO_pending(bio); + + *string = (unsigned char*)malloc(bioLength + 1); + + if(string == NULL) + { + log_it(ERROR,"bioToString failed.\n"); + return -1; + } + + BIO_read(bio, *string, bioLength); + + (*string)[bioLength] = '\0'; + + BIO_free_all(bio); + + return (int)bioLength; +} + +/** + * @brief enc_rsa_decode + * @param key + * @param in + * @param in_size + * @param out + * @details decode by server local rsa key + * @return + */ +size_t enc_rsa_decode(struct enc_key* key, const void * in, size_t in_size,void * out) +{ + size_t decrypt_len; + + if(in == NULL) + { + log_it(ERROR,"enc_rsa_decode failed (empty message for decode)"); + return 0; + } + + if(key == NULL) + { + log_it(ERROR,"enc_rsa_decode failed (empty key for decode)"); + return 0; + } + + if((decrypt_len = RSA_private_decrypt(in_size, (unsigned char*)in, (unsigned char*)out, + ((rsa_key_t*)key->internal)->server_key, RSA_PKCS1_PADDING)) == -1) + { + log_it(ERROR,"enc_rsa_decode failed (incorrect decode)"); + return 0; + } + + memset(out + decrypt_len, 0, 1); + + //log_it(INFO, "Decode out = %s",out); + + return decrypt_len; +} + + +/** + * @brief enc_rsa_encode + * @param key + * @param in + * @param in_size + * @param out + * @details encode by RSA Public key Client + * @return + */ +size_t enc_rsa_encode(struct enc_key* key, void * in, size_t in_size,void * out) +{ + size_t encrypt_len = 0; + + if(in == NULL || key == NULL) + { + log_it(ERROR,"enc_rsa_encode failed"); + } + + if((encrypt_len = RSA_public_encrypt(in_size, (unsigned char*)in, (unsigned char*)out, + (RSA*)((rsa_key_t*)key->internal)->client_public_key, RSA_PKCS1_PADDING)) == -1) + { + log_it(ERROR,"enc_rsa_encode Error Encrypt"); + return 0; + } + + //log_it(INFO,"Encrypt Len = %d",encrypt_len); + + return encrypt_len; +} + + +/** + * @brief getRsaKeyFromString + * @param str_key + * @param strLen + * @return + */ +void setRsaPubKeyFromString(char *str_key, size_t strLen, struct enc_key * key) +{ + if(str_key == NULL) + { + log_it(ERROR,"getRsaKeyFromString failed"); + return; + } + + BIO *bio = BIO_new(BIO_s_mem()); + BIO_write(bio, str_key,strLen); + + PEM_read_bio_RSAPublicKey( bio, (void*)&key->internal, NULL, NULL); + + BIO_free_all(bio); + + key->enc = (void*) enc_rsa_encode; + key->dec = (void*) enc_rsa_decode; + + if ( key == NULL) + { + log_it(ERROR,"getRsaKeyFromString failed"); + return; + } + +} + + +/** + * @brief getStringPrivateKeyFromRsa + * @param key + * @param out + * @details get string public key from RSA* key ( Allocated memory for ptr ) + * @return + */ +size_t getStringPrivateKeyFromRsa(RSA *key, char **out) +{ + BIO *bio = BIO_new(BIO_s_mem()); + + if(key == NULL) + { + log_it(ERROR,"getStringPubKeyFromRsa failed"); + return 0; + } + + PEM_write_bio_RSAPrivateKey(bio,key,NULL,NULL,0,NULL,NULL); + + size_t key_len = BIO_pending(bio); + *out = malloc(key_len + 1); + + BIO_read(bio, *out, key_len); + + BIO_free_all(bio); + + return key_len; +} + + +/** + * @brief getStringPubKeyFromRsa + * @param key + * @param out + * @details get string public key from RSA* key ( Allocated memory for ptr ) + * @return + */ +size_t getStringPubKeyFromRsa(RSA *key, char **out) +{ + BIO *bio = BIO_new(BIO_s_mem()); + + if(key == NULL) + { + log_it(ERROR,"getStringPubKeyFromRsa failed"); + return 0; + } + + PEM_write_bio_RSAPublicKey(bio, key); + + size_t key_len = BIO_pending(bio); + *out = malloc(key_len + 1); + + BIO_read(bio, *out, key_len); + //out[key_len] = '\0'; + + BIO_free_all(bio); + + return key_len; +} + + diff --git a/crypt/enc.h b/crypt/enc.h new file mode 100644 index 0000000000000000000000000000000000000000..b8099a567a050a326cecca3d395fac44a5f75405 --- /dev/null +++ b/crypt/enc.h @@ -0,0 +1,54 @@ +#ifndef _ENC_H_ +#define _ENC_H_ +#include <stddef.h> +#include <openssl/aes.h> +#include <openssl/evp.h> +#include <openssl/pem.h> +#include <openssl/err.h> +#include <openssl/rand.h> + +#define SA_ENC_TYPE_1 0x01 +#define RSA_KEY_LENGTH 4096 +#define PUB_EXP 3 + +struct enc_key; + +typedef enum enc_data_type{ENC_DATA_TYPE_RAW, ENC_DATA_TYPE_B64, ENC_KEY_TYPE_RSA} enc_data_type_t; + +typedef struct rsa_session_key { + RSA* server_key; + RSA* client_public_key; + time_t last_time_use_key; +} rsa_key_t; + +extern int enc_init(); + +/// BASE64 +extern size_t enc_base64_decode(const char * in, size_t in_size,void * out); +extern size_t enc_base64_encode(const void * in, size_t in_size,char * out); +/// + +/// AES +#include "common.h" +struct enc_key; + +extern size_t enc_rsa_decode(struct enc_key* key, const void * in, size_t in_size,void * out); +extern size_t enc_rsa_encode(struct enc_key* key, void * in, size_t in_size,void * out); + +extern void setRsaPubKeyFromString(char *str_key, size_t strLen, struct enc_key * key); +extern size_t getStringPubKeyFromRsa(RSA *key, char **out); +extern size_t getStringPrivateKeyFromRsa(RSA *key, char **out); + + +extern void enc_aes_key_new(struct enc_key * key); +extern void enc_aes_key_create(struct enc_key * key, const char *password_string); +extern void enc_aes_key_delete(struct enc_key *key); +extern size_t enc_aes_decode(struct enc_key* key, const void * in, size_t in_size,void * out); +extern size_t enc_aes_encode(struct enc_key* key, const void * in, size_t in_size,void * out); + + +size_t enc_code(struct enc_key * key, const void * buf, const size_t buf_size, void * buf_out, enc_data_type_t data_type_out); +size_t enc_decode(struct enc_key * key, const void * buf, const size_t buf_size, void * buf_out, enc_data_type_t data_type_in); + + +#endif diff --git a/crypt/enc_fnam2.c b/crypt/enc_fnam2.c new file mode 100644 index 0000000000000000000000000000000000000000..28d811fdb1ce74c6466496c85dd7996b4005da06 --- /dev/null +++ b/crypt/enc_fnam2.c @@ -0,0 +1,191 @@ +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include "enc_key.h" +#include "enc_fnam2.h" + +void fnam2_crypt(int *key, int key_size, unsigned long *num_block, unsigned long b1,unsigned long b2,unsigned long b3,unsigned long b4, void * out ); +void fnam2_decrypt(int *key, int key_size, unsigned long *num_block, unsigned long b1,unsigned long b2,unsigned long b3,unsigned long b4, void * out ); + +/** + * @brief enc_fnam2_key_new + * @param key + */ +void enc_fnam2_key_new(struct enc_key * key) +{ + size_t i; + for(i=0;i<key->data_size;i++) + key->data[i] = rand()%255; +} + + +/** + * @brief enc_fnam2_decode + * @param key + * @param key_size + * @param in + * @param in_size + * @param out + * @return + */ +size_t enc_fnam2_decode(struct enc_key * key, const void * in, size_t in_size,void * out) +{ + unsigned long num_block=0; + int key_pos=0; + const size_t block_size=16; + const unsigned char * in_ul=(const unsigned char*) in; + + size_t pos; + + for (pos=0;pos<= in_size-block_size; pos+=block_size){ + fnam2_decrypt( (int *) (key->data+key_pos), block_size,&num_block, *((int*)(in_ul+pos)) , + *((int*)(in_ul+pos+4)), *((int*)(in_ul+pos+8)),*((int*)(in_ul+pos+12)),out+pos); + /*key_pos+=block_size; + if(key_pos+block_size>=key->data_size) + key_pos=0;*/ + } + + return pos; +} + +/** + * @brief enc_fnam2_encode + * @param key + * @param key_size + * @param in + * @param in_size + * @param out + * @return + */ +size_t enc_fnam2_encode(struct enc_key * key,const void * in, size_t in_size,void * out) +{ + unsigned long num_block=0; + int key_pos=0; + const size_t block_size=16; + const unsigned char * in_ul=(const unsigned char*) in; + + size_t pos; + + + for (pos=0;pos<= in_size-block_size; pos+=block_size){ + fnam2_crypt( (int *) (key->data+key_pos), block_size,&num_block, *((int*)(in_ul+pos)) , + *((int*)(in_ul+pos+4)), *((int*)(in_ul+pos+8)),*((int*)(in_ul+pos+12)),out+pos); + /* key_pos+=block_size; + if(key_pos+block_size>=key->data_size) + key_pos=0;*/ + } + + if(pos<in_size){ + char * buf = (char*) calloc(1,block_size); + memcpy(buf,in_ul+pos, in_size-pos); + fnam2_crypt(( int *)(key->data+key_pos), block_size,&num_block, *((int*)(buf)) , + *((int*)(buf+4)), *((int*)(buf+8)),*((int*)(buf+12)),out+pos); + pos+=block_size; + } + return pos; +} + +void fnam2_crypt(int *key, int key_size, unsigned long *num_block, unsigned long b1,unsigned long b2,unsigned long b3,unsigned long b4, void * out ) +{ + int subkey,i,ip,im; + unsigned long Num=*num_block; + int r; + + for(r=0;r<key_size*4;r++) { + //Selecting the part of key for a concrete stage + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + + //Generating the subkey on the basis of nmber part of a key, + //number of the block in a file and number of a round + subkey=key[i]*r+(key[im]*Num+key[ip]); + + //F - function + b1+=(((b2>>16)^((b2<<25)+subkey))+(subkey*(~(b2<<7)))); + b1=~b1; + r++; + + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b2+=(((b3>>16)^((b3<<25)+subkey))+(subkey*(~(b3<<7)))); + b2=~b2; + r++; + + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b3+=(((b4>>16)^((b4<<25)+subkey))+(subkey*(~(b4<<7)))); + b3=~b3; + r++; + + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b4+=(((b1>>16)^((b1<<25)+subkey))+(subkey*(~(b1<<7)))); + b4=~b4; + } + Num++; + *num_block=Num; + ((unsigned char*)out)[0]=b1; + ((unsigned char*)out)[1]=b2; + ((unsigned char*)out)[2]=b3; + ((unsigned char*)out)[3]=b4; +} + +void fnam2_decrypt(int *key, int key_size, unsigned long *num_block, unsigned long b1,unsigned long b2,unsigned long b3,unsigned long b4, void * out ) +{ + int subkey,i,ip,im; + unsigned long Num=*num_block; + int r; + for(r=key_size*sizeof(int)-1;r>=0;r--){ + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b4=~b4; + b4-=(((b1>>16)^((b1<<25)+subkey))+(subkey*(~(b1<<7)))); + r--; + + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b3=~b3; + b3-=(((b4>>16)^((b4<<25)+subkey))+(subkey*(~(b4<<7)))); + r--; + + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b2=~b2; + b2-=(((b3>>16)^((b3<<25)+subkey))+(subkey*(~(b3<<7)))); + r--; + + i=r%key_size; + if(i==key_size) {ip=1;im=key_size-1;} + if(i==1) {ip=2;im=key_size;} + else {ip=i+1;im=i-1;} + subkey=key[i]*r+(key[im]*Num+key[ip]); + b1=~b1; + b1-=(((b2>>16)^((b2<<25)+subkey))+(subkey*(~(b2<<7)))); + } + Num++; + *num_block=Num; + ((unsigned char*)out)[0]=b1; + ((unsigned char*)out)[1]=b2; + ((unsigned char*)out)[2]=b3; + ((unsigned char*)out)[3]=b4; +} diff --git a/crypt/enc_fnam2.h b/crypt/enc_fnam2.h new file mode 100644 index 0000000000000000000000000000000000000000..3762d1e4988c8306a52efa9388ddc5517df8351a --- /dev/null +++ b/crypt/enc_fnam2.h @@ -0,0 +1,12 @@ +#ifndef _ENC_FNAM2_H_ +#define _ENC_FNAM2_H_ +#include <stddef.h> + +struct enc_key; + +extern void enc_fnam2_key_new(struct enc_key * key); + +extern size_t enc_fnam2_decode(struct enc_key * key, const void * in, size_t in_size,void * out); +extern size_t enc_fnam2_encode(struct enc_key * key,const void * in, size_t in_size,void * out); + +#endif diff --git a/crypt/enc_key.c b/crypt/enc_key.c new file mode 100644 index 0000000000000000000000000000000000000000..4a32c9148ab952ea3e5a9072ff312b11e3ea5a85 --- /dev/null +++ b/crypt/enc_key.c @@ -0,0 +1,107 @@ +#include <stdlib.h> +#include <string.h> + +#include "enc_key.h" +#include "enc_fnam2.h" + +#define LOG_TAG "enc_key" + + +/** + * @brief enc_key_session_pair_create + * @param client_pub_key + * @param key_len + * @return + */ +rsa_key_t* enc_key_session_pair_create(const char* client_pub_key, u_int16_t key_len) +{ + rsa_key_t* key_session_pair = (rsa_key_t*)calloc(1, sizeof(rsa_key_t)); + + BIO *bio = BIO_new(BIO_s_mem()); + BIO_write(bio, client_pub_key,key_len); + PEM_read_bio_RSAPublicKey(bio, &key_session_pair->client_public_key, NULL, NULL); + BIO_free_all(bio); + + if ( key_session_pair->client_public_key == NULL) + { + free(key_session_pair); + log_it(WARNING, "key session pair not create"); + return NULL; + } + + key_session_pair->server_key = RSA_generate_key(RSA_KEY_LENGTH, PUB_EXP, NULL, NULL); + + if ( key_session_pair->server_key == NULL ) + log_it(ERROR, "Error generate rsa key"); + + return key_session_pair; +} + + + +/** + * @brief enc_key_generate + * @param v_type + * @param key_session_pair + * @return + */ +enc_key_t* enc_key_generate(enc_data_type_t v_type, rsa_key_t* key_session_pair) +{ + switch (v_type) { + case ENC_KEY_TYPE_RSA: { + if(key_session_pair == NULL) + { + log_it(WARNING, "Error generate enc key, key session pair is NULL"); + return NULL; + } + enc_key_t *key = (enc_key_t*)malloc(sizeof(enc_key_t)); + key->enc = (enc_callback_t) enc_rsa_encode; + key->dec = enc_rsa_decode; + key->internal = (void*) key_session_pair; + key->type = ENC_KEY_TYPE_RSA; + return key; + } + break; + default: + break; + } + return NULL; +} + +/** + * @brief enc_key_create + * @param key_input_b64 + * @param v_type + * @return + */ +enc_key_t *enc_key_create(const char * key_input,enc_key_type_t v_type) +{ + enc_key_t * ret= (enc_key_t *) calloc(1,sizeof(enc_key_t) ); + size_t input_size=strlen(key_input); + switch(v_type){ + case ENC_KEY_TYPE_AES:{ + enc_aes_key_create(ret,key_input); + }break; + case ENC_KEY_TYPE_FNAM2:{ + ret->data = (unsigned char*) calloc(1,input_size*2); + ret->data_size= enc_base64_decode(key_input,input_size,ret->data); + }break; + } + ret->type=v_type; + return ret; +} + +/** + * @brief enc_key_delete + * @param key + */ +void enc_key_delete(enc_key_t * key) +{ + free(key->data); + if(key->type == ENC_KEY_TYPE_AES) + enc_aes_key_delete(key); + if(key->internal) + free(key->internal); + free(key); +} + diff --git a/crypt/enc_key.h b/crypt/enc_key.h new file mode 100644 index 0000000000000000000000000000000000000000..b3445736708bba42be9c8b97199d8d3ab4122101 --- /dev/null +++ b/crypt/enc_key.h @@ -0,0 +1,30 @@ +#ifndef _ENC_KEY_H_ +#define _ENC_KEY_H_ + +#include "enc.h" + +#include <stddef.h> +#include "enc_key.h" +typedef enum enc_key_type{ENC_KEY_TYPE_FNAM2, ENC_KEY_TYPE_AES,ENC_KEY_RSA_SESSION} enc_key_type_t; + +struct enc_key; +typedef size_t (*enc_callback_t)(struct enc_key *, const void * , const size_t ,void *); + +typedef struct enc_key{ + unsigned char * data; + size_t data_size; + enc_key_type_t type; + + enc_callback_t enc; + enc_callback_t dec; + + void * internal; +} enc_key_t; + +extern enc_key_t *enc_key_new(size_t key_size,enc_key_type_t key_type); +extern enc_key_t *enc_key_generate(enc_data_type_t v_type, rsa_key_t* key_session_pair); +extern enc_key_t *enc_key_create(const char * key_input,enc_key_type_t v_type); +extern void enc_key_delete(enc_key_t * key); +extern rsa_key_t* enc_key_session_pair_create(const char* client_pub_key, u_int16_t key_len); + +#endif diff --git a/crypt/test.c b/crypt/test.c new file mode 100644 index 0000000000000000000000000000000000000000..072c72bb3799a145a560ae4d0f8b7ba4944de7b3 --- /dev/null +++ b/crypt/test.c @@ -0,0 +1,92 @@ +#include <stdlib.h> +#include <stdio.h> +#include <stdbool.h> +#include "enc_key.h" +#include "enc_base64.h" +#include "enc_rsa.h" +#include "enc_sha.h" +#include "enc.h" +#include "Aes.h" + +#define LOG_TAG "main" + +char * buf_src; +size_t test_size=38915; + +//char buf_src[]="Test string as long as it could be - much more than the one cypher block!!!"; +//const size_t test_size=sizeof(buf_src); + +bool test_enc_func( enc_key_t *key_enc, enc_key_t* key_dec,enc_data_type_t dt) +{ + bool noDiff=true; + char *buf_crypto , * buf_out; + size_t buf_crypto_size; + size_t buf_out_size; + size_t i; + + buf_crypto=(char*) calloc(1,test_size*4); + + buf_out = (char*) calloc(1,test_size*2); + + buf_crypto_size=enc_code(key_enc,buf_src,test_size,buf_crypto,dt); + buf_out_size=enc_decode(key_dec,buf_crypto,buf_crypto_size,buf_out,dt); + for(i=0; i<test_size;i++){ + if(buf_out[i]!=buf_src[i]){ + noDiff=false; + break; + } + } + + free(buf_out); + free(buf_crypto); + + if(noDiff){ + printf (" passed\n"); + return true; + }else{ + printf (" ERROR: Output '%s'\n", buf_out ); + exit(1); + } + return false; +} + +int main (int argc, const char *argv[]) +{ + (void) argc; + (void) argv; + enc_key_t * key, * key_pub; + printf("SafeCrypto test\n"); + + enc_init(); + printf("-- Init buffers (test data size %lu )\n",test_size); + + printf( "-- Aes_Test %s\n", (Aes_Test()==0)?"passed":"was with ERROR" ); + + buf_src=(char*) calloc(1,test_size); + + size_t i; + for(i=0;i<test_size; i++) + buf_src[i]=rand()%255; + + /*printf("-- Test FNAM2... "); + key=enc_key_new(512/8,ENC_KEY_TYPE_FNAM2); + test_enc_func( key,key, ENC_DATA_TYPE_RAW); + enc_key_delete(key); + + exit(0);*/ + + /* printf("-- Test RSA... "); + key=enc_key_new(2048,ENC_KEY_TYPE_RSA_PVT); + key_pub=enc_rsa_pvt_to_pub(key); + test_enc_func(key_pub,key, ENC_DATA_TYPE_B64); + enc_key_delete(key); + enc_key_delete(key_pub);*/ + + printf("-- Test AES... "); + key=enc_key_create("TestPasswW0rdStringAsLongfgsdjgupsidfujp0sijughwrpighjsgjskigjsigh",ENC_KEY_TYPE_AES); + test_enc_func( key,key, ENC_DATA_TYPE_B64); + enc_key_delete(key); + + return 0; +} + diff --git a/http/dap_http_client.c b/http/dap_http_client.c new file mode 100644 index 0000000000000000000000000000000000000000..c688b493d2f1f86e80de196a7209e03727314029 --- /dev/null +++ b/http/dap_http_client.c @@ -0,0 +1,396 @@ +#include <stdio.h> +#include <ctype.h> +#include <libgen.h> +#include "common.h" +#include "dap_client.h" +#include "dap_server.h" +#include "dap_http.h" +#include "dap_http_client.h" + +#define LOG_TAG "http_client" + +#define BUF_SIZE 2048 + +void dap_http_client_out_header_generate(dap_http_client_t *cl_ht); + +/** + * @brief dap_http_client_init Init HTTP client module + * @return Zero if ok others if not + */ +int dap_http_client_init() +{ + log_it(NOTICE,"Initialized HTTP client module"); + return 0; +} + +/** + * @brief dap_http_client_deinit Deinit HTTP client module + */ +void dap_http_client_deinit() +{ + log_it(INFO,"HTTP client module deinit"); +} + +/** + * @brief dap_http_client_new Creates HTTP client's internal structure + * @param cl HTTP Client instance + * @param arg Additional argument (usualy not used) + */ +void dap_http_client_new(dap_client_t * cl,void * arg) +{ + (void) arg; + cl->internal=calloc(1,sizeof(dap_http_client_t)); + dap_http_client_t * cl_ht=DAP_HTTP_CLIENT(cl); + cl_ht->client=cl; + cl_ht->http= DAP_HTTP(cl->server); + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_START; + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_NONE; + +} + +/** + * @brief dap_http_client_delete + * @param cl HTTP Client instance + * @param arg Additional argument (usualy not used) + */ +void dap_http_client_delete(dap_client_t * cl,void * arg) +{ + dap_http_client_t * cl_ht=DAP_HTTP_CLIENT(cl); + while(cl_ht->in_headers) + dap_http_header_remove(&cl_ht->in_headers,cl_ht->in_headers); + + while(cl_ht->out_headers) + dap_http_header_remove(&cl_ht->out_headers,cl_ht->out_headers); + + if(cl_ht->proc) + if(cl_ht->proc->delete_callback) + cl_ht->proc->delete_callback(cl_ht,NULL); + + if(cl_ht->internal) + free(cl_ht->internal); + (void) arg; +} + + +/** + * @brief detect_end_of_line Detect end of line, return position of its end (with \n symbols) + * @param buf Input buffer + * @param max_size Maximum size of this buffer minus 1 (for terminating zero) + * @return position of the end of line + */ +int detect_end_of_line(const char * buf, size_t max_size) +{ + size_t i; + for(i=0;i<max_size; i++){ + if(buf[i]=='\n'){ + return i; + } + } + return -1; +} + +bool dap_http_request_line_parse(dap_http_client_t * cl_ht, char * buf, size_t buf_length) +{ + size_t pos; + size_t pos_kw_begin=0; + enum parse_state{PS_START=0, PS_ACTION=1, PS_URL=2, PS_TYPE=3, PS_VER_MAJOR=4, PS_VER_MINOR=5} p_st=PS_ACTION; + for(pos=0;pos<buf_length; pos++){ + if(buf[pos]=='\n'){ + break; + }else if(( buf[pos]==' ')||( buf[pos]=='\t')){ + switch(p_st){ + case PS_ACTION:{ + size_t c_size= ((pos-pos_kw_begin+1)>sizeof(cl_ht->action) )? + (sizeof(cl_ht->action)-1) : + (pos-pos_kw_begin) ; + memcpy(cl_ht->action, buf+pos_kw_begin,c_size ); + cl_ht->action[c_size]='\0'; + //log_it(DEBUG, "Input: action '%s' pos=%lu pos_kw_begin=%lu", cl_ht->action,pos,pos_kw_begin); + p_st=PS_URL; + pos_kw_begin=pos+1; + }break; + case PS_URL:{ + size_t c_size= ((pos-pos_kw_begin+1)>sizeof(cl_ht->action) )? + (sizeof(cl_ht->url_path)-1) : + (pos-pos_kw_begin) ; + memcpy(cl_ht->url_path, buf+pos_kw_begin,c_size ); + cl_ht->url_path[c_size]='\0'; + //log_it(DEBUG, "Input: url '%s' pos=%lu pos_kw_begin=%lu", cl_ht->url_path,pos,pos_kw_begin); + p_st=PS_TYPE; + pos_kw_begin=pos+1; + }break; + } + }else{ + switch(p_st){ + case PS_START:{ + p_st=PS_ACTION; + pos_kw_begin=pos; + };break; + } + } + } + return cl_ht->url_path[0]&&cl_ht->action[0]; +} + +/** + * @brief dap_http_client_read + * @param cl HTTP Client instance + * @param arg Additional argument (usualy not used) + */ +void dap_http_client_read(dap_client_t * cl,void * arg) +{ + + (void) arg; + dap_http_client_t * cl_ht=DAP_HTTP_CLIENT(cl); + char buf_line[4096]; +// log_it(DEBUG,"HTTP client in state read %d taked bytes in input %lu",cl_ht->state_read,cl->buf_in_size); +cnt:switch(cl_ht->state_read){ + case DAP_HTTP_CLIENT_STATE_START:{ // Beginning of the session. We try to detect + int eol = detect_end_of_line(cl->buf_in,cl->buf_in_size); + if(eol<0){ + return; + }else if((eol+3)<sizeof(buf_line) ){ + memcpy(buf_line,cl->buf_in,eol+1); + dap_client_shrink_buf_in(cl,eol+1); + buf_line[eol+2]='\0'; + if( dap_http_request_line_parse(cl_ht,buf_line,eol+1) ){ + char * query_string; + + if( query_string = strchr(cl_ht->url_path,'?')) + { + size_t len_after=strlen(query_string+1); + if(len_after){ + if(len_after>(sizeof(cl_ht->in_query_string)-1)) + len_after=sizeof(cl_ht->in_query_string)-1; + + if(strstr(query_string, "HTTP/1.1")) + strncpy(cl_ht->in_query_string,query_string+1,len_after - 11); + else + strncpy(cl_ht->in_query_string,query_string+1,len_after); + + if(cl_ht->in_query_string[strlen(cl_ht->in_query_string) - 1] == ' ') + cl_ht->in_query_string[strlen(cl_ht->in_query_string) - 1] = '\0'; + query_string[0]='\0'; + } + } + //log_it(NOTICE, "Input: %s request for %s document (query string '%s')",cl_ht->action,cl_ht->url_path, cl_ht->in_query_string? cl_ht->in_query_string: ""); + char * d_name, *b_name; + char * url_cpy1, *url_cpy2; + url_cpy1=strdup(cl_ht->url_path); + url_cpy2=strdup(cl_ht->url_path); + + d_name=dirname(url_cpy1); + b_name=basename(url_cpy2); + + strncpy(cl_ht->url_path,b_name,sizeof(cl_ht->url_path)); + + dap_http_url_proc_t * url_proc; + + HASH_FIND_STR(cl_ht->http->url_proc, d_name , url_proc); // Find URL processor + + cl_ht->proc=url_proc; + if(url_proc) { + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_HEADERS; + } + else{ + log_it(WARNING, "Input: unprocessed URL request %s is rejected", d_name); + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_NONE; + dap_client_ready_to_read(cl_ht->client,true); + dap_client_ready_to_write(cl_ht->client,true); + cl_ht->reply_status_code=505; + strcpy(cl_ht->reply_reason_phrase,"Error"); + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_START; + cl->buf_in_size=0; + free(url_cpy1); + free(url_cpy2); + break; + } + //free(d_name); + //free(b_name); + free(url_cpy1); + free(url_cpy2); + }else{ + log_it(WARNING, "Input: Wrong request line '%s'",buf_line); + cl->buf_in_size=0; + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_NONE; + dap_client_ready_to_read(cl_ht->client,false); + dap_client_ready_to_write(cl_ht->client,true); + cl_ht->reply_status_code=505; + strcpy(cl_ht->reply_reason_phrase,"Error"); + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_START; + } + }else{ + log_it(WARNING,"Too big line in request, more than %llu symbols - thats very strange",sizeof(buf_line)-3); + cl->buf_in_size=0; + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_NONE; + dap_client_ready_to_read(cl_ht->client,false); + dap_client_ready_to_write(cl_ht->client,true); + cl_ht->reply_status_code=505; + strcpy(cl_ht->reply_reason_phrase,"Error"); + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_START; + } + }break; + case DAP_HTTP_CLIENT_STATE_HEADERS:{ // Parse input headers + int eol = detect_end_of_line(cl->buf_in,cl->buf_in_size); + if(eol<0) + return; + else{ + int parse_ret; + memcpy(buf_line,cl->buf_in,eol+1); + buf_line[eol-1]='\0'; + + parse_ret=dap_http_header_parse(cl_ht,buf_line); + // log_it(WARNING, "++ ALL HEADERS TO PARSE [%s]", buf_line); + if(parse_ret<0) + log_it(WARNING,"Input: not a valid header '%s'",buf_line); + else if(parse_ret==1){ + log_it(INFO,"Input: HTTP headers are over"); + if(cl_ht->proc->access_callback){ + bool isOk=true; + cl_ht->proc->access_callback(cl_ht,&isOk); + if(!isOk){ + log_it(NOTICE,"Access restricted"); + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_NONE; + dap_client_ready_to_read(cl_ht->client,false); + dap_client_ready_to_write(cl_ht->client,true); + cl_ht->reply_status_code=505; + strcpy(cl_ht->reply_reason_phrase,"Error"); + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_START; + } + } + + if(cl_ht->proc->headers_read_callback) + cl_ht->proc->headers_read_callback(cl_ht,NULL); + // If no headers callback we go to the DATA processing + if(cl_ht->in_content_length ){ + cl_ht->state_read=DAP_HTTP_CLIENT_STATE_DATA; + }else{ + //log_it + //cl_ht->state_read=DAP_HTTP_CLIENT_STATE_NONE; + //cl_ht->client->ready_to_read=t; + //cl_ht->client->signal_close=!cl_ht->keep_alive; + } + + } + dap_client_shrink_buf_in(cl,eol+1); + } + }break; + case DAP_HTTP_CLIENT_STATE_DATA:{//Read the data + // log_it(WARNING, "DBG_#002 [%s] [%s]", cl_ht->in_query_string, cl_ht->url_path); + int read_bytes=0; + if(cl_ht->proc->data_read_callback){ + //while(cl_ht->client->buf_in_size){ + cl_ht->proc->data_read_callback(cl_ht,&read_bytes); + dap_client_shrink_buf_in(cl,read_bytes); + //} + }else + cl->buf_in_size=0; + } break; + case DAP_HTTP_CLIENT_STATE_NONE:{ + cl->buf_in_size=0; + }break; + + } + if(cl->buf_in_size>0){ + //log_it(DEBUG,"Continue to process to parse input"); + goto cnt; + } +} + +/** + * @brief dap_http_client_write Process write event + * @param cl HTTP Client instance + * @param arg Additional argument (usualy not used) + */ +void dap_http_client_write(struct dap_client * cl,void * arg) +{ + + (void) arg; + dap_http_client_t * cl_ht=DAP_HTTP_CLIENT(cl); + // log_it(DEBUG,"HTTP client write callback in state %d",cl_ht->state_write); + switch(cl_ht->state_write){ + case DAP_HTTP_CLIENT_STATE_NONE: return; + case DAP_HTTP_CLIENT_STATE_START:{ + if(cl_ht->proc) + if(cl_ht->proc->headers_write_callback) + cl_ht->proc->headers_write_callback(cl_ht,NULL); + log_it(DEBUG,"Output: HTTP response with %u status code",cl_ht->reply_status_code); + dap_client_write_f(cl,"HTTP/1.1 %u %s\r\n",cl_ht->reply_status_code, cl_ht->reply_reason_phrase[0]?cl_ht->reply_reason_phrase:"UNDEFINED"); + dap_http_client_out_header_generate(cl_ht); + + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_HEADERS; + }break; + case DAP_HTTP_CLIENT_STATE_HEADERS:{ + dap_http_header_t * hdr=cl_ht->out_headers; + if(hdr==NULL){ + log_it(DEBUG, "Output: headers are over (reply status code %u)",cl_ht->reply_status_code); + dap_client_write_f(cl,"\r\n"); + if(cl_ht->out_content_length || cl_ht->out_content_ready){ + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_DATA; + }else{ + log_it(DEBUG,"Nothing to output"); + cl_ht->state_write=DAP_HTTP_CLIENT_STATE_NONE; + dap_client_ready_to_write(cl,false); + + cl->signal_close=true; + } + dap_client_ready_to_read(cl,true); + }else{ + //log_it(DEBUG,"Output: header %s: %s",hdr->name,hdr->value); + dap_client_write_f(cl,"%s: %s\n",hdr->name,hdr->value); + dap_http_header_remove(&cl_ht->out_headers, hdr); + } + }break; + case DAP_HTTP_CLIENT_STATE_DATA:{ + if(cl_ht->proc) + if(cl_ht->proc->data_write_callback) + cl_ht->proc->data_write_callback(cl_ht,NULL); + }break; + } +} + +/** + * @brief dap_http_client_out_header_generate Produce general headers + * @param cl_ht HTTP client instance + */ +void dap_http_client_out_header_generate(dap_http_client_t *cl_ht) +{ + char buf[1024]; + time_t current_time=time(NULL); + time_to_rfc822(buf,sizeof(buf),current_time); + dap_http_header_add(&cl_ht->out_headers,"Date",buf); + if(cl_ht->reply_status_code==200){ + if(cl_ht->out_last_modified){ + time_to_rfc822(buf,sizeof(buf),cl_ht->out_last_modified); + dap_http_header_add(&cl_ht->out_headers,"Last-Modified",buf); + } + if(cl_ht->out_content_type[0]){ + dap_http_header_add(&cl_ht->out_headers,"Content-Type",cl_ht->out_content_type); + log_it(DEBUG,"output: Content-Type = '%s'",cl_ht->out_content_type); + } + if(cl_ht->out_content_length){ + snprintf(buf,sizeof(buf),"%llu",(unsigned long long)cl_ht->out_content_length); + dap_http_header_add(&cl_ht->out_headers,"Content-Length",buf); + log_it(DEBUG,"output: Content-Length = %llu",cl_ht->out_content_length); + } + } + if(cl_ht->out_connection_close || (!cl_ht->keep_alive) ) + dap_http_header_add(&cl_ht->out_headers,"Connection","Close"); + + dap_http_header_add(&cl_ht->out_headers,"Server-Name", cl_ht->http->server_name); + log_it(DEBUG,"Output: Headers generated"); +} + +/** + * @brief dap_http_client_error Process errors + * @param cl HTTP Client instance + * @param arg Additional argument (usualy not used) + */ +void dap_http_client_error(struct dap_client * cl,void * arg) +{ + (void) arg; + dap_http_client_t * cl_ht=DAP_HTTP_CLIENT(cl); + if(cl_ht->proc) + if(cl_ht->proc->error_callback) + cl_ht->proc->error_callback(cl_ht,arg); +} diff --git a/http/dap_http_client.h b/http/dap_http_client.h new file mode 100644 index 0000000000000000000000000000000000000000..7e02a221406f83d35935733f4179e2b57705e4b8 --- /dev/null +++ b/http/dap_http_client.h @@ -0,0 +1,72 @@ +#ifndef _DAP_HTTP_CLIENT_H_ +#define _DAP_HTTP_CLIENT_H_ + +#include <stdint.h> +#include <time.h> +#include <stdbool.h> +struct dap_client; +struct dap_http_client; +struct dap_http; +struct dap_http_url_proc; + + +typedef enum dap_http_client_state{ + DAP_HTTP_CLIENT_STATE_NONE=0, + DAP_HTTP_CLIENT_STATE_START=1, + DAP_HTTP_CLIENT_STATE_HEADERS=2, + DAP_HTTP_CLIENT_STATE_DATA=3 +} dap_http_client_state_t; + +typedef void (*dap_http_client_callback_t) (struct dap_http_client *,void * arg); // Callback for specific client operations + +typedef struct dap_http_client +{ + char action[128]; // Type of HTTP action (GET, PUT and etc) + char url_path[2048]; // URL path of requested document + uint32_t http_version_major; // Major version of HTTP protocol + uint32_t http_version_minor; // Minor version of HTTP protocol + bool keep_alive; + + dap_http_client_state_t state_read; + dap_http_client_state_t state_write; + + struct dap_http_header * in_headers; + uint64_t in_content_length; + char in_content_type[256]; + char in_query_string[1024]; + char in_cookie[1024]; + + struct dap_http_header * out_headers; + uint64_t out_content_length; + bool out_content_ready; + char out_content_type[256]; + time_t out_last_modified; + bool out_connection_close; + + + struct dap_client * client; + struct dap_http * http; + + uint32_t reply_status_code; + char reply_reason_phrase[256]; + + struct dap_http_url_proc * proc; + + void * internal; + +} dap_http_client_t; +#define DAP_HTTP_CLIENT(a) ((dap_http_client_t *) (a)->internal ) + +extern int dap_http_client_init(); +extern void dap_http_client_deinit(); + + +extern void dap_http_client_new(struct dap_client * cl,void * arg); // Creates HTTP client's internal structure +extern void dap_http_client_delete(struct dap_client * cl,void * arg); // Free memory for HTTP client's internal structure + +extern void dap_http_client_read(struct dap_client * cl,void * arg); // Process read event +extern void dap_http_client_write(struct dap_client * cl,void * arg); // Process write event +extern void dap_http_client_error(struct dap_client * cl,void * arg); // Process error event + + +#endif diff --git a/http/dap_http_header.c b/http/dap_http_header.c new file mode 100644 index 0000000000000000000000000000000000000000..b1544726bedd195ee0ee4629e60c5e29523e0699 --- /dev/null +++ b/http/dap_http_header.c @@ -0,0 +1,173 @@ +#include <stdio.h> +#include <stdarg.h> +#include <string.h> +#include <stdlib.h> +#include "common.h" +#include "dap_client.h" +#include "dap_http_client.h" +#include "dap_http_header.h" + +#define LOG_TAG "http_header" + + +/** + * @brief dap_http_header_init Init module + * @return Zero if ok others if not + */ +int dap_http_header_init() +{ + log_it(NOTICE, "Initialized HTTP headers module"); + return 0; +} + +/** + * @brief dap_http_header_deinit Deinit module + */ +void dap_http_header_deinit() +{ + log_it(INFO, "HTTP headers module deinit"); +} + + +/** + * @brief dap_http_header_parse Parse string with HTTP header + * @param top Top of list with HTTP header structures + * @param str String to parse + * @return Zero if parsed well -1 if it wasn't HTTP header 1 if its "\r\n" string + */ +int dap_http_header_parse(struct dap_http_client * cl_ht, const char * str) +{ + + char name[256], value[1024]; + + size_t str_len=strlen(str); + //sn=sscanf(str,"%255s: %1023s\r\n",name,value); + size_t pos; + if( str_len==0 ) + return 1; + + //log_it(DEBUG, "Parse header string '%s'",str); + for(pos=1; pos<str_len;pos++) + if(str[pos]==':'){ + size_t name_len; + name_len=pos; + if(name_len>(sizeof(name)-1) ) + name_len=(sizeof(name)-1); + strncpy(name,str,name_len); + name[name_len]='\0'; + + // log_it(DEBUG, "Found name '%s'",name); + pos+=2; + size_t value_len=str_len-pos; + if(value_len>(sizeof(value)-1)) + value_len=(sizeof(value)-1); + strncpy(value,str+pos,value_len); + value[value_len]='\0'; + // log_it(DEBUG, "Found value '%s'",value); + + if(strcmp(name,"Connection")==0){ + if(strcmp(value,"Keep-Alive")==0){ + log_it(INFO, "Input: Keep-Alive connection detected"); + cl_ht->keep_alive=true; + } + }else if(strcmp(name,"Content-Type")==0){ + strncpy(cl_ht->in_content_type,value,sizeof(cl_ht->in_content_type)); + }else if(strcmp(name,"Content-Length")==0){ + cl_ht->in_content_length =atoi(value); + }else if(strcmp(name,"Cookie")==0){ + strncpy(cl_ht->in_cookie,value,sizeof(cl_ht->in_cookie)); + } + + + //log_it(DEBUG, "Input: Header\t%s '%s'",name,value); + + dap_http_header_add(&cl_ht->in_headers,name,value); + return 0; + } + + + log_it(ERROR,"Input: Wasn't found ':' symbol in the header"); + return -1; +} + + + +/** + * @brief http_header_add Add HTTP header to the HTTP server instance + * @param sh HTTP server instance + * @param name Header's name + * @param value Header's value + * @return Pointer to the new HTTP header's structure + */ +dap_http_header_t* dap_http_header_add(dap_http_header_t ** top, const char*name, const char * value) +{ + dap_http_header_t * nh = (dap_http_header_t*) calloc(1,sizeof(dap_http_header_t)); + // log_it(DEBUG,"Added header %s",name); + nh->name=strdup(name); + nh->value=strdup(value); + nh->next=*top; + if(*top) + (*top)->prev=nh; + *top=nh; + return nh; +} + + +struct dap_http_header* dap_http_out_header_add(dap_http_client_t * ht, const char*name, const char * value) +{ + + return dap_http_header_add(&ht->out_headers,name,value); +} + + +/** + * @brief dap_http_out_header_add_f Add header to the output queue with format-filled string + * @param ht HTTP client instance + * @param name Header name + * @param value Formatted string to header value + * @param ... Arguments for formatted string + * @return + */ +dap_http_header_t * dap_http_out_header_add_f(dap_http_client_t * ht, const char*name, const char * value,...) +{ + va_list ap; + dap_http_header_t * ret; + char buf[1024]; + va_start(ap,value); + vsnprintf(buf,sizeof(buf)-1,value,ap); + ret=dap_http_out_header_add(ht,name,buf); + va_end(ap); + return ret; +} + +/** + * @brief dap_http_header_remove Removes header from the list + * @param dap_hdr HTTP header + */ +void dap_http_header_remove(dap_http_header_t ** top, dap_http_header_t * hdr ) +{ + if(hdr->prev) + hdr->prev=hdr->next; + else + *top=hdr->next; + + if(hdr->next) + hdr->next->prev=hdr->prev; + free(hdr->name); + free(hdr->value); +} + +/** + * @brief dap_http_header_find Looks or the header with specified name + * @param top Top of the list + * @param name Name of the header + * @return NULL if not found or pointer to structure with found item + */ +dap_http_header_t * dap_http_header_find(dap_http_header_t * top, const char*name) +{ + dap_http_header_t * ret; + for(ret=top; ret; ret=ret->next) + if(strcmp(ret->name,name)==0) + return ret; + return ret; +} diff --git a/http/dap_http_header.h b/http/dap_http_header.h new file mode 100644 index 0000000000000000000000000000000000000000..05cd1a1d28c8a566644abb72f0d5b1b5292b0494 --- /dev/null +++ b/http/dap_http_header.h @@ -0,0 +1,28 @@ +#ifndef _DAP_HTTP_HEADER_H_ +#define _DAP_HTTP_HEADER_H_ + +//Structure for holding HTTP header in the bidirectional list +typedef struct dap_http_header{ + char * name; + char * value; + struct dap_http_header * next; + struct dap_http_header * prev; +} dap_http_header_t; + +struct dap_http_client; + +extern int dap_http_header_init(); // Init module +extern void dap_http_header_deinit(); // Deinit module + +extern int dap_http_header_parse(struct dap_http_client * cl_ht, const char * str); + +extern dap_http_header_t * dap_http_header_add(dap_http_header_t ** top, const char*name, const char * value); + +extern dap_http_header_t * dap_http_out_header_add(struct dap_http_client * ht, const char*name, const char * value); +extern dap_http_header_t * dap_http_out_header_add_f(struct dap_http_client * ht, const char*name, const char * value,...); + +extern dap_http_header_t * dap_http_header_find(dap_http_header_t * top, const char*name); + +extern void dap_http_header_remove(dap_http_header_t ** top,dap_http_header_t * hdr ); + +#endif