Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • cellframe/cellframe-node
  • evseev/cellframe-node
  • dmitry.puzyrkov/cellframe-node
  • MIKA83/cellframe-node
4 results
Show changes
Showing with 955 additions and 1407 deletions
......@@ -6,9 +6,9 @@
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
This file is part of DAP (Distributed Applications Platform) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
DAP (Distributed Applications Platform) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
......@@ -27,195 +27,75 @@
#include <stdlib.h>
#include <string.h>
//#include "dap_client.h"
#include "dap_common.h"
#include "dap_chain_node_cli.h"
#include "main_node_cli.h"
#include "main_node_cli_net.h"
#include "main_node_cli_shell.h"
static connect_param *cparam;
/**
* split string to argc and argv
*/
static char** split_word(char *line, int *argc)
{
if(!line)
{
if(argc)
*argc = 0;
return NULL ;
}
char **argv = calloc(sizeof(char*), strlen(line));
int n = 0;
char *s, *start = line;
size_t len = strlen(line);
for(s = line; s <= line + len; s++) {
if(whitespace(*s)) {
*s = '\0';
argv[n] = start;
s++;
// miss spaces
for(; whitespace(*s); s++)
;
start = s;
n++;
}
}
// last param
if(len) {
argv[n] = start;
n++;
}
if(argc)
*argc = n;
return argv;
}
/*
* Execute a command line.
*/
int execute_line(char *line)
{
register int i;
dap_chain_node_cmd_item_t *command;
char *word;
/* Isolate the command word. */
i = 0;
while(line[i] && whitespace(line[i]))
i++;
word = line + i;
/* while(line[i] && !whitespace(line[i]))
i++;
if(line[i])
line[i++] = '\0';
command = find_command(word);
if(!command)
{
fprintf(stderr, "%s: No such command\n", word);
return (-1);
}*/
/* Get argument to command, if any.
while(whitespace(line[i]))
i++;
word = line + i;*/
int argc = 0;
char **argv = split_word(word, &argc);
// Call the function
if(argc > 0) {
cmd_state cmd;
memset(&cmd, 0, sizeof(cmd_state));
cmd.cmd_name = (char *) argv[0];
cmd.cmd_param_count = argc - 1;
if(cmd.cmd_param_count > 0)
cmd.cmd_param = (char**) (argv + 1);
// Send command
int res = node_cli_post_command(cparam, &cmd);
return res;
}
fprintf(stderr, "No command\n");
return -1; //((*(command->func))(argc, (const char **) argv, NULL));
}
/**
* Clear and delete memory of structure cmd_state
*/
void free_cmd_state(cmd_state *cmd) {
if(!cmd->cmd_param)
return;
for(int i = 0; i < cmd->cmd_param_count; i++)
{
DAP_DELETE(cmd->cmd_param[i]);
}
DAP_DELETE(cmd->cmd_res);
DAP_DELETE(cmd);
}
/**
* Read and execute commands until EOF is reached. This assumes that
* the input source has already been initialized.
*/
int shell_reader_loop()
{
char *line, *s;
rl_initialize(); /* Bind our completer. */
int done = 0;
// Loop reading and executing lines until the user quits.
for(; done == 0;) {
// Read a line of input
line = rl_readline("> ");
#include "dap_common.h"
#include "dap_file_utils.h"
#include "dap_strfuncs.h"
#include "dap_app_cli.h"
#include "dap_app_cli_net.h"
#include "dap_app_cli_shell.h"
if(!line)
break;
#ifdef DAP_OS_WINDOWS
#include "registry.h"
#elif defined DAP_OS_ANDROID
/* Remove leading and trailing whitespace from the line.
Then, if there is anything left, add it to the history list
and execute it. */
s = rl_stripwhite(line);
#include <android/log.h>
#include <jni.h>
#endif
if(*s)
{
add_history(s);
execute_line(s);
}
#define NODE_NAME "cellframe-node"
DAP_DELETE(line);
}
exit(0);
}
static dap_app_cli_connect_param_t *cparam;
static const char *listen_socket = NULL;
int main(int argc, const char * argv[])
#if !DAP_OS_ANDROID
int main(int argc, const char *argv[])
{
// set_default_locale();
// command_execution_string = shell_script_filename = (char *) NULL;
// connect to node
cparam = node_cli_connect();
if(!cparam)
{
printf("Can't connected to kelvin-node\n");
exit(-1);
dap_set_appname(NODE_NAME "-cli");
// get relative path to config
if (argc > 2 && !dap_strcmp("-B" , argv[1])) {
g_sys_dir_path = dap_strdup(argv[2]);
if (! dap_dir_test(g_sys_dir_path) )
return printf("Invalid path \"%s\"", g_sys_dir_path), DAP_DELETE(g_sys_dir_path), -1;
argc -= 2;
argv += 2;
} else {
g_sys_dir_path =
#ifdef DAP_OS_WINDOWS
dap_strdup_printf("%s/%s", regGetUsrPath(), NODE_NAME);
#elif defined DAP_OS_MAC
dap_strdup_printf("/Library/Application Support/CellframeNode/");
#elif defined DAP_OS_UNIX
dap_strdup_printf("/opt/%s", NODE_NAME);
#endif
}
/*{
printf("start node_cli_post_command()\n");
cmd_state *cmd = DAP_NEW_Z(cmd_state);
cmd->cmd_name = "cmd1";
cmd->cmd_param_count = 2;
cmd->cmd_param = DAP_NEW_Z_SIZE(char*, cmd->cmd_param_count * sizeof(char*));
cmd->cmd_param[0] = strdup("t2-t1");
cmd->cmd_param[1] = strdup("-opt");
int a = node_cli_post_command(cparam, cmd);
printf("node_cli_post_command()=%d\n", a);
free_cmd_state(cmd);
}*/
if(argc > 1){
// Call the function
//int res = ((*(command->func))(argc - 2, argv + 2));
cmd_state cmd;
memset(&cmd, 0, sizeof(cmd_state));
cmd.cmd_name = strdup(argv[1]);
cmd.cmd_param_count = argc - 2;
if(cmd.cmd_param_count > 0)
cmd.cmd_param = (char**) (argv + 2);
// Send command
int res = node_cli_post_command(cparam, &cmd);
node_cli_desconnect(cparam);
return res;
#ifdef DAP_OS_WINDOWS
SetConsoleCP(1252);
SetConsoleOutputCP(1252);
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
#endif
dap_log_level_set(L_CRITICAL);
int res = dap_app_cli_main(NODE_NAME, argc, argv);
switch (res) {
case DAP_CLI_ERROR_FORMAT:
printf("Response format error!\n");
break;
case DAP_CLI_ERROR_SOCKET:
printf("Socket read error!\n");
break;
case DAP_CLI_ERROR_TIMEOUT:
printf("No response recieved\n");
break;
case DAP_CLI_ERROR_INCOMPLETE:
printf("Connection closed by peer\n");
default:
break;
}
// command not found, start interactive shell
shell_reader_loop();
node_cli_desconnect(cparam);
return 0;
DAP_DELETE(g_sys_dir_path);
#ifdef DAP_OS_WINDOWS
WSACleanup();
#endif
return res;
}
#endif
\ No newline at end of file
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h>
// command description
typedef struct cmd_state_ {
char *cmd_name;
char **cmd_param;
int cmd_param_count;
int ret_code;
// for reply
char *cmd_res;
size_t cmd_res_len;
size_t cmd_res_cur;
} cmd_state;
/**
* Clear and delete memory of structure cmd_state
*/
void free_cmd_state(cmd_state *cmd);
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* Alexander Lysikov <alexander.lysikov@demlabs.net>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
//#include <dap_client.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include "dap_common.h"
#include "dap_strfuncs.h"
#include "dap_chain_node_cli.h" // for UNIX_SOCKET_FILE
#include "main_node_cli_net.h"
/**
* Add to one array another one
*
* memory - destination array of data
* add_mem - source array of data
* memory_len - memory array size
* add_size - add_mem array size
*/
static int add_mem_data(uint8_t **memory, size_t *memory_len, char *add_mem, size_t add_size)
{
*memory = (char*) realloc(*memory, *memory_len + add_size + 1);
//out of memory!
if(*memory == NULL) {
//printf("not enough memory (realloc returned NULL)\n");
return 0;
}
if(add_mem) {
memcpy((*memory + *memory_len), add_mem, add_size);
// increase the received bytes number
*memory_len += add_size;
// zero out the last byte
*(*memory + *memory_len) = 0;
}
return add_size;
}
//callback functions to receive header
static size_t WriteHttpMemoryHeadCallback(void *contents, size_t size, size_t nmemb, cmd_state *cmd)
{
if(!cmd)
return 0;
//printf("[header] %s len=%d\n", contents, size * nmemb);
const char *head_str = "Content-Length:";
int len_str = strlen(head_str);
if(!strncasecmp(contents, head_str, len_str)) {
cmd->cmd_res_len = atoi((contents + len_str));
cmd->cmd_res_cur = 0;
cmd->cmd_res = DAP_NEW_Z_SIZE(char, cmd->cmd_res_len + 1);
}
return size * nmemb;
}
// callback function to receive data
static size_t WriteHttpMemoryCallback(void *contents, size_t size, size_t nmemb, cmd_state *cmd)
{
//printf("[data] %s len=%d\n", contents, size * nmemb);
if(!cmd)
return 0;
// add received data to body
memcpy(cmd->cmd_res + cmd->cmd_res_cur, contents, size * nmemb);
cmd->cmd_res_cur += size * nmemb;
return size * nmemb;
}
/**
* Connect to node unix socket server
*
* return struct connect_param if connect established, else NULL
*/
connect_param* node_cli_connect(void)
{
curl_global_init(CURL_GLOBAL_DEFAULT);
connect_param *param = DAP_NEW_Z(connect_param);
CURL *curl_handle = curl_easy_init();
int ret = curl_easy_setopt(curl_handle, CURLOPT_UNIX_SOCKET_PATH, UNIX_SOCKET_FILE); // unix socket mode
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 60L); // complete within 60 seconds
ret = curl_easy_setopt(curl_handle, CURLOPT_CONNECT_ONLY, 1L); // connection only
ret = curl_easy_setopt(curl_handle, CURLOPT_URL, "http:/localhost/connect");
// execute request
ret = curl_easy_perform(curl_handle);
if(!ret)
{
param->curl = curl_handle;
curl_easy_setopt(curl_handle, CURLOPT_CONNECT_ONLY, 0L); // disable mode - connection only
}
else
{
curl_easy_cleanup(curl_handle);
DAP_DELETE(param);
param = NULL;
}
return param;
}
/**
* Send request to kelvin-node
*
* return 0 if OK, else error code
*/
int node_cli_post_command(connect_param *conn, cmd_state *cmd)
{
if(!conn || !conn->curl || !cmd || !cmd->cmd_name)
{
assert(0);
return -1;
}
CURLcode ret;
CURL *curl = conn->curl;
ret = curl_easy_setopt(curl, CURLOPT_HEADER, 0L); // don't get header in the body
//ret = curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip, deflate"); // allow receive of compressed data
//callback functions to receive data
ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteHttpMemoryCallback); // callback for the data read
//callback functions to receive header
ret = curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteHttpMemoryHeadCallback); // callback for the header read
// passing a parameter to the callback function
ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void * )cmd);
ret = curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void * )cmd);
ret = curl_easy_setopt(curl, CURLOPT_USERAGENT, "kelvin-console 1.0");
char *post_data = NULL;
ret = curl_easy_setopt(curl, CURLOPT_POST, 1); // POST request - optional if CURLOPT_POSTFIELDS will be
size_t post_data_len = 0;
add_mem_data((uint8_t**) &post_data, &post_data_len, cmd->cmd_name, strlen(cmd->cmd_name));
if(cmd->cmd_param) {
for(int i = 0; i < cmd->cmd_param_count; i++) {
if(cmd->cmd_param[i]) {
add_mem_data((uint8_t**) &post_data, &post_data_len, "\r\n", 2);
add_mem_data((uint8_t**) &post_data, &post_data_len, cmd->cmd_param[i], strlen(cmd->cmd_param[i]));
}
}
}
add_mem_data((uint8_t**) &post_data, &post_data_len, "\r\n\r\n", 4);
if (post_data)
ret = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); // data for POST request
if (post_data_len >= 0)
ret = curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
(long )post_data_len); // if need a lot to send: CURLOPT_POSTFIELDSIZE_LARGE
// sending request and receiving the http page (filling cmd)
//printf("cmd='%s'\n", cmd->cmd_name);
ret = curl_easy_perform(curl); // curl_easy_send
if (ret != CURLE_OK) {
printf("Error (err_code=%d)\n", ret);
exit(-1);
}
int l_err_code = -1;
if (cmd->cmd_res) {
char **l_str = dap_strsplit(cmd->cmd_res, "\r\n", 1);
int l_cnt = dap_str_countv(l_str);
char *l_str_reply = NULL;
if (l_cnt == 2) {
l_err_code = strtol(l_str[0], NULL, 10);
l_str_reply = l_str[1];
}
printf("%s\n", (l_str_reply) ? l_str_reply : "no response");
dap_strfreev(l_str);
}
DAP_DELETE(post_data);
exit(l_err_code);
return 0;
}
int node_cli_desconnect(connect_param *param)
{
if(param) {
if(param->curl)
curl_easy_cleanup(param->curl);
DAP_DELETE(param);
}
curl_global_cleanup();
return 0;
}
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <curl/curl.h>
#include "main_node_cli.h"
// connection description
typedef struct connect_param_ {
CURL *curl;
//SOCKET sock;
} connect_param;
/**
* Connect to node unix socket server
*
* return struct connect_param if connect established, else NULL
*/
connect_param* node_cli_connect(void);
/**
* Send request to kelvin-node
*
* return 0 if OK, else error code
*/
int node_cli_post_command(connect_param *conn, cmd_state *cmd);
int node_cli_desconnect(connect_param *conn);
#include <locale.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ttydefaults.h>
#include <unistd.h>
#include "dap_common.h"
#include "main_node_cli.h"
#include "main_node_cli_shell.h"
//#include "posixjmp.h"
#ifndef savestring
#define savestring(x) strcpy ((char *)malloc (1 + strlen (x)), (x))
#endif
typedef void rl_voidfunc_t(void);
typedef void rl_vintfunc_t(int);
/* Current prompt. */
char *rl_prompt = (char *) NULL;
int rl_visible_prompt_length = 0;
/* Non-zero means we have been called at least once before. */
static int rl_initialized;
/* The stuff that gets printed out before the actual text of the line.
This is usually pointing to rl_prompt. */
char *rl_display_prompt = (char *) NULL;
/* Non-zero makes this the next keystroke to read. */
int rl_pending_input = 0;
/* Make this non-zero to return the current input_line. */
int rl_done;
/* Non-zero if the previous command was a kill command. */
int _rl_last_command_was_kill = 0;
/* Top level environment for readline_internal (). */
jmp_buf _rl_top_level;
/* Length of the current input line. */
int rl_end;
/* The character that can generate an EOF. Really read from
the terminal driver... just defaulted here. */
int _rl_eof_char = CTRL('D');
#define NEWLINE '\n'
/* Input error; can be returned by (*rl_getc_function) if readline is reading
a top-level command (RL_ISSTATE (RL_STATE_READCMD)). */
#define READERR (-2)
/* Possible state values for rl_readline_state */
#define RL_STATE_NONE 0x000000 /* no state; before first call */
#define RL_STATE_INITIALIZING 0x0000001 /* initializing */
#define RL_STATE_INITIALIZED 0x0000002 /* initialization done */
#define RL_STATE_READCMD 0x0000008 /* reading a command key */
#define RL_STATE_INPUTPENDING 0x0020000 /* rl_execute_next called */
#define RL_STATE_TERMPREPPED 0x0000004 /* terminal is prepped */
/* Flags word encapsulating the current readline state. */
unsigned long rl_readline_state = RL_STATE_NONE;
#define RL_SETSTATE(x) (rl_readline_state |= (x))
#define RL_UNSETSTATE(x) (rl_readline_state &= ~(x))
#define RL_ISSTATE(x) (rl_readline_state & (x))
/* The names of the streams that we do input and output to. */
FILE *rl_instream = (FILE *) NULL;
FILE *rl_outstream = (FILE *) NULL;
/**
* Read one symbol
*/
unsigned char rl_getc(FILE *stream)
{
int result;
unsigned char c;
while(1)
{
#if defined (__MINGW32__)
if (isatty (fileno (stream)))
return (_getch ()); /* "There is no error return." */
#endif
result = 0;
if(result >= 0)
result = read(fileno(stream), &c, sizeof(unsigned char));
if(result == sizeof(unsigned char))
return (c);
/* If zero characters are returned, then the file that we are
reading from is empty! Return EOF in that case. */
if(result == 0)
return (EOF);
}
}
/**
* Set up the prompt and expand it. Called from readline()
*/
int rl_set_prompt(const char *prompt)
{
free(rl_prompt);
rl_prompt = prompt ? savestring(prompt) : (char *) NULL;
rl_display_prompt = rl_prompt ? rl_prompt : "";
fprintf(stdout, prompt);
fflush(stdout);
//rl_visible_prompt_length = rl_expand_prompt (rl_prompt);
return 0;
}
/**
* Read a line of input. Prompt with PROMPT. An empty PROMPT means none.
* A return value of NULL means that EOF was encountered.
*/
char *rl_readline(const char *prompt)
{
int value_size = 3, value_len = 0;
char *value = DAP_NEW_Z_SIZE(char, value_size + 1);
// Set up the prompt
rl_set_prompt(prompt);
// Read a line of input from the global rl_instream, doing output on the global rl_outstream.
while(1)
{
unsigned char c = rl_getc(rl_instream);
if(c == EOF || c == NEWLINE)
break;
value[value_len] = c;
value_len++;
if(value_len == value_size) {
value_size += 32;
value = realloc(value, value_size + 1);
}
}
return (value);
}
static char* _rl_get_locale_var(const char *v)
{
char *lspec;
lspec = getenv("LC_ALL");
if(lspec == 0 || *lspec == 0)
lspec = getenv(v);
if(lspec == 0 || *lspec == 0)
lspec = getenv("LANG");
return lspec;
}
/*
* Query the right environment variables and call setlocale() to initialize
* the C library locale settings.
*/
static char* _rl_init_locale(void)
{
char *ret, *lspec;
/* Set the LC_CTYPE locale category from environment variables. */
lspec = _rl_get_locale_var("LC_CTYPE");
/* Since _rl_get_locale_var queries the right environment variables,
we query the current locale settings with setlocale(), and, if
that doesn't return anything, we set lspec to the empty string to
force the subsequent call to setlocale() to define the `native'
environment. */
if(lspec == 0 || *lspec == 0)
lspec = setlocale(LC_CTYPE, (char *) NULL);
if(lspec == 0)
lspec = "";
ret = setlocale(LC_CTYPE, lspec); /* ok, since it does not change locale */
//_rl_utf8locale = (ret && *ret) ? utf8locale (ret) : 0;
return ret;
}
/*
* Initialize readline (and terminal if not already).
*/
int rl_initialize(void)
{
/* If we have never been called before, initialize the
terminal and data structures. */
if(rl_initialized == 0)
{
RL_SETSTATE(RL_STATE_INITIALIZING);
rl_instream = (FILE *) stdin;
rl_outstream = (FILE *) stdout;
RL_UNSETSTATE(RL_STATE_INITIALIZING);
rl_initialized++;
RL_SETSTATE(RL_STATE_INITIALIZED);
}
else
(void) _rl_init_locale(); /* check current locale */
RL_SETSTATE(RL_STATE_INITIALIZING);
rl_instream = (FILE *) stdin;
rl_outstream = (FILE *) stdout;
RL_UNSETSTATE(RL_STATE_INITIALIZING);
}
int parse_shell_options(char **argv, int arg_start, int arg_end)
{
int arg_index;
int arg_character, on_or_off, next_arg, i;
char *o_option, *arg_string;
arg_index = arg_start;
while(arg_index != arg_end && (arg_string = argv[arg_index]) &&
(*arg_string == '-' || *arg_string == '+'))
{
/* There are flag arguments, so parse them. */
next_arg = arg_index + 1;
/* A single `-' signals the end of options. From the 4.3 BSD sh.
An option `--' means the same thing; this is the standard
getopt(3) meaning. */
if(arg_string[0] == '-' &&
(arg_string[1] == '\0' ||
(arg_string[1] == '-' && arg_string[2] == '\0')))
return (next_arg);
i = 1;
on_or_off = arg_string[0];
while(arg_character = arg_string[i++])
{
switch (arg_character)
{
case 'c':
//want_pending_command = 1;
break;
case 'l':
//make_login_shell = 1;
break;
case 's':
//read_from_stdin = 1;
break;
case 'o':
o_option = argv[next_arg];
if(o_option == 0)
{
//list_minus_o_opts(-1, (on_or_off == '-') ? 0 : 1);
break;
}
//if(set_minus_o_option(on_or_off, o_option) != EXECUTION_SUCCESS)
// exit(EX_BADUSAGE);
next_arg++;
break;
case 'O':
/* Since some of these can be overridden by the normal
interactive/non-interactive shell initialization or
initializing posix mode, we save the options and process
them after initialization. */
o_option = argv[next_arg];
if(o_option == 0)
{
//shopt_listopt(o_option, (on_or_off == '-') ? 0 : 1);
break;
}
//add_shopt_to_alist(o_option, on_or_off);
next_arg++;
break;
case 'D':
//dump_translatable_strings = 1;
break;
default:
break;
// if(change_flag(arg_character, on_or_off) == FLAG_ERROR)
// {
// report_error(_("%c%c: invalid option"), on_or_off, arg_character);
// show_shell_usage(stderr, 0);
// exit(EX_BADUSAGE);
// }
}
}
/* Can't do just a simple increment anymore -- what about
"bash -abouo emacs ignoreeof -hP"? */
arg_index = next_arg;
}
return (arg_index);
}
/**
* Strip whitespace from the start and end of STRING. Return a pointer into STRING.
*/
char * rl_stripwhite(char *string)
{
register char *s, *t;
for(s = string; whitespace(*s); s++)
;
if(*s == 0)
return (s);
t = s + strlen(s) - 1;
while(t > s && whitespace(*t))
t--;
*++t = '\0';
return s;
}
/* The structure used to store a history entry. */
typedef struct _hist_entry {
char *line;
char *timestamp; /* char * rather than time_t for read/write */
char *data;
} HIST_ENTRY;
/**
* Place STRING at the end of the history list.
*/
void add_history(const char *string)
{
HIST_ENTRY *temp;
// The data field is set to NULL
// TODO
}
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef whitespace
#define whitespace(c) (((c) == ' ') || ((c) == '\t'))
#endif
/*
* Initialize readline (and terminal if not already).
*/
int rl_initialize(void);
/**
* Strip whitespace from the start and end of STRING. Return a pointer into STRING.
*/
char * rl_stripwhite(char *string);
/**
* Read a line of input. Prompt with PROMPT. An empty PROMPT means none.
* A return value of NULL means that EOF was encountered.
*/
char *rl_readline(const char *prompt);
/**
* Place STRING at the end of the history list.
*/
void add_history(const char *string);
int parse_shell_options(char **argv, int arg_start, int arg_end);
......@@ -6,9 +6,9 @@
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
This file is part of DAP (Distributed Applications Platform) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
DAP (Distributed Applications Platform) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
......@@ -21,407 +21,758 @@
You should have received a copy of the GNU General Public License
along with any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <getopt.h>
#include <string.h>
#include "sig_unix_handler.h"
#include "dap_common.h"
#include "dap_config.h"
#include "dap_server.h"
#include "dap_http.h"
#include "dap_http_folder.h"
#include "dap_events.h"
#include "dap_enc.h"
#include "dap_enc_ks.h"
#include "dap_enc_http.h"
#include "dap_chain.h"
#include "dap_cert.h"
#include "dap_cert_file.h"
#include "dap_chain_wallet.h"
#include "dap_file_utils.h"
#include "dap_chain_cert.h"
#include "dap_chain_cert_file.h"
#define LOG_TAG "main_node_tool"
#define NODE_NAME "cellframe-node"
#undef log_it
#ifdef DAP_OS_WINDOWS
#include "registry.h"
#define log_it(_log_level, string, ...) __mingw_printf(string, ##__VA_ARGS__)
#else
#define log_it(_log_level, string, ...) printf(string, ##__VA_ARGS__)
#endif
static int s_init();
static void s_help( );
static int s_is_file_available (char *l_path, const char *name, const char *ext);
static void s_fill_hash_key_for_data(dap_enc_key_t *key, void *data);
static char s_system_ca_dir[MAX_PATH];
static char s_system_wallet_dir[MAX_PATH];
static int s_wallet_create(int argc, const char **argv);
static int s_wallet_create_from(int argc, const char **argv);
static int s_wallet_create_wp(int argc, const char **argv);
static int s_wallet_pkey_show(int argc, const char **argv);
static int s_wallet_pkey_show_full(int argc, const char **argv);
static int s_wallet_sign_file(int argc, const char **argv);
static int s_cert_create(int argc, const char **argv);
static int s_cert_dump(int argc, const char **argv);
static int s_cert_copy(int argc, const char **argv, bool a_pvt_key_copy);
static int s_cert_create_pkey(int argc, const char **argv);
static inline int s_cert_create_cert_pkey(int argc, const char **argv){
int res = s_cert_copy(argc, argv, false);
if (res == 0) {
log_it(L_NOTICE, "A certificate with a public key has been created.\n");
} else {
log_it(L_ERROR, "\nFailed to create a certificate with a public key. Error code: %d.", res);
}
return res;
}
static inline int s_cert_rename(int argc, const char **argv) {
int res = s_cert_copy(argc, argv, true);
if (res == 0) {
log_it(L_NOTICE, "Certificate renaming has been completed.\n");
} else {
log_it(L_ERROR, "\nFailed to rename the certificate.");
}
return res;
}
static int s_cert_add_metadata(int argc, const char **argv);
static int s_cert_sign(int argc, const char **argv);
static int s_cert_pkey_show(int argc, const char **argv);
static int s_cert_pkey_show_full(int argc, const char **argv);
static int s_cert_get_addr(int argc, const char **argv);
struct options {
char *cmd;
char *subcmd[5];
int count_of_subcommands;
int (*handler) (int argc, const char **argv);
} s_opts[] = {
{ "wallet", {"create"}, 1, s_wallet_create },
{ "wallet", {"create_from"}, 1, s_wallet_create_from },
{"wallet", {"create_wp"}, 1, s_wallet_create_wp},
{ "wallet", {"pkey", "show"}, 2, s_wallet_pkey_show },
{ "wallet", {"pkey", "show_full"}, 2, s_wallet_pkey_show_full },
{ "cert", {"create"}, 1, s_cert_create },
{ "cert", {"dump"}, 1, s_cert_dump },
{ "cert", {"create_pkey"}, 1, s_cert_create_pkey },
{ "cert", {"create_cert_pkey"}, 1, s_cert_create_cert_pkey },
{ "cert", {"rename"}, 1, s_cert_rename },
{ "cert", {"add_metadata"}, 1, s_cert_add_metadata },
{ "cert", {"sign"}, 1, s_cert_sign },
{ "cert", {"pkey", "show"}, 2, s_cert_pkey_show },
{ "cert", {"pkey", "show_full"}, 2, s_cert_pkey_show_full },
{"cert", {"addr", "show"}, 2, s_cert_get_addr }
};
#ifdef __ANDROID__
int cellframe_node_tool_Main(int argc, const char **argv)
#else
int main(int argc, const char **argv)
#endif
{
dap_set_appname(NODE_NAME);
// get relative path to config
int l_argv_start = 1, l_argvi, l_err = -2, l_ret_cmd = -1;
if (argc > 2 && !dap_strcmp("-B" , argv[1])) {
g_sys_dir_path = dap_strdup(argv[2]);
if (! dap_dir_test(g_sys_dir_path) )
return printf("Invalid path \"%s\"", g_sys_dir_path), DAP_DELETE(g_sys_dir_path), -1;
argc -= 2;
argv += 2;
l_argv_start += 2;
} else {
g_sys_dir_path =
#ifdef DAP_OS_WINDOWS
dap_strdup_printf("%s/%s", regGetUsrPath(), dap_get_appname());
#elif defined DAP_OS_MAC
dap_strdup_printf("/Library/Application Support/CellframeNode/");
#elif defined DAP_OS_UNIX
dap_strdup_printf("/opt/%s", dap_get_appname());
#endif
}
if ( argc < 2 )
return s_help( ), DAP_DELETE(g_sys_dir_path), -2;
if ( s_init() )
return log_it( L_ERROR, "Can't init modules" ), DAP_DELETE(g_sys_dir_path), -3;
size_t i, l_size = sizeof(s_opts) / sizeof(struct options);
for (i = 0; i < l_size; ++i) {
l_argvi = l_argv_start;
if (argc >= l_argvi && !strncmp(s_opts[i].cmd, argv[l_argvi], strlen (argv[l_argvi]) + 1)) {
l_err = 0;
for (int isub = 0; isub < s_opts[i].count_of_subcommands; isub++) {
if ( argc - 1 < ++l_argvi || strncmp(s_opts[i].subcmd[isub], argv[l_argvi], strlen(argv[l_argvi]) + 1) ) {
l_err = -1;
break;
}
}
if ( !l_err ) {
l_ret_cmd = s_opts[i].handler(argc, argv);
break;
}
}
}
switch ( l_err ) {
case -2:
printf("Command \"%s\" not found.\n", argv[1]);
s_help();
break;
case -1:
printf("No subcommand was found for command \"%s\".\n", argv[1]);
s_help();
break;
default: break;
}
dap_config_close(g_config);
DAP_DELETE(g_sys_dir_path);
return l_err ? l_err : l_ret_cmd;
}
#include "dap_chain_cs_dag.h"
#include "dap_chain_cs_dag_event.h"
#include "dap_chain_cs_dag_poa.h"
#include "dap_chain_cs_dag_pos.h"
static int s_wallet_create(int argc, const char **argv) {
if ( argc < 5 ) {
log_it( L_ERROR, "Wrong 'wallet create' command params" );
s_help( );
exit( -2003 );
}
const char *l_wallet_name = argv[3];
dap_sign_type_t l_sig_type = dap_sign_type_from_str( argv[4] );
dap_chain_wallet_t *l_wallet = NULL;
#include "dap_chain_net.h"
#include "dap_chain_net_srv.h"
#include "dap_chain_net_srv_app.h"
#include "dap_chain_net_srv_app_db.h"
#include "dap_chain_net_srv_datum.h"
#include "dap_chain_net_srv_datum_pool.h"
#include "dap_chain_net_srv_vpn.h"
//
// Check if wallet name has only digits and English letters
//
size_t is_str = dap_isstralnum(l_wallet_name);
#include "dap_stream_session.h"
#include "dap_stream.h"
#include "dap_stream_ch_vpn.h"
#include "dap_stream_ch_chain.h"
#include "dap_stream_ch_chain_net.h"
#include "dap_stream_ch_chain_net_srv.h"
if (!is_str)
{
log_it( L_ERROR, "Wallet name must contain digits and alphabet symbols");
exit( -2004 );
}
#include "dap_chain_wallet.h"
if ( l_sig_type.type == SIG_TYPE_NULL ) {
log_it( L_ERROR, "Invalid signature type '%s', you can use the following:\n%s",
argv[4], dap_sign_get_str_recommended_types());
s_help( );
exit( -2004 );
}
//
// Check unsupported tesla algorithm
//
if (dap_sign_type_is_depricated(l_sig_type))
{
log_it( L_ERROR, "Tesla, picnic, bliss algorithms is not supported, please, use another variant:\n%s",
dap_sign_get_str_recommended_types());
exit( -2004 );
}
#include "dap_common.h"
#include "dap_client.h"
#include "dap_http_simple.h"
#include "dap_process_manager.h"
char *l_file_name = dap_strdup_printf("%s/%s.dwallet", dap_chain_wallet_get_path(g_config), l_wallet_name);
if (dap_file_test(l_file_name)) {
log_it(L_ERROR, "The '%s' wallet already exists.\n", l_wallet_name);
exit(-2007);
}
DAP_DELETE(l_file_name);
#define DAP_APP_NAME NODE_NETNAME"-node"
#define SYSTEM_PREFIX "/opt/"DAP_APP_NAME
#define LOCAL_PREFIX "~/."DAP_APP_NAME
if (l_sig_type.type == SIG_TYPE_MULTI_CHAINED){
if (argc < 7) {
log_it(L_ERROR, "For a signature with type sig_multi_chained, two more signature type parameters must be set.");
exit(-2006);
}
dap_sign_type_t l_types[MAX_ENC_KEYS_IN_MULTYSIGN] = {0};
size_t l_count_signs = 0;
for (int i = 6; i < argc; i++) {
l_types[l_count_signs] = dap_sign_type_from_str(argv[i]);
if (l_types[l_count_signs].type == SIG_TYPE_NULL) {
log_it( L_ERROR, "Invalid signature type '%s', you can use the following:\n%s",
argv[i], dap_sign_get_str_recommended_types());
exit(-2007);
}
if (dap_sign_type_is_depricated(l_types[l_count_signs]))
{
log_it( L_ERROR, "Tesla, picnic, bliss algorithms is not supported, please, use another variant:\n%s",
dap_sign_get_str_recommended_types());
exit( -2008 );
}
l_count_signs++;
}
l_wallet = dap_chain_wallet_create_with_seed_multi(l_wallet_name, s_system_wallet_dir,
l_types, l_count_signs,
NULL, 0, NULL);
} else
l_wallet = dap_chain_wallet_create(l_wallet_name, s_system_wallet_dir, l_sig_type, NULL);
if (l_wallet) {
log_it(L_NOTICE, "Wallet %s has been created.\n", l_wallet_name);
return 0;
} else {
log_it(L_ERROR, "Failed to create a wallet.");
return -1;
}
}
#define SYSTEM_CONFIGS_DIR SYSTEM_PREFIX"/etc"
#define LOCAL_CONFIGS_DIR LOCAL_PREFIX"/etc"
static int s_wallet_create_wp(int argc, const char **argv) {
if ( argc < 5 ) {
log_it( L_ERROR, "Wrong 'wallet create' command params" );
s_help( );
exit( -2003 );
}
#define SYSTEM_CA_DIR SYSTEM_PREFIX"/var/lib/ca"
#define LOCAL_CA_DIR LOCAL_PREFIX"/ca"
const char *l_wallet_name = argv[3], *l_pass_str = argv[4];
dap_sign_type_t l_sig_type = dap_sign_type_from_str( argv[5] );
dap_chain_wallet_t *l_wallet = NULL;
#define SYSTEM_WALLET_DIR SYSTEM_PREFIX"/var/lib/wallet"
#define LOCAL_WALLET_DIR LOCAL_PREFIX"/wallet"
//
// Check if wallet name has only digits and English letters
//
#define SYSTEM_CONFIG_GLOBAL_FILENAME SYSTEM_PREFIX"/etc/"DAP_APP_NAME".cfg"
#define LOCAL_CONFIG_GLOBAL LOCAL_PREFIX"/etc/"DAP_APP_NAME".cfg"
size_t is_str = dap_isstralnum(l_wallet_name);
#define SYSTEM_PID_FILE_PATH SYSTEM_PREFIX"/run/"DAP_APP_NAME".pid"
#define LOCAL_PID_FILE_PATH SYSTEM_PREFIX"/run/"DAP_APP_NAME".pid"
if (!is_str)
{
log_it( L_ERROR, "Wallet name must contain digits and alphabet symbols");
exit( -2004 );
}
#define ENC_HTTP_URL "/enc_init"
#define STREAM_CTL_URL "/stream_ctl"
#define STREAM_URL "/stream"
#define SLIST_URL "/nodelist"
#define MAIN_URL "/"
#define LOG_TAG "main_node_tool"
if ( l_sig_type.type == SIG_TYPE_NULL ) {
log_it( L_ERROR, "Invalid signature type '%s', you can use the following:\n%s",
argv[4], dap_sign_get_str_recommended_types());
s_help( );
exit( -2004 );
}
//
// Check unsupported tesla algorithm
//
if (dap_sign_type_is_depricated(l_sig_type))
{
log_it( L_ERROR, "Tesla, picnic, bliss algorithms is not supported, please, use another variant:\n%s",
dap_sign_get_str_recommended_types());
exit( -2004 );
}
char *l_file_name = dap_strdup_printf("%s/%s.dwallet", dap_chain_wallet_get_path(g_config), l_wallet_name);
if (dap_file_test(l_file_name)) {
log_it(L_ERROR, "The '%s' wallet already exists.\n", l_wallet_name);
exit(-2007);
}
DAP_DELETE(l_file_name);
static int s_init(int argc, const char * argv[]);
static void s_help();
// Checking that if a password is set, it contains only Latin characters, numbers and special characters, except for spaces.
if (!dap_check_valid_password(l_pass_str, dap_strlen(l_pass_str))) {
log_it(L_ERROR, "Invalid characters used for password.\n");
exit(-2008);
}
static const char * s_appname;
int main(int argc, const char * argv[])
{
int ret;
s_appname = argv[0];
ret = s_init(argc, argv);
if (ret == 0){
if( argc >= 2 ){
if ( strcmp ( argv[1], "wallet" ) == 0 ){
if ( argc >=3 ){
if ( strcmp( argv[2],"create") == 0 ){
// wallet create <network name> <wallet name> <wallet_sign>
if ( argc >= 6 ){
dap_chain_net_id_t l_network_id = dap_chain_net_id_by_name (argv[3]) ;
if ( l_network_id.raw != 0) {
const char * l_wallet_name = argv[4];
dap_chain_sign_type_t l_sig_type = dap_chain_sign_type_from_str(argv[5]);
dap_chain_wallet_t * l_wallet = NULL;
if ( l_sig_type.type != SIG_TYPE_NULL ) {
size_t l_wallet_path_size = strlen(l_wallet_name)+strlen(SYSTEM_WALLET_DIR)+10;
char * l_wallet_path = DAP_NEW_Z_SIZE(char,l_wallet_path_size);
snprintf(l_wallet_path,l_wallet_path_size,"%s/%s.dwallet",SYSTEM_WALLET_DIR,l_wallet_name);
l_wallet = dap_chain_wallet_create(l_wallet_name,SYSTEM_WALLET_DIR,l_network_id,l_sig_type);
DAP_DELETE (l_wallet_path);
}else {
log_it(L_CRITICAL,"Wrong signature '%s'",argv[4]);
s_help();
exit(-2004);
}
}else {
log_it(L_CRITICAL,"No such network name '%s'",argv[3]);
s_help();
exit(-2005);
}
}else {
log_it(L_CRITICAL,"Wrong 'wallet create' command params");
s_help();
exit(-2003);
}
} else if ( strcmp( argv[2],"sign_file") == 0 ) {
// wallet sign_file <wallet name> <cert index> <data file path> <data offset> <data length> <dsign file path>
if ( argc >= 8 ){
dap_chain_wallet_t *l_wallet = dap_chain_wallet_open(argv[3],SYSTEM_WALLET_DIR);
if ( l_wallet) {
int l_cert_index = atoi(argv[4]);
size_t l_wallet_certs_number = dap_chain_wallet_get_certs_number(l_wallet);
if ( ( l_cert_index > 0 ) && ( l_wallet_certs_number >(size_t) l_cert_index ) ){
FILE * l_data_file = fopen (argv[5],"r");
if ( l_data_file){
}
} else {
log_it(L_CRITICAL,"Cert index %d can't be found in wallet with %u certs inside"
,l_cert_index,l_wallet_certs_number);
s_help();
exit(-3002);
}
}else {
log_it(L_CRITICAL,"Can't open wallet \"%s\"",argv[3]);
s_help();
exit(-3001);
}
}else {
log_it(L_CRITICAL,"Wrong 'wallet sign_file' command params");
s_help();
exit(-3000);
}
}
/* if ( strcmp( argv[2],"create_from") == 0 ){
}else if ( argc >=7){
// wallet create_from <wallet name> from <wallet ca1> [<wallet ca2> ...<wallet caN>]
dap_chain_cert_t ** l_wallet_cert = NULL;
size_t l_wallet_cert_size = 0;
l_wallet_cert_size = (argc - 3 )
l_wallet_cert = DAP_NEW_Z_SIZE (dap_chain_cert_t*, l_wallet_cert_size );
}else {
log_it(L_CRITICAL,"Wrong 'wallet create_from' command params");
s_help();
exit(-2002);
}
if ( l_wallet_cert ){
if (l_wallet_cert_size > 0)
for (size_t i = 0; i < l_wallet_cert_size; i++)
dap_chain_cert_delete( l_wallet_cert[i]->);
}
}*/else {
log_it(L_CRITICAL,"Wrong 'wallet' command params");
s_help();
exit(-2001);
}
}else {
log_it(L_CRITICAL,"Wrong 'wallet' command params");
s_help();
exit(-2000);
}
}else if (strcmp (argv[1],"cert") == 0 ){
if ( argc >=3 ){
if ( strcmp( argv[2],"dump") == 0 ){
if (argc>=4) {
const char * l_cert_name = argv[3];
dap_chain_cert_t * l_cert = dap_chain_cert_add_file(l_cert_name,SYSTEM_CA_DIR);
if ( l_cert ){
dap_chain_cert_dump(l_cert);
dap_chain_cert_delete_by_name(l_cert_name);
ret = 0;
}else{
exit(-702);
}
}
}else if ( strcmp( argv[2],"create_pkey") == 0 ){
if (argc>=5) {
const char * l_cert_name = argv[3];
const char * l_cert_pkey_path = argv[4];
dap_chain_cert_t * l_cert = dap_chain_cert_add_file(l_cert_name,SYSTEM_CA_DIR);
if ( l_cert ){
l_cert->enc_key->pub_key_data_size = dap_enc_gen_key_public_size(l_cert->enc_key);
if ( l_cert->enc_key->pub_key_data_size ){
//l_cert->key_private->pub_key_data = DAP_NEW_SIZE(void, l_cert->key_private->pub_key_data_size);
//if ( dap_enc_gen_key_public(l_cert->key_private, l_cert->key_private->pub_key_data) == 0){
dap_chain_pkey_t * l_pkey = dap_chain_pkey_from_enc_key( l_cert->enc_key );
if (l_pkey){
FILE * l_file = fopen(l_cert_pkey_path,"w");
if (l_file){
fwrite(l_pkey,1,l_pkey->header.size + sizeof(l_pkey->header),l_file);
fclose(l_file);
}
}else {
log_it(L_CRITICAL, "Can't produce pkey from the certificate");
exit(-7022);
}
dap_chain_cert_delete_by_name(l_cert_name);
ret = 0;
//}else{
// log_it(L_CRITICAL,"Can't produce public key with this key type");
// exit(-7024);
//}
}else{
log_it(L_CRITICAL,"Can't produce pkey from this cert type");
exit(-7023);
}
}else{
exit(-7021);
}
}
}else if ( strcmp( argv[2],"create_cert_pkey") == 0 ){
if (argc>=5) {
const char * l_cert_name = argv[3];
const char * l_cert_new_name = argv[4];
dap_chain_cert_t * l_cert = dap_chain_cert_add_file(l_cert_name,SYSTEM_CA_DIR);
if ( l_cert ){
if ( l_cert->enc_key->pub_key_data_size ){
// Create empty new cert
dap_chain_cert_t * l_cert_new = dap_chain_cert_new(l_cert_new_name);
l_cert_new->enc_key = dap_enc_key_new( l_cert->enc_key->type);
// Copy only public key
l_cert_new->enc_key->pub_key_data = DAP_NEW_Z_SIZE(uint8_t,
l_cert_new->enc_key->pub_key_data_size =
l_cert->enc_key->pub_key_data_size );
memcpy(l_cert_new->enc_key->pub_key_data, l_cert->enc_key->pub_key_data,l_cert->enc_key->pub_key_data_size);
dap_chain_cert_save_to_folder(l_cert_new, SYSTEM_CA_DIR);
//dap_chain_cert_delete_by_name(l_cert_name);
//dap_chain_cert_delete_by_name(l_cert_new_name);
}else{
log_it(L_CRITICAL,"Can't produce pkey from this cert type");
exit(-7023);
}
}else{
exit(-7021);
}
}
}
else if ( strcmp( argv[2],"create" ) == 0 ){
if (argc>=5) {
size_t l_key_length = 0;
const char * l_cert_name = argv[3];
size_t l_cert_path_length = strlen(argv[3])+8+strlen(SYSTEM_CA_DIR);
char * l_cert_path = DAP_NEW_Z_SIZE(char,l_cert_path_length);
snprintf(l_cert_path,l_cert_path_length,"%s/%s.dcert",SYSTEM_CA_DIR,l_cert_name);
if( access( l_cert_path, F_OK ) != -1 ) {
log_it (L_ERROR, "File %s is already exists! Who knows, may be its smth important?", l_cert_path);
exit(-700);
}
dap_enc_key_type_t l_key_type = DAP_ENC_KEY_TYPE_NULL;
if ( strcmp (argv[4],"sig_bliss") == 0 ){
l_key_type = DAP_ENC_KEY_TYPE_SIG_BLISS;
} else if ( strcmp (argv[4],"sig_tesla") == 0){
l_key_type = DAP_ENC_KEY_TYPE_SIG_TESLA;
} else if ( strcmp (argv[4],"sig_picnic") == 0){
l_key_type = DAP_ENC_KEY_TYPE_SIG_PICNIC;
}else{
log_it (L_ERROR, "Wrong key create action \"%s\"",argv[4]);
exit(-600);
}
if ( l_key_type != DAP_ENC_KEY_TYPE_NULL ){
int l_key_length = argc >=6 ? atoi(argv[5]) : 0;
dap_chain_cert_t * l_cert = dap_chain_cert_generate(l_cert_name,l_cert_path,l_key_type ); // key length ignored!
if (l_cert == NULL){
log_it(L_CRITICAL, "Can't create %s",l_cert_path);
}
} else {
s_help();
DAP_DELETE(l_cert_path);
exit(-500);
}
DAP_DELETE(l_cert_path);
}else{
s_help();
exit(-500);
}
}else {
log_it(L_CRITICAL,"Wrong params");
s_help();
exit(-1000);
}
}else {
log_it(L_CRITICAL,"Wrong params");
s_help();
exit(-1000);
}
}else {
log_it(L_CRITICAL,"Wrong params");
s_help();
exit(-1000);
if (l_sig_type.type == SIG_TYPE_MULTI_CHAINED){
if (argc < 8) {
log_it(L_ERROR, "For a signature with type sig_multi_chained, two more signature type parameters must be set.\n");
exit(-2006);
}
dap_sign_type_t l_types[MAX_ENC_KEYS_IN_MULTYSIGN] = {0};
size_t l_count_signs = 0;
for (int i = 6; i < argc; i++) {
l_types[l_count_signs] = dap_sign_type_from_str(argv[i]);
if (l_types[l_count_signs].type == SIG_TYPE_NULL) {
log_it( L_ERROR, "Invalid signature type '%s', you can use the following:\n%s",
argv[i], dap_sign_get_str_recommended_types());
exit(-2007);
}
}else {
log_it(L_CRITICAL,"Wrong params");
s_help();
exit(-1000);
if (dap_sign_type_is_depricated(l_types[l_count_signs]))
{
log_it( L_ERROR, "Tesla, picnic, bliss algorithms is not supported, please, use another variant:\n%s",
dap_sign_get_str_recommended_types());
exit( -2008 );
}
l_count_signs++;
}
}else
log_it(L_CRITICAL,"Can't init modules");
return ret;
l_wallet = dap_chain_wallet_create_with_seed_multi(l_wallet_name, s_system_wallet_dir,
l_types, l_count_signs,
NULL, 0, l_pass_str);
} else
l_wallet = dap_chain_wallet_create(l_wallet_name, s_system_wallet_dir, l_sig_type, l_pass_str);
if (l_wallet) {
log_it(L_NOTICE, "Wallet %s has been created.\n", l_wallet_name);
return 0;
} else {
log_it(L_ERROR, "Failed to create a wallet.");
return -1;
}
}
/**
* @brief s_init
* @param argc
* @param argv
* @return
*/
static int s_init(int argc, const char * argv[])
{
dap_config_init(SYSTEM_CONFIGS_DIR);
if((g_config = dap_config_open(DAP_APP_NAME) ) == NULL) {
log_it(L_CRITICAL,"Can't init general configurations");
return -1;
static int s_wallet_create_from(int argc, const char **argv) {
printf("The wallet create_from command is not implemented.");
return -1;
}
static int s_wallet_sign_file(int argc, const char **argv) {
if ( argc < 8 ) {
log_it(L_ERROR,"Wrong 'wallet sign_file' command params");
s_help();
exit(-3000);
}
dap_chain_wallet_t *l_wallet = dap_chain_wallet_open(argv[3], s_system_wallet_dir, NULL);
if ( !l_wallet ) {
log_it(L_ERROR,"Can't open wallet \"%s\"",argv[3]);
s_help();
exit(-3001);
}
if(dap_common_init(DAP_APP_NAME"_logs.txt")!=0){
log_it(L_CRITICAL,"Can't init common functions module");
return -2;
int l_cert_index = atoi(argv[4]);
size_t l_wallet_certs_number = dap_chain_wallet_get_certs_number( l_wallet );
if ( (l_cert_index > 0) && (l_wallet_certs_number > (size_t)l_cert_index) ) {
FILE *l_data_file = fopen( argv[5],"rb" );
if ( l_data_file ) {
fclose(l_data_file);
log_it(L_NOTICE, "Certificate %s was successfully created from wallet %s.\n", argv[5], argv[3]);
exit(0);
}
} else {
log_it( L_ERROR, "Cert index %d can't be found in wallet with %zu certs inside"
,l_cert_index,l_wallet_certs_number );
s_help();
exit( -3002 );
}
return 0;
}
static int s_cert_create(int argc, const char **argv) {
if ( argc < 5 ) {
log_it( L_ERROR, "Wrong 'cert create' command params\n");
s_help();
exit(-500);
}
const char *l_cert_name = argv[3];
size_t l_cert_path_length = strlen(argv[3])+8+strlen(s_system_ca_dir);
char *l_cert_path = DAP_NEW_Z_SIZE(char,l_cert_path_length);
snprintf(l_cert_path,l_cert_path_length,"%s/%s.dcert",s_system_ca_dir,l_cert_name);
if ( access( l_cert_path, F_OK ) != -1 ) {
log_it (L_ERROR, "File \"%s\" already exists!\n", l_cert_path);
exit(-700);
}
if (dap_chain_init() != 0 ){
log_it(L_CRITICAL,"Can't chain module");
return -3;
dap_sign_type_t l_sig_type = dap_sign_type_from_str( argv[4] );
if (l_sig_type.type == SIG_TYPE_NULL || l_sig_type.type == SIG_TYPE_MULTI_CHAINED) {
log_it(L_ERROR, "Unknown signature type %s specified, recommended signatures:\n%s",
argv[4], dap_cert_get_str_recommended_sign());
exit(-600);
} else if (l_sig_type.type == SIG_TYPE_MULTI_CHAINED) {
log_it(L_ERROR, "The sig_multi_chained signature is not applicable for certificate creation. "
"Use the following signatures:\\n%s", dap_cert_get_str_recommended_sign());
exit(-601);
}
if (dap_chain_cert_init() != 0) {
log_it(L_CRITICAL,"Can't chain certificate storage module");
return -4;
//
// Check unsupported algorithm
//
if (dap_sign_type_is_depricated(l_sig_type)) {
log_it(L_ERROR, "Signature type %s is obsolete, we recommend the following signatures:\n%s",
argv[4], dap_cert_get_str_recommended_sign());
exit(-602);
}
if (dap_chain_wallet_init() != 0) {
log_it(L_CRITICAL,"Can't chain wallet storage module");
return -5;
dap_enc_key_type_t l_key_type = dap_sign_type_to_key_type(l_sig_type);
if ( l_key_type != DAP_ENC_KEY_TYPE_INVALID ) {
dap_cert_t * l_cert = dap_cert_generate(l_cert_name,l_cert_path,l_key_type ); // key length ignored!
if (l_cert == NULL){
log_it(L_ERROR, "Can't create \"%s\"",l_cert_path);
}
dap_cert_delete(l_cert);
} else {
log_it (L_ERROR, "Wrong key create action \"%s\"",argv[4]);
s_help();
DAP_DELETE(l_cert_path);
exit(-500);
}
log_it(L_NOTICE, "Cert \"%s\" created\n", l_cert_path);
DAP_DELETE(l_cert_path);
return 0;
}
static int s_cert_dump(int argc, const char **argv)
{
if (argc>=4) {
const char * l_cert_name = argv[3];
dap_cert_t * l_cert = dap_cert_add_file(l_cert_name, s_system_ca_dir);
if ( l_cert ) {
char *l_cert_dump = dap_cert_dump(l_cert);
printf("%s", l_cert_dump);
dap_cert_delete_by_name(l_cert_name);
}
else {
log_it( L_ERROR, "Can't open '%s' cert\n", l_cert_name);
exit(-702);
}
} else {
log_it( L_ERROR, "Wrong 'cert dump' command params\n");
}
return 0;
}
if (dap_server_init(0) != 0) {
log_it(L_CRITICAL,"Can't server module");
return -6;
static int s_cert_create_pkey(int argc, const char **argv) {
if (argc < 5) {
log_it( L_ERROR, "Wrong 'cert create_pkey' command params\n");
exit(-7023);
}
const char *l_cert_name = argv[3];
const char *l_cert_pkey_path = argv[4];
dap_cert_t *l_cert = dap_cert_add_file(l_cert_name, s_system_ca_dir);
if ( !l_cert ) {
log_it(L_ERROR, "Failed to open \"%s\" certificate.", l_cert_name);
exit(-7021);
}
l_cert->enc_key->pub_key_data_size = dap_enc_ser_pub_key_size(l_cert->enc_key);
if ( l_cert->enc_key->pub_key_data_size ) {
//l_cert->key_private->pub_key_data = DAP_NEW_SIZE(void, l_cert->key_private->pub_key_data_size);
//if ( dap_enc_gen_key_public(l_cert->key_private, l_cert->key_private->pub_key_data) == 0){
dap_pkey_t * l_pkey = dap_pkey_from_enc_key( l_cert->enc_key );
if (l_pkey) {
if (dap_file_test(l_cert_pkey_path)){
log_it(L_ERROR, "The file \"%s\" exists.\n", l_cert_pkey_path);
exit(-7023);
}
FILE *l_file = fopen(l_cert_pkey_path,"wb");
if (l_file) {
fwrite(l_pkey,1,l_pkey->header.size + sizeof(l_pkey->header),l_file);
fclose(l_file);
}
} else {
log_it(L_ERROR, "Can't produce pkey from the certificate\n");
exit(-7022);
}
dap_cert_delete_by_name(l_cert_name);
log_it(L_NOTICE, "Created \"%s\" public key based on \"%s\" private key.\n", l_cert_pkey_path, l_cert_name);
return 0;
} else {
log_it(L_ERROR,"Can't produce pkey from this cert type\n");
exit(-7023);
}
}
static int s_cert_copy(int argc, const char **argv, bool a_pvt_key_copy)
{
if (argc < 5) {
log_it(L_ERROR, "Incorrect arguments count");
exit(-7021);
}
const char *l_cert_name = argv[3];
const char *l_cert_new_name = argv[4];
dap_cert_t *l_cert = dap_cert_add_file(l_cert_name, s_system_ca_dir);
if (!l_cert) {
log_it(L_ERROR, "Can't read specified certificate");
exit(-7023);
}
if (!l_cert->enc_key->pub_key_data || !l_cert->enc_key->pub_key_data_size) {
log_it(L_ERROR, "Invalid certificate key, no public key found");
exit(-7022);
}
char *l_cert_new_path = dap_strdup_printf("%s/%s.dcert", s_system_ca_dir, l_cert_new_name);
if (dap_file_test(l_cert_new_path)) {
log_it(L_ERROR, "The \"%s\" file already exists.\n", l_cert_new_path);
exit(-7023);
}
DAP_DELETE(l_cert_new_path);
// Create empty new cert
dap_cert_t *l_cert_new = dap_cert_new(l_cert_new_name);
l_cert_new->enc_key = dap_enc_key_new(l_cert->enc_key->type);
// Copy public key (copy only memory address of key storage)
l_cert_new->enc_key->pub_key_data = DAP_DUP_SIZE((byte_t*)l_cert->enc_key->pub_key_data,
l_cert->enc_key->pub_key_data_size);
if (!l_cert_new->enc_key->pub_key_data) {
log_it(L_CRITICAL, "%s", c_error_memory_alloc);
return -1;
}
l_cert_new->enc_key->pub_key_data_size = l_cert->enc_key->pub_key_data_size;
// Copy private key for rename (copy only memory address of key storage)
if (l_cert->enc_key->priv_key_data && l_cert->enc_key->priv_key_data_size && a_pvt_key_copy) {
l_cert_new->enc_key->priv_key_data = DAP_DUP_SIZE((byte_t*)l_cert->enc_key->priv_key_data,
l_cert->enc_key->priv_key_data_size);
if (!l_cert_new->enc_key->priv_key_data) {
log_it(L_CRITICAL, "%s", c_error_memory_alloc);
return -1;
}
l_cert_new->enc_key->priv_key_data_size = l_cert->enc_key->priv_key_data_size;
}
int ret = dap_cert_save_to_folder(l_cert_new, s_system_ca_dir);
if (!ret && a_pvt_key_copy) // Remove original cert after renaming
ret = dap_cert_delete_file(l_cert_name, s_system_ca_dir);
dap_cert_delete(l_cert); // Do not remove it before disk saving op
DAP_DEL_Z(l_cert_new->enc_key->pub_key_data);
DAP_DEL_Z(l_cert_new->enc_key->priv_key_data);
dap_cert_delete(l_cert_new);
return ret;
}
if (dap_stream_init(false) != 0) {
log_it(L_CRITICAL,"Can't init stream module");
return -7;
static int s_cert_add_metadata(int argc, const char **argv) {
if (argc >= 5) {
const char *l_cert_name = argv[3];
dap_cert_t *l_cert = dap_cert_add_file(l_cert_name, s_system_ca_dir);
if ( l_cert ) {
char **l_params = dap_strsplit(argv[4], ":", 4);
dap_cert_metadata_type_t l_type = (dap_cert_metadata_type_t)atoi(l_params[1]);
if (l_type == DAP_CERT_META_STRING || l_type == DAP_CERT_META_SIGN || l_type == DAP_CERT_META_CUSTOM) {
dap_cert_add_meta(l_cert, l_params[0], l_type, (void *)l_params[3], strtoul(l_params[2], NULL, 10));
} else {
dap_cert_add_meta_scalar(l_cert, l_params[0], l_type,
strtoull(l_params[3], NULL, 10), strtoul(l_params[2], NULL, 10));
}
dap_strfreev(l_params);
dap_cert_save_to_folder(l_cert, s_system_ca_dir);
dap_cert_delete_by_name(l_cert_name);
log_it(L_NOTICE, "The metainformation was successfully added to %s certificate\n", l_cert_name);
return 0;
}
else {
log_it(L_ERROR, "Can't open %s certificate", l_cert_name);
exit(-800);
}
} else {
log_it( L_ERROR, "Wrong 'cert add_metadata' command params\n");
exit(-800);
}
}
static int s_cert_sign(int argc, const char **argv) {
log_it(L_ERROR, "The command 'cert sign' is not implemented.");
return -1;
}
static int s_cert_pkey_show(int argc, const char **argv)
{
if (argc != 5) {
log_it( L_ERROR, "Wrong 'cert pkey show' command params\n");
exit(-800);
}
dap_cert_t *l_cert = dap_cert_find_by_name(argv[4]);
if (!l_cert) {
printf("Not found cert %s\n", argv[4]);
exit(-134);
}
dap_hash_fast_t l_hash;
if (dap_cert_get_pkey_hash(l_cert, &l_hash)) {
printf("Can't serialize cert %s", argv[4]);
exit(-135);
}
if (dap_stream_ch_init() != 0) {
log_it(L_CRITICAL,"Can't init stream ch module");
return -8;
printf("%s\n", dap_chain_hash_fast_to_str_static(&l_hash));
return 0;
}
static int s_cert_pkey_show_full(int argc, const char **argv)
{
if (argc != 5) {
log_it( L_ERROR, "Wrong 'cert pkey show' command params\n");
exit(-800);
}
dap_cert_t *l_cert = dap_cert_find_by_name(argv[4]);
if (!l_cert) {
printf("Not found cert %s\n", argv[4]);
exit(-134);
}
dap_hash_fast_t l_hash;
if (dap_cert_get_pkey_hash(l_cert, &l_hash)) {
printf("Can't serialize cert %s", argv[4]);
exit(-135);
}
if (dap_stream_ch_chain_init() != 0) {
log_it(L_CRITICAL,"Can't init stream ch chain module");
return -9;
char *l_pkey_str = dap_cert_get_pkey_str(l_cert, "hex");
printf("hash: %s\npkey: %s\n", dap_chain_hash_fast_to_str_static(&l_hash), l_pkey_str);
DAP_DELETE(l_pkey_str);
return 0;
}
static int s_wallet_pkey_show(int argc, const char **argv)
{
if (argc != 5) {
log_it( L_ERROR, "Wrong 'wallet pkey show' command params\n");
exit(-800);
}
dap_chain_wallet_t *l_wallet = dap_chain_wallet_open(argv[4], s_system_wallet_dir, NULL);
if (!l_wallet) {
printf("Not found wallet %s\n", argv[4]);
exit(-134);
}
if (dap_stream_ch_chain_net_init() != 0) {
log_it(L_CRITICAL,"Can't init stream ch chain net module");
return -10;
dap_hash_fast_t l_hash;
if (dap_chain_wallet_get_pkey_hash(l_wallet, &l_hash)) {
printf("Can't serialize wallet %s", argv[4]);
exit(-135);
}
if (dap_stream_ch_chain_net_srv_init() != 0) {
log_it(L_CRITICAL,"Can't init stream ch chain net srv module");
return -11;
printf("%s\n", dap_chain_hash_fast_to_str_static(&l_hash));
return 0;
}
static int s_wallet_pkey_show_full(int argc, const char **argv)
{
if (argc != 5) {
log_it( L_ERROR, "Wrong 'wallet pkey show' command params\n");
exit(-800);
}
dap_chain_wallet_t *l_wallet = dap_chain_wallet_open(argv[4], s_system_wallet_dir, NULL);
if (!l_wallet) {
printf("Not found wallet %s\n", argv[4]);
exit(-134);
}
if (dap_client_init() != 0) {
log_it(L_CRITICAL,"Can't chain wallet storage module");
return -12;
dap_hash_fast_t l_hash;
if (dap_chain_wallet_get_pkey_hash(l_wallet, &l_hash)) {
printf("Can't serialize wallet %s", argv[4]);
exit(-135);
}
char *l_pkey_str = dap_chain_wallet_get_pkey_str(l_wallet, "hex");
printf("hash: %s\npkey: %s\n", dap_chain_hash_fast_to_str_static(&l_hash), l_pkey_str);
DAP_DELETE(l_pkey_str);
return 0;
}
static int s_cert_get_addr(int argc, const char **argv) {
if (argc != 5) {
log_it( L_ERROR, "Wrong 'cert pkey show' command params\n");
exit(-900);
}
dap_cert_t *l_cert = dap_cert_find_by_name(argv[4]);
if (!l_cert) {
printf("Not found cert %s\n", argv[4]);
exit(-134);
}
dap_stream_node_addr_t l_addr = dap_stream_node_addr_from_cert(l_cert);
printf("%s\n", dap_stream_node_addr_to_str_static(l_addr));
return 0;
}
/**
* @brief s_init
* @param argc
* @param argv
* @return
*/
static int s_init()
{
if ( dap_common_init(dap_get_appname(), NULL) )
return printf("Fatal Error: Can't init common functions module"), -2;
#if defined (DAP_DEBUG) || !defined(DAP_OS_WINDOWS)
dap_log_set_external_output(LOGGER_OUTPUT_STDOUT, NULL);
#else
dap_log_set_external_output(LOGGER_OUTPUT_NONE, NULL);
#endif
dap_log_level_set(L_ERROR);
{
char l_config_dir[MAX_PATH];
snprintf(l_config_dir, MAX_PATH, "%s/etc", g_sys_dir_path);
if ( dap_config_init(l_config_dir) || !(g_config = dap_config_open(dap_get_appname())) )
return printf("Can't init general config \"%s/%s.cfg\"\n", l_config_dir, dap_get_appname()), -3;
}
char *l_ca_path = dap_config_get_item_str_path_default(g_config, "resources", "ca_folders", "."),
*l_wal_path = dap_config_get_item_str_path_default(g_config, "resources", "wallets_path", ".");
char *l_pos = dap_strncpy(s_system_ca_dir, l_ca_path, MAX_PATH);
if (*--l_pos == '/')
*l_pos = '\0';
dap_strncpy(s_system_wallet_dir, l_wal_path, MAX_PATH);
DAP_DEL_MULTY(l_ca_path, l_wal_path);
return 0;
}
/**
* @brief static_is_file_available
* @param l_path
* @param name
* @return
*/
static int s_is_file_available (char *l_path, const char *name, const char *ext)
{
char l_buf_path[MAX_PATH + 1];
snprintf (l_buf_path, MAX_PATH, "%s/%s%s", l_path, name, ext ? ext : 0);
return access (l_buf_path, F_OK) ? -1 : 0;
}
/**
* @brief s_fill_hash_key_for_data
* @param key
* @param data
*/
static void s_fill_hash_key_for_data(dap_enc_key_t *l_key, void *l_data)
{
size_t l_sign_unserialized_size = dap_sign_create_output_unserialized_calc_size(l_key);
if(l_sign_unserialized_size > 0) {
size_t l_pub_key_size = 0;
uint8_t *l_pub_key = dap_enc_key_serialize_pub_key(l_key, &l_pub_key_size);
if (!l_pub_key)
return;
uint8_t* l_sign_unserialized = DAP_NEW_Z_SIZE(uint8_t, l_sign_unserialized_size);
size_t l_sign_ser_size = l_sign_unserialized_size;
uint8_t *l_sign_ser = dap_enc_key_serialize_sign(l_key->type, l_sign_unserialized, &l_sign_ser_size);
if ( l_sign_ser ) {
dap_sign_t *l_ret = DAP_NEW_Z_SIZE_RET_IF_FAIL(dap_sign_t, sizeof(dap_sign_hdr_t) + l_sign_ser_size + l_pub_key_size);
// write serialized public key to dap_sign_t
memcpy(l_ret->pkey_n_sign, l_pub_key, l_pub_key_size);
l_ret->header.type = dap_sign_type_from_key_type(l_key->type);
// write serialized signature to dap_sign_t
memcpy(l_ret->pkey_n_sign + l_pub_key_size, l_sign_ser, l_sign_ser_size);
l_ret->header.sign_pkey_size = (uint32_t) l_pub_key_size;
l_ret->header.sign_size = (uint32_t) l_sign_ser_size;
DAP_DELETE(l_sign_ser);
dap_enc_key_signature_delete(l_key->type, l_sign_unserialized);
DAP_DELETE(l_pub_key);
dap_chain_hash_fast_t fast_hash;
dap_hash_fast(l_ret->pkey_n_sign, l_ret->header.sign_pkey_size, &fast_hash);
uint8_t *s = (uint8_t *) l_data;
for (int i = 0; i < DAP_CHAIN_HASH_FAST_SIZE; i++) {
s[i] = fast_hash.raw[i];
}
DAP_DEL_Z(l_ret);
}
}
}
/**
......@@ -430,27 +781,51 @@ static int s_init(int argc, const char * argv[])
*/
static void s_help()
{
printf("%s usage:\n",s_appname);
printf("\t\t%s wallet create <network name> <wallet name> <signature type> [<signature type 2>[...<signature type N>]]");
printf("\nCreate new key wallet and generate signatures with same names plus index \n\n");
#ifdef _WIN32
SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), 7 );
#endif
char *l_tool_appname = dap_strdup_printf("%s-tool", dap_get_appname());
printf( "\n" );
printf( "%s usage:\n\n", l_tool_appname);
printf("\t\t%s wallet create_from <network name> <wallet name> <wallet ca1> [<wallet ca2> [...<wallet caN>]]");
printf("\nCreate new key wallet from existent certificates in the system\n\n");
printf(" * Create new key wallet and generate signatures with same names plus index \n" );
printf("\t%s wallet create <wallet name> <signature type> [<signature type 2>[...<signature type N>]]\n\n", l_tool_appname);
printf("\t\t%s cert create <cert name> <key type> [<key length>]\n",s_appname);
printf("\nCreate new key file with randomly produced key stored in\n\n");
printf(" * Create a new key wallet and generate signatures with the same names plus index. The wallet will be password protected. \n" );
printf("\t%s wallet create_wp <wallet name> <password> <signature type> [<signature type 2>[...<signature type N>]]\n\n", l_tool_appname);
printf("\t\t%s cert dump <cert name>\n",s_appname);
printf("\nDump cert data stored in <file path>\n");
printf("\t\t%s cert sign <cert name> <data file path> <sign file output> [<sign data length>] [<sign data offset>]\n",s_appname);
printf("\nSign some data with cert \n");
#if 0
printf(" * Create new key wallet from existent certificates in the system\n");
printf("\t%s wallet create_from <network name> <wallet name> <wallet ca1> [<wallet ca2> [...<wallet caN>]]\n\n", l_tool_appname);
#endif
printf("\t\t%s cert create_pkey <cert name> <pkey path>\n",s_appname);
printf("\nCreate pkey from <cert name> and store it on <pkey path>\n");
printf(" * Print hash of public key for wallet <wallet name>\n");
printf("\t%s wallet pkey show <wallet name>\n\n", l_tool_appname);
printf(" * Create new key file with randomly produced key stored in\n");
printf("\t%s cert create <cert name> <sign type> [<key length>]\n\n", l_tool_appname);
printf("\t\t%s cert create_cert_pkey <cert name> <new cert name>\n",s_appname);
printf("\nExport only public key from <cert name> and stores it \n");
}
printf(" * Dump cert data stored in <file path>\n");
printf("\t%s cert dump <cert name>\n\n", l_tool_appname);
printf(" * Sign some data with cert \n");
printf("\t%s cert sign <cert name> <data file path> <sign file output> [<sign data length>] [<sign data offset>]\n\n", l_tool_appname);
printf(" * Create pkey from <cert name> and store it on <pkey path>\n");
printf("\t%s cert create_pkey <cert name> <pkey path>\n\n", l_tool_appname);
printf(" * Export only public key from <cert name> and stores it \n");
printf("\t%s cert create_cert_pkey <cert name> <new cert name>\n\n", l_tool_appname);
printf(" * Print hash of public key for cert <cert name>\n");
printf("\t%s cert pkey show <cert name>\n\n", l_tool_appname);
printf(" * Print addr of cert <cert name>\n");
printf("\t%s cert addr show <cert name>\n\n", l_tool_appname);
printf(" * Add metadata item to <cert name>\n");
printf("\t%s cert add_metadata <cert name> <key:type:length:value>\n\n", l_tool_appname);
DAP_DELETE(l_tool_appname);
}
......@@ -2,9 +2,9 @@
Copyright (c) 2017-2018 (c) Project "DeM Labs Inc" https://github.com/demlabsinc
All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
This file is part of DAP (Demlabs Application Protocol) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
DAP (Demlabs Application Protocol) is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
......@@ -89,10 +89,13 @@ void client_disconnect(dap_server_client_t *client,void * arg)
* @return Zero if ok or error code
*/
int node_manager_init(){
if(dap_common_init("build/log.txt")!=0){
log_it(L_CRITICAL,"Can't init common functions module");
return -2;
}
if ( dap_common_init("build/log.txt") )
return printf("Can't init common functions module"), -2;
#if defined (DAP_DEBUG) || !defined(DAP_OS_WINDOWS)
dap_log_set_external_output(LOGGER_OUTPUT_STDOUT, NULL);
#else
dap_log_set_external_output(LOGGER_OUTPUT_NONE, NULL);
#endif
if(dap_config_init("build/config")!=0){
log_it(L_CRITICAL,"Can't init configurations module");
return -1;
......
......@@ -2,9 +2,9 @@
Copyright (c) 2017-2018 (c) Project "DeM Labs Inc" https://github.com/demlabsinc
All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
This file is part of DAP (Demlabs Application Protocol) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
DAP (Demlabs Application Protocol) is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
......
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "dap_common.h"
#include "dap_events.h"
#include "dap_global_db.h"
#include "dap_chain_node.h"
#include "dap_chain_net_srv_xchange.h"
#include "dap_chain_net_srv_stake_pos_delegate.h"
#include "dap_chain_net_srv_stake_lock.h"
#include "dap_chain.h"
#include "dap_stream.h"
#include "dap_stream_ctl.h"
#include "dap_enc_ks.h"
#include "dap_enc_http.h"
#include "dap_http_server.h"
#include "dap_chain_node_dns_server.h"
#include "sig_unix_handler.h"
#include "dap_plugin.h"
#ifdef DAP_MODULES_DYNAMIC
#include "dap_modules_dynamic_cdb.h"
#endif
#define LOG_TAG "sig_unix_handler"
static const char *l_pid_path;
void dap_chain_plugins_deinit();
static const char *s_pid_path = NULL;
static void clear_pid_file() {
FILE * f = fopen(l_pid_path, "w");
FILE * f = fopen(s_pid_path, "w");
if (f == NULL)
log_it(L_WARNING, "Pid file not cleared");
else
fclose(f);
}
_Noreturn static void sig_exit_handler(int sig_code) {
static void sig_exit_handler(int sig_code) {
log_it(L_DEBUG, "Got exit code: %d", sig_code);
clear_pid_file();
fflush(stdout);
exit(0);
/*clear_pid_file();
dap_plugin_deinit();
dap_chain_node_mempool_autoproc_deinit();
dap_chain_net_srv_xchange_deinit();
dap_chain_net_srv_stake_pos_delegate_deinit();
dap_chain_net_srv_stake_lock_deinit();
dap_chain_net_deinit();
dap_global_db_deinit();
dap_chain_deinit();
dap_stream_ctl_deinit();
dap_stream_deinit();
dap_enc_ks_deinit();
enc_http_deinit();
dap_http_deinit();
#ifdef DAP_MODULES_DYNAMIC
dap_modules_dynamic_close_cdb();
#endif
dap_interval_timer_deinit();
dap_common_deinit();
log_it(L_NOTICE,"Stopped Cellframe Node");
fflush(stdout);
exit(0);*/
}
int sig_unix_handler_init(const char *pid_path) {
l_pid_path = strdup(pid_path);
int sig_unix_handler_init(const char *a_pid_path)
{
//char * l_pid_dir = dap_path_get_dirname(a_pid_path);
//sleep(1); // Don't know why but without it it crashes O_o
//dap_mkdir_with_parents(l_pid_dir);
//DAP_DELETE(l_pid_dir);
//log_it(L_DEBUG, "Init");
s_pid_path = strdup(a_pid_path);
signal(SIGINT, sig_exit_handler);
signal(SIGTERM, sig_exit_handler);
signal(SIGHUP, sig_exit_handler);
signal(SIGTERM, sig_exit_handler);
signal(SIGQUIT, sig_exit_handler);
signal(SIGTSTP, sig_exit_handler);
return 0;
}
int sig_unix_handler_deinit() {
free((char*)l_pid_path);
//log_it(L_DEBUG, "Deinit");
if( s_pid_path )
DAP_DELETE((void *)s_pid_path);
signal(SIGTERM, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGHUP, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <memory.h>
#include <windows.h>
#include "dap_common.h"
#include "sig_win32_handler.h"
#define LOG_TAG "sig_win32_handler"
BOOL WINAPI sig_exit_handler( DWORD fdwCtrlType )
{
HANDLE hConOut = GetStdHandle( STD_OUTPUT_HANDLE );
SetConsoleTextAttribute( hConOut, 12 );
switch (fdwCtrlType)
{
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
printf("Ctrl-C event\n\n");
Beep(750, 300);
break;
// CTRL-CLOSE: confirm that the user wants to exit.
case CTRL_CLOSE_EVENT:
Beep(600, 200);
printf("Ctrl-Close event\n\n");
break;
// Pass other signals to the next handler.
case CTRL_BREAK_EVENT:
Beep(900, 200);
printf("Ctrl-Break event\n\n");
break;
case CTRL_LOGOFF_EVENT:
Beep(1000, 200);
printf("Ctrl-Logoff event\n\n");
break;
case CTRL_SHUTDOWN_EVENT:
Beep(750, 500);
printf("Ctrl-Shutdown event\n\n");
break;
}
SetConsoleTextAttribute( hConOut, 7 );
ExitProcess( 2 );
}
int sig_win32_handler_init( const char *pid_path ) {
if ( !SetConsoleCtrlHandler( sig_exit_handler, TRUE ) ) return 1;
return 0;
}
int sig_win32_handler_deinit() {
SetConsoleCtrlHandler( sig_exit_handler, FALSE );
return 0;
}
#pragma once
int sig_win32_handler_init( const char *pid_path );
int sig_win32_handler_deinit( );
if(TARGET kelvin_node_test)
return() # The project has already been built.
endif()
project(kelvin_node_test)
add_subdirectory(libdap-test)
file(GLOB SOURCES *.c)
file(GLOB HEADERS *.h)
add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})
target_link_libraries(${PROJECT_NAME} dap_core dap_test dap_chain_global_db)
add_test(
NAME kelvin_node_test
COMMAND kelvin_node_test
)
#include <time.h>
#include <unistd.h>
#include "dap_common.h"
#include "dap_strfuncs.h"
//#include "dap_list.h"
#include "dap_chain_global_db.h"
#include "dap_chain_global_db_driver.h"
#include "dap_global_db_test.h"
#define DB_FILE "./base.sqlite"
static void test_create_db(void)
{
unlink(DB_FILE);
int res = dap_db_driver_init("sqlite", DB_FILE);
dap_assert(!res, "Test init global_db");
}
static void test_write_read_one(void)
{
dap_store_obj_t *l_store_obj = DAP_NEW_Z(dap_store_obj_t);
size_t l_store_count = 1;
l_store_obj->type = 'a';
l_store_obj->key = dap_strdup("key");
l_store_obj->group = dap_strdup("section.1");
l_store_obj->timestamp = time(NULL);
l_store_obj->value_len = rand() % 100;
l_store_obj->value = DAP_NEW_SIZE(uint8_t, l_store_obj->value_len);
for(size_t i = 0; i < l_store_obj->value_len; i++) {
l_store_obj->value[i] = rand();
}
int ret = dap_chain_global_db_driver_add(l_store_obj, l_store_count);
dap_store_obj_t *l_store_obj2 = dap_chain_global_db_driver_read(l_store_obj->group, l_store_obj->key, NULL);
dap_assert_PIF(l_store_obj2, "Read global_db entry");
// compare l_store_obj and l_store_obj
if(l_store_obj->timestamp == l_store_obj2->timestamp &&
l_store_obj->value_len == l_store_obj2->value_len &&
l_store_obj->value && l_store_obj2->value &&
!memcmp(l_store_obj->value, l_store_obj2->value, l_store_obj->value_len)) {
dap_assert_PIF(1, "Check read entry");
}
else {
dap_assert_PIF(0, "Check read entry");
}
dap_store_obj_free(l_store_obj, 1);
dap_store_obj_free(l_store_obj2, 1);
dap_assert(1, "Test dap_global_db one record");
}
static void test_close_db(void)
{
dap_db_driver_deinit();//dap_chain_global_db_deinit();
dap_assert(1, "Test close global_db");
}
static void test_write_db_count(void)
{
int a_count = 20000;
dap_store_obj_t *l_store_obj = DAP_NEW_Z_SIZE(dap_store_obj_t, sizeof(dap_store_obj_t) * a_count);
size_t l_store_count = 1;
for(size_t n = 0; n < a_count; n++) {
dap_store_obj_t *l_store_obj_cur = l_store_obj + n;
l_store_obj_cur->type = 'a';
l_store_obj_cur->key = dap_strdup_printf("key_%d", rand());
l_store_obj_cur->group = dap_strdup("section.1");
l_store_obj_cur->timestamp = time(NULL);
l_store_obj_cur->value_len = 10 + rand() % 100;
l_store_obj_cur->value = DAP_NEW_SIZE(uint8_t, l_store_obj_cur->value_len);
for(size_t i = 0; i < l_store_obj_cur->value_len; i++) {
l_store_obj_cur->value[i] = rand();
}
}
//dap_test_msg("Start test write dap_global_db %d record", a_count);
int ret = dap_chain_global_db_driver_add(l_store_obj, a_count);
//dap_test_msg("Read first record");
dap_store_obj_t *l_store_obj2 = dap_chain_global_db_driver_read(l_store_obj->group, l_store_obj->key, NULL);
dap_store_obj_free(l_store_obj2, 1);
//dap_test_msg("Start test read dap_global_db %d record", a_count);
for(size_t n = 1; n < a_count; n++) {
dap_store_obj_t *l_store_obj2 = dap_chain_global_db_driver_read(l_store_obj->group, l_store_obj->key, NULL);
dap_assert_PIF(l_store_obj2, "Read data");
// compare l_store_obj and l_store_obj
if(l_store_obj->timestamp == l_store_obj2->timestamp &&
l_store_obj->value_len == l_store_obj2->value_len &&
l_store_obj->value && l_store_obj2->value &&
!memcmp(l_store_obj->value, l_store_obj2->value, l_store_obj->value_len)) {
;
}
else {
dap_assert_PIF(0, "Check read entry");
}
dap_store_obj_free(l_store_obj2, 1);
}
//dap_assert_PIF(1, "Read global_db entry");
dap_store_obj_free(l_store_obj, a_count);
//dap_usleep(5 * DAP_USEC_PER_SEC);
//dap_assert(1, "Test dap_global_db");
}
void dap_global_db_tests_run(void)
{
dap_print_module_name("dap_global_db");
unlink(DB_FILE);
test_create_db();
test_write_read_one();
// test_write_db_count(1000000);
benchmark_mgs_time("Read and Write in global_db 20000 records",
benchmark_test_time(test_write_db_count, 1));
//dap_assert(1, "Test dap_global_db: write and read 20000 records");
/*
benchmark_mgs_time("Read and Write in global_db 100 times",
benchmark_test_time(test_write_db_count, 1));
dap_assert(1, "Test dap_global_db 100 records");
*/
// benchmark_mgs_rate("Read and Write in global_db",
// benchmark_test_rate(test_write_db_count, 2000));
//dap_usleep(2 * DAP_USEC_PER_SEC);
test_close_db();
}
#pragma once
#include "libdap-test/dap_test.h"
extern void dap_global_db_tests_run(void);
Subproject commit b76175acc517f085c319c8e66c62bd143f96bf94
#include "dap_global_db_test.h"
#include "dap_common.h"
int main(void) {
// switch off debug info from library
dap_log_level_set(L_CRITICAL);
dap_global_db_tests_run();
return 0;
}
VERSION_MAJOR=5
VERSION_MINOR=3
VERSION_PATCH=178