baseEx.cpp 29 KB

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