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 1797 additions and 2171 deletions
resources/cellframe.ico

99.7 KiB

my-dir = $(call parent-dir,$(lastword $(MAKEFILE_LIST)))
prextarget := ../lib/
LOCAL_PATH := $(call my-dir)
LOCAL_MODULE := kelvin-node-cli$(xtarget)
include ../win32/[cdf_set].mk
LOCAL_C_INCLUDES += \
../libdap-server-http-db-auth/ \
../libdap-client/include/ \
../libdap-chain-gdb/ \
../libdap-chain-cs-dag-pos/ \
../libdap-chain-cs-dag-poa/ \
../libdap-chain-cs-dag/ \
../libdap-stream-ch-chain-net-srv/ \
../libdap-stream-ch-vpn/ \
../libdap-stream-ch-chain-net/ \
../libdap-stream-ch-chain/ \
../libdap-chain-wallet/ \
../libdap-chain-net-srv-vpn/ \
../libdap-chain-net-srv-datum-pool/ \
../libdap-chain-net-srv-datum/ \
../libdap-chain-net-srv-app-db/ \
../libdap-chain-net-srv-app/ \
../libdap-chain-net-srv/ \
../libdap-chain-net/ \
../libdap-chain-mempool/ \
../libdap-chain-global-db/ \
../libdap-chain/ \
../libdap-chain-crypto/monero_crypto/ \
../libdap-chain-crypto/ \
../libdap-stream/stream \
../libdap-stream/session \
../libdap/include/ \
../libdap-crypto/include/ \
../libdap-crypto/src/ \
../libdap/src/win32/ \
../libdap-server-core/include/ \
../libdap-server/http_server/ \
../libdap-server/enc_server/ \
../libdap-server/http_server/http_client/ \
../libdap-server-udp/ \
../libdap-stream-ch/ \
../3rdparty/curl/include/ \
../3rdparty/libsqlite3/ \
../3rdparty/libjson-c/ \
../3rdparty/libmemcached/ \
../3rdparty/libmemcached/win32/ \
../3rdparty/wepoll/include/ \
../3rdparty/uthash/src/ \
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES)
LOCAL_C_DEFINES := UNDEBUG NDEBUG WIN32 _WINDOWS __WINDOWS__ _CRT_SECURE_NO_WARNINGS CURL_STATICLIB
LOCAL_C_DEFINES += DAP_SERVER NODE_NETNAME=\"kelvin\"
LOCAL_LSLIBS := \
libdap-stream-ch-chain-net \
libdap-stream-ch-chain \
libdap-chain-net-srv \
libdap-chain-net \
libdap-chain-gdb \
libdap-chain-cs-dag-poa \
libdap-chain-cs-dag-pos \
libdap-chain-cs-dag \
libdap-chain-net \
libdap-chain-wallet \
libdap-chain-mempool \
libdap-chain \
libdap-client \
libdap-stream \
libdap-stream-ch \
libdap-chain-global-db \
libdap-chain-crypto \
libdap_server \
libdap_server_core \
libdap \
libdap-server-udp \
libjson-c \
libmemcached \
wepoll \
libmagic \
monero_crypto \
libdap_crypto \
libsqlite3 \
regex \
libmongoc \
libbson \
curl \
nghttp2 \
libssl \
c-ares \
misc \
zlib \
libssh2 \
libcrypto \
LOCAL_LSLIBS := $(addsuffix $(xtarget).a, $(LOCAL_LSLIBS))
ifneq ($(filter [x86CLANG] [x86_64CLANG] [x86GCC] [x86_64GCC],$(xtarget)),)
LOCAL_LSLIBS := $(addprefix ../lib/$(xtarget)/, $(LOCAL_LSLIBS))
endif
LOCAL_LDLIBS := \
KERNEL32 \
USER32 \
SHELL32 \
WINMM \
GDI32 \
ADVAPI32 \
Ole32 \
Version \
Imm32 \
OleAut32 \
ws2_32 \
ntdll \
psapi \
Shlwapi \
Bcrypt \
Crypt32 \
Secur32
ifneq ($(filter [x86CLANG] [x86_64CLANG] [x86GCC] [x86_64GCC],$(xtarget)),)
LOCAL_LDLIBS := $(addprefix -l, $(LOCAL_LDLIBS))
else
LOCAL_LDLIBS := $(addsuffix .lib, $(LOCAL_LDLIBS))
endif
LOCAL_SRC_FILES := \
main_node_cli.c \
main_node_cli_net.c \
main_node_cli_shell.c \
sig_win32_handler.c \
include ../win32/[cdf_makebin].mk
cmake_minimum_required(VERSION 3.22.1)
project("android-node")
add_library(android-node SHARED
./node_jni.cpp)
target_link_libraries(android-node
# List libraries link to the target library
android
log
cellframe-node
cellframe-node-config)
\ No newline at end of file
#include <android/log.h>
#include <time.h>
#include <unistd.h>
#include <jni.h>
#include "../cellframe-node.h"
#include "../../conftool/cellframe-node-config.h"
std::string jstring2string(JNIEnv *env,
jstring jStr) {
if (!jStr)
return "";
const jclass stringClass = env->GetObjectClass(jStr);
const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes, env->NewStringUTF("UTF-8"));
size_t length = (size_t) env->GetArrayLength(stringJbytes);
jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL);
std::string ret = std::string((char *)pBytes, length);
env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_ABORT);
env->DeleteLocalRef(stringJbytes);
env->DeleteLocalRef(stringClass);
return ret;
}
//notify listner logic
static JavaVM *jvm = nullptr;
class NotifyListenerStore {
public:
NotifyListenerStore(jweak pJobject, jmethodID pID){
store_Wlistener=pJobject;
store_method = pID;
}
jweak store_Wlistener=NULL;
jmethodID store_method = NULL;
};
std::vector<NotifyListenerStore *> listeners_vector;
JNIEnv *store_env;
extern "C"
JNIEXPORT void JNICALL
Java_com_cellframe_node_NodeService_setNotifyListenerNativeCallback(JNIEnv *env, jobject instance,
jobject listener) {
env->GetJavaVM(&jvm); //store jvm reference for later call
store_env = env;
jweak store_Wlistener = env->NewWeakGlobalRef(listener);
jclass clazz = env->GetObjectClass(store_Wlistener);
jmethodID store_method = env->GetMethodID(clazz, "onNotify", "(Ljava/lang/String;)V");
NotifyListenerStore *tmpt = new NotifyListenerStore(store_Wlistener, store_method);
listeners_vector.push_back(tmpt);
__android_log_print(ANDROID_LOG_VERBOSE, "GetEnv:", " Subscribe to Listener OK \n");
if (nullptr == store_method) return;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_cellframe_node_NodeService_clearNotifyListenerNativeCallbacks(JNIEnv *env, jobject instance) {
if (!listeners_vector.empty()) {
for (auto &i: listeners_vector) {
env->DeleteWeakGlobalRef(i->store_Wlistener);
i->store_method = NULL;
}
listeners_vector.clear();
}
}
void callOnNotify(JNIEnv *env, const _jstring *message_)
{
if (!listeners_vector.empty()) {
for (auto &i: listeners_vector) {
env->CallVoidMethod(i->store_Wlistener,
i->store_method, message_);
}
}
}
bool notifycallback(const char *data){
__android_log_print(ANDROID_LOG_ERROR, "CellframeNotify", "%s" , data);
__android_log_print(ANDROID_LOG_VERBOSE, "GetEnv:", " start Callback to JNL [%d] \n", data);
JNIEnv *g_env;
if (NULL == jvm) {
__android_log_print(ANDROID_LOG_ERROR, "GetEnv:", " No VM \n");
return false;
}
// double check it's all ok
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6; // set your JNI version
args.name = NULL; // you might want to give the java thread a name
args.group = NULL; // you might want to assign the java thread to a ThreadGroup
int getEnvStat = jvm->GetEnv((void **) &g_env, JNI_VERSION_1_6);
if (getEnvStat == JNI_EDETACHED) {
if (jvm->AttachCurrentThread(&g_env, &args) != 0) {
__android_log_print(ANDROID_LOG_ERROR, "GetEnv:", " Failed to attach");
}
} else if (getEnvStat == JNI_OK) {
__android_log_print(ANDROID_LOG_VERBOSE, "GetEnv:", " JNI_OK");
} else if (getEnvStat == JNI_EVERSION) {
__android_log_print(ANDROID_LOG_ERROR, "GetEnv:", " version not supported");
}
jstring message = g_env->NewStringUTF(data);//
callOnNotify(g_env, message);
if (g_env->ExceptionCheck()) {
g_env->ExceptionDescribe();
}
if (getEnvStat == JNI_EDETACHED) {
jvm->DetachCurrentThread();
}
return true;
}
extern "C" JNIEXPORT jint JNICALL
Java_com_cellframe_node_NodeService_nodeMainNative(
JNIEnv* env,
jobject instance , jstring system_dir)
{
set_global_sys_dir(jstring2string(env,system_dir).c_str());
dap_notify_data_set_user_callback(notifycallback);
int res= main(0,0);
Java_com_cellframe_node_NodeService_clearNotifyListenerNativeCallbacks(env, instance);
return res;
}
extern "C" JNIEXPORT jint JNICALL Java_com_cellframe_node_NodeService_initConfigs(
JNIEnv* env,
jobject /* this */, jstring base_path, jstring setup_file_path)
{
try {
conftool::populate_variables(jstring2string(env, base_path));
return conftool::init_configs(jstring2string(env, setup_file_path),0,true);
}
catch (std::exception e){
__android_log_print(ANDROID_LOG_ERROR, "CellframeNodeConfig", "Error in configuration init: %s" , e.what());
}
return -1;
}
extern "C" JNIEXPORT jint JNICALL Java_com_cellframe_node_NodeService_configure(
JNIEnv* env,
jobject /* this */, jstring base_path, jstring config_command)
{
try {
conftool::populate_variables(jstring2string(env, base_path));
std::vector < std::unique_ptr<CAbstractScriptCommand>> commands;
commands.push_back(conftool::parse_line_to_cmd(jstring2string(env, config_command), 0, 0));
return conftool::run_commands(commands,false, 0);
}
catch (std::exception e){
__android_log_print(ANDROID_LOG_ERROR, "CellframeNodeConfig", "Error in configuration init: %s" , e.what());
}
return -1;
}
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_cellframe_node_NodeService_clicommandArgs(JNIEnv *env, jobject instance, jobjectArray stringArray)
{
int stringCount = env->GetArrayLength(stringArray);
std::vector< char *> args;
for (int i=0; i<stringCount; i++) {
jstring string = (jstring) (env->GetObjectArrayElement(stringArray, i));
const char *rawString = env->GetStringUTFChars(string, 0);
args.push_back((char *)rawString);
}
args.push_back(0);
char * cli_answer = dap_cli_exec(args.size(),&args[0]);
int reslen = strlen(cli_answer);
jbyteArray arr = env->NewByteArray(reslen);
env->SetByteArrayRegion(arr,0,reslen, (jbyte*)cli_answer);
return arr;
}
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_cellframe_node_NodeService_clicommandString(JNIEnv *env, jobject instance, jstring cmd)
{
std::string rcmd = jstring2string(env, cmd);
std::vector<char *> args;
std::istringstream iss(rcmd);
std::string token;
while(iss >> token) {
char *arg = new char[token.size() + 1];
copy(token.begin(), token.end(), arg);
arg[token.size()] = '\0';
args.push_back(arg);
}
args.push_back(0);
char * cli_answer = dap_cli_exec(args.size(),&args[0]);
int reslen = strlen(cli_answer);
jbyteArray arr = env->NewByteArray(reslen);
env->SetByteArrayRegion(arr,0,reslen, (jbyte*)cli_answer);
for(size_t i = 0; i < args.size(); i++)
delete[] args[i];
return arr;
}
/*
* Authors:
* Dmitriy A. Gerasimov <kahovski@gmail.com>
* DeM Labs Ltd. https://demlabs.net
* CellFrame https://cellframe.net
* Copyright (c) 2017-2020
* All rights reserved.
This file is part of DAP (Distributed Applications Platform) the open source project
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.
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_strfuncs.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <getopt.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#include <io.h>
#include <pthread.h>
#include "userenv.h"
#endif
#define LOG_TAG "main"
#ifndef _WIN32
#include "sig_unix_handler.h"
#else
#include "sig_win32_handler.h"
#include "registry.h"
void S_SetExceptionFilter( void );
#endif
#include "dap_common.h"
#include "dap_config.h"
#include "dap_server.h"
#include "dap_notify_srv.h"
#include "dap_http_server.h"
#include "dap_http_folder.h"
#include "dap_chain_node_dns_client.h"
#include "dap_chain_node_dns_server.h"
#include "dap_chain_net_balancer.h"
#include "dap_chain_net_node_list.h"
#ifdef DAP_MODULES_DYNAMIC
#include "dap_modules_dynamic_cdb.h"
#endif
#include "dap_events.h"
#include "dap_enc.h"
#include "dap_enc_ks.h"
#include "dap_enc_http.h"
#include "dap_chain.h"
#include "dap_chain_wallet.h"
#include "dap_chain_cs_blocks.h"
#include "dap_chain_cs_dag.h"
#include "dap_chain_cs_dag_poa.h"
#include "dap_chain_cs_none.h"
#include "dap_chain_cs_esbocs.h"
//#include "dap_chain_bridge.h"
//#include "dap_chain_bridge_btc.h"
#include "dap_chain_net.h"
#include "dap_chain_net_srv.h"
#include "dap_chain_net_srv_geoip.h"
#if defined(DAP_OS_DARWIN) || ( defined(DAP_OS_LINUX) && ! defined (DAP_OS_ANDROID))
#include "dap_chain_net_srv_vpn.h"
#include "dap_chain_net_vpn_client.h"
#endif
#include "dap_global_db.h"
#include "dap_chain_mempool.h"
#include "dap_chain_node.h"
#include "dap_chain_node_cli.h"
#include "dap_json_rpc.h"
#include "dap_stream.h"
#include "dap_stream_ctl.h"
#include "dap_chain_net_srv_order.h"
#include "dap_chain_net_srv_xchange.h"
#include "dap_chain_net_srv_voting.h"
#include "dap_chain_net_srv_bridge.h"
#include "dap_chain_net_srv_stake_pos_delegate.h"
#include "dap_chain_net_srv_stake_lock.h"
#include "dap_chain_net_srv_emit_delegate.h"
#include "dap_chain_wallet_cache.h"
#include "dap_chain_policy.h"
#include "dap_events_socket.h"
#include "dap_client.h"
#include "dap_http_simple.h"
#include "dap_process_manager.h"
#include "dap_file_utils.h"
#include "dap_plugin.h"
#ifdef DAP_SUPPORT_PYTHON_PLUGINS
#include "dap_chain_plugins.h"
#include "dap_plugins_python_app_context.h"
#endif
#define MEMPOOL_URL "/mempool"
#define MAIN_URL "/"
const char *dap_node_version();
static int s_proc_running_check(const char *a_path);
#ifdef DAP_OS_ANDROID
#include "dap_app_cli.h"
#include <android/log.h>
#include <jni.h>
#endif
#ifndef BUILD_HASH
#define BUILD_HASH "0000000" // 0000000 means uninitialized
#endif
#ifndef BUILD_TS
#define BUILD_TS "undefined"
#endif
#define NODE_NAME "cellframe-node"
const char *dap_node_version() {
return "CellframeNode, " DAP_VERSION ", " BUILD_TS ", " BUILD_HASH;
}
void set_global_sys_dir(const char *dir)
{
g_sys_dir_path = dap_strdup(dir);
}
int main( int argc, const char **argv )
{
if ( argv[1] && !dap_strcmp("-version", argv[1]) )
return printf("%s\n", dap_node_version()), 0;
dap_server_t *l_server = NULL; // DAP Server instance
bool l_debug_mode = true;
bool bServerEnabled = false;
int rc = 0;
dap_set_appname(NODE_NAME);
#if defined(_WIN32) && defined(NDEBUG)
S_SetExceptionFilter( );
#endif
// get relative path to config
#if !DAP_OS_ANDROID
if (argc > 2 && !dap_strcmp("-B" , argv[1]))
g_sys_dir_path = dap_strdup(argv[2]);
#endif
if (!g_sys_dir_path) {
#ifdef DAP_OS_WINDOWS
g_sys_dir_path = dap_strdup_printf("%s/%s", regGetUsrPath(), dap_get_appname());
#elif DAP_OS_MAC
g_sys_dir_path = dap_strdup_printf("/Library/Application Support/CellframeNode/");
#elif DAP_OS_UNIX
g_sys_dir_path = dap_strdup_printf("/opt/%s", dap_get_appname());
#endif
}
if ( !dap_dir_test(g_sys_dir_path) ) {
printf("Invalid path \"%s\"", g_sys_dir_path);
rc = -1;
} else {
char l_path[MAX_PATH + 1];
int pos = snprintf(l_path, sizeof(l_path), "%s/var/log", g_sys_dir_path);
if ( dap_mkdir_with_parents(l_path) ) {
printf("Can't create directory %s, error %d", l_path, errno);
rc = -2;
} else {
snprintf(l_path + pos, sizeof(l_path) - pos, "/%s.log", dap_get_appname());
if ( dap_common_init(dap_get_appname(), l_path) ) {
printf("Fatal Error: Can't init common functions module");
rc = -3;
} else {
#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
#ifdef DAP_OS_ANDROID
dap_log_set_external_output(LOGGER_OUTPUT_ALOG, "NativeCellframeNode");
#endif
log_it(L_DEBUG, "Use main path: %s", g_sys_dir_path);
snprintf(l_path, sizeof(l_path), "%s/etc", g_sys_dir_path);
if ( dap_config_init(l_path) ) {
log_it( L_CRITICAL,"Can't init general config \"%s/%s.cfg\"\n", l_path, NODE_NAME );
rc = -4;
}
}
}
}
if ( rc )
return DAP_DELETE(g_sys_dir_path), rc;
if (!( g_config = dap_config_open(dap_get_appname()) ))
return log_it( L_CRITICAL,"Can't open general config %s.cfg", dap_get_appname() ), DAP_DELETE(g_sys_dir_path), -5;
#ifndef DAP_OS_WINDOWS
char l_default_dir[MAX_PATH + 1];
snprintf(l_default_dir, MAX_PATH + 1, "%s/tmp", g_sys_dir_path);
char *l_pid_file_path = dap_config_get_item_str_path_default(g_config, "resources", "pid_path", l_default_dir);
int l_pid_check = s_proc_running_check(l_pid_file_path);
DAP_DELETE(l_pid_file_path);
if (l_pid_check)
return 2;
#else
if ( s_proc_running_check("DAP_CELLFRAME_NODE_74E9201D33F7F7F684D2FEF1982799A79B6BF94"
"B568446A8D1DE947B00E3C75060F3FD5BF277592D02F77D7E50935E56") )
return DAP_DELETE(g_sys_dir_path), 2;
#endif
log_it(L_DEBUG, "Parsing command line args");
l_debug_mode = dap_config_get_item_bool_default( g_config,"general","debug_mode", false );
if ( l_debug_mode )
log_it( L_ATT, "*** DEBUG MODE ***" );
else
log_it( L_ATT, "*** NORMAL MODE ***" );
dap_log_level_set( l_debug_mode ? L_DEBUG : L_NOTICE );
log_it( L_DAP, "*** CellFrame Node version: %s ***", DAP_VERSION );
if ( dap_config_get_item_bool_default(g_config, "log", "rotate_enabled", false) ) {
size_t l_timeout_minutes = dap_config_get_item_int64(g_config, "log", "rotate_timeout"),
l_max_file_size = dap_config_get_item_int64(g_config, "log", "rotate_size");
log_it(L_NOTICE, "Log rotation every %lu min enabled, max log file size %lu MB",
l_timeout_minutes, l_max_file_size);
dap_common_enable_cleaner_log(l_timeout_minutes * 60000, l_max_file_size);
}
if ( dap_enc_init() != 0 ){
log_it( L_CRITICAL, "Can't init encryption module" );
return -56;
}
// change to dap_config_get_item_int_default when it's will be possible
uint32_t l_thread_cnt = dap_config_get_item_int32_default(g_config, "resources", "threads_cnt", 0);
// New event loop init
dap_events_init(l_thread_cnt, 0);
dap_events_start();
bServerEnabled = dap_config_get_item_bool_default( g_config, "server", "enabled", false );
if ( bServerEnabled && dap_server_init() != 0 ) {
log_it( L_CRITICAL, "Can't init socket server module" );
return -4;
}
if ( dap_http_init() != 0 ) {
log_it( L_CRITICAL, "Can't init http server module" );
return -5;
}
#if !DAP_OS_ANDROID
if ( dap_http_folder_init() != 0 ){
log_it( L_CRITICAL, "Can't init http server module" );
return -55;
}
#endif
if ( dap_http_simple_module_init() != 0 ) {
log_it(L_CRITICAL,"Can't init http simple module");
return -9;
}
if ( enc_http_init() != 0 ) {
log_it( L_CRITICAL, "Can't init encryption http session storage module" );
return -81;
}
if ( dap_stream_init(g_config) != 0 ) {
log_it( L_CRITICAL, "Can't init stream server module" );
return -82;
}
if ( dap_stream_ctl_init() != 0 ){
log_it( L_CRITICAL, "Can't init stream control module" );
return -83;
}
dap_client_init();
// Create and init notify server
if ( dap_notify_server_init() != 0 ){
log_it( L_ERROR, "Can't init notify server module" );
}
if ( dap_global_db_init() != 0 ) {
log_it( L_CRITICAL, "Can't init global db module" );
return -58;
}
if ( dap_datum_mempool_init() ) {
log_it( L_CRITICAL, "Can't init mempool module" );
return -59;
}
if( dap_chain_init() ) {
log_it(L_CRITICAL,"Can't init dap chain modules");
return -60;
}
if (dap_chain_net_srv_stake_pos_delegate_init()) {
log_it(L_ERROR, "Can't start delegated PoS stake service");
}
if( dap_chain_cs_dag_init() ) {
log_it(L_CRITICAL,"Can't init dap chain dag consensus module");
return -62;
}
if( dap_chain_cs_dag_poa_init() ) {
log_it(L_CRITICAL,"Can't init dap chain dag consensus PoA module");
return -63;
}
if( dap_chain_cs_blocks_init() ) {
log_it(L_CRITICAL,"Can't init dap chain blocks consensus module");
return -62;
}
if( dap_chain_cs_esbocs_init() ){
log_it(L_CRITICAL,"Can't init enhanced stake-based blocks operating consensus module");
return -69;
}
if( dap_nonconsensus_init() ) {
log_it(L_CRITICAL, "Can't init nonconsensus chain module");
return -71;
}
if( dap_chain_net_init() ){
log_it(L_CRITICAL,"Can't init dap chain network module");
return -65;
}
if( dap_chain_policy_init() ){
log_it(L_CRITICAL,"Can't init dap chain policy module");
return -66;
}
if( dap_chain_wallet_init() ) {
log_it(L_CRITICAL,"Can't init dap chain wallet module");
return -61;
}
if( dap_chain_net_srv_init() ){
log_it(L_CRITICAL,"Can't init dap chain network service module");
return -66;
}
if( dap_chain_net_srv_order_init() )
return -67;
if (dap_chain_net_srv_xchange_init()) {
log_it(L_ERROR, "Can't provide exchange capability");
}
if (dap_chain_net_srv_voting_init()) {
log_it(L_ERROR, "Can't provide voting capability");
}
if (dap_chain_net_srv_bridge_init()) {
log_it(L_ERROR, "Can't provide bridge capability");
}
if (dap_chain_net_srv_stake_lock_init()) {
log_it(L_ERROR, "Can't start stake lock service");
}
if (dap_chain_net_srv_emit_delegate_init()) {
log_it(L_ERROR, "Can't start stake lock service");
}
#ifndef _WIN32
# if !DAP_OS_ANDROID
if( dap_chain_net_srv_vpn_pre_init() ){
log_it(L_ERROR, "Can't pre-init vpn service");
}
# endif
if (sig_unix_handler_init(dap_config_get_item_str_default(g_config,
"resources",
"pid_path",
"/tmp")) != 0) {
log_it(L_CRITICAL,"Can't init sig unix handler module");
return -12;
}
#else
if ( sig_win32_handler_init( NULL ) ) {
log_it( L_CRITICAL,"Can't init sig win32 handler module" );
return -12;
}
#endif
if ( dap_chain_node_cli_init(g_config) ) {
log_it( L_CRITICAL, "Can't init server for console" );
return -11;
}
if( dap_chain_wallet_cache_init() ) {
log_it(L_CRITICAL,"Can't init dap chain wallet module");
return -61;
}
dap_chain_net_load_all();
log_it(L_INFO, "Automatic mempool processing %s",
dap_chain_node_mempool_autoproc_init() ? "enabled" : "disabled");
uint16_t l_listen_addrs_count = 0;
if ( bServerEnabled )
l_server = dap_http_server_new("server", dap_get_appname());
if ( l_server ) { // If listener server is initialized
// Handshake URL
enc_http_add_proc( DAP_HTTP_SERVER(l_server), "/"DAP_UPLINK_PATH_ENC_INIT );
// Streaming URLs
dap_stream_add_proc_http( DAP_HTTP_SERVER(l_server), "/"DAP_UPLINK_PATH_STREAM );
dap_stream_ctl_add_proc( DAP_HTTP_SERVER(l_server), "/"DAP_UPLINK_PATH_STREAM_CTL );
const char *str_start_mempool = dap_config_get_item_str( g_config, "mempool", "accept" );
if ( str_start_mempool && !strcmp(str_start_mempool, "true")) {
dap_chain_mempool_add_proc(DAP_HTTP_SERVER(l_server), MEMPOOL_URL);
}
if (dap_json_rpc_init(l_server, g_config)) {
log_it( L_CRITICAL, "Can't init json-rpc" );
return -12;
}
// Built in WWW server
#if !DAP_OS_ANDROID
if ( dap_config_get_item_bool_default(g_config,"www","enabled",false) ){
dap_http_folder_add( DAP_HTTP_SERVER(l_server), "/",
dap_config_get_item_str(g_config,
"resources",
"www_root") );
}
#endif
dap_server_set_default(l_server);
dap_http_simple_proc_add(DAP_HTTP_SERVER(l_server), "/"DAP_UPLINK_PATH_NODE_LIST, 2048, dap_chain_net_node_check_http_issue_link);
if ( dap_config_get_item_bool_default(g_config, "bootstrap_balancer", "http_server", false) ) {
log_it(L_DEBUG, "HTTP balancer enabled");
dap_http_simple_proc_add(DAP_HTTP_SERVER(l_server), "/"DAP_UPLINK_PATH_BALANCER,
DAP_BALANCER_MAX_REPLY_SIZE, dap_chain_net_balancer_http_issue_link);
}
if ( dap_config_get_item_bool_default(g_config, "bootstrap_balancer", "dns_server", false) ) {
log_it(L_DEBUG, "DNS balancer enabled");
dap_dns_server_start("bootstrap_balancer");
}
} else
log_it( L_INFO, "No enabled server, working in client mode only" );
#if defined(DAP_OS_DARWIN) || ( defined(DAP_OS_LINUX) && ! defined (DAP_OS_ANDROID))
// vpn server
if(dap_config_get_item_bool_default(g_config, "srv_vpn", "enabled", false)) {
if(dap_chain_net_srv_vpn_init(g_config) != 0) {
log_it(L_ERROR, "Can't init dap chain network service vpn module");
return -70;
}
}
// vpn client
if(dap_chain_net_vpn_client_init(g_config) != 0) {
log_it(L_ERROR, "Can't init dap chain network service vpn client");
return -72;
}
if(dap_config_get_item_bool_default(g_config, "srv_vpn", "geoip_enabled", false)) {
if(chain_net_geoip_init(g_config) != 0) {
log_it(L_CRITICAL, "Can't init geoip module");
return -73;
}
}
#endif
if(dap_config_get_item_bool_default(g_config,"plugins","enabled",false)){
#ifdef DAP_OS_WINDOWS
char * l_plugins_path_default = dap_strdup_printf("%s/var/lib/plugins/", g_sys_dir_path);
#else
char * l_plugins_path_default = dap_strdup_printf("%s/var/lib/plugins", g_sys_dir_path);
#endif
int rc_plugin_init = 0;
rc_plugin_init = dap_plugin_init( dap_config_get_item_str_default(g_config, "plugins", "path", l_plugins_path_default) );
if (rc_plugin_init) {
log_it(L_ERROR, "The initial initialization for working with manifests and binary plugins failed. Error code %d", rc_plugin_init);
DAP_DELETE(l_plugins_path_default);
} else {
DAP_DELETE(l_plugins_path_default);
#ifdef DAP_SUPPORT_PYTHON_PLUGINS
//Init python plugins
log_it(L_NOTICE, "Loading python plugins");
dap_plugins_python_app_content_init(l_server);
rc_plugin_init = dap_chain_plugins_init(g_config);
#endif
dap_plugin_start_all();
#ifdef DAP_SUPPORT_PYTHON_PLUGINS
if (!rc_plugin_init) {
dap_chain_plugins_save_thread(g_config);
} else {
log_it(L_ERROR, "Failed to initialize python-cellframe plugins. Error code %d", rc_plugin_init);
}
#endif
}
}
dap_chain_net_try_online_all();
dap_chain_net_announce_addr_all();
rc = dap_events_wait();
log_it( rc ? L_CRITICAL : L_NOTICE, "Server loop stopped with return code %d", rc );
// Deinit modules
//failure:
if(dap_config_get_item_bool_default(g_config,"plugins","enabled",false)){
dap_plugin_stop_all();
dap_plugin_deinit();
}
dap_dns_server_stop();
dap_stream_deinit();
dap_stream_ctl_deinit();
#if !DAP_OS_ANDROID
dap_http_folder_deinit();
#endif
dap_http_deinit();
if (bServerEnabled) dap_server_deinit();
dap_enc_ks_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_srv_bridge_deinit();
dap_chain_net_srv_voting_deinit();
dap_chain_net_deinit();
dap_global_db_deinit();
dap_chain_deinit();
dap_config_close( g_config );
dap_interval_timer_deinit();
dap_common_deinit();
return rc * 10;
}
static struct option long_options[] = {
{ "stop", 0, NULL, 0 },
{ NULL, 0, NULL, 0 } // must be a last element
};
/*void parse_args( int argc, const char **argv ) {
int opt, option_index = 0, is_daemon = 0;
while ( (opt = getopt_long(argc, (char *const *)argv, "D0",
long_options, &option_index)) != -1) {
switch ( opt ) {
case 0: // --stop
{
#ifndef DAP_OS_WINDOWS
pid_t pid = get_pid_from_file(s_pid_file_path);
if ( pid == 0 ) {
log_it( L_ERROR, "Can't read pid from file" );
exit( -20 );
}
if ( kill_process(pid) ) {
log_it( L_INFO, "Server successfully stopped" );
exit( 0 );
}
log_it( L_WARNING, "Server not stopped. Maybe he is not running now?" );
exit( -21 );
#else
// TODO OpenEvent + SetEvent
exit (-22);
#endif
}
case 'D':
{
log_it( L_INFO, "Daemonize server starting..." );
//exit_if_server_already_running( );
is_daemon = 1;
daemonize_process( );
break;
}
default:
log_it( L_WARNING, "Unknown option from command line" );
}
}
//if( !is_daemon )
// exit_if_server_already_running( );
}*/
int s_proc_running_check(const char *a_path) {
#ifdef DAP_OS_WINDOWS
CreateEvent(0, TRUE, FALSE, a_path);
return GetLastError() == ERROR_ALREADY_EXISTS ? ( log_it(L_ERROR, "dap_server is already running"), 1 ) : 0;
#else
FILE *l_pidfile = fopen(a_path, "r");
if (l_pidfile) {
pid_t f_pid = 0;
if ( fscanf( l_pidfile, "%d", &f_pid ) && lockf(fileno(l_pidfile), F_TEST, 0) == -1 ) {
return log_it(L_ERROR, "Error %d: \"%s\", dap_server is already running with PID %d",
errno, dap_strerror(errno), f_pid), 1;
}
else
l_pidfile = freopen(a_path, "w", l_pidfile);
} else
l_pidfile = fopen(a_path, "w");
if (!l_pidfile)
return log_it(L_ERROR, "Can't open file %s for writing, error %d: %s",
a_path, errno, dap_strerror(errno)), 2;
fprintf(l_pidfile, "%d", getpid());
fflush(l_pidfile);
return lockf(fileno(l_pidfile), F_TLOCK, sizeof(pid_t));
#endif
}
//
// Created by dpuzyrkov on 9/17/24.
//
#ifndef NODE_CELLFRAME_NODE_H
#define NODE_CELLFRAME_NODE_H
extern "C"
{
int main( int argc, const char **argv );
void set_global_sys_dir(const char *dir);
typedef bool (*dap_notify_data_user_callback_t)(const char *data);
void dap_notify_data_set_user_callback(dap_notify_data_user_callback_t callback);
char *dap_cli_exec(int argc, char **argv);
const char *dap_node_version();
};
#endif //NODE_CELLFRAME_NODE_H
#pragma once
#define DAP_APP_NAME NODE_NETNAME "-node"
//#ifdef _WIN32
// #define SYSTEM_PREFIX "%USERPROFILE%/opt/"DAP_APP_NAME
//#else
#define SYSTEM_PREFIX "/opt/"DAP_APP_NAME
// #define SYSTEM_PREFIX "opt/"DAP_APP_NAME
//#endif
#define LOCAL_PREFIX "~/."DAP_APP_NAME
#define SYSTEM_CONFIGS_DIR SYSTEM_PREFIX"/etc"
#define LOCAL_CONFIGS_DIR LOCAL_PREFIX"/etc"
#define SYSTEM_LOGS_DIR SYSTEM_PREFIX"/var/log"
#define SYSTEM_CONFIG_GLOBAL_FILENAME SYSTEM_PREFIX"/etc/"DAP_APP_NAME".cfg"
#define LOCAL_CONFIG_GLOBAL LOCAL_PREFIX"/etc/"DAP_APP_NAME".cfg"
#define SYSTEM_PID_FILE_PATH SYSTEM_PREFIX"/run/"DAP_APP_NAME".pid"
#define LOCAL_PID_FILE_PATH SYSTEM_PREFIX"/run/"DAP_APP_NAME".pid"
...@@ -4,97 +4,24 @@ ...@@ -4,97 +4,24 @@
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
#include <stdbool.h> #include <stdbool.h>
#include <conio.h>
#include "dap_common.h" #include "dap_common.h"
DWORD ExceptionFilter( EXCEPTION_POINTERS *ep ); LONG ExceptionFilter( EXCEPTION_POINTERS *ep );
void S_SetExceptionFilter( void ) void S_SetExceptionFilter( void )
{ {
SetErrorMode( SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX ); SetErrorMode( SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX );
#ifdef WIN64 #ifdef WIN64
AddVectoredExceptionHandler( 1, ExceptionFilter ); AddVectoredExceptionHandler( 1, ExceptionFilter );
#else #else
SetUnhandledExceptionFilter( (LPTOP_LEVEL_EXCEPTION_FILTER) ExceptionFilter ); SetUnhandledExceptionFilter( (LPTOP_LEVEL_EXCEPTION_FILTER) ExceptionFilter );
#endif
return;
}
#if 0
typedef struct _EXCEPTION_RECORD {
DWORD ExceptionCode;
DWORD ExceptionFlags;
struct _EXCEPTION_RECORD *ExceptionRecord;
PVOID ExceptionAddress;
DWORD NumberParameters;
ULONG_PTR ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD;
#endif #endif
}
DWORD ExceptionFilter( EXCEPTION_POINTERS *ep ) LONG ExceptionFilter( EXCEPTION_POINTERS *ep )
{ {
// printf( "\r\nExceptionCode = 0x%0X[%s]\r\n", ep->ExceptionRecord->ExceptionCode, buff ); return Beep( 1000, 200 );
uint8_t buff[128];
if ( ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
memcpy( buff, "EXCEPTION_ACCESS_VIOLATION", 27 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ARRAY_BOUNDS_EXCEEDED)
memcpy( buff, "EXCEPTION_ARRAY_BOUNDS_EXCEEDED", 32 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
memcpy( buff, "EXCEPTION_BREAKPOINT", 21 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_DATATYPE_MISALIGNMENT)
memcpy( buff, "EXCEPTION_DATATYPE_MISALIGNMENT", 32 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_DENORMAL_OPERAND)
memcpy( buff, "EXCEPTION_FLT_DENORMAL_OPERAND", 31 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_DIVIDE_BY_ZERO)
memcpy( buff, "EXCEPTION_FLT_DIVIDE_BY_ZERO", 29 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_INEXACT_RESULT)
memcpy( buff, "EXCEPTION_FLT_INEXACT_RESULT", 29 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_INVALID_OPERATION)
memcpy( buff, "EXCEPTION_FLT_INVALID_OPERATION", 32 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_OVERFLOW)
memcpy( buff, "EXCEPTION_FLT_OVERFLOW", 23 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_STACK_CHECK)
memcpy( buff, "EXCEPTION_FLT_STACK_CHECK", 26 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_FLT_UNDERFLOW)
memcpy( buff, "EXCEPTION_FLT_UNDERFLOW", 24 );
else if (ep->ExceptionRecord->ExceptionCode == STATUS_ILLEGAL_INSTRUCTION)
memcpy( buff, "EXCEPTION_ILLEGAL_INSTRUCTION", 30 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_IN_PAGE_ERROR)
memcpy( buff, "EXCEPTION_IN_PAGE_ERROR", 24 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO)
memcpy( buff, "EXCEPTION_INT_DIVIDE_BY_ZERO", 29 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_INT_OVERFLOW)
memcpy( buff, "EXCEPTION_INT_OVERFLOW", 23 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_INVALID_DISPOSITION)
memcpy( buff, "EXCEPTION_INVALID_DISPOSITION", 30 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_NONCONTINUABLE_EXCEPTION)
memcpy( buff, "EXCEPTION_NONCONTINUABLE_EXCEPTION", 35 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_PRIV_INSTRUCTION)
memcpy( buff, "EXCEPTION_PRIV_INSTRUCTION", 27 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP)
memcpy( buff, "EXCEPTION_SINGLE_STEP", 22 );
else if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)
memcpy( buff, "EXCEPTION_STACK_OVERFLOW", 25 );
else
memcpy( buff, "EXCEPTION_UNKNOWN", 18 );
HANDLE hConOut = GetStdHandle( STD_OUTPUT_HANDLE );
SetConsoleTextAttribute( hConOut, 12 );
printf( "\r\nExceptionCode = 0x%0X[%s]\r\n", ep->ExceptionRecord->ExceptionCode, buff );
SetConsoleTextAttribute( hConOut, 7 );
dap_common_deinit( ); // close log file
Beep( 1000, 200 );
Sleep( 1000 );
getch( );
ExitProcess( -1 );
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/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <getopt.h>
#include <signal.h>
#ifdef _WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <windows.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#include <io.h>
//#include "wrappers.h"
#include <wepoll.h>
#include <pthread.h>
#include "Userenv.h"
#endif
#define LOG_TAG "main"
#ifndef _WIN32
#include "sig_unix_handler.h"
#else
#include "sig_win32_handler.h"
void S_SetExceptionFilter( void );
#endif
#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_chain_wallet.h"
#include "dap_chain_cs_dag.h"
#include "dap_chain_cs_dag_poa.h"
#include "dap_chain_cs_dag_pos.h"
#include "dap_chain_gdb.h"
#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"
#include "dap_chain_global_db.h"
#include "dap_chain_mempool.h"
#include "dap_chain_node_cli.h"
#include "dap_stream_session.h"
#include "dap_stream.h"
#include "dap_stream_ctl.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"
#include "dap_common.h"
#include "dap_client_remote.h"
#include "dap_client.h"
#include "dap_http_client.h"
#include "dap_http_client_simple.h"
#include "dap_http_simple.h"
#include "dap_process_manager.h"
#include "dap_traffic_track.h"
#include "dap_defines.h"
#define ENC_HTTP_URL "/enc_init"
#define STREAM_CTL_URL "/stream_ctl"
#define STREAM_URL "/stream"
#define SLIST_URL "/nodelist"
#define MEMPOOL_URL "/mempool"
#define MAIN_URL "/"
void parse_args( int argc, const char **argv );
void exit_if_server_already_running( void );
char *win_prefix = NULL, *l_pid_file_path = NULL;
uint32_t win_prefix_size = 0;
int main( int argc, const char **argv )
{
dap_server_t *l_server = NULL; // DAP Server instance
bool bDebugMode = true;
bool bServerEnabled = true;
int rc = 0;
#if defined(_WIN32) && defined(NDEBUG)
S_SetExceptionFilter( );
#endif
char *l_log_file_path,
*l_sys_dir_path;
char *l_path_buff = (char *)DAP_MALLOC( 2048 * 4 );
if ( !l_path_buff )
goto failure;
win_prefix = l_path_buff;
l_log_file_path = l_path_buff + 2048;
l_sys_dir_path = l_path_buff + 2048 * 2;
l_pid_file_path = l_path_buff + 2048 * 3;
uint32_t path_len = 0;
#ifdef _WIN32
{
HKEY hKey;
win_prefix_size = 2048;
LSTATUS lRes = RegOpenKeyExA( HKEY_CURRENT_USER,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
0, KEY_READ, &hKey );
lRes = RegQueryValueExA( hKey, "Personal", 0, NULL, (LPBYTE)&win_prefix[0], (DWORD*)&win_prefix_size );
RegCloseKey( hKey );
if ( lRes != ERROR_SUCCESS ) {
memcpy( &win_prefix[0], "c:", 3 );
win_prefix_size = 3;
}
path_len = dap_sprintf( l_log_file_path, "%s/%s", win_prefix, DAP_APP_NAME );
memcpy( l_pid_file_path, l_log_file_path, path_len + 1 );
memcpy( l_sys_dir_path, l_log_file_path, path_len + 1 );
path_len = dap_sprintf( l_pid_file_path, "%s/%s", win_prefix, DAP_APP_NAME );
memcpy( l_sys_dir_path, l_pid_file_path, path_len + 1 );
}
#endif
dap_sprintf( l_pid_file_path + win_prefix_size - 1, "/%s%s", DAP_APP_NAME, SYSTEM_PID_FILE_PATH );
memcpy( l_log_file_path + path_len, SYSTEM_LOGS_DIR, sizeof(SYSTEM_LOGS_DIR) );
dap_mkdir_with_parents( l_log_file_path );
#if !DAP_RELEASE
dap_sprintf( l_log_file_path, "/%s_logs.txt", DAP_APP_NAME );
#else
dap_sprintf( l_log_file_path + path_len + sizeof(SYSTEM_LOGS_DIR) - 1, "/%s_logs.txt", DAP_APP_NAME );
#endif
if ( dap_common_init( DAP_APP_NAME, l_log_file_path ) != 0 ) {
printf( "Fatal Error: Can't init common functions module" );
return -2;
}
memcpy( l_sys_dir_path + path_len, SYSTEM_CONFIGS_DIR, sizeof(SYSTEM_CONFIGS_DIR) );
dap_config_init( l_sys_dir_path );
if ( (g_config = dap_config_open(DAP_APP_NAME)) == NULL ) {
log_it( L_CRITICAL,"Can't init general configurations" );
printf("log_it\n");
return -1;
}
parse_args( argc, argv );
#ifdef _WIN32
CreateMutexW( NULL, FALSE, (WCHAR *) L"DAP_KELVIN_NODE_74E9201D33F7F7F684D2FEF1982799A79B6BF94B568446A8D1DE947B00E3C75060F3FD5BF277592D02F77D7E50935E56" );
#endif
// bDebugMode = dap_config_get_item_bool_default( g_config,"general","debug_mode", false );
bDebugMode = true;//dap_config_get_item_bool_default( g_config,"general","debug_mode", false );
if ( bDebugMode )
log_it( L_ATT, "*** DEBUG MODE ***" );
else
log_it( L_ATT, "*** NORMAL MODE ***" );
dap_log_level_set( bDebugMode ? L_DEBUG: L_NOTICE );
log_it( L_DAP, "*** Kelvin Node version: %s ***", "0.0.0" ); //DAP_SERVER_VERSION_STR );
// change to dap_config_get_item_int_default when it's will be possible
size_t l_thread_cnt = 0;
const char *s_thrd_cnt = dap_config_get_item_str( g_config, "resources", "threads_cnt" );
if ( s_thrd_cnt != NULL )
l_thread_cnt = (size_t)atoi( s_thrd_cnt );
if ( !l_thread_cnt ) {
#ifndef _WIN32
l_thread_cnt = (size_t)sysconf(_SC_NPROCESSORS_ONLN);
#else
SYSTEM_INFO si;
GetSystemInfo( &si );
l_thread_cnt = si.dwNumberOfProcessors;
#endif
}
if ( dap_server_init(l_thread_cnt) != 0 ) {
log_it( L_CRITICAL, "Can't init socket server module" );
return -4;
}
if ( dap_http_init() != 0 ) {
log_it( L_CRITICAL, "Can't init http server module" );
return -5;
}
if ( dap_http_folder_init() != 0 ){
log_it( L_CRITICAL, "Can't init http server module" );
return -55;
}
if ( dap_enc_init() != 0 ){
log_it( L_CRITICAL, "Can't init encryption module" );
return -56;
}
if ( dap_enc_ks_init( false, 60 *60 * 2 ) != 0 ) {
log_it( L_CRITICAL, "Can't init encryption key storage module" );
return -57;
}
if ( dap_chain_global_db_init(g_config) ) {
log_it( L_CRITICAL, "Can't init global db module" );
return -58;
}
dap_client_init();
dap_http_client_simple_init( );
if ( dap_datum_mempool_init() ) {
log_it( L_CRITICAL, "Can't init mempool module" );
return -59;
}
if( dap_chain_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain modules");
return -60;
}
if( dap_chain_wallet_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain wallet module");
return -61;
}
if( dap_chain_cs_dag_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain dag consensus module");
return -62;
}
if( dap_chain_cs_dag_poa_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain dag consensus PoA module");
return -63;
}
if( dap_chain_cs_dag_pos_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain dag consensus PoA module");
return -64;
}
if(dap_chain_gdb_init() != 0) {
log_it(L_CRITICAL, "Can't init dap chain gdb module");
return -71;
}
if( dap_chain_net_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain network module");
return -65;
}
if( dap_chain_net_srv_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain network service module");
return -66;
}
#if 0
if( dap_chain_net_srv_app_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain network service applications module");
return -67;
}
if( dap_chain_net_srv_datum_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain network service datum module");
return -68;
}
if( dap_chain_net_srv_datum_pool_init() !=0){
log_it(L_CRITICAL,"Can't init dap chain network service datum pool module");
return -69;
}
if( dap_chain_net_srv_vpn_init(g_config) !=0){
log_it(L_ERROR,"Can't init dap chain network service vpn module");
//return -70;
}
#endif
if ( enc_http_init() != 0 ) {
log_it( L_CRITICAL, "Can't init encryption http session storage module" );
return -81;
}
if ( dap_stream_init(dap_config_get_item_bool_default(g_config,"general","debug_dump_stream_headers",false)) != 0 ) {
log_it( L_CRITICAL, "Can't init stream server module" );
return -82;
}
if ( dap_stream_ctl_init(DAP_ENC_KEY_TYPE_OAES, 32) != 0 ){
log_it( L_CRITICAL, "Can't init stream control module" );
return -83;
}
if ( dap_http_simple_module_init() != 0 ) {
log_it(L_CRITICAL,"Can't init http simple module");
return -9;
}
if ( dap_chain_node_cli_init(g_config) ) {
log_it( L_CRITICAL, "Can't init server for console" );
return -11;
}
#ifndef _WIN32
if (sig_unix_handler_init(dap_config_get_item_str_default(g_config,
"resources",
"pid_path",
SYSTEM_PID_FILE_PATH)) != 0) {
log_it(L_CRITICAL,"Can't init sig unix handler module");
return -12;
}
#else
if ( sig_win32_handler_init( NULL ) ) {
log_it( L_CRITICAL,"Can't init sig win32 handler module" );
return -12;
}
#endif
save_process_pid_in_file(dap_config_get_item_str_default( g_config,
"resources",
"pid_path",
l_pid_file_path));
bServerEnabled = dap_config_get_item_bool_default( g_config, "server", "enabled", false );
log_it ( L_DEBUG,"config server->enabled = \"%u\" ", bServerEnabled );
if ( bServerEnabled ) {
int32_t l_port = dap_config_get_item_int32_default(g_config, "server", "listen_port_tcp", 8079 ); // TODO Default listen port
if( l_port > 0 ) {
l_server = dap_server_listen( (dap_config_get_item_str_default(g_config,
"server",
"listen_address",
"0.0.0.0")),
l_port,
DAP_SERVER_TCP );
} else
log_it( L_WARNING, "Server is enabled but no port is defined" );
}
if ( l_server ) { // If listener server is initialized
//bool is_traffick_track_enable = dap_config_get_item_bool_default(g_config, "traffic_track", "enable", false);
#if 0
if ( is_traffick_track_enable ) {
time_t timeout = // TODO add default timeout (get_item_int32_default)
dap_config_get_item_int32(g_config, "traffic_track", "callback_timeout");
dap_traffic_track_init( l_server, timeout );
dap_traffic_callback_set( dap_chain_net_srv_traffic_callback );
//dap_traffic_callback_set(db_auth_traffic_track_callback);
}
#endif
// TCP-specific things
if ( dap_config_get_item_int32_default(g_config, "server", "listen_port_tcp",-1) > 0) {
// Init HTTP-specific values
dap_http_new( l_server, DAP_APP_NAME );
// Handshake URL
enc_http_add_proc( DAP_HTTP(l_server), ENC_HTTP_URL );
// Streaming URLs
dap_stream_add_proc_http( DAP_HTTP(l_server), STREAM_URL );
dap_stream_ctl_add_proc( DAP_HTTP(l_server), STREAM_CTL_URL );
const char *str_start_mempool = dap_config_get_item_str( g_config, "mempool", "accept" );
if ( str_start_mempool && !strcmp(str_start_mempool, "true")) {
dap_chain_mempool_add_proc(DAP_HTTP(l_server), MEMPOOL_URL);
}
// Built in WWW server
if ( dap_config_get_item_bool_default(g_config,"www","enabled",false) ){
dap_http_folder_add( DAP_HTTP(l_server), "/",
dap_config_get_item_str(g_config,
"resources",
"www_root") );
}
}
} else
log_it( L_INFO, "No enabled server, working in client mode only" );
// VPN channel
/// if (dap_config_get_item_bool_default(g_config,"vpn","enabled",false)){
/// dap_stream_ch_vpn_init(dap_config_get_item_str_default(g_config, "vpn", "network_address", NULL),
/// dap_config_get_item_str_default(g_config, "vpn", "network_mask", NULL));
///
/// }
// Chain Network init
dap_stream_ch_chain_init( );
dap_stream_ch_chain_net_init( );
/// dap_stream_ch_chain_net_srv_init();
// New event loop init
dap_events_init( 0, 0 );
dap_events_t *l_events = dap_events_new( );
dap_events_start( l_events );
/// if (dap_config_get_item_bool_default(g_config,"vpn","enabled",false))
/// dap_stream_ch_vpn_deinit();
// Load all chain networks
dap_chain_net_load_all();
// Endless loop for server's requests processing
rc = dap_server_loop(l_server);
// After loop exit actions
log_it( rc ? L_CRITICAL : L_NOTICE, "Server loop stopped with return code %d", rc );
// Deinit modules
failure:;
dap_stream_deinit();
dap_stream_ctl_deinit();
dap_http_folder_deinit();
dap_http_deinit();
dap_server_deinit();
dap_enc_ks_deinit();
dap_config_close( g_config );
dap_common_deinit();
if ( l_path_buff )
DAP_FREE( l_path_buff );
return rc * 10;
}
static struct option long_options[] = {
{ "stop", 0, NULL, 0 },
{ NULL, 0, NULL, 0 } // must be a last element
};
void parse_args( int argc, const char **argv ) {
int opt, option_index = 0, is_daemon = 0;
while ( (opt = getopt_long(argc, (char *const *)argv, "D0",
long_options, &option_index)) != -1) {
switch ( opt ) {
case 0: // --stop
{
pid_t pid = get_pid_from_file( dap_config_get_item_str_default( g_config, "resources", "pid_path", l_pid_file_path) );
if ( pid == 0 ) {
log_it( L_ERROR, "Can't read pid from file" );
exit( -20 );
}
if ( kill_process(pid) ) {
log_it( L_INFO, "Server successfully stopped" );
exit( 0 );
}
log_it( L_WARNING, "Server not stopped. Maybe he is not running now?" );
exit( -21 );
}
case 'D':
{
log_it( L_INFO, "Daemonize server starting..." );
exit_if_server_already_running( );
is_daemon = 1;
daemonize_process( );
break;
}
default:
log_it( L_WARNING, "Unknown option from command line" );
}
}
if( !is_daemon )
exit_if_server_already_running( );
}
void exit_if_server_already_running( void ) {
pid_t pid = get_pid_from_file( dap_config_get_item_str_default( g_config, "resources", "pid_path", l_pid_file_path) );
bool mf = false;
#ifdef _WIN32
CreateMutexW( NULL, FALSE, (WCHAR *) L"DAP_KELVIN_NODE_74E9201D33F7F7F684D2FEF1982799A79B6BF94B568446A8D1DE947B00E3C75060F3FD5BF277592D02F77D7E50935E56" );
if ( GetLastError( ) == 183 ) {
mf = true;
}
#endif
if ( (pid != 0 && is_process_running(pid)) || mf ) {
log_it( L_WARNING, "Proccess %d is running, don't allow "
"to run more than one copy of DapServer, exiting...", pid );
exit( -2 );
}
}
...@@ -6,9 +6,9 @@ ...@@ -6,9 +6,9 @@
* Copyright (c) 2017-2019 * Copyright (c) 2017-2019
* All rights reserved. * 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 it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
...@@ -27,236 +27,75 @@ ...@@ -27,236 +27,75 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
//#include "dap_client.h"
#include "dap_common.h"
#include "dap_chain_node_cli.h" #include "dap_chain_node_cli.h"
#include "main_node_cli.h" #include "dap_common.h"
#include "main_node_cli_net.h" #include "dap_file_utils.h"
#include "main_node_cli_shell.h" #include "dap_strfuncs.h"
#include "dap_app_cli.h"
#include "dap_defines.h" #include "dap_app_cli_net.h"
#include "dap_app_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. */ #ifdef DAP_OS_WINDOWS
int done = 0; #include "registry.h"
// Loop reading and executing lines until the user quits. #elif defined DAP_OS_ANDROID
for(; done == 0;) {
// Read a line of input
line = rl_readline("> ");
if(!line) #include <android/log.h>
break; #include <jni.h>
#endif
/* Remove leading and trailing whitespace from the line. #define NODE_NAME "cellframe-node"
Then, if there is anything left, add it to the history list
and execute it. */
s = rl_stripwhite(line);
if(*s) static dap_app_cli_connect_param_t *cparam;
{ static const char *listen_socket = NULL;
add_history(s);
execute_line(s);
}
DAP_DELETE(line); #if !DAP_OS_ANDROID
} int main(int argc, const char *argv[])
exit(0);
}
int main(int argc, const char * argv[])
{ {
char l_sys_dir_path[ 2048 ], win_prefix[ 2048 ]; dap_set_appname(NODE_NAME "-cli");
uint32_t path_len = 0; // get relative path to config
uint32_t win_prefix_size; if (argc > 2 && !dap_strcmp("-B" , argv[1])) {
g_sys_dir_path = dap_strdup(argv[2]);
#ifdef _WIN32 if (! dap_dir_test(g_sys_dir_path) )
{ return printf("Invalid path \"%s\"", g_sys_dir_path), DAP_DELETE(g_sys_dir_path), -1;
HKEY hKey; argc -= 2;
win_prefix_size = 2048; argv += 2;
} else {
LSTATUS lRes = RegOpenKeyExA( HKEY_CURRENT_USER, g_sys_dir_path =
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", #ifdef DAP_OS_WINDOWS
0, KEY_READ, &hKey ); dap_strdup_printf("%s/%s", regGetUsrPath(), NODE_NAME);
#elif defined DAP_OS_MAC
lRes = RegQueryValueExA( hKey, "Personal", 0, NULL, (LPBYTE)&win_prefix[0], (DWORD*)&win_prefix_size ); dap_strdup_printf("/Library/Application Support/CellframeNode/");
RegCloseKey( hKey ); #elif defined DAP_OS_UNIX
dap_strdup_printf("/opt/%s", NODE_NAME);
if ( lRes != ERROR_SUCCESS ) { #endif
memcpy( &win_prefix[0], "c:", 3 );
win_prefix_size = 3;
}
path_len = dap_sprintf( l_sys_dir_path, "%s/%s", win_prefix, DAP_APP_NAME );
}
#endif
// set_default_locale();
// command_execution_string = shell_script_filename = (char *) NULL;
memcpy( l_sys_dir_path + path_len, SYSTEM_CONFIGS_DIR, sizeof(SYSTEM_CONFIGS_DIR) );
dap_common_init( DAP_APP_NAME "Console interface", NULL );
dap_log_level_set( L_CRITICAL );
dap_config_init( l_sys_dir_path );
if((g_config = dap_config_open(DAP_APP_NAME)) == NULL) {
printf("Can't init general configurations\n");
exit(-1);
} }
#ifdef DAP_OS_WINDOWS
// connect to node SetConsoleCP(1252);
cparam = node_cli_connect(); SetConsoleOutputCP(1252);
if(!cparam) WSADATA wsaData;
{ WSAStartup(MAKEWORD(2,2), &wsaData);
printf("Can't connected to kelvin-node\n"); #endif
exit(-1); dap_log_level_set(L_CRITICAL);
} int res = dap_app_cli_main(NODE_NAME, argc, argv);
switch (res) {
/*{ case DAP_CLI_ERROR_FORMAT:
printf("start node_cli_post_command()\n"); printf("Response format error!\n");
cmd_state *cmd = DAP_NEW_Z(cmd_state); break;
cmd->cmd_name = "cmd1"; case DAP_CLI_ERROR_SOCKET:
cmd->cmd_param_count = 2; printf("Socket read error!\n");
cmd->cmd_param = DAP_NEW_Z_SIZE(char*, cmd->cmd_param_count * sizeof(char*)); break;
cmd->cmd_param[0] = strdup("t2-t1"); case DAP_CLI_ERROR_TIMEOUT:
cmd->cmd_param[1] = strdup("-opt"); printf("No response recieved\n");
int a = node_cli_post_command(cparam, cmd); break;
printf("node_cli_post_command()=%d\n", a); case DAP_CLI_ERROR_INCOMPLETE:
free_cmd_state(cmd); printf("Connection closed by peer\n");
}*/ default:
break;
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;
} }
DAP_DELETE(g_sys_dir_path);
// command not found, start interactive shell #ifdef DAP_OS_WINDOWS
shell_reader_loop(); WSACleanup();
node_cli_desconnect(cparam); #endif
return 0; 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 <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <assert.h>
#ifdef _WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <windows.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#include <io.h>
//#include "wrappers.h"
#include <wepoll.h>
#include <pthread.h>
#else
#include <sys/socket.h>
#endif
#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 = (uint8_t*) 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();
#ifndef _WIN32
int ret = curl_easy_setopt(curl_handle, CURLOPT_UNIX_SOCKET_PATH, dap_config_get_item_str( g_config, "conserver", "listen_unix_socket_path") ); // unix socket mode
#else
int ret = curl_easy_setopt(curl_handle, CURLOPT_PORT, dap_config_get_item_uint16 ( g_config, "conserver", "listen_tcp_port")); // unix socket mode
#endif
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 <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <assert.h>
#include <setjmp.h>
#include <locale.h>
#ifdef _WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <windows.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#include <io.h>
//#include "wrappers.h"
#include <wepoll.h>
#include <pthread.h>
#else
#include <sys/ttydefaults.h>
#endif
#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 @@ ...@@ -6,9 +6,9 @@
* Copyright (c) 2017-2019 * Copyright (c) 2017-2019
* All rights reserved. * 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 it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
...@@ -28,339 +28,667 @@ ...@@ -28,339 +28,667 @@
#include <getopt.h> #include <getopt.h>
#include <string.h> #include <string.h>
#ifdef _WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <windows.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#include <io.h>
//#include "wrappers.h"
#include <wepoll.h>
#endif
#include <pthread.h>
#include "dap_common.h" #include "dap_common.h"
#include "sig_unix_handler.h"
#include "dap_config.h" #include "dap_config.h"
#include "dap_server.h" #include "dap_cert.h"
#include "dap_http.h" #include "dap_cert_file.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_chain_wallet.h" #include "dap_chain_wallet.h"
#include "dap_file_utils.h"
#include "dap_chain_cert.h" #define LOG_TAG "main_node_tool"
#include "dap_chain_cert_file.h" #define NODE_NAME "cellframe-node"
#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"
#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"
#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"
#include "dap_chain_wallet.h"
#include "dap_client.h" #undef log_it
#include "dap_http_simple.h" #ifdef DAP_OS_WINDOWS
#include "dap_process_manager.h" #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
#define DAP_APP_NAME NODE_NETNAME "-node" static int s_init();
#ifdef _WIN32 static void s_help( );
#define SYSTEM_PREFIX "opt/"DAP_APP_NAME 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 #else
#define SYSTEM_PREFIX "/opt/"DAP_APP_NAME int main(int argc, const char **argv)
#endif #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;
}
#define LOCAL_PREFIX "~/."DAP_APP_NAME 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;
#define SYSTEM_CONFIGS_DIR SYSTEM_PREFIX"/etc" //
#define LOCAL_CONFIGS_DIR LOCAL_PREFIX"/etc" // Check if wallet name has only digits and English letters
//
#define SYSTEM_CA_DIR SYSTEM_PREFIX"/var/lib/ca" size_t is_str = dap_isstralnum(l_wallet_name);
#define LOCAL_CA_DIR LOCAL_PREFIX"/ca"
#define SYSTEM_WALLET_DIR SYSTEM_PREFIX"/var/lib/wallet" if (!is_str)
#define LOCAL_WALLET_DIR LOCAL_PREFIX"/wallet" {
log_it( L_ERROR, "Wallet name must contain digits and alphabet symbols");
exit( -2004 );
}
#define SYSTEM_CONFIG_GLOBAL_FILENAME SYSTEM_PREFIX"/etc/"DAP_APP_NAME".cfg" if ( l_sig_type.type == SIG_TYPE_NULL ) {
#define LOCAL_CONFIG_GLOBAL LOCAL_PREFIX"/etc/"DAP_APP_NAME".cfg" 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 );
}
#define SYSTEM_PID_FILE_PATH SYSTEM_PREFIX"/run/"DAP_APP_NAME".pid" //
#define LOCAL_PID_FILE_PATH SYSTEM_PREFIX"/run/"DAP_APP_NAME".pid" // 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 );
}
#define ENC_HTTP_URL "/enc_init" char *l_file_name = dap_strdup_printf("%s/%s.dwallet", dap_chain_wallet_get_path(g_config), l_wallet_name);
#define STREAM_CTL_URL "/stream_ctl" if (dap_file_test(l_file_name)) {
#define STREAM_URL "/stream" log_it(L_ERROR, "The '%s' wallet already exists.\n", l_wallet_name);
#define SLIST_URL "/nodelist" exit(-2007);
#define MAIN_URL "/" }
#define LOG_TAG "main_node_tool" DAP_DELETE(l_file_name);
static int s_init( int argc, const char * argv[] ); if (l_sig_type.type == SIG_TYPE_MULTI_CHAINED){
static void s_help( ); 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;
}
}
static const char *s_appname = "kelvin-node-tool"; 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 );
}
int main( int argc, const char **argv ) 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] );
uint8_t *buff = (uint8_t *)malloc( 8192 ); dap_chain_wallet_t *l_wallet = NULL;
int ret = s_init( argc, argv );
if ( ret ) { //
log_it( L_ERROR, "Can't init modules" ); // Check if wallet name has only digits and English letters
return ret; //
}
size_t is_str = dap_isstralnum(l_wallet_name);
if (!is_str)
{
log_it( L_ERROR, "Wallet name must contain digits and alphabet symbols");
exit( -2004 );
}
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 );
}
if ( argc < 2 ) { char *l_file_name = dap_strdup_printf("%s/%s.dwallet", dap_chain_wallet_get_path(g_config), l_wallet_name);
log_it( L_INFO, "No params. Nothing to do" ); if (dap_file_test(l_file_name)) {
s_help( ); log_it(L_ERROR, "The '%s' wallet already exists.\n", l_wallet_name);
exit( -1000 ); exit(-2007);
} }
DAP_DELETE(l_file_name);
if ( strcmp ( argv[1], "wallet" ) == 0 ) { // 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);
}
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);
}
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, 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;
}
}
if ( argc < 3 ) { static int s_wallet_create_from(int argc, const char **argv) {
log_it(L_ERROR,"Wrong 'wallet' command params"); 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(); s_help();
exit(-2001); exit(-3001);
} }
if ( strcmp( argv[2],"create") == 0 ) { int l_cert_index = atoi(argv[4]);
// wallet create <network name> <wallet name> <wallet_sign> size_t l_wallet_certs_number = dap_chain_wallet_get_certs_number( l_wallet );
if ( argc < 6 ) { if ( (l_cert_index > 0) && (l_wallet_certs_number > (size_t)l_cert_index) ) {
log_it( L_ERROR, "Wrong 'wallet create' command params" ); FILE *l_data_file = fopen( argv[5],"rb" );
s_help( ); if ( l_data_file ) {
exit( -2003 ); 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;
}
dap_chain_net_id_t l_network_id = dap_chain_net_id_by_name( argv[3] ); static int s_cert_create(int argc, const char **argv) {
if ( !l_network_id.raw ) { if ( argc < 5 ) {
log_it( L_ERROR, "No such network name '%s'", argv[3] ); log_it( L_ERROR, "Wrong 'cert create' command params\n");
s_help() ; s_help();
exit( -2005 ); 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);
}
const char *l_wallet_name = argv[4]; dap_sign_type_t l_sig_type = dap_sign_type_from_str( 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 ) { if (l_sig_type.type == SIG_TYPE_NULL || l_sig_type.type == SIG_TYPE_MULTI_CHAINED) {
log_it( L_ERROR, "Wrong signature '%s'", argv[4] ); log_it(L_ERROR, "Unknown signature type %s specified, recommended signatures:\n%s",
s_help( ); argv[4], dap_cert_get_str_recommended_sign());
exit( -2004 ); 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);
}
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);
//
// 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);
} }
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> dap_enc_key_type_t l_key_type = dap_sign_type_to_key_type(l_sig_type);
if ( argc < 8 ) {
log_it(L_ERROR,"Wrong 'wallet sign_file' command params"); if ( l_key_type != DAP_ENC_KEY_TYPE_INVALID ) {
s_help(); dap_cert_t * l_cert = dap_cert_generate(l_cert_name,l_cert_path,l_key_type ); // key length ignored!
exit(-3000); if (l_cert == NULL){
log_it(L_ERROR, "Can't create \"%s\"",l_cert_path);
} }
dap_chain_wallet_t *l_wallet = dap_chain_wallet_open( argv[3], SYSTEM_WALLET_DIR ); dap_cert_delete(l_cert);
if ( !l_wallet ) { } else {
log_it(L_ERROR,"Can't open wallet \"%s\"",argv[3]); log_it (L_ERROR, "Wrong key create action \"%s\"",argv[4]);
s_help(); s_help();
exit(-3001); DAP_DELETE(l_cert_path);
} exit(-500);
}
int l_cert_index = atoi(argv[4]); log_it(L_NOTICE, "Cert \"%s\" created\n", l_cert_path);
DAP_DELETE(l_cert_path);
return 0;
}
size_t l_wallet_certs_number = dap_chain_wallet_get_certs_number( l_wallet ); static int s_cert_dump(int argc, const char **argv)
if ( (l_cert_index > 0) && (l_wallet_certs_number > (size_t)l_cert_index) ) { {
FILE *l_data_file = fopen( argv[5],"rb" ); if (argc>=4) {
if ( l_data_file ) {} 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 { else {
log_it( L_ERROR, "Cert index %d can't be found in wallet with %u certs inside" log_it( L_ERROR, "Can't open '%s' cert\n", l_cert_name);
,l_cert_index,l_wallet_certs_number ); exit(-702);
s_help();
exit( -3002 );
} }
} else {
log_it( L_ERROR, "Wrong 'cert dump' command params\n");
} }
/* if ( strcmp( argv[2],"create_from") == 0 ){ return 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; static int s_cert_create_pkey(int argc, const char **argv) {
size_t l_wallet_cert_size = 0; if (argc < 5) {
l_wallet_cert_size = (argc - 3 ) log_it( L_ERROR, "Wrong 'cert create_pkey' command params\n");
l_wallet_cert = DAP_NEW_Z_SIZE (dap_chain_cert_t*, l_wallet_cert_size ); exit(-7023);
}else { }
log_it(L_ERROR,"Wrong 'wallet create_from' command params"); const char *l_cert_name = argv[3];
s_help(); const char *l_cert_pkey_path = argv[4];
exit(-2002); 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);
if ( l_wallet_cert ){ exit(-7021);
if (l_wallet_cert_size > 0) }
for (size_t i = 0; i < l_wallet_cert_size; i++) l_cert->enc_key->pub_key_data_size = dap_enc_ser_pub_key_size(l_cert->enc_key);
dap_chain_cert_delete( l_wallet_cert[i]->); 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 );
} // wallet if (l_pkey) {
else if (strcmp (argv[1],"cert") == 0 ) { if (dap_file_test(l_cert_pkey_path)){
if ( argc >=3 ) { log_it(L_ERROR, "The file \"%s\" exists.\n", l_cert_pkey_path);
if ( strcmp( argv[2],"dump") == 0 ){ exit(-7023);
if (argc>=4) { }
const char * l_cert_name = argv[3]; FILE *l_file = fopen(l_cert_pkey_path,"wb");
dap_chain_cert_t * l_cert = dap_chain_cert_add_file(l_cert_name,SYSTEM_CA_DIR); if (l_file) {
if ( l_cert ) { fwrite(l_pkey,1,l_pkey->header.size + sizeof(l_pkey->header),l_file);
dap_chain_cert_dump(l_cert); fclose(l_file);
dap_chain_cert_delete_by_name(l_cert_name); }
ret = 0; } else {
} log_it(L_ERROR, "Can't produce pkey from the certificate\n");
else { exit(-7022);
exit(-702);
} }
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;
} }
} else if ( strcmp( argv[2],"create_pkey") == 0 ){ l_cert_new->enc_key->priv_key_data_size = l_cert->enc_key->priv_key_data_size;
if (argc < 5) exit(-7023); }
const char *l_cert_name = argv[3]; int ret = dap_cert_save_to_folder(l_cert_new, s_system_ca_dir);
const char *l_cert_pkey_path = argv[4]; if (!ret && a_pvt_key_copy) // Remove original cert after renaming
dap_chain_cert_t *l_cert = dap_chain_cert_add_file(l_cert_name,SYSTEM_CA_DIR); ret = dap_cert_delete_file(l_cert_name, s_system_ca_dir);
if ( !l_cert ) exit( -7021 ); dap_cert_delete(l_cert); // Do not remove it before disk saving op
l_cert->enc_key->pub_key_data_size = dap_enc_gen_key_public_size(l_cert->enc_key); DAP_DEL_Z(l_cert_new->enc_key->pub_key_data);
if ( l_cert->enc_key->pub_key_data_size ) { DAP_DEL_Z(l_cert_new->enc_key->priv_key_data);
//l_cert->key_private->pub_key_data = DAP_NEW_SIZE(void, l_cert->key_private->pub_key_data_size); dap_cert_delete(l_cert_new);
//if ( dap_enc_gen_key_public(l_cert->key_private, l_cert->key_private->pub_key_data) == 0){ return ret;
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,"wb"); static int s_cert_add_metadata(int argc, const char **argv) {
if (l_file) { if (argc >= 5) {
fwrite(l_pkey,1,l_pkey->header.size + sizeof(l_pkey->header),l_file); const char *l_cert_name = argv[3];
fclose(l_file); dap_cert_t *l_cert = dap_cert_add_file(l_cert_name, s_system_ca_dir);
} if ( l_cert ) {
} else { char **l_params = dap_strsplit(argv[4], ":", 4);
log_it(L_ERROR, "Can't produce pkey from the certificate"); dap_cert_metadata_type_t l_type = (dap_cert_metadata_type_t)atoi(l_params[1]);
exit(-7022); 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));
dap_chain_cert_delete_by_name(l_cert_name); } else {
ret = 0; dap_cert_add_meta_scalar(l_cert, l_params[0], l_type,
//}else{ strtoull(l_params[3], NULL, 10), strtoul(l_params[2], NULL, 10));
// log_it(L_ERROR,"Can't produce public key with this key type"); }
// exit(-7024); dap_strfreev(l_params);
//} dap_cert_save_to_folder(l_cert, s_system_ca_dir);
} else { dap_cert_delete_by_name(l_cert_name);
log_it(L_ERROR,"Can't produce pkey from this cert type"); log_it(L_NOTICE, "The metainformation was successfully added to %s certificate\n", l_cert_name);
exit(-7023); return 0;
} }
} else if ( strcmp( argv[2],"create_cert_pkey") == 0 ) { else {
if ( argc >= 5 ) { log_it(L_ERROR, "Can't open %s certificate", l_cert_name);
const char *l_cert_name = argv[3]; exit(-800);
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); } else {
if ( l_cert ) { log_it( L_ERROR, "Wrong 'cert add_metadata' command params\n");
if ( l_cert->enc_key->pub_key_data_size ) { exit(-800);
// 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); static int s_cert_sign(int argc, const char **argv) {
log_it(L_ERROR, "The command 'cert sign' is not implemented.");
// Copy only public key return -1;
l_cert_new->enc_key->pub_key_data = DAP_NEW_Z_SIZE(uint8_t, }
l_cert_new->enc_key->pub_key_data_size = static int s_cert_pkey_show(int argc, const char **argv)
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); if (argc != 5) {
log_it( L_ERROR, "Wrong 'cert pkey show' command params\n");
dap_chain_cert_save_to_folder(l_cert_new, SYSTEM_CA_DIR); exit(-800);
//dap_chain_cert_delete_by_name(l_cert_name); }
//dap_chain_cert_delete_by_name(l_cert_new_name); dap_cert_t *l_cert = dap_cert_find_by_name(argv[4]);
} else { if (!l_cert) {
log_it(L_ERROR,"Can't produce pkey from this cert type"); printf("Not found cert %s\n", argv[4]);
exit(-7023); exit(-134);
} }
} else {
exit(-7021); 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);
else if ( strcmp( argv[2],"create" ) == 0 ) { }
if ( argc < 5 ) {
s_help(); printf("%s\n", dap_chain_hash_fast_to_str_static(&l_hash));
exit(-500); return 0;
} }
size_t l_key_length = 0; static int s_cert_pkey_show_full(int argc, const char **argv)
const char *l_cert_name = argv[3]; {
size_t l_cert_path_length = strlen(argv[3])+8+strlen(SYSTEM_CA_DIR); if (argc != 5) {
char *l_cert_path = DAP_NEW_Z_SIZE(char,l_cert_path_length); log_it( L_ERROR, "Wrong 'cert pkey show' command params\n");
snprintf(l_cert_path,l_cert_path_length,"%s/%s.dcert",SYSTEM_CA_DIR,l_cert_name); exit(-800);
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); dap_cert_t *l_cert = dap_cert_find_by_name(argv[4]);
exit(-700); if (!l_cert) {
} printf("Not found cert %s\n", argv[4]);
exit(-134);
dap_enc_key_type_t l_key_type = DAP_ENC_KEY_TYPE_NULL; }
if ( strcmp (argv[4],"sig_bliss") == 0 ){ dap_hash_fast_t l_hash;
l_key_type = DAP_ENC_KEY_TYPE_SIG_BLISS; if (dap_cert_get_pkey_hash(l_cert, &l_hash)) {
} else if ( strcmp (argv[4],"sig_tesla") == 0) { printf("Can't serialize cert %s", argv[4]);
l_key_type = DAP_ENC_KEY_TYPE_SIG_TESLA; exit(-135);
} 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_ERROR, "Can't create %s",l_cert_path);
}
} else {
s_help();
DAP_DELETE(l_cert_path);
exit(-500);
}
DAP_DELETE(l_cert_path);
} else {
log_it(L_ERROR,"Wrong params");
s_help();
exit(-1000);
}
} else {
log_it(L_ERROR,"Wrong params");
s_help();
exit(-1000);
}
}else {
log_it(L_ERROR,"Wrong params");
s_help();
exit(-1000);
}
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);
}
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);
}
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);
}
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;
} }
/** /**
...@@ -369,76 +697,82 @@ int main( int argc, const char **argv ) ...@@ -369,76 +697,82 @@ int main( int argc, const char **argv )
* @param argv * @param argv
* @return * @return
*/ */
static int s_init( int argc, const char **argv ) static int s_init()
{ {
if ( dap_common_init( DAP_APP_NAME, DAP_APP_NAME"_logs.txt") != 0 ) { if ( dap_common_init(dap_get_appname(), NULL) )
printf( "Fatal Error: Can't init common functions module" ); return printf("Fatal Error: Can't init common functions module"), -2;
return -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;
}
dap_config_init( SYSTEM_CONFIGS_DIR ); /**
* @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;
}
if ( (g_config = dap_config_open(DAP_APP_NAME)) == NULL ) { /**
log_it( L_ERROR, "Can't init general configurations" ); * @brief s_fill_hash_key_for_data
return -1; * @param key
} * @param data
*/
// if(dap_common_init(DAP_APP_NAME"_logs.txt")!=0){ static void s_fill_hash_key_for_data(dap_enc_key_t *l_key, void *l_data)
// log_it(L_ERROR,"Can't init common functions module"); {
// return -2; 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;
if ( dap_chain_init() != 0 ) { uint8_t *l_pub_key = dap_enc_key_serialize_pub_key(l_key, &l_pub_key_size);
log_it( L_ERROR, "Can't chain module" ); if (!l_pub_key)
return -3; 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;
if ( dap_chain_cert_init() != 0 ) { uint8_t *l_sign_ser = dap_enc_key_serialize_sign(l_key->type, l_sign_unserialized, &l_sign_ser_size);
log_it( L_ERROR, "Can't chain certificate storage module" ); if ( l_sign_ser ) {
return -4; 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);
if ( dap_chain_wallet_init() != 0 ) { l_ret->header.type = dap_sign_type_from_key_type(l_key->type);
log_it( L_ERROR, "Can't chain wallet storage module" ); // write serialized signature to dap_sign_t
return -5; 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;
if ( dap_server_init(0) != 0 ) { DAP_DELETE(l_sign_ser);
log_it( L_ERROR, "Can't server module" ); dap_enc_key_signature_delete(l_key->type, l_sign_unserialized);
return -6; 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);
if ( dap_stream_init(false) != 0 ) { uint8_t *s = (uint8_t *) l_data;
log_it( L_ERROR, "Can't init stream module" ); for (int i = 0; i < DAP_CHAIN_HASH_FAST_SIZE; i++) {
return -7; s[i] = fast_hash.raw[i];
} }
DAP_DEL_Z(l_ret);
if ( dap_stream_ch_init() != 0 ) { }
log_it( L_ERROR, "Can't init stream ch module" ); }
return -8;
}
if ( dap_stream_ch_chain_init() != 0 ) {
log_it( L_ERROR, "Can't init stream ch chain module" );
return -9;
}
if ( dap_stream_ch_chain_net_init() != 0 ) {
log_it( L_ERROR, "Can't init stream ch chain net module" );
return -10;
}
if ( dap_stream_ch_chain_net_srv_init() != 0 ) {
log_it( L_ERROR, "Can't init stream ch chain net srv module" );
return -11;
}
if ( dap_client_init() != 0 ) {
log_it( L_ERROR, "Can't chain wallet storage module" );
return -12;
}
return 0;
} }
/** /**
...@@ -448,31 +782,50 @@ static int s_init( int argc, const char **argv ) ...@@ -448,31 +782,50 @@ static int s_init( int argc, const char **argv )
static void s_help() static void s_help()
{ {
#ifdef _WIN32 #ifdef _WIN32
SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), 7 ); SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), 7 );
#endif #endif
char *l_tool_appname = dap_strdup_printf("%s-tool", dap_get_appname());
printf( "\n" );
printf( "%s usage:\n\n", l_tool_appname);
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(" * 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);
#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(" * Print hash of public key for wallet <wallet name>\n");
printf("\t%s wallet pkey show <wallet name>\n\n", l_tool_appname);
printf( "\n" ); printf(" * Create new key file with randomly produced key stored in\n");
printf( "%s usage:\n\n", s_appname ); printf("\t%s cert create <cert name> <sign type> [<key length>]\n\n", l_tool_appname);
printf(" * Create new key wallet and generate signatures with same names plus index \n" ); printf(" * Dump cert data stored in <file path>\n");
printf("\t%s wallet create <network name> <wallet name> <signature type> [<signature type 2>[...<signature type N>]]\n\n", s_appname ); printf("\t%s cert dump <cert name>\n\n", l_tool_appname);
printf(" * Create new key wallet from existent certificates in the system\n"); printf(" * Sign some data with cert \n");
printf("\t%s wallet create_from <network name> <wallet name> <wallet ca1> [<wallet ca2> [...<wallet caN>]]\n\n", s_appname ); 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 new key file with randomly produced key stored in\n"); printf(" * Create pkey from <cert name> and store it on <pkey path>\n");
printf("\t%s cert create <cert name> <key type> [<key length>]\n\n", s_appname ); printf("\t%s cert create_pkey <cert name> <pkey path>\n\n", l_tool_appname);
printf(" * Dump cert data stored in <file path>\n"); printf(" * Export only public key from <cert name> and stores it \n");
printf("\t%s cert dump <cert name>\n\n", s_appname ); printf("\t%s cert create_cert_pkey <cert name> <new cert name>\n\n", l_tool_appname);
printf(" * Sign some data with cert \n"); printf(" * Print hash of public key for cert <cert name>\n");
printf("\t%s cert sign <cert name> <data file path> <sign file output> [<sign data length>] [<sign data offset>]\n\n", s_appname ); printf("\t%s cert pkey show <cert name>\n\n", l_tool_appname);
printf(" * Create pkey from <cert name> and store it on <pkey path>\n"); printf(" * Print addr of cert <cert name>\n");
printf("\t%s cert create_pkey <cert name> <pkey path>\n\n", s_appname ); printf("\t%s cert addr show <cert name>\n\n", l_tool_appname);
printf(" * Export only public key from <cert name> and stores it \n"); printf(" * Add metadata item to <cert name>\n");
printf("\t%s cert create_cert_pkey <cert name> <new cert name>\n\n",s_appname); 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 @@ ...@@ -2,9 +2,9 @@
Copyright (c) 2017-2018 (c) Project "DeM Labs Inc" https://github.com/demlabsinc Copyright (c) 2017-2018 (c) Project "DeM Labs Inc" https://github.com/demlabsinc
All rights reserved. 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 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 the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
...@@ -89,10 +89,13 @@ void client_disconnect(dap_server_client_t *client,void * arg) ...@@ -89,10 +89,13 @@ void client_disconnect(dap_server_client_t *client,void * arg)
* @return Zero if ok or error code * @return Zero if ok or error code
*/ */
int node_manager_init(){ int node_manager_init(){
if(dap_common_init("build/log.txt")!=0){ if ( dap_common_init("build/log.txt") )
log_it(L_CRITICAL,"Can't init common functions module"); return printf("Can't init common functions module"), -2;
return -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){ if(dap_config_init("build/config")!=0){
log_it(L_CRITICAL,"Can't init configurations module"); log_it(L_CRITICAL,"Can't init configurations module");
return -1; return -1;
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
Copyright (c) 2017-2018 (c) Project "DeM Labs Inc" https://github.com/demlabsinc Copyright (c) 2017-2018 (c) Project "DeM Labs Inc" https://github.com/demlabsinc
All rights reserved. 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 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 the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
......
#include <signal.h> #include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#include "dap_common.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 "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" #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() { static void clear_pid_file() {
FILE * f = fopen(l_pid_path, "w"); FILE * f = fopen(s_pid_path, "w");
if (f == NULL) if (f == NULL)
log_it(L_WARNING, "Pid file not cleared"); log_it(L_WARNING, "Pid file not cleared");
else else
fclose(f); 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); log_it(L_DEBUG, "Got exit code: %d", sig_code);
clear_pid_file(); fflush(stdout);
exit(0); 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(SIGINT, sig_exit_handler);
signal(SIGTERM, sig_exit_handler);
signal(SIGHUP, 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; return 0;
} }
int sig_unix_handler_deinit() { 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(SIGTERM, SIG_DFL);
signal(SIGINT, SIG_DFL); signal(SIGINT, SIG_DFL);
signal(SIGHUP, SIG_DFL); signal(SIGHUP, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
return 0; return 0;
} }