pull/32/merge
apexliu 2017-03-06 09:13:25 +08:00
parent f3013f771d
commit bfedef4a4e
13 changed files with 325 additions and 714 deletions

View File

@ -184,7 +184,7 @@
<ClCompile Include="..\..\..\external\mongoose\mongoose.c" />
<ClCompile Include="main.cpp" />
<ClCompile Include="ts_crypto.cpp" />
<ClCompile Include="ts_db.cpp" />
<ClCompile Include="ts_web_rpc.cpp" />
<ClCompile Include="ts_env.cpp" />
<ClCompile Include="ts_http_client.cpp" />
<ClCompile Include="ts_http_rpc.cpp" />
@ -209,7 +209,7 @@
<ClInclude Include="..\common\ts_const.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="ts_crypto.h" />
<ClInclude Include="ts_db.h" />
<ClInclude Include="ts_web_rpc.h" />
<ClInclude Include="ts_env.h" />
<ClInclude Include="ts_http_client.h" />
<ClInclude Include="ts_http_rpc.h" />

View File

@ -52,9 +52,6 @@
<ClCompile Include="ts_crypto.cpp">
<Filter>main app</Filter>
</ClCompile>
<ClCompile Include="ts_db.cpp">
<Filter>main app</Filter>
</ClCompile>
<ClCompile Include="ts_env.cpp">
<Filter>main app</Filter>
</ClCompile>
@ -106,6 +103,9 @@
<ClCompile Include="..\..\..\external\mbedtls\library\sha1.c">
<Filter>mbedtls\library</Filter>
</ClCompile>
<ClCompile Include="ts_web_rpc.cpp">
<Filter>main app</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="ts_main.h">
@ -120,9 +120,6 @@
<ClInclude Include="ts_crypto.h">
<Filter>main app</Filter>
</ClInclude>
<ClInclude Include="ts_db.h">
<Filter>main app</Filter>
</ClInclude>
<ClInclude Include="ts_env.h">
<Filter>main app</Filter>
</ClInclude>
@ -177,6 +174,9 @@
<ClInclude Include="..\common\ts_const.h">
<Filter>common</Filter>
</ClInclude>
<ClInclude Include="ts_web_rpc.h">
<Filter>main app</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="tp_core.rc">

View File

@ -1,540 +0,0 @@
#include "ts_db.h"
#include "ts_env.h"
#include "ts_http_client.h"
#include "../common/ts_const.h"
#include <ex/ex_str.h>
#include <algorithm>
#include <functional>
typedef std::map<ex_astr, ex_astr> mapStringKey;
TsDB g_db;
TsDB::TsDB()
{
}
TsDB::~TsDB()
{
// ExThreadSmartLock locker(m_lock);
// sqlite3Map::iterator it;
// for (it = m_sqlite3Map.begin(); it != m_sqlite3Map.end(); it++)
// {
// if (it->second != NULL)
// {
// sqlite3_close(it->second);
// it->second = NULL;
// }
// }
// m_sqlite3Map.clear();
}
// sqlite3* TsDB::get_db()
// {
// ex_astr db_path;
// ex_wstr2astr(g_env.m_db_file, db_path);
//
// ex_u64 _tid = ex_get_thread_id();
//
// {
// ExThreadSmartLock locker(m_lock);
// long tid = (long)_tid;
// sqlite3Map::iterator it = m_sqlite3Map.find(tid);
// if (it != m_sqlite3Map.end())
// return it->second;
//
// sqlite3* sql_db = NULL;
// int ret = sqlite3_open(db_path.c_str(), &sql_db);
// if (SQLITE_OK != ret)
// {
// EXLOGE("[core-db] can not open database: %s\n", sqlite3_errmsg(sql_db));
// sqlite3_close(sql_db);
// sql_db = NULL;
// return NULL;
// }
//
// m_sqlite3Map[tid] = sql_db;
// return sql_db;
// }
//
// return NULL;
// }
bool TsDB::get_auth_info(int auth_id, Json::Value& jret)
{
Json::FastWriter json_writer;
Json::Value jreq;
jreq["method"] = "get_auth_info";
jreq["param"]["authid"] = auth_id;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
ex_astr body;
if (!ts_http_get(url, body))
{
// EXLOGV("request `get_auth_info` from web return: ");
// EXLOGV(body.c_str());
// EXLOGV("\n");
return false;
}
Json::Reader jreader;
if (!jreader.parse(body.c_str(), jret))
return false;
if (!jret.isObject())
return false;
if (!jret["data"].isObject())
return false;
Json::Value& _jret = jret["data"];
if (
!_jret["host_ip"].isString()
|| !_jret["host_port"].isInt()
|| !_jret["sys_type"].isInt()
|| !_jret["protocol"].isInt()
|| !_jret["auth_mode"].isInt()
|| !_jret["account_lock"].isInt()
|| !_jret["user_name"].isString()
|| !_jret["user_auth"].isString()
|| !_jret["user_param"].isString()
|| !_jret["account_name"].isString()
)
{
return false;
}
return true;
}
// bool TsDB::get_auth_info(int auth_id, TS_DB_AUTH_INFO& info)
// {
// int result = 0;
// char * errmsg = NULL;
// char **dbResult;
// int nRow, nColumn;
// int i, j;
// int index;
//
// sqlite3* sql_exec = get_db();
// if (sql_exec == NULL)
// return false;
//
// char szSQL[1024] = { 0 };
// ex_strformat(szSQL, 1024,
// "SELECT a.auth_id as auth_id, a.account_name as account_name, \
// a.host_auth_id as host_auth_id, a.host_id as host_id,host_lock, \
// b.host_sys_type as host_sys_type, host_ip, host_port, protocol, \
// c.user_pswd as user_pswd, c.cert_id as cert_id, c.user_name as user_name, \
// c.encrypt as encrypt, c.auth_mode as auth_mode,c.user_param as user_param, \
// d.account_lock as account_lock FROM ts_auth as a \
// LEFT JOIN ts_host_info as b ON a.host_id = b.host_id \
// LEFT JOIN ts_auth_info as c ON a.host_auth_id = c.id \
// LEFT JOIN ts_account as d ON a.account_name = d.account_name \
// WHERE a.auth_id=%d", auth_id);
//
// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg);
// if (result != 0)
// return false;
//
// //查询是否存在表
// index = nColumn;
// bool bFind = false;
// for (i = 0; i < nRow; i++)
// {
// mapStringKey mapstringKey;
// for (j = 0; j < nColumn; j++)
// {
// ex_astr temp = dbResult[j];
// if (dbResult[index] == NULL)
// {
// mapstringKey[dbResult[j]] = "";
// }
// else
// {
// mapstringKey[dbResult[j]] = dbResult[index];
// }
//
// ++index;
// }
//
// mapStringKey::iterator it = mapstringKey.find("host_ip");
// if (it != mapstringKey.end())
// info.host_ip = it->second;
//
// it = mapstringKey.find("host_sys_type");
// if (it != mapstringKey.end())
// info.sys_type = atoi(it->second.c_str());
// else
// return false;
//
// it = mapstringKey.find("account_name");
// if (it != mapstringKey.end())
// info.account_name = it->second;
// else
// return false;
//
// it = mapstringKey.find("account_lock");
// if (it != mapstringKey.end())
// info.account_lock = atoi(it->second.c_str());
// else
// return false;
//
// it = mapstringKey.find("host_lock");
// if (it != mapstringKey.end())
// info.host_lock = atoi(it->second.c_str());
// else
// return false;
//
// it = mapstringKey.find("host_port");
// if (it != mapstringKey.end())
// info.host_port = atoi(it->second.c_str());
//
// it = mapstringKey.find("protocol");
// if (it != mapstringKey.end())
// {
// info.protocol = atoi(it->second.c_str());
// it = mapstringKey.find("host_port");
// }
// else
// {
// return false;
// }
//
// it = mapstringKey.find("encrypt");
// if (it != mapstringKey.end())
// info.is_encrypt = atoi(it->second.c_str());
// else
// return false;
//
// it = mapstringKey.find("auth_mode");
// if (it != mapstringKey.end())
// info.auth_mode = atoi(it->second.c_str());
// else
// return false;
//
// it = mapstringKey.find("user_name");
// if (it != mapstringKey.end())
// info.user_name = it->second;
// else
// return false;
//
// it = mapstringKey.find("user_param");
// if (it != mapstringKey.end())
// info.user_param = it->second;
// else
// return false;
//
// if (info.auth_mode == TS_AUTH_MODE_PASSWORD)
// {
// it = mapstringKey.find("user_pswd");
// if (it != mapstringKey.end())
// info.user_auth = it->second;
// else
// return false;
// }
// else if (info.auth_mode == TS_AUTH_MODE_PRIVATE_KEY)
// {
// it = mapstringKey.find("cert_id");
// if (it != mapstringKey.end())
// {
// int cert_id = atoi(it->second.c_str());
// ex_astr cert_pri;
// get_cert_pri(cert_id, cert_pri);
// info.user_auth = cert_pri;
// }
// else
// {
// return false;
// }
// }
// else if (info.auth_mode == TS_AUTH_MODE_NONE)
// {
// }
// else
// {
// }
//
// bFind = true;
// break;
// }
//
// sqlite3_free_table(dbResult);
// return bFind;
// }
// bool TsDB::get_cert_pri(int cert_id, ex_astr& cert_pri)
// {
// int result = 0;
// char * errmsg = NULL;
// char **dbResult;
// int nRow, nColumn;
// int i, j;
// int index;
//
// sqlite3* sql_exec = get_db();
// if (sql_exec == NULL)
// return false;
//
// char szSQL[256] = { 0 };
// ex_strformat(szSQL, 256, "SELECT a.cert_pri as cert_pri FROM ts_cert as a WHERE a.cert_id=%d", cert_id);
//
// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg);
// if (result != 0)
// return false;
//
// //查询是否存在表
// index = nColumn;
// for (i = 0; i < nRow; i++)
// {
// mapStringKey mapstringKey;
// for (j = 0; j < nColumn; j++)
// {
// ex_astr temp = dbResult[j];
// if (dbResult[index] == NULL)
// mapstringKey[dbResult[j]] = "";
// else
// mapstringKey[dbResult[j]] = dbResult[index];
//
// ++index;
// }
//
// mapStringKey::iterator it = mapstringKey.find("cert_pri");
// if (it != mapstringKey.end())
// cert_pri = it->second.c_str();
// }
//
// sqlite3_free_table(dbResult);
// return true;
// }
// bool TsDB::get_host_count(int& count)
// {
// int result;
// char * errmsg = NULL;
// char **dbResult; //是 char ** 类型,两个*号
// int nRow, nColumn;
// int index;
//
// sqlite3* sql_exec = get_db();
// if (sql_exec == NULL)
// return false;
//
// const char* szSQL = "select count(*) from ts_host_info;";
//
// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg);
// if (result != 0)
// {
// if (dbResult)
// sqlite3_free_table(dbResult);
// return false;
// }
//
// index = nColumn;
// if (nColumn != 1)
// {
// if (dbResult)
// sqlite3_free_table(dbResult);
// return false;
// }
//
// count = atoi(dbResult[index]);
//
// sqlite3_free_table(dbResult);
//
// return true;
// }
bool TsDB::update_reset_log()
{
ex_astr param;
ts_url_encode("{\"method\":\"session_fix\",\"param\":[]}", param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
ex_astr body;
return ts_http_get(url, body);
}
// bool TsDB::session_begin(TS_SESSION_INFO& info, int& sid)
// {
// int result;
// char * errmsg = NULL;
// char **dbResult;
// int nRow, nColumn;
// int index;
//
// sqlite3* sql_exec = get_db();
// if (sql_exec == NULL)
// return false;
//
// int ret_code = 0;
// int begin_time = 0;
// int end_time = 0;
//
// struct tm _now;
// if (!ex_localtime_now(&begin_time, &_now))
// return false;
//
// char szTime[64] = { 0 };
// ex_strformat(szTime, 64, "%04d-%02d-%02d %02d:%02d:%02d", (1900 + _now.tm_year), (1 + _now.tm_mon), _now.tm_mday, _now.tm_hour, _now.tm_min, _now.tm_sec);
//
// char szSQL[1024] = { 0 };
// ex_strformat(szSQL, 1024,
// "INSERT INTO ts_log (session_id, account_name,host_ip,sys_type, host_port,auth_type,\
// user_name,ret_code,begin_time,end_time,log_time, protocol) \
// VALUES (\'%s\', \'%s\',\'%s\', %d,%d,%d,\'%s\', %d, %d,%d, \'%s\', %d);",
// info.sid.c_str(), info.account_name.c_str(), info.host_ip.c_str(), info.sys_type,
// info.host_port, info.auth_mode, info.user_name.c_str(), ret_code, begin_time, end_time,
// szTime, info.protocol);
//
// result = sqlite3_exec(sql_exec, szSQL, NULL, NULL, &errmsg);
// if (result != 0)
// {
// EXLOGE("[db] insert new session failed: %s.\n", errmsg);
// return false;
// }
//
// ex_strformat(szSQL, 1024, "SELECT last_insert_rowid() as id;");
// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg);
// if (result != 0)
// {
// if (dbResult)
// sqlite3_free_table(dbResult);
// return false;
// }
//
// index = nColumn;
// if (nColumn != 1)
// {
// if (dbResult)
// sqlite3_free_table(dbResult);
// return false;
// }
//
// sid = atoi(dbResult[index]);
//
// sqlite3_free_table(dbResult);
//
// return true;
// }
bool TsDB::session_begin(TS_SESSION_INFO& info, int& record_id)
{
Json::FastWriter json_writer;
Json::Value jreq;
// ex_strformat(szSQL, 1024,
// "INSERT INTO ts_log (session_id, account_name,host_ip,sys_type, host_port,auth_type,\
// user_name,ret_code,begin_time,end_time,log_time, protocol) \
// VALUES (\'%s\', \'%s\',\'%s\', %d,%d,%d,\'%s\', %d, %d,%d, \'%s\', %d);",
// info.sid.c_str(), info.account_name.c_str(), info.host_ip.c_str(), info.sys_type,
// info.host_port, info.auth_mode, info.user_name.c_str(), ret_code, begin_time, end_time,
// szTime, info.protocol);
jreq["method"] = "session_begin";
jreq["param"]["sid"] = info.sid.c_str();
jreq["param"]["account_name"] = info.account_name.c_str();
jreq["param"]["host_ip"] = info.host_ip.c_str();
jreq["param"]["sys_type"] = info.sys_type;
jreq["param"]["host_port"] = info.host_port;
jreq["param"]["auth_mode"] = info.auth_mode,
jreq["param"]["user_name"] = info.user_name.c_str();
jreq["param"]["protocol"] = info.protocol;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
ex_astr body;
if (!ts_http_get(url, body))
{
// EXLOGV("request `get_auth_info` from web return: ");
// EXLOGV(body.c_str());
// EXLOGV("\n");
return false;
}
Json::Reader jreader;
Json::Value jret;
if (!jreader.parse(body.c_str(), jret))
return false;
if (!jret.isObject())
return false;
if (!jret["data"].isObject())
return false;
if (!jret["data"]["rid"].isUInt())
return false;
record_id = jret["data"]["rid"].asUInt();
return true;
}
//session 结束
bool TsDB::session_end(int record_id, int ret_code)
{
// int result = 0;
// char * errmsg = NULL;
//
// sqlite3* sql_exec = get_db();
// if (sql_exec == NULL)
// return false;
//
// int end_time = 0;
// if (!ex_localtime_now(&end_time, NULL))
// {
// EXLOGE("[db] can not local time.\n");
// return false;
// }
//
// char szSQL[256] = { 0 };
// ex_strformat(szSQL, 256, "UPDATE ts_log SET ret_code=%d, end_time=%d WHERE id=%d;", ret_code, end_time, id);
//
// result = sqlite3_exec(sql_exec, szSQL, 0, 0, &errmsg);
// if (result != 0)
// {
// EXLOGE("[db] update log failed: %s.\n", errmsg);
// return false;
// }
//
// return true;
Json::FastWriter json_writer;
Json::Value jreq;
jreq["method"] = "session_end";
jreq["param"]["rid"] = record_id;
jreq["param"]["code"] = ret_code;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
// ex_astr param;
// ts_url_encode("{\"method\":\"session_end\",\"param\":[]}", param);
// ex_astr url = "http://127.0.0.1:7190/rpc?";
// url += param;
ex_astr body;
return ts_http_get(url, body);
}

View File

@ -1,89 +0,0 @@
#ifndef __TS_DB_H__
#define __TS_DB_H__
#include "ts_session.h"
#include <json/json.h>
//#include <sqlite3.h>
#include <ex.h>
// #include <map>
// typedef std::map<long, sqlite3*> sqlite3Map;
//
// typedef struct TS_DB_AUTH_INFO
// {
// ex_astr host_ip;
// int host_port;
// int host_lock;
// int sys_type;
// int protocol;
// int is_encrypt;
// int auth_mode;
// int account_lock;
// ex_astr user_name;
// ex_astr user_auth;
// ex_astr user_param;
// ex_astr account_name;
// }TS_DB_AUTH_INFO;
//
// typedef struct TS_DB_AUTH_INFO_2
// {
// int auth_id;
// int host_id;
// ex_astr host_ip;
// int pro_type;
// int auth_mode;
// int host_lock;
// }TS_DB_AUTH_INFO_2;
// typedef struct TS_DB_AUTH_INFO_3
// {
// int host_id;
// ex_astr host_ip;
// ex_astr host_user_name;
// ex_astr host_user_pwd;
// int auth_mode;
// int cert_id;
// ex_astr cert_name;
// ex_astr cert_pri;
// ex_astr cert_pub;
//
// }TS_DB_AUTH_INFO_3;
// typedef struct TS_DB_SERVER_CONFIG
// {
// ex_astr ts_server_rpc_ip;
// int ts_server_rpc_port;
// int ts_server_rdp_port;
// int ts_server_ssh_port;
// int ts_server_telnet_port;
// }TS_DB_SERVER_CONFIG;
// typedef std::vector<TS_DB_AUTH_INFO_2> AuthInfo2Vec;
// typedef std::vector<TS_DB_AUTH_INFO_3> AuthInfo3Vec;
class TsDB
{
public:
TsDB();
~TsDB();
// 根据认证ID获取认证信息包括服务器IP、端口用户名、密码或私钥、协议如RDP或SSH等等
bool get_auth_info(int auth_id, Json::Value& jret);
// 重置log日志状态
bool update_reset_log();
// 记录会话的开始
bool session_begin(TS_SESSION_INFO& info, int& record_id);
//session 结束
bool session_end(int id,int ret_code);
// protected:
// sqlite3* get_db();
// private:
// ExThreadLock m_lock;
// sqlite3Map m_sqlite3Map;
};
extern TsDB g_db;
#endif // __TS_DB_H__

View File

@ -2,7 +2,7 @@
#include "ts_env.h"
#include "ts_session.h"
#include "ts_crypto.h"
#include "ts_db.h"
#include "ts_web_rpc.h"
//#include <sqlite3.h>
@ -279,6 +279,43 @@ void TsHttpRpc::_rpc_func_exit(const Json::Value& json_param, ex_astr& buf)
_create_json_ret(buf, TSR_OK);
}
void TsHttpRpc::_rpc_func_get_config(const Json::Value& json_param, ex_astr& buf)
{
Json::Value jr_data;
ExIniFile& ini = g_env.get_ini();
ex_ini_sections& secs = ini.GetAllSections();
ex_ini_sections::iterator it = secs.begin();
for (; it != secs.end(); ++it)
{
if (it->first.length() > 9 && 0 == wcsncmp(it->first.c_str(), L"protocol-", 9))
{
ex_wstr libname;
if (!it->second->GetStr(L"lib", libname))
continue;
bool enabled = false;
it->second->GetBool(L"enabled", enabled, false);
if (!enabled)
{
EXLOGV(L"[core] `%ls` not enabled.\n", libname.c_str());
continue;
}
// if (!g_tpp_mgr.load_tpp(libname))
// {
// all_ok = false;
// break;
// }
}
}
jr_data["sid"] = sid;
_create_json_ret(buf, TSR_OK, jr_data);
}
void TsHttpRpc::_rpc_func_request_session(const Json::Value& json_param, ex_astr& buf)
{
// https://github.com/eomsoft/teleport/wiki/TELEPORT-CORE-JSON-RPC#request_session
@ -311,7 +348,7 @@ void TsHttpRpc::_rpc_func_request_session(const Json::Value& json_param, ex_astr
authid = json_param["authid"].asInt();
Json::Value jret;
if (!g_db.get_auth_info(authid, jret))
if (!ts_web_rpc_get_auth_info(authid, jret))
{
_create_json_ret(buf, TSR_GETAUTH_INFO_ERROR);
return;

View File

@ -55,6 +55,8 @@ private:
void _create_json_ret(ex_astr& buf, int errcode);
void _create_json_ret(ex_astr& buf, int errcode, const char* message);
// 获取core服务的配置信息主要是支持的各个协议是否启用以及其端口号等
void _rpc_func_get_config(const Json::Value& json_param, ex_astr& buf);
// 请求一个会话ID
void _rpc_func_request_session(const Json::Value& json_param, ex_astr& buf);
// 加密一个字符串返回的是密文的BASE64编码

View File

@ -1,7 +1,7 @@
#include "ts_main.h"
#include "ts_session.h"
#include "ts_http_rpc.h"
#include "ts_db.h"
#include "ts_web_rpc.h"
#include "ts_env.h"
//#include "ts_http_client.h"
//#include "ts_ver.h"
@ -57,12 +57,12 @@ bool tpp_take_session(const ex_astr& sid, TS_SESSION_INFO& info)
bool tpp_session_begin(TS_SESSION_INFO& info, int& db_id)
{
return g_db.session_begin(info, db_id);
return ts_web_rpc_session_begin(info, db_id);
}
bool tpp_session_end(int db_id, int ret)
{
return g_db.session_end(db_id, ret);
return ts_web_rpc_session_end(db_id, ret);
}
typedef struct TPP_LIB
@ -257,24 +257,9 @@ int ts_main(void)
}
// if (!g_cfg.init())
// {
// // EXLOGE("[ERROR] can not load configuration.\n");
// return 1;
// }
// //TS_DB_AUTH_INFO info;
// //g_db.get_auth_info(17, info);
g_db.update_reset_log();
//mbedtls_debug_set_threshold(9999);
ts_web_rpc_register_core();
EXLOGV("[core] ---- initialized, ready for service ----\n");
while (!g_exit_flag)
{
ex_sleep_ms(1000);

View File

@ -0,0 +1,157 @@
#include "ts_web_rpc.h"
#include "ts_env.h"
#include "ts_http_client.h"
#include "../common/ts_const.h"
#include <ex/ex_str.h>
bool ts_web_rpc_register_core()
{
Json::FastWriter json_writer;
Json::Value jreq;
jreq["method"] = "register";
jreq["param"]["ip"] = g_env.rpc_bind_ip.c_str();
jreq["param"]["port"] = g_env.rpc_bind_port;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
ex_astr body;
return ts_http_get(url, body);
}
bool ts_web_rpc_get_auth_info(int auth_id, Json::Value& jret)
{
Json::FastWriter json_writer;
Json::Value jreq;
jreq["method"] = "get_auth_info";
jreq["param"]["authid"] = auth_id;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
ex_astr body;
if (!ts_http_get(url, body))
{
// EXLOGV("request `get_auth_info` from web return: ");
// EXLOGV(body.c_str());
// EXLOGV("\n");
return false;
}
Json::Reader jreader;
if (!jreader.parse(body.c_str(), jret))
return false;
if (!jret.isObject())
return false;
if (!jret["data"].isObject())
return false;
Json::Value& _jret = jret["data"];
if (
!_jret["host_ip"].isString()
|| !_jret["host_port"].isInt()
|| !_jret["sys_type"].isInt()
|| !_jret["protocol"].isInt()
|| !_jret["auth_mode"].isInt()
|| !_jret["account_lock"].isInt()
|| !_jret["user_name"].isString()
|| !_jret["user_auth"].isString()
|| !_jret["user_param"].isString()
|| !_jret["account_name"].isString()
)
{
return false;
}
return true;
}
bool ts_web_rpc_session_begin(TS_SESSION_INFO& info, int& record_id)
{
Json::FastWriter json_writer;
Json::Value jreq;
jreq["method"] = "session_begin";
jreq["param"]["sid"] = info.sid.c_str();
jreq["param"]["account_name"] = info.account_name.c_str();
jreq["param"]["host_ip"] = info.host_ip.c_str();
jreq["param"]["sys_type"] = info.sys_type;
jreq["param"]["host_port"] = info.host_port;
jreq["param"]["auth_mode"] = info.auth_mode,
jreq["param"]["user_name"] = info.user_name.c_str();
jreq["param"]["protocol"] = info.protocol;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
ex_astr body;
if (!ts_http_get(url, body))
{
// EXLOGV("request `get_auth_info` from web return: ");
// EXLOGV(body.c_str());
// EXLOGV("\n");
return false;
}
Json::Reader jreader;
Json::Value jret;
if (!jreader.parse(body.c_str(), jret))
return false;
if (!jret.isObject())
return false;
if (!jret["data"].isObject())
return false;
if (!jret["data"]["rid"].isUInt())
return false;
record_id = jret["data"]["rid"].asUInt();
return true;
}
//session ½áÊø
bool ts_web_rpc_session_end(int record_id, int ret_code)
{
Json::FastWriter json_writer;
Json::Value jreq;
jreq["method"] = "session_end";
jreq["param"]["rid"] = record_id;
jreq["param"]["code"] = ret_code;
ex_astr json_param;
json_param = json_writer.write(jreq);
ex_astr param;
ts_url_encode(json_param.c_str(), param);
ex_astr url = "http://127.0.0.1:7190/rpc?";
url += param;
// ex_astr param;
// ts_url_encode("{\"method\":\"session_end\",\"param\":[]}", param);
// ex_astr url = "http://127.0.0.1:7190/rpc?";
// url += param;
ex_astr body;
return ts_http_get(url, body);
}

View File

@ -0,0 +1,20 @@
#ifndef __TS_WEB_RPC_H__
#define __TS_WEB_RPC_H__
#include "ts_session.h"
#include <json/json.h>
// 重置log日志状态
bool ts_web_rpc_register_core();
// 根据认证ID获取认证信息包括服务器IP、端口用户名、密码或私钥、协议如RDP或SSH等等
bool ts_web_rpc_get_auth_info(int auth_id, Json::Value& jret);
// 记录会话的开始
bool ts_web_rpc_session_begin(TS_SESSION_INFO& info, int& record_id);
//session 结束
bool ts_web_rpc_session_end(int id, int ret_code);
#endif // __TS_WEB_RPC_H__

View File

@ -65,51 +65,53 @@ class ConfigFile(AttrDict):
# log.set_attribute(min_level=self['log_level'])
return True
def load_core(self, cfg_file):
if not os.path.exists(cfg_file):
log.e('configuration file does not exists: [{}]\n'.format(cfg_file))
return False
try:
_cfg = configparser.ConfigParser()
_cfg.read(cfg_file)
except:
log.e('can not load configuration file: [{}]\n'.format(cfg_file))
return False
self['core'] = AttrDict()
self['core']['rpc'] = AttrDict()
self['core']['rpc']['ip'] = '127.0.0.1'
self['core']['rpc']['port'] = 52080
if 'rpc' in _cfg:
self['core']['rpc']['ip'] = _cfg['rpc'].get('bind-ip', '127.0.0.1')
self['core']['rpc']['port'] = _cfg['rpc'].getint('bind-port', 52080)
self['core']['ssh'] = AttrDict()
self['core']['ssh']['enabled'] = False
self['core']['ssh']['port'] = 52189
if 'protocol-ssh' in _cfg:
self['core']['ssh']['enabled'] = _cfg['protocol-ssh'].getboolean('enabled', False)
self['core']['ssh']['port'] = _cfg['protocol-ssh'].getint('bind-port', 52189)
self['core']['rdp'] = AttrDict()
self['core']['rdp']['enabled'] = False
self['core']['rdp']['port'] = 52089
if 'protocol-rdp' in _cfg:
self['core']['rdp']['enabled'] = _cfg['protocol-rdp'].getboolean('enabled', False)
self['core']['rdp']['port'] = _cfg['protocol-rdp'].getint('bind-port', 52089)
self['core']['telnet'] = AttrDict()
self['core']['telnet']['enabled'] = False
self['core']['telnet']['port'] = 52389
if 'protocol-telnet' in _cfg:
self['core']['telnet']['enabled'] = _cfg['protocol-telnet'].getboolean('enabled', False)
self['core']['telnet']['port'] = _cfg['protocol-telnet'].getint('bind-port', 52389)
self['core_server_rpc'] = _comm.get('core-server-rpc', 'http://127.0.0.1:52080/rpc')
return True
# def load_core(self, cfg_file):
# if not os.path.exists(cfg_file):
# log.e('configuration file does not exists: [{}]\n'.format(cfg_file))
# return False
# try:
# _cfg = configparser.ConfigParser()
# _cfg.read(cfg_file)
# except:
# log.e('can not load configuration file: [{}]\n'.format(cfg_file))
# return False
#
# self['core'] = AttrDict()
#
# self['core']['rpc'] = AttrDict()
# self['core']['rpc']['ip'] = '127.0.0.1'
# self['core']['rpc']['port'] = 52080
# if 'rpc' in _cfg:
# self['core']['rpc']['ip'] = _cfg['rpc'].get('bind-ip', '127.0.0.1')
# self['core']['rpc']['port'] = _cfg['rpc'].getint('bind-port', 52080)
#
# self['core']['ssh'] = AttrDict()
# self['core']['ssh']['enabled'] = False
# self['core']['ssh']['port'] = 52189
# if 'protocol-ssh' in _cfg:
# self['core']['ssh']['enabled'] = _cfg['protocol-ssh'].getboolean('enabled', False)
# self['core']['ssh']['port'] = _cfg['protocol-ssh'].getint('bind-port', 52189)
#
# self['core']['rdp'] = AttrDict()
# self['core']['rdp']['enabled'] = False
# self['core']['rdp']['port'] = 52089
# if 'protocol-rdp' in _cfg:
# self['core']['rdp']['enabled'] = _cfg['protocol-rdp'].getboolean('enabled', False)
# self['core']['rdp']['port'] = _cfg['protocol-rdp'].getint('bind-port', 52089)
#
# self['core']['telnet'] = AttrDict()
# self['core']['telnet']['enabled'] = False
# self['core']['telnet']['port'] = 52389
# if 'protocol-telnet' in _cfg:
# self['core']['telnet']['enabled'] = _cfg['protocol-telnet'].getboolean('enabled', False)
# self['core']['telnet']['port'] = _cfg['protocol-telnet'].getint('bind-port', 52389)
#
# return True
_g_cfg = ConfigFile()
del ConfigFile

View File

@ -1,7 +1,10 @@
# -*- coding: utf-8 -*-
import os
import sys
# import sys
import json
import urllib.parse
import urllib.request
import tornado.httpserver
import tornado.ioloop
@ -46,9 +49,11 @@ class WebServerCore:
return False
# TODO: 不要直接读取core.ini而是通过core的json-rpc获取其配置数据
_cfg_file = os.path.join(cfg.cfg_path, 'core.ini')
if not cfg.load_core(_cfg_file):
return False
# _cfg_file = os.path.join(cfg.cfg_path, 'core.ini')
# if not cfg.load_core(_cfg_file):
# return False
# if not self._get_core_server_config():
# return False
cfg.log_path = os.path.abspath(options['log_path'])
cfg.log_file = os.path.join(cfg.log_path, 'tpweb.log')
@ -72,6 +77,31 @@ class WebServerCore:
return True
def _get_core_server_config(self):
try:
req = {'method': 'get_config', 'param': []}
req_data = json.dumps(req)
data = urllib.parse.quote(req_data).encode('utf-8')
req = urllib.request.Request(url=cfg.core_server_rpc, data=data)
rep = urllib.request.urlopen(req, timeout=3)
body = rep.read().decode()
print('core-config:', body)
# info = response.info()
# _zip = info.get('Content-Encoding')
# if _zip == 'gzip':
# the_page = gzip.decompress(the_page)
# else:
# pass
# the_page = the_page.decode()
# print(the_page)
# return the_page
x = json.loads(body)
cfg.core = x['data']
except:
log.w('can not connect to core server for get config, maybe it not start yet.\n')
# return True
def run(self):
settings = {
@ -106,6 +136,8 @@ class WebServerCore:
# settings['compiled_template_cache'] = False
# settings['static_hash_cache'] = False
# 尝试通过CORE-JSON-RPC获取core服务的配置主要是ssh/rdp/telnet的端口
self._get_core_server_config()
from eom_app.controller import controllers
web_app = tornado.web.Application(controllers, **settings)
@ -118,9 +150,12 @@ class WebServerCore:
log.e('Can not listen on port {}, maybe it been used by another application.\n'.format(cfg.server_port))
return 0
# 启动session超时管理
web_session().start()
tornado.ioloop.IOLoop.instance().start()
web_session().stop()
return 0

View File

@ -13,19 +13,17 @@ from .base import SwxAdminHandler, SwxAdminJsonHandler
cfg = app_cfg()
def get_free_space_mb(folder):
def get_free_space_bytes(folder):
""" Return folder/drive free space (in bytes)
"""
if platform.system() == 'Windows':
_free_bytes = ctypes.c_ulonglong(0)
_total_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(folder, None, ctypes.pointer(_total_bytes), ctypes.pointer(_free_bytes))
# return _total_bytes.value / 1024 / 1024 / 1024, _free_bytes.value / 1024 / 1024 / 1024
total_bytes = _total_bytes.value
free_bytes = _free_bytes.value
else:
st = os.statvfs(folder)
# return st.f_blocks * st.f_frsize / 1024 / 1024 / 1024, st.f_bavail * st.f_frsize / 1024 / 1024 / 1024
total_bytes = st.f_blocks * st.f_frsize
free_bytes = st.f_bavail * st.f_frsize
@ -35,12 +33,11 @@ def get_free_space_mb(folder):
class LogHandler(SwxAdminHandler):
def get(self):
user_list = user.get_user_list()
total_size, free_size = get_free_space_mb(cfg.data_path)
total_size, free_size = get_free_space_bytes(cfg.data_path)
# config_list = host.get_config_list()
ts_server = dict()
ts_server['ip'] = cfg.core.rpc.ip # config_list['ts_server_ip']
ts_server['port'] = cfg.core.rpc.port # cfg.server_port
ts_server['ip'] = cfg.core.rpc.ip
ts_server['port'] = cfg.core.rpc.port
self.render('log/index.mako', user_list=user_list, total_size=total_size, free_size=free_size, ts_server=ts_server)

View File

@ -6,10 +6,13 @@ import tornado.gen
import json
import urllib.parse
from eom_app.app.session import web_session
from eom_app.app.configs import app_cfg
from eom_app.module import host, record
from .base import SwxJsonHandler
cfg = app_cfg()
class RpcHandler(SwxJsonHandler):
@tornado.gen.coroutine
@ -52,8 +55,8 @@ class RpcHandler(SwxJsonHandler):
return self._session_begin(_req['param'])
elif 'session_end' == _req['method']:
return self._session_end(_req['param'])
elif 'session_fix' == _req['method']:
return self._session_fix()
elif 'register_core' == _req['method']:
return self._register_core(_req['param'])
elif 'exit' == _req['method']:
return self._exit()
@ -121,8 +124,10 @@ class RpcHandler(SwxJsonHandler):
else:
self.write_json(0)
def _session_fix(self):
def _register_core(self, param):
# 因为core服务启动了之前可能非正常终止了做一下数据库中会话状态的修复操作
record.session_fix()
self.write_json(0)
def _exit(self):