baseEx.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. #include "stdafx.h"
  2. #include "baseEx.h"
  3. #include <stdint.h>
  4. #include <iostream>
  5. #include <vector>
  6. #include <map>
  7. #include <boost/xpressive/xpressive_dynamic.hpp>
  8. #include <boost/algorithm/string.hpp>
  9. #include <boost/filesystem.hpp>
  10. #include <boost/chrono.hpp>
  11. #include <boost/interprocess/ipc/message_queue.hpp>
  12. #include <boost/interprocess/permissions.hpp>
  13. #include <boost/thread/mutex.hpp>
  14. #include <boost/thread/lock_guard.hpp>
  15. #include <boost/algorithm/hex.hpp>
  16. #include "EventCode.h"
  17. #include "exLog/log.h"
  18. #include "cJSON.h"
  19. #include "RVCComm.h"
  20. using namespace boost::interprocess;
  21. //read ini
  22. #include <boost/property_tree/ptree.hpp>
  23. #include <boost/property_tree/ini_parser.hpp>
  24. #if (defined _WIN32 || defined _WIN64)
  25. #define BOOST_INTERPROCESS_SHARED_DIR_PATH "C:\\"
  26. #endif
  27. void* logProducer = nullptr;
  28. std::map<std::string, void*> g_logProducerArr;
  29. bool g_useMagic = false;
  30. bool g_loggerInitSuccess = false;
  31. bool g_logToFile = true;
  32. bool g_withMedia = false;
  33. bool g_withConsole = false;
  34. bool g_withSpecialTest = false;
  35. std::string g_usercodeTranslateFile = "";
  36. std::map<std::string, std::vector<std::string>> g_networkParse;
  37. std::map<std::string, clock_t> g_networkExpiredData;
  38. std::map<std::string, std::string> g_UserCodeToMsgTip;
  39. boost::mutex g_networkMutex;
  40. const std::wstring WCHAR_NULL = L"";
  41. const std::wstring specialStr = L"乗俓僜刓匼哱圽塡奬媆峔嶾廫慭怽揬昞朶梊榎橽歕沑漒瀄焅燶猏玕琝甛璡痋盶癨瞈砛碶穃竆筡篭糪絓綷縗繺羂耚肻腬臶臷芢蒤薥蚛蝄蟎衆蟎裓覾譢豛赲踈躙輁郳醆鈂鉢鎈鏫閈闬隲頫颸餦馶骪鯸鮘鳿鵟鸤黒齖";
  42. #define NOR_LEN 50
  43. #define MAX_LOG_LEN 4096
  44. #define MAX_CEFLOG_LEN 5120
  45. #if (defined _WIN32 || defined _WIN64)
  46. #include <ShellAPI.h>
  47. std::string UtfToGbk(const char* utf8)
  48. {
  49. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  50. wchar_t* wstr = new wchar_t[len + 1];
  51. memset(wstr, 0, len + 1);
  52. MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
  53. len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
  54. char* str = new char[len + 1];
  55. memset(str, 0, len + 1);
  56. WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
  57. if (wstr) delete[] wstr;
  58. return str;
  59. }
  60. //GBK转化为UTF8格式
  61. std::string ConvertGBKToUtf8(std::string& strGBK)
  62. {
  63. int len = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK.c_str(), -1, NULL, 0);
  64. wchar_t* wszUtf8 = new wchar_t[len];
  65. memset(wszUtf8, 0, len);
  66. MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK.c_str(), -1, wszUtf8, len);
  67. len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
  68. char* szUtf8 = new char[len + 1];
  69. memset(szUtf8, 0, len + 1);
  70. WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);
  71. std::string ret = szUtf8;
  72. delete[] szUtf8;
  73. delete[] wszUtf8;
  74. return ret;
  75. }
  76. #else
  77. std::string UtfToGbk(const char* utf8)
  78. {
  79. return utf8;
  80. }
  81. std::string ConvertGBKToUtf8(std::string& strGBK)
  82. {
  83. return strGBK;
  84. }
  85. #endif
  86. struct cefclientLog {
  87. LOG_LEVEL_E m_level;
  88. LOG_TYPE_E m_type;
  89. char m_logTime[NOR_LEN];
  90. char m_filename[NOR_LEN];
  91. int m_filePos;
  92. char m_cefLog[MAX_CEFLOG_LEN];
  93. cefclientLog(LOG_LEVEL_E t_level, LOG_TYPE_E t_type, const char* t_logTime, const char* t_filename, int t_filePos, const char* t_cefLog) {
  94. m_level = t_level;
  95. m_type = t_type;
  96. strcpy_s(m_logTime, NOR_LEN, t_logTime);
  97. strcpy_s(m_filename, NOR_LEN, t_filename);
  98. m_filePos = t_filePos;
  99. strcpy_s(m_cefLog, MAX_CEFLOG_LEN, t_cefLog);
  100. }
  101. cefclientLog()
  102. :m_level(LOG_LEVEL_DEBUG), m_type(LOG_TYPE_SYSTEM), m_filePos(0)
  103. {
  104. memset(m_logTime, 0, NOR_LEN);
  105. memset(m_filename, 0, NOR_LEN);
  106. memset(m_cefLog, 0, MAX_CEFLOG_LEN);
  107. }
  108. };
  109. #define CEF_GUID "{5ED197CD-9D64-4D10-9839-2A0773B6F5D2}"
  110. bool InitFileLogger(std::string dbgPath)
  111. {
  112. return g_loggerInitSuccess = logger::init(dbgPath.c_str(), "cefLog");
  113. }
  114. void DbgToFileLogger(std::string msg)
  115. {
  116. if(g_loggerInitSuccess)
  117. logger::showLog(msg);
  118. }
  119. void DbgEx(const char* str, ...)
  120. {
  121. va_list arg;
  122. va_start(arg, str);
  123. #if (defined _WIN32 || defined _WIN64)
  124. int n = _vscprintf(str, arg);
  125. char* buf = (char*)malloc(n + 1);
  126. vsprintf(buf, str, arg);
  127. auto modifyStr = CSimpleString::Format("%s", buf);
  128. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).withExtendLog(g_logToFile).setResultMsg(modifyStr.GetData())();
  129. free(buf);
  130. #else
  131. auto modifyStr = CSimpleString::Format("%s", str);
  132. vDbg(modifyStr.GetData(), arg);
  133. #endif
  134. va_end(arg);
  135. }
  136. bool SYSTEM_ON(std::string cmdLine, bool isWait)
  137. {
  138. #if (defined _WIN32 || defined _WIN64)
  139. auto waitSystem = [](const std::string cmd, const std::string par, BOOL nShow) ->DWORD
  140. {
  141. SHELLEXECUTEINFO ShExecInfo = { 0 };
  142. ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
  143. ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  144. ShExecInfo.hwnd = NULL;
  145. ShExecInfo.lpVerb = NULL;
  146. ShExecInfo.lpFile = cmd.c_str(); //调用的程序名
  147. ShExecInfo.lpParameters = par.c_str(); //调用程序的命令行参数
  148. ShExecInfo.lpDirectory = NULL;
  149. ShExecInfo.nShow = nShow ? SW_SHOW : SW_HIDE; //窗口状态为隐藏
  150. ShExecInfo.hInstApp = NULL;
  151. if (ShellExecuteEx(&ShExecInfo) && ShExecInfo.hProcess)//如果设置了 SEE_MASK_NOCLOSEPROCESS ,并且调用成功则该值大于32,调用失败者被设置错误值
  152. {
  153. //创建进程成功
  154. WaitForSingleObject(ShExecInfo.hProcess, INFINITE); //等到该进程结束
  155. DWORD exitCode = 0;
  156. GetExitCodeProcess(ShExecInfo.hProcess, &exitCode);
  157. return exitCode;
  158. }
  159. else {
  160. std::string errMsg;
  161. auto errorCode = GetLastError();
  162. switch (errorCode)
  163. {
  164. #define CASE(code) \
  165. case code: \
  166. errMsg = #code; \
  167. break
  168. CASE(ERROR_FILE_NOT_FOUND);
  169. CASE(ERROR_PATH_NOT_FOUND);
  170. CASE(ERROR_DDE_FAIL);
  171. CASE(ERROR_NO_ASSOCIATION);
  172. CASE(ERROR_ACCESS_DENIED);
  173. CASE(ERROR_DLL_NOT_FOUND);
  174. CASE(ERROR_CANCELLED);
  175. CASE(ERROR_NOT_ENOUGH_MEMORY);
  176. CASE(ERROR_SHARING_VIOLATION);
  177. default:
  178. errMsg = "UNKNOWN";
  179. }
  180. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SYSTEM_ON wait with %s failed, reason:%d-%s", par.c_str(), errorCode, errMsg.c_str());
  181. return false;
  182. }
  183. };
  184. std::string strCmd, strPar;
  185. if (isWait)
  186. {
  187. strPar = std::string("/c ") + cmdLine;
  188. strCmd = std::string("cmd ") + strPar;
  189. return waitSystem("cmd.exe", strPar, FALSE);
  190. }
  191. else {
  192. strCmd = cmdLine;
  193. unsigned int result = WinExec(strCmd.c_str(), SW_HIDE);
  194. if (result > 31)
  195. return true;
  196. else
  197. {
  198. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setAPI(__FUNCTION__)("SYSTEM_ON nowait with %s failed, reason:%d", result);
  199. return false;
  200. }
  201. }
  202. #else
  203. system(cmdLine.c_str());
  204. return true;
  205. #endif
  206. return false;
  207. }
  208. DWORD SaveCefclientLog(std::string magicStr)
  209. {
  210. std::string dstGuid = magicStr + "_" + CEF_GUID;
  211. try {
  212. auto removeRet = message_queue::remove(dstGuid.c_str());
  213. if (!removeRet)
  214. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("message_queue did not remove!");
  215. boost::interprocess::permissions cur;
  216. cur.set_unrestricted();
  217. message_queue mq(create_only, dstGuid.c_str(), 100, sizeof(cefclientLog), cur);
  218. g_useMagic = true;
  219. while (true)
  220. {
  221. cefclientLog t_data;
  222. #if (defined _WIN32 || defined _WIN64)
  223. unsigned int t_recvSize = 0;
  224. #else
  225. unsigned long t_recvSize = 0;
  226. #endif
  227. unsigned int t_priority = 0;
  228. mq.receive(&t_data, sizeof(cefclientLog), t_recvSize, t_priority);
  229. std::string source = std::string(t_data.m_filename) + "(" + std::to_string((ULONGLONG)t_data.m_filePos) + ")";
  230. DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(logProducer).setSourceType(source.c_str()).withExtendLog(false).setResultMsg(t_data.m_cefLog)();
  231. if (sizeof(cefclientLog) != t_recvSize)
  232. break;
  233. /*特么制品库太恶心了
  234. cefclientLog tmp;
  235. std::istringstream iss(t_data);
  236. boost::archive::binary_iarchive iarchive(iss);
  237. iarchive >> tmp;//从一个保存序列化数据的string里面反序列化,从而得到原来的对象
  238. std::string source = tmp.m_filename + "(" + std::to_string((ULONGLONG)tmp.m_filePos) + ")";
  239. DbgWithLink(tmp.m_level, tmp.m_type).setSourceType(source.c_str())(tmp.m_cefLog.c_str());
  240. */
  241. }
  242. }
  243. catch (interprocess_exception& ex) {
  244. message_queue::remove(dstGuid.c_str());
  245. g_useMagic = false;
  246. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s run exception, for %s", dstGuid.c_str(), ex.what());
  247. return 1;
  248. }
  249. g_useMagic = false;
  250. message_queue::remove(dstGuid.c_str());
  251. return 0;
  252. }
  253. std::vector<std::string> find_files(const std::string srcPath, const std::string fileName, bool isDir)
  254. {
  255. static boost::xpressive::sregex_compiler rc;
  256. if (!rc[fileName].regex_id())
  257. {
  258. std::string str = boost::algorithm::replace_all_copy(
  259. boost::algorithm::replace_all_copy(fileName, ".", "\\."), "*", ".*");
  260. rc[fileName] = rc.compile(str);
  261. }
  262. std::vector<std::string> ret;
  263. if (!boost::filesystem::exists(srcPath) || !boost::filesystem::is_directory(srcPath))
  264. return ret;
  265. typedef boost::filesystem::recursive_directory_iterator rd_iterator;
  266. rd_iterator end;
  267. for (rd_iterator pos(srcPath); pos != end; ++pos)
  268. {
  269. if ((isDir ? boost::filesystem::is_directory(*pos) : !boost::filesystem::is_directory(*pos)) && boost::xpressive::regex_match(pos->path().filename().string(), rc[fileName]))
  270. ret.emplace_back(pos->path().string());
  271. }
  272. return ret;
  273. }
  274. bool deleteDir_byFileSystem(const std::string srcPath)
  275. {
  276. boost::system::error_code ec;
  277. return boost::filesystem::remove_all(srcPath, ec);
  278. }
  279. std::string generateTimeStr(bool isSimple)
  280. {
  281. auto tt = boost::chrono::system_clock::to_time_t(boost::chrono::system_clock::now());
  282. struct tm* ptm = localtime(&tt);
  283. char date[60] = { 0 };
  284. if (isSimple)
  285. sprintf(date, "%02d%02d%02d", (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
  286. else
  287. sprintf(date, "%d-%02d-%02d-%02d:%02d:%02d", (int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday, (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
  288. return std::string(date);
  289. }
  290. void InitTranslateFile(std::string srcFile)
  291. {
  292. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitTranslateFile %s", srcFile.c_str());
  293. g_usercodeTranslateFile = srcFile;
  294. }
  295. void InitUserCodeToMsgTip(CAutoArray<CSimpleStringA>& strErrorCodeArr, CAutoArray<CSimpleStringA>& strDescriptionArr, CAutoArray<CSimpleStringA>& strRemarkArr)
  296. {
  297. g_UserCodeToMsgTip.clear();//should not be inited muli times
  298. for (int i = 0; i < strErrorCodeArr.GetCount(); i++)
  299. {
  300. std::string dstDescribe = std::string(strErrorCodeArr[i].GetData()) + "|" + std::string(strDescriptionArr[i].GetData());
  301. if(g_UserCodeToMsgTip.find(strRemarkArr[i].GetData()) != g_UserCodeToMsgTip.end())
  302. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitUserCodeToMsgTip repeated usercode:%s", strRemarkArr[i].GetData());
  303. g_UserCodeToMsgTip.insert(std::make_pair(strRemarkArr[i].GetData(), dstDescribe));
  304. }
  305. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitUserCodeToMsgTip size:%d", g_UserCodeToMsgTip.size());
  306. }
  307. std::pair<unsigned long, std::string> getErrMsgByRemark(std::string srcMsg)
  308. {
  309. const std::string headerStr = "UserError=";
  310. if (srcMsg.find(headerStr) != 0)
  311. return std::make_pair(0, srcMsg);
  312. unsigned long userCode = std::stoi(srcMsg.substr(headerStr.length()));
  313. std::string userCodeStr = CSimpleString::Format("0x%X", userCode).GetData();
  314. if(g_UserCodeToMsgTip.size() == 0)
  315. return std::make_pair(0, CSimpleString::Format("RTA42F0|微服务异常|(%s)", srcMsg.c_str()).GetData());
  316. if (g_UserCodeToMsgTip.find(userCodeStr) != g_UserCodeToMsgTip.end())
  317. {
  318. auto curMsg = g_UserCodeToMsgTip[userCodeStr];
  319. return std::make_pair(userCode, curMsg.c_str());
  320. }
  321. else
  322. return std::make_pair(userCode, CSimpleString::Format("RTA42F1|错误映射异常|(%s)", srcMsg.c_str()).GetData());
  323. }
  324. std::pair<unsigned long, std::string> splitStrToUserCodeAndErrMsg(std::string srcMsg)
  325. {
  326. const std::string headerStr = "UserError=";
  327. if (srcMsg.find(headerStr) != 0)
  328. return std::make_pair(0, srcMsg);
  329. unsigned long userCode = std::stoi(srcMsg.substr(headerStr.length()));
  330. std::string userCodeStr = CSimpleString::Format("0x%X", userCode).GetData();
  331. if (g_usercodeTranslateFile.length() == 0)
  332. return std::make_pair(userCode, srcMsg);
  333. try
  334. {
  335. boost::property_tree::ptree ptr, tag;
  336. boost::property_tree::ini_parser::read_ini(g_usercodeTranslateFile, ptr);
  337. tag = ptr.get_child("UserCodeToMsgTip");
  338. std::string tipMsg = tag.get<std::string>(userCodeStr);
  339. return std::make_pair(userCode, UtfToGbk(tipMsg.c_str()));
  340. }
  341. catch (std::exception &e) {
  342. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ini_parse failed, reason:%s", e.what());
  343. }
  344. return std::make_pair(userCode, srcMsg);
  345. }
  346. std::string hexdumpToString(const char* buf, const int num)
  347. {
  348. char str[8192 * 2] = { 0 };
  349. int i = 0;
  350. char c[5] = { 0 };
  351. if (num > 100)
  352. {
  353. for (i = 0; i < 50; i++)
  354. {
  355. sprintf(c, "%02X ", (unsigned char)buf[i]);
  356. strcat(str, c);
  357. }
  358. return CSimpleStringA::Format("buffer too long to show!show pre 50 hex! CSocketClient hex buf len = %d : %s", num, str).GetData();
  359. }
  360. for (i = 0; i < num; i++)
  361. {
  362. sprintf(c, "%02X ", (unsigned char)buf[i]);
  363. strcat(str, c);
  364. }
  365. return CSimpleStringA::Format("CSocketClient hex buf len = %d : %s", num, str).GetData();
  366. }
  367. void hexdump(const char* buf, const int num) {
  368. auto hexStr = hexdumpToString(buf, num);
  369. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)(hexStr.c_str());
  370. }
  371. bool modifyBySpecialStr(std::wstring& src)
  372. {
  373. #if 0
  374. clock_t cur = clock();
  375. std::set<wchar_t> srcArr;
  376. static std::set<wchar_t> compareArr;
  377. for (auto it = src.begin(); it != src.end(); it++)
  378. srcArr.insert(*it);
  379. if (compareArr.size() == 0)
  380. {
  381. for (auto it = specialStr.begin(); it != specialStr.end(); it++)
  382. compareArr.insert(*it);
  383. }
  384. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr insert cost:%d", clock() - cur);
  385. cur = clock();
  386. std::set<wchar_t> result;
  387. std::set_intersection(std::begin(srcArr), std::end(srcArr), std::begin(compareArr), std::end(compareArr), std::inserter(result, std::begin(result)));
  388. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr intersection cost:%d", clock() - cur);
  389. cur = clock();
  390. if (result.size() == 0)
  391. return false;
  392. for (auto it = result.begin(); it != result.end(); it++)
  393. {
  394. int pos = 0;
  395. for (int pos = 0; pos < src.length();)
  396. {
  397. pos = src.find(*it, pos);
  398. if (pos < 0)
  399. break;
  400. if (pos + 1 < src.length() && src[pos + 1] == '\\')
  401. src.erase(pos + 1, 1);
  402. else
  403. pos++;
  404. }
  405. }
  406. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr modify cost:%d", clock() - cur);
  407. cur = clock();
  408. return true;
  409. #endif
  410. clock_t cur = clock();
  411. wchar_t specialone = L'碶';
  412. if (src.find(specialone, 0) == -1)
  413. return false;
  414. int pos = 0;
  415. for (int pos = 0; pos < src.length();)
  416. {
  417. pos = src.find(specialone, pos);
  418. if (pos < 0)
  419. break;
  420. if (pos + 1 < src.length() && src[pos + 1] == '\\')
  421. src.erase(pos + 1, 1);
  422. else
  423. pos++;
  424. }
  425. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr modify cost:%d", clock() - cur);
  426. return true;
  427. }
  428. #include <boost/stacktrace.hpp>
  429. #if (defined _WIN32 || defined _WIN64)
  430. long WINAPI printSEG(struct _EXCEPTION_POINTERS* ExceptionInfo)
  431. #else
  432. long printSEG()
  433. #endif
  434. {
  435. auto dumpArr = boost::stacktrace::stacktrace().as_vector();
  436. if (dumpArr.size() > 20)
  437. {
  438. for (auto i = 0; i < 10; i++)
  439. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Pre SEG[%d]%X---%s(%s-%d)", i, dumpArr[i].address(), dumpArr[i].name().c_str(), dumpArr[i].source_file().c_str(), dumpArr[i].source_line());
  440. for (auto i = dumpArr.size() - 10; i < dumpArr.size(); i++)
  441. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Post SEG[%d]%X---%s(%s-%d)", i, dumpArr[i].address(), dumpArr[i].name().c_str(), dumpArr[i].source_file().c_str(), dumpArr[i].source_line());
  442. }
  443. else
  444. {
  445. for (auto i = 0; i < dumpArr.size(); i++)
  446. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SEG[%d]%X---%s(%s-%d)", i, dumpArr[i].address(), dumpArr[i].name().c_str(), dumpArr[i].source_file().c_str(), dumpArr[i].source_line());
  447. }
  448. return 0;
  449. }
  450. //singal,退出函数
  451. #if (defined _WIN32 || defined _WIN64)
  452. #else
  453. #include <signal.h> // ::signal, ::raise
  454. #include <boost/stacktrace.hpp>
  455. #include "CModTools.h"
  456. #include "CWebsocketServer.h"
  457. std::string g_backtracePath = "";
  458. void seg_signal_handler(int signum)
  459. {
  460. //boost::stacktrace::safe_dump_to(g_backtracePath.c_str());
  461. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, seg_signal_handler", signum);
  462. printSEG();
  463. Chromium::CModTools::get_mutable_instance().killAllChromium();
  464. Chromium::CWebsocketServer::stopServer();
  465. signal(signum, SIG_DFL);
  466. raise(signum);
  467. }
  468. void normal_signal_handle(int signum)
  469. {
  470. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, normal_signal_handle", signum);
  471. signal(signum, SIG_DFL);
  472. raise(signum);
  473. }
  474. void set_traceback_path(std::string path)
  475. {
  476. g_backtracePath = path + "/mod_chromium/" + generateTimeStr(true) + "_chromium_backtrace.dump";
  477. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set_traceback_path %s", g_backtracePath.c_str());
  478. }
  479. #endif
  480. void receivehexdump(const char* buf, const int num) {
  481. char str[8192 * 2] = { 0 };
  482. int i = 0;
  483. char c[5] = { 0 };
  484. if (num > 100)
  485. {
  486. for (i = 0; i < 50; i++)
  487. {
  488. sprintf(c, "%02X ", (unsigned char)buf[i]);
  489. strcat(str, c);
  490. }
  491. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("buffer too long to show!show pre 50 hex! receivehexdump hex buf len = %d : %s", num, str);
  492. return;
  493. }
  494. for (i = 0; i < num; i++)
  495. {
  496. sprintf(c, "%02X ", (unsigned char)buf[i]);
  497. strcat(str, c);
  498. }
  499. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receivehexdump hex buf len = %d : %s", num, str);
  500. return;
  501. }
  502. void doWithDebugModeData(const char* strMethod, const char* buf)
  503. {
  504. boost::lock_guard<boost::mutex> lock(g_networkMutex);
  505. if(std::string(strMethod).find("Network.") == 0)
  506. {
  507. /*for example
  508. {
  509. "method": "Network.requestWillBeSent",
  510. "params": {
  511. "documentURL": "https://www.btbtt12.com/",
  512. "frameId": "8F58093A23334B311DB645BA3652E63C",
  513. "hasUserGesture": false,
  514. "initiator": {
  515. "type": "other"
  516. },
  517. "loaderId": "9F7B28B896C791554C69C5985CA92E79",
  518. "request": {
  519. "headers": {
  520. "Referer": "https://www.btbtt12.com/",
  521. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36"
  522. },
  523. "initialPriority": "Low",
  524. "method": "GET",
  525. "mixedContentType": "none",
  526. "referrerPolicy": "no-referrer-when-downgrade",
  527. "url": "https://pic.picnewsss.com/tu-2022290039/960-60.gif"
  528. },
  529. "requestId": "18476.34",
  530. "timestamp": 19338.811603,
  531. "type": "Image",
  532. "wallTime": 1666099893.800733
  533. }
  534. }
  535. */
  536. std::shared_ptr<cJSON> pJson(cJSON_Parse(buf), [](cJSON* p) {
  537. if (nullptr != p)
  538. cJSON_Delete(p);
  539. });
  540. auto paramsItem = cJSON_GetObjectItem(pJson.get(), "params");
  541. if (paramsItem == nullptr)
  542. return;
  543. auto requestIdItem = cJSON_GetObjectItem(paramsItem, "requestId");
  544. if (requestIdItem == nullptr)
  545. return;
  546. std::string requestId_str = requestIdItem->valuestring;
  547. /*
  548. ['Network.loadingFailed', 'Network.loadingFinished', 'Network.resourceChangedPriority',
  549. 'Network.requestServedFromCache', 'Network.requestWillBeSent', 'Network.requestWillBeSentExtraInfo',
  550. 'Network.responseReceived', 'Network.responseReceivedExtraInfo', 'Network.dataReceived',
  551. 'Page.frameAttached', 'Page.frameRequestedNavigation', 'Page.frameStoppedLoading',
  552. 'Page.frameClearedScheduledNavigation', 'Page.loadEventFired', 'Page.frameStartedLoading',
  553. 'Page.frameDetached', 'Page.frameScheduledNavigation', 'Page.frameNavigated', 'Page.frameResized',
  554. 'Page.domContentEventFired']
  555. */
  556. if(std::string(strMethod) == "Network.loadingFinished")
  557. {
  558. if (g_networkParse.find(requestId_str) != g_networkParse.end())
  559. g_networkParse.erase(requestId_str);
  560. if (g_networkExpiredData.find(requestId_str) != g_networkExpiredData.end())
  561. g_networkExpiredData.erase(requestId_str);
  562. if (g_networkExpiredData.size() < 30)
  563. return;
  564. for(auto it = g_networkExpiredData.begin(); it != g_networkExpiredData.end();)
  565. {
  566. if((clock() - it -> second) < 100000)
  567. {
  568. it++;
  569. continue;
  570. }
  571. if (g_networkParse.find(it->first) != g_networkParse.end())
  572. g_networkParse.erase(it->first);
  573. g_networkExpiredData.erase(it++);
  574. }
  575. }
  576. else if(std::string(strMethod) == "Network.loadingFailed"
  577. || std::string(strMethod) == "Network.webSocketFrameError"
  578. || std::string(strMethod) == "Network.requestServedFromCache")
  579. {
  580. if (g_networkParse.find(requestId_str) != g_networkParse.end())
  581. {
  582. for(auto it = g_networkParse[requestId_str].begin(); it != g_networkParse[requestId_str].end(); it++)
  583. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402402Z00001").setResultMsg(it->c_str())();
  584. g_networkParse.erase(requestId_str);
  585. }
  586. else//此时,上一轮记录已结束
  587. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402402Z00001").setResultMsg(buf)();
  588. if (g_networkExpiredData.find(requestId_str) != g_networkExpiredData.end())
  589. g_networkExpiredData.erase(requestId_str);
  590. }
  591. else
  592. {
  593. if (g_networkParse.find(requestId_str) != g_networkParse.end())
  594. g_networkParse[requestId_str].push_back(buf);
  595. else
  596. {
  597. std::vector<std::string> tmp;
  598. tmp.push_back(buf);
  599. g_networkParse[requestId_str] = tmp;
  600. g_networkExpiredData[requestId_str] = clock();
  601. }
  602. }
  603. }
  604. if (std::string(strMethod) == "Network.webSocketFrameError" ||
  605. std::string(strMethod) == "Network.loadingFailed" ||
  606. std::string(strMethod) == "Runtime.exceptionThrown")
  607. {
  608. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_CHROMIUM_OPENWEBWARN, buf);
  609. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402402Z00002").setResultMsg(buf)();
  610. }
  611. }
  612. std::pair<bool, CSimpleStringA> json_deal::getStringFromCjsonObj(void* object, const char* name)
  613. {
  614. if (object == NULL)
  615. return std::make_pair(false, "");
  616. auto curNode = cJSON_GetObjectItem((cJSON*)object, name);
  617. if (curNode && curNode->type == cJSON_String) {
  618. return std::make_pair(true, curNode->valuestring);
  619. }
  620. else
  621. return std::make_pair(false, "");
  622. }
  623. std::pair<bool, int> json_deal::getIntergerFromCjsonObj(void* object, const char* name)
  624. {
  625. if (object == NULL)
  626. return std::make_pair(false, 0);
  627. auto curNode = cJSON_GetObjectItem((cJSON*)object, name);
  628. if (curNode && curNode->type == cJSON_Number) {
  629. return std::make_pair(true, curNode->valueint);
  630. }
  631. else
  632. return std::make_pair(false, 0);
  633. }
  634. std::pair<bool, double> json_deal::getDoubleFromCjsonObj(void* object, const char* name)
  635. {
  636. if (object == NULL)
  637. return std::make_pair(false, 0);
  638. auto curNode = cJSON_GetObjectItem((cJSON*)object, name);
  639. if (curNode && curNode->type == cJSON_Number) {
  640. return std::make_pair(true, curNode->valuedouble);
  641. }
  642. else
  643. return std::make_pair(false, 0);
  644. }
  645. SM2_Encrypt_Manager::SM2_Encrypt_Manager()
  646. :m_public_key_buf_len(DEFAULT_KEY_LEN),
  647. m_private_key_buf_len(DEFAULT_KEY_LEN),
  648. m_opposite_public_key_buf_len(DEFAULT_KEY_LEN)
  649. {
  650. memset(m_public_key_buf, 0, DEFAULT_KEY_LEN);
  651. memset(m_private_key_buf, 0, DEFAULT_KEY_LEN);
  652. memset(m_opposite_public_key_buf, 0, DEFAULT_KEY_LEN);
  653. GenerateSM2_key(m_public_key, m_private_key);
  654. m_state = SM2ProtocolState::WAIT_KEY_EXCHANGE;
  655. }
  656. SM2_Encrypt_Manager::~SM2_Encrypt_Manager()
  657. {
  658. }
  659. bool SM2_Encrypt_Manager::GenerateSM2_key(std::string& pub, std::string& pri)
  660. {
  661. if (!::CreateSM2KeyPair(m_public_key_buf, &m_public_key_buf_len, m_private_key_buf, &m_private_key_buf_len))
  662. return false;
  663. pub = binToHex(m_public_key_buf, m_public_key_buf_len);
  664. pri = binToHex(m_private_key_buf, m_private_key_buf_len);
  665. return true;
  666. }
  667. std::string SM2_Encrypt_Manager::binToHex(const unsigned char* data, int len)
  668. {
  669. std::string hexString;
  670. // 使用 boost::algorithm::hex 进行编码
  671. boost::algorithm::hex(data, data + len, std::back_inserter(hexString));
  672. return hexString;
  673. }
  674. void SM2_Encrypt_Manager::hexToBin(const std::string& hexStr, unsigned char* binData, int& binLen)
  675. {
  676. binLen = hexStr.size() / 2;
  677. if (binData == nullptr) {
  678. // 如果 binData 为 nullptr,仅返回计算出的 binLen,不执行实际的转换
  679. return;
  680. }
  681. // 使用 boost::algorithm::unhex 进行解码
  682. boost::algorithm::unhex(hexStr.begin(), hexStr.end(), binData);
  683. }
  684. void SM2_Encrypt_Manager::setOpposite(const std::string pub)
  685. {
  686. m_opposite_public_key = pub;
  687. hexToBin(m_opposite_public_key, m_opposite_public_key_buf, m_opposite_public_key_buf_len);
  688. }
  689. std::pair<bool, std::string> SM2_Encrypt_Manager::checkSM2Enable()
  690. {
  691. if (m_public_key.length() == 0)
  692. return std::make_pair(false, "public_key is empty");
  693. if (m_private_key.length() == 0)
  694. return std::make_pair(false, "private_key is empty");
  695. if (m_opposite_public_key.length() == 0)
  696. return std::make_pair(false, "opposite public_key is empty");
  697. return std::make_pair(true, "");
  698. }
  699. std::pair<std::string, std::string> SM2_Encrypt_Manager::EncryptMsg(std::string msg)
  700. {
  701. unsigned char sign[DEFAULT_KEY_LEN] = "";
  702. int sign_len = DEFAULT_KEY_LEN;
  703. unsigned char* dstMsg = new unsigned char[msg.length() * 2];
  704. int dstMsgLen = msg.length() * 2;
  705. std::shared_ptr<void> msgClean((void*)0, [&](void*) {
  706. if (dstMsg)
  707. {
  708. delete[]dstMsg;
  709. dstMsg = nullptr;
  710. }
  711. });
  712. if (!SM2SignWithSM3(m_private_key_buf, m_private_key_buf_len, (unsigned char*)msg.c_str(), msg.length(), sign, &sign_len))
  713. {
  714. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SM2SignWithSM3::err, can not sign msg");
  715. return std::make_pair("", "");
  716. }
  717. if(!EncWithSM2PubKey((unsigned char*)msg.c_str(), msg.length(), dstMsg, &dstMsgLen, m_opposite_public_key_buf, m_opposite_public_key_buf_len))
  718. {
  719. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("EncWithSM2PubKey::err, can not encrypt msg");
  720. return std::make_pair("", "");
  721. }
  722. return std::make_pair(binToHex(sign, sign_len), binToHex(dstMsg, dstMsgLen));
  723. }
  724. std::pair<bool, std::string> SM2_Encrypt_Manager::DecryptMsg(std::string sign, std::string msg)
  725. {
  726. unsigned char* binMsg = new unsigned char[msg.length()], *outMsg = new unsigned char[msg.length() * 2], *binSign = new unsigned char[sign.length()];//normally, it is half length of msg
  727. int binMsgLen = msg.length(), outMsgLen = msg.length() * 2, signLen = sign.length();
  728. std::shared_ptr<void> msgClean((void*)0, [&](void*) {
  729. if (binMsg) {
  730. delete[] binMsg;
  731. binMsg = nullptr;
  732. }
  733. if (outMsg) {
  734. delete[] outMsg;
  735. outMsg = nullptr;
  736. }
  737. if (binSign) {
  738. delete[] binSign;
  739. binSign = nullptr;
  740. }
  741. });
  742. hexToBin(msg, binMsg, binMsgLen);
  743. hexToBin(sign, binSign, signLen);
  744. if (!DecWithSM2PriKey(binMsg, binMsgLen, outMsg, &outMsgLen, m_private_key_buf, m_private_key_buf_len))
  745. return std::make_pair(false, "DecWithSM2PriKey::err, can not dectrypt msg");
  746. if (!SM2VerifyWithSM3(m_opposite_public_key_buf, m_opposite_public_key_buf_len, outMsg, outMsgLen, binSign, signLen))
  747. return std::make_pair(false, "SM2VerifyWithSM3::err, can not verify sign");
  748. return std::make_pair(true, (char*)outMsg);
  749. }
  750. std::pair<bool, std::string> SM2_Encrypt_Manager::GenerateEncPubKey()
  751. {
  752. if(!verifySM2Manager())
  753. return std::make_pair(false, "GenerateEncPubKey::verifySM2Manager err");
  754. unsigned char encPubKey[DEFAULT_KEY_LEN] = "";
  755. int encPubKey_len = DEFAULT_KEY_LEN;
  756. if(!EncWithSM2PubKey(m_public_key_buf, m_public_key_buf_len, encPubKey, &encPubKey_len, m_opposite_public_key_buf, m_opposite_public_key_buf_len))
  757. return std::make_pair(false, "GenerateEncPubKey::EncWithSM2PubKey err");
  758. return std::make_pair(true, binToHex(encPubKey, encPubKey_len));
  759. }
  760. bool SM2_Encrypt_Manager::verifySM2Manager()
  761. {
  762. if (m_opposite_public_key.length() == 0 || m_public_key.length() == 0 || m_private_key.length() == 0)
  763. return false;
  764. if (m_opposite_public_key_buf == NULL || m_public_key_buf == NULL || m_private_key_buf == NULL)
  765. return false;
  766. return true;
  767. }