天津项目版本:V3.2.1.6

main
wangbo 8 months ago
commit 122b6d4244

@ -0,0 +1,75 @@
/*****************************************************************************
* file include/array.h
* author YuLiang
* version 1.0.0
* date 22-Sep-2021
* brief This file provides all the headers of the array functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _ARRAY_H_
#define _ARRAY_H_
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
#define ARRAY_MIN_SIZE 8
/* Exported types ------------------------------------------------------------*/
typedef struct
{
uint32_t active; /* 当前可使用的索引位置. */
uint32_t alloced; /* 申请的内存大小. */
void **index; /* 数组元素. */
} array_t;
/* Extern global variables ---------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* 获取数组A索引I的数据. */
#define array_get(A, I) ((A)->index[(I)])
/* 获取数组A目前激活的索引. */
#define array_active(A) ((A)->active)
/* Exported functions --------------------------------------------------------*/
extern array_t *array_init(uint32_t size, int32_t mem_type);
extern void array_set(array_t *a, uint32_t i, void *val, int32_t mem_type);
extern void array_unset(array_t *v, uint32_t i);
extern uint32_t array_append(array_t *a, void *val, int32_t mem_type);
extern void array_free_wrapper(array_t *a, int32_t mem_type);
extern void array_free_index(array_t *a, int32_t mem_type);
extern void array_free(array_t *a, int32_t mem_type);
extern array_t *array_copy(array_t *a, int32_t mem_type);
extern void array_merge(array_t *a, array_t *b, int32_t mem_type);
extern void *array_lookup(array_t *a, uint32_t i);
extern uint32_t array_count(array_t *a);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,177 @@
/******************************************************************************
* file include/better_log.h
* author YuLiang
* version 1.0.0
* date 14-Sep-2021
* brief This file provides all the headers of the log functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _BETTER_LOG_H_
#define _BETTER_LOG_H_
/* Includes ------------------------------------------------------------------*/
#include <sqlite3.h>
/* Define --------------------------------------------------------------------*/
#define LOG_FILE "PowerIoT.db"
#define LOG_CMD_LEN 512
#define LOG_STR_LEN 256
#define LOG_TABLE_NAME "better_log"
#define LOG_MAX_DECORD 5000
#define LOG_DEFAULT_SHOW_CNT 100
#define LOG_DB_FIFO "LOG_DB_FIFO"
#define LOG_STR "Display default most 100 logs\n"
#define LOG_LEVELS "(errors|warnings|notifications|informational|debug)"
#define LOG_LEVEL_DESC \
"Error messages\n" \
"Warning messages\n" \
"Normal but significant messages\n" \
"Informational messages\n" \
"Debug messages\n"
/* Exported types ------------------------------------------------------------*/
typedef enum
{
LOG_LVL_ERR,
LOG_LVL_WARN,
LOG_LVL_NOTIF,
LOG_LVL_INFO,
LOG_LVL_DBG,
LOG_LVL_MAX
} LOG_LVL_E;
typedef enum
{
LOG_MODE_STDOUT,
LOG_MODE_FILE,
LOG_MODE_MONITOR,
LOG_MODE_MAX
} LOG_MODE_E;
typedef enum
{
LOG_DEFAULT,
LOG_CLI,
LOG_MEMORY,
LOG_FIFO,
LOG_GPIO,
LOG_COLL,
LOG_CA_DB,
LOG_CA_DBG,
LOG_CA_MQTT,
LOG_CA_LAND,
LOG_MAX
} LOG_MODULE_E;
typedef enum
{
LOG_SHOW_CNT,
LOG_SHOW_LVL,
LOG_SHOW_KEYWORD,
LOG_SHOW_MAX
} LOG_SHOW_E;
typedef struct _log_lvl
{
int32_t lvl;
char *describe;
} log_lvl_t;
typedef struct _log_module
{
int32_t module;
char *describe;
} log_module_t;
/* log全局数据结构体. */
typedef struct _log_sys
{
int32_t enable_lvl[LOG_MODE_MAX]; /* log模块使能等级位图表示. */
int32_t default_lvl; /* 默认log模块使能等级位图表示. */
sqlite3 *db; /* log数据库指针. */
int32_t log_fifo_id; /* log fifo id. */
char *filename; /* log数据库名字. */
int32_t timestamp_precision; /* 默认log时间戳精度. */
pthread_mutex_t log_db_mutex; /* 数据库读写互斥锁 */
} log_sys_t;
typedef struct
{
LOG_SHOW_E type;
int32_t param;
char log_show_str[LOG_STR_LEN];
} _log_show_t;
typedef struct
{
LOG_MODULE_E module;
LOG_LVL_E lvl;
char log_out_str[LOG_STR_LEN];
} _log_out_t;
typedef struct
{
uint32_t type;
void *data;
} _log_msg_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
extern log_sys_t *log_sys;
/* Extern functions ----------------------------------------------------------*/
/* 配置函数属性,让gcc按printf一样检查函数参数,第b个参数为可变参数. */
#define BTLOG_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
extern void log_out(LOG_MODULE_E module, LOG_LVL_E priority, const char *format, ...)
BTLOG_ATTRIBUTE(3, 4);
extern void log_err(LOG_MODULE_E module, const char *format, ...)
BTLOG_ATTRIBUTE(2, 3);
extern void log_warn(LOG_MODULE_E module, const char *format, ...)
BTLOG_ATTRIBUTE(2, 3);
extern void log_info(LOG_MODULE_E module, const char *format, ...)
BTLOG_ATTRIBUTE(2, 3);
extern void log_notice(LOG_MODULE_E module, const char *format, ...)
BTLOG_ATTRIBUTE(2, 3);
extern void log_debug(LOG_MODULE_E module, const char *format, ...)
BTLOG_ATTRIBUTE(2, 3);
extern int32_t log_open();
extern void log_set_level(LOG_MODE_E mode, LOG_LVL_E log_level);
extern void log_unset_level(LOG_MODE_E mode, LOG_LVL_E log_level);
extern int32_t log_level_get_by_name(const char *lvl_name);
extern int32_t log_module_get_by_name( const char *module_name );
extern void log_backtrace(int32_t priority);
extern void log_clean(void);
extern void log_show( int32_t cnt, LOG_LVL_E priority, const char *key_word );
extern int32_t log_handle_init(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,300 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
#define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
#endif
#else /* !__WINDOWS__ */
#define CJSON_CDECL
#define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 15
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
* The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
* The input pointer json cannot point to a read-only address area, such as a string constant,
* but should point to a readable and writable address area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/
#define cJSON_SetBoolValue(object, boolValue) ( \
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \
cJSON_Invalid\
)
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,163 @@
/*****************************************************************************
* file include/ca_coll.h
* author YuLiang
* version 1.0.0
* date 28-Nov-2023
* brief This file provides all the headers of the collect functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __CA_COLL_H__
#define __CA_COLL_H__
#ifdef CFG_DEV_TYPE_LAND_CA
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
#define CA_COLL_ADC_CH_SUM 8
#define CA_COLL_SENSOR_SUM 8
#define CA_COLL_VERSION_LEN 32
#define CA_COLL_COMPILE_LEN 32
#define CA_COLL_NAME_LEN 128
#define CA_COLL_USART_NAME_LEN 64
#define CA_COLL_ERR_CNT_MAX 9
#define CA_COLL_VPN_LEN 64
/* Exported types ------------------------------------------------------------*/
/* 环流设备信息结构体 */
typedef struct
{
/* 设备信息. 36byte */
uint8_t type_m;
uint8_t type_s;
uint8_t mac[6];
uint32_t id;
uint8_t ip[4];
uint8_t ip_mask[4];
uint8_t ip_gw[4];
uint8_t server_ip[4];
uint8_t wireless_server_ip[4];
uint16_t server_port;
uint16_t wireless_server_port;
/* 版本信息. 224byte */
uint8_t boot_version[CA_COLL_VERSION_LEN];
uint8_t boot_compile_time[CA_COLL_COMPILE_LEN];
uint8_t img_version[CA_COLL_VERSION_LEN];
uint8_t img_compile_time[CA_COLL_COMPILE_LEN];
uint8_t hardware_version[CA_COLL_VERSION_LEN];
uint8_t FPGA_version[CA_COLL_VERSION_LEN];
uint8_t factory_time[CA_COLL_COMPILE_LEN];
/* 设备其他信息. 128byte */
uint8_t name[CA_COLL_NAME_LEN];
} ca_coll_dev_info_t;
/* 实时数据结构体. */
typedef struct
{
int16_t temperature; // 设备温度, 单位: 0.1℃.
uint16_t vbat; // 电池电压, 单位: mv.
int16_t CSQ; // 4G 信号质量 > -51dBm 统一显示 -51dBm, < -113 dBm 为无信号.
uint16_t vin; // 工作电压, 单位: mv.
uint32_t elec[CA_COLL_ADC_CH_SUM]; // 通道电流有效值 mA.
uint16_t vsc; // 超级电容电压, 单位: mv.
uint16_t sen_temp[CA_COLL_SENSOR_SUM]; // 传感器温度: 单位: 0.1℃.
uint16_t sen_x[CA_COLL_SENSOR_SUM]; // 传感器震动 x 轴.
uint16_t sen_y[CA_COLL_SENSOR_SUM]; // 传感器震动 y 轴.
uint16_t sen_z[CA_COLL_SENSOR_SUM]; // 传感器震动 z 轴.
uint8_t energy_mode; // 当前设备工作模式.
uint8_t sen_short; // 传感器是否短路, 0 没有短路, 1 短路.
uint8_t sen_valid[CA_COLL_SENSOR_SUM]; // 传感器数据是否有效, 0 - 无效, 1 - 有效.
uint32_t run_time; // 设备运行时长, 单位 s.
uint8_t fre_valid; // 工频数据有效, 有线协议使用.
uint8_t wave_valid; // 高频数据有效, 有线协议使用.
uint8_t reserve[2];
} ca_coll_dev_data_t;
/* 环流配置结构体. */
typedef struct
{
uint16_t interval; // 环流采集间隔, 单位: m
uint16_t threshold; // 工频采样阈值, 单位: A
uint16_t wave_threshold; // 高频采样阈值, 单位: mv
uint8_t wave_interval; // 高频采样间隔, 单位: h
uint8_t main_cable; // 主缆 ID (0-6) 默认 5
uint8_t normal_sleep; // 正常模式是否休眠: 0 - 否 1 - 是默认 0
uint8_t is_voltage_col; // 是否开启电流采集
uint8_t is_temp_col; // 是否开启温度震度
uint8_t is_wave_col; // 是否开启高频录波
} ca_coll_dev_cfg_t;
/* 设备配置结构体. */
typedef struct
{
int fd; // 打开的文件描述符
char dev[CA_COLL_USART_NAME_LEN]; // 串口驱动位置
int32_t baud; // 波特率
int8_t bits; // 几位数据位
char parity; // 奇偶校验位
int8_t stop; // 几位停止位
int8_t is_4G; // 4G 是否使能
int32_t coll_inr; // 采集间隔, 单位: s
char apn[CA_COLL_VPN_LEN]; // VPN
int8_t is_MQTT; // 是否打开 MQTT
int8_t is_land; // 是否打开协议
uint16_t land_port; // 私有协议端口
char land_ip[INET_ADDRSTRLEN]; // 私有协议地址
} ca_coll_cfg_t;
/* 设备状态结构体. */
typedef struct
{
int fd_read; // 环流升级文件描述符
uint32_t send_err_cnt; // 环流发送失败计数
uint32_t update_index; // 环流升级报文索引
bool is_update_cable; // 环流设备升级中
bool is_4g_connect; // EC20 是否拨号成功
} ca_coll_state_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern int32_t ca_coll_init(void);
extern int32_t ca_coll_init_after(void);
extern ca_coll_cfg_t* ca_coll_cfg_get(void);
extern ca_coll_dev_info_t* ca_coll_cable_info_get(void);
extern ca_coll_dev_cfg_t* ca_coll_cable_cfg_get(void);
extern ca_coll_dev_data_t* ca_coll_cable_data_get(void);
extern ca_coll_state_t* ca_coll_cable_state_get(void);
extern void ca_coll_cable_update_set(bool enable);
extern void ca_coll_show_dev(void);
extern void ca_coll_show_dev_data(void);
extern void ca_coll_show_dev_state(void);
#endif
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,66 @@
/*****************************************************************************
* file include/ca_db.h
* author YuLiang
* version 1.0.0
* date 29-Nov-2023
* brief This file provides all the headers of the database functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __CA_DB_H__
#define __CA_DB_H__
#ifdef CFG_DEV_TYPE_LAND_CA
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
#define CA_DB_FILE "Cable.db"
/* Exported types ------------------------------------------------------------*/
/* 数据类型枚举 */
enum CA_DB_TYPE
{
CA_DB_T_NONE = 0, // 空
CA_DB_T_DATA, // 历史数据
CA_DB_T_CNT // 累计计数
};
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern int32_t ca_db_init(void);
extern int32_t ca_db_init_after(void);
extern int32_t ca_db_write(uint32_t type, void *data);
extern void ca_db_show_data_by_index(uint16_t index, uint16_t num);
#endif
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,56 @@
/*****************************************************************************
* file include/ca_dbg.h
* author YuLiang
* version 1.0.0
* date 30-Nov-2023
* brief This file provides all the headers of the debug server functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __CA_DBG_H__
#define __CA_DBG_H__
#ifdef CFG_DEV_TYPE_LAND_CA
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern int32_t ca_dbg_handle_init_after(void);
extern int32_t ca_dbg_update_rt_send(int32_t rt);
#endif
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,65 @@
/*****************************************************************************
* file include/ca_land.h
* author YuLiang
* version 1.0.0
* date 20-Dec-2023
* brief This file provides all the headers of the LandPower protocol functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __CA_LAND_H__
#define __CA_LAND_H__
#ifdef CFG_DEV_TYPE_LAND_CA
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* 私有协议状态结构体 */
typedef struct
{
bool is_connect; // 是否连接上服务器
bool is_send_data; // 是否向服务器发送数据
} ca_land_state_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern int32_t ca_land_init(void);
extern int32_t ca_land_init_after(void);
extern ca_land_state_t* ca_land_state_get(void);
extern void ca_land_state_show(void);
#endif
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,56 @@
/*****************************************************************************
* file include/ca_main.h
* author YuLiang
* version 1.0.0
* date 27-Nov-2023
* brief This file provides all the headers of the cable functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __CA_MAIN_H__
#define __CA_MAIN_H__
#ifdef CFG_DEV_TYPE_LAND_CA
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
#endif
extern int32_t ca_main(void);
extern int32_t ca_main_after(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,111 @@
/*****************************************************************************
* file include/ca_mqtt.h
* author YuLiang
* version 1.0.0
* date 07-Dec-2023
* brief This file provides all the headers of the MQTT functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __CA_MQTT_H__
#define __CA_MQTT_H__
#ifdef CFG_DEV_TYPE_LAND_CA
/* Includes ------------------------------------------------------------------*/
#include "ca_collect.h"
#include "cmd.h"
#include "MQTTAsync.h"
/* Define --------------------------------------------------------------------*/
#define CA_MQTT_FIFO "CA_MQTT_FIFO"
#define NODE_NUM (1)
#define TOPIC_WILL "offline/will" //遗嘱主题
#define QOS 1
#define DEVICE_MODEL "SD_JK_LD_FBDMX"//
//#define DEVICE_MODEL "DL_WHLD_HL"
#define MANUFACTURERID "WHLD"
#define DEVICE_CODE "03MW00000000001"
#define DEVICE_POINT_A "03MCD00000000001"
#define DEVICE_POINT_B "03MCD00000000002"
#define DEVICE_POINT_C "03MCD00000000003"
/* Exported types ------------------------------------------------------------*/
/* MQTT 状态结构体 */
typedef struct
{
bool is_connect; // 是否连接
uint8_t login_err_cnt; // 4G 网络连接成功的情况下, 登录失败次数
} ca_mqtt_state_t;
/* fifo 消息结构体 */
typedef struct
{
uint32_t type; // 类型
void *data; // 数据
} ca_mqtt_msg_t;
typedef struct
{
char node_id[32];
char device_id[32];
} node_info_t;
/* 全局控制结构体 */
typedef struct
{
int32_t fifo_id; // fifo id
ca_mqtt_dev_info_t info; // MQTT 信息
ca_mqtt_state_t state; // MQTT 状态
MQTTAsync client;
node_info_t node[NODE_NUM]; // 测点信息
} ca_mqtt_ctrl_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern int32_t ca_mqtt_init(void);
extern int32_t ca_mqtt_init_after(void);
extern int32_t ca_mqtt_data_report(ca_coll_dev_data_t *data);
extern ca_mqtt_state_t* ca_mqtt_state_get(void);
extern void ca_mqtt_state_show(void);
extern void _ca_mqtt_query_device_info();
extern int _ca_mqtt_gen_topic(char *topic, char *id, char *cmd);
extern void _ca_mqtt_json_ground_current(ca_coll_dev_data_t *data, char *outmsg, int idx);
extern int _ca_mqtt_data_report_child_device(ca_coll_dev_data_t *data, char *device_id, int idx);
extern int _ca_mqtt_update_device_status(char *device_id);
extern int _ca_mqtt_add_sub_device(node_info_t *node_info);
#endif
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,346 @@
/******************************************************************************
* file include/cmd.h
* author YuLiang
* version 1.0.0
* date 09-Oct-2021
* brief This file provides all the headers of the command functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _CMD_H_
#define _CMD_H_
/* Includes ------------------------------------------------------------------*/
#include "array.h"
#include "vty.h"
/* Define --------------------------------------------------------------------*/
/* 命令行最大参数个数. */
#define CMD_ARGC_MAX 16
/* rang检查数字最大位数. */
#define DECIMAL_STRLEN_MAX 10
#define INIT_MATCHARR_SIZE 10
#define COMPLETE_BUF_SIZE 256
#define CA_MQTT_CLINET_ID_LEN 64
#define CA_MQTT_USERNAME_LEN 64
#define CA_MQTT_PASSWD_LEN 64
#define CA_MQTT_DEV_ID_LEN 64
#define IPV6_ADDR_STR "0123456789abcdefABCDEF:.%"
#define IPV6_PREFIX_STR "0123456789abcdefABCDEF:.%/"
#define STATE_START 1
#define STATE_COLON 2
#define STATE_DOUBLE 3
#define STATE_ADDR 4
#define STATE_DOT 5
#define STATE_SLASH 6
#define STATE_MASK 7
/* 命令行返回值. */
#define CMD_SUCCESS 0
#define CMD_WARNING 1
#define CMD_ERR_NO_MATCH 2
#define CMD_ERR_AMBIGUOUS 3
#define CMD_ERR_INCOMPLETE 4
#define CMD_ERR_EXEED_ARGC_MAX 5
#define CMD_ERR_NOTHING_TODO 6
#define CMD_COMPLETE_FULL_MATCH 7
#define CMD_COMPLETE_MATCH 8
#define CMD_COMPLETE_LIST_MATCH 9
#define CMD_SUCCESS_DAEMON 10
#define CONF_BACKUP_EXT ".sav"
#define CL_COPYRIGHT "Copyright 2023-2024 LandPower."
/* Common descriptions. */
#define SHOW_STR "Show running system information\n"
#define IP_STR "IP information\n"
#define IPV6_STR "IPv6 information\n"
#define NO_STR "Negate a command or set its defaults\n"
#define REDIST_STR "Redistribute information from another routing protocol\n"
#define CLEAR_STR "Reset functions\n"
#define RIP_STR "RIP information\n"
#define BGP_STR "BGP information\n"
#define OSPF_STR "OSPF information\n"
#define NEIGHBOR_STR "Specify neighbor router\n"
#define DEBUG_STR "Debugging functions (see also 'undebug')\n"
#define UNDEBUG_STR "Disable debugging functions (see also 'debug')\n"
#define ROUTER_STR "Enable a routing process\n"
#define AS_STR "AS number\n"
#define MBGP_STR "MBGP information\n"
#define MATCH_STR "Match values from routing table\n"
#define SET_STR "Set values in destination routing protocol\n"
#define OUT_STR "Filter outgoing routing updates\n"
#define IN_STR "Filter incoming routing updates\n"
#define V4NOTATION_STR "specify by IPv4 address notation(e.g. 0.0.0.0)\n"
#define OSPF6_NUMBER_STR "Specify by number\n"
#define INTERFACE_STR "Interface infomation\n"
#define IFNAME_STR "Interface name(e.g. ep0)\n"
#define IP6_STR "IPv6 Information\n"
#define OSPF6_STR "Open Shortest Path First (OSPF) for IPv6\n"
#define OSPF6_ROUTER_STR "Enable a routing process\n"
#define OSPF6_INSTANCE_STR "<1-65535> Instance ID\n"
#define SECONDS_STR "<1-65535> Seconds\n"
#define ROUTE_STR "Routing Table\n"
#define PREFIX_LIST_STR "Build a prefix list\n"
/* Some macroes */
#define CMD_OPTION(S) ('[' == (S[0]))
#define CMD_VARIABLE(S) (((S[0]) >= 'A' && (S[0]) <= 'Z') || ('<' == (S[0])))
#define CMD_VARARG(S) ('.' ==(S[0]))
#define CMD_RANGE(S) ('<' == (S[0]))
#define CMD_IPV4(S) (0 == strcmp((S), "A.B.C.D"))
#define CMD_IPV4_PREFIX(S) (0 == strcmp((S), "A.B.C.D/M"))
#define CMD_IPV6(S) (0 == strcmp((S), "X:X::X:X"))
#define CMD_IPV6_PREFIX(S) (0 == strcmp((S), "X:X::X:X/M"))
#define DEV_INFO_DEFAULT_IP "192.168.1.110"
#define DEV_INFO_DEFAULT_MASK "255.255.255.0"
#define DEV_INFO_DEFAULT_GW "192.168.1.1"
#define DEVICE_RUN_PATH "/home/Cable"
#define SAVE_STA_CFG_BAK_FILE 1
#define SAVE_DEV_CFG_BAK_FILE 2
/* Exported types ------------------------------------------------------------*/
enum
{
CMD_ATTR_DEPRECATED = 1,
CMD_ATTR_HIDDEN,
};
/* 匹配结果类型. */
typedef enum
{
no_match,
extend_match,
ipv4_prefix_match,
ipv4_match,
ipv6_prefix_match,
ipv6_match,
range_match,
vararg_match,
partly_match,
exact_match
} MATCH_TYPE_E;
/* 用于定义命令的宏. */
#define CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attrs, dnum) \
cmd_element_t cmdname = \
{ \
.string = cmdstr, \
.func = funcname, \
.doc = helpstr, \
.attr = attrs, \
.daemon = dnum, \
};
#define CMD_FUNC_DECL(funcname) \
static int funcname(cmd_element_t *, vty_t *, int, const char *[]);
#define CMD_FUNC_TEXT(funcname) \
static int funcname \
(cmd_element_t *self __attribute__ ((unused)), \
vty_t *vty __attribute__ ((unused)), \
int argc __attribute__ ((unused)), \
const char *argv[] __attribute__ ((unused)))
/* CMD for vty command interafce. Little bit hacky ;-). */
#define CMD(funcname, cmdname, cmdstr, helpstr) \
CMD_FUNC_DECL(funcname) \
CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0) \
CMD_FUNC_TEXT(funcname)
#define CMD_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \
CMD_FUNC_DECL(funcname) \
CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0) \
CMD_FUNC_TEXT(funcname)
#define CMD_HIDDEN(funcname, cmdname, cmdstr, helpstr) \
CMD_ATTR(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN)
#define CMD_DEPRECATED(funcname, cmdname, cmdstr, helpstr) \
CMD_ATTR(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED) \
/* ALIAS macro which define existing command's alias. */
#define ALIAS(funcname, cmdname, cmdstr, helpstr) \
CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0)
#define ALIAS_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \
CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0)
#define ALIAS_HIDDEN(funcname, cmdname, cmdstr, helpstr) \
CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, 0)
#define ALIAS_DEPRECATED(funcname, cmdname, cmdstr, helpstr) \
CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED, 0)
/* 命令行模式节点宏 */
typedef enum
{
USERNAME_NODE, /* Username node. Default mode of vty interface. */
PASSWORD_NODE, /* Password node. */
ENABLE_NODE, /* Enable node. */
CONFIG_NODE, /* Config node. Default mode of config file. */
COLL_RS485_NODE, /* RS485 node. */
COMMON_NODE, /* Common node. Cmd is common to other node. */
NODES_COUNT
} NODE_TYPE_E;
/* config节点配置优先级 */
typedef enum
{
CONFIG_PRI_CA_COLL,
CONFIG_PRI_CA_MQTT,
CONFIG_PRI_COUNT
} CONFIG_PRI_E;
/* MQTT 基本配置结构体 */
typedef struct
{
char server_ip[INET_ADDRSTRLEN]; // 服务器 ip
uint16_t server_port; // 服务器 端口
uint16_t alive_time; // 保活时间
char dev_id[CA_MQTT_DEV_ID_LEN]; // 设备 id
char client_id[CA_MQTT_CLINET_ID_LEN]; // 客户端 id
char username[CA_MQTT_USERNAME_LEN]; // 用户名
char passwd[CA_MQTT_PASSWD_LEN]; // 密码
} ca_mqtt_dev_info_t;
/* Host configuration variable */
typedef struct
{
uint32_t id_minor; /* 设备次设备号 */
uint16_t id_major; /* 设备主设备号 */
uint32_t dev_id; /* 设备 ID */
uint8_t mac[MAC_ADDR_LEN]; /* System mac. */
char host_ip[INET_ADDRSTRLEN]; /* host ip string. */
char host_mask[INET_ADDRSTRLEN];/* host mask string. */
char host_gw[INET_ADDRSTRLEN]; /* host gw string. */
uint32_t factory_date; /* 出厂日期. */
uint32_t deployment_date; /* 部署日期. */
char dev_type[FILE_NAME_LEN]; /* 设备型号字符串. */
ca_mqtt_dev_info_t mqtt; /* MQTT 信息 */
} device_info_t;
/* Host configuration variable */
typedef struct
{
char name[FILE_NAME_LEN]; /* Host name of this router. */
int lines; /* System wide terminal lines. */
char *version; /* 版本号. */
char *compile; /* 编译时间. */
char configfile[FILE_NAME_LEN]; /* config file name of this host */
char bannerfile[FILE_NAME_LEN]; /* Banner configuration file name. */
} host_t;
/* Structure of command element. */
typedef struct _cmd_element
{
const char *string; /* Command specification by string */
const char *doc; /* Documentation of this command */
array_t *strs; /* Pointing out each description array */
unsigned int str_size; /* Command index count */
int (*func)(struct _cmd_element*, vty_t*, int, const char *[]);
int daemon; /* Daemon to which this command belong */
char *config; /* Configuration string */
array_t *sub_cfg; /* Sub configuration string */
unsigned char attr; /* Command attributes */
} cmd_element_t;
/* Command description structure. */
typedef struct
{
char *cmd; /* Command string. */
char *str; /* Command's description. */
} desc_t;
/* 用于命令行模式节点注册配置保存函数 */
typedef int cmd_save_config_f(vty_t*);
/* 命令行模式节点结构体 */
typedef struct
{
uint32_t node; /* Node index. */
uint32_t up_node; /* Upper level node index. */
uint8_t param_num; /* Prompt param num. */
char *prompt; /* Prompt character at vty interface. */
cmd_save_config_f *func; /* Node's configuration write function */
array_t *cmds; /* Array of this node's command list. */
array_t *configs; /* 配置函数数组. */
} cmd_node_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
extern host_t host;
extern device_info_t device_info;
extern array_t *cmd_nodes;
extern int8_t is_system_init;
extern int8_t is_system_reboot;
/* Extern functions ----------------------------------------------------------*/
static inline cmd_node_t *cmd_node_get(NODE_TYPE_E ntype)
{
return (cmd_node_t *)array_lookup(cmd_nodes, ntype);
}
extern void cmd_init(void);
extern int32_t cmd_execute(vty_t *vty);
extern const char *cmd_prompt(NODE_TYPE_E ntype);
extern array_t *cmd_strs_create(const char *string);
extern void cmd_strs_free(array_t *a);
extern void cmd_sort_node(void);
extern void cmd_install_node(cmd_node_t *node, cmd_save_config_f *func);
extern array_t *cmd_describe_command (array_t *cmd_line, vty_t *vty, int32_t *status);
extern char **cmd_complete_command(array_t *vline, vty_t *vty, int32_t *status);
extern void cmd_install_element(NODE_TYPE_E ntype, cmd_element_t *cmd);
extern int32_t cmd_config_node_config_register(int32_t pri, cmd_save_config_f *func);
extern void vtysh_init(void);
extern char *vtysh_prompt (void);
extern int vtysh_rl_question(void);
extern int vtysh_rl_completion(void);
extern char *vtysh_completion_entry_function(const char *ignore, int invoking_key);
extern void vtysh_config_recovery(void);
extern void vtysh_device_save(void);
extern void vtysh_eth0_save(void);
extern int32_t vtysh_config_save(void);
extern int32_t vtysh_host_addr_set(char *addr, char *mask);
extern int32_t vtysh_gateway_set(char *gateway);
extern void vtysh_shell_init(void);
extern void vtycmd_init(void);
extern void vtycmd_cmd_init(void);
extern bool vtycmd_connect(void);
extern void vtycmd_print(const char *format, va_list va);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,172 @@
/******************************************************************************
* file include/common.h
* author YuLiang
* version 1.0.0
* date 10-Sep-2021
* brief This file provides all the headers of the common functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _COMMON_H_
#define _COMMON_H_
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include "array.h"
#include "better_log.h"
#include "dbg.h"
#include "memory.h"
#include "thread_monitor.h"
/* Define --------------------------------------------------------------------*/
#define FALSE 0
#define TRUE 1
#define E_NONE 0
#define E_ERROR -1
#define E_BAD_PARAM -2
#define E_MEM -3
#define E_SYS_CALL -4
#define E_NULL -5
#define E_NOT_FOUND -6
#define E_NOT_IDENTIFY -7
#define E_TIMEOUT -8
#define E_SAME -9
#define OUT
#define BACKTRACE_SIZE 20
#define TIME_STR_LEN 64
#define RECV_MSG_LEN 1536
#define DEVICE_INVALID 255
#define FILE_NAME_LEN 128
#define DIR_PATH_LEN 512
#define INET_ADDRSTRLEN 16
#define INET6_ADDRSTRLEN 46
#define ETH_GIS_DEV_ID_LEN 16
#define ETH_GIS_CMD_PARAM_LEN 16
#define DEVICE_ID_LEN 6
#define MAC_ADDR_LEN 6
#define IP_ADDR_LEN 4
#define DEV_DATA_LEN 1000
#define DEV_DATA_BITMAP_LEN 8
#define DEV_NAME_STR_LEN 32
/* Does the I/O error indicate that the operation should be retried later? */
#define ERRNO_IO_RETRY(EN) \
(((EN) == EAGAIN) || ((EN) == EWOULDBLOCK) || ((EN) == EINTR))
/* Exported types ------------------------------------------------------------*/
typedef int8_t bool;
/* Exported macro ------------------------------------------------------------*/
#define BITMAP_SET(t, b) ((t) |= 1 << (b))
#define BITMAP_RESET(t, b) ((t) &= ~(1 << (b)))
#define IS_BITMAP_SET(t, b) ((t) & (1 << b))
typedef enum _BOOT_MSG
{
BOOT_NONE = 0,
BOOT_SYSTEM_RESET,
BOOT_SYSTEM_LOGOUT,
BOOT_REMOTE_CFG_SET,
BOOT_REMOTE_RESET,
BOOT_REMOTE_UPDATE,
BOOT_FILE_RECOVER,
BOOT_4G_ERR,
BOOT_CONNECT_ERR,
BOOT_TIMER,
BOOT_MAX,
} BOOT_MSG;
typedef struct
{
BOOT_MSG type; // 重启类型
char *msg; // 重启日志
} boot_msg_t;
#define LD_E_RETURN(_module_, _f_) \
do { \
int _rv_ = E_ERROR; \
if ((_rv_ = _f_) != E_NONE) \
{ \
DBG(_module_, "ERROR return %d!\r\n", _rv_); \
return _rv_; \
} \
} while(0)
#define LD_NULL_RETURN(_module_, _f_) \
do { \
if (NULL == (_f_)) \
{ \
DBG(_module_, "ERROR return %d!\r\n", _rv_); \
return E_NULL; \
} \
} while(0)
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern char *str_to_lower(char *str);
extern char *str_omit_space(char *str, bool omit_end);
extern size_t time_string(int32_t timestamp_precision, char *buf, size_t buflen);
extern const char *safe_strerror(int errnum);
extern void buf_print(char *buf, int32_t len);
extern int32_t mac_generate_from_ip(char *ip_str, uint8_t *mac);
extern uint16_t crc16(uint8_t *data, uint16_t size);
extern uint16_t crc16_modbus(uint8_t *data, uint16_t size);
extern void crc32_table_init(void);
extern uint32_t crc32(void const *buf, uint16_t byte_count);
extern uint32_t crc32_update(uint32_t crc, char* buf, uint32_t len);
extern void speed_detection_stat(void);
extern void speed_detection_end(void);
extern int printh(const char *format, ...);
extern char* version_get();
extern char* version_date_get();
extern uint16_t sofrware_version_get(void);
extern int32_t str_to_mac(char *mac_str, OUT uint8_t *mac);
extern int32_t str_to_id(char *id_str, OUT uint32_t *id);
extern int32_t bitmap_set(uint8_t *buf, int32_t nbit, int32_t buf_len);
extern int32_t bitmap_reset(uint8_t *buf, int32_t nbit, int32_t buf_len);
extern int32_t is_bitmap_set(uint8_t *buf, int32_t nbit, int32_t buf_len);
extern int32_t time_str_to_long(char *date, char *time, uint32_t *t);
extern uint16_t version_str_to_int(void);
extern void time_set(time_t timestamp);
extern void reboot_system(int module, BOOT_MSG type);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,112 @@
/******************************************************************************
* file include/common.h
* author YuLiang
* version 1.0.0
* date 10-Sep-2021
* brief This file provides all the headers of the debug functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _DBG_H_
#define _DBG_H_
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
#define DBG_HELP_STR_MAX 32
#define DBG_INVALID_MODULE 0xffffffff
/* Exported types ------------------------------------------------------------*/
/* debug模块. */
typedef enum
{
DBG_M_DBG = 0,
DBG_M_CLI,
DBG_M_MTIMER,
DBG_M_PROCESS,
DBG_M_GPIO,
DBG_M_FIFO,
DBG_M_FIFO_ERR,
DBG_M_CA_COLL,
DBG_M_CA_COLL_ERR,
DBG_M_CA_DB,
DBG_M_CA_DB_ERR,
DBG_M_CA_DBG,
DBG_M_CA_DBG_ERR,
DBG_M_CA_MQTT,
DBG_M_CA_MQTT_ERR,
DBG_M_CA_LAND,
DBG_M_CA_LAND_ERR,
DBG_M_COUNT
} DBG_MODULE_E;
/* debug命令字. */
typedef enum
{
DBG_CMD_ON = 0,
DBG_CMD_OFF,
DBG_CMD_ALL_OFF
} DBG_CMD_E;
/* debug结构体,每个结构体代表一个模块. */
typedef struct
{
int32_t num;
int32_t stat;
char desc[DBG_HELP_STR_MAX];
} dbg_module_t;
/* Exported macro ------------------------------------------------------------*/
#ifdef CFG_DBG_ON
#define DBG(_MODULE_, _format_, _msg_...) \
do { \
if (dbg_stat_get(_MODULE_)) printh("%s(%d): " _format_, __FUNCTION__, __LINE__, ##_msg_); \
} while(0)
#define DBG_Q(_MODULE_, _format_, _msg_...) \
do { \
if (_dbg_module[_MODULE_].stat) printh(_format_, ##_msg_); \
} while(0)
#else
#define DBG(_MODULE_, _msg_...)
#define DBG(_MODULE_, _format_, _msg_...)
#endif
/* Extern global variables ---------------------------------------------------*/
#ifdef CFG_DBG_ON
extern dbg_module_t _dbg_module[DBG_M_COUNT];
#endif
/* Extern functions ----------------------------------------------------------*/
extern int32_t dbg_stat_get(DBG_MODULE_E module);
extern int dbg_cmd_hander(DBG_CMD_E cmd, int32_t module);
extern void dbg_init(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,73 @@
/******************************************************************************
* file include/fifo.h
* author YuLiang
* version 1.0.0
* date 21-Feb-2023
* brief This file provides all the headers of the fifo functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _FIFO_H_
#define _FIFO_H_
/* Includes ------------------------------------------------------------------*/
#include <semaphore.h>
/* Define --------------------------------------------------------------------*/
#define FIFO_NAME_LEN 32
/* Exported types ------------------------------------------------------------*/
/* . */
typedef struct _fifo_t
{
char name[FIFO_NAME_LEN]; // fifo 名字.
uint32_t size; // fifo 大小.
uint32_t cur; // 当前的数据位置.
uint32_t valid; // 当前读取的数据位置.
uint32_t used; // fifo 使用数量.
uint32_t max; // fifo 最大使用数量.
pthread_mutex_t mutex; // 多线程同时操作的信号量.
sem_t sem; // 读取有效互斥锁.
void **data; // 数据数组.
} fifo_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern int32_t fifo_init(void);
extern int32_t fifo_create(char* name, uint32_t size);
extern int32_t fifo_write(uint32_t id, void *data, int32_t len);
extern int32_t fifo_read(uint32_t id, void **data);
extern int32_t fifo_push(uint32_t id);
extern void fifo_show(uint32_t id);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,76 @@
/******************************************************************************
* file include/hwgpio.h
* author YuLiang
* version 1.0.0
* date 24-Nov-2021
* brief This file provides all the headers of the gpio functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _HWGPIO_H_
#define _HWGPIO_H_
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
#define GPIO_DIR_IN 1
#define GPIO_DIR_OUT 2
#define GPIO_RUN 79
#define GPIO_WDG 123
/* Exported types ------------------------------------------------------------*/
/* 记录每个打开的gpio信息 */
typedef struct
{
uint16_t index; /* gpio在数组中的索引 */
uint16_t gpio; /* gpio号 gpio2-15 = (2 - 1) * 32 + 15 = 47 */
uint8_t is_export; /* 是否已导出 */
uint8_t curr_dir; /* 方向当前值 1-in 2-out */
uint8_t curr_val; /* 电平当前值 针对dir==out时 ,当dir为in时,每次都需要读文件 */
} gpio_node_t;
/* Exported macro ------------------------------------------------------------*/
#define GPIO_RUN_LED(_v_) gpio_val_set(gpio_run_idx, _v_)
#define GPIO_WATCHDOG(_v_) gpio_val_set(gpio_wdg_idx, _v_)
/* Extern global variables ---------------------------------------------------*/
extern int32_t gpio_run_idx;
extern int32_t gpio_wdg_idx;
/* Extern functions ----------------------------------------------------------*/
extern int32_t gpio_val_set(uint16_t gpio, uint8_t value);
extern int32_t gpio_val_get(uint16_t gpio, uint8_t *value);
extern int32_t gpio_dir_set(uint16_t gpio, uint8_t dir);
extern int32_t gpio_export(uint16_t gpio);
extern int32_t gpio_init(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,701 @@
#ifndef _LIST_H_
#define _LIST_H_
/*
* Simple doubly linked list implementation.
*
* Some of the internal functions ("__xxx") are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
#define l_offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - l_offsetof(type,member) );})
static inline void prefetch(const void *x) {;}
static inline void prefetchw(const void *x) {;}
#define LIST_POISON1 ((void *) 0x00100100)
#define LIST_POISON2 ((void *) 0x00200200)
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
/**
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
/**
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty() on entry does not return true after this, the entry is
* in an undefined state.
*/
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
/**
* list_replace - replace old entry by new one
* @old : the element to be replaced
* @new : the new element to insert
*
* If @old was empty, it will be overwritten.
*/
static inline void list_replace(struct list_head *old,
struct list_head *new)
{
new->next = old->next;
new->next->prev = new;
new->prev = old->prev;
new->prev->next = new;
}
static inline void list_replace_init(struct list_head *old,
struct list_head *new)
{
list_replace(old, new);
INIT_LIST_HEAD(old);
}
/**
* list_del_init - deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
static inline void list_del_init(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
INIT_LIST_HEAD(entry);
}
/**
* list_move - delete from one list and add as another's head
* @list: the entry to move
* @head: the head that will precede our entry
*/
static inline void list_move(struct list_head *list, struct list_head *head)
{
__list_del(list->prev, list->next);
list_add(list, head);
}
/**
* list_move_tail - delete from one list and add as another's tail
* @list: the entry to move
* @head: the head that will follow our entry
*/
static inline void list_move_tail(struct list_head *list,
struct list_head *head)
{
__list_del(list->prev, list->next);
list_add_tail(list, head);
}
/**
* list_is_last - tests whether @list is the last entry in list @head
* @list: the entry to test
* @head: the head of the list
*/
static inline int list_is_last(const struct list_head *list,
const struct list_head *head)
{
return list->next == head;
}
/**
* list_empty - tests whether a list is empty
* @head: the list to test.
*/
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}
/**
* list_empty_careful - tests whether a list is empty and not being modified
* @head: the list to test
*
* Description:
* tests whether a list is empty _and_ checks that no other CPU might be
* in the process of modifying either member (next or prev)
*
* NOTE: using list_empty_careful() without synchronization
* can only be safe if the only activity that can happen
* to the list entry is list_del_init(). Eg. it cannot be used
* if another CPU could re-list_add() it.
*/
static inline int list_empty_careful(const struct list_head *head)
{
struct list_head *next = head->next;
return (next == head) && (next == head->prev);
}
/**
* list_is_singular - tests whether a list has just one entry.
* @head: the list to test.
*/
static inline int list_is_singular(const struct list_head *head)
{
return !list_empty(head) && (head->next == head->prev);
}
static inline void __list_cut_position(struct list_head *list,
struct list_head *head, struct list_head *entry)
{
struct list_head *new_first = entry->next;
list->next = head->next;
list->next->prev = list;
list->prev = entry;
entry->next = list;
head->next = new_first;
new_first->prev = head;
}
/**
* list_cut_position - cut a list into two
* @list: a new list to add all removed entries
* @head: a list with entries
* @entry: an entry within head, could be the head itself
* and if so we won't cut the list
*
* This helper moves the initial part of @head, up to and
* including @entry, from @head to @list. You should
* pass on @entry an element you know is on @head. @list
* should be an empty list or a list you do not care about
* losing its data.
*
*/
static inline void list_cut_position(struct list_head *list,
struct list_head *head, struct list_head *entry)
{
if (list_empty(head))
return;
if (list_is_singular(head) &&
(head->next != entry && head != entry))
return;
if (entry == head)
INIT_LIST_HEAD(list);
else
__list_cut_position(list, head, entry);
}
static inline void __list_splice(const struct list_head *list,
struct list_head *prev,
struct list_head *next)
{
struct list_head *first = list->next;
struct list_head *last = list->prev;
first->prev = prev;
prev->next = first;
last->next = next;
next->prev = last;
}
/**
* list_splice - join two lists, this is designed for stacks
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice(const struct list_head *list,
struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head, head->next);
}
/**
* list_splice_tail - join two lists, each list being a queue
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice_tail(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head->prev, head);
}
/**
* list_splice_init - join two lists and reinitialise the emptied list.
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* The list at @list is reinitialised
*/
static inline void list_splice_init(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head, head->next);
INIT_LIST_HEAD(list);
}
}
/**
* list_splice_tail_init - join two lists and reinitialise the emptied list
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* Each of the lists is a queue.
* The list at @list is reinitialised
*/
static inline void list_splice_tail_init(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head->prev, head);
INIT_LIST_HEAD(list);
}
}
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
/**
* list_first_entry - get the first element from a list
* @ptr: the list head to take the element from.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*
* Note, that list is expected to be not empty.
*/
#define list_first_entry(ptr, type, member) \
list_entry((ptr)->next, type, member)
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; prefetch(pos->next), pos != (head); \
pos = pos->next)
/**
* __list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*
* This variant differs from list_for_each() in that it's the
* simplest possible list iteration code, no prefetching is done.
* Use this for code that knows the list to be very short (empty
* or 1 entry) most of the time.
*/
#define __list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
/**
* list_for_each_prev - iterate over a list backwards
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \
pos = pos->prev)
/**
* list_for_each_safe - iterate over a list safe against removal of list entry
* @pos: the &struct list_head to use as a loop cursor.
* @n: another &struct list_head to use as temporary storage
* @head: the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)
/**
* list_for_each_prev_safe - iterate over a list backwards safe against removal of list entry
* @pos: the &struct list_head to use as a loop cursor.
* @n: another &struct list_head to use as temporary storage
* @head: the head for your list.
*/
#define list_for_each_prev_safe(pos, n, head) \
for (pos = (head)->prev, n = pos->prev; \
prefetch(pos->prev), pos != (head); \
pos = n, n = pos->prev)
/**
* list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry(pos, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member); \
prefetch(pos->member.next), &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
/**
* list_for_each_entry_reverse - iterate backwards over list of given type.
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_reverse(pos, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member); \
prefetch(pos->member.prev), &pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))
/**
* list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue()
* @pos: the type * to use as a start point
* @head: the head of the list
* @member: the name of the list_struct within the struct.
*
* Prepares a pos entry for use as a start point in list_for_each_entry_continue().
*/
#define list_prepare_entry(pos, head, member) \
((pos) ? : list_entry(head, typeof(*pos), member))
/**
* list_for_each_entry_continue - continue iteration over list of given type
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*
* Continue to iterate over list of given type, continuing after
* the current position.
*/
#define list_for_each_entry_continue(pos, head, member) \
for (pos = list_entry(pos->member.next, typeof(*pos), member); \
prefetch(pos->member.next), &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
/**
* list_for_each_entry_continue_reverse - iterate backwards from the given point
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*
* Start to iterate over list of given type backwards, continuing after
* the current position.
*/
#define list_for_each_entry_continue_reverse(pos, head, member) \
for (pos = list_entry(pos->member.prev, typeof(*pos), member); \
prefetch(pos->member.prev), &pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))
/**
* list_for_each_entry_from - iterate over list of given type from the current point
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate over list of given type, continuing from current position.
*/
#define list_for_each_entry_from(pos, head, member) \
for (; prefetch(pos->member.next), &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
/**
* list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
* @pos: the type * to use as a loop cursor.
* @n: another type * to use as temporary storage
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_safe(pos, n, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
/**
* list_for_each_entry_safe_continue
* @pos: the type * to use as a loop cursor.
* @n: another type * to use as temporary storage
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate over list of given type, continuing after current point,
* safe against removal of list entry.
*/
#define list_for_each_entry_safe_continue(pos, n, head, member) \
for (pos = list_entry(pos->member.next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
/**
* list_for_each_entry_safe_from
* @pos: the type * to use as a loop cursor.
* @n: another type * to use as temporary storage
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate over list of given type from current point, safe against
* removal of list entry.
*/
#define list_for_each_entry_safe_from(pos, n, head, member) \
for (n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
/**
* list_for_each_entry_safe_reverse
* @pos: the type * to use as a loop cursor.
* @n: another type * to use as temporary storage
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate backwards over list of given type, safe against removal
* of list entry.
*/
#define list_for_each_entry_safe_reverse(pos, n, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member), \
n = list_entry(pos->member.prev, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.prev, typeof(*n), member))
/*
* Double linked lists with a single pointer list head.
* Mostly useful for hash tables where the two pointer list head is
* too wasteful.
* You lose the ability to access the tail in O(1).
*/
struct hlist_head {
struct hlist_node *first;
};
struct hlist_node {
struct hlist_node *next, **pprev;
};
#define HLIST_HEAD_INIT { .first = NULL }
#define HLIST_HEAD(name) struct hlist_head name = { .first = NULL }
#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL)
static inline void INIT_HLIST_NODE(struct hlist_node *h)
{
h->next = NULL;
h->pprev = NULL;
}
static inline int hlist_unhashed(const struct hlist_node *h)
{
return !h->pprev;
}
static inline int hlist_empty(const struct hlist_head *h)
{
return !h->first;
}
static inline void __hlist_del(struct hlist_node *n)
{
struct hlist_node *next = n->next;
struct hlist_node **pprev = n->pprev;
*pprev = next;
if (next)
next->pprev = pprev;
}
static inline void hlist_del(struct hlist_node *n)
{
__hlist_del(n);
n->next = LIST_POISON1;
n->pprev = LIST_POISON2;
}
static inline void hlist_del_init(struct hlist_node *n)
{
if (!hlist_unhashed(n)) {
__hlist_del(n);
INIT_HLIST_NODE(n);
}
}
static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
{
struct hlist_node *first = h->first;
n->next = first;
if (first)
first->pprev = &n->next;
h->first = n;
n->pprev = &h->first;
}
/* next must be != NULL */
static inline void hlist_add_before(struct hlist_node *n,
struct hlist_node *next)
{
n->pprev = next->pprev;
n->next = next;
next->pprev = &n->next;
*(n->pprev) = n;
}
static inline void hlist_add_after(struct hlist_node *n,
struct hlist_node *next)
{
next->next = n->next;
n->next = next;
next->pprev = &n->next;
if(next->next)
next->next->pprev = &next->next;
}
/*
* Move a list from one list head to another. Fixup the pprev
* reference of the first entry if it exists.
*/
static inline void hlist_move_list(struct hlist_head *old,
struct hlist_head *new)
{
new->first = old->first;
if (new->first)
new->first->pprev = &new->first;
old->first = NULL;
}
#define hlist_entry(ptr, type, member) container_of(ptr,type,member)
#define hlist_for_each(pos, head) \
for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \
pos = pos->next)
#define hlist_for_each_safe(pos, n, head) \
for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \
pos = n)
/**
* hlist_for_each_entry - iterate over list of given type
* @tpos: the type * to use as a loop cursor.
* @pos: the &struct hlist_node to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry(tpos, pos, head, member) \
for (pos = (head)->first; \
pos && ({ prefetch(pos->next); 1;}) && \
({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
pos = pos->next)
/**
* hlist_for_each_entry_continue - iterate over a hlist continuing after current point
* @tpos: the type * to use as a loop cursor.
* @pos: the &struct hlist_node to use as a loop cursor.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry_continue(tpos, pos, member) \
for (pos = (pos)->next; \
pos && ({ prefetch(pos->next); 1;}) && \
({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
pos = pos->next)
/**
* hlist_for_each_entry_from - iterate over a hlist continuing from current point
* @tpos: the type * to use as a loop cursor.
* @pos: the &struct hlist_node to use as a loop cursor.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry_from(tpos, pos, member) \
for (; pos && ({ prefetch(pos->next); 1;}) && \
({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
pos = pos->next)
/**
* hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry
* @tpos: the type * to use as a loop cursor.
* @pos: the &struct hlist_node to use as a loop cursor.
* @n: another &struct hlist_node to use as temporary storage
* @head: the head for your list.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry_safe(tpos, pos, n, head, member) \
for (pos = (head)->first; \
pos && ({ n = pos->next; 1; }) && \
({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
pos = n)
#endif

@ -0,0 +1,116 @@
/******************************************************************************
* file include/memory.h
* author YuLiang
* version 1.0.0
* date 10-Sep-2021
* brief This file provides all the headers of the memory functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _MEMORY_H_
#define _MEMORY_H_
/* Includes ------------------------------------------------------------------*/
#define MTYPE_MEMSTR_LEN 20
/* Define --------------------------------------------------------------------*/
enum
{
MTYPE_CLI = 1,
MTYPE_BUF,
MTYPE_BUF_DATA,
MTYPE_BUF_TMP,
MTYPE_VTY,
MTYPE_VTY_TMP,
MTYPE_VTY_OUT_BUF,
MTYPE_VTY_HIST,
MTYPE_LOG,
MTYPE_PREFIX,
MTYPE_THREAD_MONITOR,
MTYPE_MTIMER,
MTYPE_HASH,
MTYPE_HASH_BACKET,
MTYPE_HASH_INDEX,
MTYPE_THREAD,
MTYPE_THREAD_STATS,
MTYPE_THREAD_MASTER,
MTYPE_THREAD_FUNCNAME,
MTYPE_FIFO,
MTYPE_GPIO,
MTYPE_CA_COLL,
MTYPE_CA_DB,
MTYPE_CA_MQTT,
MTYPE_MAX,
};
/* Exported types ------------------------------------------------------------*/
/* For pretty printing of memory allocate information. */
typedef struct _mem_node
{
int32_t index;
const char *format;
} mem_node_t;
typedef struct _mem_list
{
mem_node_t *nodes;
const char *name;
} mem_list_t;
/* Exported macro ------------------------------------------------------------*/
#define XMALLOC(mtype, size) \
mtype_x_malloc (__FILE__, __LINE__, (mtype), (size))
#define XMALLOC_Q(mtype, size) \
mtype_x_malloc_q (__FILE__, __LINE__, (mtype), (size))
#define XCALLOC(mtype, size) \
mtype_x_calloc (__FILE__, __LINE__, (mtype), (size))
#define XREALLOC(mtype, ptr, size) \
mtype_x_realloc (__FILE__, __LINE__, (mtype), (ptr), (size))
#define XFREE(mtype, ptr) \
do { \
mtype_x_free (__FILE__, __LINE__, (mtype), (ptr)); \
ptr = NULL; } \
while (0)
#define XSTRDUP(mtype, str) \
mtype_x_strdup (__FILE__, __LINE__, (mtype), (str))
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern void *mtype_x_malloc(const char *file, int32_t line, int32_t type, size_t size);
extern void *mtype_x_malloc_q(const char *file, int32_t line, int32_t type, size_t size);
extern void *mtype_x_calloc(const char *file, int32_t line, int32_t type, size_t size);
extern void *mtype_x_realloc(const char *file, int32_t line, int32_t type, void *ptr, size_t size);
extern void mtype_x_free(const char *file, int32_t line, int32_t type, void *ptr);
extern char *mtype_x_strdup(const char *file, int32_t line, int32_t type, const char *str);
extern void mtype_init(void);
extern void mtype_init_befor(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,72 @@
/*****************************************************************************
* file include/mtimer.h
* author YuLiang
* version 1.0.0
* date 22-Sep-2021
* brief This file provides all the headers of the timer functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __MTIMER_H__
#define __MTIMER_H__
/* Includes ------------------------------------------------------------------*/
#include <pthread.h>
/* Define --------------------------------------------------------------------*/
/* 以太网连接类型类型. */
typedef enum
{
MTIMER_S_STOP = 0,
MTIMER_S_RUN,
} MTIMER_STATE_E;
/* Exported types ------------------------------------------------------------*/
typedef void* (*MTIMER_CALLBACK)(void *arg);
/* 定时器属性结构体. */
typedef struct _mtimer_t
{
MTIMER_CALLBACK handle; /* 回调函数 */
void *arg; /* 运行参数 */
char name[DEV_NAME_STR_LEN]; /* 定时器名字 */
uint16_t interval; /* 间隔时间s */
uint32_t time; /* 加入定时器的时间 */
} mtimer_t;
/* Extern global variables ---------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
extern int32_t mtimer_add(MTIMER_CALLBACK func, void *arg, uint16_t interval, char *name);
extern int32_t mtimer_init(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,58 @@
/*****************************************************************************
* file include/process.h
* author YuLiang
* version 1.0.0
* date 26-Sep-2021
* brief This file provides all the headers of the process functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __PROCESS_H__
#define __PROCESS_H__
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* 消息队列类型. */
typedef enum
{
MSG_TYPE_DAU_RECV = 5, /* 1-4 固定被 DAU 发送线程使用, 这里从 5 开始. */
MSG_TYPE_COUNT,
} MSG_TYPE_E;
/* Extern global variables ---------------------------------------------------*/
extern uint32_t start_time;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,230 @@
/******************************************************************************
* file include/sockunion.h
* author YuLiang
* version 1.0.0
* date 09-Oct-2021
* brief This file provides all the headers of the sockunion functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _SOCKUNION_H_
#define _SOCKUNION_H_
/* Includes ------------------------------------------------------------------*/
/* Define --------------------------------------------------------------------*/
#define IPV4_MAX_BITLEN 32
#define IPV6_MAX_BITLEN 128
#define PNBBY 8
#define AFI_IP 1
#define AFI_IP6 2
#define AFI_MAX 3
#define SU_ADDRSTRLEN 46
/* Default address family. */
#ifdef HAVE_IPV6
#define AF_INET_UNION AF_INET6
#else
#define AF_INET_UNION AF_INET
#endif
/* Exported types ------------------------------------------------------------*/
/* IPv4 and IPv6 unified prefix structure. */
typedef struct _prefix
{
uint8_t family;
uint8_t prefixlen;
union
{
uint8_t prefix;
struct in_addr prefix4;
#ifdef HAVE_IPV6
struct in6_addr prefix6;
#endif /* HAVE_IPV6 */
struct
{
struct in_addr id;
struct in_addr adv_router;
} lp;
uint8_t val[8];
} u __attribute__ ((aligned (8)));
} prefix_t;
/* IPv4 prefix structure. */
typedef struct _prefix_ipv4
{
uint8_t family;
uint8_t prefixlen;
struct in_addr prefix __attribute__ ((aligned (8)));
} prefix_ipv4_t;
/* IPv6 prefix structure. */
#ifdef HAVE_IPV6
typedef struct _prefix_ipv6
{
uint8_t family;
uint8_t prefixlen;
struct in6_addr prefix __attribute__ ((aligned (8)));
} prefix_ipv6_t;
#endif /* HAVE_IPV6 */
typedef enum
{
ACCESS_TYPE_STRING,
ACCESS_TYPE_NUMBER
} ACCESS_TYPE_E;
/* Filter type is made by `permit', `deny' and `dynamic'. */
typedef enum
{
FILTER_DENY,
FILTER_PERMIT,
FILTER_DYNAMIC
} FILTER_TYPE_E;
/* List of access_list. */
typedef struct
{
struct _access_list *head;
struct _access_list *tail;
} access_list_list_t;
/* Master structure of access_list. */
typedef struct
{
/* List of access_list which name is number. */
access_list_list_t num;
/* List of access_list which name is string. */
access_list_list_t str;
/* Hook function which is executed when new access_list is added. */
void (*add_hook)(struct _access_list *);
/* Hook function which is executed when access_list is deleted. */
void (*delete_hook)(struct _access_list *);
} access_master_t;
typedef struct
{
/* Cisco access-list */
int extended;
struct in_addr addr;
struct in_addr addr_mask;
struct in_addr mask;
struct in_addr mask_mask;
} filter_cisco_t;
typedef struct
{
/* If this filter is "exact" match then this flag is set. */
int exact;
/* Prefix information. */
prefix_t prefix;
} filter_zebra_t;
/* Filter element of access list */
typedef struct _filter
{
/* For doubly linked list. */
struct _filter *next;
struct _filter *prev;
/* Filter type information. */
FILTER_TYPE_E type;
/* Cisco access-list */
int cisco;
union
{
filter_cisco_t cfilter;
filter_zebra_t zfilter;
} u;
} filter_t;
/* Access list */
typedef struct _access_list
{
char *name;
char *remark;
access_master_t *master;
ACCESS_TYPE_E type;
struct _access_list *next;
struct _access_list *prev;
filter_t *head;
filter_t *tail;
} access_list_t;
typedef union
{
struct sockaddr sa;
struct sockaddr_in sin;
#ifdef HAVE_IPV6
struct sockaddr_in6 sin6;
#endif /* HAVE_IPV6 */
} SOCKUNION_U;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern void prefix_free(prefix_t *p);
extern prefix_ipv4_t *prefix_ipv4_new(void);
#ifdef HAVE_IPV6
extern prefix_ipv6_t *prefix_ipv6_new(void);
#endif /* HAVE_IPV6 */
extern access_list_t *access_list_lookup(uint16_t afi, const char *name);
extern FILTER_TYPE_E access_list_apply(access_list_t *access, void *object);
extern void masklen2ip(int masklen, struct in_addr *netmask);
extern int prefix_match(const prefix_t *n, const prefix_t *p);
extern int str2sockunion(const char *str, SOCKUNION_U *su);
extern const char *sockunion2str(SOCKUNION_U *su, char *buf, size_t len);
extern int sockunion_accept(int sock, SOCKUNION_U *su);
extern int set_nonblocking(int fd);
extern prefix_t *sockunion2hostprefix(const SOCKUNION_U *su);
extern char *sockunion_su2str(SOCKUNION_U *su);
extern int sockunion_stream_socket(SOCKUNION_U *su);
extern int sockunion_reuseaddr(int sock);
extern int sockunion_bind(int sock, SOCKUNION_U *su, unsigned short port, SOCKUNION_U *su_addr);
extern int sockunion_ip_set(char *name, unsigned int addr);
extern int sockunion_mask_set(char *name, unsigned int mask);
extern int sockunion_gw_set(char *name, unsigned int gateway, unsigned int gateway_old);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,64 @@
/*****************************************************************************
* file include/thread_monitor.h
* author YuLiang
* version 1.0.0
* date 08-Oct-2021
* brief This file provides all the headers of the thread monitor functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef __THREAD_M_H__
#define __THREAD_M_H__
/* Includes ------------------------------------------------------------------*/
#include <pthread.h>
/* Define --------------------------------------------------------------------*/
#define THREAD_M_NAME_LEN 32
/* Exported types ------------------------------------------------------------*/
/* 线程监控结构体. */
typedef struct _thread_m_t
{
char name[THREAD_M_NAME_LEN]; /* 线程名字 */
pthread_t pid; /* 线程pid */
int8_t alive; /* 是否活着 */
} thread_m_t;
/* Extern global variables ---------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
extern int32_t thread_m_add(char *str, pthread_t pid);
extern int32_t thread_m_init(void);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,154 @@
/*************************************************
Copyright (C), 2023--
: typedef.h
: wangbo
: 2023-08-24
:
:
:
1:
: 2023-08-24
: wangbo
:
*************************************************/
#ifndef _TPYEDEF_H
#define _TPYEDEF_H
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <fcntl.h>
//#include <stdint.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <time.h>
#include <signal.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
#include <math.h>
#include <fnmatch.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/file.h> // flock函数
/************************************************************************
************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/utsname.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h> // tcp keepalive
#include <netinet/ip_icmp.h>
#include <netpacket/packet.h>
#include <net/ethernet.h>
#include <net/if_arp.h>
#include <netdb.h>
#include <arpa/inet.h>
#define ZERO_INIT {}
#define NFDS_FOR_SELECT(sock) ((sock) + 1)
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef SUCCESS
#define SUCCESS 0
#endif
#ifndef FAILURE
#define FAILURE -1
#endif
// 整型环境, 内核使用的类型
typedef char s8;
typedef unsigned char u8;
typedef short s16;
typedef unsigned short u16;
typedef int s32;
typedef unsigned int u32;
#if defined WIN32
typedef __int64 s64;
typedef unsigned __int64 u64;
#else
typedef long long s64;
typedef unsigned long long u64;
#endif
typedef int TIMER_T;
typedef int socket_t;
typedef pid_t ThreadId_T;
typedef pid_t ProcessId_T; /// < 进程id
typedef pthread_t Thread_T;
typedef pid_t Process_T;
typedef void * ThreadResult_T;
typedef void * ThreadParam_T;
typedef unsigned int TimeTick_T;
typedef int DevHandle_T;
typedef int Semaphore_T;
#define ThreadProcSpec
#define INVALID_THREAD (Thread_T)(~0)
#define INVALID_SOCKET (~0)
#define INVALID_TIMER (-1)
typedef pthread_mutex_t Mutex_T;
/// @brief 线程函数指针类型
typedef ThreadResult_T (ThreadProcSpec* ThreadProc_T)(ThreadParam_T param);
// max / min
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a,b) ((a) > (b) ? (b) : (a))
#endif
#ifndef setbitEx
#ifndef NBBYTE //the BSD family defines NBBY
#define NBBYTE 8 //8 bits per byte
#endif
#define setbit(a, i) (((unsigned char *)a)[(i)/NBBYTE] |= 1<<((i)%NBBYTE))
#define clrbit(a, i) (((unsigned char *)a)[(i)/NBBYTE] &= ~(1<<((i)%NBBYTE)))
#define isset(a, i) (((const unsigned char *)a)[(i)/NBBYTE] & (1<<((i)%NBBYTE)))
#define isclr(a, i) ((((const unsigned char *)a)[(i)/NBBYTE] & (1<<((i)%NBBYTE))) == 0)
#endif
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /*_TPYEDEF_H*/

@ -0,0 +1,331 @@
/******************************************************************************
* file include/vty.h
* author YuLiang
* version 1.0.0
* date 10-Sep-2021
* brief This file provides all the headers of the vty functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#ifndef _VTY_H_
#define _VTY_H_
/* Includes ------------------------------------------------------------------*/
#include <sys/resource.h>
#include "array.h"
/* Define --------------------------------------------------------------------*/
/* Thread types. */
#define THREAD_READ 0
#define THREAD_WRITE 1
#define THREAD_TIMER 2
#define THREAD_EVENT 3
#define THREAD_READY 4
#define THREAD_BACKGROUND 5
#define THREAD_UNUSED 6
#define THREAD_PERFORM 7
/* Struct timeval's tv_usec one second value. */
#define TIMER_SECOND_MICRO 1000000L
#define RUSAGE_T rusage_t
#define GETRUSAGE(X) thread_getrusage(X)
#define THREAD_ADD_READ(m,f,a,v) thread_add_read(m,f,a,v,#f)
#define THREAD_ADD_WRITE(m,f,a,v) thread_add_write(m,f,a,v,#f)
#define THREAD_ADD_TIMER(m,f,a,v) thread_add_timer(m,f,a,v,#f)
#define THREAD_ADD_TIMER_MSEC(m,f,a,v) thread_add_timer_msec(m,f,a,v,#f)
#define THREAD_ADD_EVENT(m,f,a,v) thread_add_event(m,f,a,v,#f)
#define THREAD_EXECUTE(m,f,a,v) thread_execute(m,f,a,v,#f)
/* Macros. */
#define THREAD_ARG(X) ((X)->arg)
#define THREAD_FD(X) ((X)->u.fd)
#define THREAD_VAL(X) ((X)->u.val)
#define VTY_BUFSIZ 512
#define VTY_TMP_BUFSIZ 1024
#define VTY_MAXHIST 20
#define TELNET_NAWS_SB_LEN 5
#define VTY_TIMEOUT_VAL 600
/* Vty read buffer size. */
#define VTY_READ_BUFSIZ 512
/* Small macro to determine newline is newline only or linefeed needed. */
#define VTY_NEWLINE ((vty->type == VTY_TERM) ? "\r\n" : "\n")
#define CONTROL(X) ((X) - '@')
#define VTY_NO_ESCAPE 0
#define VTY_PRE_ESCAPE 1
#define VTY_ESCAPE 2
#define VTY_USERNAME_LEN 32
#define VTY_USERNAME_DEFAULT "ld"
#define VTY_PASSWORD_DEFAULT "1"
/* Exported types ------------------------------------------------------------*/
/* buffer数据结构体. 必须保证: 0 <= sp <= cp <= size. */
typedef struct _buf_data
{
struct _buf_data *next; /* 数据链表. */
size_t cp; /* 当前可以添加的数据索引. */
size_t sp; /* 等待数据发送的数据索引. */
unsigned char data[]; /* 数据空间. */
} buf_data_t;
/* Buffer结构体. */
typedef struct _buf
{
buf_data_t *head; /* 数据块头. */
buf_data_t *tail; /* 数据块尾. */
size_t size; /* 每个数据块的大小. */
} buf_t;
typedef int hash_key_f(void*);
typedef void* hash_alloc_f(void *);
typedef int hash_cmp_f(const void*, const void*);
typedef struct _hash_backet
{
struct _hash_backet *next; /* Linked list. */
unsigned int key; /* Hash key. */
void *data; /* Data. */
} hash_backet_t;
typedef struct _hash
{
hash_backet_t **index; /* Hash backet. */
unsigned int size; /* Hash table size. */
hash_key_f *hash_key; /* Key make function. */
hash_cmp_f *hash_cmp; /* Data compare function. */
unsigned long count; /* Backet alloc. */
} hash_t;
typedef unsigned char thread_type;
typedef struct _rusage
{
struct rusage cpu;
struct timeval real;
} rusage_t;
typedef struct _time_stats
{
unsigned long total, max;
} time_stats_t;
typedef struct _cpu_thread_history
{
int (*func)(void*);
char *funcname;
unsigned int total_calls;
time_stats_t real;
time_stats_t cpu;
thread_type types;
} cpu_thread_history_t;
/* Linked list of thread. */
typedef struct _thread_list
{
struct _thread *head;
struct _thread *tail;
int count;
} thread_list_t;
/* Master of the theads. */
typedef struct _thread_master
{
thread_list_t read;
thread_list_t write;
thread_list_t timer;
thread_list_t event;
thread_list_t ready;
thread_list_t unuse;
thread_list_t background;
fd_set readfd;
fd_set writefd;
fd_set exceptfd;
unsigned long alloc;
} thread_master_t;
/* Thread itself. */
typedef struct _thread
{
thread_type type; /* thread type */
thread_type add_type; /* thread type */
struct _thread *next; /* next pointer of the thread */
struct _thread *prev; /* previous pointer of the thread */
thread_master_t *master; /* pointer to the struct thread_master. */
int (*func)(struct _thread*); /* event function */
void *arg; /* event argument */
union
{
int val; /* second argument of the event. */
int fd; /* file descriptor in case of read/write. */
struct timeval sands; /* rest of time sands value. */
} u;
RUSAGE_T ru; /* Indepth usage info. */
cpu_thread_history_t *hist; /* cache pointer to cpu_history */
char* funcname;
} thread_t;
typedef int thread_func_f(thread_t*);
typedef enum {VTY_TERM, VTY_FILE, VTY_SHELL, VTY_SHELL_SERV, VTY_CMD} VTY_TYPE_E;
typedef enum {VTY_NORMAL, VTY_CLOSE, VTY_MORE, VTY_MORELINE} VTY_STAT_E;
/* Vty events */
typedef enum
{
VTY_SERV,
VTY_READ,
VTY_WRITE,
VTY_TIMEOUT_RESET,
#if 0
VTYSH_SERV,
VTYSH_READ,
VTYSH_WRITE
#endif /* VTYSH */
} VTY_EVENT_E;
/* 用户结构体 */
typedef struct
{
char username[VTY_USERNAME_LEN];
char password[VTY_USERNAME_LEN];
uint8_t level; /* 用户等级 */
} vty_user_t;
/* VTY struct. */
typedef struct
{
int fd; /* File descripter of this vty. */
VTY_TYPE_E type; /* Is this vty connect to file or not */
uint32_t node; /* Node status of this vty */
char *address; /* What address is this vty comming from. */
uint32_t fail_count; /* Failure count */
buf_t *out_buf; /* Output buffer. */
char *buf; /* Command input buffer */
uint32_t cp; /* Command cursor point */
uint32_t length; /* Command length */
uint32_t max; /* Command max length. */
char *hist[VTY_MAXHIST]; /* Histry of command */
uint32_t hp; /* History lookup current point */
uint32_t hindex; /* History insert end point */
void *index; /* For current referencing point of interface, route-map, access-list etc... */
void *index_sub; /* For multiple level index treatment such as key chain and key. */
unsigned char escape; /* For escape character. */
VTY_STAT_E status; /* Current vty status. */
/* IAC handling: was the last character received the
IAC (interpret-as-command) escape character (and therefore the next
character will be the command code)? Refer to Telnet RFC 854. */
unsigned char iac;
unsigned char iac_sb_in_progress; /* IAC SB (option subnegotiation) handling */
/* At the moment, we care only about the NAWS (window size) negotiation,
and that requires just a 5-character buffer (RFC 1073):
<NAWS char> <16-bit width> <16-bit height> */
unsigned char sb_buf[TELNET_NAWS_SB_LEN];
/* How many subnegotiation characters have we received? We just drop
those that do not fit in the buffer. */
size_t sb_len;
uint32_t width; /* Window width/height. */
uint32_t height;
int32_t lines; /* Configure lines. */
int32_t monitor; /* Terminal monitor. */
int config; /* In configure mode. */
/* Read and write thread. */
thread_t *t_read;
thread_t *t_write;
/* Timeout seconds and thread. */
unsigned long v_timeout;
thread_t *t_timeout;
/* Timeout seconds and thread. */
vty_user_t user;
} vty_t;
/* Exported macro ------------------------------------------------------------*/
/* Extern global variables ---------------------------------------------------*/
/* Extern functions ----------------------------------------------------------*/
extern void *hash_get(hash_t *hash, void *data, hash_alloc_f alloc_func);
extern unsigned long thread_consumed_time(RUSAGE_T *now,RUSAGE_T *start, unsigned long *cputime);
extern thread_master_t *thread_master_create();
extern void thread_call(thread_t *thread);
extern thread_t *thread_add_read(thread_master_t *m, thread_func_f *func, void *arg, int fd, const char* funcname);
extern thread_t *thread_add_write(thread_master_t *m, thread_func_f *func, void *arg, int fd, const char* funcname);
extern thread_t *thread_add_timer(thread_master_t *m, thread_func_f *func, void *arg, long timer, const char* funcname);
extern thread_t *thread_add_timer_msec(thread_master_t *m, thread_func_f *func, void *arg, long timer, const char* funcname);
extern thread_t *thread_add_background(thread_master_t *m, thread_func_f *func, void *arg, long delay, const char *funcname);
extern thread_t *thread_add_event(thread_master_t *m, thread_func_f *func, void *arg, int val, const char* funcname);
extern thread_t *thread_execute(thread_master_t *m, thread_func_f *func, void *arg, int val, const char* funcname);
extern void thread_cancel(thread_t *thread);
extern thread_t *thread_fetch(thread_master_t *m, thread_t *fetch);
extern int vty_out(vty_t *vty, const char *format, ...);
extern vty_t *vty_create();
extern int vty_execute(vty_t *vty);
extern int vty_config_lock(vty_t *vty);
extern int vty_config_unlock(vty_t *vty);
extern void vty_question(vty_t *vty, array_t *cmd_line);
extern void vty_print_word(vty_t *vty, char *strs[]);
extern void vty_free_match_strs(char *match_strs[]);
extern void vty_will_echo(vty_t *vty);
extern void vty_will_suppress_go_ahead(vty_t *vty);
extern void vty_dont_linemode(vty_t *vty);
extern void vty_do_window_size(vty_t *vty);
extern void vty_prompt(vty_t *vty);
extern void vty_close(vty_t *vty);
extern void vty_init(void);
extern void vty_event(VTY_EVENT_E event, int sock, vty_t *vty);
extern void vty_log(const char *level, const char *proto_str, const char *format, char *time_str, va_list va);
extern void vty_print(const char *format, va_list va);
extern void vty_serv_sock_family(const char* addr, unsigned short port, int family);
extern void vty_reset(void);
extern void vty_version_print(vty_t *vty);
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

File diff suppressed because it is too large Load Diff

@ -0,0 +1,444 @@
/*****************************************************************************
* file lib/process/ca_db.c
* author YuLiang
* version 1.0.0
* date 29-Nov-2023
* brief This file provides all the database related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef CFG_DEV_TYPE_LAND_CA
/* 标准 C 库头文件 */
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <execinfo.h>
/* 私有头文件 */
#include <sqlite3.h>
#include "cmd.h"
#include "fifo.h"
#include "ca_db.h"
#include "ca_collect.h"
/* Private define ------------------------------------------------------------*/
#define CA_DB_NAME_LEN 64
#define CA_DB_FIFO "CA_DB_FIFO"
#define CA_DB_BUF_LEN 2048
#define CA_DB_WR_CNT 500 // 写 500 次数据库进行一次数据库清理
#define CA_DB_LOCK pthread_mutex_lock(&ca_db_ctrl.mutex)
#define CA_DB_UNLOCK pthread_mutex_unlock(&ca_db_ctrl.mutex)
/* Private typedef -----------------------------------------------------------*/
/* fifo 数据结构 */
typedef struct
{
uint32_t type; // 数据类型
void *data; // 数据
} ca_db_msg_t;
/* 数据库模块属性结构体 */
typedef struct
{
char filename[CA_DB_NAME_LEN]; // 数据库名字
sqlite3 *db; // 数据库指针
int32_t fifo_id; // fifo id
int32_t cnt; // 写入计数
char str[CA_DB_BUF_LEN]; // 操作 buf
pthread_mutex_t mutex; // 数据库读写互斥锁
} ca_db_ctrl_t;
/* Private function prototypes -----------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
ca_db_ctrl_t ca_db_ctrl; // 数据库全局控制结构体
/* Internal functions --------------------------------------------------------*/
/* description: 显示历史环流数据
param:
return: CMD_XXX */
CMD(ca_db_show_data,
ca_db_show_data_cmd,
"show db offset <1-5000> num <1-5000>",
"Show\n"
"Database\n"
"Offset\n"
"Offset index\n"
"Number\n"
"Number\n")
{
uint16_t index = strtol(argv[0], NULL, 10) - 1;
uint16_t num = strtol(argv[1], NULL, 10);
ca_db_show_data_by_index(index, num);
return CMD_SUCCESS;
}
/* description: 将数据按照格式串口打印
param: argv -
return: E_XXX */
int _ca_db_show_data(void *data, int argc, char **argv, char **azColName)
{
ca_coll_dev_data_t d;
float temp = 0;
uint8_t i = 0;
uint8_t k = 0;
k = 2;
d.vin = strtol(argv[k++], NULL, 10);
d.vbat = strtol(argv[k++], NULL, 10);
d.vsc = strtol(argv[k++], NULL, 10);
d.temperature = strtol(argv[k++], NULL, 10);
d.run_time = strtol(argv[k++], NULL, 10);
d.energy_mode = strtol(argv[k++], NULL, 10);
d.CSQ = strtol(argv[k++], NULL, 10);
for(i = 0; i < CA_COLL_ADC_CH_SUM; i++)
{
d.elec[i] = strtol(argv[k++], NULL, 10);
}
d.sen_short = strtol(argv[k++], NULL, 10);
for(i = 0; i < CA_COLL_SENSOR_SUM; i++)
{
d.sen_temp[i] = strtol(argv[k++], NULL, 10);
d.sen_x[i] = strtol(argv[k++], NULL, 10);
d.sen_y[i] = strtol(argv[k++], NULL, 10);
d.sen_z[i] = strtol(argv[k++], NULL, 10);
}
printh("ID %s UTC %s\r\n", argv[0], argv[1]);
printh("VCC %-0.3fv VBAT %-0.3fv VSC %-0.3fv ", d.vin / 1000.0, d.vbat / 1000.0, d.vsc / 1000.0);
printh("Temperature %-0.1f℃ Run %ds Mode %d ", d.temperature / 10.0, d.run_time,d.energy_mode);
printh("Short %s\r\n", d.sen_short ? "TRUE" : "FALSE");
printh("Electricity(v): ");
for(i = 0; i < CA_COLL_ADC_CH_SUM - 2; i++)
{
printh("%-8.3f ", d.elec[i] / 1000.0);
}
printh("\r\n");
printh("Sensor temperature(℃): ");
for(i = 0; i < CA_COLL_SENSOR_SUM; i++)
{
temp = d.sen_temp[i] / 10.0;
printh("%-5.1f ", temp);
}
printh("\r\n");
printh("Sensor x: ");
for(i = 0; i < CA_COLL_SENSOR_SUM; i++)
{
printh("%-5d ", d.sen_x[i]);
}
printh("\r\n");
printh("Sensor y: ");
for(i = 0; i < CA_COLL_SENSOR_SUM; i++)
{
printh("%-5d ", d.sen_y[i]);
}
printh("\r\n");
printh("Sensor z: ");
for(i = 0; i < CA_COLL_SENSOR_SUM; i++)
{
printh("%-5d ", d.sen_z[i]);
}
printh("\r\n\n");
return 0;
}
/* description: 删除多余的数据保留 5000 条
param: argv -
return: E_XXX */
int32_t _ca_db_clean(void)
{
ca_db_ctrl_t *log = &ca_db_ctrl;
char *zErrMsg = NULL;
/* 删除小于比最大 id 小 5000 的数据, 即保留 id 最大的 5000 条数据 */
snprintf(log->str, CA_DB_BUF_LEN, "delete from cable_data where id<(select Max(id) from cable_data)-5000;");
if (sqlite3_exec(log->db, log->str, 0, 0, &zErrMsg) != SQLITE_OK)
{
DBG(DBG_M_CA_DB_ERR, "SQL DELETE ERR: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
return E_SYS_CALL;
}
return E_NONE;
}
/* description: 将历史数据写入数据库
param: data -
return: E_XXX */
int32_t _ca_db_data_write(ca_coll_dev_data_t *data)
{
struct tm *day = NULL;
char *zErrMsg = NULL;
char *str = ca_db_ctrl.str;
char time_str[TIME_STR_LEN] = {0};
uint16_t len = 0;
time_t utc = 0;
utc = time(NULL);
day = localtime(&utc);
strftime(time_str, TIME_STR_LEN, "%Y/%m/%d %H:%M:%S", day);
CA_DB_LOCK;
len = snprintf(str, CA_DB_BUF_LEN, "INSERT INTO cable_data VALUES (NULL, \"%s\", %d, %d, %d, %d, %d, %d, %d, ", \
time_str, data->vin, data->vbat, data->vsc, data->temperature, data->run_time, data->energy_mode, data->CSQ);
len += snprintf(str + len, CA_DB_BUF_LEN - len, "%d, %d, %d, %d, %d, %d, %d, %d, ", \
data->elec[0], data->elec[1], data->elec[2], data->elec[3], data->elec[4], data->elec[5], data->elec[6], data->elec[7]);
len += snprintf(str + len, CA_DB_BUF_LEN - len, "%d, %d, %d, %d, %d, %d, %d, %d, %d, ", \
data->sen_short, data->sen_temp[0], data->sen_x[0], data->sen_y[0], data->sen_z[0], data->sen_temp[1], data->sen_x[1], data->sen_y[1], data->sen_z[1]);
len += snprintf(str + len, CA_DB_BUF_LEN - len, "%d, %d, %d, %d, %d, %d, %d, %d, ", \
data->sen_temp[2], data->sen_x[2], data->sen_y[2], data->sen_z[2], data->sen_temp[3], data->sen_x[3], data->sen_y[3], data->sen_z[3]);
len += snprintf(str + len, CA_DB_BUF_LEN - len, "%d, %d, %d, %d, %d, %d, %d, %d, ", \
data->sen_temp[4], data->sen_x[4], data->sen_y[4], data->sen_z[4], data->sen_temp[5], data->sen_x[5], data->sen_y[5], data->sen_z[5]);
len += snprintf(str + len, CA_DB_BUF_LEN - len, "%d, %d, %d, %d, %d, %d, %d, %d);", \
data->sen_temp[6], data->sen_x[6], data->sen_y[6], data->sen_z[6], data->sen_temp[7], data->sen_x[7], data->sen_y[7], data->sen_z[7]);
if (sqlite3_exec(ca_db_ctrl.db, str, 0, 0, &zErrMsg ) != SQLITE_OK)
{
DBG(DBG_M_CA_DB_ERR, "SQL INSERT error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
return E_SYS_CALL;
}
/* 保证数据库大小不超过 5000 */
ca_db_ctrl.cnt++;
if (ca_db_ctrl.cnt >= CA_DB_WR_CNT)
{
_ca_db_clean();
ca_db_ctrl.cnt = 0;
}
CA_DB_UNLOCK;
return E_NONE;
}
/* description: 写数据库线程
param:
return: */
void *_ca_db_handle_write(void *arg)
{
ca_db_msg_t *recv_msg = NULL;
while(1)
{
/* 等待数据 */
if (fifo_read(ca_db_ctrl.fifo_id, (void **)&recv_msg) != 0)
{
DBG(DBG_M_CA_DB_ERR, "ERROR at fifo read!\r\n");
continue;
}
/* 处理数据 */
switch(recv_msg->type)
{
case CA_DB_T_DATA:
_ca_db_data_write((ca_coll_dev_data_t*)recv_msg->data);
break;
default:
break;
}
/* 释放数据 */
XFREE(MTYPE_CA_DB, recv_msg->data);
fifo_push(ca_db_ctrl.fifo_id);
}
return NULL;
}
/* Interface functions -------------------------------------------------------*/
/* description: 数据库处理预初始化.
param:
return: E_XXX */
int32_t ca_db_init(void)
{
ca_db_ctrl_t *log = &ca_db_ctrl;
int32_t rv = 0;
char *zErrMsg = NULL;
/* 打开数据库 */
snprintf(log->filename, CA_DB_NAME_LEN, CA_DB_FILE);
rv = sqlite3_open(log->filename, &log->db);
if (rv)
{
log->db = NULL;
log_err(LOG_CA_DB, "Can't open database!");
return E_SYS_CALL;
}
/* 创建历史数据表 */
snprintf(log->str, CA_DB_BUF_LEN, \
"CREATE TABLE IF NOT EXISTS cable_data(ID INTEGER PRIMARY KEY AUTOINCREMENT," \
"UTC TEXT, VIN INTEGER, VBAT INTEGER, VSC INTEGER, TEMP INTEGER, RUN INTEGER, MODE INTEGER, CSQ INTEGER," \
"ELEC1 INTEGER, ELEC2 INTEGER, ELEC3 INTEGER, ELEC4 INTEGER, ELEC5 INTEGER, ELEC6 INTEGER, ELEC7 INTEGER, ELEC8 INTEGER," \
"SEN_S INTEGER, SEN1_T INTEGER, SEN1_X INTEGER, SEN1_Y INTEGER, SEN1_Z INTEGER, SEN2_T INTEGER, SEN2_X INTEGER, SEN2_Y INTEGER, SEN2_Z INTEGER," \
"SEN3_T INTEGER, SEN3_X INTEGER, SEN3_Y INTEGER, SEN3_Z INTEGER, SEN4_T INTEGER, SEN4_X INTEGER, SEN4_Y INTEGER, SEN4_Z INTEGER," \
"SEN5_T INTEGER, SEN5_X INTEGER, SEN5_Y INTEGER, SEN5_Z INTEGER, SEN6_T INTEGER, SEN6_X INTEGER, SEN6_Y INTEGER, SEN6_Z INTEGER," \
"SEN7_T INTEGER, SEN7_X INTEGER, SEN7_Y INTEGER, SEN7_Z INTEGER, SEN8_T INTEGER, SEN8_X INTEGER, SEN8_Y INTEGER, SEN8_Z INTEGER);");
if (sqlite3_exec(log->db, log->str, 0, 0, &zErrMsg) != SQLITE_OK)
{
log_err(LOG_CA_DB, "SQL create error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
return E_SYS_CALL;
}
/* 维持数据库大小 */
_ca_db_clean();
/* 添加命令行 */
cmd_install_element(COMMON_NODE, &ca_db_show_data_cmd);
return E_NONE;
}
/* description: 数据库处理初始化.
param:
return: E_XXX */
int32_t ca_db_init_after(void)
{
struct sched_param param;
pthread_attr_t attr;
pthread_t pid;
ca_db_ctrl_t *db = &ca_db_ctrl;
int rv = 0;
/* 舒适化线程锁, 保证只有数据库单线程操作 */
pthread_mutex_init(&db->mutex, NULL);
/* 初始化 fifo */
db->fifo_id = fifo_create(CA_DB_FIFO, 32);
if (db->fifo_id < 0)
{
log_err(LOG_CA_DB, "Open fifo " CA_DB_FIFO " error.");
return E_ERROR;
}
/* 创建数据库造作线程, 配置线程RR调度优先级25 */
pthread_attr_init(&attr);
param.sched_priority = 25;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, &param);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
rv = pthread_create(&pid, &attr, _ca_db_handle_write, NULL);
if (rv != 0)
{
log_err(LOG_CA_DB, "Can't create cable db pthread %d.", rv);
return E_SYS_CALL;
}
else
{
thread_m_add("CA_DB_THREAD", pid);
}
pthread_attr_destroy(&attr);
return E_NONE;
}
/* description: 写数据库
param: type -
data -
return: E_XXX */
int32_t ca_db_write(uint32_t type, void *data)
{
ca_db_msg_t msg;
void *pkt = NULL;
/* 申请报文空间 */
if (CA_DB_T_DATA == type)
{
pkt = XMALLOC_Q(MTYPE_CA_DB, sizeof(ca_coll_dev_data_t));
if (!pkt)
{
DBG(DBG_M_CA_DB_ERR, "Malloc ERR!\r\n");
return E_MEM;
}
/* 封装消息. */
memcpy(pkt, data, sizeof(ca_coll_dev_data_t));
}
msg.type = type;
msg.data = pkt;
if (fifo_write(ca_db_ctrl.fifo_id, (void*)(&msg), sizeof(ca_db_msg_t)) != sizeof(ca_db_msg_t))
{
DBG(DBG_M_CA_DB_ERR, "Fifo write ERROR\r\n");
XFREE(MTYPE_CA_DB, pkt);
return E_ERROR;
}
return E_NONE;
}
/* description: 显示据库数据
param: index -
num -
return: */
void ca_db_show_data_by_index(uint16_t index, uint16_t num)
{
ca_db_ctrl_t *log = &ca_db_ctrl;
char *zErrMsg = NULL;
CA_DB_LOCK;
/* 按最新数据排序(id 递减), 读取偏移 index, 数量 num 条数据 */
snprintf(log->str, CA_DB_BUF_LEN, "SELECT * FROM cable_data ORDER BY id DESC LIMIT %d OFFSET %d;", num, index);
if (sqlite3_exec(log->db, log->str, _ca_db_show_data, 0, &zErrMsg) != SQLITE_OK)
{
DBG(DBG_M_CA_DB_ERR, "SQL show error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
}
CA_DB_UNLOCK;
}
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

File diff suppressed because it is too large Load Diff

@ -0,0 +1,603 @@
/*****************************************************************************
* file lib/process/ca_land.c
* author YuLiang
* version 1.0.0
* date 20-Dec-2023
* brief This file provides all the LandPower protocol related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef CFG_DEV_TYPE_LAND_CA
/* 标准C库头文件. */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <netinet/tcp.h>
#include <sys/types.h>
/* 用户代码头文件. */
#include "cmd.h"
#include "process.h"
#include "ca_land.h"
#include "ca_collect.h"
/* Private define ------------------------------------------------------------*/
#define CA_LAND_BUF_SIZE 1512
#define CA_LAND_CMD_BUF_LEN 3024
#define CA_LAND_SHIQUCHA 28800
#define CA_LAND_CMD_REPLY_RD 0xC081
#define CA_LAND_CMD_REQ_ID 0xC401
#define CA_LAND_START_FLAG 0x5555AAAA
#define CA_LAND_END_FLAG 0x5AA55AA5
#define CA_LAND_HEAD_LEN (sizeof(ca_land_head_t) + 8) //包头加包尾长度
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* BEGIN: 以下结构体为私有协议数据 */
#pragma pack(1)
typedef struct{
uint32_t StartFlag1; //设备ID 0x40110304=ID=40110304
uint8_t FarmeType; //帧类型: 0x00 定时发送
uint32_t RunSecCnt; //系统运行时间 0x01020304=16909060秒
uint16_t Local_Vbat; //本机电池电压 0x1965= 6505/1000=6.501V
int16_t RoomIn_Temp; //本机温度 0x0C02=(3074/10)-273.1=34.3摄氏度
float RMS_Ia; //CH1:A相接地电流
float RMS_Ib; //CH2:B相接地电流
float RMS_Ic; //CH3:C相接地电流
float RMS_In; //CH4: [主缆电流]
float RMS_Ground; //CH5: [总接地电流]
float RMS_rIa; //CH6:A相运行电流
float RMS_rIb; //CH7:B相运行电流
float RMS_rIc; //CH8:C相运行电流
int16_t RoomOut_Temp; //环境温度 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t I16A_Gx; //A相接头振动X轴 0x6655=26197-16000=10197mg
uint16_t I16A_Gy; //A相接头振动Y轴 0x6655=26197-16000=10197mg
uint16_t I16A_Gz; //A相接头振动Z轴 0x6655=26197-16000=10197mg
uint16_t I16A_Temp1; //A相电缆接头温度 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t I16A_Temp2; //A相电缆表面温度 同上
uint16_t I16B_Gx; //B相接头振动X轴 0x6655=26197-16000=10197mg
uint16_t I16B_Gy; //B相接头振动Y轴 0x6655=26197-16000=10197mg
uint16_t I16B_Gz; //B相接头振动Z轴 0x6655=26197-16000=10197mg
uint16_t I16B_Temp1; //B相接头温度 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t I16B_Temp2; //B相电缆表面温度 同上
uint16_t I16C_Gx; //C相接头振动X轴 0x6655=26197-16000=10197mg
uint16_t I16C_Gy; //C相接头振动Y轴 0x6655=26197-16000=10197mg
uint16_t I16C_Gz; //C相接头振动Z轴 0x6655=26197-16000=10197mg
uint16_t I16C_Temp1; //C相接头温度 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t I16C_Temp2; //C相电缆表面温度 同上
uint8_t Status_AG; //A相姿态告警 0x01 告警 0x00正常 复归 故障
uint8_t Status_BG; //B相姿态告警 0x01 故障 0x00正常
uint8_t Status_CG; //C相姿态告警 0x01故障 0x00正常
uint8_t Status_A_OT; //A相温度超限告警 0x01故障 0x00正常
uint8_t Status_B_OT; //B相温度超限告警 0x01故障 0x00正常
uint8_t Status_C_OT; //C相温度超限告警 0x01故障 0x00正常
uint8_t Status_Bat; //电池电路硬件状态0x01故障 0x00正常
uint8_t Error_AT; //A相温度硬件状态 0x01故障 0x00正常
uint8_t Error_BT; //B相温度硬件状态 0x01故障 0x00正常
uint8_t Error_CT; //C相温度硬件状态 0x01故障 0x00正常
uint8_t Error_AG; //A相ADXL硬件状态 0x01故障 0x00正常
uint8_t Error_BG; //B相ADXL硬件状态 0x01故障 0x00正常
uint8_t Error_CG; //C相ADXL硬件状态 0x01故障 0x00正常
uint8_t Error_ROT; //环境温度硬件状态 0x01故障 0x00正常
uint16_t WaterLevel; //水位 0x20=32cm
uint16_t RoomOut_Humidity; //环境湿度 0x0321 = (801/10) = 80.1%
uint8_t Error_Humidity; //环境湿度硬件状态 1:告警0:正常
uint32_t Gas_O2; //氧气浓度 0x000100013= 0x0013=19 %VOL
uint32_t Gas_CH4; //甲烷浓度 同上
uint32_t Gas_H2s; //硫化氢浓度 同上
uint32_t Gas_CO; //一氧化碳浓度 同上
float RMS_Va; //A相电压
float RMS_Vb; //B相电压
float RMS_Vc; //C相电压
uint16_t reserve; //保留
uint16_t endFlag; //值0X0D 0X0A 结束符 “/r/n”
}ca_land_rd_t;//实时数据报文 128 Byte
typedef struct{
uint32_t StartFlag1; //设备ID 0x40110304=ID=40110304
uint8_t FarmeType; //帧类型: 0x01 告警发送
uint32_t RunSecCnt; //系统运行时间 0x01020304=16909060秒
uint8_t WaveNum; //当前的录波物理编号:最新的文件 值:[0-127]
uint8_t RMS_Ig_Err; //总接地电流告 0x01 告警 0x00正常
uint16_t RMS_Ig_Before; //总接地电流变化前 0x0533=1331/10=133.1A
uint16_t RMS_Ig_After; //总接地电流变化后 0x0533=1331/10=133.1A
uint8_t RMS_Ia_Err; //A相电流告警 0x01 告警 0x00正常
uint16_t RMS_Ia_Before; //A相电流变化前 0x0533=1331/10=133.1A
uint16_t RMS_Ia_After; //A相电流变化后 0x0533=1331/10=133.1A
uint8_t Sanke_a_Err; //A相振动告警 0x01 告警 0x00正常
uint16_t Sanke_a_x; //A相X振动值
uint16_t Sanke_a_y; //A相Y振动值
uint16_t Sanke_a_z; //A相Z振动值
uint8_t Temper_a_Err; //A相温度告警 0x01 告警 0x00正常
uint8_t Temper_a_Change; //A相温度变化值 0x02 升高了2度
uint16_t Temper_a_Before; //A相温度前 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t Temper_a_After; //A相温度后 0x0C02=(3074/10)-273.1=34.3摄氏度
uint8_t RMS_Ib_Err; //B相电流告警 0x01 告警 0x00正常
uint16_t RMS_Ib_Before; //B相电流变化前 0x0533=1331/10=133.1A
uint16_t RMS_Ib_After; //B相电流变化后 0x0533=1331/10=133.1A
uint8_t Sanke_b_Err; //B相振动告警 0x01 告警 0x00正常
uint16_t Sanke_b_x; //B相X振动值
uint16_t Sanke_b_y; //B相Y振动值
uint16_t Sanke_b_z; //B相Z振动值
uint8_t Temper_b_Err; //B相温度告警 0x01 告警 0x00正常
uint8_t Temper_b_Change; //B相温度变化值 0x02 升高了2度
uint16_t Temper_b_Before; //B相温度前 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t Temper_b_After; //B相温度后 0x0C02=(3074/10)-273.1=34.3摄氏度
uint8_t RMS_Ic_Err; //C相电流告警 0x01 告警 0x00正常
uint16_t RMS_Ic_Before; //C相电流变化前 0x0533=1331/10=133.1A
uint16_t RMS_Ic_After; //C相电流变化后 0x0533=1331/10=133.1A
uint8_t Sanke_c_Err; //C相振动告警 0x01 告警 0x00正常
uint16_t Sanke_c_x; //C相X振动值
uint16_t Sanke_c_y; //C相Y振动值
uint16_t Sanke_c_z; //C相Z振动值
uint8_t Temper_c_Err; //C相温度告警 0x01 告警 0x00正常
uint8_t Temper_c_Change; //C相温度变化值 0x02 升高了2度
uint16_t Temper_c_Before; //C相温度前 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t Temper_c_After; //C相温度后 0x0C02=(3074/10)-273.1=34.3摄氏度
uint16_t endFlag; //值0X0D 0X0A 结束符 “/r/n”
}ca_land_war_t;//告警数据 71Byte
typedef struct{
uint32_t StatusA; //24个通道的温度数据的正确性判断 Bit24 0 开关量正常 1开关量报警
int16_t TempA[24]; //测温带的温度 I16/16【原始值】
uint32_t StatusB;
int16_t TempB[24];
uint32_t StatusC;
int16_t TempC[24];
} ca_land_tmp_t;//测温带数据 156 Byte
typedef struct{
uint32_t proVer; //协议版本号 0x00000363
uint32_t utc;
ca_land_rd_t rtd;
uint32_t reslved1; //调试工具 用来存历史数据条数
ca_land_war_t war;
uint8_t reslved2;
ca_land_tmp_t mul;
uint32_t reslved3;
uint32_t powertatus;
uint32_t vbat;
uint32_t vout;
uint32_t batteryStatus;
float Gpslatitude;
float Gpslongitude;
uint8_t PowerFail[8]; //电源故障 485
uint32_t vsc;
uint8_t reslved4[104];
} ca_land_date_t;//512Byte
#pragma pack()
typedef struct{
uint32_t Head; //StartFlag1 0X5555AAAA
uint16_t Len; //报文长度:所有字节总长度
uint16_t Type; //报文类型
uint32_t ID; //从机ID: 【ex. 0x40111234 】
uint32_t LifeCnt; //主机每次加1从机应答收到的值
uint16_t gNum; //报文分组数目:1-65535
uint16_t gNumIndex; //报文分组编号0 gNum1
} ca_land_head_t;//朗德协议包头
typedef struct{
uint32_t CheckSum;
uint32_t EndFlag1;
} ca_land_tail_t;//朗德协议包尾
/* END: 以上结构体为私有协议数据 */
/* 私有协议全局控制结构 */
typedef struct{
int fd; // TCP server 监听使用的 socket
char buf[CA_LAND_BUF_SIZE]; // 通讯使用收发包 buf
ca_land_state_t state; // 协议状态
} ca_land_ctrl_t;
ca_land_ctrl_t ca_land_ctrl; // 全局控制结构
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* description: 显示当前状态
param:
return: CMD_XXX */
CMD(ca_land_show_state,
ca_land_show_state_cmd,
"show land",
"Show\n"
"LandPower protocol\n")
{
ca_land_state_show();
return CMD_SUCCESS;
}
/* description: 私有协议 socket 属性配置
param: fd - socket
return: E_XXX */
int32_t _ca_land_socket_set(int fd)
{
//int keep_alive = 1;
//int keep_idle = 60;
//int keep_interval = 6;
//int keep_count = 10;
int keep_time = 30000;
struct timeval timeout;
#if 0
/* 开启保活, 保活参数表示 60 秒内无交互后, 每隔 6 秒检测一次. 10 次都没得到响应时会断开连接 */
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keep_alive, sizeof(keep_alive)))
{
DBG(DBG_M_CA_LAND_ERR, "Error setsockopt(SO_KEEPALIVE) failed, return %s!\r\n", safe_strerror(errno));
return E_SYS_CALL;
}
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keep_idle, sizeof(keep_idle)))
{
DBG(DBG_M_CA_LAND_ERR, "Error setsockopt(TCP_KEEPIDLE) failed, return %s!\r\n", safe_strerror(errno));
return E_SYS_CALL;
}
if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void *)&keep_interval, sizeof(keep_interval)))
{
DBG(DBG_M_CA_LAND_ERR, "Error setsockopt(TCP_KEEPINTVL) failed, return %s!\r\n", safe_strerror(errno));
return E_SYS_CALL;
}
if (setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void *)&keep_count, sizeof(keep_count)))
{
DBG(DBG_M_CA_LAND_ERR, "Error setsockopt(TCP_KEEPCNT) failed, return %s!\r\n", safe_strerror(errno));
return E_SYS_CALL;
}
#endif
/* 发送超时配置 */
if (setsockopt(fd, SOL_TCP, TCP_USER_TIMEOUT, (void *)&keep_time, sizeof(keep_time)))
{
DBG(DBG_M_CA_LAND_ERR, "Error setsockopt(TCP_USER_TIMEOUT) failed, return %s!\r\n", safe_strerror(errno));
return E_SYS_CALL;
}
/* 发送超时 */
timeout.tv_sec = 30;
timeout.tv_usec = 0;
if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)))
{
DBG(DBG_M_CA_LAND_ERR, "Error setsockopt(SO_SNDTIMEO) failed, return %s!\r\n", safe_strerror(errno));
return E_SYS_CALL;
}
return E_NONE;
}
/* description: 初始化报文头
param: cmd -
len -
return: */
void _ca_land_head_init(uint16_t cmd, int32_t len)
{
char *pkt = ca_land_ctrl.buf;
ca_land_head_t *head = (ca_land_head_t*)pkt;
memset(pkt, 0, CA_LAND_BUF_SIZE);
head->Head = CA_LAND_START_FLAG;
head->Len = CA_LAND_HEAD_LEN + len;
head->Type = cmd;
head->ID = device_info.dev_id;
head->LifeCnt = 1;
head->gNum = 1;
head->gNumIndex = 0;
}
/* description: 报文校验和计算
param: data_len -
return: */
void _ca_land_cheak_sum(int32_t data_len)
{
char *pkt = ca_land_ctrl.buf;
uint32_t *temp = (uint32_t*)(pkt + 4);
ca_land_tail_t *tail = (ca_land_tail_t*)(pkt + data_len - 8);
int32_t i = 0;
int32_t len = (data_len - 12) >> 2; // 起始位和报文尾不参与计算
uint32_t cheakSum = 0;
for(i = 0; i < len; i++ )
{
cheakSum += *temp;
temp++;
}
tail->CheckSum = cheakSum;
tail->EndFlag1 = CA_LAND_END_FLAG;
}
int32_t _ca_land_heart_send(void)
{
char *pkt = ca_land_ctrl.buf;
ca_land_head_t *head = (ca_land_head_t*)pkt;
int fd = ca_land_ctrl.fd;
/* 初始化报文头 */
_ca_land_head_init(CA_LAND_CMD_REQ_ID, 36);
_ca_land_cheak_sum(head->Len);
/* 发送数据 */
if (send(fd, pkt, head->Len, 0) < 0)
{
DBG(DBG_M_CA_LAND_ERR, "LAND send ERR!\r\n");
return E_SYS_CALL;
}
/* 调试打印 */
DBG(DBG_M_CA_LAND, "LAND send(%d): %d %d\r\n", head->Len, time(NULL));
if (dbg_stat_get(DBG_M_CA_LAND))
{
buf_print(pkt, 32);
}
return E_NONE;
}
/* description: 数据报文组装
param: data -
return: */
void _ca_land_date(ca_land_rd_t *data)
{
ca_coll_dev_data_t *dev_data = ca_coll_cable_data_get();
data->StartFlag1 = device_info.dev_id;
data->endFlag = 0x0A0D;
data->Local_Vbat = dev_data->vbat;
data->RoomIn_Temp = dev_data->temperature +2731;
data->RunSecCnt = start_time;
data->RMS_Ia = dev_data->elec[0] / 1000.0;
data->RMS_Ib = dev_data->elec[1] / 1000.0;
data->RMS_Ic = dev_data->elec[2] / 1000.0;
data->RMS_rIa = dev_data->elec[3] / 1000.0;
data->RMS_Ground = dev_data->elec[4] / 1000.0;
}
/* description: 数据报文发送
param: data -
return: E_XXX */
int32_t _ca_land_real_data_send(void)
{
char *pkt = ca_land_ctrl.buf;
ca_land_head_t *head = (ca_land_head_t*)pkt;
ca_land_date_t *rd = (ca_land_date_t*)(pkt + sizeof(ca_land_head_t));
ca_coll_dev_data_t *dev_data = ca_coll_cable_data_get();
time_t now = time(NULL);
int fd = ca_land_ctrl.fd;
/* 初始化报文头 */
_ca_land_head_init(CA_LAND_CMD_REPLY_RD, sizeof(ca_land_date_t));
/* 填充数据 */
rd->proVer = 0x00000601;
rd->utc = now - CA_LAND_SHIQUCHA;
rd->powertatus = 0;
rd->batteryStatus = 0;
rd->vbat = dev_data->vbat;
rd->vsc = dev_data->vsc;
rd->vout = dev_data->vin;
rd->Gpslatitude = 0;
rd->Gpslongitude = 0;
rd->reslved1 = 0;
_ca_land_date(&rd->rtd);
_ca_land_cheak_sum(head->Len);
/* 发送数据 */
if (send(fd, pkt, head->Len, 0) < 0)
{
DBG(DBG_M_CA_LAND_ERR, "LAND send ERR!\r\n");
return E_SYS_CALL;
}
/* 调试打印 */
DBG(DBG_M_CA_LAND, "LAND send(%d): %d %d\r\n", head->Len, now);
if (dbg_stat_get(DBG_M_CA_LAND))
{
buf_print(pkt, 32);
}
return E_NONE;
}
/* description: 私有协议数据发送线程
param:
return: */
void *_ca_land_handle_send(void *arg)
{
static uint8_t cnt = 0;
ca_coll_cfg_t *cfg = ca_coll_cfg_get();
ca_coll_state_t *state = ca_coll_cable_state_get();
struct sockaddr_in server;
int fd = ca_land_ctrl.fd;
int8_t err_cnt = 0;
while (!is_system_init)
{
sleep(1);
}
/* 绑定端口 */
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(cfg->land_ip);
server.sin_port = htons(cfg->land_port);
printf("land_ip:%s land_port:%d\n", cfg->land_ip, cfg->land_port);
while (1)
{
sleep(30);
/* 创建 socket */
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
log_err(LOG_CA_LAND, "ERROR at socket create return %s!", safe_strerror(errno));
continue;
}
if (connect(fd, (struct sockaddr*)&server, sizeof(server)) < 0)
{
DBG(DBG_M_CA_LAND_ERR, "ERROR at socket connect return %s!\r\n", safe_strerror(errno));
close(fd);
/* 如果 4G 连接, 服务器未连接, 假 4G 连接需要重启设备 */
if (cfg->is_4G && state->is_4g_connect)
{
err_cnt++;
if (err_cnt >= 10)
{
// 如果是私网卡会连不上
//reboot_system(LOG_CA_LAND, BOOT_CONNECT_ERR);
}
}
else
{
err_cnt = 0;
}
continue;
}
_ca_land_socket_set(fd);
ca_land_ctrl.fd = fd;
/* 定时发送数据 */
cnt = 0;
while(1)
{
if (ca_land_ctrl.state.is_send_data)
{
ca_land_ctrl.state.is_send_data = FALSE;
if (_ca_land_real_data_send() != E_NONE)
{
ca_land_ctrl.state.is_connect = FALSE;
DBG(DBG_M_CA_LAND_ERR, "ERROR at server disconnect!\r\n");
close(fd);
break;
}
ca_land_ctrl.state.is_connect = TRUE;
}
else if(cnt >= 30)
{
cnt = 0;
if (_ca_land_heart_send() != E_NONE)
{
ca_land_ctrl.state.is_connect = FALSE;
DBG(DBG_M_CA_LAND_ERR, "ERROR at server disconnect!\r\n");
close(fd);
break;
}
ca_land_ctrl.state.is_connect = TRUE;
}
sleep(1);
cnt++;
}
}
return NULL;
}
/* Interface functions -------------------------------------------------------*/
/* description: 私有协预初始化
param:
return: E_XXX */
int32_t ca_land_init(void)
{
cmd_install_element(COMMON_NODE, &ca_land_show_state_cmd);
return E_NONE;
}
/* description: 朗德协议初始化函数.
param: 111.47.21.141
return: */
int32_t ca_land_init_after(void)
{
ca_coll_cfg_t *cfg = ca_coll_cfg_get();
struct sched_param param;
pthread_attr_t attr;
pthread_t pid;
int32_t rv = 0;
if (!cfg->is_land)
{
return E_NONE;
}
pthread_attr_init(&attr);
param.sched_priority = 25;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, &param);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
rv = pthread_create(&pid, &attr, _ca_land_handle_send, NULL);
if (rv != 0)
{
log_err(LOG_CA_LAND, "Can't create debug pthread %d!", rv);
return E_SYS_CALL;
}
else
{
thread_m_add("CA_LAND", pid);
}
pthread_attr_destroy(&attr);
return E_NONE;
}
/* description: 私有协议状态结构体获取
param:
return: ca_land_state_t - */
ca_land_state_t* ca_land_state_get(void)
{
return &ca_land_ctrl.state;
}
/* description: 私有协议状态显示
param:
return: */
void ca_land_state_show(void)
{
ca_land_state_t *state = &ca_land_ctrl.state;
printh("Connect: %s\r\n\n", state->is_connect ? "yes" : "no");
}
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,110 @@
/*****************************************************************************
* file lib/process/ca_main.c
* author YuLiang
* version 1.0.0
* date 27-Nov-2023
* brief This file provides all the cable related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef CFG_DEV_TYPE_LAND_CA
/* 标准C库头文件. */
/* 私有头文件 */
#include "ca_db.h"
#include "ca_collect.h"
#include "ca_dbg.h"
#include "ca_mqtt.h"
#include "ca_land.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 将端口字符串, 转换成 unit port 格式. */
/* Interface functions -------------------------------------------------------*/
/* description: 环流预初始化.
param:
return: E_XXX */
int32_t ca_main(void)
{
int32_t rv = E_NONE;
rv |= ca_db_init();
rv |= ca_coll_init();
rv |= ca_mqtt_init();
rv |= ca_land_init();
return rv;
}
/* description: 环流初始化
param:
return: E_XXX */
int32_t ca_main_after(void)
{
int32_t rv = E_NONE;
rv |= ca_db_init_after();
rv |= ca_coll_init_after();
rv |= ca_dbg_handle_init_after();
rv |= ca_mqtt_init_after();
rv |= ca_land_init_after();
return rv;
}
#else
int32_t ca_main(void)
{
return 0;
}
int32_t ca_main_after(void)
{
return 0;
}
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,980 @@
/*****************************************************************************
* file lib/process/ca_mqtt.c
* author YuLiang
* version 1.0.0
* date 07-Dec-2023
* brief This file provides all the MQTT related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2023 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef CFG_DEV_TYPE_LAND_CA
/* 标准 C 库头文件 */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* 私有头文件 */
#include "vty.h"
#include "cmd.h"
#include "fifo.h"
#include "cJSON.h"
#include "ca_mqtt.h"
/* Private define ------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* fifo 消息类型 */
enum CA_MQTT_TYPE
{
CA_MQTT_T_NONE = 0,
CA_MQTT_T_DATA, // 环流数据
CA_MQTT_T_CNT
};
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
ca_mqtt_ctrl_t ca_mqtt_ctrl; // 全局控制结构体
/* Internal functions --------------------------------------------------------*/
/* description: MQTT 服务器设置
param:
return: CMD_XXX */
CMD(ca_mqtt_server_set,
ca_mqtt_server_set_cmd,
"mqtt server A.B.C.D <1-65535>",
"MQTT\n"
"Server\n"
"IPv4 address\n"
"Server port\n")
{
snprintf(device_info.mqtt.server_ip, INET_ADDRSTRLEN, argv[0]);
device_info.mqtt.server_port = strtol((char*)argv[1], NULL, 10);
vtysh_device_save();
return CMD_SUCCESS;
}
/* description: MQTT 保活时间设置
param:
return: CMD_XXX */
CMD(ca_mqtt_alive_set,
ca_mqtt_alive_set_cmd,
"mqtt alive <1-65535>",
"MQTT\n"
"Keep alive\n"
"time\n")
{
device_info.mqtt.alive_time = strtol((char*)argv[0], NULL, 10);
vtysh_device_save();
return CMD_SUCCESS;
}
/* description: MQTT 设备 id 设置
param:
return: CMD_XXX */
CMD(ca_mqtt_dev_id_set,
ca_mqtt_dev_id_set_cmd,
"mqtt device id WORD",
"MQTT\n"
"Device\n"
"Id\n"
"Device id\n")
{
snprintf(device_info.mqtt.dev_id, CA_MQTT_DEV_ID_LEN, argv[0]);
vtysh_device_save();
return CMD_SUCCESS;
}
/* description: MQTT 客户端 id 设置
param:
return: CMD_XXX */
CMD(ca_mqtt_client_id_set,
ca_mqtt_client_id_set_cmd,
"mqtt client id WORD",
"MQTT\n"
"Client\n"
"Id\n"
"Client id\n")
{
snprintf(device_info.mqtt.client_id, CA_MQTT_CLINET_ID_LEN, argv[0]);
vtysh_device_save();
return CMD_SUCCESS;
}
/* description: MQTT 用户名设置
param:
return: CMD_XXX */
CMD(ca_mqtt_username_set,
ca_mqtt_username_set_cmd,
"mqtt username WORD",
"MQTT\n"
"Username\n"
"Username\n")
{
snprintf(device_info.mqtt.username, CA_MQTT_USERNAME_LEN, argv[0]);
vtysh_device_save();
return CMD_SUCCESS;
}
/* description: MQTT 密码设置
param:
return: CMD_XXX */
CMD(ca_mqtt_passwd_set,
ca_mqtt_passwd_set_cmd,
"mqtt passwd WORD",
"MQTT\n"
"Passwd\n"
"Passwd\n")
{
snprintf(device_info.mqtt.passwd, CA_MQTT_PASSWD_LEN, argv[0]);
vtysh_device_save();
return CMD_SUCCESS;
}
/* description: MQTT 状态显示
param:
return: CMD_XXX */
CMD(ca_mqtt_show_state,
ca_mqtt_show_state_cmd,
"show mqtt",
"Show\n"
"MQTT\n")
{
ca_mqtt_state_show();
return CMD_SUCCESS;
}
void connlost(void *context, char *cause)
{
DBG(DBG_M_CA_MQTT, "\nConnection lost\n");
DBG(DBG_M_CA_MQTT, " cause: %s\n", cause);
ca_mqtt_ctrl.state.is_connect = FALSE;
}
void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
{
DBG(DBG_M_CA_MQTT, "Disconnect failed\n");
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
DBG(DBG_M_CA_MQTT, "Successful disconnection\n");
}
void onSendFailure(void* context, MQTTAsync_failureData* response)
{
DBG(DBG_M_CA_MQTT, "send failed\n");
ca_mqtt_ctrl.state.is_connect = FALSE;
}
void onSend(void* context, MQTTAsync_successData* response)
{
DBG(DBG_M_CA_MQTT, "Message with token value %d delivery confirmed\n", response->token);
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
DBG(DBG_M_CA_MQTT, "Connect failed, [%d:%s]\n", response->code, response->message);
ca_mqtt_ctrl.state.is_connect = FALSE;
ca_coll_cfg_t *cfg = ca_coll_cfg_get();
ca_coll_state_t *state = ca_coll_cable_state_get();
/* 避免 4G 伪连接情况, 此时设备会重启. */
if (cfg->is_4G && state->is_4g_connect)
{
ca_mqtt_ctrl.state.login_err_cnt++;
if (ca_mqtt_ctrl.state.login_err_cnt++ >= 10)
{
reboot_system(LOG_CA_LAND, BOOT_CONNECT_ERR);
}
}
else
{
ca_mqtt_ctrl.state.login_err_cnt = 0;
}
sleep(30);
DBG(DBG_M_CA_MQTT, "Login again\r\n");
}
void onSubscribe(void* context, MQTTAsync_successData* response)
{
DBG(DBG_M_CA_MQTT, "Subscribe succeeded token=%d\n", response->token);
//subscribed = 1;
}
void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
DBG(DBG_M_CA_MQTT, "Subscribe failed, rc %d\n", response->code);
ca_mqtt_ctrl.state.is_connect = FALSE;
}
// 回调函数,当接收到消息时会被调用
int onMessageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
// 处理接收到的消息
DBG(DBG_M_CA_MQTT, "topicName:%s \r\n", topicName, topicLen);
DBG(DBG_M_CA_MQTT, "payload:%s \r\n", message->payload);
cJSON *pRoot = cJSON_Parse((char *)message->payload);
if (pRoot != NULL)
{
cJSON *statusCodeJson = cJSON_GetObjectItem(pRoot, "statusCode");
if (statusCodeJson->valueint == 0)
{
cJSON *dataJson = cJSON_GetObjectItem(pRoot, "data");
if (dataJson && dataJson->type == cJSON_Array)
{
int dataArrSize = cJSON_GetArraySize(dataJson);
if (dataArrSize > 0)
{
for (int i = 0; i < dataArrSize; i++)
{
cJSON *itemObj = cJSON_GetArrayItem(dataJson,i);
if (itemObj)
{
cJSON *devInfoJson = cJSON_GetObjectItem(itemObj, "deviceInfo");
if (devInfoJson)
{
cJSON *devIdJson = cJSON_GetObjectItem(devInfoJson, "deviceId");
cJSON *nodeIdJson = cJSON_GetObjectItem(devInfoJson, "nodeId");
if (devIdJson && devIdJson->type == cJSON_String
&& nodeIdJson && nodeIdJson->type == cJSON_String)
{
for (int j = 0; j < NODE_NUM; j++)
{
if (!strncmp(nodeIdJson->valuestring, ca_mqtt_ctrl.node[j].node_id, sizeof(ca_mqtt_ctrl.node[j].node_id)))
{
memcpy(ca_mqtt_ctrl.node[j].device_id, devIdJson->valuestring, sizeof(ca_mqtt_ctrl.node[j].device_id));
DBG(DBG_M_CA_MQTT, "deviceId[%d]:%s \r\n", j, ca_mqtt_ctrl.node[j].device_id);
_ca_mqtt_update_device_status(ca_mqtt_ctrl.node[j].device_id);
break;
}
}
}
}
}
}
}
}
}
cJSON_Delete(pRoot);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
char topics[5][64] = {0};
char *pTopics[5];
char tmp[64] = {0};
int qos[5] = {1, 1, 1, 1, 1};
DBG(DBG_M_CA_MQTT, "Successful connection\n");
ca_mqtt_ctrl.state.is_connect = TRUE;
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/%s", ca_mqtt_ctrl.info.dev_id, "command");
strcpy(topics[0], tmp);
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/topo/%s", ca_mqtt_ctrl.info.dev_id, "addResponse");
strcpy(topics[1], tmp);
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/topo/%s", ca_mqtt_ctrl.info.dev_id, "delete");
strcpy(topics[2], tmp);
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/topo/%s", ca_mqtt_ctrl.info.dev_id, "updateResponse");
strcpy(topics[3], tmp);
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/topo/%s", ca_mqtt_ctrl.info.dev_id, "queryResponse");
strcpy(topics[4], tmp);
for (int i = 0; i < 5; i++)
{
pTopics[i] = topics[i];
DBG(DBG_M_CA_MQTT, "topics[%d]:%s %s\r\n", i, pTopics[i], topics[i]);
}
opts.onSuccess = onSubscribe;
opts.onFailure = onSubscribeFailure;
opts.context = client;
// 执行订阅
rc = MQTTAsync_subscribeMany(ca_mqtt_ctrl.client, 5, pTopics, qos, &opts);
if (rc != MQTTASYNC_SUCCESS)
{
DBG(DBG_M_CA_MQTT, "Failed to start subscribe, return code %d\n", rc);
}
_ca_mqtt_add_sub_device(ca_mqtt_ctrl.node);
DBG(DBG_M_CA_MQTT, "ON CONNECT ..............\r\n");
}
void _ca_mqtt_json_add_sub_device(char *outmsg, node_info_t *node_info)
{
cJSON *pRoot = NULL;
char *tempbody = NULL;
cJSON *pSub = NULL;
pRoot = cJSON_CreateObject();
if (NULL == pRoot)
{
printf("cJSON_CreateObject proot err\n");
goto Toexit;
}
pSub = cJSON_CreateArray();
if(NULL == pSub)
{
goto Toexit;
}
cJSON_AddNumberToObject(pRoot, "mid", 4000);
cJSON_AddItemToObject(pRoot,"deviceInfos", pSub);
for (int i = 0; i < NODE_NUM; i++)
{
cJSON *pEle = cJSON_CreateObject();
cJSON_AddItemToArray(pSub, pEle);
cJSON_AddStringToObject(pEle, "nodeId", node_info[i].node_id);
cJSON_AddStringToObject(pEle, "name", "cable");
cJSON_AddStringToObject(pEle, "description", "cable tianjing");
cJSON_AddStringToObject(pEle, "manufacturerId", MANUFACTURERID);
cJSON_AddStringToObject(pEle, "model", "SD_JK_LD_FBDMX");
//cJSON_AddStringToObject(pSub, "model", DEVICE_MODEL);
}
tempbody = cJSON_PrintUnformatted(pRoot);
if (NULL != tempbody)
{
printf("tempbody:%s\n", tempbody);
strcpy(outmsg, tempbody);
}
Toexit:
if (NULL != pRoot)
{
cJSON_Delete(pRoot);
}
if (NULL != tempbody)
{
free(tempbody);
}
}
void _ca_mqtt_json_update_device_status(char *outmsg, char *devid, char *status)
{
cJSON *pRoot = NULL;
char *tempbody = NULL;
cJSON *pSub = NULL;
pRoot = cJSON_CreateObject();
if (NULL == pRoot)
{
printf("cJSON_CreateObject proot err\n");
goto Toexit;
}
pSub = cJSON_CreateObject();
if(NULL == pSub)
{
goto Toexit;
}
cJSON_AddNumberToObject(pRoot, "mid", 4000);
cJSON_AddItemToObject(pRoot,"deviceStatuses", pSub);
cJSON_AddStringToObject(pSub, "deviceId", devid);
cJSON_AddStringToObject(pSub, "status", status);
tempbody = cJSON_PrintUnformatted(pRoot);
if (NULL != tempbody)
{
printf("tempbody:%s\n", tempbody);
strcpy(outmsg, tempbody);
}
Toexit:
if (NULL != pRoot)
{
cJSON_Delete(pRoot);
}
if (NULL != tempbody)
{
free(tempbody);
}
}
void _ca_mqtt_json_ground_current(ca_coll_dev_data_t *data, char *outmsg, int idx)
{
cJSON *pRoot = NULL;
char *tempbody = NULL;
pRoot = cJSON_CreateObject();
if (pRoot == NULL)
{
printf("cJSON_CreateObject proot err\n");
goto Toexit;
}
cJSON *pdevicesArr = cJSON_CreateArray();
if (NULL == pdevicesArr)
{
printf("cJSON_CreateArray pdevicesArr err\n");
goto Toexit;
}
cJSON_AddItemToObject(pRoot, "devices", pdevicesArr);
for (int i = 0; i < NODE_NUM; i++)
{
char str[64] = {0};
struct tm *day;
char time_str[TIME_STR_LEN] = {0};
time_t utc = 0;
/* 组装数据 */
utc = time(NULL);
day = localtime(&utc);
strftime(time_str, TIME_STR_LEN, "%Y%m%dT%H%M%SZ", day);
cJSON *psub = cJSON_CreateObject();
if (psub == NULL)
{
printf("cJSON_CreateObject psub err\n");
goto Toexit;
}
cJSON *pserviceArr = cJSON_CreateArray();
if (NULL == pserviceArr)
{
printf("cJSON_CreateArray pserviceArr err\n");
goto Toexit;
}
cJSON_AddItemToObject(psub, "services", pserviceArr);
cJSON_AddStringToObject(psub, "deviceId", ca_mqtt_ctrl.node[i].device_id);
cJSON *pelement = cJSON_CreateObject();
if (pelement == NULL)
{
printf("cJSON_CreateObject pelement err\n");
goto Toexit;
}
cJSON_AddStringToObject(pelement, "serviceId", "circulating_031002");
cJSON_AddStringToObject(pelement, "eventTime", time_str);
cJSON *pdataJson = cJSON_CreateObject();
if (pdataJson == NULL)
{
printf("cJSON_CreateObject pdataJson err\n");
goto Toexit;
}
//cJSON_AddStringToObject(pdataJson, "DeviceID", ca_mqtt_ctrl.node[i].device_id);
cJSON_AddStringToObject(pdataJson, "manufacturerId", MANUFACTURERID);
cJSON_AddStringToObject(pdataJson, "deviceModel", DEVICE_MODEL);
cJSON_AddStringToObject(pdataJson, "manufacturerName", "武汉朗德");
cJSON_AddStringToObject(pdataJson, "monitorTime", time_str);
cJSON_AddStringToObject(pdataJson, "deviceCode", ca_mqtt_ctrl.node[i].node_id);
bzero(str, sizeof(str));
sprintf(str, "%s_%03d", ca_mqtt_ctrl.node[i].device_id, idx+1);
cJSON_AddStringToObject(pdataJson, "pointCode", str);
if (idx == 0)
{
bzero(str, sizeof(str));
sprintf(str, "%f", data->elec[0] / 1000.0);
//sprintf(str, "%f", 1111 / 1000.0);
cJSON_AddStringToObject(pdataJson, "pointPhase", "A");
cJSON_AddStringToObject(pdataJson, "ShieldEarthCurrentPhase", str);
}
else if (idx == 1)
{
bzero(str, sizeof(str));
sprintf(str, "%f", data->elec[1] / 1000.0);
//sprintf(str, "%f", 1122 / 1000.0);
cJSON_AddStringToObject(pdataJson, "pointPhase", "B");
cJSON_AddStringToObject(pdataJson, "ShieldEarthCurrentPhase", str);
}
else if (idx == 2)
{
bzero(str, sizeof(str));
sprintf(str, "%f", data->elec[2] / 1000.0);
//sprintf(str, "%f", 1133 / 1000.0);
cJSON_AddStringToObject(pdataJson, "pointPhase", "C");
cJSON_AddStringToObject(pdataJson, "ShieldEarthCurrentPhase", str);
}
else if (idx == 3)
{
bzero(str, sizeof(str));
sprintf(str, "%f", data->elec[3] / 1000.0);
//sprintf(str, "%f", 1523 / 1000.0);
cJSON_AddStringToObject(pdataJson, "pointPhase", "R");
cJSON_AddStringToObject(pdataJson, "ShieldEarthCurrentPhase", str);
cJSON_AddStringToObject(pdataJson, "runingCurrent", str);
//cJSON_AddStringToObject(pdataJson, "totalShieldEarthCurrent", str);
}
else if (idx == 4)
{
bzero(str, sizeof(str));
sprintf(str, "%f", data->elec[4] / 1000.0);
//sprintf(str, "%f", 1423 / 1000.0);
cJSON_AddStringToObject(pdataJson, "pointPhase", "T");
cJSON_AddStringToObject(pdataJson, "ShieldEarthCurrentPhase", str);
cJSON_AddStringToObject(pdataJson, "totalShieldEarthCurrent", str);
//cJSON_AddStringToObject(pdataJson, "runingCurrent", str);
}
//cJSON_AddStringToObject(pdataJson, "ShieldEarthCurrentSampleType", "A");
//cJSON_AddStringToObject(pJson, "SECFaultType", "A");
//cJSON_AddStringToObject(pJson, "LoadCurrent", "A");
//cJSON_AddStringToObject(pJson, "LoadCurrentLevel", "A");
//cJSON_AddStringToObject(pdataJson, "CurrentVol", "A");
cJSON_AddItemToObject(pelement,"data", pdataJson);
cJSON_AddItemToArray(pserviceArr, pelement);
cJSON_AddItemToArray(pdevicesArr, psub);
}
tempbody = cJSON_PrintUnformatted(pRoot);
if (NULL != tempbody)
{
printf("tempbody:%s\n", tempbody);
strcpy(outmsg, tempbody);
}
Toexit:
if (NULL != pRoot)
{
cJSON_Delete(pRoot);
}
if (NULL != tempbody)
{
free(tempbody);
}
}
int _ca_mqtt_add_sub_device(node_info_t *node_info)
{
int rc;
char buffer[4096] = {0};
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
char tmp[64] = {0};
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/topo/%s", ca_mqtt_ctrl.info.dev_id, "add");
_ca_mqtt_json_add_sub_device(buffer, node_info);
opts.onSuccess = onSend;
opts.onFailure = onSendFailure;
//opts.context = client;
pubmsg.payload = buffer;
pubmsg.payloadlen = (int)strlen(buffer);
pubmsg.qos = QOS;
pubmsg.retained = 0;
if ((rc = MQTTAsync_sendMessage(ca_mqtt_ctrl.client, tmp, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("add sub device over...\r\n");
return 0;
}
int _ca_mqtt_update_device_status(char *device_id)
{
int rc;
char buffer[1024] = {0};
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
char tmp[64] = {0};
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/topo/%s", ca_mqtt_ctrl.info.dev_id, "update");
_ca_mqtt_json_update_device_status(buffer, device_id, "ONLINE");
opts.onSuccess = onSend;
opts.onFailure = onSendFailure;
//opts.context = client;
pubmsg.payload = buffer;
pubmsg.payloadlen = (int)strlen(buffer);
pubmsg.qos = QOS;
pubmsg.retained = 0;
if ((rc = MQTTAsync_sendMessage(ca_mqtt_ctrl.client, tmp, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
return 0;
}
int _ca_mqtt_data_report_child_device(ca_coll_dev_data_t *data, char *device_id, int idx)
{
int rc;
char buffer[4096] = {0};
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
char tmp[64] = {0};
bzero(tmp, sizeof(tmp));
snprintf(tmp, sizeof(tmp), "/v1/devices/%s/datas", device_id);
DBG(DBG_M_CA_MQTT, "Topic:%s\n", tmp);
_ca_mqtt_json_ground_current(data, buffer, idx);
opts.onSuccess = onSend;
opts.onFailure = onSendFailure;
//opts.context = client;
pubmsg.payload = buffer;
pubmsg.payloadlen = (int)strlen(buffer);
pubmsg.qos = QOS;
pubmsg.retained = 0;
if ((rc = MQTTAsync_sendMessage(ca_mqtt_ctrl.client, tmp, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("send child device data.....\r\n");
return 0;
}
int _ca_mqtt_gen_topic(char *topic, char *id, char *cmd)
{
if (topic)
{
snprintf(topic, 128, "/v1/devices/%s/%s", id, cmd);
}
return 0;
}
int _ca_mqtt_connect(char *brokeAddr, char *clientId, char *username, char *passwd)
{
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
DBG(DBG_M_CA_MQTT, "start connect mqtt \r\n broke_addr:%s \r\n clientId:%s \r\nusername:%s \r\npasswd:%s\r\n",
brokeAddr, clientId, username, passwd);
if (ca_mqtt_ctrl.client)
{
#if 0
MQTTAsync_disconnectOptions dis_opts = MQTTAsync_disconnectOptions_initializer;
int rc;
dis_opts.onSuccess = onDisconnect;
dis_opts.onFailure = onDisconnectFailure;
//dis_opts.context = client;
if ((rc = MQTTAsync_disconnect(ca_mqtt_ctrl.client, &dis_opts)) != MQTTASYNC_SUCCESS)
{
DBG(DBG_M_CA_MQTT, "Failed to start disconnect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
ca_mqtt_ctrl.client = NULL;
#endif
DBG(DBG_M_CA_MQTT, " Destroy Mqtt, Relogin\r\n");
MQTTAsync_destroy(&ca_mqtt_ctrl.client);
}
if ((rc = MQTTAsync_create(&ca_mqtt_ctrl.client, brokeAddr, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTASYNC_SUCCESS)
{
DBG(DBG_M_CA_MQTT, "Failed to create client object, return code %d\n", rc);
exit(EXIT_FAILURE);
}
if ((rc = MQTTAsync_setCallbacks(ca_mqtt_ctrl.client, NULL, connlost, onMessageArrived, NULL)) != MQTTASYNC_SUCCESS)
{
DBG(DBG_M_CA_MQTT, "Failed to set callback, return code %d\n", rc);
exit(EXIT_FAILURE);
}
conn_opts.keepAliveInterval = 60;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.username = username;
conn_opts.password = passwd;
conn_opts.context = ca_mqtt_ctrl.client;
if ((rc = MQTTAsync_connect(ca_mqtt_ctrl.client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
DBG(DBG_M_CA_MQTT, "Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
return rc;
}
/* description: 南网 MQTT 协议处理线程
param:
return: */
void *_ca_mqtt_handle(void *param)
{
ca_mqtt_msg_t *recv_msg = NULL;
ca_coll_cfg_t *cfg = ca_coll_cfg_get();
ca_coll_state_t *state = ca_coll_cable_state_get();
/* 主循环 */
while(1)
{
if (ca_mqtt_ctrl.state.is_connect == FALSE)
{
DBG(DBG_M_CA_MQTT, "is_4G=%d is_4g_connect=%d\n", cfg->is_4G, state->is_4g_connect);
if (cfg->is_4G && state->is_4g_connect)
{
char broke_addr[64] = {0};
snprintf(broke_addr, sizeof(broke_addr), "tcp://%s:%d", ca_mqtt_ctrl.info.server_ip, ca_mqtt_ctrl.info.server_port);
_ca_mqtt_connect(broke_addr, ca_mqtt_ctrl.info.client_id, ca_mqtt_ctrl.info.username, ca_mqtt_ctrl.info.passwd);
}
sleep(10);
continue;
}
/* 等待数据 */
if (fifo_read(ca_mqtt_ctrl.fifo_id, (void **)&recv_msg) != 0)
{
DBG(DBG_M_CA_MQTT_ERR, "ERROR at fifo read!\r\n");
continue;
}
/* 发送数据 */
if (ca_mqtt_ctrl.state.is_connect)
{
switch(recv_msg->type)
{
case CA_MQTT_T_DATA:
_ca_mqtt_data_report_child_device(recv_msg->data, ca_mqtt_ctrl.info.dev_id, 0);
_ca_mqtt_data_report_child_device(recv_msg->data, ca_mqtt_ctrl.info.dev_id, 1);
_ca_mqtt_data_report_child_device(recv_msg->data, ca_mqtt_ctrl.info.dev_id, 2);
_ca_mqtt_data_report_child_device(recv_msg->data, ca_mqtt_ctrl.info.dev_id, 3);
_ca_mqtt_data_report_child_device(recv_msg->data, ca_mqtt_ctrl.info.dev_id, 4);
break;
default:
break;
}
}
/* 释放数据 */
XFREE(MTYPE_CA_MQTT, recv_msg->data);
fifo_push(ca_mqtt_ctrl.fifo_id);
}
return NULL;
}
/* description: 配置保存函数
param:
return: */
int _ca_mqtt_config_save(vty_t* vty)
{
ca_coll_cfg_t *cfg = ca_coll_cfg_get();
vty_out(vty, "mqtt %s%s", cfg->is_MQTT ? "enable" : "disable", VTY_NEWLINE);
return 1;
}
/* Interface functions -------------------------------------------------------*/
/* description: 预初始化
param:
return: E_XXX */
int32_t ca_mqtt_init(void)
{
int32_t rv = E_ERROR;
/* 初始化配置 */
//snprintf(ca_mqtt_ctrl.info.server_ip, INET_ADDRSTRLEN, device_info.mqtt.server_ip);
//ca_mqtt_ctrl.info.server_port = device_info.mqtt.server_port;
//ca_mqtt_ctrl.info.alive_time = device_info.mqtt.alive_time;
//snprintf(ca_mqtt_ctrl.info.dev_id, CA_MQTT_DEV_ID_LEN, device_info.mqtt.dev_id);
//snprintf(ca_mqtt_ctrl.info.client_id, CA_MQTT_CLINET_ID_LEN, device_info.mqtt.client_id);
//snprintf(ca_mqtt_ctrl.info.username, CA_MQTT_USERNAME_LEN, device_info.mqtt.username);
//snprintf(ca_mqtt_ctrl.info.passwd, CA_MQTT_PASSWD_LEN, device_info.mqtt.passwd);
memcpy(&ca_mqtt_ctrl.info, &device_info.mqtt, sizeof(ca_mqtt_dev_info_t));
memset(ca_mqtt_ctrl.node, 0, sizeof(node_info_t)*NODE_NUM);
memset(&ca_mqtt_ctrl.state, 0, sizeof(ca_mqtt_state_t));
ca_mqtt_ctrl.client = NULL;
for (int i = 0; i < NODE_NUM; i++)
{
strcpy(ca_mqtt_ctrl.node[i].node_id, ca_mqtt_ctrl.info.dev_id);
}
/* 注册命令行 */
cmd_install_element(ENABLE_NODE, &ca_mqtt_server_set_cmd);
cmd_install_element(ENABLE_NODE, &ca_mqtt_alive_set_cmd);
cmd_install_element(ENABLE_NODE, &ca_mqtt_dev_id_set_cmd);
cmd_install_element(ENABLE_NODE, &ca_mqtt_client_id_set_cmd);
cmd_install_element(ENABLE_NODE, &ca_mqtt_username_set_cmd);
cmd_install_element(ENABLE_NODE, &ca_mqtt_passwd_set_cmd);
cmd_install_element(COMMON_NODE, &ca_mqtt_show_state_cmd);
/* 注册配置保存函数 */
rv = cmd_config_node_config_register(CONFIG_PRI_CA_MQTT, _ca_mqtt_config_save);
if (rv != E_NONE)
{
log_err(LOG_CA_MQTT, "Command save register ERROR %d!", rv);
return rv;
}
return E_NONE;
}
/* description: 初始化
param:
return: E_XXX */
int32_t ca_mqtt_init_after(void)
{
struct sched_param param;
pthread_attr_t attr;
pthread_t pid;
int rv = 0;
ca_coll_cfg_t *cfg = ca_coll_cfg_get();
if (!cfg->is_MQTT)
{
return E_NONE;
}
/* 初始化 fifo */
ca_mqtt_ctrl.fifo_id = fifo_create(CA_MQTT_FIFO, 32);
if (ca_mqtt_ctrl.fifo_id < 0)
{
log_err(LOG_CA_MQTT, "Open fifo " CA_MQTT_FIFO " error.");
return E_ERROR;
}
/* 配置线程RR调度优先级25 */
pthread_attr_init(&attr);
param.sched_priority = 25;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, &param);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
rv = pthread_create(&pid, &attr, _ca_mqtt_handle, NULL);
if (rv != 0)
{
log_err(LOG_CA_MQTT, "Can't create cable MQTT pthread %d.", rv);
return E_SYS_CALL;
}
else
{
thread_m_add("CA_MQTT_THREAD", pid);
}
pthread_attr_destroy(&attr);
return E_NONE;
}
/* description: 数据发送接口
param: data -
return: E_XXX */
int32_t ca_mqtt_data_report(ca_coll_dev_data_t *data)
{
ca_mqtt_msg_t msg;
ca_coll_dev_data_t *pkt = NULL;
/* 申请报文空间 */
pkt = XMALLOC_Q(MTYPE_CA_MQTT, sizeof(ca_coll_dev_data_t));
if (!pkt)
{
DBG(DBG_M_CA_MQTT_ERR, "Malloc ERR!\r\n");
return E_MEM;
}
/* 封装消息. */
memcpy(pkt, data, sizeof(ca_coll_dev_data_t));
msg.type = CA_MQTT_T_DATA;
msg.data = pkt;
/* 发送数据 */
if (fifo_write(ca_mqtt_ctrl.fifo_id, (void*)(&msg), sizeof(ca_mqtt_msg_t)) != sizeof(ca_mqtt_msg_t))
{
DBG(DBG_M_CA_MQTT_ERR, "Fifo write ERROR\r\n");
XFREE(MTYPE_CA_MQTT, pkt);
return E_ERROR;
}
return E_NONE;
}
/* description: MQTT 状态结构体获取
param: data -
return: ca_mqtt_state_t - MQTT */
ca_mqtt_state_t* ca_mqtt_state_get(void)
{
return &ca_mqtt_ctrl.state;
}
/* description: MQTT 状态显示
param:
return: */
void ca_mqtt_state_show(void)
{
ca_mqtt_state_t *state = &ca_mqtt_ctrl.state;
printh("Server %s:%d\r\n", ca_mqtt_ctrl.info.server_ip, ca_mqtt_ctrl.info.server_port);
printh("Alive %d\r\n", ca_mqtt_ctrl.info.alive_time);
printh("Device id %s\r\n", ca_mqtt_ctrl.info.dev_id);
printh("Client id %s\r\n", ca_mqtt_ctrl.info.client_id);
printh("Username %s\r\n", ca_mqtt_ctrl.info.username);
printh("Passwd %s\r\n", ca_mqtt_ctrl.info.passwd);
printh("Connect: %s\r\n\n", state->is_connect ? "yes" : "no");
}
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,3 @@
local_src := $(patsubst $(SOURCE_DIR)/%,%,$(wildcard $(SOURCE_DIR)/$(subdirectory)/*.c))
$(eval $(call make-library,$(subdirectory)/liba_process.a,$(local_src)))

@ -0,0 +1,215 @@
/*****************************************************************************
* file lib/process/process.c
* author YuLiang
* version 1.0.0
* date 26-Sep-2021
* brief This file provides all the process related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
#include <locale.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/watchdog.h>
#include "cmd.h"
#include "mtimer.h"
#include "process.h"
#include "hwgpio.h"
#include "fifo.h"
#include "ca_main.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint32_t start_time;
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 信号处理函数 */
void _signal_handler(int sig)
{
if (SIGSEGV == sig)
{
log_backtrace(LOG_LVL_ERR);
}
else if(SIGINT == sig
|| SIGTSTP == sig)
{
/* 屏蔽信号 */
return;
}
exit(-1);
}
/* Interface functions -------------------------------------------------------*/
/* description: 喂狗
param:
return: E_NONE - , E_XXXX - */
void wdg_clr(void)
{
static uint64_t cnt = 0;
/* 防止设备重启不成功, 此时不再喂狗, cpu依然会重启 */
if (is_system_reboot)
{
return;
}
GPIO_WATCHDOG((cnt++) & 0x1);
}
/* description: 数据处理初始化.
param:
return: (E_NONE),() */
int32_t process_init(void)
{
int32_t rv = E_NONE;
crc32_table_init();
rv |= ca_main();
return rv;
}
/* description: 数据处理初始化.
param:
return: (E_NONE),() */
int32_t process_init_after(void)
{
int32_t rv = E_NONE;
rv |= ca_main_after();
return rv;
}
/* description: 程序入口函数.
param:
return: */
int32_t main(int32_t argc, char **argv)
{
struct sigaction act;
/* 设置本地化信息为默认值. */
setlocale(LC_ALL, "");
/* 必须最前面, 初始化内存管理模块的基本参数. */
mtype_init_befor();
/* log初始化 */
log_open();
/* 初始化时定量清除 log */
log_clean();
log_out(LOG_DEFAULT, LOG_LVL_WARN, "System start!");
/* 设置信号处理的回调函数 */
act.sa_handler = _signal_handler;
sigemptyset(&act.sa_mask);
sigaction(SIGINT, &act, NULL);
sigaction(SIGSEGV, &act, NULL);
sigaction(SIGTSTP, &act, NULL);
/* 初始化cli等公共模块. */
cmd_init();
thread_m_init();
mtype_init();
dbg_init();
mtimer_init();
vtysh_init();
vtycmd_init();
gpio_init();
fifo_init();
log_handle_init();
/* 主处理函数初始化 */
process_init();
/* 配置恢复命令行启动 */
vtysh_config_recovery();
/* 后初始化 */
process_init_after();
/* 启动命令行 */
vtysh_shell_init();
vtycmd_cmd_init();
/* 初始化完成 */
is_system_init = TRUE;
/* 主循环, 点灯喂狗. */
for(;;)
{
sleep(1);
wdg_clr();
start_time++;
if (start_time > 86400)
{
reboot_system(LOG_DEFAULT, BOOT_TIMER);
while(1)
{
sleep(30);
}
}
/* 点 RUN 灯. */
if (start_time & 0x1)
{
GPIO_RUN_LED(0);
}
else
{
GPIO_RUN_LED(1);
}
}
return 0;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,297 @@
/*****************************************************************************
* file lib/management/array.c
* author YuLiang
* version 1.0.0
* date 22-Sep-2021
* brief This file provides all the array related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
/* 用户代码头文件. */
#include "array.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 确保设置的数组成员没有内存越界如果超出数组长度则重新realloc:
a --
len --
mem_type -- 使
return: void */
static void _array_len_ensure(array_t *a, uint32_t len, int32_t mem_type)
{
if (a->alloced > len)
{
return;
}
a->index = XREALLOC(mem_type, a->index, sizeof(void *) * (a->alloced * 2));
memset(&a->index[a->alloced], 0, sizeof(void *) * a->alloced);
a->alloced *= 2;
if (a->alloced <= len)
{
_array_len_ensure(a, len, mem_type);
}
}
/* 查找数组a的第一个空位置.
a --
return: */
uint32_t _array_empty_slot(array_t *a)
{
uint32_t i = 0;
for(i = 0; i < a->active; i++)
{
if (NULL == a->index[i])
{
return i;
}
}
return i;
}
/* Interface functions -------------------------------------------------------*/
/* 初始化数组:
size --
mem_type -- 使
return: */
array_t *array_init(uint32_t size, int32_t mem_type)
{
array_t *a = XMALLOC(mem_type, sizeof(array_t));
/* 如果大小为0,设置默认大小. */
if (0 == size)
{
size = ARRAY_MIN_SIZE;
}
a->alloced = size;
a->active = 0;
a->index = XMALLOC(mem_type, sizeof(void *) * size);
return a;
}
/* 设置数组相应索引位置的值:
a --
i --
val --
mem_type -- 使
return: void */
void array_set(array_t *a, uint32_t i, void *val, int32_t mem_type)
{
_array_len_ensure(a, i, mem_type);
a->index[i] = val;
if (a->active <= i)
{
a->active = i + 1;
}
}
/* 删除数组相应索引位置的值:
a --
i --
return: void */
void array_unset(array_t *a, uint32_t i)
{
if (i >= a->alloced)
{
return;
}
a->index[i] = NULL;
/* 不是最后一个元素直接返回. */
if (i + 1 != a->active)
{
return;
}
/* 如果是最后一个元素,则将当前可使用指针前移. */
while(--a->active)
{
if (a->index[a->active - 1] != NULL)
{
break;
}
}
}
/* 将数据放入数组的第一个空位置:
a --
val --
mem_type -- 使
return: */
uint32_t array_append(array_t *a, void *val, int32_t mem_type)
{
uint32_t i = 0;
i = _array_empty_slot(a);
_array_len_ensure(a, i, mem_type);
a->index[i] = val;
if (a->active <= i)
{
a->active = i + 1;
}
return i;
}
/* 复制数组a:
a --
mem_type -- 使
return: */
array_t *array_copy(array_t *a, int32_t mem_type)
{
unsigned int size = 0;
array_t *array = XMALLOC(mem_type, sizeof(array_t));
array->active = a->active;
array->alloced = a->alloced;
size = sizeof(void *) * (a->alloced);
array->index = XMALLOC(mem_type, size);
memcpy(array->index, a->index, size);
return array;
}
/* 将数组a和数组b合并成数组a:
a -- 1
b -- 2
mem_type -- 使
return: void */
void array_merge(array_t *a, array_t *b, int32_t mem_type)
{
uint32_t size = 0;
if (0 == b->alloced)
{
return;
}
size = sizeof(void *) * (a->alloced + b->alloced);
a->index = XREALLOC(mem_type, a->index, size);
memcpy(&a->index[a->active], b->index, sizeof(void *) * b->active);
a->active = a->active + b->active;
a->alloced = a->alloced + b->alloced;
}
/* 释放array_t:
a --
mem_type -- 使
return: void */
void array_free_wrapper(array_t *a, int32_t mem_type)
{
XFREE(mem_type, a);
}
/* 释放array_t->index:
a --
mem_type -- 使
return: void */
void array_free_index(array_t *a, int32_t mem_type)
{
XFREE(mem_type, a->index);
}
/* 释放array_t和array_t->index:
a --
mem_type -- 使
return: void */
void array_free(array_t *a, int32_t mem_type)
{
XFREE(mem_type, a->index);
XFREE(mem_type, a);
}
/* 查询数组a的数据i:
a --
i --
return: */
void *array_lookup(array_t *a, uint32_t i)
{
return (i >= a->active) ? NULL : a->index[i];
}
/* 获取数组a中有效数据的个数:
a --
return: void */
uint32_t array_count(array_t *a)
{
uint32_t i = 0;
uint32_t count = 0;
for (i = 0; i < a->active; i++)
{
if (a->index[i] != NULL)
{
count++;
}
}
return count;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,530 @@
/******************************************************************************
* file lib/management/better_log.c
* author YuLiang
* version 1.0.0
* date 14-Sep-2021
* brief This file provides all the log operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <execinfo.h>
/* 用户代码头文件. */
#include <fifo.h>
/* Private define ------------------------------------------------------------*/
#define LOG_DB_LOCK pthread_mutex_lock(&log_sys->log_db_mutex)
#define LOG_DB_UNLOCK pthread_mutex_unlock(&log_sys->log_db_mutex)
#define LOG_OUT 0
#define LOG_SHOW 1
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
log_sys_t *log_sys;
static char *log_str = NULL;
/* log等级. */
static const log_lvl_t log_priority[] =
{
{LOG_LVL_ERR, "err"},
{LOG_LVL_WARN, "warn"},
{LOG_LVL_NOTIF, "notif"},
{LOG_LVL_INFO, "info"},
{LOG_LVL_DBG, "debug"},
{-1, NULL}
};
/* log模块. */
static const log_module_t log_module_names[] =
{
{LOG_DEFAULT, "DEFAULT"},
{LOG_CLI, "CLI"},
{LOG_MEMORY, "MEMORY"},
{LOG_FIFO, "FIFO"},
{LOG_GPIO, "GPIO"},
{LOG_COLL, "COLLECT"},
{LOG_CA_DB, "CA_DB"},
{LOG_CA_DBG, "CA_DBG"},
{LOG_CA_MQTT, "CA_MQTT"},
{LOG_CA_LAND, "CA_LAND"},
{-1, NULL}
};
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 文件log输出底层函数. */
static void _log_out_db(LOG_MODULE_E module, LOG_LVL_E priority, const char *va_str)
{
log_sys_t *log = log_sys;
char time_str[TIME_STR_LEN] = {0};
char *zErrMsg = NULL;
static uint64_t logCnt = 0;
time_string(log->timestamp_precision, time_str, sizeof(time_str));
LOG_DB_LOCK;
snprintf(log_str, LOG_CMD_LEN,
"INSERT INTO better_log (LEVEL,LOG) VALUES (%d, \"%s %s-%s: %s\"); ",
priority, time_str, log_priority[priority].describe, log_module_names[module].describe, va_str ); //id 已设为自增
if (sqlite3_exec( log->db, log_str, 0, 0, &zErrMsg ) != SQLITE_OK)
{
printh("SQL INSERT error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
}
/*定量清除log*/
logCnt++;
if (logCnt >= 100)
{
clock_t begin,end;
begin = clock();
log_clean();
end = clock();
printh("Log clean runtimer : %lf\r\n",(double)(end-begin)/CLOCKS_PER_SEC);
logCnt = 0;
}
LOG_DB_UNLOCK;
}
/* 解日志输出fifo数据封装 */
static void _log_out(_log_out_t *data)
{
_log_out_db(data->module, data->lvl, data->log_out_str);
}
/* 串口日志输出 */
static void _log_out_std( LOG_MODULE_E module, LOG_LVL_E priority, const char *va_str )
{
log_sys_t *log = log_sys;
char time_str[TIME_STR_LEN] = {0};
time_string(log->timestamp_precision, time_str, sizeof(time_str));
printh("%s %s-%s: %s\n", time_str, log_priority[priority].describe, log_module_names[module].describe, va_str);
}
/* 将日志按照格式串口打印 */
static int _log_show_print(void *data, int argc, char **argv, char **azColName)
{
printh("LOG id %s: %s\r\n", argv[0], argv[2]);
return 0;
}
/* log打印底层函数 */
static void _log_show(_log_show_t *data)
{
log_sys_t *log = log_sys;
char *zErrMsg = NULL;
LOG_DB_LOCK;
memset(log_str, 0, LOG_CMD_LEN);
switch (data->type)
{
case LOG_SHOW_CNT: //打印指定数量的日志
snprintf(log_str, LOG_CMD_LEN, "SELECT * FROM better_log ORDER BY id DESC LIMIT %d;", data->param);
break;
case LOG_SHOW_LVL: //打印指定等级的日志
snprintf(log_str, LOG_CMD_LEN, "SELECT * FROM better_log WHERE LEVEL = %d ORDER BY id DESC LIMIT 100;", data->param);
break;
case LOG_SHOW_KEYWORD: //打印含关键词的日志
if (data->param <= 0)
{
snprintf(log_str, LOG_CMD_LEN, "SELECT * FROM better_log WHERE LOG GLOB \'*%s*\' ORDER BY id DESC;",
data->log_show_str);
}
else
{
snprintf(log_str, LOG_CMD_LEN, "SELECT * FROM better_log WHERE LOG GLOB \'*%s*\' ORDER BY id DESC LIMIT %d;",
data->log_show_str, data->param);
}
break;
default: //打印所有日志
snprintf(log_str, LOG_CMD_LEN, "SELECT * FROM better_log ORDER BY id DESC;");
break;
}
if (sqlite3_exec(log->db, log_str, _log_show_print, 0, &zErrMsg) != SQLITE_OK)
{
printh("SQL show error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
}
LOG_DB_UNLOCK;
}
/* 封装数据并写fifo */
int32_t _log_msg_send(uint32_t type, void *data)
{
_log_msg_t log_msg;
/* 封装消息. */
log_msg.type = type;
log_msg.data = data;
/* 发送消息 */
if (fifo_write(log_sys->log_fifo_id, (void*)(&log_msg), sizeof(_log_msg_t)) != sizeof(_log_msg_t))
{
DBG(DBG_M_FIFO, "LOG write ERROR!\r\n");
return E_ERROR;
}
return E_NONE;
}
/* 经由fifo输出日志 */
void _log_fifo_out(LOG_MODULE_E module, LOG_LVL_E priority, const char *va_str)
{
_log_out_t *log_data = NULL;
log_data = XMALLOC_Q(MTYPE_LOG, sizeof(_log_out_t));
if (!log_data)
{
return;
}
log_data->module = module;
log_data->lvl = priority;
snprintf(log_data->log_out_str, LOG_STR_LEN, va_str);
_log_msg_send(LOG_OUT, log_data);
}
/* 读取log fifo数据循环线程 */
void *_log_handle(void *arg)
{
_log_msg_t *recv_msg = NULL;
while(1)
{
if (fifo_read(log_sys->log_fifo_id, (void **)&recv_msg) != 0)
{
DBG(DBG_M_FIFO, "ERROR at fifo %d read!\r\n", log_sys->log_fifo_id);
continue;
}
if (recv_msg->type == LOG_OUT) //输出日志,写数据库
{
_log_out((_log_out_t*) recv_msg->data);
}
else if (recv_msg->type == LOG_SHOW) //打印日志,读数据库
{
_log_show((_log_show_t*) recv_msg->data);
}
XFREE(MTYPE_LOG, recv_msg->data);
fifo_push(log_sys->log_fifo_id);
}
return NULL;
}
/* Interface functions -------------------------------------------------------*/
/* log打印输出函数. */
#define BLOG_FUNC(FUNCNAME,PRIORITY) \
void FUNCNAME(LOG_MODULE_E module, const char *format, ...) \
{ \
char str[LOG_STR_LEN] = {0}; \
log_sys_t *log = log_sys; \
if (NULL == log) return; \
va_list args; \
va_start(args, format); \
vsnprintf(str, LOG_STR_LEN, format, args); \
va_end(args); \
if ((1 << PRIORITY) & log->enable_lvl[LOG_MODE_STDOUT]) \
_log_out_std(module, PRIORITY, str); \
if (((1 << PRIORITY) & log->enable_lvl[LOG_MODE_FILE]) && log->db){ \
if (log_sys->log_fifo_id) \
_log_fifo_out(module, PRIORITY, str); \
else \
_log_out_db(module, PRIORITY, str);} \
}
BLOG_FUNC(log_err, LOG_LVL_ERR)
BLOG_FUNC(log_warn, LOG_LVL_WARN)
BLOG_FUNC(log_info, LOG_LVL_INFO)
BLOG_FUNC(log_notice, LOG_LVL_NOTIF)
BLOG_FUNC(log_debug, LOG_LVL_DBG)
#undef BLOG_FUNC
/* description: log输出.
param: module --
priority --
return: */
void log_out(LOG_MODULE_E module, LOG_LVL_E priority, const char *format, ...)
{
char str[LOG_STR_LEN] = {0}; \
log_sys_t *log = log_sys;
if (NULL == log) return;
va_list args;
va_start(args, format);
vsnprintf(str, LOG_STR_LEN, format, args);
va_end (args);
/* 串口log. */
if ((1 << priority) & log->enable_lvl[LOG_MODE_STDOUT])
_log_out_std(module, priority, str);
/* 判断是否是文件输出 */
if (((1 << priority) & log->enable_lvl[LOG_MODE_FILE]) && log->db)
_log_out_db(module, priority, str);
}
/* 打印日志函数 */
void log_show(int32_t show_cnt, LOG_LVL_E priority, const char *key_word)
{
_log_show_t *log_data = NULL;
log_data = XMALLOC_Q(MTYPE_LOG, sizeof(_log_show_t));
if (!log_data)
{
return;
}
if (priority != LOG_LVL_MAX) // 按等级打印日志
{
log_data->type = LOG_SHOW_LVL;
log_data->param = priority;
}
else if (key_word != NULL) // 高级打印功能
{
log_data->type = LOG_SHOW_KEYWORD;
log_data->param = show_cnt;
snprintf(log_data->log_show_str, LOG_STR_LEN, key_word);
}
else if (show_cnt > 0) // 按数量打印日志
{
log_data->type = LOG_SHOW_CNT;
log_data->param = show_cnt;
}
else
{
log_data->type = LOG_SHOW_MAX;
}
_log_msg_send(LOG_SHOW, log_data);
}
/* description: log系统初始化.
param:
return: (0),(-1) */
int32_t log_open()
{
log_sys_t *log = NULL;
int32_t i = 0;
int32_t rv = 0;
char *sql = NULL;
char *zErrMsg = NULL;
/* 申请内存. */
log_str = XMALLOC(MTYPE_LOG, LOG_CMD_LEN);
log_sys = XMALLOC(MTYPE_LOG, sizeof(log_sys_t));
if (NULL == log_sys)
{
return E_MEM;
}
log = log_sys;
pthread_mutex_init(&log->log_db_mutex, NULL);
/* 打开 log 数据库. */
log->filename = XSTRDUP(MTYPE_LOG, LOG_FILE);
rv = sqlite3_open(log->filename, &log->db);
if (rv)
{
log->db = NULL;
printf("Can't open database: %s\r\n", sqlite3_errmsg(log->db));
return E_SYS_CALL;
}
/* 创建表. */
sql = "CREATE TABLE IF NOT EXISTS better_log(" \
"ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," \
"LEVEL INT8 NOT NULL," \
"LOG TEXT);";
if (sqlite3_exec(log->db, sql, 0, 0, &zErrMsg) != SQLITE_OK)
{
printf("SQL create error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
}
/* 设置默认log级别输出方式 */
for (i = 0; i < LOG_MODE_MAX; i++)
{
log->enable_lvl[i] = 0;
}
log->enable_lvl[LOG_MODE_FILE] = (1 << LOG_LVL_ERR) | (1 << LOG_LVL_WARN) | (1 << LOG_LVL_NOTIF);
log->enable_lvl[LOG_MODE_STDOUT] = (1 << LOG_LVL_ERR) | (1 << LOG_LVL_WARN) | (1 << LOG_LVL_NOTIF);
log->enable_lvl[LOG_MODE_MONITOR] = (1 << LOG_LVL_ERR) | (1 << LOG_LVL_WARN) | (1 << LOG_LVL_NOTIF);
log->default_lvl = 0;
return E_NONE;
}
/* description: 配置对应等级的log的输出方式.
param: mode --
log_level --
return: */
void log_set_level(LOG_MODE_E mode, LOG_LVL_E log_level)
{
log_sys->enable_lvl[mode] |= (1 << log_level);
}
/* description: 取消对应等级的log的输出方式.
param: mode --
log_level --
return: */
void log_unset_level(LOG_MODE_E mode, LOG_LVL_E log_level)
{
log_sys->enable_lvl[mode] &= ~(1 << log_level);
}
/* description: 根据传入的字符串返回相应的log优先级.
param: lvl_name --
return: (LOG_LVL_E) */
int32_t log_level_get_by_name(const char *lvl_name)
{
int32_t level = LOG_LVL_MAX;
for (level = 0 ; log_priority[level].describe != NULL ; level++)
if (!strncmp(lvl_name, log_priority[level].describe, 2))
return log_priority[level].lvl;
return LOG_LVL_MAX;
}
/* 打印堆栈使用情况: */
/* description: 根据传入的字符串返回相应的log优先级.
param: priority -- log
return: */
void log_backtrace(int32_t priority)
{
void *array[BACKTRACE_SIZE] = {NULL};
int32_t size = 0;
int32_t i = 0;
char **strings = NULL;
size = backtrace(array, BACKTRACE_SIZE);
if ((size <= 0) || ((size_t)size > BACKTRACE_SIZE))
{
log_err(LOG_DEFAULT, "Cannot get backtrace, returned invalid # of frames %d "
"(valid range is between 1 and %d)", size, BACKTRACE_SIZE);
return;
}
log_out(LOG_DEFAULT, priority, "Backtrace for %d stack frames:", size);
strings = backtrace_symbols(array, size);
if (!strings)
{
log_out(LOG_DEFAULT, priority, "Cannot get backtrace symbols (out of memory?)");
for (i = 0; i < size; i++)
log_out(LOG_DEFAULT, priority, "[bt %d] %p", i, array[i]);
}
else
{
for (i = 0; i < size; i++)
log_out(LOG_DEFAULT, priority, "[bt %d] %s",i,strings[i]);
free(strings);
}
}
/* 删除多余的 log 保留 5000 条. */
void log_clean(void)
{
log_sys_t *log = log_sys;
char *zErrMsg = NULL;
const char *sql = "delete from better_log where id<(select Max(id) from better_log)-5000;";
if (sqlite3_exec(log->db, sql, 0, 0, &zErrMsg) != SQLITE_OK)
{
printh("SQL delete error: %s\r\n", zErrMsg);
sqlite3_free(zErrMsg);
}
}
int32_t log_handle_init(void)
{
struct sched_param param;
pthread_attr_t attr;
pthread_t pid;
int rv = 0;
/* 初始化log fifo */
log_sys->log_fifo_id = fifo_create(LOG_DB_FIFO, 32);
if (log_sys->log_fifo_id < 0)
{
log_out(LOG_DEFAULT, LOG_LVL_ERR, "Open fifo " LOG_DB_FIFO " error.");
return E_ERROR;
}
/* 配置线程RR调度优先级50 */
pthread_attr_init(&attr);
param.sched_priority = 25;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, &param);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
rv = pthread_create(&pid, &attr, _log_handle, NULL);
if (rv != 0)
{
log_out(LOG_DEFAULT, LOG_LVL_ERR, "PD can't create log db pthread %d.", rv);
return E_SYS_CALL;
}
else
{
thread_m_add("LOG_DB_THREAD", pid);
}
pthread_attr_destroy(&attr);
return E_NONE;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

File diff suppressed because it is too large Load Diff

@ -0,0 +1,688 @@
/******************************************************************************
* file lib/management/cli.c
* author YuLiang
* version 1.0.0
* date 10-Sep-2021
* brief This file provides all the cli related operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
/* Standard includes. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <termios.h>
#include <pthread.h>
/* 外部程序库头文件. */
#include <readline/readline.h>
#include <readline/history.h>
/* User includes. */
#include "cli.h"
#include "list.h"
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static int32_t _cli_help(const char *cmd_str);
static int32_t _cli_version(const char *cmd_str);
static int32_t _cli_exit(const char *cmd_str);
/* The definition of the "help" command. This command is always at the front
of the list of registered commands. */
static const cli_command_t _cli_cmd_help =
{
"help",
"List all command.",
_cli_help,
0
};
static const cli_command_t _cli_cmd_version =
{
"version",
"Show device version information.",
_cli_version,
0
};
static const cli_command_t _cli_cmd_exit =
{
"exit",
"Returns the upper-level node.",
_cli_exit,
0
};
/* The definition of the list of commands. Commands that are registered are
added to this list. */
static cli_node_t _cli_node[CLI_NODE_COUNT] =
{
{"common", 0xffff, CLI_NODE_COMMON, {NULL, NULL}},
{"Username: ", 0, CLI_NODE_PASSWORD, {NULL, NULL}},
{"config", 0xffff, CLI_NODE_PASSWORD, {NULL, NULL}},
};
/* 保存readline命令行历史的文件. */
static const char _cli_history_file[128] = "/home/embed/.command_line_history";
/* 保存readline命令行内容的buf. */
static char *_cli_cmd_inpurt = NULL;
/* 当前cli所在的节点. */
static CLI_NODE_E _cli_now = CLI_NODE_PASSWORD;
/* 命令行用户链表. */
static struct list_head _cli_user_list;
/* cli线程pid. */
static pthread_t _cli_pid;
/* Private function prototypes -----------------------------------------------*/
extern char* version_get();
extern char* version_date_get();
static int8_t _cli_param_num_get(const char *cmd_str);
static cli_list_item_t *_cli_cmd_search(const char *cmd_str, CLI_NODE_E node);
/* Internal functions --------------------------------------------------------*/
/* 将node节点下的命令复制到cmd_list_new链表中并排序. */
static int32_t _cli_cmd_copy_for_node(struct list_head *cmd_list_new, CLI_NODE_E node)
{
struct list_head *cmd_list = NULL;
cli_list_item_t *cmd_item = NULL;
cli_list_item_t *cmd_item_new = NULL;
cli_list_item_t *cmd_item_temp = NULL;
cli_list_item_t *cmd_item_next = NULL;
int32_t rv = E_NONE;
cmd_list = &_cli_node[node].list;
list_for_each_entry(cmd_item, cmd_list, list)
{
/* 复制命令 */
cmd_item_new = XMALLOC(MTYPE_CLI, sizeof(cli_list_item_t));
if (NULL == cmd_item_new)
{
goto CMD_COPY_FOR_NODE_ERROR;
}
memcpy(cmd_item_new, cmd_item, sizeof(cli_list_item_t));
/* 命令排序 */
list_for_each_entry_reverse(cmd_item_temp, cmd_list_new, list)
{
if (strcmp(cmd_item_new->cmd->cmd_str, cmd_item_temp->cmd->cmd_str) > 0)
{
list_add(&cmd_item_new->list, &cmd_item_temp->list);
break;
}
}
/* 最小的命令放在链表头 */
if (&cmd_item_temp->list == cmd_list_new)
{
list_add(&cmd_item_new->list, &cmd_item_temp->list);
}
}
return rv;
/* 错误回滚已经申请的内存 */
CMD_COPY_FOR_NODE_ERROR:
list_for_each_entry_safe(cmd_item_temp, cmd_item_next, cmd_list_new, list)
{
list_del(&cmd_item_temp->list);
XFREE(MTYPE_CLI, cmd_item_temp);
}
return rv;
}
/* The callback function tyhat is executed when "help" is entered. This is the
only default command that is always present. */
static int32_t _cli_help(const char *cmd_str)
{
struct list_head cmd_list_new;
cli_list_item_t *cmd_item_temp = NULL;
cli_list_item_t *cmd_item_next = NULL;
INIT_LIST_HEAD(&cmd_list_new);
/* 复制命令 */
LD_E_RETURN(DBG_M_CLI, _cli_cmd_copy_for_node(&cmd_list_new, _cli_now));
LD_E_RETURN(DBG_M_CLI, _cli_cmd_copy_for_node(&cmd_list_new, CLI_NODE_COMMON));
/* 打印信息 */
list_for_each_entry(cmd_item_temp, &cmd_list_new, list)
{
printf("%-32s", cmd_item_temp->cmd->cmd_str);
printf("%s\r\n", cmd_item_temp->cmd->help_str);
}
printf("\n");
/* 释放内存 */
list_for_each_entry_safe(cmd_item_temp, cmd_item_next, &cmd_list_new, list)
{
list_del(&cmd_item_temp->list);
XFREE(MTYPE_CLI, cmd_item_temp);
}
return E_NONE;
}
static int32_t _cli_version(const char *cmd_str)
{
printf("Welcome To Power IoT Application, By LandPower Embed Application Team.\r\n");
printf("Copyright(c) 2021 LandPower. All rights reserved.\r\n");
printf("Software version %s, compile time is %s.\r\n\n", version_get(), version_date_get());
return E_NONE;
}
static int32_t _cli_exit(const char *cmd_str)
{
cli_quit_node();
return E_NONE;
}
/* Return the number of parameters that follow the command name. */
static int8_t _cli_param_num_get(const char *cmd_str)
{
int8_t num = 0;
bool is_end = FALSE;
/* Count the number of space delimited words in pcCommandString. */
while(*cmd_str != 0)
{
if (' ' == (*cmd_str))
{
if (is_end != TRUE)
{
num++;
is_end = TRUE;
}
}
else
{
is_end = FALSE;
}
cmd_str++;
}
/* If the command string ended with spaces, then there will have been too
many parameters counted. */
if( is_end == TRUE )
{
num--;
}
/* The value returned is one less than the number of space delimited words,
as the first word should be the command itself. */
return num;
}
/* 命令行查找 */
static cli_list_item_t *_cli_cmd_search(const char *cmd_str, CLI_NODE_E node)
{
struct list_head *cmd_list = &_cli_node[node].list;
cli_list_item_t *cmd_item = NULL;
const char *cmd_str_register = NULL;
size_t cmd_str_len = 0;
/* Search for the command string in the list of registered commands. */
list_for_each_entry(cmd_item, cmd_list, list)
{
cmd_str_register = cmd_item->cmd->cmd_str;
cmd_str_len = strlen(cmd_str_register);
/* To ensure the string lengths match exactly, so as not to pick up
a sub-string of a longer command, check the byte after the expected
end of the string is either the end of the string or a space before
a parameter. */
if ((cmd_str[cmd_str_len] != ' ') && (cmd_str[cmd_str_len] != 0x00))
{
continue;
}
if (0 == strncmp(cmd_str, cmd_str_register, cmd_str_len))
{
return cmd_item;
}
}
return NULL;
}
/* 获取命令行前缀 */
char *_cli_prefix_get(char *host)
{
static char buf[100] = {0};
if (0xffff == _cli_node[_cli_now].index)
{
snprintf(buf, sizeof(buf), "%s(%s)> ", host, _cli_node[_cli_now].name);
}
else
{
snprintf(buf, sizeof(buf), "%s(%s-%d)> ", host, _cli_node[_cli_now].name, _cli_node[_cli_now].index);
}
return buf;
}
/* readline初始化 */
void _cli_readline_init(void)
{
/* 修改自己的按键操作. */
//rl_bind_key('?', (rl_command_func_t *)vtysh_rl_question);
//rl_bind_key('\t', (rl_command_func_t *)vtysh_rl_completion);
/* do not append space after completion. It will be appended
* in new_completion() function explicitly. */
rl_completion_append_character = '\0';
read_history(_cli_history_file);
}
/* 密码处理函数 */
static int32_t _cli_process_password(const char * const cmd_str)
{
static cli_user_t user_login;
cli_user_t *user = NULL;
/* 表示在输入username */
if (0 == _cli_node[_cli_now].index)
{
/* 保存username,并进入输入password模式 */
_cli_node[_cli_now].index = 1;
snprintf(_cli_node[_cli_now].name, CLI_NODE_MAME_LEN, "Password: ");
snprintf(user_login.username, CLI_USERNAME_LEN, "%s", cmd_str);
return E_NONE;
}
else
{
_cli_node[_cli_now].index = 0;
snprintf(_cli_node[_cli_now].name, CLI_NODE_MAME_LEN, "Username: ");
/* 保存password,比较输入正确性 */
snprintf(user_login.password, CLI_USERNAME_LEN, "%s", cmd_str);
list_for_each_entry(user, &_cli_user_list, list)
{
if (0 == strcmp(user_login.username, user->username)
&& 0 == strcmp(user_login.password, user->password))
{
/* 找到匹配 */
printf("\r\n\n");
cli_entry_node(CLI_NODE_CONFIG, 0xffff);
return E_NONE;
}
}
}
return E_NOT_FOUND;
}
/* 添加一个新用户 */
int32_t _cli_user_add(const cli_user_t* const user)
{
cli_user_t *user_new = NULL;
user_new = XMALLOC(MTYPE_CLI, sizeof(cli_user_t));
if (NULL == user_new)
{
return E_MEM;
}
memcpy(user_new, user, sizeof(cli_user_t));
list_add(&user_new->list, &_cli_user_list);
return E_NONE;
}
void *_cli_handle(void *arg)
{
char *cmd = NULL;
/* 主循环 */
for(;;)
{
/* 输入命令. */
cmd = cli_shell_gets();
if (NULL == cmd)
{
continue;
}
/* 执行命令. */
cli_process_command(cmd);
}
}
/* Interface functions -------------------------------------------------------*/
/* description: 命令行注册函数.
param: cmd -- 要注册的命令行结构体
node -- 要注册到的节点
return: E_NONE -- OK
其他 -- ERROR */
int32_t cli_register_command(const cli_command_t* const cmd, CLI_NODE_E node)
{
struct list_head *cmd_list = &_cli_node[node].list;
cli_list_item_t *cmd_item = NULL;
/* Check the parameter is not NULL. */
if (NULL == cmd)
{
return E_NULL;
}
/* Create a new list item that will reference the command being registered. */
cmd_item = XMALLOC(MTYPE_CLI, sizeof(cli_list_item_t));
if (NULL == cmd_item)
{
return E_MEM;
}
/* Reference the command being registered from the newly created list item. */
cmd_item->cmd = cmd;
/* The new list item will get added to the end of the list. */
list_add(&cmd_item->list, cmd_list);
return E_NONE;
}
/* description: 命令行注册函数.
param: cmd_str -- 要执行的命令行
return: E_NONE -- OK
其他 -- ERROR */
int32_t cli_process_command(const char * const cmd_str)
{
static const cli_list_item_t *cmd_item = NULL;
int32_t rv = E_NONE;
/* 输入密码的过程不同于执行命令的过程 */
if (CLI_NODE_PASSWORD == _cli_now)
{
if (_cli_process_password(cmd_str) != E_NONE)
{
printf("Username or password is not match!!!\r\n\n");
return E_NOT_FOUND;
}
return E_NONE;
}
cmd_item = _cli_cmd_search(cmd_str, (CLI_NODE_E)_cli_now);
if (NULL == cmd_item)
{
cmd_item = _cli_cmd_search(cmd_str, CLI_NODE_COMMON);
}
/* The command has been found. Check it has the expected
number of parameters. If cExpectedNumberOfParameters is -1,
then there could be a variable number of parameters and no
check is made. */
if (cmd_item != NULL)
{
if (cmd_item->cmd->param_num >= 0
&& _cli_param_num_get(cmd_str) > cmd_item->cmd->param_num )
{
rv = E_BAD_PARAM;
}
}
if ((cmd_item != NULL) && (rv != E_NONE))
{
/* The command was found, but the number of parameters with the command
was incorrect. */
printf("%s", cli_param_erro);
cmd_item = NULL;
}
else if(cmd_item != NULL)
{
/* Call the callback function that is registered to this command. */
rv = cmd_item->cmd->function(cmd_str);
if (rv != E_NONE)
{
printf("Command(%s) return %d.\r\n\n", cmd_item->cmd->cmd_str, rv);
}
}
else
{
/* pxCommand was NULL, the command was not found. */
printf("Command not recognised.\r\n\n");
rv = E_NOT_FOUND;
}
return rv;
}
/* description: 进入命令行节点.
param: cmd_str -- 命令字符串
param_index -- 需要获取的参数索引
param_len -- 获取的参数长度
return: char* -- 获取的参数字符串 */
const char *cli_parameter_get(const char *cmd_str, int32_t param_index, OUT int32_t *param_len)
{
int32_t index = 0;
const char *param_str = NULL;
*param_len = 0;
while(index < param_index)
{
/* Index the character pointer past the current word. If this is the start
of the command string then the first word is the command itself. */
while(((*cmd_str) != 0x00 ) && ((*cmd_str) != ' '))
{
cmd_str++;
}
/* Find the start of the next string. */
while(((*cmd_str) != 0x00) && (' ' == (*cmd_str)))
{
cmd_str++;
}
/* Was a string found? */
if (*cmd_str != 0x00)
{
/* Is this the start of the required parameter? */
index++;
if (index == param_index)
{
/* How long is the parameter? */
param_str = cmd_str;
while(((*cmd_str) != 0x00 ) && ((*cmd_str) != ' '))
{
(*param_len)++;
cmd_str++;
}
if (*param_len == 0 || *param_len >= CLI_PARAM_LEN)
{
param_str = NULL;
}
break;
}
}
else
{
break;
}
}
return param_str;
}
/* description: 进入命令行节点.
param: node -- 节点号
index -- 节点内部索引
return: E_NONE -- OK
其他 -- ERROR */
int32_t cli_entry_node(CLI_NODE_E node, int16_t index)
{
if (node >= CLI_NODE_COUNT)
{
return E_BAD_PARAM;
}
_cli_now = node;
_cli_node[_cli_now].index = index;
return E_NONE;
}
/* description: 返回上一级节点.
param:
return: */
void cli_quit_node(void)
{
_cli_now = _cli_node[_cli_now].upper_node;
}
/* description: 命令行读取.
param:
return: char* -- 读取的一行命令 */
char *cli_shell_gets(void)
{
HIST_ENTRY *last = NULL;
struct termios new_setting,init_setting;
/* readline要求自己释放其返回的buf. */
if (_cli_cmd_inpurt)
{
free(_cli_cmd_inpurt);
_cli_cmd_inpurt = NULL;
}
/* 获取一行命令. */
if (CLI_NODE_PASSWORD == _cli_now)
{
/* 如果是输入密码则关闭回显. */
if (1 == _cli_node[_cli_now].index)
{
tcgetattr(0, &init_setting);
new_setting = init_setting;
new_setting.c_lflag &= ~ECHO;
tcsetattr(0,TCSANOW,&new_setting);
}
_cli_cmd_inpurt = readline(_cli_node[_cli_now].name);
if (1 == _cli_node[_cli_now].index)
{
tcsetattr(0,TCSANOW,&init_setting);
}
}
else
{
_cli_cmd_inpurt = readline(_cli_prefix_get("Power_IoT"));
/* 如果命令有效记录历史. */
if (_cli_cmd_inpurt && *_cli_cmd_inpurt)
{
using_history();
last = previous_history();
if (!last || strcmp (last->line, _cli_cmd_inpurt) != 0)
{
add_history(_cli_cmd_inpurt);
append_history(1, _cli_history_file);
}
}
}
//if (strlen(_cli_cmd_inpurt) > 0)
//{
// log_warn(LOG_CLI, "\"%s\" is input.", _cli_cmd_inpurt);
//}
return _cli_cmd_inpurt;
}
/* description: 命令行初始函数.
param:
return: */
int32_t cli_init(void)
{
struct sched_param param;
pthread_attr_t attr;
cli_user_t user_default;
int32_t i = 0;
int32_t rv = 0;
/* 初始化readline */
_cli_readline_init();
/* 初始化命令节点数据链表 */
for(i = 0; i < CLI_NODE_COUNT; i++)
{
INIT_LIST_HEAD(&_cli_node[i].list);
}
/* 注册公有命令 */
cli_register_command(&_cli_cmd_help, CLI_NODE_COMMON);
cli_register_command(&_cli_cmd_version, CLI_NODE_COMMON);
cli_register_command(&_cli_cmd_exit, CLI_NODE_COMMON);
/* 初始化用户列表 */
INIT_LIST_HEAD(&_cli_user_list);
/* 添加默认用户 */
memset(&user_default, 0, sizeof(cli_user_t));
snprintf(user_default.username, CLI_USERNAME_LEN, CLI_USERNAME_DEFAULT);
snprintf(user_default.password, CLI_USERNAME_LEN, CLI_PASSWORD_DEFAULT);
_cli_user_add(&user_default);
/* 配置线程RR调度,优先级50 */
pthread_attr_init(&attr);
param.sched_priority = 10;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, &param);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
rv = pthread_create(&_cli_pid, &attr, _cli_handle, NULL);
if (rv != 0)
{
DBG(DBG_M_CLI, "Can't create pthread %d\r\n", rv);
}
else
{
thread_m_add("CLI", _cli_pid);
}
pthread_attr_destroy(&attr);
return E_NONE;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

File diff suppressed because it is too large Load Diff

@ -0,0 +1,708 @@
/******************************************************************************
* file lib/management/common.c
* author YuLiang
* version 1.0.0
* date 14-Sep-2021
* brief This file provides all the common operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
#include <sys/time.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* 用户代码头文件. */
#include "vty.h"
/* Private define ------------------------------------------------------------*/
/* CRC32 使用. */
#define CRC32_CHAR_BIT 8
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* 时间缓存结构体. */
typedef struct _time_cache
{
time_t last; /* 最后一次时间缓存数据. */
size_t len; /* buf中数据的长度. */
char buf[TIME_STR_LEN]; /* 时间数据转化的字符串. */
} time_cache_t;
/* Private variables ---------------------------------------------------------*/
static struct timeval sd_start, sd_end;
static uint32_t crc32Table[256];
extern int8_t is_system_reboot;
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 在时间后面根据precision长度,添加更加精确的时间字符串. */
static size_t _time_string_prec_add(char *buf, size_t len, int32_t precision, struct timeval *clock)
{
static const int divisor[] = {0, 100000, 10000, 1000, 100, 10, 1};
char *p = NULL;
/* 最多统计到us */
if (precision > 6)
precision = 6;
p = buf + len + 1 + precision;
*p-- = '\0';
clock->tv_usec /= divisor[precision];
do
{
*p-- = '0' + (clock->tv_usec % 10);
clock->tv_usec /= 10;
}
while(--precision > 0);
*p = '.';
return len + 1 + precision;
}
/* Interface functions -------------------------------------------------------*/
/* description: 将字符串转为小写.
param: str --
return: */
char *str_to_lower(char *str)
{
uint32_t i = 0;
if (str != NULL)
{
for(i = 0; str[i] != '\0'; i++)
{
str[i] = tolower(str[i]);
}
}
return str;
}
/* description: 去掉字符串中的多余空格.
param: str --
omit_end -- omit_end(TRUE)
omit_end(FALSE)1
return: */
char *str_omit_space(char *str, bool omit_end)
{
char *front = str;
char *last = str;
if (NULL == str)
{
return NULL;
}
while(' ' == *front)
front++;
while((*front) != '\0')
{
if (' ' == *front)
{
while((*++front) == ' ');
if ('\0' == *front && omit_end)
;
else
{
*last = ' ';
last++;
}
}
else
{
*last = *front;
front++;
last++;
}
}
*last = '\0';
return str;
}
/* description: 根据传入的精度precision,将时间字符串填到buf.
param: precision -- ,
buf -- buffer
buflen -- buf
return: ,,0 */
size_t time_string(int32_t precision, char *buf, size_t buflen)
{
static time_cache_t cache;
struct timeval clock;
/* 获取时间数据clock. */
gettimeofday(&clock, NULL);
/* 更新时间到字符串,cache是静态的,如果两次time_string调用在1秒之内,将沿用上次的cache. */
if (cache.last != clock.tv_sec)
{
struct tm *tm = NULL;
cache.last = clock.tv_sec;
tm = localtime(&cache.last);
cache.len = strftime(cache.buf, sizeof(cache.buf), "%Y/%m/%d %H:%M:%S", tm);
}
if (buflen > cache.len)
{
memcpy(buf, cache.buf, cache.len);
/* 计算秒之后的精度. */
if ((precision > 0) && (buflen > cache.len + 1 + precision))
return _time_string_prec_add(buf, cache.len, precision, &clock);
buf[cache.len] = '\0';
return cache.len;
}
/* buf太小,无法生成字符串. */
if (buflen > 0)
buf[0] = '\0';
return 0;
}
/* description: 获取错误代码字符串.
param: errnum --
return: */
const char *safe_strerror(int errnum)
{
const char *s = strerror(errnum);
return (s != NULL) ? s : "Unknown error";
}
/* description: 按16进制打印buf数据.
param: buf --
len --
return: */
void buf_print(char *buf, int32_t len)
{
int32_t i = 0;
for(i = 0; i < len;)
{
printh("%02x ", (uint8_t)buf[i++]);
if(0 == i % 32)
{
printh("\r\n");
}
}
if(i % 32 != 0)
{
printh("\r\n\n");
}
else
{
printh("\n");
}
return;
}
/* description: 通过 ip 生成 mac 地址.
param: ip_str -- ip
mac -- mac
return: E_XXXX */
int32_t mac_generate_from_ip(char *ip_str, uint8_t *mac)
{
struct sockaddr_in server;
uint32_t ip = 0;
uint32_t temp = 0;
if (NULL == ip_str || NULL == mac)
{
return E_BAD_PARAM;
}
/* 将 ip_str 转为数字. */
if (inet_aton(ip_str, &server.sin_addr) < 0)
{
DBG(DBG_M_CLI, "inet_aton ip is error!\r\n");
return E_BAD_PARAM;
}
ip = server.sin_addr.s_addr;
/* 产生 mac. */
srand(time(NULL));
temp = rand();
mac[0] = 0x68;
mac[1] = temp & 0xff;
mac[2] = (temp >> 8) & 0xff;
mac[3] = (temp >> 16) & 0xff;
mac[4] = (temp >> 24) & 0xff;
mac[5] = (ip >> 24) & 0xff;
return E_NONE;
}
/* description: 计算CRC16/MODBUS.
param: data --
size --
return: crc */
uint16_t crc16(uint8_t *data, uint16_t size)
{
uint16_t crc = 0xFFFF;
uint8_t i = 0;
while(size--)
{
crc = crc ^ *data++;
for(i = 0; i < 8; i++)
{
if ((crc & 0x0001) > 0)
{
crc = crc >> 1;
crc = crc ^ 0xa001;
}
else
crc = crc >> 1;
}
}
return crc;
}
void invert_uint8(unsigned char *dest_buf, unsigned char *src_buf)
{
int i;
unsigned char tmp[4];
tmp[0] = 0;
for (i = 0; i < 8; i++)
{
if (src_buf[0] & (1 << i))
tmp[0] |= 1 << (7 - i);
}
dest_buf[0] = tmp[0];
}
void invert_uint16(unsigned short *dest_buf, unsigned short *src_buf)
{
int i;
unsigned short tmp[4];
tmp[0] = 0;
for (i = 0; i < 16; i++)
{
if (src_buf[0] & (1 << i))
tmp[0] |= 1 << (15 - i);
}
dest_buf[0] = tmp[0];
}
uint16_t crc16_modbus(uint8_t *data, uint16_t size)
{
unsigned short wCRCin = 0xFFFF;
unsigned short wCPoly = 0x8005;
unsigned char wChar = 0;
while (size--)
{
wChar = *(data++);
invert_uint8(&wChar, &wChar);
wCRCin ^= (wChar << 8);
int i = 0;
for (i = 0; i < 8; i++)
{
if (wCRCin & 0x8000)
wCRCin = (wCRCin << 1) ^ wCPoly;
else
wCRCin = wCRCin << 1;
}
}
invert_uint16(&wCRCin, &wCRCin);
return (wCRCin);
}
uint32_t crc32_reflect(uint32_t value, uint8_t bits)
{
uint32_t reflection = 0;
for(uint8_t i = 0; i < bits ; i++)
{
if (value & (1u << i))
reflection |= 1 << (bits - 1 - i);
}
return reflection;
}
/* crc32 初始化. */
void crc32_table_init(void)
{
uint32_t int1 = 1;
uint32_t const value_high_bit = int1 << 31u;
uint8_t dividend = 0;
do
{
uint32_t remainder = 0;
for(uint8_t mask = 1u << (CRC32_CHAR_BIT - 1u); mask; mask >>= 1)
{
if (dividend & mask)
remainder ^= value_high_bit;
if (remainder & value_high_bit)
{
remainder <<= 1;
remainder ^= 0x04C11DB7u;
}
else
remainder <<= 1;
}
crc32Table[crc32_reflect(dividend, CRC32_CHAR_BIT)] = crc32_reflect(remainder, 32);
}
while(++dividend);
}
uint32_t crc32(void const *buf, uint16_t byte_count)
{
uint32_t rem = 0xFFFFFFFF;
uint8_t const * const b_begin = (uint8_t*)buf;
uint8_t const * const b_end = b_begin + byte_count;
for(uint8_t const *p = b_begin; p < b_end; p++)
{
uint8_t const byte_index = *p ^ rem;
rem >>= CRC32_CHAR_BIT;
rem ^= crc32Table[ byte_index ];
}
return ~rem;
}
/**
* @brief crc32.
* @param buf: .
* @param len: .
* @retval crc32.
*/
uint32_t crc32_update(uint32_t crc, char* buf, uint32_t len)
{
uint32_t i = 0;
for(i = 0; i < len; i++)
crc = crc32Table[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
return crc;
}
/* description: 时间统计开始.
param:
return: */
void speed_detection_stat(void)
{
gettimeofday(&sd_start, NULL);
}
/* description: 时间统计结束.
param:
return: */
void speed_detection_end(void)
{
float timeuse;
gettimeofday(&sd_end, NULL);
timeuse = 1000000 * (sd_end.tv_sec - sd_start.tv_sec) + sd_end.tv_usec - sd_start.tv_usec;
timeuse /= 1000000;
printh("Used Time:%f\r\n", timeuse);
}
/* description: 通用打印函数.
param:
return: */
int printh(const char *format, ...)
{
va_list args;
va_start(args, format);
vty_print(format, args);
va_end(args);
return 0;
}
/* description: 获取int16_t类型的版本号.
param:
return: int16_t */
uint16_t sofrware_version_get(void)
{
char version_str[16];
char *str = NULL;
char *p = NULL;
uint16_t version = 0;
snprintf(version_str, 16, "%s", version_get());
str = strtok_r(version_str, ".", &p);
while(str != NULL)
{
version = version << 8;
version |= (uint8_t)(atoi(str));
str = strtok_r(NULL, ".", &p);
}
return version;
}
/* description: 根据传入的字符串转换成mac地址.
param:
return: */
int32_t str_to_mac(char *mac_str, OUT uint8_t *mac)
{
char *str = NULL;
char *p = NULL;
uint8_t len = 0;
uint8_t i = 0;
/* 按:分词 */
str = strtok_r(mac_str, ":", &p);
while(str != NULL)
{
/* 检查mac长度 */
if (len >= 6)
{
return E_BAD_PARAM;
}
/* 检查字符串 */
for(i = 0; str[i] && str[i] != '\0'; i++)
{
if (!((str[i] >= '0' && str[i] <= '9')
|| (str[i] >= 'a' && str[i] <= 'f')
|| (str[i] >= 'A' && str[i] <= 'F')))
{
return E_BAD_PARAM;
}
}
/* 检查数据长度 */
if (i != 2)
{
return E_BAD_PARAM;
}
mac[len++] = strtol(str, NULL, 16);
/* 获取下个数据 */
str = strtok_r(NULL, ":", &p);
}
return E_NONE;
}
/* description: 根据传入的字符串转换成设备id.
param:
return: */
int32_t str_to_id(char *id_str, OUT uint32_t *id)
{
char *str = NULL;
char *p = NULL;
uint8_t len = 0;
uint8_t i = 0;
/* 按:分词 */
str = strtok_r(id_str, ".", &p);
while(str != NULL && len < 2)
{
/* 检查id长度 */
if (len >= 2)
{
return E_BAD_PARAM;
}
/* 检查字符串 */
for(i = 0; str[i] && str[i] != '\0'; i++)
{
if (!(str[i] >= '0' && str[i] <= '9'))
{
return E_BAD_PARAM;
}
}
id[len++] = strtol(str, NULL, 10);
/* 获取下个数据 */
str = strtok_r(NULL, ".", &p);
}
return E_NONE;
}
int32_t bitmap_set(uint8_t *buf, int32_t nbit, int32_t buf_len)
{
if ((NULL == buf) || (nbit >= buf_len * 8))
{
return E_BAD_PARAM;
}
buf[nbit / 8] |= 1 << (nbit % 8);
return E_NONE;
}
int32_t bitmap_reset(uint8_t *buf, int32_t nbit, int32_t buf_len)
{
if ((NULL == buf) || (nbit >= buf_len * 8))
{
return E_BAD_PARAM;
}
buf[nbit / 8] &= ~(1 << (nbit % 8));
return E_NONE;
}
int32_t is_bitmap_set(uint8_t *buf, int32_t nbit, int32_t buf_len)
{
if ((NULL == buf) || (nbit >= buf_len * 8))
{
return FALSE;
}
return buf[nbit / 8] & (1 << (nbit % 8));
}
int32_t time_str_to_long(char *date, char *time, uint32_t *t)
{
struct tm stm;
int32_t year, month, day, hour, minute,second;
if (sscanf(date, "%d-%d-%d", &year, &month, &day) != 3)
{
return E_BAD_PARAM;
}
if (sscanf(time, "%d:%d:%d", &hour, &minute, &second) != 3)
{
return E_BAD_PARAM;
}
stm.tm_year = year - 1900;
stm.tm_mon = month - 1;
stm.tm_mday = day;
stm.tm_hour = hour;
stm.tm_min = minute;
stm.tm_sec = second;
stm.tm_isdst = 0;
*t = mktime(&stm);
return E_NONE;
}
uint16_t version_str_to_int(void)
{
uint32_t version_m = 0;
uint32_t version_s = 0;
uint32_t version_hm = 0;
uint32_t version_hs = 0;
uint32_t n = 0;
n = sscanf(version_get(), "%d.%d.%d.%d", &version_hm, &version_hs, &version_m, &version_s);
if (n != 4)
{
return 0xffff;
}
return (version_m << 8 | (version_s & 0xff)) & 0xffff;
}
void time_set(time_t timestamp)
{
struct tm *p =localtime(&timestamp);
struct tm tptr = {0};
struct timeval tv = {0};
tptr.tm_year = p->tm_year;
tptr.tm_mon = p->tm_mon;
tptr.tm_mday = p->tm_mday;
tptr.tm_hour = p->tm_hour;
tptr.tm_min = p->tm_min;
tptr.tm_sec = p->tm_sec;
tv.tv_sec = mktime(&tptr);
tv.tv_usec = 0;
settimeofday(&tv, NULL);
system("hwclock -w");
}
boot_msg_t g_bootmsg[] =
{
{BOOT_NONE, "Boot none."},
{BOOT_SYSTEM_RESET, "System reboot..."},
{BOOT_SYSTEM_LOGOUT, "System logout..."},
{BOOT_REMOTE_CFG_SET, "Remote device info change..."},
{BOOT_REMOTE_RESET, "Remote reboot..."},
{BOOT_REMOTE_UPDATE, "Remote update..."},
{BOOT_FILE_RECOVER, "File recover..."},
{BOOT_4G_ERR, "4G is disconnect..."},
{BOOT_CONNECT_ERR, "Server is disconnect..."},
{BOOT_TIMER, "Timer reset..."},
{BOOT_MAX, NULL}
};
void reboot_system(int module, BOOT_MSG type)
{
char *pmsg = NULL;
is_system_reboot = TRUE;
for (BOOT_MSG i = BOOT_NONE; i < BOOT_MAX; i++)
{
if (g_bootmsg[i].type == type)
{
pmsg = g_bootmsg[i].msg;
break;
}
}
if (pmsg)
{
log_out(module, LOG_LVL_WARN, pmsg);
//log_out(module, LOG_LVL_WARN, "Now,start reboot system...");
system("sync");
sleep(3);
system("reboot -f");
}
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,255 @@
/******************************************************************************
* file lib/management/common.c
* author YuLiang
* version 1.0.0
* date 14-Sep-2021
* brief This file provides all the debug operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "cmd.h"
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
#ifdef CFG_DBG_ON
dbg_module_t _dbg_module[DBG_M_COUNT] =
{
{DBG_M_DBG, FALSE, "debug"},
{DBG_M_CLI, FALSE, "cli"},
{DBG_M_MTIMER, FALSE, "timer"},
{DBG_M_PROCESS, FALSE, "process"},
{DBG_M_GPIO, FALSE, "gpio"},
{DBG_M_FIFO, FALSE, "fifo"},
{DBG_M_FIFO_ERR, TRUE, "fifo_err"},
{DBG_M_CA_COLL, FALSE, "ca_coll"},
{DBG_M_CA_COLL_ERR, TRUE, "ca_coll_err"},
{DBG_M_CA_DB, FALSE, "ca_db"},
{DBG_M_CA_DB_ERR, TRUE, "ca_db_err"},
{DBG_M_CA_DBG, FALSE, "ca_dbg"},
{DBG_M_CA_DBG_ERR, TRUE, "ca_dbg_err"},
{DBG_M_CA_MQTT, TRUE, "ca_mqtt"},
{DBG_M_CA_MQTT_ERR, TRUE, "ca_mqtt_err"},
{DBG_M_CA_LAND, FALSE, "ca_land"},
{DBG_M_CA_LAND_ERR, TRUE, "ca_land_err"}
};
/* Private function prototypes -----------------------------------------------*/
CMD(debug_on,
debug_on_cmd,
"debug WORD",
"Debug\n"
"Debug module\n")
{
int32_t i = 0;
int32_t len_desc = 0;
int32_t len_cmd = 0;
for(i = 0; i < DBG_M_COUNT; i++)
{
len_desc = strlen(_dbg_module[i].desc);
len_cmd = strlen(argv[0]);
if (strncmp(argv[0], _dbg_module[i].desc, len_desc > len_cmd ? len_desc : len_cmd))
{
continue;
}
dbg_cmd_hander(DBG_CMD_ON, i);
}
return CMD_SUCCESS;
}
CMD(no_debug_on,
no_debug_on_cmd,
"no debug WORD",
NO_STR
"Debug\n"
"Debug module\n")
{
int32_t i = 0;
int32_t len_desc = 0;
int32_t len_cmd = 0;
for(i = 0; i < DBG_M_COUNT; i++)
{
len_desc = strlen(_dbg_module[i].desc);
len_cmd = strlen(argv[0]);
if (strncmp(argv[0], _dbg_module[i].desc, len_desc > len_cmd ? len_desc : len_cmd))
{
continue;
}
dbg_cmd_hander(DBG_CMD_OFF, i);
}
return CMD_SUCCESS;
}
CMD(no_debug_all,
no_debug_all_cmd,
"no debug",
NO_STR
"Debug\n")
{
dbg_cmd_hander(DBG_CMD_ALL_OFF, 0);
return CMD_SUCCESS;
}
CMD(show_debug_all,
show_debug_all_cmd,
"show debug",
SHOW_STR
"Debug state\n")
{
int32_t i = 0;
for(i = 0; i < DBG_M_COUNT; i++)
{
vty_out(vty, "%03d | %-16s %s%s", i, _dbg_module[i].desc, _dbg_module[i].stat ? "on" : "off", VTY_NEWLINE);
}
return CMD_SUCCESS;
}
/* Internal functions --------------------------------------------------------*/
/* 开指定模块的debug */
static int32_t _dbg_on(DBG_MODULE_E module)
{
if (module >= DBG_M_COUNT)
{
return E_BAD_PARAM;
}
_dbg_module[module].stat = TRUE;
return E_NONE;
}
/* 关指定模块的debug */
static int32_t _dbg_off(DBG_MODULE_E module)
{
if (module >= DBG_M_COUNT)
{
return E_BAD_PARAM;
}
_dbg_module[module].stat = FALSE;
return E_NONE;
}
/* 关所有模块的debug */
static int32_t _dbg_all_off(void)
{
unsigned int i = 0;
for(i = 0; i < DBG_M_COUNT; i++)
{
_dbg_module[i].stat = FALSE;
}
return E_NONE;
}
/* Interface functions -------------------------------------------------------*/
/* description: 获取当前模块debug状态.
param: module -- ID
return: (TRUE),(FALSE) */
int32_t dbg_stat_get(DBG_MODULE_E module)
{
if (module >= DBG_M_COUNT)
{
return FALSE;
}
return _dbg_module[module].stat;
}
/* description: debug模块命令函数分发.
param: module -- ID
return: (E_NONE),() */
int32_t dbg_cmd_hander(DBG_CMD_E cmd, int32_t module)
{
switch(cmd)
{
case DBG_CMD_ON:
LD_E_RETURN(DBG_M_DBG, _dbg_on(module));
break;
case DBG_CMD_OFF:
LD_E_RETURN(DBG_M_DBG, _dbg_off(module));
break;
case DBG_CMD_ALL_OFF:
LD_E_RETURN(DBG_M_DBG, _dbg_all_off());
break;
default:
break;
}
return E_NONE;
}
/* description: debug模块初始化.
param:
return: */
void dbg_init(void)
{
cmd_install_element(COMMON_NODE, &show_debug_all_cmd);
cmd_install_element(ENABLE_NODE, &debug_on_cmd);
cmd_install_element(ENABLE_NODE, &no_debug_on_cmd);
cmd_install_element(ENABLE_NODE, &no_debug_all_cmd);
}
#else
int32_t dbg_stat_get(DBG_MODULE_E module)
{
return FALSE;
}
int dbg_cmd_hander(DBG_CMD_E cmd, int32_t module)
{
return E_NONE;
}
void dbg_init(void)
{
}
#endif
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,273 @@
/******************************************************************************
* file lib/management/fifo.c
* author YuLiang
* version 1.0.0
* date 21-Feb-2023
* brief This file provides all the fifo operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
/* 用户代码头文件. */
#include "cmd.h"
#include "fifo.h"
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static array_t *fifo = NULL;
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 显示 fifo 的使用情况. */
CMD(show_fifo,
show_fifo_cmd,
"show fifo",
"Show\n"
"Fifo\n")
{
uint32_t id = 0;
fifo_t *fifo_node = NULL;
for (id = 0; id < array_active(fifo); id++)
{
fifo_node = array_lookup(fifo, id);
if (NULL == fifo_node)
{
continue;
}
fifo_show(id);
}
return CMD_SUCCESS;
}
/* Interface functions -------------------------------------------------------*/
/* 初始化 fifo 全局结构 */
int32_t fifo_init(void)
{
fifo = array_init(16, MTYPE_FIFO);
if (!fifo)
{
log_err(LOG_FIFO, "ERROR at array init!");
return E_MEM;
}
cmd_install_element(COMMON_NODE, &show_fifo_cmd);
return E_NONE;
}
/* 创建 1 个 fifo. */
int32_t fifo_create(char* name, uint32_t size)
{
fifo_t *fifo_node = NULL;
/* 初始化. */
fifo_node = XMALLOC(MTYPE_FIFO, sizeof(fifo_t));
if (!fifo_node)
{
return E_MEM;
}
snprintf(fifo_node->name, FIFO_NAME_LEN, "%s", name);
fifo_node->size = size;
/* 申请互斥锁, 用于通知读线程读取有效. */
if (sem_init(&fifo_node->sem, 0, 0) != 0)
{
XFREE(MTYPE_FIFO, fifo_node);
DBG(DBG_M_FIFO_ERR, "%s ERROR at sem init return %s!\r\n", name, safe_strerror(errno));
return E_SYS_CALL;
}
/* 申请信号量, 防止多个线程同时操作 fifo. */
if (pthread_mutex_init(&fifo_node->mutex, NULL) != 0)
{
XFREE(MTYPE_FIFO, fifo_node);
sem_destroy(&fifo_node->sem);
DBG(DBG_M_FIFO_ERR, "%s ERROR at sem init return %s!\r\n", name, safe_strerror(errno));
return E_SYS_CALL;
}
/* 申请 fifo 空间. */
fifo_node->data = XMALLOC(MTYPE_FIFO, sizeof(void *) * size);
if (!fifo_node->data)
{
XFREE(MTYPE_FIFO, fifo_node);
sem_destroy(&fifo_node->sem);
pthread_mutex_destroy(&fifo_node->mutex);
return E_MEM;
}
/* 添加到全局结构体. */
return array_append(fifo, fifo_node, MTYPE_FIFO);
}
/* 往 fifo 中写入一条数据. */
int32_t fifo_write(uint32_t id, void *data, int32_t len)
{
int32_t index = 0;
fifo_t *fifo_node = array_get(fifo, id);
void *temp = NULL;
/* 参数检查. */
if (!fifo_node)
{
DBG_Q(DBG_M_FIFO_ERR, "#7\r\n");
return E_NOT_FOUND;
}
/* 申请数据空间. */
temp = XMALLOC_Q(MTYPE_FIFO, len);
if (!temp)
{
return E_MEM;
}
memcpy(temp, data, len);
pthread_mutex_lock(&fifo_node->mutex);
/* 判断 fifo 是否满了. */
index = fifo_node->cur + 1;
if (index == fifo_node->size)
{
index = 0;
}
if (index == fifo_node->valid)
{
DBG_Q(DBG_M_FIFO_ERR, "#8 %d\r\n", id);
XFREE(MTYPE_FIFO, temp);
pthread_mutex_unlock(&fifo_node->mutex);
return E_MEM;
}
/* 数据加入 fifo. */
fifo_node->data[fifo_node->cur] = temp;
fifo_node->used++;
if (fifo_node->used > fifo_node->max)
{
fifo_node->max = fifo_node->used;
}
fifo_node->cur = index;
sem_post(&fifo_node->sem);
pthread_mutex_unlock(&fifo_node->mutex);
return len;
}
/* 从 fifo 中读取数据, 注意, 只能一个进程进行读取. */
int32_t fifo_read(uint32_t id, void **data)
{
fifo_t *fifo_node = array_get(fifo, id);
/* 参数检查. */
if (!fifo_node)
{
DBG(DBG_M_FIFO_ERR, "Fifo %d is not found!\r\n", id);
return E_NOT_FOUND;
}
/* 等待有效数据, 如果有效, 返回数据. */
while (fifo_node->valid == fifo_node->cur)
{
sem_wait(&fifo_node->sem);
}
*data = fifo_node->data[fifo_node->valid];
return E_NONE;
}
/* 释放 fifo 数据, 因为节省了一次内存申请, 所以必须手动释放 fifo 数据. */
int32_t fifo_push(uint32_t id)
{
uint32_t index = 0;
fifo_t *fifo_node = array_get(fifo, id);
/* 检查参数. */
if (!fifo_node)
{
DBG(DBG_M_FIFO_ERR, "Fifo %d is not found!\r\n", id);
return E_NOT_FOUND;
}
/* 释放数据. */
if (fifo_node->valid != fifo_node->cur)
{
pthread_mutex_lock(&fifo_node->mutex);
XFREE(MTYPE_FIFO, fifo_node->data[fifo_node->valid]);
fifo_node->data[fifo_node->valid] = NULL;
index = fifo_node->valid + 1;
if (index == fifo_node->size)
{
index = 0;
}
fifo_node->used--;
fifo_node->valid = index;
pthread_mutex_unlock(&fifo_node->mutex);
}
return E_NONE;
}
/* 显示 fifo 的使用情况. */
void fifo_show(uint32_t id)
{
fifo_t *fifo_node = NULL;
fifo_node = array_lookup(fifo, id);
if (NULL == fifo_node)
{
return;
}
printh("%-32s %-2d %-2d %-2d %-2d %-2d %-2d\r\n", fifo_node->name, id, fifo_node->size, fifo_node->cur,
fifo_node->valid, fifo_node->used, fifo_node->max);
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,551 @@
/******************************************************************************
* file lib/management/memory.c
* author YuLiang
* version 1.0.0
* date 14-Sep-2021
* brief This file provides all the memory operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
#include <malloc.h>
#include <sys/resource.h>
/* 用户代码头文件. */
#include "cmd.h"
/* Private define ------------------------------------------------------------*/
#define MEM_LOCK pthread_mutex_lock(&mem_mutex)
#define MEM_UNLOCK pthread_mutex_unlock(&mem_mutex)
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static mem_node_t mem_list_management[] =
{
{MTYPE_CLI, "Cli"},
{MTYPE_BUF, "Buffer"},
{MTYPE_BUF_DATA, "Buffer data"},
{MTYPE_BUF_TMP, "Buffer temp"},
{MTYPE_VTY, "Vty"},
{MTYPE_VTY_TMP, "Vty temp"},
{MTYPE_VTY_OUT_BUF, "Vty output buffer"},
{MTYPE_VTY_HIST, "Vty history"},
{MTYPE_HASH, "Hash"},
{MTYPE_HASH_BACKET, "Hash Bucket"},
{MTYPE_HASH_INDEX, "Hash Index"},
{MTYPE_LOG, "Logging"},
{MTYPE_MTIMER, "Timer"},
{MTYPE_THREAD_MONITOR, "Thread monitor"},
{MTYPE_PREFIX, "Prefix"},
{MTYPE_THREAD, "Thread"},
{MTYPE_THREAD_STATS, "Thread stats"},
{MTYPE_THREAD_MASTER, "Thread master"},
{MTYPE_THREAD_FUNCNAME, "Thread function name"},
{MTYPE_FIFO, "fifo"},
{MTYPE_GPIO, "gpio"},
{ -1, NULL },
};
static mem_node_t mem_list_process[] =
{
{MTYPE_CA_COLL, "collect"},
{MTYPE_CA_DB, "database"},
{MTYPE_CA_MQTT, "MQTT"},
{ -1, NULL },
};
static mem_list_t mlists[] __attribute__ ((unused)) =
{
{mem_list_management, "MANAGEMENT"},
{mem_list_process, "PROCESS"},
{NULL, NULL},
};
/* 同于统计每个模块申请内存的次数. */
static struct
{
const char *name;
int32_t alloc;
uint32_t t_malloc;
uint32_t c_malloc;
uint32_t t_calloc;
uint32_t c_calloc;
uint32_t t_realloc;
uint32_t t_free;
uint32_t c_strdup;
} mstat[MTYPE_MAX];
static pthread_mutex_t mem_mutex;
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* 查找模块相应的说明字符串: key -- 模块 */
static const char *_x_desc_lookup(uint32_t key)
{
const mem_list_t *list = NULL;
const mem_node_t *pnt = NULL;
for(list = mlists; list->nodes != NULL; list++)
{
for(pnt = list->nodes; pnt->index >= 0; pnt++)
{
if (pnt->index == key)
{
return pnt->format;
}
}
}
return "";
}
/* 打印每个模块的内存使用情况: pri -- log优先级 */
static void _x_memstats_print(int32_t pri)
{
mem_list_t *ml = NULL;
for (ml = mlists; ml->nodes; ml++)
{
mem_node_t *m = NULL;
log_out(LOG_MEMORY, pri, "Memory utilization in module %s:", ml->name);
for(m = ml->nodes; m->index >= 0; m++)
{
if (m->index && mstat[m->index].alloc)
{
log_out(LOG_MEMORY, pri, " %-30s: %10ld", m->format, (long)mstat[m->index].alloc);
}
}
}
}
/* 打印内存申请错误信息: fname -- 调用的函数type -- 模块, size -- 大小 */
static void __attribute__ ((noreturn)) _x_mem_error(const char *fname, int32_t type, size_t size)
{
log_err(LOG_MEMORY, "%s : can't allocate memory for '%s' size %d: %s!",
fname, _x_desc_lookup(type), (int)size, safe_strerror(errno));
/* 打印每个模块的内存使用请款 */
_x_memstats_print(LOG_LVL_WARN);
/* 打印堆栈信息 */
log_backtrace(LOG_LVL_WARN);
abort();
}
/* 增加内存alloc计数 */
static void _x_alloc_inc(int32_t type)
{
MEM_LOCK;
mstat[type].alloc++;
MEM_UNLOCK;
}
/* 减少内存alloc计数 */
static void _x_alloc_dec(int32_t type)
{
MEM_LOCK;
mstat[type].alloc--;
MEM_UNLOCK;
}
/* 打印内存申请释放的debug信息. */
static void _x_mtype_log(char *func, void *memory, const char *file, int32_t line, uint32_t type)
{
//log_debug(LOG_MEMORY, "%s: %s %p %s %d", func, _x_desc_lookup(type), memory, file, line);
log_out(LOG_MEMORY, LOG_LVL_DBG,"%s: %s %p %s %d", func, _x_desc_lookup(type), memory, file, line);
}
/* Stats querying from users */
/* Return a pointer to a human friendly string describing
* the byte count passed in. E.g:
* "0 bytes", "2048 bytes", "110kB", "500MiB", "11GiB", etc.
* Up to 4 significant figures will be given.
* The pointer returned may be NULL (indicating an error)
* or point to the given buffer, or point to static storage. */
static const char *_x_mtype_memstr(char *buf, size_t len, uint32_t bytes)
{
int32_t t = 0;
int32_t g = 0;
int32_t m = 0;
int32_t k = 0;
/* easy cases */
if (!bytes)
return "0 bytes";
if (1 == bytes)
return "1 byte";
#if 0
if (sizeof(unsigned long) >= 8)
/* Hacked to make it not warn on ILP32 machines
* Shift will always be 40 at runtime. See below too */
t = bytes >> (sizeof (unsigned long) >= 8 ? 40 : 0);
else
t = 0;
#endif
g = bytes >> 30;
m = bytes >> 20;
k = bytes >> 10;
if (t > 10)
{
/* The shift will always be 39 at runtime.
* Just hacked to make it not warn on 'smaller' machines.
* Static compiler analysis should mean no extra code */
if (bytes & (1UL << (sizeof(unsigned long) >= 8 ? 39 : 0)))
t++;
snprintf (buf, len, "%4d TiB", t);
}
else if (g > 10)
{
if (bytes & (1 << 29))
g++;
snprintf (buf, len, "%d GiB", g);
}
else if (m > 10)
{
if (bytes & (1 << 19))
m++;
snprintf (buf, len, "%d MiB", m);
}
else if (k > 10)
{
if (bytes & (1 << 9))
k++;
snprintf (buf, len, "%d KiB", k);
}
else
snprintf (buf, len, "%d bytes", bytes);
return buf;
}
/* 打印内存使用情况根据系统调用. */
static int32_t _x_show_memory_mallinfo(vty_t *vty)
{
struct mallinfo minfo = mallinfo();
char buf[MTYPE_MEMSTR_LEN] = {0};
vty_out(vty, "System allocator statistics:%s", VTY_NEWLINE);
vty_out(vty, " Total heap allocated: %s%s",
_x_mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.arena), VTY_NEWLINE);
vty_out(vty, " Holding block headers: %s%s",
_x_mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.hblkhd), VTY_NEWLINE);
vty_out(vty, " Used small blocks: %s%s",
_x_mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.usmblks), VTY_NEWLINE);
vty_out(vty, " Used ordinary blocks: %s%s",
_x_mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.uordblks), VTY_NEWLINE);
vty_out(vty, " Free small blocks: %s%s",
_x_mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.fsmblks), VTY_NEWLINE);
vty_out(vty, " Free ordinary blocks: %s%s",
_x_mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.fordblks), VTY_NEWLINE);
vty_out(vty, " Ordinary blocks: %ld%s", (unsigned long)minfo.ordblks, VTY_NEWLINE);
vty_out(vty, " Small blocks: %ld%s", (unsigned long)minfo.smblks, VTY_NEWLINE);
vty_out(vty, " Holding blocks: %ld%s", (unsigned long)minfo.hblks, VTY_NEWLINE);
vty_out(vty, "(see system documentation for 'mallinfo' for meaning)%s", VTY_NEWLINE);
return 1;
}
static void _x_show_separator(vty_t *vty)
{
vty_out(vty, "-----------------------------%s", VTY_NEWLINE);
}
int32_t _x_show_memory_vty(vty_t *vty, mem_node_t *list)
{
mem_node_t *m = NULL;
int32_t needsep = 0;
for (m = list; m->index >= 0; m++)
if (0 == m->index)
{
if (needsep)
{
_x_show_separator(vty);
needsep = 0;
}
}
else
{
vty_out(vty, "%-30s: %10d%s", m->format, mstat[m->index].alloc, VTY_NEWLINE);
needsep = 1;
}
return needsep;
}
/* 申请内存,并增加相应的模块的申请数: type -- 模块size -- 大小 */
static void *_x_malloc (int32_t type, size_t size)
{
void *memory = NULL;
memory = malloc(size);
if (NULL == memory)
_x_mem_error("malloc", type, size);
memset(memory, 0, size);
_x_alloc_inc(type);
return memory;
}
/* 申请内存,并增加相应的模块的申请数: type -- 模块size -- 大小 */
static void *_x_malloc_q (int32_t type, size_t size)
{
void *memory = NULL;
memory = malloc(size);
if (NULL == memory)
_x_mem_error("malloc", type, size);
_x_alloc_inc(type);
return memory;
}
/* Allocate memory as in zmalloc, and also clear the memory. */
static void *_x_calloc(int32_t type, size_t size)
{
void *memory = NULL;
memory = calloc(1, size);
if (NULL == memory)
_x_mem_error("calloc", type, size);
memset(memory, 0, size);
_x_alloc_inc(type);
return memory;
}
/* Given a pointer returned by zmalloc or zcalloc, free it and
* return a pointer to a new size, basically acting like realloc().
* Requires: ptr was returned by zmalloc, zcalloc, or zrealloc with the
* same type.
* Effects: Returns a pointer to the new memory, or aborts. */
static void *_x_realloc(int32_t type, void *ptr, size_t size)
{
void *memory = NULL;
memory = realloc(ptr, size);
if (NULL == memory)
_x_mem_error("realloc", type, size);
if (NULL == ptr)
_x_alloc_inc(type);
return memory;
}
/* Free memory allocated by z*alloc or zstrdup.
* Requires: ptr was returned by zmalloc, zcalloc, or zrealloc with the
* same type.
* Effects: The memory is freed and may no longer be referenced. */
static void _x_free(int32_t type, void *ptr)
{
if (ptr != NULL)
{
_x_alloc_dec(type);
free(ptr);
}
}
/* Duplicate a string, counting memory usage by type.
* Effects: The string is duplicated, and the return value must
* eventually be passed to zfree with the same type. The function will
* succeed or abort. */
static char *_x_strdup(int32_t type, const char *str)
{
void *dup = NULL;
dup = strdup(str);
if (dup == NULL)
_x_mem_error("strdup", type, strlen(str));
_x_alloc_inc(type);
return dup;
}
/* Interface functions -------------------------------------------------------*/
/* description: 申请内存.
param: file --
line --
type --
size --
return: */
void *mtype_x_malloc(const char *file, int32_t line, int32_t type, size_t size)
{
void *memory = NULL;
mstat[type].c_malloc++;
mstat[type].t_malloc++;
memory = _x_malloc(type, size);
_x_mtype_log("x_malloc", memory, file, line, type);
return memory;
}
void *mtype_x_malloc_q(const char *file, int32_t line, int32_t type, size_t size)
{
void *memory = NULL;
mstat[type].c_malloc++;
mstat[type].t_malloc++;
memory = _x_malloc_q(type, size);
_x_mtype_log("x_malloc_q", memory, file, line, type);
return memory;
}
/* 见mtype_x_malloc. */
void *mtype_x_calloc(const char *file, int32_t line, int32_t type, size_t size)
{
void *memory = NULL;
mstat[type].c_calloc++;
mstat[type].t_calloc++;
memory = _x_calloc(type, size);
_x_mtype_log("x_calloc", memory, file, line, type);
return memory;
}
/* 见mtype_x_malloc. */
void *mtype_x_realloc(const char *file, int32_t line, int32_t type, void *ptr, size_t size)
{
void *memory = NULL;
/* Realloc need before allocated pointer. */
mstat[type].t_realloc++;
memory = _x_realloc(type, ptr, size);
_x_mtype_log("x_realloc", memory, file, line, type);
return memory;
}
/* 见mtype_x_malloc. */
void mtype_x_free(const char *file, int32_t line, int32_t type, void *ptr)
{
mstat[type].t_free++;
_x_free(type, ptr);
_x_mtype_log("x_free", ptr, file, line, type);
}
/* 见mtype_x_malloc. */
char *mtype_x_strdup(const char *file, int32_t line, int32_t type, const char *str)
{
char *memory = NULL;
mstat[type].c_strdup++;
memory = _x_strdup(type, str);
_x_mtype_log("x_strdup", memory, file, line, type);
return memory;
}
CMD(show_memory_all,
show_memory_all_cmd,
"show memory",
SHOW_STR
"Memory statistics\n")
{
mem_list_t *ml = NULL;
int needsep = 0;
needsep = _x_show_memory_mallinfo(vty);
for (ml = mlists; ml->nodes; ml++)
{
if (needsep)
_x_show_separator(vty);
needsep = _x_show_memory_vty(vty, ml->nodes);
}
return CMD_SUCCESS;
}
void mem_show(vty_t *vty)
{
mem_list_t *ml = NULL;
int needsep = 0;
for (ml = mlists; ml->nodes; ml++)
{
if (needsep)
_x_show_separator(vty);
needsep = _x_show_memory_vty(vty, ml->nodes);
}
}
/* description: memory模块初始化.
param:
return: */
void mtype_init(void)
{
cmd_install_element(COMMON_NODE, &show_memory_all_cmd);
}
/* description: memory模块初始化.
param:
return: */
void mtype_init_befor(void)
{
/* 初始化线程锁. */
pthread_mutex_init(&mem_mutex, NULL);
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,3 @@
local_src := $(patsubst $(SOURCE_DIR)/%,%,$(wildcard $(SOURCE_DIR)/$(subdirectory)/*.c))
$(eval $(call make-library,$(subdirectory)/libm_management.a,$(local_src)))

@ -0,0 +1,243 @@
/*****************************************************************************
* file lib/management/mtimer.c
* author Yuliang
* version 1.0.0
* date 22-Sep-2021
* brief This file provides all the timer related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/time.h>
#include <pthread.h>
#include <signal.h>
#include "array.h"
#include "mtimer.h"
#include "cmd.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static pthread_t mtimer_pid;
static array_t *mtimer_array;
static pthread_mutex_t mtimer_mutex;
/* Private function prototypes -----------------------------------------------*/
extern void _mtimer_lock(void);
extern void _mtimer_unlock(void);
/* 485设备显示. */
CMD(mtime_show,
mtime_show_cmd,
"show mtime",
SHOW_STR
"mtime\n")
{
mtimer_t *entry = NULL;
uint32_t i = 0;
/* 遍历所有外设 */
_mtimer_lock();
vty_out(vty, "ID %-32s INR%s", "NAME", VTY_NEWLINE);
for (i = 0; i < array_active(mtimer_array); i++)
{
entry = array_lookup(mtimer_array, i);
if (NULL == entry)
{
continue;
}
vty_out(vty, "%-02d %-32s %d%s", i, entry->name, entry->interval, VTY_NEWLINE);
}
_mtimer_unlock();
return CMD_SUCCESS;
}
/* Internal functions --------------------------------------------------------*/
void _mtimer_lock(void)
{
pthread_mutex_lock(&mtimer_mutex);
}
void _mtimer_unlock(void)
{
pthread_mutex_unlock(&mtimer_mutex);
}
/* 定时器线程. */
void *_mtimer_process(void *arg)
{
uint32_t i = 0;
uint32_t t = 0;
mtimer_t *entry = NULL;
while(1)
{
/* 最小粒度1s */
sleep(1);
/* 遍历所有定时器 */
_mtimer_lock();
t = time(NULL);
for (i = 0; i < array_active(mtimer_array); i++)
{
entry = array_lookup(mtimer_array, i);
if (NULL == entry)
{
continue;
}
/* 判断时间有没有到 */
if (abs(t - entry->time) < entry->interval)
{
continue;
}
/* 调用回调函数 */
entry->handle(entry->arg);
/* 删除定时器 */
array_unset(mtimer_array, i);
XFREE(MTYPE_MTIMER, entry);
}
_mtimer_unlock();
}
return NULL;
}
/* Interface functions -------------------------------------------------------*/
/* description: 添加定时器.
param:
return: (E_NONE),() */
int32_t mtimer_add(MTIMER_CALLBACK func, void *arg, uint16_t interval, char *name)
{
mtimer_t *timer = NULL;
_mtimer_lock();
timer = XMALLOC(MTYPE_MTIMER, sizeof(mtimer_t));
if (NULL == timer)
{
DBG(DBG_M_MTIMER, "Malloc error!\r\n");
_mtimer_unlock();
return E_MEM;
}
timer->handle = func;
timer->arg = arg;
snprintf(timer->name, DEV_NAME_STR_LEN, "%s", name);
timer->interval = interval;
timer->time = time(NULL);
array_append(mtimer_array, timer, MTYPE_MTIMER);
_mtimer_unlock();
return E_NONE;
}
/* description: 删除定时器.
param:
return: (E_NONE),() */
int32_t mtimer_del(MTIMER_CALLBACK func, void *arg)
{
uint32_t i = 0;
mtimer_t *entry = NULL;
_mtimer_lock();
/* 遍历数组 */
for (i = 0; i < array_active(mtimer_array); i++)
{
entry = array_lookup(mtimer_array, i);
if (NULL == entry)
{
continue;
}
/* 比较数据 */
if (entry->handle == func && entry->arg == arg)
{
/* 删除定时器 */
array_unset(mtimer_array, i);
XFREE(MTYPE_MTIMER, entry);
}
}
_mtimer_unlock();
return E_NONE;
}
/* description: 定时器初始化.
param:
return: (E_NONE),() */
int32_t mtimer_init(void)
{
struct sched_param param;
pthread_attr_t attr;
pthread_mutexattr_t attr_m;
/* 初始化用户列表 */
mtimer_array = array_init(16, MTYPE_MTIMER);
/* 递归锁 */
pthread_mutexattr_init(&attr_m);
pthread_mutexattr_settype(&attr_m, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mtimer_mutex, &attr_m);
/* 配置线程RR调度,优先级50 */
pthread_attr_init(&attr);
param.sched_priority = 50;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, &param);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
/* 创建接收数据线程. */
if (pthread_create(&mtimer_pid, &attr, _mtimer_process, NULL) != 0)
{
log_err(LOG_DEFAULT, "mtimer_init can't create pthread!");
}
else
{
thread_m_add("TIMER", mtimer_pid);
}
pthread_attr_destroy(&attr);
cmd_install_element(COMMON_NODE, &mtime_show_cmd);
return E_NONE;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

@ -0,0 +1,605 @@
/******************************************************************************
* file lib/management/sockunion.c
* author YuLiang
* version 1.0.0
* date 14-Sep-2021
* brief This file provides all the sockunion operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/route.h>
#include <arpa/inet.h>
#include "memory.h"
#include "sockunion.h"
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Maskbit. */
static const u_char maskbit[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0,
0xf8, 0xfc, 0xfe, 0xff};
/* Static structure for IPv4 access_list's master. */
static access_master_t access_master_ipv4 =
{
{NULL, NULL},
{NULL, NULL},
NULL,
NULL,
};
#ifdef HAVE_IPV6
/* Static structure for IPv6 access_list's master. */
static access_master_t access_master_ipv6 =
{
{NULL, NULL},
{NULL, NULL},
NULL,
NULL,
};
#endif /* HAVE_IPV6 */
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
/* Malloc prefix structure. */
static prefix_t *_prefix_new(void)
{
prefix_t *p = NULL;
p = XMALLOC(MTYPE_PREFIX, sizeof(prefix_t));
return p;
}
/* Interface functions -------------------------------------------------------*/
/* Free prefix structure. */
void prefix_free(prefix_t *p)
{
XFREE(MTYPE_PREFIX, p);
}
/* Allocate new prefix_ipv4 structure. */
prefix_ipv4_t *prefix_ipv4_new(void)
{
prefix_ipv4_t *p = NULL;
/* Call prefix_new to allocate a full-size struct prefix to avoid problems
* where the prefix_ipv4_t is cast to struct prefix and unallocated
* bytes were being referenced (e.g. in structure assignments). */
p = (prefix_ipv4_t *)_prefix_new();
p->family = AF_INET;
return p;
}
#ifdef HAVE_IPV6
/* Allocate a new ip version 6 route */
prefix_ipv6_t *prefix_ipv6_new (void)
{
prefix_ipv6_t *p = NULL;
/* Allocate a full-size struct prefix to avoid problems with structure
* 8 size mismatches. */
p = (prefix_ipv6_t *)_prefix_new();
p->family = AF_INET6;
return p;
}
#endif
static access_master_t *_access_master_get(uint16_t afi)
{
if (AFI_IP == afi)
return &access_master_ipv4;
#ifdef HAVE_IPV6
else if (AFI_IP6 == afi)
return &access_master_ipv6;
#endif /* HAVE_IPV6 */
return NULL;
}
/* If filter match to the prefix then return 1. */
static int _filter_match_cisco(filter_t *mfilter, prefix_t *p)
{
filter_cisco_t *filter = NULL;
struct in_addr mask;
uint32_t check_addr = 0;
uint32_t check_mask = 0;
filter = &mfilter->u.cfilter;
check_addr = p->u.prefix4.s_addr & ~filter->addr_mask.s_addr;
if (filter->extended)
{
masklen2ip(p->prefixlen, &mask);
check_mask = mask.s_addr & ~filter->mask_mask.s_addr;
if (0 == memcmp(&check_addr, &filter->addr.s_addr, 4) &&
0 == memcmp(&check_mask, &filter->mask.s_addr, 4))
return 1;
}
else if (0 == memcmp(&check_addr, &filter->addr.s_addr, 4))
return 1;
return 0;
}
/* If filter match to the prefix then return 1. */
static int _filter_match_zebra(filter_t *mfilter, prefix_t *p)
{
filter_zebra_t *filter= NULL;
filter = &mfilter->u.zfilter;
if (filter->prefix.family == p->family)
{
if (filter->exact)
{
if (filter->prefix.prefixlen == p->prefixlen)
return prefix_match(&filter->prefix, p);
else
return 0;
}
else
return prefix_match(&filter->prefix, p);
}
else
return 0;
}
/* Lookup access_list from list of access_list by name. */
access_list_t *access_list_lookup(uint16_t afi, const char *name)
{
access_list_t *access = NULL;
access_master_t *master = NULL;
if (NULL == name)
return NULL;
master = _access_master_get(afi);
if (NULL== master)
return NULL;
for(access = master->num.head; access; access = access->next)
if (0 == strcmp(access->name, name))
return access;
for(access = master->str.head; access; access = access->next)
if (0 == strcmp(access->name, name))
return access;
return NULL;
}
/* Apply access list to object (which should be prefix_t *). */
FILTER_TYPE_E access_list_apply(access_list_t *access, void *object)
{
filter_t *filter = NULL;
prefix_t *p = NULL;
p = (prefix_t *)object;
if (NULL == access)
return FILTER_DENY;
for (filter = access->head; filter; filter = filter->next)
{
if (filter->cisco)
{
if (_filter_match_cisco(filter, p))
return filter->type;
}
else
{
if (_filter_match_zebra(filter, p))
return filter->type;
}
}
return FILTER_DENY;
}
/* Convert masklen into IP address's netmask. */
void masklen2ip(int masklen, struct in_addr *netmask)
{
uint8_t *pnt = NULL;
int32_t bit = 0;
int32_t offset = 0;
memset(netmask, 0, sizeof(struct in_addr));
pnt = (unsigned char *)netmask;
offset = masklen / 8;
bit = masklen % 8;
while(offset--)
*pnt++ = 0xff;
if (bit)
*pnt = maskbit[bit];
}
/* If n includes p prefix then return 1 else return 0. */
int prefix_match(const prefix_t *n, const prefix_t *p)
{
int32_t offset = 0;
int32_t shift = 0;
const uint8_t *np = NULL;
const uint8_t *pp = NULL;
/* If n's prefix is longer than p's one return 0. */
if (n->prefixlen > p->prefixlen)
return 0;
/* Set both prefix's head pointer. */
np = (const u_char *)&n->u.prefix;
pp = (const u_char *)&p->u.prefix;
offset = n->prefixlen / PNBBY;
shift = n->prefixlen % PNBBY;
if (shift)
if (maskbit[shift] & (np[offset] ^ pp[offset]))
return 0;
while (offset--)
if (np[offset] != pp[offset])
return 0;
return 1;
}
/* Convert IPv4 compatible IPv6 address to IPv4 address. */
static void _sockunion_normalise_mapped(SOCKUNION_U *su)
{
#ifdef HAVE_IPV6
struct sockaddr_in sin;
if (AF_INET6 == su->sa.sa_family &&
IN6_IS_ADDR_V4MAPPED(&su->sin6.sin6_addr))
{
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = su->sin6.sin6_port;
memcpy(&sin.sin_addr, ((char *)&su->sin6.sin6_addr) + 12, 4);
memcpy(su, &sin, sizeof(struct sockaddr_in));
}
#endif /* HAVE_IPV6 */
}
int str2sockunion(const char *str, SOCKUNION_U *su)
{
int ret = 0;
memset(su, 0, sizeof(SOCKUNION_U));
ret = inet_pton(AF_INET, str, &su->sin.sin_addr);
/* Valid IPv4 address format. */
if (ret > 0)
{
su->sin.sin_family = AF_INET;
#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
su->sin.sin_len = sizeof(struct sockaddr_in);
#endif
return 0;
}
#ifdef HAVE_IPV6
ret = inet_pton(AF_INET6, str, &su->sin6.sin6_addr);
/* Valid IPv6 address format. */
if (ret > 0)
{
su->sin6.sin6_family = AF_INET6;
#ifdef SIN6_LEN
su->sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif
return 0;
}
#endif
return -1;
}
const char *sockunion2str(SOCKUNION_U *su, char *buf, size_t len)
{
if (AF_INET == su->sa.sa_family)
return inet_ntop(AF_INET, &su->sin.sin_addr, buf, len);
#ifdef HAVE_IPV6
else if(AF_INET6 == su->sa.sa_family)
return inet_ntop(AF_INET6, &su->sin6.sin6_addr, buf, len);
#endif
return NULL;
}
/* Return accepted new socket file descriptor. */
int sockunion_accept(int sock, SOCKUNION_U *su)
{
socklen_t len;
int client_sock;
len = sizeof(SOCKUNION_U);
client_sock = accept(sock, (struct sockaddr*)su, &len);
_sockunion_normalise_mapped(su);
return client_sock;
}
int set_nonblocking(int fd)
{
int flags = 0;
/* According to the Single UNIX Spec, the return value for F_GETFL should
* never be negative. */
if ((flags = fcntl(fd, F_GETFL)) < 0)
{
printh("fcntl(F_GETFL) failed for fd %d: %s", fd, safe_strerror(errno));
return -1;
}
if (fcntl(fd, F_SETFL, (flags | O_NONBLOCK)) < 0)
{
printh("fcntl failed setting fd %d non-blocking: %s", fd, safe_strerror(errno));
return -1;
}
return 0;
}
/* Utility function of convert between struct prefix <=> union sockunion. */
prefix_t *sockunion2hostprefix(const SOCKUNION_U *su)
{
if (su->sa.sa_family == AF_INET)
{
prefix_ipv4_t *p = NULL;
p = prefix_ipv4_new();
p->family = AF_INET;
p->prefix = su->sin.sin_addr;
p->prefixlen = IPV4_MAX_BITLEN;
return (prefix_t*)p;
}
#ifdef HAVE_IPV6
if (su->sa.sa_family == AF_INET6)
{
prefix_ipv6_t *p = NULL;
p = prefix_ipv6_new();
p->family = AF_INET6;
p->prefixlen = IPV6_MAX_BITLEN;
memcpy(&p->prefix, &su->sin6.sin6_addr, sizeof(struct in6_addr));
return (prefix_t*)p;
}
#endif /* HAVE_IPV6 */
return NULL;
}
char *sockunion_su2str(SOCKUNION_U *su)
{
char str[SU_ADDRSTRLEN] = {0};
switch (su->sa.sa_family)
{
case AF_INET:
inet_ntop(AF_INET, &su->sin.sin_addr, str, sizeof(str));
break;
#ifdef HAVE_IPV6
case AF_INET6:
inet_ntop(AF_INET6, &su->sin6.sin6_addr, str, sizeof(str));
break;
#endif /* HAVE_IPV6 */
}
return XSTRDUP(MTYPE_PREFIX, str);
}
/* Make socket from sockunion union. */
int sockunion_stream_socket(SOCKUNION_U *su)
{
int32_t sock = 0;
if (0 == su->sa.sa_family)
su->sa.sa_family = AF_INET_UNION;
sock = socket(su->sa.sa_family, SOCK_STREAM, 0);
if (sock < 0)
printh("can't make socket sockunion_stream_socket");
return sock;
}
int sockunion_reuseaddr(int sock)
{
int ret;
int on = 1;
ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
if (ret < 0)
{
printh("can't set sockopt SO_REUSEADDR to socket %d", sock);
return -1;
}
return 0;
}
/* Bind socket to specified address. */
int sockunion_bind(int sock, SOCKUNION_U *su, unsigned short port, SOCKUNION_U *su_addr)
{
int size = 0;
int ret = 0;
if (AF_INET == su->sa.sa_family)
{
size = sizeof(struct sockaddr_in);
su->sin.sin_port = htons(port);
if (NULL == su_addr)
su->sin.sin_addr.s_addr = htonl(INADDR_ANY);
}
#ifdef HAVE_IPV6
else if(AF_INET6 == su->sa.sa_family)
{
size = sizeof(struct sockaddr_in6);
su->sin6.sin6_port = htons(port);
if (NULL == su_addr)
memset (&su->sin6.sin6_addr, 0, sizeof(struct in6_addr));
}
#endif /* HAVE_IPV6 */
ret = bind(sock, (struct sockaddr *)su, size);
if (ret < 0)
printh("can't bind socket : %s\n", safe_strerror(errno));
return ret;
}
int sockunion_ip_set(char *name, unsigned int addr)
{
int fd = 0;
struct ifreq ifr;
struct sockaddr_in *sin = NULL;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
printh("Ip set socket error!\r\n");
return -1;
}
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
sin = (struct sockaddr_in*)&ifr.ifr_addr;
sin->sin_family = AF_INET;
/* IP地址 */
sin->sin_addr.s_addr = addr;
if (ioctl(fd, SIOCSIFADDR, &ifr) < 0)
{
close(fd);
printh("Ip set ioctl SIOCSIFADDR error!\r\n");
return -2;
}
close(fd);
return 0;
}
int sockunion_mask_set(char *name, unsigned int mask)
{
int fd = 0;
struct ifreq ifr;
struct sockaddr_in *sin = NULL;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
printh("socket error\r\n");
return -1;
}
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
sin = (struct sockaddr_in*)&ifr.ifr_addr;
sin->sin_family = AF_INET;
/* 子网掩码 */
sin->sin_addr.s_addr = mask;
if (ioctl(fd, SIOCSIFNETMASK, &ifr) < 0)
{
close(fd);
printh("ioctl\r\n");
return -3;
}
close(fd);
return 0;
}
int sockunion_gw_set(char *name, unsigned int gateway, unsigned int gateway_old)
{
int fd = 0;
struct rtentry rt;
int rv = 0;
fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
printh("Gateway set socket error!\r\n");
return -1;
}
/* Delete existing defalt gateway */
memset(&rt, 0, sizeof(rt));
rt.rt_dst.sa_family = AF_INET;
((struct sockaddr_in *)&rt.rt_dst)->sin_addr.s_addr = 0;
rt.rt_gateway.sa_family = AF_INET;
((struct sockaddr_in *)&rt.rt_gateway)->sin_addr.s_addr = gateway_old;
rt.rt_genmask.sa_family = AF_INET;
((struct sockaddr_in *)&rt.rt_genmask)->sin_addr.s_addr = 0;
rt.rt_flags = RTF_UP;
rv = ioctl(fd, SIOCDELRT, &rt);
/* Set default gateway */
if ((rv == 0 || errno == ESRCH) && gateway)
{
memset(&rt, 0, sizeof(rt));
rt.rt_dst.sa_family = AF_INET;
((struct sockaddr_in *)&rt.rt_dst)->sin_addr.s_addr = 0;
rt.rt_gateway.sa_family = AF_INET;
((struct sockaddr_in *)&rt.rt_gateway)->sin_addr.s_addr = gateway;
rt.rt_genmask.sa_family = AF_INET;
((struct sockaddr_in *)&rt.rt_genmask)->sin_addr.s_addr = 0;
rt.rt_flags = RTF_UP | RTF_GATEWAY;
rv = ioctl(fd, SIOCADDRT, &rt);
}
close(fd);
return rv;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,125 @@
/*****************************************************************************
* file lib/management/thread_monitor.c
* author Yuliang
* version 1.0.0
* date 08-Oct-2021
* brief This file provides all the thread monitor related operation functions.
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "array.h"
#include "cmd.h"
#include "thread_monitor.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define THREAD_M_SIZE 32
#define THREAD_LOCK pthread_mutex_lock(&thread_mutex)
#define THREAD_UNLOCK pthread_mutex_unlock(&thread_mutex)
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static pthread_mutex_t thread_mutex;
static array_t *thread_a;
/* Private function prototypes -----------------------------------------------*/
extern int pthread_tryjoin_np(pthread_t thread, void **retval);
/* Internal functions --------------------------------------------------------*/
CMD(thread_show,
thread_show_cmd,
"show thread",
SHOW_STR
"thread\n")
{
thread_m_t *node = NULL;
int32_t i = 0;
for (i = 0; i < thread_a->active; i++)
{
if (thread_a->index[i] != NULL)
{
node = (thread_m_t*)thread_a->index[i];
/* 当返回不为EBUSY时说明线程退出或者出错了,但是再次查询又会变为EBUSY,
FALSE,TRUE. */
if (pthread_tryjoin_np(node->pid, NULL) != EBUSY)
{
node->alive = FALSE;
}
vty_out(vty, "%-32s %-2d%s", node->name, node->alive, VTY_NEWLINE);
}
}
vty_out(vty, "%s", VTY_NEWLINE);
return CMD_SUCCESS;
}
/* Interface functions -------------------------------------------------------*/
/* description: 添加需要监控的线程.
param:
return: (E_NONE),() */
int32_t thread_m_add(char *str, pthread_t pid)
{
thread_m_t *node = NULL;
node = XMALLOC(MTYPE_THREAD_MONITOR, sizeof(thread_m_t));
snprintf(node->name, THREAD_M_NAME_LEN, "%s", str);
node->pid = pid;
node->alive = TRUE;
THREAD_LOCK;
array_append(thread_a, node, MTYPE_THREAD_MONITOR);
THREAD_UNLOCK;
return E_NONE;
}
/* description: 线程监控初始化.
param:
return: (E_NONE),() */
int32_t thread_m_init(void)
{
/* 初始化线程锁. */
pthread_mutex_init(&thread_mutex, NULL);
thread_a = array_init(THREAD_M_SIZE, MTYPE_THREAD_MONITOR);
cmd_install_element(COMMON_NODE, &thread_show_cmd);
return E_NONE;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****/

File diff suppressed because it is too large Load Diff

@ -0,0 +1,353 @@
/******************************************************************************
* file lib/hardware/hwgpio.c
* author YuLiang
* version 1.0.0
* date 24-Nov-2021
* brief This file provides all the gpio operation functions.
*
******************************************************************************
* Attention
*
* <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of LandPower nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 标准C库头文件. */
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/* 用户代码头文件. */
#include "hwgpio.h"
#include "cmd.h"
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static array_t *gpios = NULL;
int32_t gpio_run_idx;
int32_t gpio_wdg_idx;
/* Private function prototypes -----------------------------------------------*/
/* Internal functions --------------------------------------------------------*/
int32_t _gpio_name_get(uint8_t gpio, char *name)
{
if (!name)
{
return E_NULL;
}
switch (gpio)
{
case GPIO_RUN:
snprintf(name, DEV_NAME_STR_LEN, "run");
break;
default:
snprintf(name, DEV_NAME_STR_LEN, "default");
break;
}
return E_NONE;
}
CMD(gpio_show,
gpio_show_cmd,
"show gpio",
SHOW_STR
"Gpios\n")
{
uint16_t i = 0;
char gpio_name[DEV_NAME_STR_LEN] = {0};
gpio_node_t *gpio_node = NULL;
vty_out(vty, "GPIO NAME DIR VALUE%s", VTY_NEWLINE);
for(i = 0; i < array_active(gpios); i++)
{
gpio_node = array_lookup(gpios, i);
if (!gpio_node)
{
continue;
}
if (gpio_node->curr_dir == GPIO_DIR_IN)
{
gpio_val_get(gpio_node->index, &gpio_node->curr_val);
}
_gpio_name_get(gpio_node->gpio, gpio_name);
vty_out(vty, "%4d %-12s %-03s %d%s", gpio_node->gpio, gpio_name, gpio_node->curr_dir == GPIO_DIR_IN ? "in" : "out",
gpio_node->curr_val, VTY_NEWLINE);
}
return CMD_SUCCESS;
}
/* Interface functions -------------------------------------------------------*/
/* 根据 gpio 找到对应的结构体, 如果不存在, 返回NULL. */
gpio_node_t *gpio_get_by_gpio(uint16_t gpio)
{
uint16_t i = 0;
gpio_node_t *gpio_node = NULL;
for(i = 0; i < array_active(gpios); i++)
{
gpio_node = array_lookup(gpios, i);
if (!gpio_node)
{
continue;
}
if (gpio_node->gpio == gpio)
{
return gpio_node;
}
}
return NULL;
}
/* 根据数组 index 找到对应的结构体, 如果不存在, 返回 NULL. */
gpio_node_t *gpio_get_by_index(uint16_t index)
{
return (gpio_node_t*)array_lookup(gpios, index);
}
/* 设置gpio输出值 */
int32_t gpio_val_set(uint16_t index, uint8_t value)
{
int32_t fd = 0;
char buf[40] = {0};
gpio_node_t *gpio_node = gpio_get_by_index(index);
/* 参数检查 */
if (!gpio_node)
{
DBG(DBG_M_GPIO, "gpio index %d is not found\r\n", index);
return E_NOT_FOUND;
}
/* 只有out方向可以设置值 */
if (gpio_node->curr_dir != GPIO_DIR_OUT)
{
DBG(DBG_M_GPIO, "gpio %d direction is not out\r\n", gpio_node->gpio);
return E_BAD_PARAM;
}
/* 如果值相等就不需要再操作了 */
if (gpio_node->curr_val == value)
{
return E_NONE;
}
/* 打开文件 */
snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio_node->gpio);
fd = open(buf, O_WRONLY);
if (fd <= 0)
{
DBG(DBG_M_GPIO, "Open %s error", buf);
return E_SYS_CALL;
}
/* 设置值 */
snprintf(buf, sizeof(buf), "%d", (value == 0) ? 0 : 1);
if (write(fd, buf, 1) <= 0)
{
DBG(DBG_M_GPIO, "Write gpio %d value error", gpio_node->gpio);
return E_SYS_CALL;
}
close(fd);
gpio_node->curr_val = value;
return E_NONE;
}
/* 设置gpio输出值 */
int32_t gpio_val_get(uint16_t index, uint8_t *value)
{
int32_t fd = 0;
char buf[40] = {0};
gpio_node_t *gpio_node = gpio_get_by_index(index);
/* 参数检查 */
if (!gpio_node)
{
DBG(DBG_M_GPIO, "gpio index %d is not found\r\n", index);
return E_NOT_FOUND;
}
/* out方向直接读取 */
if (GPIO_DIR_OUT == gpio_node->curr_dir)
{
*value = gpio_node->curr_val;
return E_NONE;
}
/* 打开文件 */
snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio_node->gpio);
fd = open(buf, O_RDONLY);
if (fd <= 0)
{
DBG(DBG_M_GPIO, "Open %s error", buf);
return E_SYS_CALL;
}
/* 读取值 */
memset(buf, 0, sizeof(buf));
if (read(fd, buf, sizeof(buf) - 1) <= 0)
{
DBG(DBG_M_GPIO, "Read gpio %d value error", gpio_node->gpio);
return E_SYS_CALL;
}
close(fd);
*value = strtol(buf, NULL, 10);
return E_NONE;
}
/* 设置gpio方向 */
int32_t gpio_dir_set(uint16_t index, uint8_t dir)
{
int32_t fd = 0;
char buf[40] = {0};
gpio_node_t *gpio_node = gpio_get_by_index(index);
/* 参数检查 */
if (!gpio_node)
{
DBG(DBG_M_GPIO, "gpio index %d is not found\r\n", index);
return E_NOT_FOUND;
}
/* 如果方向相等,不用继续操作 */
if (gpio_node->curr_dir == dir)
{
return E_NONE;
}
/* 打开文件 */
snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/direction", gpio_node->gpio);
fd = open(buf, O_WRONLY);
if (fd <= 0)
{
DBG(DBG_M_GPIO, "Open %s error", buf);
return E_SYS_CALL;
}
/* 设置方向 */
snprintf(buf, sizeof(buf), "%s", (dir == GPIO_DIR_IN) ? "in" : "out");
if (write(fd, buf, strlen(buf)) <= 0)
{
DBG(DBG_M_GPIO, "Write gpio %d direction error", gpio_node->gpio);
return E_SYS_CALL;
}
close(fd);
gpio_node->curr_dir = dir;
return E_NONE;
}
/* 导出 GPIO, 返回值大于等于 0, 表示加入数组的 index; 小于 0 表示失败. */
int32_t gpio_export(uint16_t gpio)
{
int32_t fd = 0;
char buf[40] = {0};
gpio_node_t *gpio_node = gpio_get_by_gpio(gpio);
/* 如果找到表示已经 export. */
if (gpio_node)
{
return -1;
}
/* 文件不存在则导出, 存在不做操作. */
snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d", gpio);
if (access(buf, 0) < 0)
{
/* 打开文件描述符 */
fd = open("/sys/class/gpio/export", O_WRONLY);
if (fd <= 0)
{
log_err(LOG_GPIO, "Open /sys/class/gpio/export error!");
return -2;
}
/* 导出gpio */
snprintf(buf, sizeof(buf), "%d", gpio);
if (write(fd, buf, strlen(buf)) <= 0)
{
log_err(LOG_GPIO, "Write /sys/class/gpio/export(%d) error!", gpio);
return -3;
}
close(fd);
}
/* 添加结构体 */
gpio_node = XMALLOC_Q(MTYPE_GPIO, sizeof(gpio_node_t));
gpio_node->gpio = gpio;
/* 默认值是不确定的 */
gpio_node->curr_val = 0xff;
gpio_node->is_export = TRUE;
gpio_node->index = array_append(gpios, gpio_node, MTYPE_GPIO);
return gpio_node->index;
}
/* 初始化函数 */
int32_t gpio_init(void)
{
gpios = array_init(ARRAY_MIN_SIZE, MTYPE_GPIO);
cmd_install_element(COMMON_NODE, &gpio_show_cmd);
gpio_run_idx = gpio_export(GPIO_RUN);
if (gpio_run_idx < 0)
{
DBG(DBG_M_GPIO, "ERROR return %d!\r\n", gpio_run_idx);
return E_BAD_PARAM;
}
LD_E_RETURN(DBG_M_GPIO, gpio_dir_set(gpio_run_idx, GPIO_DIR_OUT));
gpio_wdg_idx = gpio_export(GPIO_WDG);
if (gpio_wdg_idx < 0)
{
DBG(DBG_M_GPIO, "ERROR return %d!\r\n", gpio_wdg_idx);
return E_BAD_PARAM;
}
LD_E_RETURN(DBG_M_GPIO, gpio_dir_set(gpio_wdg_idx, GPIO_DIR_OUT));
return E_NONE;
}
/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/

@ -0,0 +1,3 @@
local_src := $(patsubst $(SOURCE_DIR)/%,%,$(wildcard $(SOURCE_DIR)/$(subdirectory)/*.c))
$(eval $(call make-library,$(subdirectory)/libz_hardware.a,$(local_src)))

@ -0,0 +1,6 @@
# debug 功能开启
CFG_DBG_ON := y
# Cable 设备
CFG_DEV_TYPE_LAND_CA := y
# 是否有 MQTT 通讯协议
CFG_PROTO_MQTT := y

@ -0,0 +1,138 @@
# $(call source-to-object,source-file-list($1))
source-to-object = $(subst .c,.o,$(filter %.c,$1))
# 产生库文件相对路å¾?被æ¯<C3A6>个库ç¨åº<C3A5>çš„module.mkæ‡ä»¶ä½¿ç”¨.
# $(subdirectory)
subdirectory = $(patsubst $(SOURCE_DIR)/%/module.mk,%, \
$(word \
$(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)))
# 产生库文件规åˆ?被æ¯<C3A6>个库ç¨åº<C3A5>çš„module.mkæ‡ä»¶ä½¿ç”¨.
$(call make-library,library-name($1),source-file-list($2))
define make-library
libraries += $1
sources += $2
$1: $(call source-to-object,$2)
$(QUIET)$(AR) $(ARFLAGS) $$@ $$^ $(ENULL)
@echo "$$(INFO_C)AR $$@ done";echo
endef
# 产生ä¾<C3A4>èµæ‡ä»¶.
# $(call make-depend,source-file($1),object-file($2),depend-file($3))
define make-depend
$(CC) -MM -MF $3 -MP -MT $2 $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) $1
endef
SOURCE_DIR := ../app
MQTT_DIR := ../mqtt
PRODUCT := $(MAKECMDGOALS)
CONFIG_FILE := $(SOURCE_DIR)/include/config.h
VERSION_FILE := $(SOURCE_DIR)/include/version.h
VERSION_LIB := version.a
DATE_STRING := `date "+%Y.%m.%d %k:%M:%S"`
VERSION_STRING := "3.2.1.6"
MV := mv -f
RM := rm -rf
SED := sed
TEST := test
MKDIR := mkdir -p
# 交å<C2A4>‰ç¼è¯è®¾ç½®
#DEFARCH = PC
DEFARCH = MYiR
ifeq ($(DEFARCH), PC)
CROSS_COMPILE =
CC = $(CROSS_COMPILE)gcc
AR = $(CROSS_COMPILE)ar
CFLAGS = -g -Wall -funwind-tables -rdynamic -DHAVE_CONFIG_H
else ifeq ($(DEFARCH), MYiR)
CFLAGS += -g -Wall -funwind-tables -rdynamic -DHAVE_CONFIG_H
endif
LDLIB := -lreadline -lncurses -pthread -lm -ldl -lrt -lpaho-mqtt3as -lssl -lcrypto -lsqlite3
# 这里如果是‘@’则éš<C3A9>è—<C3A8>具体的ç¼è¯å½ä»?
#QUIET := @
ENULL := > /dev/null
INFO_C := "\\33[32mInfo\\33[0m "
ERROR_C := "\\33[31mInfo\\33[0m "
modules := $(patsubst $(SOURCE_DIR)/%/module.mk,%, \
$(shell find $(SOURCE_DIR) -name module.mk))
# 该å<C2A5>˜é‡<C3A9>仅用于产生输出ç®å½•,ä¸<C3A4>å<EFBFBD>šä»»ä½•å…¶ä»ä½¿ç”¨.
create-output-directories := $(shell for f in $(modules); \
do \
$(TEST) -d $$f || $(MKDIR) $$f; \
done)
programs :=
sources :=
libraries :=
objects = $(call source-to-object,$(sources))
dependencies = $(subst .o,.d,$(objects))
include_dirs := $(SOURCE_DIR)/include $(MQTT_DIR)/include
CPPFLAGS += $(addprefix -I ,$(include_dirs))
vpath %.h $(include_dirs)
vpath %.c $(SOURCE_DIR)
.PHONY: empty
empty:
@echo "Please explicitly specify the Makefile target!!!Example \"make PDMonitor\"."
include $(patsubst %,$(SOURCE_DIR)/%/module.mk,$(modules))
$(VERSION_LIB): $(CONFIG_FILE) $(libraries) version.c
$(QUIET)$(RM) $(VERSION_FILE)
@echo "/* WARNING: Don't modify this file anywhere!!! */" >> $(VERSION_FILE)
@echo "#ifndef _VERSION_H_" >> $(VERSION_FILE)
@echo "#define _VERSION_H_" >> $(VERSION_FILE)
@echo "" >> $(VERSION_FILE)
@echo "#define VERSION \"$(VERSION_STRING)\"" >> $(VERSION_FILE)
@echo "#define DATE \"$(DATE_STRING)\"" >> $(VERSION_FILE)
@echo "" >> $(VERSION_FILE)
@echo "char* version_get();" >> $(VERSION_FILE)
@echo "char* version_date_get();" >> $(VERSION_FILE)
@echo "" >> $(VERSION_FILE)
@echo "#endif" >> $(VERSION_FILE)
@echo "/* WARNING: Don't modify this file anywhere!!! */" >> $(VERSION_FILE)
@echo "COMPILE version.o"
$(QUIET)$(COMPILE.c) -o version.o version.c
$(QUIET)$(AR) $(ARFLAGS) $(VERSION_LIB) version.o $(ENULL)
@echo "$(INFO_C)AR $@ done";echo
PDMonitor: $(CONFIG_FILE) $(libraries) $(VERSION_LIB)
# 使用两次$(libraries)é<>¿å…<C3A5>库æ‡ä»¶ä¹é—´çš„交å<C2A4>‰å¼•用问题.
$(QUIET)$(LINK.o) -rdynamic $(libraries) $(VERSION_LIB) $(LDLIB) -o $@
@echo "$(INFO_C)LINK $@ done";echo
# $(QUIET)cp $@ //home//embed//LandPower//
CableMQTT: $(CONFIG_FILE) $(libraries) $(VERSION_LIB)
# 使用两次$(libraries)é<>¿å…<C3A5>库æ‡ä»¶ä¹é—´çš„交å<C2A4>‰å¼•用问题.
$(QUIET)$(LINK.o) -rdynamic $(libraries) $(libraries) $(VERSION_LIB) $(LDLIB) -L $(MQTT_DIR)/lib -o $@
@echo "$(INFO_C)LINK $@ done";echo
# $(QUIET)cp $@ //home//embed//LandPower//
.PHONY: libraries
libraries: $(libraries)
.PHONY: clean
clean:
$(RM) $(modules) $(CONFIG_FILE) $(VERSION_FILE) PDMonitor CableMQTT $(VERSION_LIB) version.o
ifneq "$(MAKECMDGOALS)" "clean"
-include $(dependencies)
include config.mk
endif
%.o: %.c
@echo "COMPILE $@"
$(QUIET)$(call make-depend,$<,$@,$(subst .o,.d,$@))
$(QUIET)$(COMPILE.c) -o $@ $<

@ -0,0 +1,49 @@
include $(PRODUCT).cfg
$(CONFIG_FILE): $(PRODUCT).cfg
$(QUIET)rm $(CONFIG_FILE) -rf
@echo "/* WARNING: Don't modify this file anywhere!!! */" >> $(CONFIG_FILE)
@echo "#ifndef _CONFIG_H_" >> $(CONFIG_FILE)
@echo "#define _CONFIG_H_" >> $(CONFIG_FILE)
@echo "" >> $(CONFIG_FILE)
@echo "#define PROGNAME \"$(PRODUCT)\"" >> $(CONFIG_FILE)
# debug开关
ifeq ($(CFG_DBG_ON), y)
@echo "#define CFG_DBG_ON" >> $(CONFIG_FILE)
endif
# 设备类型定义
ifeq ($(CFG_DEV_TYPE_LAND_PD), y)
@echo "#define CFG_DEV_TYPE_LAND_PD" >> $(CONFIG_FILE)
endif
ifeq ($(CFG_DEV_TYPE_LAND_CA), y)
@echo "#define CFG_DEV_TYPE_LAND_CA" >> $(CONFIG_FILE)
endif
# 朗德GIS协议开关
ifeq ($(CFG_PROTO_GIS), y)
@echo "#define CFG_PROTO_GIS" >> $(CONFIG_FILE)
endif
# 默认使能朗德GIS协议开关
ifeq ($(CFG_PROTO_GIS_DEFAULT), y)
@echo "#define CFG_PROTO_GIS_DEFAULT" >> $(CONFIG_FILE)
endif
# MQTT 协议开关
ifeq ($(CFG_PROTO_MQTT), y)
@echo "#define CFG_PROTO_MQTT" >> $(CONFIG_FILE)
endif
@echo "" >> $(CONFIG_FILE)
@echo "#include \"common.h\"" >> $(CONFIG_FILE)
@echo "" >> $(CONFIG_FILE)
@echo "#endif" >> $(CONFIG_FILE)
@echo "/* WARNING: Don't modify this file anywhere!!! */" >> $(CONFIG_FILE)
@echo "$(INFO_C)Create $@ done";echo
$(VERSION_FILE): $(PRODUCT).cfg

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,277 @@
/*******************************************************************************
* Copyright (c) 2009, 2020 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial API and implementation and/or initial documentation
*******************************************************************************/
/**
* @file
* \brief This structure represents a persistent data store, used to store
* outbound and inbound messages, in order to achieve reliable messaging.
*
* The MQTT Client persists QoS1 and QoS2 messages in order to meet the
* assurances of delivery associated with these @ref qos levels. The messages
* are saved in persistent storage
* The type and context of the persistence implementation are specified when
* the MQTT client is created (see MQTTClient_create()). The default
* persistence type (::MQTTCLIENT_PERSISTENCE_DEFAULT) uses a file system-based
* persistence mechanism. The <i>persistence_context</i> argument passed to
* MQTTClient_create() when using the default peristence is a string
* representing the location of the persistence directory. If the context
* argument is NULL, the working directory will be used.
*
* To use memory-based persistence, an application passes
* ::MQTTCLIENT_PERSISTENCE_NONE as the <i>persistence_type</i> to
* MQTTClient_create(). This can lead to message loss in certain situations,
* but can be appropriate in some cases (see @ref qos).
*
* Client applications can provide their own persistence mechanism by passing
* ::MQTTCLIENT_PERSISTENCE_USER as the <i>persistence_type</i>. To implement a
* custom persistence mechanism, the application must pass an initialized
* ::MQTTClient_persistence structure as the <i>persistence_context</i>
* argument to MQTTClient_create().
*
* If the functions defined return an ::MQTTCLIENT_PERSISTENCE_ERROR then the
* state of the persisted data should remain as it was prior to the function
* being called. For example, if Persistence_put() returns
* ::MQTTCLIENT_PERSISTENCE_ERROR, then it is assumed tha tthe persistent store
* does not contain the data that was passed to the function. Similarly, if
* Persistence_remove() returns ::MQTTCLIENT_PERSISTENCE_ERROR then it is
* assumed that the data to be removed is still held in the persistent store.
*
* It is up to the persistence implementation to log any error information that
* may be required to diagnose a persistence mechanism failure.
*/
/*
/// @cond EXCLUDE
*/
#if !defined(MQTTCLIENTPERSISTENCE_H)
#define MQTTCLIENTPERSISTENCE_H
/*
/// @endcond
*/
/**
* This <i>persistence_type</i> value specifies the default file system-based
* persistence mechanism (see MQTTClient_create()).
*/
#define MQTTCLIENT_PERSISTENCE_DEFAULT 0
/**
* This <i>persistence_type</i> value specifies a memory-based
* persistence mechanism (see MQTTClient_create()).
*/
#define MQTTCLIENT_PERSISTENCE_NONE 1
/**
* This <i>persistence_type</i> value specifies an application-specific
* persistence mechanism (see MQTTClient_create()).
*/
#define MQTTCLIENT_PERSISTENCE_USER 2
/**
* Application-specific persistence functions must return this error code if
* there is a problem executing the function.
*/
#define MQTTCLIENT_PERSISTENCE_ERROR -2
/**
* @brief Initialize the persistent store.
*
* Either open the existing persistent store for this client ID or create a new
* one if one doesn't exist. If the persistent store is already open, return
* without taking any action.
*
* An application can use the same client identifier to connect to many
* different servers. The <i>clientid</i> in conjunction with the
* <i>serverURI</i> uniquely identifies the persistence store required.
*
* @param handle The address of a pointer to a handle for this persistence
* implementation. This function must set handle to a valid reference to the
* persistence following a successful return.
* The handle pointer is passed as an argument to all the other
* persistence functions. It may include the context parameter and/or any other
* data for use by the persistence functions.
* @param clientID The client identifier for which the persistent store should
* be opened.
* @param serverURI The connection string specified when the MQTT client was
* created (see MQTTClient_create()).
* @param context A pointer to any data required to initialize the persistent
* store (see ::MQTTClient_persistence).
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_open)(void** handle, const char* clientID, const char* serverURI, void* context);
/**
* @brief Close the persistent store referred to by the handle.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_close)(void* handle);
/**
* @brief Put the specified data into the persistent store.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @param key A string used as the key for the data to be put in the store. The
* key is later used to retrieve data from the store with Persistence_get().
* @param bufcount The number of buffers to write to the persistence store.
* @param buffers An array of pointers to the data buffers associated with
* this <i>key</i>.
* @param buflens An array of lengths of the data buffers. <i>buflen[n]</i>
* gives the length of <i>buffer[n]</i>.
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_put)(void* handle, char* key, int bufcount, char* buffers[], int buflens[]);
/**
* @brief Retrieve the specified data from the persistent store.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @param key A string that is the key for the data to be retrieved. This is
* the same key used to save the data to the store with Persistence_put().
* @param buffer The address of a pointer to a buffer. This function sets the
* pointer to point at the retrieved data, if successful.
* @param buflen The address of an int that is set to the length of
* <i>buffer</i> by this function if successful.
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_get)(void* handle, char* key, char** buffer, int* buflen);
/**
* @brief Remove the data for the specified key from the store.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @param key A string that is the key for the data to be removed from the
* store. This is the same key used to save the data to the store with
* Persistence_put().
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_remove)(void* handle, char* key);
/**
* @brief Returns the keys in this persistent data store.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @param keys The address of a pointer to pointers to strings. Assuming
* successful execution, this function allocates memory to hold the returned
* keys (strings used to store the data with Persistence_put()). It also
* allocates memory to hold an array of pointers to these strings. <i>keys</i>
* is set to point to the array of pointers to strings.
* @param nkeys A pointer to the number of keys in this persistent data store.
* This function sets the number of keys, if successful.
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_keys)(void* handle, char*** keys, int* nkeys);
/**
* @brief Clears the persistence store, so that it no longer contains any
* persisted data.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @return Return 0 if the function completes successfully, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_clear)(void* handle);
/**
* @brief Returns whether any data has been persisted using the specified key.
*
* @param handle The handle pointer from a successful call to
* Persistence_open().
* @param key The string to be tested for existence in the store.
* @return Return 0 if the key was found in the store, otherwise return
* ::MQTTCLIENT_PERSISTENCE_ERROR.
*/
typedef int (*Persistence_containskey)(void* handle, char* key);
/**
* @brief A structure containing the function pointers to a persistence
* implementation and the context or state that will be shared across all
* the persistence functions.
*/
typedef struct {
/**
* A pointer to any data required to initialize the persistent store.
*/
void* context;
/**
* A function pointer to an implementation of Persistence_open().
*/
Persistence_open popen;
/**
* A function pointer to an implementation of Persistence_close().
*/
Persistence_close pclose;
/**
* A function pointer to an implementation of Persistence_put().
*/
Persistence_put pput;
/**
* A function pointer to an implementation of Persistence_get().
*/
Persistence_get pget;
/**
* A function pointer to an implementation of Persistence_remove().
*/
Persistence_remove premove;
/**
* A function pointer to an implementation of Persistence_keys().
*/
Persistence_keys pkeys;
/**
* A function pointer to an implementation of Persistence_clear().
*/
Persistence_clear pclear;
/**
* A function pointer to an implementation of Persistence_containskey().
*/
Persistence_containskey pcontainskey;
} MQTTClient_persistence;
/**
* A callback which is invoked just before a write to persistence. This can be
* used to transform the data, for instance to encrypt it.
* @param context The context as set in ::MQTTAsync_setBeforePersistenceWrite
* @param bufcount The number of buffers to write to the persistence store.
* @param buffers An array of pointers to the data buffers.
* @param buflens An array of lengths of the data buffers.
* @return Return 0 if the function completes successfully, otherwise non 0.
*/
typedef int MQTTPersistence_beforeWrite(void* context, int bufcount, char* buffers[], int buflens[]);
/**
* A callback which is invoked just after a read from persistence. This can be
* used to transform the data, for instance to decrypt it.
* @param context The context as set in ::MQTTAsync_setAfterPersistenceRead
* @param buffer The address of a pointer to a buffer.
* @param buflen The address of an int that is the length of the buffer.
* @return Return 0 if the function completes successfully, otherwise non 0.
*/
typedef int MQTTPersistence_afterRead(void* context, char** buffer, int* buflen);
#endif

@ -0,0 +1,36 @@
/*******************************************************************************
* Copyright (c) 2020, 2020 Andreas Walter
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Andreas Walter - initially moved export declarations into separate fle
*******************************************************************************/
#if !defined(EXPORTDECLARATIONS_H)
#define EXPORTDECLARATIONS_H
#if defined(_WIN32) || defined(_WIN64)
# if defined(PAHO_MQTT_EXPORTS)
# define LIBMQTT_API __declspec(dllexport)
# elif defined(PAHO_MQTT_IMPORTS)
# define LIBMQTT_API __declspec(dllimport)
# else
# define LIBMQTT_API
# endif
#else
# if defined(PAHO_MQTT_EXPORTS)
# define LIBMQTT_API __attribute__ ((visibility ("default")))
# else
# define LIBMQTT_API extern
# endif
#endif
#endif

@ -0,0 +1,222 @@
/*******************************************************************************
* Copyright (c) 2017, 2023 IBM Corp. and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial API and implementation and/or initial documentation
*******************************************************************************/
#if !defined(MQTTPROPERTIES_H)
#define MQTTPROPERTIES_H
#include "MQTTExportDeclarations.h"
#define MQTT_INVALID_PROPERTY_ID -2
/** The one byte MQTT V5 property indicator */
enum MQTTPropertyCodes {
MQTTPROPERTY_CODE_PAYLOAD_FORMAT_INDICATOR = 1, /**< The value is 1 */
MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL = 2, /**< The value is 2 */
MQTTPROPERTY_CODE_CONTENT_TYPE = 3, /**< The value is 3 */
MQTTPROPERTY_CODE_RESPONSE_TOPIC = 8, /**< The value is 8 */
MQTTPROPERTY_CODE_CORRELATION_DATA = 9, /**< The value is 9 */
MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIER = 11, /**< The value is 11 */
MQTTPROPERTY_CODE_SESSION_EXPIRY_INTERVAL = 17, /**< The value is 17 */
MQTTPROPERTY_CODE_ASSIGNED_CLIENT_IDENTIFER = 18,/**< The value is 18 */
MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE = 19, /**< The value is 19 */
MQTTPROPERTY_CODE_AUTHENTICATION_METHOD = 21, /**< The value is 21 */
MQTTPROPERTY_CODE_AUTHENTICATION_DATA = 22, /**< The value is 22 */
MQTTPROPERTY_CODE_REQUEST_PROBLEM_INFORMATION = 23,/**< The value is 23 */
MQTTPROPERTY_CODE_WILL_DELAY_INTERVAL = 24, /**< The value is 24 */
MQTTPROPERTY_CODE_REQUEST_RESPONSE_INFORMATION = 25,/**< The value is 25 */
MQTTPROPERTY_CODE_RESPONSE_INFORMATION = 26, /**< The value is 26 */
MQTTPROPERTY_CODE_SERVER_REFERENCE = 28, /**< The value is 28 */
MQTTPROPERTY_CODE_REASON_STRING = 31, /**< The value is 31 */
MQTTPROPERTY_CODE_RECEIVE_MAXIMUM = 33, /**< The value is 33*/
MQTTPROPERTY_CODE_TOPIC_ALIAS_MAXIMUM = 34, /**< The value is 34 */
MQTTPROPERTY_CODE_TOPIC_ALIAS = 35, /**< The value is 35 */
MQTTPROPERTY_CODE_MAXIMUM_QOS = 36, /**< The value is 36 */
MQTTPROPERTY_CODE_RETAIN_AVAILABLE = 37, /**< The value is 37 */
MQTTPROPERTY_CODE_USER_PROPERTY = 38, /**< The value is 38 */
MQTTPROPERTY_CODE_MAXIMUM_PACKET_SIZE = 39, /**< The value is 39 */
MQTTPROPERTY_CODE_WILDCARD_SUBSCRIPTION_AVAILABLE = 40,/**< The value is 40 */
MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIERS_AVAILABLE = 41,/**< The value is 41 */
MQTTPROPERTY_CODE_SHARED_SUBSCRIPTION_AVAILABLE = 42/**< The value is 241 */
};
/**
* Returns a printable string description of an MQTT V5 property code.
* @param value an MQTT V5 property code.
* @return the printable string description of the input property code.
* NULL if the code was not found.
*/
LIBMQTT_API const char* MQTTPropertyName(enum MQTTPropertyCodes value);
/** The one byte MQTT V5 property type */
enum MQTTPropertyTypes {
MQTTPROPERTY_TYPE_BYTE,
MQTTPROPERTY_TYPE_TWO_BYTE_INTEGER,
MQTTPROPERTY_TYPE_FOUR_BYTE_INTEGER,
MQTTPROPERTY_TYPE_VARIABLE_BYTE_INTEGER,
MQTTPROPERTY_TYPE_BINARY_DATA,
MQTTPROPERTY_TYPE_UTF_8_ENCODED_STRING,
MQTTPROPERTY_TYPE_UTF_8_STRING_PAIR
};
/**
* Returns the MQTT V5 type code of an MQTT V5 property.
* @param value an MQTT V5 property code.
* @return the MQTT V5 type code of the input property. -1 if the code was not found.
*/
LIBMQTT_API int MQTTProperty_getType(enum MQTTPropertyCodes value);
/**
* The data for a length delimited string
*/
typedef struct
{
int len; /**< the length of the string */
char* data; /**< pointer to the string data */
} MQTTLenString;
/**
* Structure to hold an MQTT version 5 property of any type
*/
typedef struct
{
enum MQTTPropertyCodes identifier; /**< The MQTT V5 property id. A multi-byte integer. */
/** The value of the property, as a union of the different possible types. */
union {
unsigned char byte; /**< holds the value of a byte property type */
unsigned short integer2; /**< holds the value of a 2 byte integer property type */
unsigned int integer4; /**< holds the value of a 4 byte integer property type */
struct {
MQTTLenString data; /**< The value of a string property, or the name of a user property. */
MQTTLenString value; /**< The value of a user property. */
};
} value;
} MQTTProperty;
/**
* MQTT version 5 property list
*/
typedef struct MQTTProperties
{
int count; /**< number of property entries in the array */
int max_count; /**< max number of properties that the currently allocated array can store */
int length; /**< mbi: byte length of all properties */
MQTTProperty *array; /**< array of properties */
} MQTTProperties;
#define MQTTProperties_initializer {0, 0, 0, NULL}
/**
* Returns the length of the properties structure when serialized ready for network transmission.
* @param props an MQTT V5 property structure.
* @return the length in bytes of the properties when serialized.
*/
int MQTTProperties_len(MQTTProperties* props);
/**
* Add a property pointer to the property array. Memory is allocated in this function,
* so MQTTClient_create or MQTTAsync_create must be called first to initialize the
* internal heap tracking. Alternatively MQTTAsync_global_init() can be called first
* or build with the HIGH_PERFORMANCE option which disables the heap tracking.
* @param props The property list to add the property to.
* @param prop The property to add to the list.
* @return 0 on success, -1 on failure.
*/
LIBMQTT_API int MQTTProperties_add(MQTTProperties* props, const MQTTProperty* prop);
/**
* Serialize the given property list to a character buffer, e.g. for writing to the network.
* @param pptr pointer to the buffer - move the pointer as we add data
* @param properties pointer to the property list, can be NULL
* @return whether the write succeeded or not: number of bytes written, or < 0 on failure.
*/
int MQTTProperties_write(char** pptr, const MQTTProperties* properties);
/**
* Reads a property list from a character buffer into an array.
* @param properties pointer to the property list to be filled. Should be initalized but empty.
* @param pptr pointer to the character buffer.
* @param enddata pointer to the end of the character buffer so we don't read beyond.
* @return 1 if the properties were read successfully.
*/
int MQTTProperties_read(MQTTProperties* properties, char** pptr, char* enddata);
/**
* Free all memory allocated to the property list, including any to individual properties.
* @param properties pointer to the property list.
*/
LIBMQTT_API void MQTTProperties_free(MQTTProperties* properties);
/**
* Copy the contents of a property list, allocating additional memory if needed.
* @param props pointer to the property list.
* @return the duplicated property list.
*/
LIBMQTT_API MQTTProperties MQTTProperties_copy(const MQTTProperties* props);
/**
* Checks if property list contains a specific property.
* @param props pointer to the property list.
* @param propid the property id to check for.
* @return 1 if found, 0 if not.
*/
LIBMQTT_API int MQTTProperties_hasProperty(MQTTProperties *props, enum MQTTPropertyCodes propid);
/**
* Returns the number of instances of a property id. Most properties can exist only once.
* User properties and subscription ids can exist more than once.
* @param props pointer to the property list.
* @param propid the property id to check for.
* @return the number of times found. Can be 0.
*/
LIBMQTT_API int MQTTProperties_propertyCount(MQTTProperties *props, enum MQTTPropertyCodes propid);
/**
* Returns the integer value of a specific property. The property given must be a numeric type.
* @param props pointer to the property list.
* @param propid the property id to check for.
* @return the integer value of the property. -9999999 on failure.
*/
LIBMQTT_API int MQTTProperties_getNumericValue(MQTTProperties *props, enum MQTTPropertyCodes propid);
/**
* Returns the integer value of a specific property when it's not the only instance.
* The property given must be a numeric type.
* @param props pointer to the property list.
* @param propid the property id to check for.
* @param index the instance number, starting at 0.
* @return the integer value of the property. -9999999 on failure.
*/
LIBMQTT_API int MQTTProperties_getNumericValueAt(MQTTProperties *props, enum MQTTPropertyCodes propid, int index);
/**
* Returns a pointer to the property structure for a specific property.
* @param props pointer to the property list.
* @param propid the property id to check for.
* @return the pointer to the property structure if found. NULL if not found.
*/
LIBMQTT_API MQTTProperty* MQTTProperties_getProperty(MQTTProperties *props, enum MQTTPropertyCodes propid);
/**
* Returns a pointer to the property structure for a specific property when it's not the only instance.
* @param props pointer to the property list.
* @param propid the property id to check for.
* @param index the instance number, starting at 0.
* @return the pointer to the property structure if found. NULL if not found.
*/
LIBMQTT_API MQTTProperty* MQTTProperties_getPropertyAt(MQTTProperties *props, enum MQTTPropertyCodes propid, int index);
#endif /* MQTTPROPERTIES_H */

@ -0,0 +1,79 @@
/*******************************************************************************
* Copyright (c) 2017, 2020 IBM Corp. and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial API and implementation and/or initial documentation
*******************************************************************************/
#if !defined(MQTTREASONCODES_H)
#define MQTTREASONCODES_H
#include "MQTTExportDeclarations.h"
/** The MQTT V5 one byte reason code */
enum MQTTReasonCodes {
MQTTREASONCODE_SUCCESS = 0,
MQTTREASONCODE_NORMAL_DISCONNECTION = 0,
MQTTREASONCODE_GRANTED_QOS_0 = 0,
MQTTREASONCODE_GRANTED_QOS_1 = 1,
MQTTREASONCODE_GRANTED_QOS_2 = 2,
MQTTREASONCODE_DISCONNECT_WITH_WILL_MESSAGE = 4,
MQTTREASONCODE_NO_MATCHING_SUBSCRIBERS = 16,
MQTTREASONCODE_NO_SUBSCRIPTION_FOUND = 17,
MQTTREASONCODE_CONTINUE_AUTHENTICATION = 24,
MQTTREASONCODE_RE_AUTHENTICATE = 25,
MQTTREASONCODE_UNSPECIFIED_ERROR = 128,
MQTTREASONCODE_MALFORMED_PACKET = 129,
MQTTREASONCODE_PROTOCOL_ERROR = 130,
MQTTREASONCODE_IMPLEMENTATION_SPECIFIC_ERROR = 131,
MQTTREASONCODE_UNSUPPORTED_PROTOCOL_VERSION = 132,
MQTTREASONCODE_CLIENT_IDENTIFIER_NOT_VALID = 133,
MQTTREASONCODE_BAD_USER_NAME_OR_PASSWORD = 134,
MQTTREASONCODE_NOT_AUTHORIZED = 135,
MQTTREASONCODE_SERVER_UNAVAILABLE = 136,
MQTTREASONCODE_SERVER_BUSY = 137,
MQTTREASONCODE_BANNED = 138,
MQTTREASONCODE_SERVER_SHUTTING_DOWN = 139,
MQTTREASONCODE_BAD_AUTHENTICATION_METHOD = 140,
MQTTREASONCODE_KEEP_ALIVE_TIMEOUT = 141,
MQTTREASONCODE_SESSION_TAKEN_OVER = 142,
MQTTREASONCODE_TOPIC_FILTER_INVALID = 143,
MQTTREASONCODE_TOPIC_NAME_INVALID = 144,
MQTTREASONCODE_PACKET_IDENTIFIER_IN_USE = 145,
MQTTREASONCODE_PACKET_IDENTIFIER_NOT_FOUND = 146,
MQTTREASONCODE_RECEIVE_MAXIMUM_EXCEEDED = 147,
MQTTREASONCODE_TOPIC_ALIAS_INVALID = 148,
MQTTREASONCODE_PACKET_TOO_LARGE = 149,
MQTTREASONCODE_MESSAGE_RATE_TOO_HIGH = 150,
MQTTREASONCODE_QUOTA_EXCEEDED = 151,
MQTTREASONCODE_ADMINISTRATIVE_ACTION = 152,
MQTTREASONCODE_PAYLOAD_FORMAT_INVALID = 153,
MQTTREASONCODE_RETAIN_NOT_SUPPORTED = 154,
MQTTREASONCODE_QOS_NOT_SUPPORTED = 155,
MQTTREASONCODE_USE_ANOTHER_SERVER = 156,
MQTTREASONCODE_SERVER_MOVED = 157,
MQTTREASONCODE_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158,
MQTTREASONCODE_CONNECTION_RATE_EXCEEDED = 159,
MQTTREASONCODE_MAXIMUM_CONNECT_TIME = 160,
MQTTREASONCODE_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161,
MQTTREASONCODE_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
};
/**
* Returns a printable string description of an MQTT V5 reason code.
* @param value an MQTT V5 reason code.
* @return the printable string description of the input reason code.
* NULL if the code was not found.
*/
LIBMQTT_API const char* MQTTReasonCode_toString(enum MQTTReasonCodes value);
#endif

@ -0,0 +1,46 @@
/*******************************************************************************
* Copyright (c) 2018 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial API and implementation and/or initial documentation
*******************************************************************************/
#if !defined(SUBOPTS_H)
#define SUBOPTS_H
/** The MQTT V5 subscribe options, apart from QoS which existed before V5. */
typedef struct MQTTSubscribe_options
{
/** The eyecatcher for this structure. Must be MQSO. */
char struct_id[4];
/** The version number of this structure. Must be 0.
*/
int struct_version;
/** To not receive our own publications, set to 1.
* 0 is the original MQTT behaviour - all messages matching the subscription are received.
*/
unsigned char noLocal;
/** To keep the retain flag as on the original publish message, set to 1.
* If 0, defaults to the original MQTT behaviour where the retain flag is only set on
* publications sent by a broker if in response to a subscribe request.
*/
unsigned char retainAsPublished;
/** 0 - send retained messages at the time of the subscribe (original MQTT behaviour)
* 1 - send retained messages on subscribe only if the subscription is new
* 2 - do not send retained messages at all
*/
unsigned char retainHandling;
} MQTTSubscribe_options;
#define MQTTSubscribe_options_initializer { {'M', 'Q', 'S', 'O'}, 0, 0, 0, 0 }
#endif

@ -0,0 +1,92 @@
/*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_AES_H
# define HEADER_AES_H
# include <openssl/opensslconf.h>
# include <stddef.h>
# ifdef __cplusplus
extern "C" {
# endif
# define AES_ENCRYPT 1
# define AES_DECRYPT 0
/*
* Because array size can't be a const in C, the following two are macros.
* Both sizes are in bytes.
*/
# define AES_MAXNR 14
# define AES_BLOCK_SIZE 16
/* This should be a hidden type, but EVP requires that the size be known */
struct aes_key_st {
# ifdef AES_LONG
unsigned long rd_key[4 * (AES_MAXNR + 1)];
# else
unsigned int rd_key[4 * (AES_MAXNR + 1)];
# endif
int rounds;
};
typedef struct aes_key_st AES_KEY;
const char *AES_options(void);
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key);
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key);
void AES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void AES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key, const int enc);
void AES_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc);
void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc);
void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc);
void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc);
void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num);
/* NB: the IV is _two_ blocks long */
void AES_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc);
/* NB: the IV is _four_ blocks long */
void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
const AES_KEY *key2, const unsigned char *ivec,
const int enc);
int AES_wrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen);
int AES_unwrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,886 @@
/*
* Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ASN1_H
# define HEADER_ASN1_H
# include <time.h>
# include <openssl/e_os2.h>
# include <openssl/opensslconf.h>
# include <openssl/bio.h>
# include <openssl/safestack.h>
# include <openssl/asn1err.h>
# include <openssl/symhacks.h>
# include <openssl/ossl_typ.h>
# if OPENSSL_API_COMPAT < 0x10100000L
# include <openssl/bn.h>
# endif
# ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
# endif
#ifdef __cplusplus
extern "C" {
#endif
# define V_ASN1_UNIVERSAL 0x00
# define V_ASN1_APPLICATION 0x40
# define V_ASN1_CONTEXT_SPECIFIC 0x80
# define V_ASN1_PRIVATE 0xc0
# define V_ASN1_CONSTRUCTED 0x20
# define V_ASN1_PRIMITIVE_TAG 0x1f
# define V_ASN1_PRIMATIVE_TAG /*compat*/ V_ASN1_PRIMITIVE_TAG
# define V_ASN1_APP_CHOOSE -2/* let the recipient choose */
# define V_ASN1_OTHER -3/* used in ASN1_TYPE */
# define V_ASN1_ANY -4/* used in ASN1 template code */
# define V_ASN1_UNDEF -1
/* ASN.1 tag values */
# define V_ASN1_EOC 0
# define V_ASN1_BOOLEAN 1 /**/
# define V_ASN1_INTEGER 2
# define V_ASN1_BIT_STRING 3
# define V_ASN1_OCTET_STRING 4
# define V_ASN1_NULL 5
# define V_ASN1_OBJECT 6
# define V_ASN1_OBJECT_DESCRIPTOR 7
# define V_ASN1_EXTERNAL 8
# define V_ASN1_REAL 9
# define V_ASN1_ENUMERATED 10
# define V_ASN1_UTF8STRING 12
# define V_ASN1_SEQUENCE 16
# define V_ASN1_SET 17
# define V_ASN1_NUMERICSTRING 18 /**/
# define V_ASN1_PRINTABLESTRING 19
# define V_ASN1_T61STRING 20
# define V_ASN1_TELETEXSTRING 20/* alias */
# define V_ASN1_VIDEOTEXSTRING 21 /**/
# define V_ASN1_IA5STRING 22
# define V_ASN1_UTCTIME 23
# define V_ASN1_GENERALIZEDTIME 24 /**/
# define V_ASN1_GRAPHICSTRING 25 /**/
# define V_ASN1_ISO64STRING 26 /**/
# define V_ASN1_VISIBLESTRING 26/* alias */
# define V_ASN1_GENERALSTRING 27 /**/
# define V_ASN1_UNIVERSALSTRING 28 /**/
# define V_ASN1_BMPSTRING 30
/*
* NB the constants below are used internally by ASN1_INTEGER
* and ASN1_ENUMERATED to indicate the sign. They are *not* on
* the wire tag values.
*/
# define V_ASN1_NEG 0x100
# define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG)
# define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG)
/* For use with d2i_ASN1_type_bytes() */
# define B_ASN1_NUMERICSTRING 0x0001
# define B_ASN1_PRINTABLESTRING 0x0002
# define B_ASN1_T61STRING 0x0004
# define B_ASN1_TELETEXSTRING 0x0004
# define B_ASN1_VIDEOTEXSTRING 0x0008
# define B_ASN1_IA5STRING 0x0010
# define B_ASN1_GRAPHICSTRING 0x0020
# define B_ASN1_ISO64STRING 0x0040
# define B_ASN1_VISIBLESTRING 0x0040
# define B_ASN1_GENERALSTRING 0x0080
# define B_ASN1_UNIVERSALSTRING 0x0100
# define B_ASN1_OCTET_STRING 0x0200
# define B_ASN1_BIT_STRING 0x0400
# define B_ASN1_BMPSTRING 0x0800
# define B_ASN1_UNKNOWN 0x1000
# define B_ASN1_UTF8STRING 0x2000
# define B_ASN1_UTCTIME 0x4000
# define B_ASN1_GENERALIZEDTIME 0x8000
# define B_ASN1_SEQUENCE 0x10000
/* For use with ASN1_mbstring_copy() */
# define MBSTRING_FLAG 0x1000
# define MBSTRING_UTF8 (MBSTRING_FLAG)
# define MBSTRING_ASC (MBSTRING_FLAG|1)
# define MBSTRING_BMP (MBSTRING_FLAG|2)
# define MBSTRING_UNIV (MBSTRING_FLAG|4)
# define SMIME_OLDMIME 0x400
# define SMIME_CRLFEOL 0x800
# define SMIME_STREAM 0x1000
struct X509_algor_st;
DEFINE_STACK_OF(X509_ALGOR)
# define ASN1_STRING_FLAG_BITS_LEFT 0x08/* Set if 0x07 has bits left value */
/*
* This indicates that the ASN1_STRING is not a real value but just a place
* holder for the location where indefinite length constructed data should be
* inserted in the memory buffer
*/
# define ASN1_STRING_FLAG_NDEF 0x010
/*
* This flag is used by the CMS code to indicate that a string is not
* complete and is a place holder for content when it had all been accessed.
* The flag will be reset when content has been written to it.
*/
# define ASN1_STRING_FLAG_CONT 0x020
/*
* This flag is used by ASN1 code to indicate an ASN1_STRING is an MSTRING
* type.
*/
# define ASN1_STRING_FLAG_MSTRING 0x040
/* String is embedded and only content should be freed */
# define ASN1_STRING_FLAG_EMBED 0x080
/* String should be parsed in RFC 5280's time format */
# define ASN1_STRING_FLAG_X509_TIME 0x100
/* This is the base type that holds just about everything :-) */
struct asn1_string_st {
int length;
int type;
unsigned char *data;
/*
* The value of the following field depends on the type being held. It
* is mostly being used for BIT_STRING so if the input data has a
* non-zero 'unused bits' value, it will be handled correctly
*/
long flags;
};
/*
* ASN1_ENCODING structure: this is used to save the received encoding of an
* ASN1 type. This is useful to get round problems with invalid encodings
* which can break signatures.
*/
typedef struct ASN1_ENCODING_st {
unsigned char *enc; /* DER encoding */
long len; /* Length of encoding */
int modified; /* set to 1 if 'enc' is invalid */
} ASN1_ENCODING;
/* Used with ASN1 LONG type: if a long is set to this it is omitted */
# define ASN1_LONG_UNDEF 0x7fffffffL
# define STABLE_FLAGS_MALLOC 0x01
/*
* A zero passed to ASN1_STRING_TABLE_new_add for the flags is interpreted
* as "don't change" and STABLE_FLAGS_MALLOC is always set. By setting
* STABLE_FLAGS_MALLOC only we can clear the existing value. Use the alias
* STABLE_FLAGS_CLEAR to reflect this.
*/
# define STABLE_FLAGS_CLEAR STABLE_FLAGS_MALLOC
# define STABLE_NO_MASK 0x02
# define DIRSTRING_TYPE \
(B_ASN1_PRINTABLESTRING|B_ASN1_T61STRING|B_ASN1_BMPSTRING|B_ASN1_UTF8STRING)
# define PKCS9STRING_TYPE (DIRSTRING_TYPE|B_ASN1_IA5STRING)
typedef struct asn1_string_table_st {
int nid;
long minsize;
long maxsize;
unsigned long mask;
unsigned long flags;
} ASN1_STRING_TABLE;
DEFINE_STACK_OF(ASN1_STRING_TABLE)
/* size limits: this stuff is taken straight from RFC2459 */
# define ub_name 32768
# define ub_common_name 64
# define ub_locality_name 128
# define ub_state_name 128
# define ub_organization_name 64
# define ub_organization_unit_name 64
# define ub_title 64
# define ub_email_address 128
/*
* Declarations for template structures: for full definitions see asn1t.h
*/
typedef struct ASN1_TEMPLATE_st ASN1_TEMPLATE;
typedef struct ASN1_TLC_st ASN1_TLC;
/* This is just an opaque pointer */
typedef struct ASN1_VALUE_st ASN1_VALUE;
/* Declare ASN1 functions: the implement macro in in asn1t.h */
# define DECLARE_ASN1_FUNCTIONS(type) DECLARE_ASN1_FUNCTIONS_name(type, type)
# define DECLARE_ASN1_ALLOC_FUNCTIONS(type) \
DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, type)
# define DECLARE_ASN1_FUNCTIONS_name(type, name) \
DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
DECLARE_ASN1_ENCODE_FUNCTIONS(type, name, name)
# define DECLARE_ASN1_FUNCTIONS_fname(type, itname, name) \
DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name)
# define DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) \
type *d2i_##name(type **a, const unsigned char **in, long len); \
int i2d_##name(type *a, unsigned char **out); \
DECLARE_ASN1_ITEM(itname)
# define DECLARE_ASN1_ENCODE_FUNCTIONS_const(type, name) \
type *d2i_##name(type **a, const unsigned char **in, long len); \
int i2d_##name(const type *a, unsigned char **out); \
DECLARE_ASN1_ITEM(name)
# define DECLARE_ASN1_NDEF_FUNCTION(name) \
int i2d_##name##_NDEF(name *a, unsigned char **out);
# define DECLARE_ASN1_FUNCTIONS_const(name) \
DECLARE_ASN1_ALLOC_FUNCTIONS(name) \
DECLARE_ASN1_ENCODE_FUNCTIONS_const(name, name)
# define DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
type *name##_new(void); \
void name##_free(type *a);
# define DECLARE_ASN1_PRINT_FUNCTION(stname) \
DECLARE_ASN1_PRINT_FUNCTION_fname(stname, stname)
# define DECLARE_ASN1_PRINT_FUNCTION_fname(stname, fname) \
int fname##_print_ctx(BIO *out, stname *x, int indent, \
const ASN1_PCTX *pctx);
# define D2I_OF(type) type *(*)(type **,const unsigned char **,long)
# define I2D_OF(type) int (*)(type *,unsigned char **)
# define I2D_OF_const(type) int (*)(const type *,unsigned char **)
# define CHECKED_D2I_OF(type, d2i) \
((d2i_of_void*) (1 ? d2i : ((D2I_OF(type))0)))
# define CHECKED_I2D_OF(type, i2d) \
((i2d_of_void*) (1 ? i2d : ((I2D_OF(type))0)))
# define CHECKED_NEW_OF(type, xnew) \
((void *(*)(void)) (1 ? xnew : ((type *(*)(void))0)))
# define CHECKED_PTR_OF(type, p) \
((void*) (1 ? p : (type*)0))
# define CHECKED_PPTR_OF(type, p) \
((void**) (1 ? p : (type**)0))
# define TYPEDEF_D2I_OF(type) typedef type *d2i_of_##type(type **,const unsigned char **,long)
# define TYPEDEF_I2D_OF(type) typedef int i2d_of_##type(type *,unsigned char **)
# define TYPEDEF_D2I2D_OF(type) TYPEDEF_D2I_OF(type); TYPEDEF_I2D_OF(type)
TYPEDEF_D2I2D_OF(void);
/*-
* The following macros and typedefs allow an ASN1_ITEM
* to be embedded in a structure and referenced. Since
* the ASN1_ITEM pointers need to be globally accessible
* (possibly from shared libraries) they may exist in
* different forms. On platforms that support it the
* ASN1_ITEM structure itself will be globally exported.
* Other platforms will export a function that returns
* an ASN1_ITEM pointer.
*
* To handle both cases transparently the macros below
* should be used instead of hard coding an ASN1_ITEM
* pointer in a structure.
*
* The structure will look like this:
*
* typedef struct SOMETHING_st {
* ...
* ASN1_ITEM_EXP *iptr;
* ...
* } SOMETHING;
*
* It would be initialised as e.g.:
*
* SOMETHING somevar = {...,ASN1_ITEM_ref(X509),...};
*
* and the actual pointer extracted with:
*
* const ASN1_ITEM *it = ASN1_ITEM_ptr(somevar.iptr);
*
* Finally an ASN1_ITEM pointer can be extracted from an
* appropriate reference with: ASN1_ITEM_rptr(X509). This
* would be used when a function takes an ASN1_ITEM * argument.
*
*/
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
/* ASN1_ITEM pointer exported type */
typedef const ASN1_ITEM ASN1_ITEM_EXP;
/* Macro to obtain ASN1_ITEM pointer from exported type */
# define ASN1_ITEM_ptr(iptr) (iptr)
/* Macro to include ASN1_ITEM pointer from base type */
# define ASN1_ITEM_ref(iptr) (&(iptr##_it))
# define ASN1_ITEM_rptr(ref) (&(ref##_it))
# define DECLARE_ASN1_ITEM(name) \
OPENSSL_EXTERN const ASN1_ITEM name##_it;
# else
/*
* Platforms that can't easily handle shared global variables are declared as
* functions returning ASN1_ITEM pointers.
*/
/* ASN1_ITEM pointer exported type */
typedef const ASN1_ITEM *ASN1_ITEM_EXP (void);
/* Macro to obtain ASN1_ITEM pointer from exported type */
# define ASN1_ITEM_ptr(iptr) (iptr())
/* Macro to include ASN1_ITEM pointer from base type */
# define ASN1_ITEM_ref(iptr) (iptr##_it)
# define ASN1_ITEM_rptr(ref) (ref##_it())
# define DECLARE_ASN1_ITEM(name) \
const ASN1_ITEM * name##_it(void);
# endif
/* Parameters used by ASN1_STRING_print_ex() */
/*
* These determine which characters to escape: RFC2253 special characters,
* control characters and MSB set characters
*/
# define ASN1_STRFLGS_ESC_2253 1
# define ASN1_STRFLGS_ESC_CTRL 2
# define ASN1_STRFLGS_ESC_MSB 4
/*
* This flag determines how we do escaping: normally RC2253 backslash only,
* set this to use backslash and quote.
*/
# define ASN1_STRFLGS_ESC_QUOTE 8
/* These three flags are internal use only. */
/* Character is a valid PrintableString character */
# define CHARTYPE_PRINTABLESTRING 0x10
/* Character needs escaping if it is the first character */
# define CHARTYPE_FIRST_ESC_2253 0x20
/* Character needs escaping if it is the last character */
# define CHARTYPE_LAST_ESC_2253 0x40
/*
* NB the internal flags are safely reused below by flags handled at the top
* level.
*/
/*
* If this is set we convert all character strings to UTF8 first
*/
# define ASN1_STRFLGS_UTF8_CONVERT 0x10
/*
* If this is set we don't attempt to interpret content: just assume all
* strings are 1 byte per character. This will produce some pretty odd
* looking output!
*/
# define ASN1_STRFLGS_IGNORE_TYPE 0x20
/* If this is set we include the string type in the output */
# define ASN1_STRFLGS_SHOW_TYPE 0x40
/*
* This determines which strings to display and which to 'dump' (hex dump of
* content octets or DER encoding). We can only dump non character strings or
* everything. If we don't dump 'unknown' they are interpreted as character
* strings with 1 octet per character and are subject to the usual escaping
* options.
*/
# define ASN1_STRFLGS_DUMP_ALL 0x80
# define ASN1_STRFLGS_DUMP_UNKNOWN 0x100
/*
* These determine what 'dumping' does, we can dump the content octets or the
* DER encoding: both use the RFC2253 #XXXXX notation.
*/
# define ASN1_STRFLGS_DUMP_DER 0x200
/*
* This flag specifies that RC2254 escaping shall be performed.
*/
#define ASN1_STRFLGS_ESC_2254 0x400
/*
* All the string flags consistent with RFC2253, escaping control characters
* isn't essential in RFC2253 but it is advisable anyway.
*/
# define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \
ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB | \
ASN1_STRFLGS_UTF8_CONVERT | \
ASN1_STRFLGS_DUMP_UNKNOWN | \
ASN1_STRFLGS_DUMP_DER)
DEFINE_STACK_OF(ASN1_INTEGER)
DEFINE_STACK_OF(ASN1_GENERALSTRING)
DEFINE_STACK_OF(ASN1_UTF8STRING)
typedef struct asn1_type_st {
int type;
union {
char *ptr;
ASN1_BOOLEAN boolean;
ASN1_STRING *asn1_string;
ASN1_OBJECT *object;
ASN1_INTEGER *integer;
ASN1_ENUMERATED *enumerated;
ASN1_BIT_STRING *bit_string;
ASN1_OCTET_STRING *octet_string;
ASN1_PRINTABLESTRING *printablestring;
ASN1_T61STRING *t61string;
ASN1_IA5STRING *ia5string;
ASN1_GENERALSTRING *generalstring;
ASN1_BMPSTRING *bmpstring;
ASN1_UNIVERSALSTRING *universalstring;
ASN1_UTCTIME *utctime;
ASN1_GENERALIZEDTIME *generalizedtime;
ASN1_VISIBLESTRING *visiblestring;
ASN1_UTF8STRING *utf8string;
/*
* set and sequence are left complete and still contain the set or
* sequence bytes
*/
ASN1_STRING *set;
ASN1_STRING *sequence;
ASN1_VALUE *asn1_value;
} value;
} ASN1_TYPE;
DEFINE_STACK_OF(ASN1_TYPE)
typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY;
DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY)
DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SET_ANY)
/* This is used to contain a list of bit names */
typedef struct BIT_STRING_BITNAME_st {
int bitnum;
const char *lname;
const char *sname;
} BIT_STRING_BITNAME;
# define B_ASN1_TIME \
B_ASN1_UTCTIME | \
B_ASN1_GENERALIZEDTIME
# define B_ASN1_PRINTABLE \
B_ASN1_NUMERICSTRING| \
B_ASN1_PRINTABLESTRING| \
B_ASN1_T61STRING| \
B_ASN1_IA5STRING| \
B_ASN1_BIT_STRING| \
B_ASN1_UNIVERSALSTRING|\
B_ASN1_BMPSTRING|\
B_ASN1_UTF8STRING|\
B_ASN1_SEQUENCE|\
B_ASN1_UNKNOWN
# define B_ASN1_DIRECTORYSTRING \
B_ASN1_PRINTABLESTRING| \
B_ASN1_TELETEXSTRING|\
B_ASN1_BMPSTRING|\
B_ASN1_UNIVERSALSTRING|\
B_ASN1_UTF8STRING
# define B_ASN1_DISPLAYTEXT \
B_ASN1_IA5STRING| \
B_ASN1_VISIBLESTRING| \
B_ASN1_BMPSTRING|\
B_ASN1_UTF8STRING
DECLARE_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
int ASN1_TYPE_get(const ASN1_TYPE *a);
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value);
int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value);
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b);
ASN1_TYPE *ASN1_TYPE_pack_sequence(const ASN1_ITEM *it, void *s, ASN1_TYPE **t);
void *ASN1_TYPE_unpack_sequence(const ASN1_ITEM *it, const ASN1_TYPE *t);
ASN1_OBJECT *ASN1_OBJECT_new(void);
void ASN1_OBJECT_free(ASN1_OBJECT *a);
int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp);
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length);
DECLARE_ASN1_ITEM(ASN1_OBJECT)
DEFINE_STACK_OF(ASN1_OBJECT)
ASN1_STRING *ASN1_STRING_new(void);
void ASN1_STRING_free(ASN1_STRING *a);
void ASN1_STRING_clear_free(ASN1_STRING *a);
int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str);
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *a);
ASN1_STRING *ASN1_STRING_type_new(int type);
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b);
/*
* Since this is used to store all sorts of things, via macros, for now,
* make its data void *
*/
int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len);
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len);
int ASN1_STRING_length(const ASN1_STRING *x);
void ASN1_STRING_length_set(ASN1_STRING *x, int n);
int ASN1_STRING_type(const ASN1_STRING *x);
DEPRECATEDIN_1_1_0(unsigned char *ASN1_STRING_data(ASN1_STRING *x))
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x);
DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING)
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length);
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value);
int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n);
int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
const unsigned char *flags, int flags_len);
int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs,
BIT_STRING_BITNAME *tbl, int indent);
int ASN1_BIT_STRING_num_asc(const char *name, BIT_STRING_BITNAME *tbl);
int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, const char *name, int value,
BIT_STRING_BITNAME *tbl);
DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER)
ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long length);
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x);
int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y);
DECLARE_ASN1_FUNCTIONS(ASN1_ENUMERATED)
int ASN1_UTCTIME_check(const ASN1_UTCTIME *a);
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t);
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
int offset_day, long offset_sec);
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str);
int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t);
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *a);
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
time_t t);
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
time_t t, int offset_day,
long offset_sec);
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str);
int ASN1_TIME_diff(int *pday, int *psec,
const ASN1_TIME *from, const ASN1_TIME *to);
DECLARE_ASN1_FUNCTIONS(ASN1_OCTET_STRING)
ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *a);
int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a,
const ASN1_OCTET_STRING *b);
int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, const unsigned char *data,
int len);
DECLARE_ASN1_FUNCTIONS(ASN1_VISIBLESTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_UNIVERSALSTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_UTF8STRING)
DECLARE_ASN1_FUNCTIONS(ASN1_NULL)
DECLARE_ASN1_FUNCTIONS(ASN1_BMPSTRING)
int UTF8_getc(const unsigned char *str, int len, unsigned long *val);
int UTF8_putc(unsigned char *str, int len, unsigned long value);
DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE)
DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING)
DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT)
DECLARE_ASN1_FUNCTIONS(ASN1_PRINTABLESTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_T61STRING)
DECLARE_ASN1_FUNCTIONS(ASN1_IA5STRING)
DECLARE_ASN1_FUNCTIONS(ASN1_GENERALSTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_UTCTIME)
DECLARE_ASN1_FUNCTIONS(ASN1_GENERALIZEDTIME)
DECLARE_ASN1_FUNCTIONS(ASN1_TIME)
DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF)
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t);
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
int offset_day, long offset_sec);
int ASN1_TIME_check(const ASN1_TIME *t);
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out);
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str);
int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str);
int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm);
int ASN1_TIME_normalize(ASN1_TIME *s);
int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t);
int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b);
int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a);
int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size);
int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a);
int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size);
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a);
int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size);
int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type);
int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a);
int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num);
ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
const char *sn, const char *ln);
int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a);
int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r);
int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a);
int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r);
int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
long ASN1_INTEGER_get(const ASN1_INTEGER *a);
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai);
BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn);
int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a);
int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r);
int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v);
long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a);
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai);
BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn);
/* General */
/* given a string, return the correct type, max is the maximum length */
int ASN1_PRINTABLE_type(const unsigned char *s, int max);
unsigned long ASN1_tag2bit(int tag);
/* SPECIALS */
int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
int *pclass, long omax);
int ASN1_check_infinite_end(unsigned char **p, long len);
int ASN1_const_check_infinite_end(const unsigned char **p, long len);
void ASN1_put_object(unsigned char **pp, int constructed, int length,
int tag, int xclass);
int ASN1_put_eoc(unsigned char **pp);
int ASN1_object_size(int constructed, int length, int tag);
/* Used to implement other functions */
void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, void *x);
# define ASN1_dup_of(type,i2d,d2i,x) \
((type*)ASN1_dup(CHECKED_I2D_OF(type, i2d), \
CHECKED_D2I_OF(type, d2i), \
CHECKED_PTR_OF(type, x)))
# define ASN1_dup_of_const(type,i2d,d2i,x) \
((type*)ASN1_dup(CHECKED_I2D_OF(const type, i2d), \
CHECKED_D2I_OF(type, d2i), \
CHECKED_PTR_OF(const type, x)))
void *ASN1_item_dup(const ASN1_ITEM *it, void *x);
/* ASN1 alloc/free macros for when a type is only used internally */
# define M_ASN1_new_of(type) (type *)ASN1_item_new(ASN1_ITEM_rptr(type))
# define M_ASN1_free_of(x, type) \
ASN1_item_free(CHECKED_PTR_OF(type, x), ASN1_ITEM_rptr(type))
# ifndef OPENSSL_NO_STDIO
void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x);
# define ASN1_d2i_fp_of(type,xnew,d2i,in,x) \
((type*)ASN1_d2i_fp(CHECKED_NEW_OF(type, xnew), \
CHECKED_D2I_OF(type, d2i), \
in, \
CHECKED_PPTR_OF(type, x)))
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x);
int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, void *x);
# define ASN1_i2d_fp_of(type,i2d,out,x) \
(ASN1_i2d_fp(CHECKED_I2D_OF(type, i2d), \
out, \
CHECKED_PTR_OF(type, x)))
# define ASN1_i2d_fp_of_const(type,i2d,out,x) \
(ASN1_i2d_fp(CHECKED_I2D_OF(const type, i2d), \
out, \
CHECKED_PTR_OF(const type, x)))
int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x);
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags);
# endif
int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in);
void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x);
# define ASN1_d2i_bio_of(type,xnew,d2i,in,x) \
((type*)ASN1_d2i_bio( CHECKED_NEW_OF(type, xnew), \
CHECKED_D2I_OF(type, d2i), \
in, \
CHECKED_PPTR_OF(type, x)))
void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x);
int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, unsigned char *x);
# define ASN1_i2d_bio_of(type,i2d,out,x) \
(ASN1_i2d_bio(CHECKED_I2D_OF(type, i2d), \
out, \
CHECKED_PTR_OF(type, x)))
# define ASN1_i2d_bio_of_const(type,i2d,out,x) \
(ASN1_i2d_bio(CHECKED_I2D_OF(const type, i2d), \
out, \
CHECKED_PTR_OF(const type, x)))
int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x);
int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a);
int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a);
int ASN1_TIME_print(BIO *fp, const ASN1_TIME *a);
int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v);
int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags);
int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int off);
int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num,
unsigned char *buf, int off);
int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent);
int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
int dump);
const char *ASN1_tag2str(int tag);
/* Used to load and write Netscape format cert */
int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s);
int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len);
int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len);
int ASN1_TYPE_set_int_octetstring(ASN1_TYPE *a, long num,
unsigned char *data, int len);
int ASN1_TYPE_get_int_octetstring(const ASN1_TYPE *a, long *num,
unsigned char *data, int max_len);
void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it);
ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it,
ASN1_OCTET_STRING **oct);
void ASN1_STRING_set_default_mask(unsigned long mask);
int ASN1_STRING_set_default_mask_asc(const char *p);
unsigned long ASN1_STRING_get_default_mask(void);
int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask);
int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask,
long minsize, long maxsize);
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
const unsigned char *in, int inlen,
int inform, int nid);
ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid);
int ASN1_STRING_TABLE_add(int, long, long, unsigned long, unsigned long);
void ASN1_STRING_TABLE_cleanup(void);
/* ASN1 template functions */
/* Old API compatible functions */
ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it);
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it);
ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **val, const unsigned char **in,
long len, const ASN1_ITEM *it);
int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it);
int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out,
const ASN1_ITEM *it);
void ASN1_add_oid_module(void);
void ASN1_add_stable_module(void);
ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf);
ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf);
int ASN1_str2mask(const char *str, unsigned long *pmask);
/* ASN1 Print flags */
/* Indicate missing OPTIONAL fields */
# define ASN1_PCTX_FLAGS_SHOW_ABSENT 0x001
/* Mark start and end of SEQUENCE */
# define ASN1_PCTX_FLAGS_SHOW_SEQUENCE 0x002
/* Mark start and end of SEQUENCE/SET OF */
# define ASN1_PCTX_FLAGS_SHOW_SSOF 0x004
/* Show the ASN1 type of primitives */
# define ASN1_PCTX_FLAGS_SHOW_TYPE 0x008
/* Don't show ASN1 type of ANY */
# define ASN1_PCTX_FLAGS_NO_ANY_TYPE 0x010
/* Don't show ASN1 type of MSTRINGs */
# define ASN1_PCTX_FLAGS_NO_MSTRING_TYPE 0x020
/* Don't show field names in SEQUENCE */
# define ASN1_PCTX_FLAGS_NO_FIELD_NAME 0x040
/* Show structure names of each SEQUENCE field */
# define ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME 0x080
/* Don't show structure name even at top level */
# define ASN1_PCTX_FLAGS_NO_STRUCT_NAME 0x100
int ASN1_item_print(BIO *out, ASN1_VALUE *ifld, int indent,
const ASN1_ITEM *it, const ASN1_PCTX *pctx);
ASN1_PCTX *ASN1_PCTX_new(void);
void ASN1_PCTX_free(ASN1_PCTX *p);
unsigned long ASN1_PCTX_get_flags(const ASN1_PCTX *p);
void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_nm_flags(const ASN1_PCTX *p);
void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_cert_flags(const ASN1_PCTX *p);
void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_oid_flags(const ASN1_PCTX *p);
void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_str_flags(const ASN1_PCTX *p);
void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags);
ASN1_SCTX *ASN1_SCTX_new(int (*scan_cb) (ASN1_SCTX *ctx));
void ASN1_SCTX_free(ASN1_SCTX *p);
const ASN1_ITEM *ASN1_SCTX_get_item(ASN1_SCTX *p);
const ASN1_TEMPLATE *ASN1_SCTX_get_template(ASN1_SCTX *p);
unsigned long ASN1_SCTX_get_flags(ASN1_SCTX *p);
void ASN1_SCTX_set_app_data(ASN1_SCTX *p, void *data);
void *ASN1_SCTX_get_app_data(ASN1_SCTX *p);
const BIO_METHOD *BIO_f_asn1(void);
BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it);
int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const ASN1_ITEM *it);
int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const char *hdr, const ASN1_ITEM *it);
int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
int ctype_nid, int econt_nid,
STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it);
ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it);
int SMIME_crlf_copy(BIO *in, BIO *out, int flags);
int SMIME_text(BIO *in, BIO *out);
const ASN1_ITEM *ASN1_ITEM_lookup(const char *name);
const ASN1_ITEM *ASN1_ITEM_get(size_t i);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,10 @@
/*
* Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#error "This file is obsolete; please update your software."

@ -0,0 +1,256 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ASN1ERR_H
# define HEADER_ASN1ERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_ASN1_strings(void);
/*
* ASN1 function codes.
*/
# define ASN1_F_A2D_ASN1_OBJECT 100
# define ASN1_F_A2I_ASN1_INTEGER 102
# define ASN1_F_A2I_ASN1_STRING 103
# define ASN1_F_APPEND_EXP 176
# define ASN1_F_ASN1_BIO_INIT 113
# define ASN1_F_ASN1_BIT_STRING_SET_BIT 183
# define ASN1_F_ASN1_CB 177
# define ASN1_F_ASN1_CHECK_TLEN 104
# define ASN1_F_ASN1_COLLECT 106
# define ASN1_F_ASN1_D2I_EX_PRIMITIVE 108
# define ASN1_F_ASN1_D2I_FP 109
# define ASN1_F_ASN1_D2I_READ_BIO 107
# define ASN1_F_ASN1_DIGEST 184
# define ASN1_F_ASN1_DO_ADB 110
# define ASN1_F_ASN1_DO_LOCK 233
# define ASN1_F_ASN1_DUP 111
# define ASN1_F_ASN1_ENC_SAVE 115
# define ASN1_F_ASN1_EX_C2I 204
# define ASN1_F_ASN1_FIND_END 190
# define ASN1_F_ASN1_GENERALIZEDTIME_ADJ 216
# define ASN1_F_ASN1_GENERATE_V3 178
# define ASN1_F_ASN1_GET_INT64 224
# define ASN1_F_ASN1_GET_OBJECT 114
# define ASN1_F_ASN1_GET_UINT64 225
# define ASN1_F_ASN1_I2D_BIO 116
# define ASN1_F_ASN1_I2D_FP 117
# define ASN1_F_ASN1_ITEM_D2I_FP 206
# define ASN1_F_ASN1_ITEM_DUP 191
# define ASN1_F_ASN1_ITEM_EMBED_D2I 120
# define ASN1_F_ASN1_ITEM_EMBED_NEW 121
# define ASN1_F_ASN1_ITEM_FLAGS_I2D 118
# define ASN1_F_ASN1_ITEM_I2D_BIO 192
# define ASN1_F_ASN1_ITEM_I2D_FP 193
# define ASN1_F_ASN1_ITEM_PACK 198
# define ASN1_F_ASN1_ITEM_SIGN 195
# define ASN1_F_ASN1_ITEM_SIGN_CTX 220
# define ASN1_F_ASN1_ITEM_UNPACK 199
# define ASN1_F_ASN1_ITEM_VERIFY 197
# define ASN1_F_ASN1_MBSTRING_NCOPY 122
# define ASN1_F_ASN1_OBJECT_NEW 123
# define ASN1_F_ASN1_OUTPUT_DATA 214
# define ASN1_F_ASN1_PCTX_NEW 205
# define ASN1_F_ASN1_PRIMITIVE_NEW 119
# define ASN1_F_ASN1_SCTX_NEW 221
# define ASN1_F_ASN1_SIGN 128
# define ASN1_F_ASN1_STR2TYPE 179
# define ASN1_F_ASN1_STRING_GET_INT64 227
# define ASN1_F_ASN1_STRING_GET_UINT64 230
# define ASN1_F_ASN1_STRING_SET 186
# define ASN1_F_ASN1_STRING_TABLE_ADD 129
# define ASN1_F_ASN1_STRING_TO_BN 228
# define ASN1_F_ASN1_STRING_TYPE_NEW 130
# define ASN1_F_ASN1_TEMPLATE_EX_D2I 132
# define ASN1_F_ASN1_TEMPLATE_NEW 133
# define ASN1_F_ASN1_TEMPLATE_NOEXP_D2I 131
# define ASN1_F_ASN1_TIME_ADJ 217
# define ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING 134
# define ASN1_F_ASN1_TYPE_GET_OCTETSTRING 135
# define ASN1_F_ASN1_UTCTIME_ADJ 218
# define ASN1_F_ASN1_VERIFY 137
# define ASN1_F_B64_READ_ASN1 209
# define ASN1_F_B64_WRITE_ASN1 210
# define ASN1_F_BIO_NEW_NDEF 208
# define ASN1_F_BITSTR_CB 180
# define ASN1_F_BN_TO_ASN1_STRING 229
# define ASN1_F_C2I_ASN1_BIT_STRING 189
# define ASN1_F_C2I_ASN1_INTEGER 194
# define ASN1_F_C2I_ASN1_OBJECT 196
# define ASN1_F_C2I_IBUF 226
# define ASN1_F_C2I_UINT64_INT 101
# define ASN1_F_COLLECT_DATA 140
# define ASN1_F_D2I_ASN1_OBJECT 147
# define ASN1_F_D2I_ASN1_UINTEGER 150
# define ASN1_F_D2I_AUTOPRIVATEKEY 207
# define ASN1_F_D2I_PRIVATEKEY 154
# define ASN1_F_D2I_PUBLICKEY 155
# define ASN1_F_DO_BUF 142
# define ASN1_F_DO_CREATE 124
# define ASN1_F_DO_DUMP 125
# define ASN1_F_DO_TCREATE 222
# define ASN1_F_I2A_ASN1_OBJECT 126
# define ASN1_F_I2D_ASN1_BIO_STREAM 211
# define ASN1_F_I2D_ASN1_OBJECT 143
# define ASN1_F_I2D_DSA_PUBKEY 161
# define ASN1_F_I2D_EC_PUBKEY 181
# define ASN1_F_I2D_PRIVATEKEY 163
# define ASN1_F_I2D_PUBLICKEY 164
# define ASN1_F_I2D_RSA_PUBKEY 165
# define ASN1_F_LONG_C2I 166
# define ASN1_F_NDEF_PREFIX 127
# define ASN1_F_NDEF_SUFFIX 136
# define ASN1_F_OID_MODULE_INIT 174
# define ASN1_F_PARSE_TAGGING 182
# define ASN1_F_PKCS5_PBE2_SET_IV 167
# define ASN1_F_PKCS5_PBE2_SET_SCRYPT 231
# define ASN1_F_PKCS5_PBE_SET 202
# define ASN1_F_PKCS5_PBE_SET0_ALGOR 215
# define ASN1_F_PKCS5_PBKDF2_SET 219
# define ASN1_F_PKCS5_SCRYPT_SET 232
# define ASN1_F_SMIME_READ_ASN1 212
# define ASN1_F_SMIME_TEXT 213
# define ASN1_F_STABLE_GET 138
# define ASN1_F_STBL_MODULE_INIT 223
# define ASN1_F_UINT32_C2I 105
# define ASN1_F_UINT32_NEW 139
# define ASN1_F_UINT64_C2I 112
# define ASN1_F_UINT64_NEW 141
# define ASN1_F_X509_CRL_ADD0_REVOKED 169
# define ASN1_F_X509_INFO_NEW 170
# define ASN1_F_X509_NAME_ENCODE 203
# define ASN1_F_X509_NAME_EX_D2I 158
# define ASN1_F_X509_NAME_EX_NEW 171
# define ASN1_F_X509_PKEY_NEW 173
/*
* ASN1 reason codes.
*/
# define ASN1_R_ADDING_OBJECT 171
# define ASN1_R_ASN1_PARSE_ERROR 203
# define ASN1_R_ASN1_SIG_PARSE_ERROR 204
# define ASN1_R_AUX_ERROR 100
# define ASN1_R_BAD_OBJECT_HEADER 102
# define ASN1_R_BMPSTRING_IS_WRONG_LENGTH 214
# define ASN1_R_BN_LIB 105
# define ASN1_R_BOOLEAN_IS_WRONG_LENGTH 106
# define ASN1_R_BUFFER_TOO_SMALL 107
# define ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 108
# define ASN1_R_CONTEXT_NOT_INITIALISED 217
# define ASN1_R_DATA_IS_WRONG 109
# define ASN1_R_DECODE_ERROR 110
# define ASN1_R_DEPTH_EXCEEDED 174
# define ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED 198
# define ASN1_R_ENCODE_ERROR 112
# define ASN1_R_ERROR_GETTING_TIME 173
# define ASN1_R_ERROR_LOADING_SECTION 172
# define ASN1_R_ERROR_SETTING_CIPHER_PARAMS 114
# define ASN1_R_EXPECTING_AN_INTEGER 115
# define ASN1_R_EXPECTING_AN_OBJECT 116
# define ASN1_R_EXPLICIT_LENGTH_MISMATCH 119
# define ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED 120
# define ASN1_R_FIELD_MISSING 121
# define ASN1_R_FIRST_NUM_TOO_LARGE 122
# define ASN1_R_HEADER_TOO_LONG 123
# define ASN1_R_ILLEGAL_BITSTRING_FORMAT 175
# define ASN1_R_ILLEGAL_BOOLEAN 176
# define ASN1_R_ILLEGAL_CHARACTERS 124
# define ASN1_R_ILLEGAL_FORMAT 177
# define ASN1_R_ILLEGAL_HEX 178
# define ASN1_R_ILLEGAL_IMPLICIT_TAG 179
# define ASN1_R_ILLEGAL_INTEGER 180
# define ASN1_R_ILLEGAL_NEGATIVE_VALUE 226
# define ASN1_R_ILLEGAL_NESTED_TAGGING 181
# define ASN1_R_ILLEGAL_NULL 125
# define ASN1_R_ILLEGAL_NULL_VALUE 182
# define ASN1_R_ILLEGAL_OBJECT 183
# define ASN1_R_ILLEGAL_OPTIONAL_ANY 126
# define ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE 170
# define ASN1_R_ILLEGAL_PADDING 221
# define ASN1_R_ILLEGAL_TAGGED_ANY 127
# define ASN1_R_ILLEGAL_TIME_VALUE 184
# define ASN1_R_ILLEGAL_ZERO_CONTENT 222
# define ASN1_R_INTEGER_NOT_ASCII_FORMAT 185
# define ASN1_R_INTEGER_TOO_LARGE_FOR_LONG 128
# define ASN1_R_INVALID_BIT_STRING_BITS_LEFT 220
# define ASN1_R_INVALID_BMPSTRING_LENGTH 129
# define ASN1_R_INVALID_DIGIT 130
# define ASN1_R_INVALID_MIME_TYPE 205
# define ASN1_R_INVALID_MODIFIER 186
# define ASN1_R_INVALID_NUMBER 187
# define ASN1_R_INVALID_OBJECT_ENCODING 216
# define ASN1_R_INVALID_SCRYPT_PARAMETERS 227
# define ASN1_R_INVALID_SEPARATOR 131
# define ASN1_R_INVALID_STRING_TABLE_VALUE 218
# define ASN1_R_INVALID_UNIVERSALSTRING_LENGTH 133
# define ASN1_R_INVALID_UTF8STRING 134
# define ASN1_R_INVALID_VALUE 219
# define ASN1_R_LIST_ERROR 188
# define ASN1_R_MIME_NO_CONTENT_TYPE 206
# define ASN1_R_MIME_PARSE_ERROR 207
# define ASN1_R_MIME_SIG_PARSE_ERROR 208
# define ASN1_R_MISSING_EOC 137
# define ASN1_R_MISSING_SECOND_NUMBER 138
# define ASN1_R_MISSING_VALUE 189
# define ASN1_R_MSTRING_NOT_UNIVERSAL 139
# define ASN1_R_MSTRING_WRONG_TAG 140
# define ASN1_R_NESTED_ASN1_STRING 197
# define ASN1_R_NESTED_TOO_DEEP 201
# define ASN1_R_NON_HEX_CHARACTERS 141
# define ASN1_R_NOT_ASCII_FORMAT 190
# define ASN1_R_NOT_ENOUGH_DATA 142
# define ASN1_R_NO_CONTENT_TYPE 209
# define ASN1_R_NO_MATCHING_CHOICE_TYPE 143
# define ASN1_R_NO_MULTIPART_BODY_FAILURE 210
# define ASN1_R_NO_MULTIPART_BOUNDARY 211
# define ASN1_R_NO_SIG_CONTENT_TYPE 212
# define ASN1_R_NULL_IS_WRONG_LENGTH 144
# define ASN1_R_OBJECT_NOT_ASCII_FORMAT 191
# define ASN1_R_ODD_NUMBER_OF_CHARS 145
# define ASN1_R_SECOND_NUMBER_TOO_LARGE 147
# define ASN1_R_SEQUENCE_LENGTH_MISMATCH 148
# define ASN1_R_SEQUENCE_NOT_CONSTRUCTED 149
# define ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG 192
# define ASN1_R_SHORT_LINE 150
# define ASN1_R_SIG_INVALID_MIME_TYPE 213
# define ASN1_R_STREAMING_NOT_SUPPORTED 202
# define ASN1_R_STRING_TOO_LONG 151
# define ASN1_R_STRING_TOO_SHORT 152
# define ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 154
# define ASN1_R_TIME_NOT_ASCII_FORMAT 193
# define ASN1_R_TOO_LARGE 223
# define ASN1_R_TOO_LONG 155
# define ASN1_R_TOO_SMALL 224
# define ASN1_R_TYPE_NOT_CONSTRUCTED 156
# define ASN1_R_TYPE_NOT_PRIMITIVE 195
# define ASN1_R_UNEXPECTED_EOC 159
# define ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH 215
# define ASN1_R_UNKNOWN_FORMAT 160
# define ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM 161
# define ASN1_R_UNKNOWN_OBJECT_TYPE 162
# define ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE 163
# define ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM 199
# define ASN1_R_UNKNOWN_TAG 194
# define ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE 164
# define ASN1_R_UNSUPPORTED_CIPHER 228
# define ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE 167
# define ASN1_R_UNSUPPORTED_TYPE 196
# define ASN1_R_WRONG_INTEGER_TYPE 225
# define ASN1_R_WRONG_PUBLIC_KEY_TYPE 200
# define ASN1_R_WRONG_TAG 168
#endif

@ -0,0 +1,945 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ASN1T_H
# define HEADER_ASN1T_H
# include <stddef.h>
# include <openssl/e_os2.h>
# include <openssl/asn1.h>
# ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
# endif
/* ASN1 template defines, structures and functions */
#ifdef __cplusplus
extern "C" {
#endif
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */
# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)(iptr))
/* Macros for start and end of ASN1_ITEM definition */
# define ASN1_ITEM_start(itname) \
const ASN1_ITEM itname##_it = {
# define static_ASN1_ITEM_start(itname) \
static const ASN1_ITEM itname##_it = {
# define ASN1_ITEM_end(itname) \
};
# else
/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */
# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)((iptr)()))
/* Macros for start and end of ASN1_ITEM definition */
# define ASN1_ITEM_start(itname) \
const ASN1_ITEM * itname##_it(void) \
{ \
static const ASN1_ITEM local_it = {
# define static_ASN1_ITEM_start(itname) \
static ASN1_ITEM_start(itname)
# define ASN1_ITEM_end(itname) \
}; \
return &local_it; \
}
# endif
/* Macros to aid ASN1 template writing */
# define ASN1_ITEM_TEMPLATE(tname) \
static const ASN1_TEMPLATE tname##_item_tt
# define ASN1_ITEM_TEMPLATE_END(tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_PRIMITIVE,\
-1,\
&tname##_item_tt,\
0,\
NULL,\
0,\
#tname \
ASN1_ITEM_end(tname)
# define static_ASN1_ITEM_TEMPLATE_END(tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_PRIMITIVE,\
-1,\
&tname##_item_tt,\
0,\
NULL,\
0,\
#tname \
ASN1_ITEM_end(tname)
/* This is a ASN1 type which just embeds a template */
/*-
* This pair helps declare a SEQUENCE. We can do:
*
* ASN1_SEQUENCE(stname) = {
* ... SEQUENCE components ...
* } ASN1_SEQUENCE_END(stname)
*
* This will produce an ASN1_ITEM called stname_it
* for a structure called stname.
*
* If you want the same structure but a different
* name then use:
*
* ASN1_SEQUENCE(itname) = {
* ... SEQUENCE components ...
* } ASN1_SEQUENCE_END_name(stname, itname)
*
* This will create an item called itname_it using
* a structure called stname.
*/
# define ASN1_SEQUENCE(tname) \
static const ASN1_TEMPLATE tname##_seq_tt[]
# define ASN1_SEQUENCE_END(stname) ASN1_SEQUENCE_END_name(stname, stname)
# define static_ASN1_SEQUENCE_END(stname) static_ASN1_SEQUENCE_END_name(stname, stname)
# define ASN1_SEQUENCE_END_name(stname, tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#tname \
ASN1_ITEM_end(tname)
# define static_ASN1_SEQUENCE_END_name(stname, tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define ASN1_NDEF_SEQUENCE(tname) \
ASN1_SEQUENCE(tname)
# define ASN1_NDEF_SEQUENCE_cb(tname, cb) \
ASN1_SEQUENCE_cb(tname, cb)
# define ASN1_SEQUENCE_cb(tname, cb) \
static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0}; \
ASN1_SEQUENCE(tname)
# define ASN1_BROKEN_SEQUENCE(tname) \
static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_BROKEN, 0, 0, 0, 0}; \
ASN1_SEQUENCE(tname)
# define ASN1_SEQUENCE_ref(tname, cb) \
static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_REFCOUNT, offsetof(tname, references), offsetof(tname, lock), cb, 0}; \
ASN1_SEQUENCE(tname)
# define ASN1_SEQUENCE_enc(tname, enc, cb) \
static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_ENCODING, 0, 0, cb, offsetof(tname, enc)}; \
ASN1_SEQUENCE(tname)
# define ASN1_NDEF_SEQUENCE_END(tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_NDEF_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(tname),\
#tname \
ASN1_ITEM_end(tname)
# define static_ASN1_NDEF_SEQUENCE_END(tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_NDEF_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(tname),\
#tname \
ASN1_ITEM_end(tname)
# define ASN1_BROKEN_SEQUENCE_END(stname) ASN1_SEQUENCE_END_ref(stname, stname)
# define static_ASN1_BROKEN_SEQUENCE_END(stname) \
static_ASN1_SEQUENCE_END_ref(stname, stname)
# define ASN1_SEQUENCE_END_enc(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
# define ASN1_SEQUENCE_END_cb(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
# define static_ASN1_SEQUENCE_END_cb(stname, tname) static_ASN1_SEQUENCE_END_ref(stname, tname)
# define ASN1_SEQUENCE_END_ref(stname, tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#tname \
ASN1_ITEM_end(tname)
# define static_ASN1_SEQUENCE_END_ref(stname, tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define ASN1_NDEF_SEQUENCE_END_cb(stname, tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_NDEF_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
/*-
* This pair helps declare a CHOICE type. We can do:
*
* ASN1_CHOICE(chname) = {
* ... CHOICE options ...
* ASN1_CHOICE_END(chname)
*
* This will produce an ASN1_ITEM called chname_it
* for a structure called chname. The structure
* definition must look like this:
* typedef struct {
* int type;
* union {
* ASN1_SOMETHING *opt1;
* ASN1_SOMEOTHER *opt2;
* } value;
* } chname;
*
* the name of the selector must be 'type'.
* to use an alternative selector name use the
* ASN1_CHOICE_END_selector() version.
*/
# define ASN1_CHOICE(tname) \
static const ASN1_TEMPLATE tname##_ch_tt[]
# define ASN1_CHOICE_cb(tname, cb) \
static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0}; \
ASN1_CHOICE(tname)
# define ASN1_CHOICE_END(stname) ASN1_CHOICE_END_name(stname, stname)
# define static_ASN1_CHOICE_END(stname) static_ASN1_CHOICE_END_name(stname, stname)
# define ASN1_CHOICE_END_name(stname, tname) ASN1_CHOICE_END_selector(stname, tname, type)
# define static_ASN1_CHOICE_END_name(stname, tname) static_ASN1_CHOICE_END_selector(stname, tname, type)
# define ASN1_CHOICE_END_selector(stname, tname, selname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_CHOICE,\
offsetof(stname,selname) ,\
tname##_ch_tt,\
sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define static_ASN1_CHOICE_END_selector(stname, tname, selname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_CHOICE,\
offsetof(stname,selname) ,\
tname##_ch_tt,\
sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define ASN1_CHOICE_END_cb(stname, tname, selname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_CHOICE,\
offsetof(stname,selname) ,\
tname##_ch_tt,\
sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
/* This helps with the template wrapper form of ASN1_ITEM */
# define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, type) { \
(flags), (tag), 0,\
#name, ASN1_ITEM_ref(type) }
/* These help with SEQUENCE or CHOICE components */
/* used to declare other types */
# define ASN1_EX_TYPE(flags, tag, stname, field, type) { \
(flags), (tag), offsetof(stname, field),\
#field, ASN1_ITEM_ref(type) }
/* implicit and explicit helper macros */
# define ASN1_IMP_EX(stname, field, type, tag, ex) \
ASN1_EX_TYPE(ASN1_TFLG_IMPLICIT | (ex), tag, stname, field, type)
# define ASN1_EXP_EX(stname, field, type, tag, ex) \
ASN1_EX_TYPE(ASN1_TFLG_EXPLICIT | (ex), tag, stname, field, type)
/* Any defined by macros: the field used is in the table itself */
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) }
# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) }
# else
# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, tblname##_adb }
# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, tblname##_adb }
# endif
/* Plain simple type */
# define ASN1_SIMPLE(stname, field, type) ASN1_EX_TYPE(0,0, stname, field, type)
/* Embedded simple type */
# define ASN1_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_EMBED,0, stname, field, type)
/* OPTIONAL simple type */
# define ASN1_OPT(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL, 0, stname, field, type)
# define ASN1_OPT_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED, 0, stname, field, type)
/* IMPLICIT tagged simple type */
# define ASN1_IMP(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, 0)
# define ASN1_IMP_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
/* IMPLICIT tagged OPTIONAL simple type */
# define ASN1_IMP_OPT(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
# define ASN1_IMP_OPT_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
/* Same as above but EXPLICIT */
# define ASN1_EXP(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, 0)
# define ASN1_EXP_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
# define ASN1_EXP_OPT(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
# define ASN1_EXP_OPT_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
/* SEQUENCE OF type */
# define ASN1_SEQUENCE_OF(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, stname, field, type)
/* OPTIONAL SEQUENCE OF */
# define ASN1_SEQUENCE_OF_OPT(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
/* Same as above but for SET OF */
# define ASN1_SET_OF(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SET_OF, 0, stname, field, type)
# define ASN1_SET_OF_OPT(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
/* Finally compound types of SEQUENCE, SET, IMPLICIT, EXPLICIT and OPTIONAL */
# define ASN1_IMP_SET_OF(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
# define ASN1_EXP_SET_OF(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
# define ASN1_IMP_SET_OF_OPT(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
# define ASN1_EXP_SET_OF_OPT(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
# define ASN1_IMP_SEQUENCE_OF(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
# define ASN1_IMP_SEQUENCE_OF_OPT(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
# define ASN1_EXP_SEQUENCE_OF(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
# define ASN1_EXP_SEQUENCE_OF_OPT(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
/* EXPLICIT using indefinite length constructed form */
# define ASN1_NDEF_EXP(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_NDEF)
/* EXPLICIT OPTIONAL using indefinite length constructed form */
# define ASN1_NDEF_EXP_OPT(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_NDEF)
/* Macros for the ASN1_ADB structure */
# define ASN1_ADB(name) \
static const ASN1_ADB_TABLE name##_adbtbl[]
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \
;\
static const ASN1_ADB name##_adb = {\
flags,\
offsetof(name, field),\
adb_cb,\
name##_adbtbl,\
sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\
def,\
none\
}
# else
# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \
;\
static const ASN1_ITEM *name##_adb(void) \
{ \
static const ASN1_ADB internal_adb = \
{\
flags,\
offsetof(name, field),\
adb_cb,\
name##_adbtbl,\
sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\
def,\
none\
}; \
return (const ASN1_ITEM *) &internal_adb; \
} \
void dummy_function(void)
# endif
# define ADB_ENTRY(val, template) {val, template}
# define ASN1_ADB_TEMPLATE(name) \
static const ASN1_TEMPLATE name##_tt
/*
* This is the ASN1 template structure that defines a wrapper round the
* actual type. It determines the actual position of the field in the value
* structure, various flags such as OPTIONAL and the field name.
*/
struct ASN1_TEMPLATE_st {
unsigned long flags; /* Various flags */
long tag; /* tag, not used if no tagging */
unsigned long offset; /* Offset of this field in structure */
const char *field_name; /* Field name */
ASN1_ITEM_EXP *item; /* Relevant ASN1_ITEM or ASN1_ADB */
};
/* Macro to extract ASN1_ITEM and ASN1_ADB pointer from ASN1_TEMPLATE */
# define ASN1_TEMPLATE_item(t) (t->item_ptr)
# define ASN1_TEMPLATE_adb(t) (t->item_ptr)
typedef struct ASN1_ADB_TABLE_st ASN1_ADB_TABLE;
typedef struct ASN1_ADB_st ASN1_ADB;
struct ASN1_ADB_st {
unsigned long flags; /* Various flags */
unsigned long offset; /* Offset of selector field */
int (*adb_cb)(long *psel); /* Application callback */
const ASN1_ADB_TABLE *tbl; /* Table of possible types */
long tblcount; /* Number of entries in tbl */
const ASN1_TEMPLATE *default_tt; /* Type to use if no match */
const ASN1_TEMPLATE *null_tt; /* Type to use if selector is NULL */
};
struct ASN1_ADB_TABLE_st {
long value; /* NID for an object or value for an int */
const ASN1_TEMPLATE tt; /* item for this value */
};
/* template flags */
/* Field is optional */
# define ASN1_TFLG_OPTIONAL (0x1)
/* Field is a SET OF */
# define ASN1_TFLG_SET_OF (0x1 << 1)
/* Field is a SEQUENCE OF */
# define ASN1_TFLG_SEQUENCE_OF (0x2 << 1)
/*
* Special case: this refers to a SET OF that will be sorted into DER order
* when encoded *and* the corresponding STACK will be modified to match the
* new order.
*/
# define ASN1_TFLG_SET_ORDER (0x3 << 1)
/* Mask for SET OF or SEQUENCE OF */
# define ASN1_TFLG_SK_MASK (0x3 << 1)
/*
* These flags mean the tag should be taken from the tag field. If EXPLICIT
* then the underlying type is used for the inner tag.
*/
/* IMPLICIT tagging */
# define ASN1_TFLG_IMPTAG (0x1 << 3)
/* EXPLICIT tagging, inner tag from underlying type */
# define ASN1_TFLG_EXPTAG (0x2 << 3)
# define ASN1_TFLG_TAG_MASK (0x3 << 3)
/* context specific IMPLICIT */
# define ASN1_TFLG_IMPLICIT (ASN1_TFLG_IMPTAG|ASN1_TFLG_CONTEXT)
/* context specific EXPLICIT */
# define ASN1_TFLG_EXPLICIT (ASN1_TFLG_EXPTAG|ASN1_TFLG_CONTEXT)
/*
* If tagging is in force these determine the type of tag to use. Otherwise
* the tag is determined by the underlying type. These values reflect the
* actual octet format.
*/
/* Universal tag */
# define ASN1_TFLG_UNIVERSAL (0x0<<6)
/* Application tag */
# define ASN1_TFLG_APPLICATION (0x1<<6)
/* Context specific tag */
# define ASN1_TFLG_CONTEXT (0x2<<6)
/* Private tag */
# define ASN1_TFLG_PRIVATE (0x3<<6)
# define ASN1_TFLG_TAG_CLASS (0x3<<6)
/*
* These are for ANY DEFINED BY type. In this case the 'item' field points to
* an ASN1_ADB structure which contains a table of values to decode the
* relevant type
*/
# define ASN1_TFLG_ADB_MASK (0x3<<8)
# define ASN1_TFLG_ADB_OID (0x1<<8)
# define ASN1_TFLG_ADB_INT (0x1<<9)
/*
* This flag when present in a SEQUENCE OF, SET OF or EXPLICIT causes
* indefinite length constructed encoding to be used if required.
*/
# define ASN1_TFLG_NDEF (0x1<<11)
/* Field is embedded and not a pointer */
# define ASN1_TFLG_EMBED (0x1 << 12)
/* This is the actual ASN1 item itself */
struct ASN1_ITEM_st {
char itype; /* The item type, primitive, SEQUENCE, CHOICE
* or extern */
long utype; /* underlying type */
const ASN1_TEMPLATE *templates; /* If SEQUENCE or CHOICE this contains
* the contents */
long tcount; /* Number of templates if SEQUENCE or CHOICE */
const void *funcs; /* functions that handle this type */
long size; /* Structure size (usually) */
const char *sname; /* Structure name */
};
/*-
* These are values for the itype field and
* determine how the type is interpreted.
*
* For PRIMITIVE types the underlying type
* determines the behaviour if items is NULL.
*
* Otherwise templates must contain a single
* template and the type is treated in the
* same way as the type specified in the template.
*
* For SEQUENCE types the templates field points
* to the members, the size field is the
* structure size.
*
* For CHOICE types the templates field points
* to each possible member (typically a union)
* and the 'size' field is the offset of the
* selector.
*
* The 'funcs' field is used for application
* specific functions.
*
* The EXTERN type uses a new style d2i/i2d.
* The new style should be used where possible
* because it avoids things like the d2i IMPLICIT
* hack.
*
* MSTRING is a multiple string type, it is used
* for a CHOICE of character strings where the
* actual strings all occupy an ASN1_STRING
* structure. In this case the 'utype' field
* has a special meaning, it is used as a mask
* of acceptable types using the B_ASN1 constants.
*
* NDEF_SEQUENCE is the same as SEQUENCE except
* that it will use indefinite length constructed
* encoding if requested.
*
*/
# define ASN1_ITYPE_PRIMITIVE 0x0
# define ASN1_ITYPE_SEQUENCE 0x1
# define ASN1_ITYPE_CHOICE 0x2
# define ASN1_ITYPE_EXTERN 0x4
# define ASN1_ITYPE_MSTRING 0x5
# define ASN1_ITYPE_NDEF_SEQUENCE 0x6
/*
* Cache for ASN1 tag and length, so we don't keep re-reading it for things
* like CHOICE
*/
struct ASN1_TLC_st {
char valid; /* Values below are valid */
int ret; /* return value */
long plen; /* length */
int ptag; /* class value */
int pclass; /* class value */
int hdrlen; /* header length */
};
/* Typedefs for ASN1 function pointers */
typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
ASN1_TLC *ctx);
typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
typedef int ASN1_ex_print_func(BIO *out, ASN1_VALUE **pval,
int indent, const char *fname,
const ASN1_PCTX *pctx);
typedef int ASN1_primitive_i2c(ASN1_VALUE **pval, unsigned char *cont,
int *putype, const ASN1_ITEM *it);
typedef int ASN1_primitive_c2i(ASN1_VALUE **pval, const unsigned char *cont,
int len, int utype, char *free_cont,
const ASN1_ITEM *it);
typedef int ASN1_primitive_print(BIO *out, ASN1_VALUE **pval,
const ASN1_ITEM *it, int indent,
const ASN1_PCTX *pctx);
typedef struct ASN1_EXTERN_FUNCS_st {
void *app_data;
ASN1_ex_new_func *asn1_ex_new;
ASN1_ex_free_func *asn1_ex_free;
ASN1_ex_free_func *asn1_ex_clear;
ASN1_ex_d2i *asn1_ex_d2i;
ASN1_ex_i2d *asn1_ex_i2d;
ASN1_ex_print_func *asn1_ex_print;
} ASN1_EXTERN_FUNCS;
typedef struct ASN1_PRIMITIVE_FUNCS_st {
void *app_data;
unsigned long flags;
ASN1_ex_new_func *prim_new;
ASN1_ex_free_func *prim_free;
ASN1_ex_free_func *prim_clear;
ASN1_primitive_c2i *prim_c2i;
ASN1_primitive_i2c *prim_i2c;
ASN1_primitive_print *prim_print;
} ASN1_PRIMITIVE_FUNCS;
/*
* This is the ASN1_AUX structure: it handles various miscellaneous
* requirements. For example the use of reference counts and an informational
* callback. The "informational callback" is called at various points during
* the ASN1 encoding and decoding. It can be used to provide minor
* customisation of the structures used. This is most useful where the
* supplied routines *almost* do the right thing but need some extra help at
* a few points. If the callback returns zero then it is assumed a fatal
* error has occurred and the main operation should be abandoned. If major
* changes in the default behaviour are required then an external type is
* more appropriate.
*/
typedef int ASN1_aux_cb(int operation, ASN1_VALUE **in, const ASN1_ITEM *it,
void *exarg);
typedef struct ASN1_AUX_st {
void *app_data;
int flags;
int ref_offset; /* Offset of reference value */
int ref_lock; /* Lock type to use */
ASN1_aux_cb *asn1_cb;
int enc_offset; /* Offset of ASN1_ENCODING structure */
} ASN1_AUX;
/* For print related callbacks exarg points to this structure */
typedef struct ASN1_PRINT_ARG_st {
BIO *out;
int indent;
const ASN1_PCTX *pctx;
} ASN1_PRINT_ARG;
/* For streaming related callbacks exarg points to this structure */
typedef struct ASN1_STREAM_ARG_st {
/* BIO to stream through */
BIO *out;
/* BIO with filters appended */
BIO *ndef_bio;
/* Streaming I/O boundary */
unsigned char **boundary;
} ASN1_STREAM_ARG;
/* Flags in ASN1_AUX */
/* Use a reference count */
# define ASN1_AFLG_REFCOUNT 1
/* Save the encoding of structure (useful for signatures) */
# define ASN1_AFLG_ENCODING 2
/* The Sequence length is invalid */
# define ASN1_AFLG_BROKEN 4
/* operation values for asn1_cb */
# define ASN1_OP_NEW_PRE 0
# define ASN1_OP_NEW_POST 1
# define ASN1_OP_FREE_PRE 2
# define ASN1_OP_FREE_POST 3
# define ASN1_OP_D2I_PRE 4
# define ASN1_OP_D2I_POST 5
# define ASN1_OP_I2D_PRE 6
# define ASN1_OP_I2D_POST 7
# define ASN1_OP_PRINT_PRE 8
# define ASN1_OP_PRINT_POST 9
# define ASN1_OP_STREAM_PRE 10
# define ASN1_OP_STREAM_POST 11
# define ASN1_OP_DETACHED_PRE 12
# define ASN1_OP_DETACHED_POST 13
/* Macro to implement a primitive type */
# define IMPLEMENT_ASN1_TYPE(stname) IMPLEMENT_ASN1_TYPE_ex(stname, stname, 0)
# define IMPLEMENT_ASN1_TYPE_ex(itname, vname, ex) \
ASN1_ITEM_start(itname) \
ASN1_ITYPE_PRIMITIVE, V_##vname, NULL, 0, NULL, ex, #itname \
ASN1_ITEM_end(itname)
/* Macro to implement a multi string type */
# define IMPLEMENT_ASN1_MSTRING(itname, mask) \
ASN1_ITEM_start(itname) \
ASN1_ITYPE_MSTRING, mask, NULL, 0, NULL, sizeof(ASN1_STRING), #itname \
ASN1_ITEM_end(itname)
# define IMPLEMENT_EXTERN_ASN1(sname, tag, fptrs) \
ASN1_ITEM_start(sname) \
ASN1_ITYPE_EXTERN, \
tag, \
NULL, \
0, \
&fptrs, \
0, \
#sname \
ASN1_ITEM_end(sname)
/* Macro to implement standard functions in terms of ASN1_ITEM structures */
# define IMPLEMENT_ASN1_FUNCTIONS(stname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, stname, stname)
# define IMPLEMENT_ASN1_FUNCTIONS_name(stname, itname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, itname)
# define IMPLEMENT_ASN1_FUNCTIONS_ENCODE_name(stname, itname) \
IMPLEMENT_ASN1_FUNCTIONS_ENCODE_fname(stname, itname, itname)
# define IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(stname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(static, stname, stname, stname)
# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS(stname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, stname, stname)
# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(pre, stname, itname, fname) \
pre stname *fname##_new(void) \
{ \
return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
} \
pre void fname##_free(stname *a) \
{ \
ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
}
# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) \
stname *fname##_new(void) \
{ \
return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
} \
void fname##_free(stname *a) \
{ \
ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
}
# define IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname)
# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
stname *d2i_##fname(stname **a, const unsigned char **in, long len) \
{ \
return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\
} \
int i2d_##fname(stname *a, unsigned char **out) \
{ \
return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\
}
# define IMPLEMENT_ASN1_NDEF_FUNCTION(stname) \
int i2d_##stname##_NDEF(stname *a, unsigned char **out) \
{ \
return ASN1_item_ndef_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(stname));\
}
# define IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(stname) \
static stname *d2i_##stname(stname **a, \
const unsigned char **in, long len) \
{ \
return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, \
ASN1_ITEM_rptr(stname)); \
} \
static int i2d_##stname(stname *a, unsigned char **out) \
{ \
return ASN1_item_i2d((ASN1_VALUE *)a, out, \
ASN1_ITEM_rptr(stname)); \
}
/*
* This includes evil casts to remove const: they will go away when full ASN1
* constification is done.
*/
# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \
stname *d2i_##fname(stname **a, const unsigned char **in, long len) \
{ \
return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\
} \
int i2d_##fname(const stname *a, unsigned char **out) \
{ \
return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\
}
# define IMPLEMENT_ASN1_DUP_FUNCTION(stname) \
stname * stname##_dup(stname *x) \
{ \
return ASN1_item_dup(ASN1_ITEM_rptr(stname), x); \
}
# define IMPLEMENT_ASN1_PRINT_FUNCTION(stname) \
IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, stname, stname)
# define IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, itname, fname) \
int fname##_print_ctx(BIO *out, stname *x, int indent, \
const ASN1_PCTX *pctx) \
{ \
return ASN1_item_print(out, (ASN1_VALUE *)x, indent, \
ASN1_ITEM_rptr(itname), pctx); \
}
# define IMPLEMENT_ASN1_FUNCTIONS_const(name) \
IMPLEMENT_ASN1_FUNCTIONS_const_fname(name, name, name)
# define IMPLEMENT_ASN1_FUNCTIONS_const_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname)
/* external definitions for primitive types */
DECLARE_ASN1_ITEM(ASN1_BOOLEAN)
DECLARE_ASN1_ITEM(ASN1_TBOOLEAN)
DECLARE_ASN1_ITEM(ASN1_FBOOLEAN)
DECLARE_ASN1_ITEM(ASN1_SEQUENCE)
DECLARE_ASN1_ITEM(CBIGNUM)
DECLARE_ASN1_ITEM(BIGNUM)
DECLARE_ASN1_ITEM(INT32)
DECLARE_ASN1_ITEM(ZINT32)
DECLARE_ASN1_ITEM(UINT32)
DECLARE_ASN1_ITEM(ZUINT32)
DECLARE_ASN1_ITEM(INT64)
DECLARE_ASN1_ITEM(ZINT64)
DECLARE_ASN1_ITEM(UINT64)
DECLARE_ASN1_ITEM(ZUINT64)
# if OPENSSL_API_COMPAT < 0x10200000L
/*
* LONG and ZLONG are strongly discouraged for use as stored data, as the
* underlying C type (long) differs in size depending on the architecture.
* They are designed with 32-bit longs in mind.
*/
DECLARE_ASN1_ITEM(LONG)
DECLARE_ASN1_ITEM(ZLONG)
# endif
DEFINE_STACK_OF(ASN1_VALUE)
/* Functions used internally by the ASN1 code */
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
ASN1_TLC *ctx);
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,76 @@
/*
* Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#ifndef HEADER_ASYNC_H
# define HEADER_ASYNC_H
#if defined(_WIN32)
# if defined(BASETYPES) || defined(_WINDEF_H)
/* application has to include <windows.h> to use this */
#define OSSL_ASYNC_FD HANDLE
#define OSSL_BAD_ASYNC_FD INVALID_HANDLE_VALUE
# endif
#else
#define OSSL_ASYNC_FD int
#define OSSL_BAD_ASYNC_FD -1
#endif
# include <openssl/asyncerr.h>
# ifdef __cplusplus
extern "C" {
# endif
typedef struct async_job_st ASYNC_JOB;
typedef struct async_wait_ctx_st ASYNC_WAIT_CTX;
#define ASYNC_ERR 0
#define ASYNC_NO_JOBS 1
#define ASYNC_PAUSE 2
#define ASYNC_FINISH 3
int ASYNC_init_thread(size_t max_size, size_t init_size);
void ASYNC_cleanup_thread(void);
#ifdef OSSL_ASYNC_FD
ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void);
void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx);
int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD fd,
void *custom_data,
void (*cleanup)(ASYNC_WAIT_CTX *, const void *,
OSSL_ASYNC_FD, void *));
int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD *fd, void **custom_data);
int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd,
size_t *numfds);
int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd,
size_t *numaddfds, OSSL_ASYNC_FD *delfd,
size_t *numdelfds);
int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key);
#endif
int ASYNC_is_capable(void);
int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *ctx, int *ret,
int (*func)(void *), void *args, size_t size);
int ASYNC_pause_job(void);
ASYNC_JOB *ASYNC_get_current_job(void);
ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job);
void ASYNC_block_pause(void);
void ASYNC_unblock_pause(void);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,42 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ASYNCERR_H
# define HEADER_ASYNCERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_ASYNC_strings(void);
/*
* ASYNC function codes.
*/
# define ASYNC_F_ASYNC_CTX_NEW 100
# define ASYNC_F_ASYNC_INIT_THREAD 101
# define ASYNC_F_ASYNC_JOB_NEW 102
# define ASYNC_F_ASYNC_PAUSE_JOB 103
# define ASYNC_F_ASYNC_START_FUNC 104
# define ASYNC_F_ASYNC_START_JOB 105
# define ASYNC_F_ASYNC_WAIT_CTX_SET_WAIT_FD 106
/*
* ASYNC reason codes.
*/
# define ASYNC_R_FAILED_TO_SET_POOL 101
# define ASYNC_R_FAILED_TO_SWAP_CONTEXT 102
# define ASYNC_R_INIT_FAILED 105
# define ASYNC_R_INVALID_POOL_SIZE 103
#endif

@ -0,0 +1,801 @@
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BIO_H
# define HEADER_BIO_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_STDIO
# include <stdio.h>
# endif
# include <stdarg.h>
# include <openssl/crypto.h>
# include <openssl/bioerr.h>
#ifdef __cplusplus
extern "C" {
#endif
/* There are the classes of BIOs */
# define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */
# define BIO_TYPE_FILTER 0x0200
# define BIO_TYPE_SOURCE_SINK 0x0400
/* These are the 'types' of BIOs */
# define BIO_TYPE_NONE 0
# define BIO_TYPE_MEM ( 1|BIO_TYPE_SOURCE_SINK)
# define BIO_TYPE_FILE ( 2|BIO_TYPE_SOURCE_SINK)
# define BIO_TYPE_FD ( 4|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_SOCKET ( 5|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_NULL ( 6|BIO_TYPE_SOURCE_SINK)
# define BIO_TYPE_SSL ( 7|BIO_TYPE_FILTER)
# define BIO_TYPE_MD ( 8|BIO_TYPE_FILTER)
# define BIO_TYPE_BUFFER ( 9|BIO_TYPE_FILTER)
# define BIO_TYPE_CIPHER (10|BIO_TYPE_FILTER)
# define BIO_TYPE_BASE64 (11|BIO_TYPE_FILTER)
# define BIO_TYPE_CONNECT (12|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_ACCEPT (13|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_NBIO_TEST (16|BIO_TYPE_FILTER)/* server proxy BIO */
# define BIO_TYPE_NULL_FILTER (17|BIO_TYPE_FILTER)
# define BIO_TYPE_BIO (19|BIO_TYPE_SOURCE_SINK)/* half a BIO pair */
# define BIO_TYPE_LINEBUFFER (20|BIO_TYPE_FILTER)
# define BIO_TYPE_DGRAM (21|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_ASN1 (22|BIO_TYPE_FILTER)
# define BIO_TYPE_COMP (23|BIO_TYPE_FILTER)
# ifndef OPENSSL_NO_SCTP
# define BIO_TYPE_DGRAM_SCTP (24|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# endif
#define BIO_TYPE_START 128
/*
* BIO_FILENAME_READ|BIO_CLOSE to open or close on free.
* BIO_set_fp(in,stdin,BIO_NOCLOSE);
*/
# define BIO_NOCLOSE 0x00
# define BIO_CLOSE 0x01
/*
* These are used in the following macros and are passed to BIO_ctrl()
*/
# define BIO_CTRL_RESET 1/* opt - rewind/zero etc */
# define BIO_CTRL_EOF 2/* opt - are we at the eof */
# define BIO_CTRL_INFO 3/* opt - extra tit-bits */
# define BIO_CTRL_SET 4/* man - set the 'IO' type */
# define BIO_CTRL_GET 5/* man - get the 'IO' type */
# define BIO_CTRL_PUSH 6/* opt - internal, used to signify change */
# define BIO_CTRL_POP 7/* opt - internal, used to signify change */
# define BIO_CTRL_GET_CLOSE 8/* man - set the 'close' on free */
# define BIO_CTRL_SET_CLOSE 9/* man - set the 'close' on free */
# define BIO_CTRL_PENDING 10/* opt - is their more data buffered */
# define BIO_CTRL_FLUSH 11/* opt - 'flush' buffered output */
# define BIO_CTRL_DUP 12/* man - extra stuff for 'duped' BIO */
# define BIO_CTRL_WPENDING 13/* opt - number of bytes still to write */
# define BIO_CTRL_SET_CALLBACK 14/* opt - set callback function */
# define BIO_CTRL_GET_CALLBACK 15/* opt - set callback function */
# define BIO_CTRL_PEEK 29/* BIO_f_buffer special */
# define BIO_CTRL_SET_FILENAME 30/* BIO_s_file special */
/* dgram BIO stuff */
# define BIO_CTRL_DGRAM_CONNECT 31/* BIO dgram special */
# define BIO_CTRL_DGRAM_SET_CONNECTED 32/* allow for an externally connected
* socket to be passed in */
# define BIO_CTRL_DGRAM_SET_RECV_TIMEOUT 33/* setsockopt, essentially */
# define BIO_CTRL_DGRAM_GET_RECV_TIMEOUT 34/* getsockopt, essentially */
# define BIO_CTRL_DGRAM_SET_SEND_TIMEOUT 35/* setsockopt, essentially */
# define BIO_CTRL_DGRAM_GET_SEND_TIMEOUT 36/* getsockopt, essentially */
# define BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP 37/* flag whether the last */
# define BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP 38/* I/O operation tiemd out */
/* #ifdef IP_MTU_DISCOVER */
# define BIO_CTRL_DGRAM_MTU_DISCOVER 39/* set DF bit on egress packets */
/* #endif */
# define BIO_CTRL_DGRAM_QUERY_MTU 40/* as kernel for current MTU */
# define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47
# define BIO_CTRL_DGRAM_GET_MTU 41/* get cached value for MTU */
# define BIO_CTRL_DGRAM_SET_MTU 42/* set cached value for MTU.
* want to use this if asking
* the kernel fails */
# define BIO_CTRL_DGRAM_MTU_EXCEEDED 43/* check whether the MTU was
* exceed in the previous write
* operation */
# define BIO_CTRL_DGRAM_GET_PEER 46
# define BIO_CTRL_DGRAM_SET_PEER 44/* Destination for the data */
# define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT 45/* Next DTLS handshake timeout
* to adjust socket timeouts */
# define BIO_CTRL_DGRAM_SET_DONT_FRAG 48
# define BIO_CTRL_DGRAM_GET_MTU_OVERHEAD 49
/* Deliberately outside of OPENSSL_NO_SCTP - used in bss_dgram.c */
# define BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE 50
# ifndef OPENSSL_NO_SCTP
/* SCTP stuff */
# define BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY 51
# define BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY 52
# define BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD 53
# define BIO_CTRL_DGRAM_SCTP_GET_SNDINFO 60
# define BIO_CTRL_DGRAM_SCTP_SET_SNDINFO 61
# define BIO_CTRL_DGRAM_SCTP_GET_RCVINFO 62
# define BIO_CTRL_DGRAM_SCTP_SET_RCVINFO 63
# define BIO_CTRL_DGRAM_SCTP_GET_PRINFO 64
# define BIO_CTRL_DGRAM_SCTP_SET_PRINFO 65
# define BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN 70
# endif
# define BIO_CTRL_DGRAM_SET_PEEK_MODE 71
/* modifiers */
# define BIO_FP_READ 0x02
# define BIO_FP_WRITE 0x04
# define BIO_FP_APPEND 0x08
# define BIO_FP_TEXT 0x10
# define BIO_FLAGS_READ 0x01
# define BIO_FLAGS_WRITE 0x02
# define BIO_FLAGS_IO_SPECIAL 0x04
# define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
# define BIO_FLAGS_SHOULD_RETRY 0x08
# ifndef BIO_FLAGS_UPLINK
/*
* "UPLINK" flag denotes file descriptors provided by application. It
* defaults to 0, as most platforms don't require UPLINK interface.
*/
# define BIO_FLAGS_UPLINK 0
# endif
# define BIO_FLAGS_BASE64_NO_NL 0x100
/*
* This is used with memory BIOs:
* BIO_FLAGS_MEM_RDONLY means we shouldn't free up or change the data in any way;
* BIO_FLAGS_NONCLEAR_RST means we shouldn't clear data on reset.
*/
# define BIO_FLAGS_MEM_RDONLY 0x200
# define BIO_FLAGS_NONCLEAR_RST 0x400
# define BIO_FLAGS_IN_EOF 0x800
typedef union bio_addr_st BIO_ADDR;
typedef struct bio_addrinfo_st BIO_ADDRINFO;
int BIO_get_new_index(void);
void BIO_set_flags(BIO *b, int flags);
int BIO_test_flags(const BIO *b, int flags);
void BIO_clear_flags(BIO *b, int flags);
# define BIO_get_flags(b) BIO_test_flags(b, ~(0x0))
# define BIO_set_retry_special(b) \
BIO_set_flags(b, (BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY))
# define BIO_set_retry_read(b) \
BIO_set_flags(b, (BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY))
# define BIO_set_retry_write(b) \
BIO_set_flags(b, (BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY))
/* These are normally used internally in BIOs */
# define BIO_clear_retry_flags(b) \
BIO_clear_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
# define BIO_get_retry_flags(b) \
BIO_test_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
/* These should be used by the application to tell why we should retry */
# define BIO_should_read(a) BIO_test_flags(a, BIO_FLAGS_READ)
# define BIO_should_write(a) BIO_test_flags(a, BIO_FLAGS_WRITE)
# define BIO_should_io_special(a) BIO_test_flags(a, BIO_FLAGS_IO_SPECIAL)
# define BIO_retry_type(a) BIO_test_flags(a, BIO_FLAGS_RWS)
# define BIO_should_retry(a) BIO_test_flags(a, BIO_FLAGS_SHOULD_RETRY)
/*
* The next three are used in conjunction with the BIO_should_io_special()
* condition. After this returns true, BIO *BIO_get_retry_BIO(BIO *bio, int
* *reason); will walk the BIO stack and return the 'reason' for the special
* and the offending BIO. Given a BIO, BIO_get_retry_reason(bio) will return
* the code.
*/
/*
* Returned from the SSL bio when the certificate retrieval code had an error
*/
# define BIO_RR_SSL_X509_LOOKUP 0x01
/* Returned from the connect BIO when a connect would have blocked */
# define BIO_RR_CONNECT 0x02
/* Returned from the accept BIO when an accept would have blocked */
# define BIO_RR_ACCEPT 0x03
/* These are passed by the BIO callback */
# define BIO_CB_FREE 0x01
# define BIO_CB_READ 0x02
# define BIO_CB_WRITE 0x03
# define BIO_CB_PUTS 0x04
# define BIO_CB_GETS 0x05
# define BIO_CB_CTRL 0x06
/*
* The callback is called before and after the underling operation, The
* BIO_CB_RETURN flag indicates if it is after the call
*/
# define BIO_CB_RETURN 0x80
# define BIO_CB_return(a) ((a)|BIO_CB_RETURN)
# define BIO_cb_pre(a) (!((a)&BIO_CB_RETURN))
# define BIO_cb_post(a) ((a)&BIO_CB_RETURN)
typedef long (*BIO_callback_fn)(BIO *b, int oper, const char *argp, int argi,
long argl, long ret);
typedef long (*BIO_callback_fn_ex)(BIO *b, int oper, const char *argp,
size_t len, int argi,
long argl, int ret, size_t *processed);
BIO_callback_fn BIO_get_callback(const BIO *b);
void BIO_set_callback(BIO *b, BIO_callback_fn callback);
BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b);
void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex callback);
char *BIO_get_callback_arg(const BIO *b);
void BIO_set_callback_arg(BIO *b, char *arg);
typedef struct bio_method_st BIO_METHOD;
const char *BIO_method_name(const BIO *b);
int BIO_method_type(const BIO *b);
typedef int BIO_info_cb(BIO *, int, int);
typedef BIO_info_cb bio_info_cb; /* backward compatibility */
DEFINE_STACK_OF(BIO)
/* Prefix and suffix callback in ASN1 BIO */
typedef int asn1_ps_func (BIO *b, unsigned char **pbuf, int *plen,
void *parg);
# ifndef OPENSSL_NO_SCTP
/* SCTP parameter structs */
struct bio_dgram_sctp_sndinfo {
uint16_t snd_sid;
uint16_t snd_flags;
uint32_t snd_ppid;
uint32_t snd_context;
};
struct bio_dgram_sctp_rcvinfo {
uint16_t rcv_sid;
uint16_t rcv_ssn;
uint16_t rcv_flags;
uint32_t rcv_ppid;
uint32_t rcv_tsn;
uint32_t rcv_cumtsn;
uint32_t rcv_context;
};
struct bio_dgram_sctp_prinfo {
uint16_t pr_policy;
uint32_t pr_value;
};
# endif
/*
* #define BIO_CONN_get_param_hostname BIO_ctrl
*/
# define BIO_C_SET_CONNECT 100
# define BIO_C_DO_STATE_MACHINE 101
# define BIO_C_SET_NBIO 102
/* # define BIO_C_SET_PROXY_PARAM 103 */
# define BIO_C_SET_FD 104
# define BIO_C_GET_FD 105
# define BIO_C_SET_FILE_PTR 106
# define BIO_C_GET_FILE_PTR 107
# define BIO_C_SET_FILENAME 108
# define BIO_C_SET_SSL 109
# define BIO_C_GET_SSL 110
# define BIO_C_SET_MD 111
# define BIO_C_GET_MD 112
# define BIO_C_GET_CIPHER_STATUS 113
# define BIO_C_SET_BUF_MEM 114
# define BIO_C_GET_BUF_MEM_PTR 115
# define BIO_C_GET_BUFF_NUM_LINES 116
# define BIO_C_SET_BUFF_SIZE 117
# define BIO_C_SET_ACCEPT 118
# define BIO_C_SSL_MODE 119
# define BIO_C_GET_MD_CTX 120
/* # define BIO_C_GET_PROXY_PARAM 121 */
# define BIO_C_SET_BUFF_READ_DATA 122/* data to read first */
# define BIO_C_GET_CONNECT 123
# define BIO_C_GET_ACCEPT 124
# define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125
# define BIO_C_GET_SSL_NUM_RENEGOTIATES 126
# define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127
# define BIO_C_FILE_SEEK 128
# define BIO_C_GET_CIPHER_CTX 129
# define BIO_C_SET_BUF_MEM_EOF_RETURN 130/* return end of input
* value */
# define BIO_C_SET_BIND_MODE 131
# define BIO_C_GET_BIND_MODE 132
# define BIO_C_FILE_TELL 133
# define BIO_C_GET_SOCKS 134
# define BIO_C_SET_SOCKS 135
# define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */
# define BIO_C_GET_WRITE_BUF_SIZE 137
# define BIO_C_MAKE_BIO_PAIR 138
# define BIO_C_DESTROY_BIO_PAIR 139
# define BIO_C_GET_WRITE_GUARANTEE 140
# define BIO_C_GET_READ_REQUEST 141
# define BIO_C_SHUTDOWN_WR 142
# define BIO_C_NREAD0 143
# define BIO_C_NREAD 144
# define BIO_C_NWRITE0 145
# define BIO_C_NWRITE 146
# define BIO_C_RESET_READ_REQUEST 147
# define BIO_C_SET_MD_CTX 148
# define BIO_C_SET_PREFIX 149
# define BIO_C_GET_PREFIX 150
# define BIO_C_SET_SUFFIX 151
# define BIO_C_GET_SUFFIX 152
# define BIO_C_SET_EX_ARG 153
# define BIO_C_GET_EX_ARG 154
# define BIO_C_SET_CONNECT_MODE 155
# define BIO_set_app_data(s,arg) BIO_set_ex_data(s,0,arg)
# define BIO_get_app_data(s) BIO_get_ex_data(s,0)
# define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL)
# ifndef OPENSSL_NO_SOCK
/* IP families we support, for BIO_s_connect() and BIO_s_accept() */
/* Note: the underlying operating system may not support some of them */
# define BIO_FAMILY_IPV4 4
# define BIO_FAMILY_IPV6 6
# define BIO_FAMILY_IPANY 256
/* BIO_s_connect() */
# define BIO_set_conn_hostname(b,name) BIO_ctrl(b,BIO_C_SET_CONNECT,0, \
(char *)(name))
# define BIO_set_conn_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,1, \
(char *)(port))
# define BIO_set_conn_address(b,addr) BIO_ctrl(b,BIO_C_SET_CONNECT,2, \
(char *)(addr))
# define BIO_set_conn_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_CONNECT,3,f)
# define BIO_get_conn_hostname(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,0))
# define BIO_get_conn_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,1))
# define BIO_get_conn_address(b) ((const BIO_ADDR *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,2))
# define BIO_get_conn_ip_family(b) BIO_ctrl(b,BIO_C_GET_CONNECT,3,NULL)
# define BIO_set_conn_mode(b,n) BIO_ctrl(b,BIO_C_SET_CONNECT_MODE,(n),NULL)
/* BIO_s_accept() */
# define BIO_set_accept_name(b,name) BIO_ctrl(b,BIO_C_SET_ACCEPT,0, \
(char *)(name))
# define BIO_set_accept_port(b,port) BIO_ctrl(b,BIO_C_SET_ACCEPT,1, \
(char *)(port))
# define BIO_get_accept_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,0))
# define BIO_get_accept_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,1))
# define BIO_get_peer_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,2))
# define BIO_get_peer_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,3))
/* #define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) */
# define BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,2,(n)?(void *)"a":NULL)
# define BIO_set_accept_bios(b,bio) BIO_ctrl(b,BIO_C_SET_ACCEPT,3, \
(char *)(bio))
# define BIO_set_accept_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_ACCEPT,4,f)
# define BIO_get_accept_ip_family(b) BIO_ctrl(b,BIO_C_GET_ACCEPT,4,NULL)
/* Aliases kept for backward compatibility */
# define BIO_BIND_NORMAL 0
# define BIO_BIND_REUSEADDR BIO_SOCK_REUSEADDR
# define BIO_BIND_REUSEADDR_IF_UNUSED BIO_SOCK_REUSEADDR
# define BIO_set_bind_mode(b,mode) BIO_ctrl(b,BIO_C_SET_BIND_MODE,mode,NULL)
# define BIO_get_bind_mode(b) BIO_ctrl(b,BIO_C_GET_BIND_MODE,0,NULL)
/* BIO_s_accept() and BIO_s_connect() */
# define BIO_do_connect(b) BIO_do_handshake(b)
# define BIO_do_accept(b) BIO_do_handshake(b)
# endif /* OPENSSL_NO_SOCK */
# define BIO_do_handshake(b) BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL)
/* BIO_s_datagram(), BIO_s_fd(), BIO_s_socket(), BIO_s_accept() and BIO_s_connect() */
# define BIO_set_fd(b,fd,c) BIO_int_ctrl(b,BIO_C_SET_FD,c,fd)
# define BIO_get_fd(b,c) BIO_ctrl(b,BIO_C_GET_FD,0,(char *)(c))
/* BIO_s_file() */
# define BIO_set_fp(b,fp,c) BIO_ctrl(b,BIO_C_SET_FILE_PTR,c,(char *)(fp))
# define BIO_get_fp(b,fpp) BIO_ctrl(b,BIO_C_GET_FILE_PTR,0,(char *)(fpp))
/* BIO_s_fd() and BIO_s_file() */
# define BIO_seek(b,ofs) (int)BIO_ctrl(b,BIO_C_FILE_SEEK,ofs,NULL)
# define BIO_tell(b) (int)BIO_ctrl(b,BIO_C_FILE_TELL,0,NULL)
/*
* name is cast to lose const, but might be better to route through a
* function so we can do it safely
*/
# ifdef CONST_STRICT
/*
* If you are wondering why this isn't defined, its because CONST_STRICT is
* purely a compile-time kludge to allow const to be checked.
*/
int BIO_read_filename(BIO *b, const char *name);
# else
# define BIO_read_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_READ,(char *)(name))
# endif
# define BIO_write_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_WRITE,name)
# define BIO_append_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_APPEND,name)
# define BIO_rw_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_READ|BIO_FP_WRITE,name)
/*
* WARNING WARNING, this ups the reference count on the read bio of the SSL
* structure. This is because the ssl read BIO is now pointed to by the
* next_bio field in the bio. So when you free the BIO, make sure you are
* doing a BIO_free_all() to catch the underlying BIO.
*/
# define BIO_set_ssl(b,ssl,c) BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)(ssl))
# define BIO_get_ssl(b,sslp) BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)(sslp))
# define BIO_set_ssl_mode(b,client) BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL)
# define BIO_set_ssl_renegotiate_bytes(b,num) \
BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL)
# define BIO_get_num_renegotiates(b) \
BIO_ctrl(b,BIO_C_GET_SSL_NUM_RENEGOTIATES,0,NULL)
# define BIO_set_ssl_renegotiate_timeout(b,seconds) \
BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL)
/* defined in evp.h */
/* #define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,1,(char *)(md)) */
# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)(pp))
# define BIO_set_mem_buf(b,bm,c) BIO_ctrl(b,BIO_C_SET_BUF_MEM,c,(char *)(bm))
# define BIO_get_mem_ptr(b,pp) BIO_ctrl(b,BIO_C_GET_BUF_MEM_PTR,0, \
(char *)(pp))
# define BIO_set_mem_eof_return(b,v) \
BIO_ctrl(b,BIO_C_SET_BUF_MEM_EOF_RETURN,v,NULL)
/* For the BIO_f_buffer() type */
# define BIO_get_buffer_num_lines(b) BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL)
# define BIO_set_buffer_size(b,size) BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL)
# define BIO_set_read_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0)
# define BIO_set_write_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1)
# define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf)
/* Don't use the next one unless you know what you are doing :-) */
# define BIO_dup_state(b,ret) BIO_ctrl(b,BIO_CTRL_DUP,0,(char *)(ret))
# define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
# define BIO_eof(b) (int)BIO_ctrl(b,BIO_CTRL_EOF,0,NULL)
# define BIO_set_close(b,c) (int)BIO_ctrl(b,BIO_CTRL_SET_CLOSE,(c),NULL)
# define BIO_get_close(b) (int)BIO_ctrl(b,BIO_CTRL_GET_CLOSE,0,NULL)
# define BIO_pending(b) (int)BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL)
# define BIO_wpending(b) (int)BIO_ctrl(b,BIO_CTRL_WPENDING,0,NULL)
/* ...pending macros have inappropriate return type */
size_t BIO_ctrl_pending(BIO *b);
size_t BIO_ctrl_wpending(BIO *b);
# define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL)
# define BIO_get_info_callback(b,cbp) (int)BIO_ctrl(b,BIO_CTRL_GET_CALLBACK,0, \
cbp)
# define BIO_set_info_callback(b,cb) (int)BIO_callback_ctrl(b,BIO_CTRL_SET_CALLBACK,cb)
/* For the BIO_f_buffer() type */
# define BIO_buffer_get_num_lines(b) BIO_ctrl(b,BIO_CTRL_GET,0,NULL)
# define BIO_buffer_peek(b,s,l) BIO_ctrl(b,BIO_CTRL_PEEK,(l),(s))
/* For BIO_s_bio() */
# define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL)
# define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL)
# define BIO_make_bio_pair(b1,b2) (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2)
# define BIO_destroy_bio_pair(b) (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL)
# define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL)
/* macros with inappropriate type -- but ...pending macros use int too: */
# define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL)
# define BIO_get_read_request(b) (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL)
size_t BIO_ctrl_get_write_guarantee(BIO *b);
size_t BIO_ctrl_get_read_request(BIO *b);
int BIO_ctrl_reset_read_request(BIO *b);
/* ctrl macros for dgram */
# define BIO_ctrl_dgram_connect(b,peer) \
(int)BIO_ctrl(b,BIO_CTRL_DGRAM_CONNECT,0, (char *)(peer))
# define BIO_ctrl_set_connected(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_CONNECTED, 0, (char *)(peer))
# define BIO_dgram_recv_timedout(b) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)
# define BIO_dgram_send_timedout(b) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP, 0, NULL)
# define BIO_dgram_get_peer(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_PEER, 0, (char *)(peer))
# define BIO_dgram_set_peer(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, (char *)(peer))
# define BIO_dgram_get_mtu_overhead(b) \
(unsigned int)BIO_ctrl((b), BIO_CTRL_DGRAM_GET_MTU_OVERHEAD, 0, NULL)
#define BIO_get_ex_new_index(l, p, newf, dupf, freef) \
CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_BIO, l, p, newf, dupf, freef)
int BIO_set_ex_data(BIO *bio, int idx, void *data);
void *BIO_get_ex_data(BIO *bio, int idx);
uint64_t BIO_number_read(BIO *bio);
uint64_t BIO_number_written(BIO *bio);
/* For BIO_f_asn1() */
int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix,
asn1_ps_func *prefix_free);
int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix,
asn1_ps_func **pprefix_free);
int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix,
asn1_ps_func *suffix_free);
int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix,
asn1_ps_func **psuffix_free);
const BIO_METHOD *BIO_s_file(void);
BIO *BIO_new_file(const char *filename, const char *mode);
# ifndef OPENSSL_NO_STDIO
BIO *BIO_new_fp(FILE *stream, int close_flag);
# endif
BIO *BIO_new(const BIO_METHOD *type);
int BIO_free(BIO *a);
void BIO_set_data(BIO *a, void *ptr);
void *BIO_get_data(BIO *a);
void BIO_set_init(BIO *a, int init);
int BIO_get_init(BIO *a);
void BIO_set_shutdown(BIO *a, int shut);
int BIO_get_shutdown(BIO *a);
void BIO_vfree(BIO *a);
int BIO_up_ref(BIO *a);
int BIO_read(BIO *b, void *data, int dlen);
int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes);
int BIO_gets(BIO *bp, char *buf, int size);
int BIO_write(BIO *b, const void *data, int dlen);
int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written);
int BIO_puts(BIO *bp, const char *buf);
int BIO_indent(BIO *b, int indent, int max);
long BIO_ctrl(BIO *bp, int cmd, long larg, void *parg);
long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp);
void *BIO_ptr_ctrl(BIO *bp, int cmd, long larg);
long BIO_int_ctrl(BIO *bp, int cmd, long larg, int iarg);
BIO *BIO_push(BIO *b, BIO *append);
BIO *BIO_pop(BIO *b);
void BIO_free_all(BIO *a);
BIO *BIO_find_type(BIO *b, int bio_type);
BIO *BIO_next(BIO *b);
void BIO_set_next(BIO *b, BIO *next);
BIO *BIO_get_retry_BIO(BIO *bio, int *reason);
int BIO_get_retry_reason(BIO *bio);
void BIO_set_retry_reason(BIO *bio, int reason);
BIO *BIO_dup_chain(BIO *in);
int BIO_nread0(BIO *bio, char **buf);
int BIO_nread(BIO *bio, char **buf, int num);
int BIO_nwrite0(BIO *bio, char **buf);
int BIO_nwrite(BIO *bio, char **buf, int num);
long BIO_debug_callback(BIO *bio, int cmd, const char *argp, int argi,
long argl, long ret);
const BIO_METHOD *BIO_s_mem(void);
const BIO_METHOD *BIO_s_secmem(void);
BIO *BIO_new_mem_buf(const void *buf, int len);
# ifndef OPENSSL_NO_SOCK
const BIO_METHOD *BIO_s_socket(void);
const BIO_METHOD *BIO_s_connect(void);
const BIO_METHOD *BIO_s_accept(void);
# endif
const BIO_METHOD *BIO_s_fd(void);
const BIO_METHOD *BIO_s_log(void);
const BIO_METHOD *BIO_s_bio(void);
const BIO_METHOD *BIO_s_null(void);
const BIO_METHOD *BIO_f_null(void);
const BIO_METHOD *BIO_f_buffer(void);
const BIO_METHOD *BIO_f_linebuffer(void);
const BIO_METHOD *BIO_f_nbio_test(void);
# ifndef OPENSSL_NO_DGRAM
const BIO_METHOD *BIO_s_datagram(void);
int BIO_dgram_non_fatal_error(int error);
BIO *BIO_new_dgram(int fd, int close_flag);
# ifndef OPENSSL_NO_SCTP
const BIO_METHOD *BIO_s_datagram_sctp(void);
BIO *BIO_new_dgram_sctp(int fd, int close_flag);
int BIO_dgram_is_sctp(BIO *bio);
int BIO_dgram_sctp_notification_cb(BIO *b,
void (*handle_notifications) (BIO *bio,
void *context,
void *buf),
void *context);
int BIO_dgram_sctp_wait_for_dry(BIO *b);
int BIO_dgram_sctp_msg_waiting(BIO *b);
# endif
# endif
# ifndef OPENSSL_NO_SOCK
int BIO_sock_should_retry(int i);
int BIO_sock_non_fatal_error(int error);
# endif
int BIO_fd_should_retry(int i);
int BIO_fd_non_fatal_error(int error);
int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u),
void *u, const char *s, int len);
int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u),
void *u, const char *s, int len, int indent);
int BIO_dump(BIO *b, const char *bytes, int len);
int BIO_dump_indent(BIO *b, const char *bytes, int len, int indent);
# ifndef OPENSSL_NO_STDIO
int BIO_dump_fp(FILE *fp, const char *s, int len);
int BIO_dump_indent_fp(FILE *fp, const char *s, int len, int indent);
# endif
int BIO_hex_string(BIO *out, int indent, int width, unsigned char *data,
int datalen);
# ifndef OPENSSL_NO_SOCK
BIO_ADDR *BIO_ADDR_new(void);
int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
const void *where, size_t wherelen, unsigned short port);
void BIO_ADDR_free(BIO_ADDR *);
void BIO_ADDR_clear(BIO_ADDR *ap);
int BIO_ADDR_family(const BIO_ADDR *ap);
int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l);
unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap);
char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric);
char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric);
char *BIO_ADDR_path_string(const BIO_ADDR *ap);
const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai);
const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai);
void BIO_ADDRINFO_free(BIO_ADDRINFO *bai);
enum BIO_hostserv_priorities {
BIO_PARSE_PRIO_HOST, BIO_PARSE_PRIO_SERV
};
int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
enum BIO_hostserv_priorities hostserv_prio);
enum BIO_lookup_type {
BIO_LOOKUP_CLIENT, BIO_LOOKUP_SERVER
};
int BIO_lookup(const char *host, const char *service,
enum BIO_lookup_type lookup_type,
int family, int socktype, BIO_ADDRINFO **res);
int BIO_lookup_ex(const char *host, const char *service,
int lookup_type, int family, int socktype, int protocol,
BIO_ADDRINFO **res);
int BIO_sock_error(int sock);
int BIO_socket_ioctl(int fd, long type, void *arg);
int BIO_socket_nbio(int fd, int mode);
int BIO_sock_init(void);
# if OPENSSL_API_COMPAT < 0x10100000L
# define BIO_sock_cleanup() while(0) continue
# endif
int BIO_set_tcp_ndelay(int sock, int turn_on);
DEPRECATEDIN_1_1_0(struct hostent *BIO_gethostbyname(const char *name))
DEPRECATEDIN_1_1_0(int BIO_get_port(const char *str, unsigned short *port_ptr))
DEPRECATEDIN_1_1_0(int BIO_get_host_ip(const char *str, unsigned char *ip))
DEPRECATEDIN_1_1_0(int BIO_get_accept_socket(char *host_port, int mode))
DEPRECATEDIN_1_1_0(int BIO_accept(int sock, char **ip_port))
union BIO_sock_info_u {
BIO_ADDR *addr;
};
enum BIO_sock_info_type {
BIO_SOCK_INFO_ADDRESS
};
int BIO_sock_info(int sock,
enum BIO_sock_info_type type, union BIO_sock_info_u *info);
# define BIO_SOCK_REUSEADDR 0x01
# define BIO_SOCK_V6_ONLY 0x02
# define BIO_SOCK_KEEPALIVE 0x04
# define BIO_SOCK_NONBLOCK 0x08
# define BIO_SOCK_NODELAY 0x10
int BIO_socket(int domain, int socktype, int protocol, int options);
int BIO_connect(int sock, const BIO_ADDR *addr, int options);
int BIO_bind(int sock, const BIO_ADDR *addr, int options);
int BIO_listen(int sock, const BIO_ADDR *addr, int options);
int BIO_accept_ex(int accept_sock, BIO_ADDR *addr, int options);
int BIO_closesocket(int sock);
BIO *BIO_new_socket(int sock, int close_flag);
BIO *BIO_new_connect(const char *host_port);
BIO *BIO_new_accept(const char *host_port);
# endif /* OPENSSL_NO_SOCK*/
BIO *BIO_new_fd(int fd, int close_flag);
int BIO_new_bio_pair(BIO **bio1, size_t writebuf1,
BIO **bio2, size_t writebuf2);
/*
* If successful, returns 1 and in *bio1, *bio2 two BIO pair endpoints.
* Otherwise returns 0 and sets *bio1 and *bio2 to NULL. Size 0 uses default
* value.
*/
void BIO_copy_next_retry(BIO *b);
/*
* long BIO_ghbn_ctrl(int cmd,int iarg,char *parg);
*/
# define ossl_bio__attr__(x)
# if defined(__GNUC__) && defined(__STDC_VERSION__) \
&& !defined(__APPLE__)
/*
* Because we support the 'z' modifier, which made its appearance in C99,
* we can't use __attribute__ with pre C99 dialects.
*/
# if __STDC_VERSION__ >= 199901L
# undef ossl_bio__attr__
# define ossl_bio__attr__ __attribute__
# if __GNUC__*10 + __GNUC_MINOR__ >= 44
# define ossl_bio__printf__ __gnu_printf__
# else
# define ossl_bio__printf__ __printf__
# endif
# endif
# endif
int BIO_printf(BIO *bio, const char *format, ...)
ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 3)));
int BIO_vprintf(BIO *bio, const char *format, va_list args)
ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 0)));
int BIO_snprintf(char *buf, size_t n, const char *format, ...)
ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 4)));
int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 0)));
# undef ossl_bio__attr__
# undef ossl_bio__printf__
BIO_METHOD *BIO_meth_new(int type, const char *name);
void BIO_meth_free(BIO_METHOD *biom);
int (*BIO_meth_get_write(const BIO_METHOD *biom)) (BIO *, const char *, int);
int (*BIO_meth_get_write_ex(const BIO_METHOD *biom)) (BIO *, const char *, size_t,
size_t *);
int BIO_meth_set_write(BIO_METHOD *biom,
int (*write) (BIO *, const char *, int));
int BIO_meth_set_write_ex(BIO_METHOD *biom,
int (*bwrite) (BIO *, const char *, size_t, size_t *));
int (*BIO_meth_get_read(const BIO_METHOD *biom)) (BIO *, char *, int);
int (*BIO_meth_get_read_ex(const BIO_METHOD *biom)) (BIO *, char *, size_t, size_t *);
int BIO_meth_set_read(BIO_METHOD *biom,
int (*read) (BIO *, char *, int));
int BIO_meth_set_read_ex(BIO_METHOD *biom,
int (*bread) (BIO *, char *, size_t, size_t *));
int (*BIO_meth_get_puts(const BIO_METHOD *biom)) (BIO *, const char *);
int BIO_meth_set_puts(BIO_METHOD *biom,
int (*puts) (BIO *, const char *));
int (*BIO_meth_get_gets(const BIO_METHOD *biom)) (BIO *, char *, int);
int BIO_meth_set_gets(BIO_METHOD *biom,
int (*gets) (BIO *, char *, int));
long (*BIO_meth_get_ctrl(const BIO_METHOD *biom)) (BIO *, int, long, void *);
int BIO_meth_set_ctrl(BIO_METHOD *biom,
long (*ctrl) (BIO *, int, long, void *));
int (*BIO_meth_get_create(const BIO_METHOD *bion)) (BIO *);
int BIO_meth_set_create(BIO_METHOD *biom, int (*create) (BIO *));
int (*BIO_meth_get_destroy(const BIO_METHOD *biom)) (BIO *);
int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy) (BIO *));
long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *biom))
(BIO *, int, BIO_info_cb *);
int BIO_meth_set_callback_ctrl(BIO_METHOD *biom,
long (*callback_ctrl) (BIO *, int,
BIO_info_cb *));
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,124 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BIOERR_H
# define HEADER_BIOERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_BIO_strings(void);
/*
* BIO function codes.
*/
# define BIO_F_ACPT_STATE 100
# define BIO_F_ADDRINFO_WRAP 148
# define BIO_F_ADDR_STRINGS 134
# define BIO_F_BIO_ACCEPT 101
# define BIO_F_BIO_ACCEPT_EX 137
# define BIO_F_BIO_ACCEPT_NEW 152
# define BIO_F_BIO_ADDR_NEW 144
# define BIO_F_BIO_BIND 147
# define BIO_F_BIO_CALLBACK_CTRL 131
# define BIO_F_BIO_CONNECT 138
# define BIO_F_BIO_CONNECT_NEW 153
# define BIO_F_BIO_CTRL 103
# define BIO_F_BIO_GETS 104
# define BIO_F_BIO_GET_HOST_IP 106
# define BIO_F_BIO_GET_NEW_INDEX 102
# define BIO_F_BIO_GET_PORT 107
# define BIO_F_BIO_LISTEN 139
# define BIO_F_BIO_LOOKUP 135
# define BIO_F_BIO_LOOKUP_EX 143
# define BIO_F_BIO_MAKE_PAIR 121
# define BIO_F_BIO_METH_NEW 146
# define BIO_F_BIO_NEW 108
# define BIO_F_BIO_NEW_DGRAM_SCTP 145
# define BIO_F_BIO_NEW_FILE 109
# define BIO_F_BIO_NEW_MEM_BUF 126
# define BIO_F_BIO_NREAD 123
# define BIO_F_BIO_NREAD0 124
# define BIO_F_BIO_NWRITE 125
# define BIO_F_BIO_NWRITE0 122
# define BIO_F_BIO_PARSE_HOSTSERV 136
# define BIO_F_BIO_PUTS 110
# define BIO_F_BIO_READ 111
# define BIO_F_BIO_READ_EX 105
# define BIO_F_BIO_READ_INTERN 120
# define BIO_F_BIO_SOCKET 140
# define BIO_F_BIO_SOCKET_NBIO 142
# define BIO_F_BIO_SOCK_INFO 141
# define BIO_F_BIO_SOCK_INIT 112
# define BIO_F_BIO_WRITE 113
# define BIO_F_BIO_WRITE_EX 119
# define BIO_F_BIO_WRITE_INTERN 128
# define BIO_F_BUFFER_CTRL 114
# define BIO_F_CONN_CTRL 127
# define BIO_F_CONN_STATE 115
# define BIO_F_DGRAM_SCTP_NEW 149
# define BIO_F_DGRAM_SCTP_READ 132
# define BIO_F_DGRAM_SCTP_WRITE 133
# define BIO_F_DOAPR_OUTCH 150
# define BIO_F_FILE_CTRL 116
# define BIO_F_FILE_READ 130
# define BIO_F_LINEBUFFER_CTRL 129
# define BIO_F_LINEBUFFER_NEW 151
# define BIO_F_MEM_WRITE 117
# define BIO_F_NBIOF_NEW 154
# define BIO_F_SLG_WRITE 155
# define BIO_F_SSL_NEW 118
/*
* BIO reason codes.
*/
# define BIO_R_ACCEPT_ERROR 100
# define BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET 141
# define BIO_R_AMBIGUOUS_HOST_OR_SERVICE 129
# define BIO_R_BAD_FOPEN_MODE 101
# define BIO_R_BROKEN_PIPE 124
# define BIO_R_CONNECT_ERROR 103
# define BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET 107
# define BIO_R_GETSOCKNAME_ERROR 132
# define BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS 133
# define BIO_R_GETTING_SOCKTYPE 134
# define BIO_R_INVALID_ARGUMENT 125
# define BIO_R_INVALID_SOCKET 135
# define BIO_R_IN_USE 123
# define BIO_R_LENGTH_TOO_LONG 102
# define BIO_R_LISTEN_V6_ONLY 136
# define BIO_R_LOOKUP_RETURNED_NOTHING 142
# define BIO_R_MALFORMED_HOST_OR_SERVICE 130
# define BIO_R_NBIO_CONNECT_ERROR 110
# define BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED 143
# define BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED 144
# define BIO_R_NO_PORT_DEFINED 113
# define BIO_R_NO_SUCH_FILE 128
# define BIO_R_NULL_PARAMETER 115
# define BIO_R_UNABLE_TO_BIND_SOCKET 117
# define BIO_R_UNABLE_TO_CREATE_SOCKET 118
# define BIO_R_UNABLE_TO_KEEPALIVE 137
# define BIO_R_UNABLE_TO_LISTEN_SOCKET 119
# define BIO_R_UNABLE_TO_NODELAY 138
# define BIO_R_UNABLE_TO_REUSEADDR 139
# define BIO_R_UNAVAILABLE_IP_FAMILY 145
# define BIO_R_UNINITIALIZED 120
# define BIO_R_UNKNOWN_INFO_TYPE 140
# define BIO_R_UNSUPPORTED_IP_FAMILY 146
# define BIO_R_UNSUPPORTED_METHOD 121
# define BIO_R_UNSUPPORTED_PROTOCOL_FAMILY 131
# define BIO_R_WRITE_TO_READ_ONLY_BIO 126
# define BIO_R_WSASTARTUP 122
#endif

@ -0,0 +1,61 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BLOWFISH_H
# define HEADER_BLOWFISH_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_BF
# include <openssl/e_os2.h>
# ifdef __cplusplus
extern "C" {
# endif
# define BF_ENCRYPT 1
# define BF_DECRYPT 0
/*-
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* ! BF_LONG has to be at least 32 bits wide. !
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
# define BF_LONG unsigned int
# define BF_ROUNDS 16
# define BF_BLOCK 8
typedef struct bf_key_st {
BF_LONG P[BF_ROUNDS + 2];
BF_LONG S[4 * 256];
} BF_KEY;
void BF_set_key(BF_KEY *key, int len, const unsigned char *data);
void BF_encrypt(BF_LONG *data, const BF_KEY *key);
void BF_decrypt(BF_LONG *data, const BF_KEY *key);
void BF_ecb_encrypt(const unsigned char *in, unsigned char *out,
const BF_KEY *key, int enc);
void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length,
const BF_KEY *schedule, unsigned char *ivec, int enc);
void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, const BF_KEY *schedule,
unsigned char *ivec, int *num, int enc);
void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out,
long length, const BF_KEY *schedule,
unsigned char *ivec, int *num);
const char *BF_options(void);
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,539 @@
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BN_H
# define HEADER_BN_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_STDIO
# include <stdio.h>
# endif
# include <openssl/opensslconf.h>
# include <openssl/ossl_typ.h>
# include <openssl/crypto.h>
# include <openssl/bnerr.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* 64-bit processor with LP64 ABI
*/
# ifdef SIXTY_FOUR_BIT_LONG
# define BN_ULONG unsigned long
# define BN_BYTES 8
# endif
/*
* 64-bit processor other than LP64 ABI
*/
# ifdef SIXTY_FOUR_BIT
# define BN_ULONG unsigned long long
# define BN_BYTES 8
# endif
# ifdef THIRTY_TWO_BIT
# define BN_ULONG unsigned int
# define BN_BYTES 4
# endif
# define BN_BITS2 (BN_BYTES * 8)
# define BN_BITS (BN_BITS2 * 2)
# define BN_TBIT ((BN_ULONG)1 << (BN_BITS2 - 1))
# define BN_FLG_MALLOCED 0x01
# define BN_FLG_STATIC_DATA 0x02
/*
* avoid leaking exponent information through timing,
* BN_mod_exp_mont() will call BN_mod_exp_mont_consttime,
* BN_div() will call BN_div_no_branch,
* BN_mod_inverse() will call bn_mod_inverse_no_branch.
*/
# define BN_FLG_CONSTTIME 0x04
# define BN_FLG_SECURE 0x08
# if OPENSSL_API_COMPAT < 0x00908000L
/* deprecated name for the flag */
# define BN_FLG_EXP_CONSTTIME BN_FLG_CONSTTIME
# define BN_FLG_FREE 0x8000 /* used for debugging */
# endif
void BN_set_flags(BIGNUM *b, int n);
int BN_get_flags(const BIGNUM *b, int n);
/* Values for |top| in BN_rand() */
#define BN_RAND_TOP_ANY -1
#define BN_RAND_TOP_ONE 0
#define BN_RAND_TOP_TWO 1
/* Values for |bottom| in BN_rand() */
#define BN_RAND_BOTTOM_ANY 0
#define BN_RAND_BOTTOM_ODD 1
/*
* get a clone of a BIGNUM with changed flags, for *temporary* use only (the
* two BIGNUMs cannot be used in parallel!). Also only for *read only* use. The
* value |dest| should be a newly allocated BIGNUM obtained via BN_new() that
* has not been otherwise initialised or used.
*/
void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags);
/* Wrapper function to make using BN_GENCB easier */
int BN_GENCB_call(BN_GENCB *cb, int a, int b);
BN_GENCB *BN_GENCB_new(void);
void BN_GENCB_free(BN_GENCB *cb);
/* Populate a BN_GENCB structure with an "old"-style callback */
void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback) (int, int, void *),
void *cb_arg);
/* Populate a BN_GENCB structure with a "new"-style callback */
void BN_GENCB_set(BN_GENCB *gencb, int (*callback) (int, int, BN_GENCB *),
void *cb_arg);
void *BN_GENCB_get_arg(BN_GENCB *cb);
# define BN_prime_checks 0 /* default: select number of iterations based
* on the size of the number */
/*
* BN_prime_checks_for_size() returns the number of Miller-Rabin iterations
* that will be done for checking that a random number is probably prime. The
* error rate for accepting a composite number as prime depends on the size of
* the prime |b|. The error rates used are for calculating an RSA key with 2 primes,
* and so the level is what you would expect for a key of double the size of the
* prime.
*
* This table is generated using the algorithm of FIPS PUB 186-4
* Digital Signature Standard (DSS), section F.1, page 117.
* (https://dx.doi.org/10.6028/NIST.FIPS.186-4)
*
* The following magma script was used to generate the output:
* securitybits:=125;
* k:=1024;
* for t:=1 to 65 do
* for M:=3 to Floor(2*Sqrt(k-1)-1) do
* S:=0;
* // Sum over m
* for m:=3 to M do
* s:=0;
* // Sum over j
* for j:=2 to m do
* s+:=(RealField(32)!2)^-(j+(k-1)/j);
* end for;
* S+:=2^(m-(m-1)*t)*s;
* end for;
* A:=2^(k-2-M*t);
* B:=8*(Pi(RealField(32))^2-6)/3*2^(k-2)*S;
* pkt:=2.00743*Log(2)*k*2^-k*(A+B);
* seclevel:=Floor(-Log(2,pkt));
* if seclevel ge securitybits then
* printf "k: %5o, security: %o bits (t: %o, M: %o)\n",k,seclevel,t,M;
* break;
* end if;
* end for;
* if seclevel ge securitybits then break; end if;
* end for;
*
* It can be run online at:
* http://magma.maths.usyd.edu.au/calc
*
* And will output:
* k: 1024, security: 129 bits (t: 6, M: 23)
*
* k is the number of bits of the prime, securitybits is the level we want to
* reach.
*
* prime length | RSA key size | # MR tests | security level
* -------------+--------------|------------+---------------
* (b) >= 6394 | >= 12788 | 3 | 256 bit
* (b) >= 3747 | >= 7494 | 3 | 192 bit
* (b) >= 1345 | >= 2690 | 4 | 128 bit
* (b) >= 1080 | >= 2160 | 5 | 128 bit
* (b) >= 852 | >= 1704 | 5 | 112 bit
* (b) >= 476 | >= 952 | 5 | 80 bit
* (b) >= 400 | >= 800 | 6 | 80 bit
* (b) >= 347 | >= 694 | 7 | 80 bit
* (b) >= 308 | >= 616 | 8 | 80 bit
* (b) >= 55 | >= 110 | 27 | 64 bit
* (b) >= 6 | >= 12 | 34 | 64 bit
*/
# define BN_prime_checks_for_size(b) ((b) >= 3747 ? 3 : \
(b) >= 1345 ? 4 : \
(b) >= 476 ? 5 : \
(b) >= 400 ? 6 : \
(b) >= 347 ? 7 : \
(b) >= 308 ? 8 : \
(b) >= 55 ? 27 : \
/* b >= 6 */ 34)
# define BN_num_bytes(a) ((BN_num_bits(a)+7)/8)
int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w);
int BN_is_zero(const BIGNUM *a);
int BN_is_one(const BIGNUM *a);
int BN_is_word(const BIGNUM *a, const BN_ULONG w);
int BN_is_odd(const BIGNUM *a);
# define BN_one(a) (BN_set_word((a),1))
void BN_zero_ex(BIGNUM *a);
# if OPENSSL_API_COMPAT >= 0x00908000L
# define BN_zero(a) BN_zero_ex(a)
# else
# define BN_zero(a) (BN_set_word((a),0))
# endif
const BIGNUM *BN_value_one(void);
char *BN_options(void);
BN_CTX *BN_CTX_new(void);
BN_CTX *BN_CTX_secure_new(void);
void BN_CTX_free(BN_CTX *c);
void BN_CTX_start(BN_CTX *ctx);
BIGNUM *BN_CTX_get(BN_CTX *ctx);
void BN_CTX_end(BN_CTX *ctx);
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_rand_range(BIGNUM *rnd, const BIGNUM *range);
int BN_priv_rand_range(BIGNUM *rnd, const BIGNUM *range);
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_pseudo_rand_range(BIGNUM *rnd, const BIGNUM *range);
int BN_num_bits(const BIGNUM *a);
int BN_num_bits_word(BN_ULONG l);
int BN_security_bits(int L, int N);
BIGNUM *BN_new(void);
BIGNUM *BN_secure_new(void);
void BN_clear_free(BIGNUM *a);
BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b);
void BN_swap(BIGNUM *a, BIGNUM *b);
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2bin(const BIGNUM *a, unsigned char *to);
int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen);
BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen);
BIGNUM *BN_mpi2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2mpi(const BIGNUM *a, unsigned char *to);
int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
/** BN_set_negative sets sign of a BIGNUM
* \param b pointer to the BIGNUM object
* \param n 0 if the BIGNUM b should be positive and a value != 0 otherwise
*/
void BN_set_negative(BIGNUM *b, int n);
/** BN_is_negative returns 1 if the BIGNUM is negative
* \param b pointer to the BIGNUM object
* \return 1 if a < 0 and 0 otherwise
*/
int BN_is_negative(const BIGNUM *b);
int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
BN_CTX *ctx);
# define BN_mod(rem,m,d,ctx) BN_div(NULL,(rem),(m),(d),(ctx))
int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx);
int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *m);
int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *m);
int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m);
int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m);
BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w);
BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w);
int BN_mul_word(BIGNUM *a, BN_ULONG w);
int BN_add_word(BIGNUM *a, BN_ULONG w);
int BN_sub_word(BIGNUM *a, BN_ULONG w);
int BN_set_word(BIGNUM *a, BN_ULONG w);
BN_ULONG BN_get_word(const BIGNUM *a);
int BN_cmp(const BIGNUM *a, const BIGNUM *b);
void BN_free(BIGNUM *a);
int BN_is_bit_set(const BIGNUM *a, int n);
int BN_lshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_lshift1(BIGNUM *r, const BIGNUM *a);
int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
int BN_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *in_mont);
int BN_mod_exp_mont_word(BIGNUM *r, BN_ULONG a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int BN_mod_exp2_mont(BIGNUM *r, const BIGNUM *a1, const BIGNUM *p1,
const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
int BN_mask_bits(BIGNUM *a, int n);
# ifndef OPENSSL_NO_STDIO
int BN_print_fp(FILE *fp, const BIGNUM *a);
# endif
int BN_print(BIO *bio, const BIGNUM *a);
int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx);
int BN_rshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_rshift1(BIGNUM *r, const BIGNUM *a);
void BN_clear(BIGNUM *a);
BIGNUM *BN_dup(const BIGNUM *a);
int BN_ucmp(const BIGNUM *a, const BIGNUM *b);
int BN_set_bit(BIGNUM *a, int n);
int BN_clear_bit(BIGNUM *a, int n);
char *BN_bn2hex(const BIGNUM *a);
char *BN_bn2dec(const BIGNUM *a);
int BN_hex2bn(BIGNUM **a, const char *str);
int BN_dec2bn(BIGNUM **a, const char *str);
int BN_asc2bn(BIGNUM **a, const char *str);
int BN_gcd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); /* returns
* -2 for
* error */
BIGNUM *BN_mod_inverse(BIGNUM *ret,
const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
BIGNUM *BN_mod_sqrt(BIGNUM *ret,
const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
void BN_consttime_swap(BN_ULONG swap, BIGNUM *a, BIGNUM *b, int nwords);
/* Deprecated versions */
DEPRECATEDIN_0_9_8(BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe,
const BIGNUM *add,
const BIGNUM *rem,
void (*callback) (int, int,
void *),
void *cb_arg))
DEPRECATEDIN_0_9_8(int
BN_is_prime(const BIGNUM *p, int nchecks,
void (*callback) (int, int, void *),
BN_CTX *ctx, void *cb_arg))
DEPRECATEDIN_0_9_8(int
BN_is_prime_fasttest(const BIGNUM *p, int nchecks,
void (*callback) (int, int, void *),
BN_CTX *ctx, void *cb_arg,
int do_trial_division))
/* Newer versions */
int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add,
const BIGNUM *rem, BN_GENCB *cb);
int BN_is_prime_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx, BN_GENCB *cb);
int BN_is_prime_fasttest_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx,
int do_trial_division, BN_GENCB *cb);
int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx);
int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2,
const BIGNUM *Xp, const BIGNUM *Xp1,
const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx,
BN_GENCB *cb);
int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1,
BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e,
BN_CTX *ctx, BN_GENCB *cb);
BN_MONT_CTX *BN_MONT_CTX_new(void);
int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
void BN_MONT_CTX_free(BN_MONT_CTX *mont);
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from);
BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock,
const BIGNUM *mod, BN_CTX *ctx);
/* BN_BLINDING flags */
# define BN_BLINDING_NO_UPDATE 0x00000001
# define BN_BLINDING_NO_RECREATE 0x00000002
BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod);
void BN_BLINDING_free(BN_BLINDING *b);
int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *);
int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b,
BN_CTX *);
int BN_BLINDING_is_current_thread(BN_BLINDING *b);
void BN_BLINDING_set_current_thread(BN_BLINDING *b);
int BN_BLINDING_lock(BN_BLINDING *b);
int BN_BLINDING_unlock(BN_BLINDING *b);
unsigned long BN_BLINDING_get_flags(const BN_BLINDING *);
void BN_BLINDING_set_flags(BN_BLINDING *, unsigned long);
BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b,
const BIGNUM *e, BIGNUM *m, BN_CTX *ctx,
int (*bn_mod_exp) (BIGNUM *r,
const BIGNUM *a,
const BIGNUM *p,
const BIGNUM *m,
BN_CTX *ctx,
BN_MONT_CTX *m_ctx),
BN_MONT_CTX *m_ctx);
DEPRECATEDIN_0_9_8(void BN_set_params(int mul, int high, int low, int mont))
DEPRECATEDIN_0_9_8(int BN_get_params(int which)) /* 0, mul, 1 high, 2 low, 3
* mont */
BN_RECP_CTX *BN_RECP_CTX_new(void);
void BN_RECP_CTX_free(BN_RECP_CTX *recp);
int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *rdiv, BN_CTX *ctx);
int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y,
BN_RECP_CTX *recp, BN_CTX *ctx);
int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
BN_RECP_CTX *recp, BN_CTX *ctx);
# ifndef OPENSSL_NO_EC2M
/*
* Functions for arithmetic over binary polynomials represented by BIGNUMs.
* The BIGNUM::neg property of BIGNUMs representing binary polynomials is
* ignored. Note that input arguments are not const so that their bit arrays
* can be expanded to the appropriate size if needed.
*/
/*
* r = a + b
*/
int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
# define BN_GF2m_sub(r, a, b) BN_GF2m_add(r, a, b)
/*
* r=a mod p
*/
int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p);
/* r = (a * b) mod p */
int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *p, BN_CTX *ctx);
/* r = (a * a) mod p */
int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
/* r = (1 / b) mod p */
int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx);
/* r = (a / b) mod p */
int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *p, BN_CTX *ctx);
/* r = (a ^ b) mod p */
int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *p, BN_CTX *ctx);
/* r = sqrt(a) mod p */
int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
BN_CTX *ctx);
/* r^2 + r = a mod p */
int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
BN_CTX *ctx);
# define BN_GF2m_cmp(a, b) BN_ucmp((a), (b))
/*-
* Some functions allow for representation of the irreducible polynomials
* as an unsigned int[], say p. The irreducible f(t) is then of the form:
* t^p[0] + t^p[1] + ... + t^p[k]
* where m = p[0] > p[1] > ... > p[k] = 0.
*/
/* r = a mod p */
int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[]);
/* r = (a * b) mod p */
int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const int p[], BN_CTX *ctx);
/* r = (a * a) mod p */
int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[],
BN_CTX *ctx);
/* r = (1 / b) mod p */
int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *b, const int p[],
BN_CTX *ctx);
/* r = (a / b) mod p */
int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const int p[], BN_CTX *ctx);
/* r = (a ^ b) mod p */
int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const int p[], BN_CTX *ctx);
/* r = sqrt(a) mod p */
int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a,
const int p[], BN_CTX *ctx);
/* r^2 + r = a mod p */
int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a,
const int p[], BN_CTX *ctx);
int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max);
int BN_GF2m_arr2poly(const int p[], BIGNUM *a);
# endif
/*
* faster mod functions for the 'NIST primes' 0 <= a < p^2
*/
int BN_nist_mod_192(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_224(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_256(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_384(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_521(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
const BIGNUM *BN_get0_nist_prime_192(void);
const BIGNUM *BN_get0_nist_prime_224(void);
const BIGNUM *BN_get0_nist_prime_256(void);
const BIGNUM *BN_get0_nist_prime_384(void);
const BIGNUM *BN_get0_nist_prime_521(void);
int (*BN_nist_mod_func(const BIGNUM *p)) (BIGNUM *r, const BIGNUM *a,
const BIGNUM *field, BN_CTX *ctx);
int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
const BIGNUM *priv, const unsigned char *message,
size_t message_len, BN_CTX *ctx);
/* Primes from RFC 2409 */
BIGNUM *BN_get_rfc2409_prime_768(BIGNUM *bn);
BIGNUM *BN_get_rfc2409_prime_1024(BIGNUM *bn);
/* Primes from RFC 3526 */
BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *bn);
# if OPENSSL_API_COMPAT < 0x10100000L
# define get_rfc2409_prime_768 BN_get_rfc2409_prime_768
# define get_rfc2409_prime_1024 BN_get_rfc2409_prime_1024
# define get_rfc3526_prime_1536 BN_get_rfc3526_prime_1536
# define get_rfc3526_prime_2048 BN_get_rfc3526_prime_2048
# define get_rfc3526_prime_3072 BN_get_rfc3526_prime_3072
# define get_rfc3526_prime_4096 BN_get_rfc3526_prime_4096
# define get_rfc3526_prime_6144 BN_get_rfc3526_prime_6144
# define get_rfc3526_prime_8192 BN_get_rfc3526_prime_8192
# endif
int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,100 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BNERR_H
# define HEADER_BNERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_BN_strings(void);
/*
* BN function codes.
*/
# define BN_F_BNRAND 127
# define BN_F_BNRAND_RANGE 138
# define BN_F_BN_BLINDING_CONVERT_EX 100
# define BN_F_BN_BLINDING_CREATE_PARAM 128
# define BN_F_BN_BLINDING_INVERT_EX 101
# define BN_F_BN_BLINDING_NEW 102
# define BN_F_BN_BLINDING_UPDATE 103
# define BN_F_BN_BN2DEC 104
# define BN_F_BN_BN2HEX 105
# define BN_F_BN_COMPUTE_WNAF 142
# define BN_F_BN_CTX_GET 116
# define BN_F_BN_CTX_NEW 106
# define BN_F_BN_CTX_START 129
# define BN_F_BN_DIV 107
# define BN_F_BN_DIV_RECP 130
# define BN_F_BN_EXP 123
# define BN_F_BN_EXPAND_INTERNAL 120
# define BN_F_BN_GENCB_NEW 143
# define BN_F_BN_GENERATE_DSA_NONCE 140
# define BN_F_BN_GENERATE_PRIME_EX 141
# define BN_F_BN_GF2M_MOD 131
# define BN_F_BN_GF2M_MOD_EXP 132
# define BN_F_BN_GF2M_MOD_MUL 133
# define BN_F_BN_GF2M_MOD_SOLVE_QUAD 134
# define BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR 135
# define BN_F_BN_GF2M_MOD_SQR 136
# define BN_F_BN_GF2M_MOD_SQRT 137
# define BN_F_BN_LSHIFT 145
# define BN_F_BN_MOD_EXP2_MONT 118
# define BN_F_BN_MOD_EXP_MONT 109
# define BN_F_BN_MOD_EXP_MONT_CONSTTIME 124
# define BN_F_BN_MOD_EXP_MONT_WORD 117
# define BN_F_BN_MOD_EXP_RECP 125
# define BN_F_BN_MOD_EXP_SIMPLE 126
# define BN_F_BN_MOD_INVERSE 110
# define BN_F_BN_MOD_INVERSE_NO_BRANCH 139
# define BN_F_BN_MOD_LSHIFT_QUICK 119
# define BN_F_BN_MOD_SQRT 121
# define BN_F_BN_MONT_CTX_NEW 149
# define BN_F_BN_MPI2BN 112
# define BN_F_BN_NEW 113
# define BN_F_BN_POOL_GET 147
# define BN_F_BN_RAND 114
# define BN_F_BN_RAND_RANGE 122
# define BN_F_BN_RECP_CTX_NEW 150
# define BN_F_BN_RSHIFT 146
# define BN_F_BN_SET_WORDS 144
# define BN_F_BN_STACK_PUSH 148
# define BN_F_BN_USUB 115
/*
* BN reason codes.
*/
# define BN_R_ARG2_LT_ARG3 100
# define BN_R_BAD_RECIPROCAL 101
# define BN_R_BIGNUM_TOO_LONG 114
# define BN_R_BITS_TOO_SMALL 118
# define BN_R_CALLED_WITH_EVEN_MODULUS 102
# define BN_R_DIV_BY_ZERO 103
# define BN_R_ENCODING_ERROR 104
# define BN_R_EXPAND_ON_STATIC_BIGNUM_DATA 105
# define BN_R_INPUT_NOT_REDUCED 110
# define BN_R_INVALID_LENGTH 106
# define BN_R_INVALID_RANGE 115
# define BN_R_INVALID_SHIFT 119
# define BN_R_NOT_A_SQUARE 111
# define BN_R_NOT_INITIALIZED 107
# define BN_R_NO_INVERSE 108
# define BN_R_NO_SOLUTION 116
# define BN_R_PRIVATE_KEY_TOO_LARGE 117
# define BN_R_P_IS_NOT_PRIME 112
# define BN_R_TOO_MANY_ITERATIONS 113
# define BN_R_TOO_MANY_TEMPORARY_VARIABLES 109
#endif

@ -0,0 +1,58 @@
/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BUFFER_H
# define HEADER_BUFFER_H
# include <openssl/ossl_typ.h>
# ifndef HEADER_CRYPTO_H
# include <openssl/crypto.h>
# endif
# include <openssl/buffererr.h>
#ifdef __cplusplus
extern "C" {
#endif
# include <stddef.h>
# include <sys/types.h>
/*
* These names are outdated as of OpenSSL 1.1; a future release
* will move them to be deprecated.
*/
# define BUF_strdup(s) OPENSSL_strdup(s)
# define BUF_strndup(s, size) OPENSSL_strndup(s, size)
# define BUF_memdup(data, size) OPENSSL_memdup(data, size)
# define BUF_strlcpy(dst, src, size) OPENSSL_strlcpy(dst, src, size)
# define BUF_strlcat(dst, src, size) OPENSSL_strlcat(dst, src, size)
# define BUF_strnlen(str, maxlen) OPENSSL_strnlen(str, maxlen)
struct buf_mem_st {
size_t length; /* current number of bytes */
char *data;
size_t max; /* size of buffer */
unsigned long flags;
};
# define BUF_MEM_FLAG_SECURE 0x01
BUF_MEM *BUF_MEM_new(void);
BUF_MEM *BUF_MEM_new_ex(unsigned long flags);
void BUF_MEM_free(BUF_MEM *a);
size_t BUF_MEM_grow(BUF_MEM *str, size_t len);
size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len);
void BUF_reverse(unsigned char *out, const unsigned char *in, size_t siz);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,34 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BUFERR_H
# define HEADER_BUFERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_BUF_strings(void);
/*
* BUF function codes.
*/
# define BUF_F_BUF_MEM_GROW 100
# define BUF_F_BUF_MEM_GROW_CLEAN 105
# define BUF_F_BUF_MEM_NEW 101
/*
* BUF reason codes.
*/
#endif

@ -0,0 +1,83 @@
/*
* Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CAMELLIA_H
# define HEADER_CAMELLIA_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CAMELLIA
# include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
# define CAMELLIA_ENCRYPT 1
# define CAMELLIA_DECRYPT 0
/*
* Because array size can't be a const in C, the following two are macros.
* Both sizes are in bytes.
*/
/* This should be a hidden type, but EVP requires that the size be known */
# define CAMELLIA_BLOCK_SIZE 16
# define CAMELLIA_TABLE_BYTE_LEN 272
# define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / 4)
typedef unsigned int KEY_TABLE_TYPE[CAMELLIA_TABLE_WORD_LEN]; /* to match
* with WORD */
struct camellia_key_st {
union {
double d; /* ensures 64-bit align */
KEY_TABLE_TYPE rd_key;
} u;
int grand_rounds;
};
typedef struct camellia_key_st CAMELLIA_KEY;
int Camellia_set_key(const unsigned char *userKey, const int bits,
CAMELLIA_KEY *key);
void Camellia_encrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key);
void Camellia_decrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key);
void Camellia_ecb_encrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key, const int enc);
void Camellia_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, const int enc);
void Camellia_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num, const int enc);
void Camellia_cfb1_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num, const int enc);
void Camellia_cfb8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num, const int enc);
void Camellia_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num);
void Camellia_ctr128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char ivec[CAMELLIA_BLOCK_SIZE],
unsigned char ecount_buf[CAMELLIA_BLOCK_SIZE],
unsigned int *num);
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,53 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CAST_H
# define HEADER_CAST_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CAST
# ifdef __cplusplus
extern "C" {
# endif
# define CAST_ENCRYPT 1
# define CAST_DECRYPT 0
# define CAST_LONG unsigned int
# define CAST_BLOCK 8
# define CAST_KEY_LENGTH 16
typedef struct cast_key_st {
CAST_LONG data[32];
int short_key; /* Use reduced rounds for short key */
} CAST_KEY;
void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data);
void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out,
const CAST_KEY *key, int enc);
void CAST_encrypt(CAST_LONG *data, const CAST_KEY *key);
void CAST_decrypt(CAST_LONG *data, const CAST_KEY *key);
void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out,
long length, const CAST_KEY *ks, unsigned char *iv,
int enc);
void CAST_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, const CAST_KEY *schedule,
unsigned char *ivec, int *num, int enc);
void CAST_ofb64_encrypt(const unsigned char *in, unsigned char *out,
long length, const CAST_KEY *schedule,
unsigned char *ivec, int *num);
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,41 @@
/*
* Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CMAC_H
# define HEADER_CMAC_H
# ifndef OPENSSL_NO_CMAC
#ifdef __cplusplus
extern "C" {
#endif
# include <openssl/evp.h>
/* Opaque */
typedef struct CMAC_CTX_st CMAC_CTX;
CMAC_CTX *CMAC_CTX_new(void);
void CMAC_CTX_cleanup(CMAC_CTX *ctx);
void CMAC_CTX_free(CMAC_CTX *ctx);
EVP_CIPHER_CTX *CMAC_CTX_get0_cipher_ctx(CMAC_CTX *ctx);
int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in);
int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen,
const EVP_CIPHER *cipher, ENGINE *impl);
int CMAC_Update(CMAC_CTX *ctx, const void *data, size_t dlen);
int CMAC_Final(CMAC_CTX *ctx, unsigned char *out, size_t *poutlen);
int CMAC_resume(CMAC_CTX *ctx);
#ifdef __cplusplus
}
#endif
# endif
#endif

@ -0,0 +1,339 @@
/*
* Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CMS_H
# define HEADER_CMS_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CMS
# include <openssl/x509.h>
# include <openssl/x509v3.h>
# include <openssl/cmserr.h>
# ifdef __cplusplus
extern "C" {
# endif
typedef struct CMS_ContentInfo_st CMS_ContentInfo;
typedef struct CMS_SignerInfo_st CMS_SignerInfo;
typedef struct CMS_CertificateChoices CMS_CertificateChoices;
typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice;
typedef struct CMS_RecipientInfo_st CMS_RecipientInfo;
typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest;
typedef struct CMS_Receipt_st CMS_Receipt;
typedef struct CMS_RecipientEncryptedKey_st CMS_RecipientEncryptedKey;
typedef struct CMS_OtherKeyAttribute_st CMS_OtherKeyAttribute;
DEFINE_STACK_OF(CMS_SignerInfo)
DEFINE_STACK_OF(CMS_RecipientEncryptedKey)
DEFINE_STACK_OF(CMS_RecipientInfo)
DEFINE_STACK_OF(CMS_RevocationInfoChoice)
DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo)
DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest)
DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo)
# define CMS_SIGNERINFO_ISSUER_SERIAL 0
# define CMS_SIGNERINFO_KEYIDENTIFIER 1
# define CMS_RECIPINFO_NONE -1
# define CMS_RECIPINFO_TRANS 0
# define CMS_RECIPINFO_AGREE 1
# define CMS_RECIPINFO_KEK 2
# define CMS_RECIPINFO_PASS 3
# define CMS_RECIPINFO_OTHER 4
/* S/MIME related flags */
# define CMS_TEXT 0x1
# define CMS_NOCERTS 0x2
# define CMS_NO_CONTENT_VERIFY 0x4
# define CMS_NO_ATTR_VERIFY 0x8
# define CMS_NOSIGS \
(CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY)
# define CMS_NOINTERN 0x10
# define CMS_NO_SIGNER_CERT_VERIFY 0x20
# define CMS_NOVERIFY 0x20
# define CMS_DETACHED 0x40
# define CMS_BINARY 0x80
# define CMS_NOATTR 0x100
# define CMS_NOSMIMECAP 0x200
# define CMS_NOOLDMIMETYPE 0x400
# define CMS_CRLFEOL 0x800
# define CMS_STREAM 0x1000
# define CMS_NOCRL 0x2000
# define CMS_PARTIAL 0x4000
# define CMS_REUSE_DIGEST 0x8000
# define CMS_USE_KEYID 0x10000
# define CMS_DEBUG_DECRYPT 0x20000
# define CMS_KEY_PARAM 0x40000
# define CMS_ASCIICRLF 0x80000
const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms);
BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont);
int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio);
ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms);
int CMS_is_detached(CMS_ContentInfo *cms);
int CMS_set_detached(CMS_ContentInfo *cms, int detached);
# ifdef HEADER_PEM_H
DECLARE_PEM_rw_const(CMS, CMS_ContentInfo)
# endif
int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms);
CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms);
int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms);
BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms);
int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags);
int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in,
int flags);
CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont);
int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags);
int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont,
unsigned int flags);
CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey,
STACK_OF(X509) *certs, BIO *data,
unsigned int flags);
CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si,
X509 *signcert, EVP_PKEY *pkey,
STACK_OF(X509) *certs, unsigned int flags);
int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags);
CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags);
int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
unsigned int flags);
CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md,
unsigned int flags);
int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms,
const unsigned char *key, size_t keylen,
BIO *dcont, BIO *out, unsigned int flags);
CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher,
const unsigned char *key,
size_t keylen, unsigned int flags);
int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph,
const unsigned char *key, size_t keylen);
int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs,
X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags);
int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms,
STACK_OF(X509) *certs,
X509_STORE *store, unsigned int flags);
STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms);
CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in,
const EVP_CIPHER *cipher, unsigned int flags);
int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert,
BIO *dcont, BIO *out, unsigned int flags);
int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert);
int CMS_decrypt_set1_key(CMS_ContentInfo *cms,
unsigned char *key, size_t keylen,
const unsigned char *id, size_t idlen);
int CMS_decrypt_set1_password(CMS_ContentInfo *cms,
unsigned char *pass, ossl_ssize_t passlen);
STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms);
int CMS_RecipientInfo_type(CMS_RecipientInfo *ri);
EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri);
CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher);
CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms,
X509 *recip, unsigned int flags);
int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey);
int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert);
int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
EVP_PKEY **pk, X509 **recip,
X509_ALGOR **palg);
int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
ASN1_OCTET_STRING **keyid,
X509_NAME **issuer,
ASN1_INTEGER **sno);
CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
unsigned char *key, size_t keylen,
unsigned char *id, size_t idlen,
ASN1_GENERALIZEDTIME *date,
ASN1_OBJECT *otherTypeId,
ASN1_TYPE *otherType);
int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
X509_ALGOR **palg,
ASN1_OCTET_STRING **pid,
ASN1_GENERALIZEDTIME **pdate,
ASN1_OBJECT **potherid,
ASN1_TYPE **pothertype);
int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
unsigned char *key, size_t keylen);
int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
const unsigned char *id, size_t idlen);
int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri,
unsigned char *pass,
ossl_ssize_t passlen);
CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
int iter, int wrap_nid,
int pbe_nid,
unsigned char *pass,
ossl_ssize_t passlen,
const EVP_CIPHER *kekciph);
int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri);
int CMS_RecipientInfo_encrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri);
int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
unsigned int flags);
CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags);
int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid);
const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms);
CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms);
int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert);
int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert);
STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms);
CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms);
int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl);
int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl);
STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms);
int CMS_SignedData_init(CMS_ContentInfo *cms);
CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
unsigned int flags);
EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si);
EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si);
STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms);
void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer);
int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
ASN1_OCTET_STRING **keyid,
X509_NAME **issuer, ASN1_INTEGER **sno);
int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert);
int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs,
unsigned int flags);
void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
X509 **signer, X509_ALGOR **pdig,
X509_ALGOR **psig);
ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si);
int CMS_SignerInfo_sign(CMS_SignerInfo *si);
int CMS_SignerInfo_verify(CMS_SignerInfo *si);
int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain);
int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs);
int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
int algnid, int keysize);
int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap);
int CMS_signed_get_attr_count(const CMS_SignerInfo *si);
int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid,
int lastpos);
int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj,
int lastpos);
X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc);
X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc);
int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr);
int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si,
const ASN1_OBJECT *obj, int type,
const void *bytes, int len);
int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si,
int nid, int type,
const void *bytes, int len);
int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si,
const char *attrname, int type,
const void *bytes, int len);
void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *oid,
int lastpos, int type);
int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si);
int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid,
int lastpos);
int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si,
const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc);
X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc);
int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr);
int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si,
const ASN1_OBJECT *obj, int type,
const void *bytes, int len);
int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si,
int nid, int type,
const void *bytes, int len);
int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si,
const char *attrname, int type,
const void *bytes, int len);
void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid,
int lastpos, int type);
int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr);
CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen,
int allorfirst,
STACK_OF(GENERAL_NAMES)
*receiptList, STACK_OF(GENERAL_NAMES)
*receiptsTo);
int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr);
void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr,
ASN1_STRING **pcid,
int *pallorfirst,
STACK_OF(GENERAL_NAMES) **plist,
STACK_OF(GENERAL_NAMES) **prto);
int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
X509_ALGOR **palg,
ASN1_OCTET_STRING **pukm);
STACK_OF(CMS_RecipientEncryptedKey)
*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri);
int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
X509_ALGOR **pubalg,
ASN1_BIT_STRING **pubkey,
ASN1_OCTET_STRING **keyid,
X509_NAME **issuer,
ASN1_INTEGER **sno);
int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert);
int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
ASN1_OCTET_STRING **keyid,
ASN1_GENERALIZEDTIME **tm,
CMS_OtherKeyAttribute **other,
X509_NAME **issuer, ASN1_INTEGER **sno);
int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
X509 *cert);
int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk);
EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri);
int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri,
CMS_RecipientEncryptedKey *rek);
int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg,
ASN1_OCTET_STRING *ukm, int keylen);
/* Backward compatibility for spelling errors. */
# define CMS_R_UNKNOWN_DIGEST_ALGORITM CMS_R_UNKNOWN_DIGEST_ALGORITHM
# define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \
CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,202 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CMSERR_H
# define HEADER_CMSERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CMS
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_CMS_strings(void);
/*
* CMS function codes.
*/
# define CMS_F_CHECK_CONTENT 99
# define CMS_F_CMS_ADD0_CERT 164
# define CMS_F_CMS_ADD0_RECIPIENT_KEY 100
# define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165
# define CMS_F_CMS_ADD1_RECEIPTREQUEST 158
# define CMS_F_CMS_ADD1_RECIPIENT_CERT 101
# define CMS_F_CMS_ADD1_SIGNER 102
# define CMS_F_CMS_ADD1_SIGNINGTIME 103
# define CMS_F_CMS_COMPRESS 104
# define CMS_F_CMS_COMPRESSEDDATA_CREATE 105
# define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106
# define CMS_F_CMS_COPY_CONTENT 107
# define CMS_F_CMS_COPY_MESSAGEDIGEST 108
# define CMS_F_CMS_DATA 109
# define CMS_F_CMS_DATAFINAL 110
# define CMS_F_CMS_DATAINIT 111
# define CMS_F_CMS_DECRYPT 112
# define CMS_F_CMS_DECRYPT_SET1_KEY 113
# define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166
# define CMS_F_CMS_DECRYPT_SET1_PKEY 114
# define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115
# define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116
# define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117
# define CMS_F_CMS_DIGEST_VERIFY 118
# define CMS_F_CMS_ENCODE_RECEIPT 161
# define CMS_F_CMS_ENCRYPT 119
# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT 179
# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120
# define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121
# define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122
# define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123
# define CMS_F_CMS_ENVELOPEDDATA_CREATE 124
# define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125
# define CMS_F_CMS_ENVELOPED_DATA_INIT 126
# define CMS_F_CMS_ENV_ASN1_CTRL 171
# define CMS_F_CMS_FINAL 127
# define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128
# define CMS_F_CMS_GET0_CONTENT 129
# define CMS_F_CMS_GET0_ECONTENT_TYPE 130
# define CMS_F_CMS_GET0_ENVELOPED 131
# define CMS_F_CMS_GET0_REVOCATION_CHOICES 132
# define CMS_F_CMS_GET0_SIGNED 133
# define CMS_F_CMS_MSGSIGDIGEST_ADD1 162
# define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159
# define CMS_F_CMS_RECEIPT_VERIFY 160
# define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134
# define CMS_F_CMS_RECIPIENTINFO_ENCRYPT 169
# define CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT 178
# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG 175
# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 173
# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS 172
# define CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 174
# define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135
# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136
# define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137
# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138
# define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139
# define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140
# define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141
# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142
# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143
# define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167
# define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144
# define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168
# define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145
# define CMS_F_CMS_SD_ASN1_CTRL 170
# define CMS_F_CMS_SET1_IAS 176
# define CMS_F_CMS_SET1_KEYID 177
# define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146
# define CMS_F_CMS_SET_DETACHED 147
# define CMS_F_CMS_SIGN 148
# define CMS_F_CMS_SIGNED_DATA_INIT 149
# define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150
# define CMS_F_CMS_SIGNERINFO_SIGN 151
# define CMS_F_CMS_SIGNERINFO_VERIFY 152
# define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153
# define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154
# define CMS_F_CMS_SIGN_RECEIPT 163
# define CMS_F_CMS_SI_CHECK_ATTRIBUTES 183
# define CMS_F_CMS_STREAM 155
# define CMS_F_CMS_UNCOMPRESS 156
# define CMS_F_CMS_VERIFY 157
# define CMS_F_KEK_UNWRAP_KEY 180
/*
* CMS reason codes.
*/
# define CMS_R_ADD_SIGNER_ERROR 99
# define CMS_R_ATTRIBUTE_ERROR 161
# define CMS_R_CERTIFICATE_ALREADY_PRESENT 175
# define CMS_R_CERTIFICATE_HAS_NO_KEYID 160
# define CMS_R_CERTIFICATE_VERIFY_ERROR 100
# define CMS_R_CIPHER_INITIALISATION_ERROR 101
# define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102
# define CMS_R_CMS_DATAFINAL_ERROR 103
# define CMS_R_CMS_LIB 104
# define CMS_R_CONTENTIDENTIFIER_MISMATCH 170
# define CMS_R_CONTENT_NOT_FOUND 105
# define CMS_R_CONTENT_TYPE_MISMATCH 171
# define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106
# define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107
# define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108
# define CMS_R_CONTENT_VERIFY_ERROR 109
# define CMS_R_CTRL_ERROR 110
# define CMS_R_CTRL_FAILURE 111
# define CMS_R_DECRYPT_ERROR 112
# define CMS_R_ERROR_GETTING_PUBLIC_KEY 113
# define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114
# define CMS_R_ERROR_SETTING_KEY 115
# define CMS_R_ERROR_SETTING_RECIPIENTINFO 116
# define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117
# define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176
# define CMS_R_INVALID_KEY_LENGTH 118
# define CMS_R_MD_BIO_INIT_ERROR 119
# define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120
# define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121
# define CMS_R_MSGSIGDIGEST_ERROR 172
# define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162
# define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163
# define CMS_R_NEED_ONE_SIGNER 164
# define CMS_R_NOT_A_SIGNED_RECEIPT 165
# define CMS_R_NOT_ENCRYPTED_DATA 122
# define CMS_R_NOT_KEK 123
# define CMS_R_NOT_KEY_AGREEMENT 181
# define CMS_R_NOT_KEY_TRANSPORT 124
# define CMS_R_NOT_PWRI 177
# define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125
# define CMS_R_NO_CIPHER 126
# define CMS_R_NO_CONTENT 127
# define CMS_R_NO_CONTENT_TYPE 173
# define CMS_R_NO_DEFAULT_DIGEST 128
# define CMS_R_NO_DIGEST_SET 129
# define CMS_R_NO_KEY 130
# define CMS_R_NO_KEY_OR_CERT 174
# define CMS_R_NO_MATCHING_DIGEST 131
# define CMS_R_NO_MATCHING_RECIPIENT 132
# define CMS_R_NO_MATCHING_SIGNATURE 166
# define CMS_R_NO_MSGSIGDIGEST 167
# define CMS_R_NO_PASSWORD 178
# define CMS_R_NO_PRIVATE_KEY 133
# define CMS_R_NO_PUBLIC_KEY 134
# define CMS_R_NO_RECEIPT_REQUEST 168
# define CMS_R_NO_SIGNERS 135
# define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136
# define CMS_R_RECEIPT_DECODE_ERROR 169
# define CMS_R_RECIPIENT_ERROR 137
# define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138
# define CMS_R_SIGNFINAL_ERROR 139
# define CMS_R_SMIME_TEXT_ERROR 140
# define CMS_R_STORE_INIT_ERROR 141
# define CMS_R_TYPE_NOT_COMPRESSED_DATA 142
# define CMS_R_TYPE_NOT_DATA 143
# define CMS_R_TYPE_NOT_DIGESTED_DATA 144
# define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145
# define CMS_R_TYPE_NOT_ENVELOPED_DATA 146
# define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147
# define CMS_R_UNKNOWN_CIPHER 148
# define CMS_R_UNKNOWN_DIGEST_ALGORITHM 149
# define CMS_R_UNKNOWN_ID 150
# define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151
# define CMS_R_UNSUPPORTED_CONTENT_TYPE 152
# define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153
# define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179
# define CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155
# define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154
# define CMS_R_UNSUPPORTED_TYPE 156
# define CMS_R_UNWRAP_ERROR 157
# define CMS_R_UNWRAP_FAILURE 180
# define CMS_R_VERIFICATION_FAILURE 158
# define CMS_R_WRAP_ERROR 159
# endif
#endif

@ -0,0 +1,53 @@
/*
* Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_COMP_H
# define HEADER_COMP_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_COMP
# include <openssl/crypto.h>
# include <openssl/comperr.h>
# ifdef __cplusplus
extern "C" {
# endif
COMP_CTX *COMP_CTX_new(COMP_METHOD *meth);
const COMP_METHOD *COMP_CTX_get_method(const COMP_CTX *ctx);
int COMP_CTX_get_type(const COMP_CTX* comp);
int COMP_get_type(const COMP_METHOD *meth);
const char *COMP_get_name(const COMP_METHOD *meth);
void COMP_CTX_free(COMP_CTX *ctx);
int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen,
unsigned char *in, int ilen);
int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen,
unsigned char *in, int ilen);
COMP_METHOD *COMP_zlib(void);
#if OPENSSL_API_COMPAT < 0x10100000L
#define COMP_zlib_cleanup() while(0) continue
#endif
# ifdef HEADER_BIO_H
# ifdef ZLIB
const BIO_METHOD *BIO_f_zlib(void);
# endif
# endif
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,44 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_COMPERR_H
# define HEADER_COMPERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_COMP
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_COMP_strings(void);
/*
* COMP function codes.
*/
# define COMP_F_BIO_ZLIB_FLUSH 99
# define COMP_F_BIO_ZLIB_NEW 100
# define COMP_F_BIO_ZLIB_READ 101
# define COMP_F_BIO_ZLIB_WRITE 102
# define COMP_F_COMP_CTX_NEW 103
/*
* COMP reason codes.
*/
# define COMP_R_ZLIB_DEFLATE_ERROR 99
# define COMP_R_ZLIB_INFLATE_ERROR 100
# define COMP_R_ZLIB_NOT_SUPPORTED 101
# endif
#endif

@ -0,0 +1,168 @@
/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CONF_H
# define HEADER_CONF_H
# include <openssl/bio.h>
# include <openssl/lhash.h>
# include <openssl/safestack.h>
# include <openssl/e_os2.h>
# include <openssl/ossl_typ.h>
# include <openssl/conferr.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
char *section;
char *name;
char *value;
} CONF_VALUE;
DEFINE_STACK_OF(CONF_VALUE)
DEFINE_LHASH_OF(CONF_VALUE);
struct conf_st;
struct conf_method_st;
typedef struct conf_method_st CONF_METHOD;
struct conf_method_st {
const char *name;
CONF *(*create) (CONF_METHOD *meth);
int (*init) (CONF *conf);
int (*destroy) (CONF *conf);
int (*destroy_data) (CONF *conf);
int (*load_bio) (CONF *conf, BIO *bp, long *eline);
int (*dump) (const CONF *conf, BIO *bp);
int (*is_number) (const CONF *conf, char c);
int (*to_int) (const CONF *conf, char c);
int (*load) (CONF *conf, const char *name, long *eline);
};
/* Module definitions */
typedef struct conf_imodule_st CONF_IMODULE;
typedef struct conf_module_st CONF_MODULE;
DEFINE_STACK_OF(CONF_MODULE)
DEFINE_STACK_OF(CONF_IMODULE)
/* DSO module function typedefs */
typedef int conf_init_func (CONF_IMODULE *md, const CONF *cnf);
typedef void conf_finish_func (CONF_IMODULE *md);
# define CONF_MFLAGS_IGNORE_ERRORS 0x1
# define CONF_MFLAGS_IGNORE_RETURN_CODES 0x2
# define CONF_MFLAGS_SILENT 0x4
# define CONF_MFLAGS_NO_DSO 0x8
# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10
# define CONF_MFLAGS_DEFAULT_SECTION 0x20
int CONF_set_default_method(CONF_METHOD *meth);
void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash);
LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file,
long *eline);
# ifndef OPENSSL_NO_STDIO
LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp,
long *eline);
# endif
LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp,
long *eline);
STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf,
const char *section);
char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group,
const char *name);
long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group,
const char *name);
void CONF_free(LHASH_OF(CONF_VALUE) *conf);
#ifndef OPENSSL_NO_STDIO
int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out);
#endif
int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out);
DEPRECATEDIN_1_1_0(void OPENSSL_config(const char *config_name))
#if OPENSSL_API_COMPAT < 0x10100000L
# define OPENSSL_no_config() \
OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, NULL)
#endif
/*
* New conf code. The semantics are different from the functions above. If
* that wasn't the case, the above functions would have been replaced
*/
struct conf_st {
CONF_METHOD *meth;
void *meth_data;
LHASH_OF(CONF_VALUE) *data;
};
CONF *NCONF_new(CONF_METHOD *meth);
CONF_METHOD *NCONF_default(void);
CONF_METHOD *NCONF_WIN32(void);
void NCONF_free(CONF *conf);
void NCONF_free_data(CONF *conf);
int NCONF_load(CONF *conf, const char *file, long *eline);
# ifndef OPENSSL_NO_STDIO
int NCONF_load_fp(CONF *conf, FILE *fp, long *eline);
# endif
int NCONF_load_bio(CONF *conf, BIO *bp, long *eline);
STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf,
const char *section);
char *NCONF_get_string(const CONF *conf, const char *group, const char *name);
int NCONF_get_number_e(const CONF *conf, const char *group, const char *name,
long *result);
#ifndef OPENSSL_NO_STDIO
int NCONF_dump_fp(const CONF *conf, FILE *out);
#endif
int NCONF_dump_bio(const CONF *conf, BIO *out);
#define NCONF_get_number(c,g,n,r) NCONF_get_number_e(c,g,n,r)
/* Module functions */
int CONF_modules_load(const CONF *cnf, const char *appname,
unsigned long flags);
int CONF_modules_load_file(const char *filename, const char *appname,
unsigned long flags);
void CONF_modules_unload(int all);
void CONF_modules_finish(void);
#if OPENSSL_API_COMPAT < 0x10100000L
# define CONF_modules_free() while(0) continue
#endif
int CONF_module_add(const char *name, conf_init_func *ifunc,
conf_finish_func *ffunc);
const char *CONF_imodule_get_name(const CONF_IMODULE *md);
const char *CONF_imodule_get_value(const CONF_IMODULE *md);
void *CONF_imodule_get_usr_data(const CONF_IMODULE *md);
void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data);
CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md);
unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md);
void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags);
void *CONF_module_get_usr_data(CONF_MODULE *pmod);
void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data);
char *CONF_get1_default_config_file(void);
int CONF_parse_list(const char *list, int sep, int nospc,
int (*list_cb) (const char *elem, int len, void *usr),
void *arg);
void OPENSSL_load_builtin_modules(void);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,40 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CONF_API_H
# define HEADER_CONF_API_H
# include <openssl/lhash.h>
# include <openssl/conf.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Up until OpenSSL 0.9.5a, this was new_section */
CONF_VALUE *_CONF_new_section(CONF *conf, const char *section);
/* Up until OpenSSL 0.9.5a, this was get_section */
CONF_VALUE *_CONF_get_section(const CONF *conf, const char *section);
/* Up until OpenSSL 0.9.5a, this was CONF_get_section */
STACK_OF(CONF_VALUE) *_CONF_get_section_values(const CONF *conf,
const char *section);
int _CONF_add_string(CONF *conf, CONF_VALUE *section, CONF_VALUE *value);
char *_CONF_get_string(const CONF *conf, const char *section,
const char *name);
long _CONF_get_number(const CONF *conf, const char *section,
const char *name);
int _CONF_new_data(CONF *conf);
void _CONF_free_data(CONF *conf);
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,76 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CONFERR_H
# define HEADER_CONFERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_CONF_strings(void);
/*
* CONF function codes.
*/
# define CONF_F_CONF_DUMP_FP 104
# define CONF_F_CONF_LOAD 100
# define CONF_F_CONF_LOAD_FP 103
# define CONF_F_CONF_PARSE_LIST 119
# define CONF_F_DEF_LOAD 120
# define CONF_F_DEF_LOAD_BIO 121
# define CONF_F_GET_NEXT_FILE 107
# define CONF_F_MODULE_ADD 122
# define CONF_F_MODULE_INIT 115
# define CONF_F_MODULE_LOAD_DSO 117
# define CONF_F_MODULE_RUN 118
# define CONF_F_NCONF_DUMP_BIO 105
# define CONF_F_NCONF_DUMP_FP 106
# define CONF_F_NCONF_GET_NUMBER_E 112
# define CONF_F_NCONF_GET_SECTION 108
# define CONF_F_NCONF_GET_STRING 109
# define CONF_F_NCONF_LOAD 113
# define CONF_F_NCONF_LOAD_BIO 110
# define CONF_F_NCONF_LOAD_FP 114
# define CONF_F_NCONF_NEW 111
# define CONF_F_PROCESS_INCLUDE 116
# define CONF_F_SSL_MODULE_INIT 123
# define CONF_F_STR_COPY 101
/*
* CONF reason codes.
*/
# define CONF_R_ERROR_LOADING_DSO 110
# define CONF_R_LIST_CANNOT_BE_NULL 115
# define CONF_R_MISSING_CLOSE_SQUARE_BRACKET 100
# define CONF_R_MISSING_EQUAL_SIGN 101
# define CONF_R_MISSING_INIT_FUNCTION 112
# define CONF_R_MODULE_INITIALIZATION_ERROR 109
# define CONF_R_NO_CLOSE_BRACE 102
# define CONF_R_NO_CONF 105
# define CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE 106
# define CONF_R_NO_SECTION 107
# define CONF_R_NO_SUCH_FILE 114
# define CONF_R_NO_VALUE 108
# define CONF_R_NUMBER_TOO_LARGE 121
# define CONF_R_RECURSIVE_DIRECTORY_INCLUDE 111
# define CONF_R_SSL_COMMAND_SECTION_EMPTY 117
# define CONF_R_SSL_COMMAND_SECTION_NOT_FOUND 118
# define CONF_R_SSL_SECTION_EMPTY 119
# define CONF_R_SSL_SECTION_NOT_FOUND 120
# define CONF_R_UNABLE_TO_CREATE_NEW_SECTION 103
# define CONF_R_UNKNOWN_MODULE_NAME 113
# define CONF_R_VARIABLE_EXPANSION_TOO_LONG 116
# define CONF_R_VARIABLE_HAS_NO_VALUE 104
#endif

@ -0,0 +1,445 @@
/*
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CRYPTO_H
# define HEADER_CRYPTO_H
# include <stdlib.h>
# include <time.h>
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_STDIO
# include <stdio.h>
# endif
# include <openssl/safestack.h>
# include <openssl/opensslv.h>
# include <openssl/ossl_typ.h>
# include <openssl/opensslconf.h>
# include <openssl/cryptoerr.h>
# ifdef CHARSET_EBCDIC
# include <openssl/ebcdic.h>
# endif
/*
* Resolve problems on some operating systems with symbol names that clash
* one way or another
*/
# include <openssl/symhacks.h>
# if OPENSSL_API_COMPAT < 0x10100000L
# include <openssl/opensslv.h>
# endif
#ifdef __cplusplus
extern "C" {
#endif
# if OPENSSL_API_COMPAT < 0x10100000L
# define SSLeay OpenSSL_version_num
# define SSLeay_version OpenSSL_version
# define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
# define SSLEAY_VERSION OPENSSL_VERSION
# define SSLEAY_CFLAGS OPENSSL_CFLAGS
# define SSLEAY_BUILT_ON OPENSSL_BUILT_ON
# define SSLEAY_PLATFORM OPENSSL_PLATFORM
# define SSLEAY_DIR OPENSSL_DIR
/*
* Old type for allocating dynamic locks. No longer used. Use the new thread
* API instead.
*/
typedef struct {
int dummy;
} CRYPTO_dynlock;
# endif /* OPENSSL_API_COMPAT */
typedef void CRYPTO_RWLOCK;
CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void);
int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock);
int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock);
int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock);
void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock);
int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock);
/*
* The following can be used to detect memory leaks in the library. If
* used, it turns on malloc checking
*/
# define CRYPTO_MEM_CHECK_OFF 0x0 /* Control only */
# define CRYPTO_MEM_CHECK_ON 0x1 /* Control and mode bit */
# define CRYPTO_MEM_CHECK_ENABLE 0x2 /* Control and mode bit */
# define CRYPTO_MEM_CHECK_DISABLE 0x3 /* Control only */
struct crypto_ex_data_st {
STACK_OF(void) *sk;
};
DEFINE_STACK_OF(void)
/*
* Per class, we have a STACK of function pointers.
*/
# define CRYPTO_EX_INDEX_SSL 0
# define CRYPTO_EX_INDEX_SSL_CTX 1
# define CRYPTO_EX_INDEX_SSL_SESSION 2
# define CRYPTO_EX_INDEX_X509 3
# define CRYPTO_EX_INDEX_X509_STORE 4
# define CRYPTO_EX_INDEX_X509_STORE_CTX 5
# define CRYPTO_EX_INDEX_DH 6
# define CRYPTO_EX_INDEX_DSA 7
# define CRYPTO_EX_INDEX_EC_KEY 8
# define CRYPTO_EX_INDEX_RSA 9
# define CRYPTO_EX_INDEX_ENGINE 10
# define CRYPTO_EX_INDEX_UI 11
# define CRYPTO_EX_INDEX_BIO 12
# define CRYPTO_EX_INDEX_APP 13
# define CRYPTO_EX_INDEX_UI_METHOD 14
# define CRYPTO_EX_INDEX_DRBG 15
# define CRYPTO_EX_INDEX__COUNT 16
/* No longer needed, so this is a no-op */
#define OPENSSL_malloc_init() while(0) continue
int CRYPTO_mem_ctrl(int mode);
# define OPENSSL_malloc(num) \
CRYPTO_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_zalloc(num) \
CRYPTO_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_realloc(addr, num) \
CRYPTO_realloc(addr, num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_clear_realloc(addr, old_num, num) \
CRYPTO_clear_realloc(addr, old_num, num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_clear_free(addr, num) \
CRYPTO_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_free(addr) \
CRYPTO_free(addr, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_memdup(str, s) \
CRYPTO_memdup((str), s, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_strdup(str) \
CRYPTO_strdup(str, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_strndup(str, n) \
CRYPTO_strndup(str, n, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_secure_malloc(num) \
CRYPTO_secure_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_secure_zalloc(num) \
CRYPTO_secure_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_secure_free(addr) \
CRYPTO_secure_free(addr, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_secure_clear_free(addr, num) \
CRYPTO_secure_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_secure_actual_size(ptr) \
CRYPTO_secure_actual_size(ptr)
size_t OPENSSL_strlcpy(char *dst, const char *src, size_t siz);
size_t OPENSSL_strlcat(char *dst, const char *src, size_t siz);
size_t OPENSSL_strnlen(const char *str, size_t maxlen);
char *OPENSSL_buf2hexstr(const unsigned char *buffer, long len);
unsigned char *OPENSSL_hexstr2buf(const char *str, long *len);
int OPENSSL_hexchar2int(unsigned char c);
# define OPENSSL_MALLOC_MAX_NELEMS(type) (((1U<<(sizeof(int)*8-1))-1)/sizeof(type))
unsigned long OpenSSL_version_num(void);
const char *OpenSSL_version(int type);
# define OPENSSL_VERSION 0
# define OPENSSL_CFLAGS 1
# define OPENSSL_BUILT_ON 2
# define OPENSSL_PLATFORM 3
# define OPENSSL_DIR 4
# define OPENSSL_ENGINES_DIR 5
int OPENSSL_issetugid(void);
typedef void CRYPTO_EX_new (void *parent, void *ptr, CRYPTO_EX_DATA *ad,
int idx, long argl, void *argp);
typedef void CRYPTO_EX_free (void *parent, void *ptr, CRYPTO_EX_DATA *ad,
int idx, long argl, void *argp);
typedef int CRYPTO_EX_dup (CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
void *from_d, int idx, long argl, void *argp);
__owur int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
/* No longer use an index. */
int CRYPTO_free_ex_index(int class_index, int idx);
/*
* Initialise/duplicate/free CRYPTO_EX_DATA variables corresponding to a
* given class (invokes whatever per-class callbacks are applicable)
*/
int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
const CRYPTO_EX_DATA *from);
void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
/*
* Get/set data in a CRYPTO_EX_DATA variable corresponding to a particular
* index (relative to the class type involved)
*/
int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val);
void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx);
# if OPENSSL_API_COMPAT < 0x10100000L
/*
* This function cleans up all "ex_data" state. It mustn't be called under
* potential race-conditions.
*/
# define CRYPTO_cleanup_all_ex_data() while(0) continue
/*
* The old locking functions have been removed completely without compatibility
* macros. This is because the old functions either could not properly report
* errors, or the returned error values were not clearly documented.
* Replacing the locking functions with no-ops would cause race condition
* issues in the affected applications. It is far better for them to fail at
* compile time.
* On the other hand, the locking callbacks are no longer used. Consequently,
* the callback management functions can be safely replaced with no-op macros.
*/
# define CRYPTO_num_locks() (1)
# define CRYPTO_set_locking_callback(func)
# define CRYPTO_get_locking_callback() (NULL)
# define CRYPTO_set_add_lock_callback(func)
# define CRYPTO_get_add_lock_callback() (NULL)
/*
* These defines where used in combination with the old locking callbacks,
* they are not called anymore, but old code that's not called might still
* use them.
*/
# define CRYPTO_LOCK 1
# define CRYPTO_UNLOCK 2
# define CRYPTO_READ 4
# define CRYPTO_WRITE 8
/* This structure is no longer used */
typedef struct crypto_threadid_st {
int dummy;
} CRYPTO_THREADID;
/* Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks */
# define CRYPTO_THREADID_set_numeric(id, val)
# define CRYPTO_THREADID_set_pointer(id, ptr)
# define CRYPTO_THREADID_set_callback(threadid_func) (0)
# define CRYPTO_THREADID_get_callback() (NULL)
# define CRYPTO_THREADID_current(id)
# define CRYPTO_THREADID_cmp(a, b) (-1)
# define CRYPTO_THREADID_cpy(dest, src)
# define CRYPTO_THREADID_hash(id) (0UL)
# if OPENSSL_API_COMPAT < 0x10000000L
# define CRYPTO_set_id_callback(func)
# define CRYPTO_get_id_callback() (NULL)
# define CRYPTO_thread_id() (0UL)
# endif /* OPENSSL_API_COMPAT < 0x10000000L */
# define CRYPTO_set_dynlock_create_callback(dyn_create_function)
# define CRYPTO_set_dynlock_lock_callback(dyn_lock_function)
# define CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function)
# define CRYPTO_get_dynlock_create_callback() (NULL)
# define CRYPTO_get_dynlock_lock_callback() (NULL)
# define CRYPTO_get_dynlock_destroy_callback() (NULL)
# endif /* OPENSSL_API_COMPAT < 0x10100000L */
int CRYPTO_set_mem_functions(
void *(*m) (size_t, const char *, int),
void *(*r) (void *, size_t, const char *, int),
void (*f) (void *, const char *, int));
int CRYPTO_set_mem_debug(int flag);
void CRYPTO_get_mem_functions(
void *(**m) (size_t, const char *, int),
void *(**r) (void *, size_t, const char *, int),
void (**f) (void *, const char *, int));
void *CRYPTO_malloc(size_t num, const char *file, int line);
void *CRYPTO_zalloc(size_t num, const char *file, int line);
void *CRYPTO_memdup(const void *str, size_t siz, const char *file, int line);
char *CRYPTO_strdup(const char *str, const char *file, int line);
char *CRYPTO_strndup(const char *str, size_t s, const char *file, int line);
void CRYPTO_free(void *ptr, const char *file, int line);
void CRYPTO_clear_free(void *ptr, size_t num, const char *file, int line);
void *CRYPTO_realloc(void *addr, size_t num, const char *file, int line);
void *CRYPTO_clear_realloc(void *addr, size_t old_num, size_t num,
const char *file, int line);
int CRYPTO_secure_malloc_init(size_t sz, int minsize);
int CRYPTO_secure_malloc_done(void);
void *CRYPTO_secure_malloc(size_t num, const char *file, int line);
void *CRYPTO_secure_zalloc(size_t num, const char *file, int line);
void CRYPTO_secure_free(void *ptr, const char *file, int line);
void CRYPTO_secure_clear_free(void *ptr, size_t num,
const char *file, int line);
int CRYPTO_secure_allocated(const void *ptr);
int CRYPTO_secure_malloc_initialized(void);
size_t CRYPTO_secure_actual_size(void *ptr);
size_t CRYPTO_secure_used(void);
void OPENSSL_cleanse(void *ptr, size_t len);
# ifndef OPENSSL_NO_CRYPTO_MDEBUG
# define OPENSSL_mem_debug_push(info) \
CRYPTO_mem_debug_push(info, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_mem_debug_pop() \
CRYPTO_mem_debug_pop()
int CRYPTO_mem_debug_push(const char *info, const char *file, int line);
int CRYPTO_mem_debug_pop(void);
void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount);
/*-
* Debugging functions (enabled by CRYPTO_set_mem_debug(1))
* The flag argument has the following significance:
* 0: called before the actual memory allocation has taken place
* 1: called after the actual memory allocation has taken place
*/
void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag,
const char *file, int line);
void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag,
const char *file, int line);
void CRYPTO_mem_debug_free(void *addr, int flag,
const char *file, int line);
int CRYPTO_mem_leaks_cb(int (*cb) (const char *str, size_t len, void *u),
void *u);
# ifndef OPENSSL_NO_STDIO
int CRYPTO_mem_leaks_fp(FILE *);
# endif
int CRYPTO_mem_leaks(BIO *bio);
# endif
/* die if we have to */
ossl_noreturn void OPENSSL_die(const char *assertion, const char *file, int line);
# if OPENSSL_API_COMPAT < 0x10100000L
# define OpenSSLDie(f,l,a) OPENSSL_die((a),(f),(l))
# endif
# define OPENSSL_assert(e) \
(void)((e) ? 0 : (OPENSSL_die("assertion failed: " #e, OPENSSL_FILE, OPENSSL_LINE), 1))
int OPENSSL_isservice(void);
int FIPS_mode(void);
int FIPS_mode_set(int r);
void OPENSSL_init(void);
# ifdef OPENSSL_SYS_UNIX
void OPENSSL_fork_prepare(void);
void OPENSSL_fork_parent(void);
void OPENSSL_fork_child(void);
# endif
struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result);
int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec);
int OPENSSL_gmtime_diff(int *pday, int *psec,
const struct tm *from, const struct tm *to);
/*
* CRYPTO_memcmp returns zero iff the |len| bytes at |a| and |b| are equal.
* It takes an amount of time dependent on |len|, but independent of the
* contents of |a| and |b|. Unlike memcmp, it cannot be used to put elements
* into a defined order as the return value when a != b is undefined, other
* than to be non-zero.
*/
int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len);
/* Standard initialisation options */
# define OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS 0x00000001L
# define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
# define OPENSSL_INIT_ADD_ALL_CIPHERS 0x00000004L
# define OPENSSL_INIT_ADD_ALL_DIGESTS 0x00000008L
# define OPENSSL_INIT_NO_ADD_ALL_CIPHERS 0x00000010L
# define OPENSSL_INIT_NO_ADD_ALL_DIGESTS 0x00000020L
# define OPENSSL_INIT_LOAD_CONFIG 0x00000040L
# define OPENSSL_INIT_NO_LOAD_CONFIG 0x00000080L
# define OPENSSL_INIT_ASYNC 0x00000100L
# define OPENSSL_INIT_ENGINE_RDRAND 0x00000200L
# define OPENSSL_INIT_ENGINE_DYNAMIC 0x00000400L
# define OPENSSL_INIT_ENGINE_OPENSSL 0x00000800L
# define OPENSSL_INIT_ENGINE_CRYPTODEV 0x00001000L
# define OPENSSL_INIT_ENGINE_CAPI 0x00002000L
# define OPENSSL_INIT_ENGINE_PADLOCK 0x00004000L
# define OPENSSL_INIT_ENGINE_AFALG 0x00008000L
/* OPENSSL_INIT_ZLIB 0x00010000L */
# define OPENSSL_INIT_ATFORK 0x00020000L
/* OPENSSL_INIT_BASE_ONLY 0x00040000L */
# define OPENSSL_INIT_NO_ATEXIT 0x00080000L
/* OPENSSL_INIT flag range 0xfff00000 reserved for OPENSSL_init_ssl() */
/* Max OPENSSL_INIT flag value is 0x80000000 */
/* openssl and dasync not counted as builtin */
# define OPENSSL_INIT_ENGINE_ALL_BUILTIN \
(OPENSSL_INIT_ENGINE_RDRAND | OPENSSL_INIT_ENGINE_DYNAMIC \
| OPENSSL_INIT_ENGINE_CRYPTODEV | OPENSSL_INIT_ENGINE_CAPI | \
OPENSSL_INIT_ENGINE_PADLOCK)
/* Library initialisation functions */
void OPENSSL_cleanup(void);
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings);
int OPENSSL_atexit(void (*handler)(void));
void OPENSSL_thread_stop(void);
/* Low-level control of initialization */
OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void);
# ifndef OPENSSL_NO_STDIO
int OPENSSL_INIT_set_config_filename(OPENSSL_INIT_SETTINGS *settings,
const char *config_filename);
void OPENSSL_INIT_set_config_file_flags(OPENSSL_INIT_SETTINGS *settings,
unsigned long flags);
int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *settings,
const char *config_appname);
# endif
void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *settings);
# if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG)
# if defined(_WIN32)
# if defined(BASETYPES) || defined(_WINDEF_H)
/* application has to include <windows.h> in order to use this */
typedef DWORD CRYPTO_THREAD_LOCAL;
typedef DWORD CRYPTO_THREAD_ID;
typedef LONG CRYPTO_ONCE;
# define CRYPTO_ONCE_STATIC_INIT 0
# endif
# else
# include <pthread.h>
typedef pthread_once_t CRYPTO_ONCE;
typedef pthread_key_t CRYPTO_THREAD_LOCAL;
typedef pthread_t CRYPTO_THREAD_ID;
# define CRYPTO_ONCE_STATIC_INIT PTHREAD_ONCE_INIT
# endif
# endif
# if !defined(CRYPTO_ONCE_STATIC_INIT)
typedef unsigned int CRYPTO_ONCE;
typedef unsigned int CRYPTO_THREAD_LOCAL;
typedef unsigned int CRYPTO_THREAD_ID;
# define CRYPTO_ONCE_STATIC_INIT 0
# endif
int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void));
int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *));
void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key);
int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val);
int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key);
CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void);
int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b);
# ifdef __cplusplus
}
# endif
#endif

@ -0,0 +1,57 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CRYPTOERR_H
# define HEADER_CRYPTOERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_CRYPTO_strings(void);
/*
* CRYPTO function codes.
*/
# define CRYPTO_F_CMAC_CTX_NEW 120
# define CRYPTO_F_CRYPTO_DUP_EX_DATA 110
# define CRYPTO_F_CRYPTO_FREE_EX_DATA 111
# define CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX 100
# define CRYPTO_F_CRYPTO_MEMDUP 115
# define CRYPTO_F_CRYPTO_NEW_EX_DATA 112
# define CRYPTO_F_CRYPTO_OCB128_COPY_CTX 121
# define CRYPTO_F_CRYPTO_OCB128_INIT 122
# define CRYPTO_F_CRYPTO_SET_EX_DATA 102
# define CRYPTO_F_FIPS_MODE_SET 109
# define CRYPTO_F_GET_AND_LOCK 113
# define CRYPTO_F_OPENSSL_ATEXIT 114
# define CRYPTO_F_OPENSSL_BUF2HEXSTR 117
# define CRYPTO_F_OPENSSL_FOPEN 119
# define CRYPTO_F_OPENSSL_HEXSTR2BUF 118
# define CRYPTO_F_OPENSSL_INIT_CRYPTO 116
# define CRYPTO_F_OPENSSL_LH_NEW 126
# define CRYPTO_F_OPENSSL_SK_DEEP_COPY 127
# define CRYPTO_F_OPENSSL_SK_DUP 128
# define CRYPTO_F_PKEY_HMAC_INIT 123
# define CRYPTO_F_PKEY_POLY1305_INIT 124
# define CRYPTO_F_PKEY_SIPHASH_INIT 125
# define CRYPTO_F_SK_RESERVE 129
/*
* CRYPTO reason codes.
*/
# define CRYPTO_R_FIPS_MODE_NOT_SUPPORTED 101
# define CRYPTO_R_ILLEGAL_HEX_DIGIT 102
# define CRYPTO_R_ODD_NUMBER_OF_DIGITS 103
#endif

@ -0,0 +1,474 @@
/*
* Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CT_H
# define HEADER_CT_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CT
# include <openssl/ossl_typ.h>
# include <openssl/safestack.h>
# include <openssl/x509.h>
# include <openssl/cterr.h>
# ifdef __cplusplus
extern "C" {
# endif
/* Minimum RSA key size, from RFC6962 */
# define SCT_MIN_RSA_BITS 2048
/* All hashes are SHA256 in v1 of Certificate Transparency */
# define CT_V1_HASHLEN SHA256_DIGEST_LENGTH
typedef enum {
CT_LOG_ENTRY_TYPE_NOT_SET = -1,
CT_LOG_ENTRY_TYPE_X509 = 0,
CT_LOG_ENTRY_TYPE_PRECERT = 1
} ct_log_entry_type_t;
typedef enum {
SCT_VERSION_NOT_SET = -1,
SCT_VERSION_V1 = 0
} sct_version_t;
typedef enum {
SCT_SOURCE_UNKNOWN,
SCT_SOURCE_TLS_EXTENSION,
SCT_SOURCE_X509V3_EXTENSION,
SCT_SOURCE_OCSP_STAPLED_RESPONSE
} sct_source_t;
typedef enum {
SCT_VALIDATION_STATUS_NOT_SET,
SCT_VALIDATION_STATUS_UNKNOWN_LOG,
SCT_VALIDATION_STATUS_VALID,
SCT_VALIDATION_STATUS_INVALID,
SCT_VALIDATION_STATUS_UNVERIFIED,
SCT_VALIDATION_STATUS_UNKNOWN_VERSION
} sct_validation_status_t;
DEFINE_STACK_OF(SCT)
DEFINE_STACK_OF(CTLOG)
/******************************************
* CT policy evaluation context functions *
******************************************/
/*
* Creates a new, empty policy evaluation context.
* The caller is responsible for calling CT_POLICY_EVAL_CTX_free when finished
* with the CT_POLICY_EVAL_CTX.
*/
CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void);
/* Deletes a policy evaluation context and anything it owns. */
void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx);
/* Gets the peer certificate that the SCTs are for */
X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx);
/*
* Sets the certificate associated with the received SCTs.
* Increments the reference count of cert.
* Returns 1 on success, 0 otherwise.
*/
int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert);
/* Gets the issuer of the aforementioned certificate */
X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx);
/*
* Sets the issuer of the certificate associated with the received SCTs.
* Increments the reference count of issuer.
* Returns 1 on success, 0 otherwise.
*/
int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer);
/* Gets the CT logs that are trusted sources of SCTs */
const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx);
/* Sets the log store that is in use. It must outlive the CT_POLICY_EVAL_CTX. */
void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx,
CTLOG_STORE *log_store);
/*
* Gets the time, in milliseconds since the Unix epoch, that will be used as the
* current time when checking whether an SCT was issued in the future.
* Such SCTs will fail validation, as required by RFC6962.
*/
uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx);
/*
* Sets the time to evaluate SCTs against, in milliseconds since the Unix epoch.
* If an SCT's timestamp is after this time, it will be interpreted as having
* been issued in the future. RFC6962 states that "TLS clients MUST reject SCTs
* whose timestamp is in the future", so an SCT will not validate in this case.
*/
void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms);
/*****************
* SCT functions *
*****************/
/*
* Creates a new, blank SCT.
* The caller is responsible for calling SCT_free when finished with the SCT.
*/
SCT *SCT_new(void);
/*
* Creates a new SCT from some base64-encoded strings.
* The caller is responsible for calling SCT_free when finished with the SCT.
*/
SCT *SCT_new_from_base64(unsigned char version,
const char *logid_base64,
ct_log_entry_type_t entry_type,
uint64_t timestamp,
const char *extensions_base64,
const char *signature_base64);
/*
* Frees the SCT and the underlying data structures.
*/
void SCT_free(SCT *sct);
/*
* Free a stack of SCTs, and the underlying SCTs themselves.
* Intended to be compatible with X509V3_EXT_FREE.
*/
void SCT_LIST_free(STACK_OF(SCT) *a);
/*
* Returns the version of the SCT.
*/
sct_version_t SCT_get_version(const SCT *sct);
/*
* Set the version of an SCT.
* Returns 1 on success, 0 if the version is unrecognized.
*/
__owur int SCT_set_version(SCT *sct, sct_version_t version);
/*
* Returns the log entry type of the SCT.
*/
ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct);
/*
* Set the log entry type of an SCT.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type);
/*
* Gets the ID of the log that an SCT came from.
* Ownership of the log ID remains with the SCT.
* Returns the length of the log ID.
*/
size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id);
/*
* Set the log ID of an SCT to point directly to the *log_id specified.
* The SCT takes ownership of the specified pointer.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len);
/*
* Set the log ID of an SCT.
* This makes a copy of the log_id.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set1_log_id(SCT *sct, const unsigned char *log_id,
size_t log_id_len);
/*
* Returns the timestamp for the SCT (epoch time in milliseconds).
*/
uint64_t SCT_get_timestamp(const SCT *sct);
/*
* Set the timestamp of an SCT (epoch time in milliseconds).
*/
void SCT_set_timestamp(SCT *sct, uint64_t timestamp);
/*
* Return the NID for the signature used by the SCT.
* For CT v1, this will be either NID_sha256WithRSAEncryption or
* NID_ecdsa_with_SHA256 (or NID_undef if incorrect/unset).
*/
int SCT_get_signature_nid(const SCT *sct);
/*
* Set the signature type of an SCT
* For CT v1, this should be either NID_sha256WithRSAEncryption or
* NID_ecdsa_with_SHA256.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set_signature_nid(SCT *sct, int nid);
/*
* Set *ext to point to the extension data for the SCT. ext must not be NULL.
* The SCT retains ownership of this pointer.
* Returns length of the data pointed to.
*/
size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext);
/*
* Set the extensions of an SCT to point directly to the *ext specified.
* The SCT takes ownership of the specified pointer.
*/
void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len);
/*
* Set the extensions of an SCT.
* This takes a copy of the ext.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set1_extensions(SCT *sct, const unsigned char *ext,
size_t ext_len);
/*
* Set *sig to point to the signature for the SCT. sig must not be NULL.
* The SCT retains ownership of this pointer.
* Returns length of the data pointed to.
*/
size_t SCT_get0_signature(const SCT *sct, unsigned char **sig);
/*
* Set the signature of an SCT to point directly to the *sig specified.
* The SCT takes ownership of the specified pointer.
*/
void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len);
/*
* Set the signature of an SCT to be a copy of the *sig specified.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set1_signature(SCT *sct, const unsigned char *sig,
size_t sig_len);
/*
* The origin of this SCT, e.g. TLS extension, OCSP response, etc.
*/
sct_source_t SCT_get_source(const SCT *sct);
/*
* Set the origin of this SCT, e.g. TLS extension, OCSP response, etc.
* Returns 1 on success, 0 otherwise.
*/
__owur int SCT_set_source(SCT *sct, sct_source_t source);
/*
* Returns a text string describing the validation status of |sct|.
*/
const char *SCT_validation_status_string(const SCT *sct);
/*
* Pretty-prints an |sct| to |out|.
* It will be indented by the number of spaces specified by |indent|.
* If |logs| is not NULL, it will be used to lookup the CT log that the SCT came
* from, so that the log name can be printed.
*/
void SCT_print(const SCT *sct, BIO *out, int indent, const CTLOG_STORE *logs);
/*
* Pretty-prints an |sct_list| to |out|.
* It will be indented by the number of spaces specified by |indent|.
* SCTs will be delimited by |separator|.
* If |logs| is not NULL, it will be used to lookup the CT log that each SCT
* came from, so that the log names can be printed.
*/
void SCT_LIST_print(const STACK_OF(SCT) *sct_list, BIO *out, int indent,
const char *separator, const CTLOG_STORE *logs);
/*
* Gets the last result of validating this SCT.
* If it has not been validated yet, returns SCT_VALIDATION_STATUS_NOT_SET.
*/
sct_validation_status_t SCT_get_validation_status(const SCT *sct);
/*
* Validates the given SCT with the provided context.
* Sets the "validation_status" field of the SCT.
* Returns 1 if the SCT is valid and the signature verifies.
* Returns 0 if the SCT is invalid or could not be verified.
* Returns -1 if an error occurs.
*/
__owur int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx);
/*
* Validates the given list of SCTs with the provided context.
* Sets the "validation_status" field of each SCT.
* Returns 1 if there are no invalid SCTs and all signatures verify.
* Returns 0 if at least one SCT is invalid or could not be verified.
* Returns a negative integer if an error occurs.
*/
__owur int SCT_LIST_validate(const STACK_OF(SCT) *scts,
CT_POLICY_EVAL_CTX *ctx);
/*********************************
* SCT parsing and serialisation *
*********************************/
/*
* Serialize (to TLS format) a stack of SCTs and return the length.
* "a" must not be NULL.
* If "pp" is NULL, just return the length of what would have been serialized.
* If "pp" is not NULL and "*pp" is null, function will allocate a new pointer
* for data that caller is responsible for freeing (only if function returns
* successfully).
* If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring
* that "*pp" is large enough to accept all of the serialized data.
* Returns < 0 on error, >= 0 indicating bytes written (or would have been)
* on success.
*/
__owur int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp);
/*
* Convert TLS format SCT list to a stack of SCTs.
* If "a" or "*a" is NULL, a new stack will be created that the caller is
* responsible for freeing (by calling SCT_LIST_free).
* "**pp" and "*pp" must not be NULL.
* Upon success, "*pp" will point to after the last bytes read, and a stack
* will be returned.
* Upon failure, a NULL pointer will be returned, and the position of "*pp" is
* not defined.
*/
STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
size_t len);
/*
* Serialize (to DER format) a stack of SCTs and return the length.
* "a" must not be NULL.
* If "pp" is NULL, just returns the length of what would have been serialized.
* If "pp" is not NULL and "*pp" is null, function will allocate a new pointer
* for data that caller is responsible for freeing (only if function returns
* successfully).
* If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring
* that "*pp" is large enough to accept all of the serialized data.
* Returns < 0 on error, >= 0 indicating bytes written (or would have been)
* on success.
*/
__owur int i2d_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp);
/*
* Parses an SCT list in DER format and returns it.
* If "a" or "*a" is NULL, a new stack will be created that the caller is
* responsible for freeing (by calling SCT_LIST_free).
* "**pp" and "*pp" must not be NULL.
* Upon success, "*pp" will point to after the last bytes read, and a stack
* will be returned.
* Upon failure, a NULL pointer will be returned, and the position of "*pp" is
* not defined.
*/
STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
long len);
/*
* Serialize (to TLS format) an |sct| and write it to |out|.
* If |out| is null, no SCT will be output but the length will still be returned.
* If |out| points to a null pointer, a string will be allocated to hold the
* TLS-format SCT. It is the responsibility of the caller to free it.
* If |out| points to an allocated string, the TLS-format SCT will be written
* to it.
* The length of the SCT in TLS format will be returned.
*/
__owur int i2o_SCT(const SCT *sct, unsigned char **out);
/*
* Parses an SCT in TLS format and returns it.
* If |psct| is not null, it will end up pointing to the parsed SCT. If it
* already points to a non-null pointer, the pointer will be free'd.
* |in| should be a pointer to a string containing the TLS-format SCT.
* |in| will be advanced to the end of the SCT if parsing succeeds.
* |len| should be the length of the SCT in |in|.
* Returns NULL if an error occurs.
* If the SCT is an unsupported version, only the SCT's 'sct' and 'sct_len'
* fields will be populated (with |in| and |len| respectively).
*/
SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len);
/********************
* CT log functions *
********************/
/*
* Creates a new CT log instance with the given |public_key| and |name|.
* Takes ownership of |public_key| but copies |name|.
* Returns NULL if malloc fails or if |public_key| cannot be converted to DER.
* Should be deleted by the caller using CTLOG_free when no longer needed.
*/
CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name);
/*
* Creates a new CTLOG instance with the base64-encoded SubjectPublicKeyInfo DER
* in |pkey_base64|. The |name| is a string to help users identify this log.
* Returns 1 on success, 0 on failure.
* Should be deleted by the caller using CTLOG_free when no longer needed.
*/
int CTLOG_new_from_base64(CTLOG ** ct_log,
const char *pkey_base64, const char *name);
/*
* Deletes a CT log instance and its fields.
*/
void CTLOG_free(CTLOG *log);
/* Gets the name of the CT log */
const char *CTLOG_get0_name(const CTLOG *log);
/* Gets the ID of the CT log */
void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id,
size_t *log_id_len);
/* Gets the public key of the CT log */
EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log);
/**************************
* CT log store functions *
**************************/
/*
* Creates a new CT log store.
* Should be deleted by the caller using CTLOG_STORE_free when no longer needed.
*/
CTLOG_STORE *CTLOG_STORE_new(void);
/*
* Deletes a CT log store and all of the CT log instances held within.
*/
void CTLOG_STORE_free(CTLOG_STORE *store);
/*
* Finds a CT log in the store based on its log ID.
* Returns the CT log, or NULL if no match is found.
*/
const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store,
const uint8_t *log_id,
size_t log_id_len);
/*
* Loads a CT log list into a |store| from a |file|.
* Returns 1 if loading is successful, or 0 otherwise.
*/
__owur int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file);
/*
* Loads the default CT log list into a |store|.
* Returns 1 if loading is successful, or 0 otherwise.
*/
__owur int CTLOG_STORE_load_default_file(CTLOG_STORE *store);
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,80 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CTERR_H
# define HEADER_CTERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CT
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_CT_strings(void);
/*
* CT function codes.
*/
# define CT_F_CTLOG_NEW 117
# define CT_F_CTLOG_NEW_FROM_BASE64 118
# define CT_F_CTLOG_NEW_FROM_CONF 119
# define CT_F_CTLOG_STORE_LOAD_CTX_NEW 122
# define CT_F_CTLOG_STORE_LOAD_FILE 123
# define CT_F_CTLOG_STORE_LOAD_LOG 130
# define CT_F_CTLOG_STORE_NEW 131
# define CT_F_CT_BASE64_DECODE 124
# define CT_F_CT_POLICY_EVAL_CTX_NEW 133
# define CT_F_CT_V1_LOG_ID_FROM_PKEY 125
# define CT_F_I2O_SCT 107
# define CT_F_I2O_SCT_LIST 108
# define CT_F_I2O_SCT_SIGNATURE 109
# define CT_F_O2I_SCT 110
# define CT_F_O2I_SCT_LIST 111
# define CT_F_O2I_SCT_SIGNATURE 112
# define CT_F_SCT_CTX_NEW 126
# define CT_F_SCT_CTX_VERIFY 128
# define CT_F_SCT_NEW 100
# define CT_F_SCT_NEW_FROM_BASE64 127
# define CT_F_SCT_SET0_LOG_ID 101
# define CT_F_SCT_SET1_EXTENSIONS 114
# define CT_F_SCT_SET1_LOG_ID 115
# define CT_F_SCT_SET1_SIGNATURE 116
# define CT_F_SCT_SET_LOG_ENTRY_TYPE 102
# define CT_F_SCT_SET_SIGNATURE_NID 103
# define CT_F_SCT_SET_VERSION 104
/*
* CT reason codes.
*/
# define CT_R_BASE64_DECODE_ERROR 108
# define CT_R_INVALID_LOG_ID_LENGTH 100
# define CT_R_LOG_CONF_INVALID 109
# define CT_R_LOG_CONF_INVALID_KEY 110
# define CT_R_LOG_CONF_MISSING_DESCRIPTION 111
# define CT_R_LOG_CONF_MISSING_KEY 112
# define CT_R_LOG_KEY_INVALID 113
# define CT_R_SCT_FUTURE_TIMESTAMP 116
# define CT_R_SCT_INVALID 104
# define CT_R_SCT_INVALID_SIGNATURE 107
# define CT_R_SCT_LIST_INVALID 105
# define CT_R_SCT_LOG_ID_MISMATCH 114
# define CT_R_SCT_NOT_SET 106
# define CT_R_SCT_UNSUPPORTED_VERSION 115
# define CT_R_UNRECOGNIZED_SIGNATURE_NID 101
# define CT_R_UNSUPPORTED_ENTRY_TYPE 102
# define CT_R_UNSUPPORTED_VERSION 103
# endif
#endif

@ -0,0 +1,174 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_DES_H
# define HEADER_DES_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_DES
# ifdef __cplusplus
extern "C" {
# endif
# include <openssl/e_os2.h>
typedef unsigned int DES_LONG;
# ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
# endif
typedef unsigned char DES_cblock[8];
typedef /* const */ unsigned char const_DES_cblock[8];
/*
* With "const", gcc 2.8.1 on Solaris thinks that DES_cblock * and
* const_DES_cblock * are incompatible pointer types.
*/
typedef struct DES_ks {
union {
DES_cblock cblock;
/*
* make sure things are correct size on machines with 8 byte longs
*/
DES_LONG deslong[2];
} ks[16];
} DES_key_schedule;
# define DES_KEY_SZ (sizeof(DES_cblock))
# define DES_SCHEDULE_SZ (sizeof(DES_key_schedule))
# define DES_ENCRYPT 1
# define DES_DECRYPT 0
# define DES_CBC_MODE 0
# define DES_PCBC_MODE 1
# define DES_ecb2_encrypt(i,o,k1,k2,e) \
DES_ecb3_encrypt((i),(o),(k1),(k2),(k1),(e))
# define DES_ede2_cbc_encrypt(i,o,l,k1,k2,iv,e) \
DES_ede3_cbc_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(e))
# define DES_ede2_cfb64_encrypt(i,o,l,k1,k2,iv,n,e) \
DES_ede3_cfb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n),(e))
# define DES_ede2_ofb64_encrypt(i,o,l,k1,k2,iv,n) \
DES_ede3_ofb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n))
OPENSSL_DECLARE_GLOBAL(int, DES_check_key); /* defaults to false */
# define DES_check_key OPENSSL_GLOBAL_REF(DES_check_key)
const char *DES_options(void);
void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output,
DES_key_schedule *ks1, DES_key_schedule *ks2,
DES_key_schedule *ks3, int enc);
DES_LONG DES_cbc_cksum(const unsigned char *input, DES_cblock *output,
long length, DES_key_schedule *schedule,
const_DES_cblock *ivec);
/* DES_cbc_encrypt does not update the IV! Use DES_ncbc_encrypt instead. */
void DES_cbc_encrypt(const unsigned char *input, unsigned char *output,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int enc);
void DES_ncbc_encrypt(const unsigned char *input, unsigned char *output,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int enc);
void DES_xcbc_encrypt(const unsigned char *input, unsigned char *output,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, const_DES_cblock *inw,
const_DES_cblock *outw, int enc);
void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int enc);
void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output,
DES_key_schedule *ks, int enc);
/*
* This is the DES encryption function that gets called by just about every
* other DES routine in the library. You should not use this function except
* to implement 'modes' of DES. I say this because the functions that call
* this routine do the conversion from 'char *' to long, and this needs to be
* done to make sure 'non-aligned' memory access do not occur. The
* characters are loaded 'little endian'. Data is a pointer to 2 unsigned
* long's and ks is the DES_key_schedule to use. enc, is non zero specifies
* encryption, zero if decryption.
*/
void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc);
/*
* This functions is the same as DES_encrypt1() except that the DES initial
* permutation (IP) and final permutation (FP) have been left out. As for
* DES_encrypt1(), you should not use this function. It is used by the
* routines in the library that implement triple DES. IP() DES_encrypt2()
* DES_encrypt2() DES_encrypt2() FP() is the same as DES_encrypt1()
* DES_encrypt1() DES_encrypt1() except faster :-).
*/
void DES_encrypt2(DES_LONG *data, DES_key_schedule *ks, int enc);
void DES_encrypt3(DES_LONG *data, DES_key_schedule *ks1,
DES_key_schedule *ks2, DES_key_schedule *ks3);
void DES_decrypt3(DES_LONG *data, DES_key_schedule *ks1,
DES_key_schedule *ks2, DES_key_schedule *ks3);
void DES_ede3_cbc_encrypt(const unsigned char *input, unsigned char *output,
long length,
DES_key_schedule *ks1, DES_key_schedule *ks2,
DES_key_schedule *ks3, DES_cblock *ivec, int enc);
void DES_ede3_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, DES_key_schedule *ks1,
DES_key_schedule *ks2, DES_key_schedule *ks3,
DES_cblock *ivec, int *num, int enc);
void DES_ede3_cfb_encrypt(const unsigned char *in, unsigned char *out,
int numbits, long length, DES_key_schedule *ks1,
DES_key_schedule *ks2, DES_key_schedule *ks3,
DES_cblock *ivec, int enc);
void DES_ede3_ofb64_encrypt(const unsigned char *in, unsigned char *out,
long length, DES_key_schedule *ks1,
DES_key_schedule *ks2, DES_key_schedule *ks3,
DES_cblock *ivec, int *num);
char *DES_fcrypt(const char *buf, const char *salt, char *ret);
char *DES_crypt(const char *buf, const char *salt);
void DES_ofb_encrypt(const unsigned char *in, unsigned char *out, int numbits,
long length, DES_key_schedule *schedule,
DES_cblock *ivec);
void DES_pcbc_encrypt(const unsigned char *input, unsigned char *output,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int enc);
DES_LONG DES_quad_cksum(const unsigned char *input, DES_cblock output[],
long length, int out_count, DES_cblock *seed);
int DES_random_key(DES_cblock *ret);
void DES_set_odd_parity(DES_cblock *key);
int DES_check_key_parity(const_DES_cblock *key);
int DES_is_weak_key(const_DES_cblock *key);
/*
* DES_set_key (= set_key = DES_key_sched = key_sched) calls
* DES_set_key_checked if global variable DES_check_key is set,
* DES_set_key_unchecked otherwise.
*/
int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule);
int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule);
int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule);
void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule);
void DES_string_to_key(const char *str, DES_cblock *key);
void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2);
void DES_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int *num, int enc);
void DES_ofb64_encrypt(const unsigned char *in, unsigned char *out,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int *num);
# define DES_fixup_key_parity DES_set_odd_parity
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,340 @@
/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_DH_H
# define HEADER_DH_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_DH
# include <openssl/e_os2.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/ossl_typ.h>
# if OPENSSL_API_COMPAT < 0x10100000L
# include <openssl/bn.h>
# endif
# include <openssl/dherr.h>
# ifdef __cplusplus
extern "C" {
# endif
# ifndef OPENSSL_DH_MAX_MODULUS_BITS
# define OPENSSL_DH_MAX_MODULUS_BITS 10000
# endif
# define OPENSSL_DH_FIPS_MIN_MODULUS_BITS 1024
# define DH_FLAG_CACHE_MONT_P 0x01
# if OPENSSL_API_COMPAT < 0x10100000L
/*
* Does nothing. Previously this switched off constant time behaviour.
*/
# define DH_FLAG_NO_EXP_CONSTTIME 0x00
# endif
/*
* If this flag is set the DH method is FIPS compliant and can be used in
* FIPS mode. This is set in the validated module method. If an application
* sets this flag in its own methods it is its responsibility to ensure the
* result is compliant.
*/
# define DH_FLAG_FIPS_METHOD 0x0400
/*
* If this flag is set the operations normally disabled in FIPS mode are
* permitted it is then the applications responsibility to ensure that the
* usage is compliant.
*/
# define DH_FLAG_NON_FIPS_ALLOW 0x0400
/* Already defined in ossl_typ.h */
/* typedef struct dh_st DH; */
/* typedef struct dh_method DH_METHOD; */
DECLARE_ASN1_ITEM(DHparams)
# define DH_GENERATOR_2 2
/* #define DH_GENERATOR_3 3 */
# define DH_GENERATOR_5 5
/* DH_check error codes */
# define DH_CHECK_P_NOT_PRIME 0x01
# define DH_CHECK_P_NOT_SAFE_PRIME 0x02
# define DH_UNABLE_TO_CHECK_GENERATOR 0x04
# define DH_NOT_SUITABLE_GENERATOR 0x08
# define DH_CHECK_Q_NOT_PRIME 0x10
# define DH_CHECK_INVALID_Q_VALUE 0x20
# define DH_CHECK_INVALID_J_VALUE 0x40
/* DH_check_pub_key error codes */
# define DH_CHECK_PUBKEY_TOO_SMALL 0x01
# define DH_CHECK_PUBKEY_TOO_LARGE 0x02
# define DH_CHECK_PUBKEY_INVALID 0x04
/*
* primes p where (p-1)/2 is prime too are called "safe"; we define this for
* backward compatibility:
*/
# define DH_CHECK_P_NOT_STRONG_PRIME DH_CHECK_P_NOT_SAFE_PRIME
# define d2i_DHparams_fp(fp,x) \
(DH *)ASN1_d2i_fp((char *(*)())DH_new, \
(char *(*)())d2i_DHparams, \
(fp), \
(unsigned char **)(x))
# define i2d_DHparams_fp(fp,x) \
ASN1_i2d_fp(i2d_DHparams,(fp), (unsigned char *)(x))
# define d2i_DHparams_bio(bp,x) \
ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, bp, x)
# define i2d_DHparams_bio(bp,x) \
ASN1_i2d_bio_of_const(DH,i2d_DHparams,bp,x)
# define d2i_DHxparams_fp(fp,x) \
(DH *)ASN1_d2i_fp((char *(*)())DH_new, \
(char *(*)())d2i_DHxparams, \
(fp), \
(unsigned char **)(x))
# define i2d_DHxparams_fp(fp,x) \
ASN1_i2d_fp(i2d_DHxparams,(fp), (unsigned char *)(x))
# define d2i_DHxparams_bio(bp,x) \
ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, bp, x)
# define i2d_DHxparams_bio(bp,x) \
ASN1_i2d_bio_of_const(DH, i2d_DHxparams, bp, x)
DH *DHparams_dup(DH *);
const DH_METHOD *DH_OpenSSL(void);
void DH_set_default_method(const DH_METHOD *meth);
const DH_METHOD *DH_get_default_method(void);
int DH_set_method(DH *dh, const DH_METHOD *meth);
DH *DH_new_method(ENGINE *engine);
DH *DH_new(void);
void DH_free(DH *dh);
int DH_up_ref(DH *dh);
int DH_bits(const DH *dh);
int DH_size(const DH *dh);
int DH_security_bits(const DH *dh);
#define DH_get_ex_new_index(l, p, newf, dupf, freef) \
CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DH, l, p, newf, dupf, freef)
int DH_set_ex_data(DH *d, int idx, void *arg);
void *DH_get_ex_data(DH *d, int idx);
/* Deprecated version */
DEPRECATEDIN_0_9_8(DH *DH_generate_parameters(int prime_len, int generator,
void (*callback) (int, int,
void *),
void *cb_arg))
/* New version */
int DH_generate_parameters_ex(DH *dh, int prime_len, int generator,
BN_GENCB *cb);
int DH_check_params_ex(const DH *dh);
int DH_check_ex(const DH *dh);
int DH_check_pub_key_ex(const DH *dh, const BIGNUM *pub_key);
int DH_check_params(const DH *dh, int *ret);
int DH_check(const DH *dh, int *codes);
int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *codes);
int DH_generate_key(DH *dh);
int DH_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh);
int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh);
DH *d2i_DHparams(DH **a, const unsigned char **pp, long length);
int i2d_DHparams(const DH *a, unsigned char **pp);
DH *d2i_DHxparams(DH **a, const unsigned char **pp, long length);
int i2d_DHxparams(const DH *a, unsigned char **pp);
# ifndef OPENSSL_NO_STDIO
int DHparams_print_fp(FILE *fp, const DH *x);
# endif
int DHparams_print(BIO *bp, const DH *x);
/* RFC 5114 parameters */
DH *DH_get_1024_160(void);
DH *DH_get_2048_224(void);
DH *DH_get_2048_256(void);
/* Named parameters, currently RFC7919 */
DH *DH_new_by_nid(int nid);
int DH_get_nid(const DH *dh);
# ifndef OPENSSL_NO_CMS
/* RFC2631 KDF */
int DH_KDF_X9_42(unsigned char *out, size_t outlen,
const unsigned char *Z, size_t Zlen,
ASN1_OBJECT *key_oid,
const unsigned char *ukm, size_t ukmlen, const EVP_MD *md);
# endif
void DH_get0_pqg(const DH *dh,
const BIGNUM **p, const BIGNUM **q, const BIGNUM **g);
int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g);
void DH_get0_key(const DH *dh,
const BIGNUM **pub_key, const BIGNUM **priv_key);
int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key);
const BIGNUM *DH_get0_p(const DH *dh);
const BIGNUM *DH_get0_q(const DH *dh);
const BIGNUM *DH_get0_g(const DH *dh);
const BIGNUM *DH_get0_priv_key(const DH *dh);
const BIGNUM *DH_get0_pub_key(const DH *dh);
void DH_clear_flags(DH *dh, int flags);
int DH_test_flags(const DH *dh, int flags);
void DH_set_flags(DH *dh, int flags);
ENGINE *DH_get0_engine(DH *d);
long DH_get_length(const DH *dh);
int DH_set_length(DH *dh, long length);
DH_METHOD *DH_meth_new(const char *name, int flags);
void DH_meth_free(DH_METHOD *dhm);
DH_METHOD *DH_meth_dup(const DH_METHOD *dhm);
const char *DH_meth_get0_name(const DH_METHOD *dhm);
int DH_meth_set1_name(DH_METHOD *dhm, const char *name);
int DH_meth_get_flags(const DH_METHOD *dhm);
int DH_meth_set_flags(DH_METHOD *dhm, int flags);
void *DH_meth_get0_app_data(const DH_METHOD *dhm);
int DH_meth_set0_app_data(DH_METHOD *dhm, void *app_data);
int (*DH_meth_get_generate_key(const DH_METHOD *dhm)) (DH *);
int DH_meth_set_generate_key(DH_METHOD *dhm, int (*generate_key) (DH *));
int (*DH_meth_get_compute_key(const DH_METHOD *dhm))
(unsigned char *key, const BIGNUM *pub_key, DH *dh);
int DH_meth_set_compute_key(DH_METHOD *dhm,
int (*compute_key) (unsigned char *key, const BIGNUM *pub_key, DH *dh));
int (*DH_meth_get_bn_mod_exp(const DH_METHOD *dhm))
(const DH *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *,
BN_CTX *, BN_MONT_CTX *);
int DH_meth_set_bn_mod_exp(DH_METHOD *dhm,
int (*bn_mod_exp) (const DH *, BIGNUM *, const BIGNUM *, const BIGNUM *,
const BIGNUM *, BN_CTX *, BN_MONT_CTX *));
int (*DH_meth_get_init(const DH_METHOD *dhm))(DH *);
int DH_meth_set_init(DH_METHOD *dhm, int (*init)(DH *));
int (*DH_meth_get_finish(const DH_METHOD *dhm)) (DH *);
int DH_meth_set_finish(DH_METHOD *dhm, int (*finish) (DH *));
int (*DH_meth_get_generate_params(const DH_METHOD *dhm))
(DH *, int, int, BN_GENCB *);
int DH_meth_set_generate_params(DH_METHOD *dhm,
int (*generate_params) (DH *, int, int, BN_GENCB *));
# define EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, len, NULL)
# define EVP_PKEY_CTX_set_dh_paramgen_subprime_len(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, len, NULL)
# define EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, typ, NULL)
# define EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, gen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, gen, NULL)
# define EVP_PKEY_CTX_set_dh_rfc5114(ctx, gen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_RFC5114, gen, NULL)
# define EVP_PKEY_CTX_set_dhx_rfc5114(ctx, gen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_RFC5114, gen, NULL)
# define EVP_PKEY_CTX_set_dh_nid(ctx, nid) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, \
EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, \
EVP_PKEY_CTRL_DH_NID, nid, NULL)
# define EVP_PKEY_CTX_set_dh_pad(ctx, pad) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_PAD, pad, NULL)
# define EVP_PKEY_CTX_set_dh_kdf_type(ctx, kdf) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_TYPE, kdf, NULL)
# define EVP_PKEY_CTX_get_dh_kdf_type(ctx) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_TYPE, -2, NULL)
# define EVP_PKEY_CTX_set0_dh_kdf_oid(ctx, oid) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_OID, 0, (void *)(oid))
# define EVP_PKEY_CTX_get0_dh_kdf_oid(ctx, poid) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_OID, 0, (void *)(poid))
# define EVP_PKEY_CTX_set_dh_kdf_md(ctx, md) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_MD, 0, (void *)(md))
# define EVP_PKEY_CTX_get_dh_kdf_md(ctx, pmd) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_MD, 0, (void *)(pmd))
# define EVP_PKEY_CTX_set_dh_kdf_outlen(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_OUTLEN, len, NULL)
# define EVP_PKEY_CTX_get_dh_kdf_outlen(ctx, plen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, 0, (void *)(plen))
# define EVP_PKEY_CTX_set0_dh_kdf_ukm(ctx, p, plen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_UKM, plen, (void *)(p))
# define EVP_PKEY_CTX_get0_dh_kdf_ukm(ctx, p) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_UKM, 0, (void *)(p))
# define EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN (EVP_PKEY_ALG_CTRL + 1)
# define EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR (EVP_PKEY_ALG_CTRL + 2)
# define EVP_PKEY_CTRL_DH_RFC5114 (EVP_PKEY_ALG_CTRL + 3)
# define EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN (EVP_PKEY_ALG_CTRL + 4)
# define EVP_PKEY_CTRL_DH_PARAMGEN_TYPE (EVP_PKEY_ALG_CTRL + 5)
# define EVP_PKEY_CTRL_DH_KDF_TYPE (EVP_PKEY_ALG_CTRL + 6)
# define EVP_PKEY_CTRL_DH_KDF_MD (EVP_PKEY_ALG_CTRL + 7)
# define EVP_PKEY_CTRL_GET_DH_KDF_MD (EVP_PKEY_ALG_CTRL + 8)
# define EVP_PKEY_CTRL_DH_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 9)
# define EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 10)
# define EVP_PKEY_CTRL_DH_KDF_UKM (EVP_PKEY_ALG_CTRL + 11)
# define EVP_PKEY_CTRL_GET_DH_KDF_UKM (EVP_PKEY_ALG_CTRL + 12)
# define EVP_PKEY_CTRL_DH_KDF_OID (EVP_PKEY_ALG_CTRL + 13)
# define EVP_PKEY_CTRL_GET_DH_KDF_OID (EVP_PKEY_ALG_CTRL + 14)
# define EVP_PKEY_CTRL_DH_NID (EVP_PKEY_ALG_CTRL + 15)
# define EVP_PKEY_CTRL_DH_PAD (EVP_PKEY_ALG_CTRL + 16)
/* KDF types */
# define EVP_PKEY_DH_KDF_NONE 1
# ifndef OPENSSL_NO_CMS
# define EVP_PKEY_DH_KDF_X9_42 2
# endif
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,88 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_DHERR_H
# define HEADER_DHERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_DH
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_DH_strings(void);
/*
* DH function codes.
*/
# define DH_F_COMPUTE_KEY 102
# define DH_F_DHPARAMS_PRINT_FP 101
# define DH_F_DH_BUILTIN_GENPARAMS 106
# define DH_F_DH_CHECK_EX 121
# define DH_F_DH_CHECK_PARAMS_EX 122
# define DH_F_DH_CHECK_PUB_KEY_EX 123
# define DH_F_DH_CMS_DECRYPT 114
# define DH_F_DH_CMS_SET_PEERKEY 115
# define DH_F_DH_CMS_SET_SHARED_INFO 116
# define DH_F_DH_METH_DUP 117
# define DH_F_DH_METH_NEW 118
# define DH_F_DH_METH_SET1_NAME 119
# define DH_F_DH_NEW_BY_NID 104
# define DH_F_DH_NEW_METHOD 105
# define DH_F_DH_PARAM_DECODE 107
# define DH_F_DH_PKEY_PUBLIC_CHECK 124
# define DH_F_DH_PRIV_DECODE 110
# define DH_F_DH_PRIV_ENCODE 111
# define DH_F_DH_PUB_DECODE 108
# define DH_F_DH_PUB_ENCODE 109
# define DH_F_DO_DH_PRINT 100
# define DH_F_GENERATE_KEY 103
# define DH_F_PKEY_DH_CTRL_STR 120
# define DH_F_PKEY_DH_DERIVE 112
# define DH_F_PKEY_DH_INIT 125
# define DH_F_PKEY_DH_KEYGEN 113
/*
* DH reason codes.
*/
# define DH_R_BAD_GENERATOR 101
# define DH_R_BN_DECODE_ERROR 109
# define DH_R_BN_ERROR 106
# define DH_R_CHECK_INVALID_J_VALUE 115
# define DH_R_CHECK_INVALID_Q_VALUE 116
# define DH_R_CHECK_PUBKEY_INVALID 122
# define DH_R_CHECK_PUBKEY_TOO_LARGE 123
# define DH_R_CHECK_PUBKEY_TOO_SMALL 124
# define DH_R_CHECK_P_NOT_PRIME 117
# define DH_R_CHECK_P_NOT_SAFE_PRIME 118
# define DH_R_CHECK_Q_NOT_PRIME 119
# define DH_R_DECODE_ERROR 104
# define DH_R_INVALID_PARAMETER_NAME 110
# define DH_R_INVALID_PARAMETER_NID 114
# define DH_R_INVALID_PUBKEY 102
# define DH_R_KDF_PARAMETER_ERROR 112
# define DH_R_KEYS_NOT_SET 108
# define DH_R_MISSING_PUBKEY 125
# define DH_R_MODULUS_TOO_LARGE 103
# define DH_R_NOT_SUITABLE_GENERATOR 120
# define DH_R_NO_PARAMETERS_SET 107
# define DH_R_NO_PRIVATE_VALUE 100
# define DH_R_PARAMETER_ENCODING_ERROR 105
# define DH_R_PEER_KEY_ERROR 111
# define DH_R_SHARED_INFO_ERROR 113
# define DH_R_UNABLE_TO_CHECK_GENERATOR 121
# endif
#endif

@ -0,0 +1,244 @@
/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_DSA_H
# define HEADER_DSA_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_DSA
# ifdef __cplusplus
extern "C" {
# endif
# include <openssl/e_os2.h>
# include <openssl/bio.h>
# include <openssl/crypto.h>
# include <openssl/ossl_typ.h>
# include <openssl/bn.h>
# if OPENSSL_API_COMPAT < 0x10100000L
# include <openssl/dh.h>
# endif
# include <openssl/dsaerr.h>
# ifndef OPENSSL_DSA_MAX_MODULUS_BITS
# define OPENSSL_DSA_MAX_MODULUS_BITS 10000
# endif
# define OPENSSL_DSA_FIPS_MIN_MODULUS_BITS 1024
# define DSA_FLAG_CACHE_MONT_P 0x01
# if OPENSSL_API_COMPAT < 0x10100000L
/*
* Does nothing. Previously this switched off constant time behaviour.
*/
# define DSA_FLAG_NO_EXP_CONSTTIME 0x00
# endif
/*
* If this flag is set the DSA method is FIPS compliant and can be used in
* FIPS mode. This is set in the validated module method. If an application
* sets this flag in its own methods it is its responsibility to ensure the
* result is compliant.
*/
# define DSA_FLAG_FIPS_METHOD 0x0400
/*
* If this flag is set the operations normally disabled in FIPS mode are
* permitted it is then the applications responsibility to ensure that the
* usage is compliant.
*/
# define DSA_FLAG_NON_FIPS_ALLOW 0x0400
# define DSA_FLAG_FIPS_CHECKED 0x0800
/* Already defined in ossl_typ.h */
/* typedef struct dsa_st DSA; */
/* typedef struct dsa_method DSA_METHOD; */
typedef struct DSA_SIG_st DSA_SIG;
# define d2i_DSAparams_fp(fp,x) (DSA *)ASN1_d2i_fp((char *(*)())DSA_new, \
(char *(*)())d2i_DSAparams,(fp),(unsigned char **)(x))
# define i2d_DSAparams_fp(fp,x) ASN1_i2d_fp(i2d_DSAparams,(fp), \
(unsigned char *)(x))
# define d2i_DSAparams_bio(bp,x) ASN1_d2i_bio_of(DSA,DSA_new,d2i_DSAparams,bp,x)
# define i2d_DSAparams_bio(bp,x) ASN1_i2d_bio_of_const(DSA,i2d_DSAparams,bp,x)
DSA *DSAparams_dup(DSA *x);
DSA_SIG *DSA_SIG_new(void);
void DSA_SIG_free(DSA_SIG *a);
int i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp);
DSA_SIG *d2i_DSA_SIG(DSA_SIG **v, const unsigned char **pp, long length);
void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps);
int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s);
DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
int DSA_do_verify(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa);
const DSA_METHOD *DSA_OpenSSL(void);
void DSA_set_default_method(const DSA_METHOD *);
const DSA_METHOD *DSA_get_default_method(void);
int DSA_set_method(DSA *dsa, const DSA_METHOD *);
const DSA_METHOD *DSA_get_method(DSA *d);
DSA *DSA_new(void);
DSA *DSA_new_method(ENGINE *engine);
void DSA_free(DSA *r);
/* "up" the DSA object's reference count */
int DSA_up_ref(DSA *r);
int DSA_size(const DSA *);
int DSA_bits(const DSA *d);
int DSA_security_bits(const DSA *d);
/* next 4 return -1 on error */
DEPRECATEDIN_1_2_0(int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp))
int DSA_sign(int type, const unsigned char *dgst, int dlen,
unsigned char *sig, unsigned int *siglen, DSA *dsa);
int DSA_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int siglen, DSA *dsa);
#define DSA_get_ex_new_index(l, p, newf, dupf, freef) \
CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DSA, l, p, newf, dupf, freef)
int DSA_set_ex_data(DSA *d, int idx, void *arg);
void *DSA_get_ex_data(DSA *d, int idx);
DSA *d2i_DSAPublicKey(DSA **a, const unsigned char **pp, long length);
DSA *d2i_DSAPrivateKey(DSA **a, const unsigned char **pp, long length);
DSA *d2i_DSAparams(DSA **a, const unsigned char **pp, long length);
/* Deprecated version */
DEPRECATEDIN_0_9_8(DSA *DSA_generate_parameters(int bits,
unsigned char *seed,
int seed_len,
int *counter_ret,
unsigned long *h_ret, void
(*callback) (int, int,
void *),
void *cb_arg))
/* New version */
int DSA_generate_parameters_ex(DSA *dsa, int bits,
const unsigned char *seed, int seed_len,
int *counter_ret, unsigned long *h_ret,
BN_GENCB *cb);
int DSA_generate_key(DSA *a);
int i2d_DSAPublicKey(const DSA *a, unsigned char **pp);
int i2d_DSAPrivateKey(const DSA *a, unsigned char **pp);
int i2d_DSAparams(const DSA *a, unsigned char **pp);
int DSAparams_print(BIO *bp, const DSA *x);
int DSA_print(BIO *bp, const DSA *x, int off);
# ifndef OPENSSL_NO_STDIO
int DSAparams_print_fp(FILE *fp, const DSA *x);
int DSA_print_fp(FILE *bp, const DSA *x, int off);
# endif
# define DSS_prime_checks 64
/*
* Primality test according to FIPS PUB 186-4, Appendix C.3. Since we only
* have one value here we set the number of checks to 64 which is the 128 bit
* security level that is the highest level and valid for creating a 3072 bit
* DSA key.
*/
# define DSA_is_prime(n, callback, cb_arg) \
BN_is_prime(n, DSS_prime_checks, callback, NULL, cb_arg)
# ifndef OPENSSL_NO_DH
/*
* Convert DSA structure (key or just parameters) into DH structure (be
* careful to avoid small subgroup attacks when using this!)
*/
DH *DSA_dup_DH(const DSA *r);
# endif
# define EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, nbits) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DSA_PARAMGEN_BITS, nbits, NULL)
# define EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, qbits) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, qbits, NULL)
# define EVP_PKEY_CTX_set_dsa_paramgen_md(ctx, md) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DSA_PARAMGEN_MD, 0, (void *)(md))
# define EVP_PKEY_CTRL_DSA_PARAMGEN_BITS (EVP_PKEY_ALG_CTRL + 1)
# define EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS (EVP_PKEY_ALG_CTRL + 2)
# define EVP_PKEY_CTRL_DSA_PARAMGEN_MD (EVP_PKEY_ALG_CTRL + 3)
void DSA_get0_pqg(const DSA *d,
const BIGNUM **p, const BIGNUM **q, const BIGNUM **g);
int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g);
void DSA_get0_key(const DSA *d,
const BIGNUM **pub_key, const BIGNUM **priv_key);
int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key);
const BIGNUM *DSA_get0_p(const DSA *d);
const BIGNUM *DSA_get0_q(const DSA *d);
const BIGNUM *DSA_get0_g(const DSA *d);
const BIGNUM *DSA_get0_pub_key(const DSA *d);
const BIGNUM *DSA_get0_priv_key(const DSA *d);
void DSA_clear_flags(DSA *d, int flags);
int DSA_test_flags(const DSA *d, int flags);
void DSA_set_flags(DSA *d, int flags);
ENGINE *DSA_get0_engine(DSA *d);
DSA_METHOD *DSA_meth_new(const char *name, int flags);
void DSA_meth_free(DSA_METHOD *dsam);
DSA_METHOD *DSA_meth_dup(const DSA_METHOD *dsam);
const char *DSA_meth_get0_name(const DSA_METHOD *dsam);
int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name);
int DSA_meth_get_flags(const DSA_METHOD *dsam);
int DSA_meth_set_flags(DSA_METHOD *dsam, int flags);
void *DSA_meth_get0_app_data(const DSA_METHOD *dsam);
int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data);
DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam))
(const unsigned char *, int, DSA *);
int DSA_meth_set_sign(DSA_METHOD *dsam,
DSA_SIG *(*sign) (const unsigned char *, int, DSA *));
int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam))
(DSA *, BN_CTX *, BIGNUM **, BIGNUM **);
int DSA_meth_set_sign_setup(DSA_METHOD *dsam,
int (*sign_setup) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **));
int (*DSA_meth_get_verify(const DSA_METHOD *dsam))
(const unsigned char *, int, DSA_SIG *, DSA *);
int DSA_meth_set_verify(DSA_METHOD *dsam,
int (*verify) (const unsigned char *, int, DSA_SIG *, DSA *));
int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam))
(DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *,
const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *);
int DSA_meth_set_mod_exp(DSA_METHOD *dsam,
int (*mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *,
const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *,
BN_MONT_CTX *));
int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam))
(DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *,
BN_CTX *, BN_MONT_CTX *);
int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam,
int (*bn_mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *,
const BIGNUM *, BN_CTX *, BN_MONT_CTX *));
int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *);
int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *));
int (*DSA_meth_get_finish(const DSA_METHOD *dsam)) (DSA *);
int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish) (DSA *));
int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam))
(DSA *, int, const unsigned char *, int, int *, unsigned long *,
BN_GENCB *);
int DSA_meth_set_paramgen(DSA_METHOD *dsam,
int (*paramgen) (DSA *, int, const unsigned char *, int, int *,
unsigned long *, BN_GENCB *));
int (*DSA_meth_get_keygen(const DSA_METHOD *dsam)) (DSA *);
int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen) (DSA *));
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,72 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_DSAERR_H
# define HEADER_DSAERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_DSA
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_DSA_strings(void);
/*
* DSA function codes.
*/
# define DSA_F_DSAPARAMS_PRINT 100
# define DSA_F_DSAPARAMS_PRINT_FP 101
# define DSA_F_DSA_BUILTIN_PARAMGEN 125
# define DSA_F_DSA_BUILTIN_PARAMGEN2 126
# define DSA_F_DSA_DO_SIGN 112
# define DSA_F_DSA_DO_VERIFY 113
# define DSA_F_DSA_METH_DUP 127
# define DSA_F_DSA_METH_NEW 128
# define DSA_F_DSA_METH_SET1_NAME 129
# define DSA_F_DSA_NEW_METHOD 103
# define DSA_F_DSA_PARAM_DECODE 119
# define DSA_F_DSA_PRINT_FP 105
# define DSA_F_DSA_PRIV_DECODE 115
# define DSA_F_DSA_PRIV_ENCODE 116
# define DSA_F_DSA_PUB_DECODE 117
# define DSA_F_DSA_PUB_ENCODE 118
# define DSA_F_DSA_SIGN 106
# define DSA_F_DSA_SIGN_SETUP 107
# define DSA_F_DSA_SIG_NEW 102
# define DSA_F_OLD_DSA_PRIV_DECODE 122
# define DSA_F_PKEY_DSA_CTRL 120
# define DSA_F_PKEY_DSA_CTRL_STR 104
# define DSA_F_PKEY_DSA_KEYGEN 121
/*
* DSA reason codes.
*/
# define DSA_R_BAD_Q_VALUE 102
# define DSA_R_BN_DECODE_ERROR 108
# define DSA_R_BN_ERROR 109
# define DSA_R_DECODE_ERROR 104
# define DSA_R_INVALID_DIGEST_TYPE 106
# define DSA_R_INVALID_PARAMETERS 112
# define DSA_R_MISSING_PARAMETERS 101
# define DSA_R_MISSING_PRIVATE_KEY 111
# define DSA_R_MODULUS_TOO_LARGE 103
# define DSA_R_NO_PARAMETERS_SET 107
# define DSA_R_PARAMETER_ENCODING_ERROR 105
# define DSA_R_Q_NOT_PRIME 113
# define DSA_R_SEED_LEN_SMALL 110
# endif
#endif

@ -0,0 +1,55 @@
/*
* Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_DTLS1_H
# define HEADER_DTLS1_H
#ifdef __cplusplus
extern "C" {
#endif
# define DTLS1_VERSION 0xFEFF
# define DTLS1_2_VERSION 0xFEFD
# define DTLS_MIN_VERSION DTLS1_VERSION
# define DTLS_MAX_VERSION DTLS1_2_VERSION
# define DTLS1_VERSION_MAJOR 0xFE
# define DTLS1_BAD_VER 0x0100
/* Special value for method supporting multiple versions */
# define DTLS_ANY_VERSION 0x1FFFF
/* lengths of messages */
/*
* Actually the max cookie length in DTLS is 255. But we can't change this now
* due to compatibility concerns.
*/
# define DTLS1_COOKIE_LENGTH 256
# define DTLS1_RT_HEADER_LENGTH 13
# define DTLS1_HM_HEADER_LENGTH 12
# define DTLS1_HM_BAD_FRAGMENT -2
# define DTLS1_HM_FRAGMENT_RETRY -3
# define DTLS1_CCS_HEADER_LENGTH 1
# define DTLS1_AL_HEADER_LENGTH 2
/* Timeout multipliers */
# define DTLS1_TMO_READ_COUNT 2
# define DTLS1_TMO_WRITE_COUNT 2
# define DTLS1_TMO_ALERT_COUNT 12
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,300 @@
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_E_OS2_H
# define HEADER_E_OS2_H
# include <openssl/opensslconf.h>
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************************************
* Detect operating systems. This probably needs completing.
* The result is that at least one OPENSSL_SYS_os macro should be defined.
* However, if none is defined, Unix is assumed.
**/
# define OPENSSL_SYS_UNIX
/* --------------------- Microsoft operating systems ---------------------- */
/*
* Note that MSDOS actually denotes 32-bit environments running on top of
* MS-DOS, such as DJGPP one.
*/
# if defined(OPENSSL_SYS_MSDOS)
# undef OPENSSL_SYS_UNIX
# endif
/*
* For 32 bit environment, there seems to be the CygWin environment and then
* all the others that try to do the same thing Microsoft does...
*/
/*
* UEFI lives here because it might be built with a Microsoft toolchain and
* we need to avoid the false positive match on Windows.
*/
# if defined(OPENSSL_SYS_UEFI)
# undef OPENSSL_SYS_UNIX
# elif defined(OPENSSL_SYS_UWIN)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_WIN32_UWIN
# else
# if defined(__CYGWIN__) || defined(OPENSSL_SYS_CYGWIN)
# define OPENSSL_SYS_WIN32_CYGWIN
# else
# if defined(_WIN32) || defined(OPENSSL_SYS_WIN32)
# undef OPENSSL_SYS_UNIX
# if !defined(OPENSSL_SYS_WIN32)
# define OPENSSL_SYS_WIN32
# endif
# endif
# if defined(_WIN64) || defined(OPENSSL_SYS_WIN64)
# undef OPENSSL_SYS_UNIX
# if !defined(OPENSSL_SYS_WIN64)
# define OPENSSL_SYS_WIN64
# endif
# endif
# if defined(OPENSSL_SYS_WINNT)
# undef OPENSSL_SYS_UNIX
# endif
# if defined(OPENSSL_SYS_WINCE)
# undef OPENSSL_SYS_UNIX
# endif
# endif
# endif
/* Anything that tries to look like Microsoft is "Windows" */
# if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN64) || defined(OPENSSL_SYS_WINNT) || defined(OPENSSL_SYS_WINCE)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_WINDOWS
# ifndef OPENSSL_SYS_MSDOS
# define OPENSSL_SYS_MSDOS
# endif
# endif
/*
* DLL settings. This part is a bit tough, because it's up to the
* application implementor how he or she will link the application, so it
* requires some macro to be used.
*/
# ifdef OPENSSL_SYS_WINDOWS
# ifndef OPENSSL_OPT_WINDLL
# if defined(_WINDLL) /* This is used when building OpenSSL to
* indicate that DLL linkage should be used */
# define OPENSSL_OPT_WINDLL
# endif
# endif
# endif
/* ------------------------------- OpenVMS -------------------------------- */
# if defined(__VMS) || defined(VMS) || defined(OPENSSL_SYS_VMS)
# if !defined(OPENSSL_SYS_VMS)
# undef OPENSSL_SYS_UNIX
# endif
# define OPENSSL_SYS_VMS
# if defined(__DECC)
# define OPENSSL_SYS_VMS_DECC
# elif defined(__DECCXX)
# define OPENSSL_SYS_VMS_DECC
# define OPENSSL_SYS_VMS_DECCXX
# else
# define OPENSSL_SYS_VMS_NODECC
# endif
# endif
/* -------------------------------- Unix ---------------------------------- */
# ifdef OPENSSL_SYS_UNIX
# if defined(linux) || defined(__linux__) && !defined(OPENSSL_SYS_LINUX)
# define OPENSSL_SYS_LINUX
# endif
# if defined(_AIX) && !defined(OPENSSL_SYS_AIX)
# define OPENSSL_SYS_AIX
# endif
# endif
/* -------------------------------- VOS ----------------------------------- */
# if defined(__VOS__) && !defined(OPENSSL_SYS_VOS)
# define OPENSSL_SYS_VOS
# ifdef __HPPA__
# define OPENSSL_SYS_VOS_HPPA
# endif
# ifdef __IA32__
# define OPENSSL_SYS_VOS_IA32
# endif
# endif
/**
* That's it for OS-specific stuff
*****************************************************************************/
/* Specials for I/O an exit */
# ifdef OPENSSL_SYS_MSDOS
# define OPENSSL_UNISTD_IO <io.h>
# define OPENSSL_DECLARE_EXIT extern void exit(int);
# else
# define OPENSSL_UNISTD_IO OPENSSL_UNISTD
# define OPENSSL_DECLARE_EXIT /* declared in unistd.h */
# endif
/*-
* OPENSSL_EXTERN is normally used to declare a symbol with possible extra
* attributes to handle its presence in a shared library.
* OPENSSL_EXPORT is used to define a symbol with extra possible attributes
* to make it visible in a shared library.
* Care needs to be taken when a header file is used both to declare and
* define symbols. Basically, for any library that exports some global
* variables, the following code must be present in the header file that
* declares them, before OPENSSL_EXTERN is used:
*
* #ifdef SOME_BUILD_FLAG_MACRO
* # undef OPENSSL_EXTERN
* # define OPENSSL_EXTERN OPENSSL_EXPORT
* #endif
*
* The default is to have OPENSSL_EXPORT and OPENSSL_EXTERN
* have some generally sensible values.
*/
# if defined(OPENSSL_SYS_WINDOWS) && defined(OPENSSL_OPT_WINDLL)
# define OPENSSL_EXPORT extern __declspec(dllexport)
# define OPENSSL_EXTERN extern __declspec(dllimport)
# else
# define OPENSSL_EXPORT extern
# define OPENSSL_EXTERN extern
# endif
/*-
* Macros to allow global variables to be reached through function calls when
* required (if a shared library version requires it, for example.
* The way it's done allows definitions like this:
*
* // in foobar.c
* OPENSSL_IMPLEMENT_GLOBAL(int,foobar,0)
* // in foobar.h
* OPENSSL_DECLARE_GLOBAL(int,foobar);
* #define foobar OPENSSL_GLOBAL_REF(foobar)
*/
# ifdef OPENSSL_EXPORT_VAR_AS_FUNCTION
# define OPENSSL_IMPLEMENT_GLOBAL(type,name,value) \
type *_shadow_##name(void) \
{ static type _hide_##name=value; return &_hide_##name; }
# define OPENSSL_DECLARE_GLOBAL(type,name) type *_shadow_##name(void)
# define OPENSSL_GLOBAL_REF(name) (*(_shadow_##name()))
# else
# define OPENSSL_IMPLEMENT_GLOBAL(type,name,value) type _shadow_##name=value;
# define OPENSSL_DECLARE_GLOBAL(type,name) OPENSSL_EXPORT type _shadow_##name
# define OPENSSL_GLOBAL_REF(name) _shadow_##name
# endif
# ifdef _WIN32
# ifdef _WIN64
# define ossl_ssize_t __int64
# define OSSL_SSIZE_MAX _I64_MAX
# else
# define ossl_ssize_t int
# define OSSL_SSIZE_MAX INT_MAX
# endif
# endif
# if defined(OPENSSL_SYS_UEFI) && !defined(ossl_ssize_t)
# define ossl_ssize_t INTN
# define OSSL_SSIZE_MAX MAX_INTN
# endif
# ifndef ossl_ssize_t
# define ossl_ssize_t ssize_t
# if defined(SSIZE_MAX)
# define OSSL_SSIZE_MAX SSIZE_MAX
# elif defined(_POSIX_SSIZE_MAX)
# define OSSL_SSIZE_MAX _POSIX_SSIZE_MAX
# else
# define OSSL_SSIZE_MAX ((ssize_t)(SIZE_MAX>>1))
# endif
# endif
# ifdef DEBUG_UNUSED
# define __owur __attribute__((__warn_unused_result__))
# else
# define __owur
# endif
/* Standard integer types */
# if defined(OPENSSL_SYS_UEFI)
typedef INT8 int8_t;
typedef UINT8 uint8_t;
typedef INT16 int16_t;
typedef UINT16 uint16_t;
typedef INT32 int32_t;
typedef UINT32 uint32_t;
typedef INT64 int64_t;
typedef UINT64 uint64_t;
# elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \
defined(__osf__) || defined(__sgi) || defined(__hpux) || \
defined(OPENSSL_SYS_VMS) || defined (__OpenBSD__)
# include <inttypes.h>
# elif defined(_MSC_VER) && _MSC_VER<1600
/*
* minimally required typdefs for systems not supporting inttypes.h or
* stdint.h: currently just older VC++
*/
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
# else
# include <stdint.h>
# endif
/* ossl_inline: portable inline definition usable in public headers */
# if !defined(inline) && !defined(__cplusplus)
# if defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L
/* just use inline */
# define ossl_inline inline
# elif defined(__GNUC__) && __GNUC__>=2
# define ossl_inline __inline__
# elif defined(_MSC_VER)
/*
* Visual Studio: inline is available in C++ only, however
* __inline is available for C, see
* http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx
*/
# define ossl_inline __inline
# else
# define ossl_inline
# endif
# else
# define ossl_inline inline
# endif
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
# define ossl_noreturn _Noreturn
# elif defined(__GNUC__) && __GNUC__ >= 2
# define ossl_noreturn __attribute__((noreturn))
# else
# define ossl_noreturn
# endif
/* ossl_unused: portable unused attribute for use in public headers */
# if defined(__GNUC__)
# define ossl_unused __attribute__((unused))
# else
# define ossl_unused
# endif
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,33 @@
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_EBCDIC_H
# define HEADER_EBCDIC_H
# include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Avoid name clashes with other applications */
# define os_toascii _openssl_os_toascii
# define os_toebcdic _openssl_os_toebcdic
# define ebcdic2ascii _openssl_ebcdic2ascii
# define ascii2ebcdic _openssl_ascii2ebcdic
extern const unsigned char os_toascii[256];
extern const unsigned char os_toebcdic[256];
void *ebcdic2ascii(void *dest, const void *srce, size_t count);
void *ascii2ebcdic(void *dest, const void *srce, size_t count);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

@ -0,0 +1,10 @@
/*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/ec.h>

@ -0,0 +1,10 @@
/*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/ec.h>

@ -0,0 +1,276 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ECERR_H
# define HEADER_ECERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_EC
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_EC_strings(void);
/*
* EC function codes.
*/
# define EC_F_BN_TO_FELEM 224
# define EC_F_D2I_ECPARAMETERS 144
# define EC_F_D2I_ECPKPARAMETERS 145
# define EC_F_D2I_ECPRIVATEKEY 146
# define EC_F_DO_EC_KEY_PRINT 221
# define EC_F_ECDH_CMS_DECRYPT 238
# define EC_F_ECDH_CMS_SET_SHARED_INFO 239
# define EC_F_ECDH_COMPUTE_KEY 246
# define EC_F_ECDH_SIMPLE_COMPUTE_KEY 257
# define EC_F_ECDSA_DO_SIGN_EX 251
# define EC_F_ECDSA_DO_VERIFY 252
# define EC_F_ECDSA_SIGN_EX 254
# define EC_F_ECDSA_SIGN_SETUP 248
# define EC_F_ECDSA_SIG_NEW 265
# define EC_F_ECDSA_VERIFY 253
# define EC_F_ECD_ITEM_VERIFY 270
# define EC_F_ECKEY_PARAM2TYPE 223
# define EC_F_ECKEY_PARAM_DECODE 212
# define EC_F_ECKEY_PRIV_DECODE 213
# define EC_F_ECKEY_PRIV_ENCODE 214
# define EC_F_ECKEY_PUB_DECODE 215
# define EC_F_ECKEY_PUB_ENCODE 216
# define EC_F_ECKEY_TYPE2PARAM 220
# define EC_F_ECPARAMETERS_PRINT 147
# define EC_F_ECPARAMETERS_PRINT_FP 148
# define EC_F_ECPKPARAMETERS_PRINT 149
# define EC_F_ECPKPARAMETERS_PRINT_FP 150
# define EC_F_ECP_NISTZ256_GET_AFFINE 240
# define EC_F_ECP_NISTZ256_INV_MOD_ORD 275
# define EC_F_ECP_NISTZ256_MULT_PRECOMPUTE 243
# define EC_F_ECP_NISTZ256_POINTS_MUL 241
# define EC_F_ECP_NISTZ256_PRE_COMP_NEW 244
# define EC_F_ECP_NISTZ256_WINDOWED_MUL 242
# define EC_F_ECX_KEY_OP 266
# define EC_F_ECX_PRIV_ENCODE 267
# define EC_F_ECX_PUB_ENCODE 268
# define EC_F_EC_ASN1_GROUP2CURVE 153
# define EC_F_EC_ASN1_GROUP2FIELDID 154
# define EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY 208
# define EC_F_EC_GF2M_SIMPLE_FIELD_INV 296
# define EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT 159
# define EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE 195
# define EC_F_EC_GF2M_SIMPLE_LADDER_POST 285
# define EC_F_EC_GF2M_SIMPLE_LADDER_PRE 288
# define EC_F_EC_GF2M_SIMPLE_OCT2POINT 160
# define EC_F_EC_GF2M_SIMPLE_POINT2OCT 161
# define EC_F_EC_GF2M_SIMPLE_POINTS_MUL 289
# define EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES 162
# define EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES 163
# define EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES 164
# define EC_F_EC_GFP_MONT_FIELD_DECODE 133
# define EC_F_EC_GFP_MONT_FIELD_ENCODE 134
# define EC_F_EC_GFP_MONT_FIELD_INV 297
# define EC_F_EC_GFP_MONT_FIELD_MUL 131
# define EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE 209
# define EC_F_EC_GFP_MONT_FIELD_SQR 132
# define EC_F_EC_GFP_MONT_GROUP_SET_CURVE 189
# define EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE 225
# define EC_F_EC_GFP_NISTP224_POINTS_MUL 228
# define EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES 226
# define EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE 230
# define EC_F_EC_GFP_NISTP256_POINTS_MUL 231
# define EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES 232
# define EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE 233
# define EC_F_EC_GFP_NISTP521_POINTS_MUL 234
# define EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES 235
# define EC_F_EC_GFP_NIST_FIELD_MUL 200
# define EC_F_EC_GFP_NIST_FIELD_SQR 201
# define EC_F_EC_GFP_NIST_GROUP_SET_CURVE 202
# define EC_F_EC_GFP_SIMPLE_BLIND_COORDINATES 287
# define EC_F_EC_GFP_SIMPLE_FIELD_INV 298
# define EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT 165
# define EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE 166
# define EC_F_EC_GFP_SIMPLE_MAKE_AFFINE 102
# define EC_F_EC_GFP_SIMPLE_OCT2POINT 103
# define EC_F_EC_GFP_SIMPLE_POINT2OCT 104
# define EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE 137
# define EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES 167
# define EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES 168
# define EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES 169
# define EC_F_EC_GROUP_CHECK 170
# define EC_F_EC_GROUP_CHECK_DISCRIMINANT 171
# define EC_F_EC_GROUP_COPY 106
# define EC_F_EC_GROUP_GET_CURVE 291
# define EC_F_EC_GROUP_GET_CURVE_GF2M 172
# define EC_F_EC_GROUP_GET_CURVE_GFP 130
# define EC_F_EC_GROUP_GET_DEGREE 173
# define EC_F_EC_GROUP_GET_ECPARAMETERS 261
# define EC_F_EC_GROUP_GET_ECPKPARAMETERS 262
# define EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS 193
# define EC_F_EC_GROUP_GET_TRINOMIAL_BASIS 194
# define EC_F_EC_GROUP_NEW 108
# define EC_F_EC_GROUP_NEW_BY_CURVE_NAME 174
# define EC_F_EC_GROUP_NEW_FROM_DATA 175
# define EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS 263
# define EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS 264
# define EC_F_EC_GROUP_SET_CURVE 292
# define EC_F_EC_GROUP_SET_CURVE_GF2M 176
# define EC_F_EC_GROUP_SET_CURVE_GFP 109
# define EC_F_EC_GROUP_SET_GENERATOR 111
# define EC_F_EC_GROUP_SET_SEED 286
# define EC_F_EC_KEY_CHECK_KEY 177
# define EC_F_EC_KEY_COPY 178
# define EC_F_EC_KEY_GENERATE_KEY 179
# define EC_F_EC_KEY_NEW 182
# define EC_F_EC_KEY_NEW_METHOD 245
# define EC_F_EC_KEY_OCT2PRIV 255
# define EC_F_EC_KEY_PRINT 180
# define EC_F_EC_KEY_PRINT_FP 181
# define EC_F_EC_KEY_PRIV2BUF 279
# define EC_F_EC_KEY_PRIV2OCT 256
# define EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES 229
# define EC_F_EC_KEY_SIMPLE_CHECK_KEY 258
# define EC_F_EC_KEY_SIMPLE_OCT2PRIV 259
# define EC_F_EC_KEY_SIMPLE_PRIV2OCT 260
# define EC_F_EC_PKEY_CHECK 273
# define EC_F_EC_PKEY_PARAM_CHECK 274
# define EC_F_EC_POINTS_MAKE_AFFINE 136
# define EC_F_EC_POINTS_MUL 290
# define EC_F_EC_POINT_ADD 112
# define EC_F_EC_POINT_BN2POINT 280
# define EC_F_EC_POINT_CMP 113
# define EC_F_EC_POINT_COPY 114
# define EC_F_EC_POINT_DBL 115
# define EC_F_EC_POINT_GET_AFFINE_COORDINATES 293
# define EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M 183
# define EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP 116
# define EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP 117
# define EC_F_EC_POINT_INVERT 210
# define EC_F_EC_POINT_IS_AT_INFINITY 118
# define EC_F_EC_POINT_IS_ON_CURVE 119
# define EC_F_EC_POINT_MAKE_AFFINE 120
# define EC_F_EC_POINT_NEW 121
# define EC_F_EC_POINT_OCT2POINT 122
# define EC_F_EC_POINT_POINT2BUF 281
# define EC_F_EC_POINT_POINT2OCT 123
# define EC_F_EC_POINT_SET_AFFINE_COORDINATES 294
# define EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M 185
# define EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP 124
# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES 295
# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M 186
# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP 125
# define EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP 126
# define EC_F_EC_POINT_SET_TO_INFINITY 127
# define EC_F_EC_PRE_COMP_NEW 196
# define EC_F_EC_SCALAR_MUL_LADDER 284
# define EC_F_EC_WNAF_MUL 187
# define EC_F_EC_WNAF_PRECOMPUTE_MULT 188
# define EC_F_I2D_ECPARAMETERS 190
# define EC_F_I2D_ECPKPARAMETERS 191
# define EC_F_I2D_ECPRIVATEKEY 192
# define EC_F_I2O_ECPUBLICKEY 151
# define EC_F_NISTP224_PRE_COMP_NEW 227
# define EC_F_NISTP256_PRE_COMP_NEW 236
# define EC_F_NISTP521_PRE_COMP_NEW 237
# define EC_F_O2I_ECPUBLICKEY 152
# define EC_F_OLD_EC_PRIV_DECODE 222
# define EC_F_OSSL_ECDH_COMPUTE_KEY 247
# define EC_F_OSSL_ECDSA_SIGN_SIG 249
# define EC_F_OSSL_ECDSA_VERIFY_SIG 250
# define EC_F_PKEY_ECD_CTRL 271
# define EC_F_PKEY_ECD_DIGESTSIGN 272
# define EC_F_PKEY_ECD_DIGESTSIGN25519 276
# define EC_F_PKEY_ECD_DIGESTSIGN448 277
# define EC_F_PKEY_ECX_DERIVE 269
# define EC_F_PKEY_EC_CTRL 197
# define EC_F_PKEY_EC_CTRL_STR 198
# define EC_F_PKEY_EC_DERIVE 217
# define EC_F_PKEY_EC_INIT 282
# define EC_F_PKEY_EC_KDF_DERIVE 283
# define EC_F_PKEY_EC_KEYGEN 199
# define EC_F_PKEY_EC_PARAMGEN 219
# define EC_F_PKEY_EC_SIGN 218
# define EC_F_VALIDATE_ECX_DERIVE 278
/*
* EC reason codes.
*/
# define EC_R_ASN1_ERROR 115
# define EC_R_BAD_SIGNATURE 156
# define EC_R_BIGNUM_OUT_OF_RANGE 144
# define EC_R_BUFFER_TOO_SMALL 100
# define EC_R_CANNOT_INVERT 165
# define EC_R_COORDINATES_OUT_OF_RANGE 146
# define EC_R_CURVE_DOES_NOT_SUPPORT_ECDH 160
# define EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING 159
# define EC_R_D2I_ECPKPARAMETERS_FAILURE 117
# define EC_R_DECODE_ERROR 142
# define EC_R_DISCRIMINANT_IS_ZERO 118
# define EC_R_EC_GROUP_NEW_BY_NAME_FAILURE 119
# define EC_R_FIELD_TOO_LARGE 143
# define EC_R_GF2M_NOT_SUPPORTED 147
# define EC_R_GROUP2PKPARAMETERS_FAILURE 120
# define EC_R_I2D_ECPKPARAMETERS_FAILURE 121
# define EC_R_INCOMPATIBLE_OBJECTS 101
# define EC_R_INVALID_ARGUMENT 112
# define EC_R_INVALID_COMPRESSED_POINT 110
# define EC_R_INVALID_COMPRESSION_BIT 109
# define EC_R_INVALID_CURVE 141
# define EC_R_INVALID_DIGEST 151
# define EC_R_INVALID_DIGEST_TYPE 138
# define EC_R_INVALID_ENCODING 102
# define EC_R_INVALID_FIELD 103
# define EC_R_INVALID_FORM 104
# define EC_R_INVALID_GROUP_ORDER 122
# define EC_R_INVALID_KEY 116
# define EC_R_INVALID_OUTPUT_LENGTH 161
# define EC_R_INVALID_PEER_KEY 133
# define EC_R_INVALID_PENTANOMIAL_BASIS 132
# define EC_R_INVALID_PRIVATE_KEY 123
# define EC_R_INVALID_TRINOMIAL_BASIS 137
# define EC_R_KDF_PARAMETER_ERROR 148
# define EC_R_KEYS_NOT_SET 140
# define EC_R_LADDER_POST_FAILURE 136
# define EC_R_LADDER_PRE_FAILURE 153
# define EC_R_LADDER_STEP_FAILURE 162
# define EC_R_MISSING_OID 167
# define EC_R_MISSING_PARAMETERS 124
# define EC_R_MISSING_PRIVATE_KEY 125
# define EC_R_NEED_NEW_SETUP_VALUES 157
# define EC_R_NOT_A_NIST_PRIME 135
# define EC_R_NOT_IMPLEMENTED 126
# define EC_R_NOT_INITIALIZED 111
# define EC_R_NO_PARAMETERS_SET 139
# define EC_R_NO_PRIVATE_VALUE 154
# define EC_R_OPERATION_NOT_SUPPORTED 152
# define EC_R_PASSED_NULL_PARAMETER 134
# define EC_R_PEER_KEY_ERROR 149
# define EC_R_PKPARAMETERS2GROUP_FAILURE 127
# define EC_R_POINT_ARITHMETIC_FAILURE 155
# define EC_R_POINT_AT_INFINITY 106
# define EC_R_POINT_COORDINATES_BLIND_FAILURE 163
# define EC_R_POINT_IS_NOT_ON_CURVE 107
# define EC_R_RANDOM_NUMBER_GENERATION_FAILED 158
# define EC_R_SHARED_INFO_ERROR 150
# define EC_R_SLOT_FULL 108
# define EC_R_UNDEFINED_GENERATOR 113
# define EC_R_UNDEFINED_ORDER 128
# define EC_R_UNKNOWN_COFACTOR 164
# define EC_R_UNKNOWN_GROUP 129
# define EC_R_UNKNOWN_ORDER 114
# define EC_R_UNSUPPORTED_FIELD 131
# define EC_R_WRONG_CURVE_PARAMETERS 145
# define EC_R_WRONG_ORDER 130
# endif
#endif

@ -0,0 +1,751 @@
/*
* Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ENGINE_H
# define HEADER_ENGINE_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_ENGINE
# if OPENSSL_API_COMPAT < 0x10100000L
# include <openssl/bn.h>
# include <openssl/rsa.h>
# include <openssl/dsa.h>
# include <openssl/dh.h>
# include <openssl/ec.h>
# include <openssl/rand.h>
# include <openssl/ui.h>
# include <openssl/err.h>
# endif
# include <openssl/ossl_typ.h>
# include <openssl/symhacks.h>
# include <openssl/x509.h>
# include <openssl/engineerr.h>
# ifdef __cplusplus
extern "C" {
# endif
/*
* These flags are used to control combinations of algorithm (methods) by
* bitwise "OR"ing.
*/
# define ENGINE_METHOD_RSA (unsigned int)0x0001
# define ENGINE_METHOD_DSA (unsigned int)0x0002
# define ENGINE_METHOD_DH (unsigned int)0x0004
# define ENGINE_METHOD_RAND (unsigned int)0x0008
# define ENGINE_METHOD_CIPHERS (unsigned int)0x0040
# define ENGINE_METHOD_DIGESTS (unsigned int)0x0080
# define ENGINE_METHOD_PKEY_METHS (unsigned int)0x0200
# define ENGINE_METHOD_PKEY_ASN1_METHS (unsigned int)0x0400
# define ENGINE_METHOD_EC (unsigned int)0x0800
/* Obvious all-or-nothing cases. */
# define ENGINE_METHOD_ALL (unsigned int)0xFFFF
# define ENGINE_METHOD_NONE (unsigned int)0x0000
/*
* This(ese) flag(s) controls behaviour of the ENGINE_TABLE mechanism used
* internally to control registration of ENGINE implementations, and can be
* set by ENGINE_set_table_flags(). The "NOINIT" flag prevents attempts to
* initialise registered ENGINEs if they are not already initialised.
*/
# define ENGINE_TABLE_FLAG_NOINIT (unsigned int)0x0001
/* ENGINE flags that can be set by ENGINE_set_flags(). */
/* Not used */
/* #define ENGINE_FLAGS_MALLOCED 0x0001 */
/*
* This flag is for ENGINEs that wish to handle the various 'CMD'-related
* control commands on their own. Without this flag, ENGINE_ctrl() handles
* these control commands on behalf of the ENGINE using their "cmd_defns"
* data.
*/
# define ENGINE_FLAGS_MANUAL_CMD_CTRL (int)0x0002
/*
* This flag is for ENGINEs who return new duplicate structures when found
* via "ENGINE_by_id()". When an ENGINE must store state (eg. if
* ENGINE_ctrl() commands are called in sequence as part of some stateful
* process like key-generation setup and execution), it can set this flag -
* then each attempt to obtain the ENGINE will result in it being copied into
* a new structure. Normally, ENGINEs don't declare this flag so
* ENGINE_by_id() just increments the existing ENGINE's structural reference
* count.
*/
# define ENGINE_FLAGS_BY_ID_COPY (int)0x0004
/*
* This flag if for an ENGINE that does not want its methods registered as
* part of ENGINE_register_all_complete() for example if the methods are not
* usable as default methods.
*/
# define ENGINE_FLAGS_NO_REGISTER_ALL (int)0x0008
/*
* ENGINEs can support their own command types, and these flags are used in
* ENGINE_CTRL_GET_CMD_FLAGS to indicate to the caller what kind of input
* each command expects. Currently only numeric and string input is
* supported. If a control command supports none of the _NUMERIC, _STRING, or
* _NO_INPUT options, then it is regarded as an "internal" control command -
* and not for use in config setting situations. As such, they're not
* available to the ENGINE_ctrl_cmd_string() function, only raw ENGINE_ctrl()
* access. Changes to this list of 'command types' should be reflected
* carefully in ENGINE_cmd_is_executable() and ENGINE_ctrl_cmd_string().
*/
/* accepts a 'long' input value (3rd parameter to ENGINE_ctrl) */
# define ENGINE_CMD_FLAG_NUMERIC (unsigned int)0x0001
/*
* accepts string input (cast from 'void*' to 'const char *', 4th parameter
* to ENGINE_ctrl)
*/
# define ENGINE_CMD_FLAG_STRING (unsigned int)0x0002
/*
* Indicates that the control command takes *no* input. Ie. the control
* command is unparameterised.
*/
# define ENGINE_CMD_FLAG_NO_INPUT (unsigned int)0x0004
/*
* Indicates that the control command is internal. This control command won't
* be shown in any output, and is only usable through the ENGINE_ctrl_cmd()
* function.
*/
# define ENGINE_CMD_FLAG_INTERNAL (unsigned int)0x0008
/*
* NB: These 3 control commands are deprecated and should not be used.
* ENGINEs relying on these commands should compile conditional support for
* compatibility (eg. if these symbols are defined) but should also migrate
* the same functionality to their own ENGINE-specific control functions that
* can be "discovered" by calling applications. The fact these control
* commands wouldn't be "executable" (ie. usable by text-based config)
* doesn't change the fact that application code can find and use them
* without requiring per-ENGINE hacking.
*/
/*
* These flags are used to tell the ctrl function what should be done. All
* command numbers are shared between all engines, even if some don't make
* sense to some engines. In such a case, they do nothing but return the
* error ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED.
*/
# define ENGINE_CTRL_SET_LOGSTREAM 1
# define ENGINE_CTRL_SET_PASSWORD_CALLBACK 2
# define ENGINE_CTRL_HUP 3/* Close and reinitialise
* any handles/connections
* etc. */
# define ENGINE_CTRL_SET_USER_INTERFACE 4/* Alternative to callback */
# define ENGINE_CTRL_SET_CALLBACK_DATA 5/* User-specific data, used
* when calling the password
* callback and the user
* interface */
# define ENGINE_CTRL_LOAD_CONFIGURATION 6/* Load a configuration,
* given a string that
* represents a file name
* or so */
# define ENGINE_CTRL_LOAD_SECTION 7/* Load data from a given
* section in the already
* loaded configuration */
/*
* These control commands allow an application to deal with an arbitrary
* engine in a dynamic way. Warn: Negative return values indicate errors FOR
* THESE COMMANDS because zero is used to indicate 'end-of-list'. Other
* commands, including ENGINE-specific command types, return zero for an
* error. An ENGINE can choose to implement these ctrl functions, and can
* internally manage things however it chooses - it does so by setting the
* ENGINE_FLAGS_MANUAL_CMD_CTRL flag (using ENGINE_set_flags()). Otherwise
* the ENGINE_ctrl() code handles this on the ENGINE's behalf using the
* cmd_defns data (set using ENGINE_set_cmd_defns()). This means an ENGINE's
* ctrl() handler need only implement its own commands - the above "meta"
* commands will be taken care of.
*/
/*
* Returns non-zero if the supplied ENGINE has a ctrl() handler. If "not",
* then all the remaining control commands will return failure, so it is
* worth checking this first if the caller is trying to "discover" the
* engine's capabilities and doesn't want errors generated unnecessarily.
*/
# define ENGINE_CTRL_HAS_CTRL_FUNCTION 10
/*
* Returns a positive command number for the first command supported by the
* engine. Returns zero if no ctrl commands are supported.
*/
# define ENGINE_CTRL_GET_FIRST_CMD_TYPE 11
/*
* The 'long' argument specifies a command implemented by the engine, and the
* return value is the next command supported, or zero if there are no more.
*/
# define ENGINE_CTRL_GET_NEXT_CMD_TYPE 12
/*
* The 'void*' argument is a command name (cast from 'const char *'), and the
* return value is the command that corresponds to it.
*/
# define ENGINE_CTRL_GET_CMD_FROM_NAME 13
/*
* The next two allow a command to be converted into its corresponding string
* form. In each case, the 'long' argument supplies the command. In the
* NAME_LEN case, the return value is the length of the command name (not
* counting a trailing EOL). In the NAME case, the 'void*' argument must be a
* string buffer large enough, and it will be populated with the name of the
* command (WITH a trailing EOL).
*/
# define ENGINE_CTRL_GET_NAME_LEN_FROM_CMD 14
# define ENGINE_CTRL_GET_NAME_FROM_CMD 15
/* The next two are similar but give a "short description" of a command. */
# define ENGINE_CTRL_GET_DESC_LEN_FROM_CMD 16
# define ENGINE_CTRL_GET_DESC_FROM_CMD 17
/*
* With this command, the return value is the OR'd combination of
* ENGINE_CMD_FLAG_*** values that indicate what kind of input a given
* engine-specific ctrl command expects.
*/
# define ENGINE_CTRL_GET_CMD_FLAGS 18
/*
* ENGINE implementations should start the numbering of their own control
* commands from this value. (ie. ENGINE_CMD_BASE, ENGINE_CMD_BASE + 1, etc).
*/
# define ENGINE_CMD_BASE 200
/*
* NB: These 2 nCipher "chil" control commands are deprecated, and their
* functionality is now available through ENGINE-specific control commands
* (exposed through the above-mentioned 'CMD'-handling). Code using these 2
* commands should be migrated to the more general command handling before
* these are removed.
*/
/* Flags specific to the nCipher "chil" engine */
# define ENGINE_CTRL_CHIL_SET_FORKCHECK 100
/*
* Depending on the value of the (long)i argument, this sets or
* unsets the SimpleForkCheck flag in the CHIL API to enable or
* disable checking and workarounds for applications that fork().
*/
# define ENGINE_CTRL_CHIL_NO_LOCKING 101
/*
* This prevents the initialisation function from providing mutex
* callbacks to the nCipher library.
*/
/*
* If an ENGINE supports its own specific control commands and wishes the
* framework to handle the above 'ENGINE_CMD_***'-manipulation commands on
* its behalf, it should supply a null-terminated array of ENGINE_CMD_DEFN
* entries to ENGINE_set_cmd_defns(). It should also implement a ctrl()
* handler that supports the stated commands (ie. the "cmd_num" entries as
* described by the array). NB: The array must be ordered in increasing order
* of cmd_num. "null-terminated" means that the last ENGINE_CMD_DEFN element
* has cmd_num set to zero and/or cmd_name set to NULL.
*/
typedef struct ENGINE_CMD_DEFN_st {
unsigned int cmd_num; /* The command number */
const char *cmd_name; /* The command name itself */
const char *cmd_desc; /* A short description of the command */
unsigned int cmd_flags; /* The input the command expects */
} ENGINE_CMD_DEFN;
/* Generic function pointer */
typedef int (*ENGINE_GEN_FUNC_PTR) (void);
/* Generic function pointer taking no arguments */
typedef int (*ENGINE_GEN_INT_FUNC_PTR) (ENGINE *);
/* Specific control function pointer */
typedef int (*ENGINE_CTRL_FUNC_PTR) (ENGINE *, int, long, void *,
void (*f) (void));
/* Generic load_key function pointer */
typedef EVP_PKEY *(*ENGINE_LOAD_KEY_PTR)(ENGINE *, const char *,
UI_METHOD *ui_method,
void *callback_data);
typedef int (*ENGINE_SSL_CLIENT_CERT_PTR) (ENGINE *, SSL *ssl,
STACK_OF(X509_NAME) *ca_dn,
X509 **pcert, EVP_PKEY **pkey,
STACK_OF(X509) **pother,
UI_METHOD *ui_method,
void *callback_data);
/*-
* These callback types are for an ENGINE's handler for cipher and digest logic.
* These handlers have these prototypes;
* int foo(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid);
* int foo(ENGINE *e, const EVP_MD **digest, const int **nids, int nid);
* Looking at how to implement these handlers in the case of cipher support, if
* the framework wants the EVP_CIPHER for 'nid', it will call;
* foo(e, &p_evp_cipher, NULL, nid); (return zero for failure)
* If the framework wants a list of supported 'nid's, it will call;
* foo(e, NULL, &p_nids, 0); (returns number of 'nids' or -1 for error)
*/
/*
* Returns to a pointer to the array of supported cipher 'nid's. If the
* second parameter is non-NULL it is set to the size of the returned array.
*/
typedef int (*ENGINE_CIPHERS_PTR) (ENGINE *, const EVP_CIPHER **,
const int **, int);
typedef int (*ENGINE_DIGESTS_PTR) (ENGINE *, const EVP_MD **, const int **,
int);
typedef int (*ENGINE_PKEY_METHS_PTR) (ENGINE *, EVP_PKEY_METHOD **,
const int **, int);
typedef int (*ENGINE_PKEY_ASN1_METHS_PTR) (ENGINE *, EVP_PKEY_ASN1_METHOD **,
const int **, int);
/*
* STRUCTURE functions ... all of these functions deal with pointers to
* ENGINE structures where the pointers have a "structural reference". This
* means that their reference is to allowed access to the structure but it
* does not imply that the structure is functional. To simply increment or
* decrement the structural reference count, use ENGINE_by_id and
* ENGINE_free. NB: This is not required when iterating using ENGINE_get_next
* as it will automatically decrement the structural reference count of the
* "current" ENGINE and increment the structural reference count of the
* ENGINE it returns (unless it is NULL).
*/
/* Get the first/last "ENGINE" type available. */
ENGINE *ENGINE_get_first(void);
ENGINE *ENGINE_get_last(void);
/* Iterate to the next/previous "ENGINE" type (NULL = end of the list). */
ENGINE *ENGINE_get_next(ENGINE *e);
ENGINE *ENGINE_get_prev(ENGINE *e);
/* Add another "ENGINE" type into the array. */
int ENGINE_add(ENGINE *e);
/* Remove an existing "ENGINE" type from the array. */
int ENGINE_remove(ENGINE *e);
/* Retrieve an engine from the list by its unique "id" value. */
ENGINE *ENGINE_by_id(const char *id);
#if OPENSSL_API_COMPAT < 0x10100000L
# define ENGINE_load_openssl() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_OPENSSL, NULL)
# define ENGINE_load_dynamic() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_DYNAMIC, NULL)
# ifndef OPENSSL_NO_STATIC_ENGINE
# define ENGINE_load_padlock() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_PADLOCK, NULL)
# define ENGINE_load_capi() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CAPI, NULL)
# define ENGINE_load_afalg() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_AFALG, NULL)
# endif
# define ENGINE_load_cryptodev() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CRYPTODEV, NULL)
# define ENGINE_load_rdrand() \
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_RDRAND, NULL)
#endif
void ENGINE_load_builtin_engines(void);
/*
* Get and set global flags (ENGINE_TABLE_FLAG_***) for the implementation
* "registry" handling.
*/
unsigned int ENGINE_get_table_flags(void);
void ENGINE_set_table_flags(unsigned int flags);
/*- Manage registration of ENGINEs per "table". For each type, there are 3
* functions;
* ENGINE_register_***(e) - registers the implementation from 'e' (if it has one)
* ENGINE_unregister_***(e) - unregister the implementation from 'e'
* ENGINE_register_all_***() - call ENGINE_register_***() for each 'e' in the list
* Cleanup is automatically registered from each table when required.
*/
int ENGINE_register_RSA(ENGINE *e);
void ENGINE_unregister_RSA(ENGINE *e);
void ENGINE_register_all_RSA(void);
int ENGINE_register_DSA(ENGINE *e);
void ENGINE_unregister_DSA(ENGINE *e);
void ENGINE_register_all_DSA(void);
int ENGINE_register_EC(ENGINE *e);
void ENGINE_unregister_EC(ENGINE *e);
void ENGINE_register_all_EC(void);
int ENGINE_register_DH(ENGINE *e);
void ENGINE_unregister_DH(ENGINE *e);
void ENGINE_register_all_DH(void);
int ENGINE_register_RAND(ENGINE *e);
void ENGINE_unregister_RAND(ENGINE *e);
void ENGINE_register_all_RAND(void);
int ENGINE_register_ciphers(ENGINE *e);
void ENGINE_unregister_ciphers(ENGINE *e);
void ENGINE_register_all_ciphers(void);
int ENGINE_register_digests(ENGINE *e);
void ENGINE_unregister_digests(ENGINE *e);
void ENGINE_register_all_digests(void);
int ENGINE_register_pkey_meths(ENGINE *e);
void ENGINE_unregister_pkey_meths(ENGINE *e);
void ENGINE_register_all_pkey_meths(void);
int ENGINE_register_pkey_asn1_meths(ENGINE *e);
void ENGINE_unregister_pkey_asn1_meths(ENGINE *e);
void ENGINE_register_all_pkey_asn1_meths(void);
/*
* These functions register all support from the above categories. Note, use
* of these functions can result in static linkage of code your application
* may not need. If you only need a subset of functionality, consider using
* more selective initialisation.
*/
int ENGINE_register_complete(ENGINE *e);
int ENGINE_register_all_complete(void);
/*
* Send parameterised control commands to the engine. The possibilities to
* send down an integer, a pointer to data or a function pointer are
* provided. Any of the parameters may or may not be NULL, depending on the
* command number. In actuality, this function only requires a structural
* (rather than functional) reference to an engine, but many control commands
* may require the engine be functional. The caller should be aware of trying
* commands that require an operational ENGINE, and only use functional
* references in such situations.
*/
int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void));
/*
* This function tests if an ENGINE-specific command is usable as a
* "setting". Eg. in an application's config file that gets processed through
* ENGINE_ctrl_cmd_string(). If this returns zero, it is not available to
* ENGINE_ctrl_cmd_string(), only ENGINE_ctrl().
*/
int ENGINE_cmd_is_executable(ENGINE *e, int cmd);
/*
* This function works like ENGINE_ctrl() with the exception of taking a
* command name instead of a command number, and can handle optional
* commands. See the comment on ENGINE_ctrl_cmd_string() for an explanation
* on how to use the cmd_name and cmd_optional.
*/
int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name,
long i, void *p, void (*f) (void), int cmd_optional);
/*
* This function passes a command-name and argument to an ENGINE. The
* cmd_name is converted to a command number and the control command is
* called using 'arg' as an argument (unless the ENGINE doesn't support such
* a command, in which case no control command is called). The command is
* checked for input flags, and if necessary the argument will be converted
* to a numeric value. If cmd_optional is non-zero, then if the ENGINE
* doesn't support the given cmd_name the return value will be success
* anyway. This function is intended for applications to use so that users
* (or config files) can supply engine-specific config data to the ENGINE at
* run-time to control behaviour of specific engines. As such, it shouldn't
* be used for calling ENGINE_ctrl() functions that return data, deal with
* binary data, or that are otherwise supposed to be used directly through
* ENGINE_ctrl() in application code. Any "return" data from an ENGINE_ctrl()
* operation in this function will be lost - the return value is interpreted
* as failure if the return value is zero, success otherwise, and this
* function returns a boolean value as a result. In other words, vendors of
* 'ENGINE'-enabled devices should write ENGINE implementations with
* parameterisations that work in this scheme, so that compliant ENGINE-based
* applications can work consistently with the same configuration for the
* same ENGINE-enabled devices, across applications.
*/
int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg,
int cmd_optional);
/*
* These functions are useful for manufacturing new ENGINE structures. They
* don't address reference counting at all - one uses them to populate an
* ENGINE structure with personalised implementations of things prior to
* using it directly or adding it to the builtin ENGINE list in OpenSSL.
* These are also here so that the ENGINE structure doesn't have to be
* exposed and break binary compatibility!
*/
ENGINE *ENGINE_new(void);
int ENGINE_free(ENGINE *e);
int ENGINE_up_ref(ENGINE *e);
int ENGINE_set_id(ENGINE *e, const char *id);
int ENGINE_set_name(ENGINE *e, const char *name);
int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth);
int ENGINE_set_DSA(ENGINE *e, const DSA_METHOD *dsa_meth);
int ENGINE_set_EC(ENGINE *e, const EC_KEY_METHOD *ecdsa_meth);
int ENGINE_set_DH(ENGINE *e, const DH_METHOD *dh_meth);
int ENGINE_set_RAND(ENGINE *e, const RAND_METHOD *rand_meth);
int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f);
int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f);
int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f);
int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f);
int ENGINE_set_load_privkey_function(ENGINE *e,
ENGINE_LOAD_KEY_PTR loadpriv_f);
int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f);
int ENGINE_set_load_ssl_client_cert_function(ENGINE *e,
ENGINE_SSL_CLIENT_CERT_PTR
loadssl_f);
int ENGINE_set_ciphers(ENGINE *e, ENGINE_CIPHERS_PTR f);
int ENGINE_set_digests(ENGINE *e, ENGINE_DIGESTS_PTR f);
int ENGINE_set_pkey_meths(ENGINE *e, ENGINE_PKEY_METHS_PTR f);
int ENGINE_set_pkey_asn1_meths(ENGINE *e, ENGINE_PKEY_ASN1_METHS_PTR f);
int ENGINE_set_flags(ENGINE *e, int flags);
int ENGINE_set_cmd_defns(ENGINE *e, const ENGINE_CMD_DEFN *defns);
/* These functions allow control over any per-structure ENGINE data. */
#define ENGINE_get_ex_new_index(l, p, newf, dupf, freef) \
CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_ENGINE, l, p, newf, dupf, freef)
int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg);
void *ENGINE_get_ex_data(const ENGINE *e, int idx);
#if OPENSSL_API_COMPAT < 0x10100000L
/*
* This function previously cleaned up anything that needs it. Auto-deinit will
* now take care of it so it is no longer required to call this function.
*/
# define ENGINE_cleanup() while(0) continue
#endif
/*
* These return values from within the ENGINE structure. These can be useful
* with functional references as well as structural references - it depends
* which you obtained. Using the result for functional purposes if you only
* obtained a structural reference may be problematic!
*/
const char *ENGINE_get_id(const ENGINE *e);
const char *ENGINE_get_name(const ENGINE *e);
const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e);
const DSA_METHOD *ENGINE_get_DSA(const ENGINE *e);
const EC_KEY_METHOD *ENGINE_get_EC(const ENGINE *e);
const DH_METHOD *ENGINE_get_DH(const ENGINE *e);
const RAND_METHOD *ENGINE_get_RAND(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e);
ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e);
ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e);
ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e);
ENGINE_SSL_CLIENT_CERT_PTR ENGINE_get_ssl_client_cert_function(const ENGINE
*e);
ENGINE_CIPHERS_PTR ENGINE_get_ciphers(const ENGINE *e);
ENGINE_DIGESTS_PTR ENGINE_get_digests(const ENGINE *e);
ENGINE_PKEY_METHS_PTR ENGINE_get_pkey_meths(const ENGINE *e);
ENGINE_PKEY_ASN1_METHS_PTR ENGINE_get_pkey_asn1_meths(const ENGINE *e);
const EVP_CIPHER *ENGINE_get_cipher(ENGINE *e, int nid);
const EVP_MD *ENGINE_get_digest(ENGINE *e, int nid);
const EVP_PKEY_METHOD *ENGINE_get_pkey_meth(ENGINE *e, int nid);
const EVP_PKEY_ASN1_METHOD *ENGINE_get_pkey_asn1_meth(ENGINE *e, int nid);
const EVP_PKEY_ASN1_METHOD *ENGINE_get_pkey_asn1_meth_str(ENGINE *e,
const char *str,
int len);
const EVP_PKEY_ASN1_METHOD *ENGINE_pkey_asn1_find_str(ENGINE **pe,
const char *str,
int len);
const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e);
int ENGINE_get_flags(const ENGINE *e);
/*
* FUNCTIONAL functions. These functions deal with ENGINE structures that
* have (or will) be initialised for use. Broadly speaking, the structural
* functions are useful for iterating the list of available engine types,
* creating new engine types, and other "list" operations. These functions
* actually deal with ENGINEs that are to be used. As such these functions
* can fail (if applicable) when particular engines are unavailable - eg. if
* a hardware accelerator is not attached or not functioning correctly. Each
* ENGINE has 2 reference counts; structural and functional. Every time a
* functional reference is obtained or released, a corresponding structural
* reference is automatically obtained or released too.
*/
/*
* Initialise a engine type for use (or up its reference count if it's
* already in use). This will fail if the engine is not currently operational
* and cannot initialise.
*/
int ENGINE_init(ENGINE *e);
/*
* Free a functional reference to a engine type. This does not require a
* corresponding call to ENGINE_free as it also releases a structural
* reference.
*/
int ENGINE_finish(ENGINE *e);
/*
* The following functions handle keys that are stored in some secondary
* location, handled by the engine. The storage may be on a card or
* whatever.
*/
EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data);
EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data);
int ENGINE_load_ssl_client_cert(ENGINE *e, SSL *s,
STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
EVP_PKEY **ppkey, STACK_OF(X509) **pother,
UI_METHOD *ui_method, void *callback_data);
/*
* This returns a pointer for the current ENGINE structure that is (by
* default) performing any RSA operations. The value returned is an
* incremented reference, so it should be free'd (ENGINE_finish) before it is
* discarded.
*/
ENGINE *ENGINE_get_default_RSA(void);
/* Same for the other "methods" */
ENGINE *ENGINE_get_default_DSA(void);
ENGINE *ENGINE_get_default_EC(void);
ENGINE *ENGINE_get_default_DH(void);
ENGINE *ENGINE_get_default_RAND(void);
/*
* These functions can be used to get a functional reference to perform
* ciphering or digesting corresponding to "nid".
*/
ENGINE *ENGINE_get_cipher_engine(int nid);
ENGINE *ENGINE_get_digest_engine(int nid);
ENGINE *ENGINE_get_pkey_meth_engine(int nid);
ENGINE *ENGINE_get_pkey_asn1_meth_engine(int nid);
/*
* This sets a new default ENGINE structure for performing RSA operations. If
* the result is non-zero (success) then the ENGINE structure will have had
* its reference count up'd so the caller should still free their own
* reference 'e'.
*/
int ENGINE_set_default_RSA(ENGINE *e);
int ENGINE_set_default_string(ENGINE *e, const char *def_list);
/* Same for the other "methods" */
int ENGINE_set_default_DSA(ENGINE *e);
int ENGINE_set_default_EC(ENGINE *e);
int ENGINE_set_default_DH(ENGINE *e);
int ENGINE_set_default_RAND(ENGINE *e);
int ENGINE_set_default_ciphers(ENGINE *e);
int ENGINE_set_default_digests(ENGINE *e);
int ENGINE_set_default_pkey_meths(ENGINE *e);
int ENGINE_set_default_pkey_asn1_meths(ENGINE *e);
/*
* The combination "set" - the flags are bitwise "OR"d from the
* ENGINE_METHOD_*** defines above. As with the "ENGINE_register_complete()"
* function, this function can result in unnecessary static linkage. If your
* application requires only specific functionality, consider using more
* selective functions.
*/
int ENGINE_set_default(ENGINE *e, unsigned int flags);
void ENGINE_add_conf_module(void);
/* Deprecated functions ... */
/* int ENGINE_clear_defaults(void); */
/**************************/
/* DYNAMIC ENGINE SUPPORT */
/**************************/
/* Binary/behaviour compatibility levels */
# define OSSL_DYNAMIC_VERSION (unsigned long)0x00030000
/*
* Binary versions older than this are too old for us (whether we're a loader
* or a loadee)
*/
# define OSSL_DYNAMIC_OLDEST (unsigned long)0x00030000
/*
* When compiling an ENGINE entirely as an external shared library, loadable
* by the "dynamic" ENGINE, these types are needed. The 'dynamic_fns'
* structure type provides the calling application's (or library's) error
* functionality and memory management function pointers to the loaded
* library. These should be used/set in the loaded library code so that the
* loading application's 'state' will be used/changed in all operations. The
* 'static_state' pointer allows the loaded library to know if it shares the
* same static data as the calling application (or library), and thus whether
* these callbacks need to be set or not.
*/
typedef void *(*dyn_MEM_malloc_fn) (size_t, const char *, int);
typedef void *(*dyn_MEM_realloc_fn) (void *, size_t, const char *, int);
typedef void (*dyn_MEM_free_fn) (void *, const char *, int);
typedef struct st_dynamic_MEM_fns {
dyn_MEM_malloc_fn malloc_fn;
dyn_MEM_realloc_fn realloc_fn;
dyn_MEM_free_fn free_fn;
} dynamic_MEM_fns;
/*
* FIXME: Perhaps the memory and locking code (crypto.h) should declare and
* use these types so we (and any other dependent code) can simplify a bit??
*/
/* The top-level structure */
typedef struct st_dynamic_fns {
void *static_state;
dynamic_MEM_fns mem_fns;
} dynamic_fns;
/*
* The version checking function should be of this prototype. NB: The
* ossl_version value passed in is the OSSL_DYNAMIC_VERSION of the loading
* code. If this function returns zero, it indicates a (potential) version
* incompatibility and the loaded library doesn't believe it can proceed.
* Otherwise, the returned value is the (latest) version supported by the
* loading library. The loader may still decide that the loaded code's
* version is unsatisfactory and could veto the load. The function is
* expected to be implemented with the symbol name "v_check", and a default
* implementation can be fully instantiated with
* IMPLEMENT_DYNAMIC_CHECK_FN().
*/
typedef unsigned long (*dynamic_v_check_fn) (unsigned long ossl_version);
# define IMPLEMENT_DYNAMIC_CHECK_FN() \
OPENSSL_EXPORT unsigned long v_check(unsigned long v); \
OPENSSL_EXPORT unsigned long v_check(unsigned long v) { \
if (v >= OSSL_DYNAMIC_OLDEST) return OSSL_DYNAMIC_VERSION; \
return 0; }
/*
* This function is passed the ENGINE structure to initialise with its own
* function and command settings. It should not adjust the structural or
* functional reference counts. If this function returns zero, (a) the load
* will be aborted, (b) the previous ENGINE state will be memcpy'd back onto
* the structure, and (c) the shared library will be unloaded. So
* implementations should do their own internal cleanup in failure
* circumstances otherwise they could leak. The 'id' parameter, if non-NULL,
* represents the ENGINE id that the loader is looking for. If this is NULL,
* the shared library can choose to return failure or to initialise a
* 'default' ENGINE. If non-NULL, the shared library must initialise only an
* ENGINE matching the passed 'id'. The function is expected to be
* implemented with the symbol name "bind_engine". A standard implementation
* can be instantiated with IMPLEMENT_DYNAMIC_BIND_FN(fn) where the parameter
* 'fn' is a callback function that populates the ENGINE structure and
* returns an int value (zero for failure). 'fn' should have prototype;
* [static] int fn(ENGINE *e, const char *id);
*/
typedef int (*dynamic_bind_engine) (ENGINE *e, const char *id,
const dynamic_fns *fns);
# define IMPLEMENT_DYNAMIC_BIND_FN(fn) \
OPENSSL_EXPORT \
int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); \
OPENSSL_EXPORT \
int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { \
if (ENGINE_get_static_state() == fns->static_state) goto skip_cbs; \
CRYPTO_set_mem_functions(fns->mem_fns.malloc_fn, \
fns->mem_fns.realloc_fn, \
fns->mem_fns.free_fn); \
skip_cbs: \
if (!fn(e, id)) return 0; \
return 1; }
/*
* If the loading application (or library) and the loaded ENGINE library
* share the same static data (eg. they're both dynamically linked to the
* same libcrypto.so) we need a way to avoid trying to set system callbacks -
* this would fail, and for the same reason that it's unnecessary to try. If
* the loaded ENGINE has (or gets from through the loader) its own copy of
* the libcrypto static data, we will need to set the callbacks. The easiest
* way to detect this is to have a function that returns a pointer to some
* static data and let the loading application and loaded ENGINE compare
* their respective values.
*/
void *ENGINE_get_static_state(void);
# if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
DEPRECATEDIN_1_1_0(void ENGINE_setup_bsd_cryptodev(void))
# endif
# ifdef __cplusplus
}
# endif
# endif
#endif

@ -0,0 +1,111 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ENGINEERR_H
# define HEADER_ENGINEERR_H
# ifndef HEADER_SYMHACKS_H
# include <openssl/symhacks.h>
# endif
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_ENGINE
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_ENGINE_strings(void);
/*
* ENGINE function codes.
*/
# define ENGINE_F_DIGEST_UPDATE 198
# define ENGINE_F_DYNAMIC_CTRL 180
# define ENGINE_F_DYNAMIC_GET_DATA_CTX 181
# define ENGINE_F_DYNAMIC_LOAD 182
# define ENGINE_F_DYNAMIC_SET_DATA_CTX 183
# define ENGINE_F_ENGINE_ADD 105
# define ENGINE_F_ENGINE_BY_ID 106
# define ENGINE_F_ENGINE_CMD_IS_EXECUTABLE 170
# define ENGINE_F_ENGINE_CTRL 142
# define ENGINE_F_ENGINE_CTRL_CMD 178
# define ENGINE_F_ENGINE_CTRL_CMD_STRING 171
# define ENGINE_F_ENGINE_FINISH 107
# define ENGINE_F_ENGINE_GET_CIPHER 185
# define ENGINE_F_ENGINE_GET_DIGEST 186
# define ENGINE_F_ENGINE_GET_FIRST 195
# define ENGINE_F_ENGINE_GET_LAST 196
# define ENGINE_F_ENGINE_GET_NEXT 115
# define ENGINE_F_ENGINE_GET_PKEY_ASN1_METH 193
# define ENGINE_F_ENGINE_GET_PKEY_METH 192
# define ENGINE_F_ENGINE_GET_PREV 116
# define ENGINE_F_ENGINE_INIT 119
# define ENGINE_F_ENGINE_LIST_ADD 120
# define ENGINE_F_ENGINE_LIST_REMOVE 121
# define ENGINE_F_ENGINE_LOAD_PRIVATE_KEY 150
# define ENGINE_F_ENGINE_LOAD_PUBLIC_KEY 151
# define ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT 194
# define ENGINE_F_ENGINE_NEW 122
# define ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR 197
# define ENGINE_F_ENGINE_REMOVE 123
# define ENGINE_F_ENGINE_SET_DEFAULT_STRING 189
# define ENGINE_F_ENGINE_SET_ID 129
# define ENGINE_F_ENGINE_SET_NAME 130
# define ENGINE_F_ENGINE_TABLE_REGISTER 184
# define ENGINE_F_ENGINE_UNLOCKED_FINISH 191
# define ENGINE_F_ENGINE_UP_REF 190
# define ENGINE_F_INT_CLEANUP_ITEM 199
# define ENGINE_F_INT_CTRL_HELPER 172
# define ENGINE_F_INT_ENGINE_CONFIGURE 188
# define ENGINE_F_INT_ENGINE_MODULE_INIT 187
# define ENGINE_F_OSSL_HMAC_INIT 200
/*
* ENGINE reason codes.
*/
# define ENGINE_R_ALREADY_LOADED 100
# define ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER 133
# define ENGINE_R_CMD_NOT_EXECUTABLE 134
# define ENGINE_R_COMMAND_TAKES_INPUT 135
# define ENGINE_R_COMMAND_TAKES_NO_INPUT 136
# define ENGINE_R_CONFLICTING_ENGINE_ID 103
# define ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED 119
# define ENGINE_R_DSO_FAILURE 104
# define ENGINE_R_DSO_NOT_FOUND 132
# define ENGINE_R_ENGINES_SECTION_ERROR 148
# define ENGINE_R_ENGINE_CONFIGURATION_ERROR 102
# define ENGINE_R_ENGINE_IS_NOT_IN_LIST 105
# define ENGINE_R_ENGINE_SECTION_ERROR 149
# define ENGINE_R_FAILED_LOADING_PRIVATE_KEY 128
# define ENGINE_R_FAILED_LOADING_PUBLIC_KEY 129
# define ENGINE_R_FINISH_FAILED 106
# define ENGINE_R_ID_OR_NAME_MISSING 108
# define ENGINE_R_INIT_FAILED 109
# define ENGINE_R_INTERNAL_LIST_ERROR 110
# define ENGINE_R_INVALID_ARGUMENT 143
# define ENGINE_R_INVALID_CMD_NAME 137
# define ENGINE_R_INVALID_CMD_NUMBER 138
# define ENGINE_R_INVALID_INIT_VALUE 151
# define ENGINE_R_INVALID_STRING 150
# define ENGINE_R_NOT_INITIALISED 117
# define ENGINE_R_NOT_LOADED 112
# define ENGINE_R_NO_CONTROL_FUNCTION 120
# define ENGINE_R_NO_INDEX 144
# define ENGINE_R_NO_LOAD_FUNCTION 125
# define ENGINE_R_NO_REFERENCE 130
# define ENGINE_R_NO_SUCH_ENGINE 116
# define ENGINE_R_UNIMPLEMENTED_CIPHER 146
# define ENGINE_R_UNIMPLEMENTED_DIGEST 147
# define ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD 101
# define ENGINE_R_VERSION_INCOMPATIBILITY 145
# endif
#endif

@ -0,0 +1,274 @@
/*
* Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ERR_H
# define HEADER_ERR_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_STDIO
# include <stdio.h>
# include <stdlib.h>
# endif
# include <openssl/ossl_typ.h>
# include <openssl/bio.h>
# include <openssl/lhash.h>
#ifdef __cplusplus
extern "C" {
#endif
# ifndef OPENSSL_NO_ERR
# define ERR_PUT_error(a,b,c,d,e) ERR_put_error(a,b,c,d,e)
# else
# define ERR_PUT_error(a,b,c,d,e) ERR_put_error(a,b,c,NULL,0)
# endif
# include <errno.h>
# define ERR_TXT_MALLOCED 0x01
# define ERR_TXT_STRING 0x02
# define ERR_FLAG_MARK 0x01
# define ERR_FLAG_CLEAR 0x02
# define ERR_NUM_ERRORS 16
typedef struct err_state_st {
int err_flags[ERR_NUM_ERRORS];
unsigned long err_buffer[ERR_NUM_ERRORS];
char *err_data[ERR_NUM_ERRORS];
int err_data_flags[ERR_NUM_ERRORS];
const char *err_file[ERR_NUM_ERRORS];
int err_line[ERR_NUM_ERRORS];
int top, bottom;
} ERR_STATE;
/* library */
# define ERR_LIB_NONE 1
# define ERR_LIB_SYS 2
# define ERR_LIB_BN 3
# define ERR_LIB_RSA 4
# define ERR_LIB_DH 5
# define ERR_LIB_EVP 6
# define ERR_LIB_BUF 7
# define ERR_LIB_OBJ 8
# define ERR_LIB_PEM 9
# define ERR_LIB_DSA 10
# define ERR_LIB_X509 11
/* #define ERR_LIB_METH 12 */
# define ERR_LIB_ASN1 13
# define ERR_LIB_CONF 14
# define ERR_LIB_CRYPTO 15
# define ERR_LIB_EC 16
# define ERR_LIB_SSL 20
/* #define ERR_LIB_SSL23 21 */
/* #define ERR_LIB_SSL2 22 */
/* #define ERR_LIB_SSL3 23 */
/* #define ERR_LIB_RSAREF 30 */
/* #define ERR_LIB_PROXY 31 */
# define ERR_LIB_BIO 32
# define ERR_LIB_PKCS7 33
# define ERR_LIB_X509V3 34
# define ERR_LIB_PKCS12 35
# define ERR_LIB_RAND 36
# define ERR_LIB_DSO 37
# define ERR_LIB_ENGINE 38
# define ERR_LIB_OCSP 39
# define ERR_LIB_UI 40
# define ERR_LIB_COMP 41
# define ERR_LIB_ECDSA 42
# define ERR_LIB_ECDH 43
# define ERR_LIB_OSSL_STORE 44
# define ERR_LIB_FIPS 45
# define ERR_LIB_CMS 46
# define ERR_LIB_TS 47
# define ERR_LIB_HMAC 48
/* # define ERR_LIB_JPAKE 49 */
# define ERR_LIB_CT 50
# define ERR_LIB_ASYNC 51
# define ERR_LIB_KDF 52
# define ERR_LIB_SM2 53
# define ERR_LIB_USER 128
# define SYSerr(f,r) ERR_PUT_error(ERR_LIB_SYS,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define BNerr(f,r) ERR_PUT_error(ERR_LIB_BN,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define RSAerr(f,r) ERR_PUT_error(ERR_LIB_RSA,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define DHerr(f,r) ERR_PUT_error(ERR_LIB_DH,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define EVPerr(f,r) ERR_PUT_error(ERR_LIB_EVP,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define BUFerr(f,r) ERR_PUT_error(ERR_LIB_BUF,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define OBJerr(f,r) ERR_PUT_error(ERR_LIB_OBJ,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define PEMerr(f,r) ERR_PUT_error(ERR_LIB_PEM,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define DSAerr(f,r) ERR_PUT_error(ERR_LIB_DSA,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define X509err(f,r) ERR_PUT_error(ERR_LIB_X509,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ASN1err(f,r) ERR_PUT_error(ERR_LIB_ASN1,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define CONFerr(f,r) ERR_PUT_error(ERR_LIB_CONF,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define CRYPTOerr(f,r) ERR_PUT_error(ERR_LIB_CRYPTO,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ECerr(f,r) ERR_PUT_error(ERR_LIB_EC,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define SSLerr(f,r) ERR_PUT_error(ERR_LIB_SSL,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define BIOerr(f,r) ERR_PUT_error(ERR_LIB_BIO,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define PKCS7err(f,r) ERR_PUT_error(ERR_LIB_PKCS7,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define X509V3err(f,r) ERR_PUT_error(ERR_LIB_X509V3,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define PKCS12err(f,r) ERR_PUT_error(ERR_LIB_PKCS12,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define RANDerr(f,r) ERR_PUT_error(ERR_LIB_RAND,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define DSOerr(f,r) ERR_PUT_error(ERR_LIB_DSO,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ENGINEerr(f,r) ERR_PUT_error(ERR_LIB_ENGINE,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define OCSPerr(f,r) ERR_PUT_error(ERR_LIB_OCSP,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define UIerr(f,r) ERR_PUT_error(ERR_LIB_UI,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define COMPerr(f,r) ERR_PUT_error(ERR_LIB_COMP,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ECDSAerr(f,r) ERR_PUT_error(ERR_LIB_ECDSA,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define OSSL_STOREerr(f,r) ERR_PUT_error(ERR_LIB_OSSL_STORE,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define CTerr(f,r) ERR_PUT_error(ERR_LIB_CT,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ASYNCerr(f,r) ERR_PUT_error(ERR_LIB_ASYNC,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define KDFerr(f,r) ERR_PUT_error(ERR_LIB_KDF,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define SM2err(f,r) ERR_PUT_error(ERR_LIB_SM2,(f),(r),OPENSSL_FILE,OPENSSL_LINE)
# define ERR_PACK(l,f,r) ( \
(((unsigned int)(l) & 0x0FF) << 24L) | \
(((unsigned int)(f) & 0xFFF) << 12L) | \
(((unsigned int)(r) & 0xFFF) ) )
# define ERR_GET_LIB(l) (int)(((l) >> 24L) & 0x0FFL)
# define ERR_GET_FUNC(l) (int)(((l) >> 12L) & 0xFFFL)
# define ERR_GET_REASON(l) (int)( (l) & 0xFFFL)
# define ERR_FATAL_ERROR(l) (int)( (l) & ERR_R_FATAL)
/* OS functions */
# define SYS_F_FOPEN 1
# define SYS_F_CONNECT 2
# define SYS_F_GETSERVBYNAME 3
# define SYS_F_SOCKET 4
# define SYS_F_IOCTLSOCKET 5
# define SYS_F_BIND 6
# define SYS_F_LISTEN 7
# define SYS_F_ACCEPT 8
# define SYS_F_WSASTARTUP 9/* Winsock stuff */
# define SYS_F_OPENDIR 10
# define SYS_F_FREAD 11
# define SYS_F_GETADDRINFO 12
# define SYS_F_GETNAMEINFO 13
# define SYS_F_SETSOCKOPT 14
# define SYS_F_GETSOCKOPT 15
# define SYS_F_GETSOCKNAME 16
# define SYS_F_GETHOSTBYNAME 17
# define SYS_F_FFLUSH 18
# define SYS_F_OPEN 19
# define SYS_F_CLOSE 20
# define SYS_F_IOCTL 21
# define SYS_F_STAT 22
# define SYS_F_FCNTL 23
# define SYS_F_FSTAT 24
/* reasons */
# define ERR_R_SYS_LIB ERR_LIB_SYS/* 2 */
# define ERR_R_BN_LIB ERR_LIB_BN/* 3 */
# define ERR_R_RSA_LIB ERR_LIB_RSA/* 4 */
# define ERR_R_DH_LIB ERR_LIB_DH/* 5 */
# define ERR_R_EVP_LIB ERR_LIB_EVP/* 6 */
# define ERR_R_BUF_LIB ERR_LIB_BUF/* 7 */
# define ERR_R_OBJ_LIB ERR_LIB_OBJ/* 8 */
# define ERR_R_PEM_LIB ERR_LIB_PEM/* 9 */
# define ERR_R_DSA_LIB ERR_LIB_DSA/* 10 */
# define ERR_R_X509_LIB ERR_LIB_X509/* 11 */
# define ERR_R_ASN1_LIB ERR_LIB_ASN1/* 13 */
# define ERR_R_EC_LIB ERR_LIB_EC/* 16 */
# define ERR_R_BIO_LIB ERR_LIB_BIO/* 32 */
# define ERR_R_PKCS7_LIB ERR_LIB_PKCS7/* 33 */
# define ERR_R_X509V3_LIB ERR_LIB_X509V3/* 34 */
# define ERR_R_ENGINE_LIB ERR_LIB_ENGINE/* 38 */
# define ERR_R_UI_LIB ERR_LIB_UI/* 40 */
# define ERR_R_ECDSA_LIB ERR_LIB_ECDSA/* 42 */
# define ERR_R_OSSL_STORE_LIB ERR_LIB_OSSL_STORE/* 44 */
# define ERR_R_NESTED_ASN1_ERROR 58
# define ERR_R_MISSING_ASN1_EOS 63
/* fatal error */
# define ERR_R_FATAL 64
# define ERR_R_MALLOC_FAILURE (1|ERR_R_FATAL)
# define ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED (2|ERR_R_FATAL)
# define ERR_R_PASSED_NULL_PARAMETER (3|ERR_R_FATAL)
# define ERR_R_INTERNAL_ERROR (4|ERR_R_FATAL)
# define ERR_R_DISABLED (5|ERR_R_FATAL)
# define ERR_R_INIT_FAIL (6|ERR_R_FATAL)
# define ERR_R_PASSED_INVALID_ARGUMENT (7)
# define ERR_R_OPERATION_FAIL (8|ERR_R_FATAL)
/*
* 99 is the maximum possible ERR_R_... code, higher values are reserved for
* the individual libraries
*/
typedef struct ERR_string_data_st {
unsigned long error;
const char *string;
} ERR_STRING_DATA;
DEFINE_LHASH_OF(ERR_STRING_DATA);
void ERR_put_error(int lib, int func, int reason, const char *file, int line);
void ERR_set_error_data(char *data, int flags);
unsigned long ERR_get_error(void);
unsigned long ERR_get_error_line(const char **file, int *line);
unsigned long ERR_get_error_line_data(const char **file, int *line,
const char **data, int *flags);
unsigned long ERR_peek_error(void);
unsigned long ERR_peek_error_line(const char **file, int *line);
unsigned long ERR_peek_error_line_data(const char **file, int *line,
const char **data, int *flags);
unsigned long ERR_peek_last_error(void);
unsigned long ERR_peek_last_error_line(const char **file, int *line);
unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
const char **data, int *flags);
void ERR_clear_error(void);
char *ERR_error_string(unsigned long e, char *buf);
void ERR_error_string_n(unsigned long e, char *buf, size_t len);
const char *ERR_lib_error_string(unsigned long e);
const char *ERR_func_error_string(unsigned long e);
const char *ERR_reason_error_string(unsigned long e);
void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
void *u);
# ifndef OPENSSL_NO_STDIO
void ERR_print_errors_fp(FILE *fp);
# endif
void ERR_print_errors(BIO *bp);
void ERR_add_error_data(int num, ...);
void ERR_add_error_vdata(int num, va_list args);
int ERR_load_strings(int lib, ERR_STRING_DATA *str);
int ERR_load_strings_const(const ERR_STRING_DATA *str);
int ERR_unload_strings(int lib, ERR_STRING_DATA *str);
int ERR_load_ERR_strings(void);
#if OPENSSL_API_COMPAT < 0x10100000L
# define ERR_load_crypto_strings() \
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL)
# define ERR_free_strings() while(0) continue
#endif
DEPRECATEDIN_1_1_0(void ERR_remove_thread_state(void *))
DEPRECATEDIN_1_0_0(void ERR_remove_state(unsigned long pid))
ERR_STATE *ERR_get_state(void);
int ERR_get_next_error_library(void);
int ERR_set_mark(void);
int ERR_pop_to_mark(void);
int ERR_clear_last_mark(void);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save