baseEx.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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 "winpr/sysinfo.h"
  17. #include "winpr/timezone.h"
  18. #include "EventCode.h"
  19. #include "exLog/log.h"
  20. #include "cJSON.h"
  21. #include "RVCComm.h"
  22. using namespace boost::interprocess;
  23. //read ini
  24. #include <boost/property_tree/ptree.hpp>
  25. #include <boost/property_tree/ini_parser.hpp>
  26. #if (defined _WIN32 || defined _WIN64)
  27. #define BOOST_INTERPROCESS_SHARED_DIR_PATH "C:\\"
  28. #else
  29. #include <sys/types.h>
  30. #include <unistd.h>
  31. #include <cstring>
  32. #include <signal.h>
  33. #endif
  34. std::string g_usercodeTranslateFile = "";
  35. std::map<std::string, std::vector<std::string>> g_networkParse;
  36. std::map<std::string, clock_t> g_networkExpiredData;
  37. std::map<std::string, ErrMsgStruct> g_UserCodeToMsgTip;
  38. boost::mutex g_networkMutex;
  39. const std::wstring WCHAR_NULL = L"";
  40. const std::wstring specialStr = L"乗俓僜刓匼哱圽塡奬媆峔嶾廫慭怽揬昞朶梊榎橽歕沑漒瀄焅燶猏玕琝甛璡痋盶癨瞈砛碶穃竆筡篭糪絓綷縗繺羂耚肻腬臶臷芢蒤薥蚛蝄蟎衆蟎裓覾譢豛赲踈躙輁郳醆鈂鉢鎈鏫閈闬隲頫颸餦馶骪鯸鮘鳿鵟鸤黒齖";
  41. #define NOR_LEN 50
  42. #define MAX_LOG_LEN 4096
  43. #define MAX_CEFLOG_LEN 5120
  44. #if (defined _WIN32 || defined _WIN64)
  45. #include <ShellAPI.h>
  46. std::string UtfToGbk(const char* utf8)
  47. {
  48. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  49. wchar_t* wstr = new wchar_t[len + 1];
  50. memset(wstr, 0, len + 1);
  51. MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
  52. len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
  53. char* str = new char[len + 1];
  54. memset(str, 0, len + 1);
  55. WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
  56. if (wstr) delete[] wstr;
  57. return str;
  58. }
  59. //GBK转化为UTF8格式
  60. std::string ConvertGBKToUtf8(std::string& strGBK)
  61. {
  62. int len = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK.c_str(), -1, NULL, 0);
  63. wchar_t* wszUtf8 = new wchar_t[len];
  64. memset(wszUtf8, 0, len);
  65. MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK.c_str(), -1, wszUtf8, len);
  66. len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
  67. char* szUtf8 = new char[len + 1];
  68. memset(szUtf8, 0, len + 1);
  69. WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);
  70. std::string ret = szUtf8;
  71. delete[] szUtf8;
  72. delete[] wszUtf8;
  73. return ret;
  74. }
  75. #else
  76. std::string UtfToGbk(const char* utf8)
  77. {
  78. return utf8;
  79. }
  80. std::string ConvertGBKToUtf8(std::string& strGBK)
  81. {
  82. return strGBK;
  83. }
  84. #endif
  85. struct cefclientLog {
  86. LOG_LEVEL_E m_level;
  87. LOG_TYPE_E m_type;
  88. char m_logTime[NOR_LEN];
  89. char m_filename[NOR_LEN];
  90. int m_filePos;
  91. char m_cefLog[MAX_CEFLOG_LEN];
  92. 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) {
  93. m_level = t_level;
  94. m_type = t_type;
  95. strcpy_s(m_logTime, NOR_LEN, t_logTime);
  96. strcpy_s(m_filename, NOR_LEN, t_filename);
  97. m_filePos = t_filePos;
  98. strcpy_s(m_cefLog, MAX_CEFLOG_LEN, t_cefLog);
  99. }
  100. cefclientLog()
  101. :m_level(LOG_LEVEL_DEBUG), m_type(LOG_TYPE_SYSTEM), m_filePos(0)
  102. {
  103. memset(m_logTime, 0, NOR_LEN);
  104. memset(m_filename, 0, NOR_LEN);
  105. memset(m_cefLog, 0, MAX_CEFLOG_LEN);
  106. }
  107. };
  108. #define CEF_GUID "{5ED197CD-9D64-4D10-9839-2A0773B6F5D2}"
  109. bool InitFileLogger(std::string dbgPath)
  110. {
  111. auto ret = logger::init(dbgPath.c_str(), "cefLog");
  112. ConfigManager::getInstance().setLoggerInitSuccess(ret);
  113. return ret;
  114. }
  115. void DbgToFileLogger(std::string msg)
  116. {
  117. if(ConfigManager::getInstance().isLoggerInitSuccess())
  118. logger::showLog(msg);
  119. }
  120. void DbgEx(const char* str, ...)
  121. {
  122. va_list arg;
  123. va_start(arg, str);
  124. #if (defined _WIN32 || defined _WIN64)
  125. int n = _vscprintf(str, arg);
  126. char* buf = (char*)malloc(n + 1);
  127. vsprintf(buf, str, arg);
  128. auto modifyStr = CSimpleString::Format("%s", buf);
  129. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).withExtendLog(!ConfigManager::getInstance().m_withNoFileLog).setResultMsg(modifyStr.GetData())();
  130. free(buf);
  131. #else
  132. auto modifyStr = CSimpleString::Format("%s", str);
  133. vDbg(modifyStr.GetData(), arg);
  134. #endif
  135. va_end(arg);
  136. }
  137. bool SYSTEM_ON(std::string cmdLine, bool isWait)
  138. {
  139. #if (defined _WIN32 || defined _WIN64)
  140. auto waitSystem = [](const std::string cmd, const std::string par, BOOL nShow) ->DWORD
  141. {
  142. SHELLEXECUTEINFO ShExecInfo = { 0 };
  143. ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
  144. ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  145. ShExecInfo.hwnd = NULL;
  146. ShExecInfo.lpVerb = NULL;
  147. ShExecInfo.lpFile = cmd.c_str(); //调用的程序名
  148. ShExecInfo.lpParameters = par.c_str(); //调用程序的命令行参数
  149. ShExecInfo.lpDirectory = NULL;
  150. ShExecInfo.nShow = nShow ? SW_SHOW : SW_HIDE; //窗口状态为隐藏
  151. ShExecInfo.hInstApp = NULL;
  152. if (ShellExecuteEx(&ShExecInfo) && ShExecInfo.hProcess)//如果设置了 SEE_MASK_NOCLOSEPROCESS ,并且调用成功则该值大于32,调用失败者被设置错误值
  153. {
  154. //创建进程成功
  155. WaitForSingleObject(ShExecInfo.hProcess, INFINITE); //等到该进程结束
  156. DWORD exitCode = 0;
  157. GetExitCodeProcess(ShExecInfo.hProcess, &exitCode);
  158. return exitCode;
  159. }
  160. else {
  161. std::string errMsg;
  162. auto errorCode = GetLastError();
  163. switch (errorCode)
  164. {
  165. #define CASE(code) \
  166. case code: \
  167. errMsg = #code; \
  168. break
  169. CASE(ERROR_FILE_NOT_FOUND);
  170. CASE(ERROR_PATH_NOT_FOUND);
  171. CASE(ERROR_DDE_FAIL);
  172. CASE(ERROR_NO_ASSOCIATION);
  173. CASE(ERROR_ACCESS_DENIED);
  174. CASE(ERROR_DLL_NOT_FOUND);
  175. CASE(ERROR_CANCELLED);
  176. CASE(ERROR_NOT_ENOUGH_MEMORY);
  177. CASE(ERROR_SHARING_VIOLATION);
  178. default:
  179. errMsg = "UNKNOWN";
  180. }
  181. 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());
  182. return false;
  183. }
  184. };
  185. std::string strCmd, strPar;
  186. if (isWait)
  187. {
  188. strPar = std::string("/c ") + cmdLine;
  189. strCmd = std::string("cmd ") + strPar;
  190. return waitSystem("cmd.exe", strPar, FALSE);
  191. }
  192. else {
  193. strCmd = cmdLine;
  194. unsigned int result = WinExec(strCmd.c_str(), SW_HIDE);
  195. if (result > 31)
  196. return true;
  197. else
  198. {
  199. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setAPI(__FUNCTION__)("SYSTEM_ON nowait with %s failed, reason:%d", result);
  200. return false;
  201. }
  202. }
  203. #else
  204. system(cmdLine.c_str());
  205. return true;
  206. #endif
  207. return false;
  208. }
  209. DWORD SaveCefclientLog(std::string magicStr)
  210. {
  211. std::string dstGuid = magicStr + "_" + CEF_GUID;
  212. try {
  213. auto removeRet = message_queue::remove(dstGuid.c_str());
  214. if (!removeRet)
  215. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("message_queue did not remove!");
  216. boost::interprocess::permissions cur;
  217. cur.set_unrestricted();
  218. message_queue mq(create_only, dstGuid.c_str(), 100, sizeof(cefclientLog), cur);
  219. ConfigManager::getInstance().setUseMagic(true);
  220. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SaveCefclientLog thread begin");
  221. while (true)
  222. {
  223. cefclientLog t_data;
  224. #if (defined _WIN32 || defined _WIN64)
  225. unsigned int t_recvSize = 0;
  226. #else
  227. unsigned long t_recvSize = 0;
  228. #endif
  229. unsigned int t_priority = 0;
  230. mq.receive(&t_data, sizeof(cefclientLog), t_recvSize, t_priority);
  231. std::string source = std::string(t_data.m_filename) + "(" + std::to_string((ULONGLONG)t_data.m_filePos) + ")";
  232. #ifdef OUTPUT_DETAIL_LOG /*DevOps流水线编译,ST环境*/
  233. DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(ConfigManager::getInstance().getLogProducer()).setSourceType(source.c_str()).withExtendLog(true).setResultMsg(t_data.m_cefLog)();
  234. #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
  235. DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(ConfigManager::getInstance().getLogProducer()).setSourceType(source.c_str()).withExtendLog(true).setResultMsg(t_data.m_cefLog)();
  236. #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
  237. DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(ConfigManager::getInstance().getLogProducer()).setSourceType(source.c_str()).withExtendLog(false).setResultMsg(t_data.m_cefLog)();
  238. #else
  239. DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(ConfigManager::getInstance().getLogProducer()).setSourceType(source.c_str()).withExtendLog(false).setResultMsg(t_data.m_cefLog)();
  240. #endif // DEVOPS
  241. if (sizeof(cefclientLog) != t_recvSize)
  242. break;
  243. /*特么制品库太恶心了
  244. cefclientLog tmp;
  245. std::istringstream iss(t_data);
  246. boost::archive::binary_iarchive iarchive(iss);
  247. iarchive >> tmp;//从一个保存序列化数据的string里面反序列化,从而得到原来的对象
  248. std::string source = tmp.m_filename + "(" + std::to_string((ULONGLONG)tmp.m_filePos) + ")";
  249. DbgWithLink(tmp.m_level, tmp.m_type).setSourceType(source.c_str())(tmp.m_cefLog.c_str());
  250. */
  251. }
  252. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SaveCefclientLog thread end");
  253. }
  254. catch (interprocess_exception& ex) {
  255. message_queue::remove(dstGuid.c_str());
  256. ConfigManager::getInstance().setUseMagic(false);
  257. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s run exception, for %s", dstGuid.c_str(), ex.what());
  258. return 1;
  259. }
  260. ConfigManager::getInstance().setUseMagic(false);
  261. message_queue::remove(dstGuid.c_str());
  262. return 0;
  263. }
  264. std::vector<std::string> find_files(const std::string srcPath, const std::string fileName, bool isDir)
  265. {
  266. static boost::xpressive::sregex_compiler rc;
  267. if (!rc[fileName].regex_id())
  268. {
  269. std::string str = boost::algorithm::replace_all_copy(
  270. boost::algorithm::replace_all_copy(fileName, ".", "\\."), "*", ".*");
  271. rc[fileName] = rc.compile(str);
  272. }
  273. std::vector<std::string> ret;
  274. if (!boost::filesystem::exists(srcPath) || !boost::filesystem::is_directory(srcPath))
  275. return ret;
  276. typedef boost::filesystem::recursive_directory_iterator rd_iterator;
  277. rd_iterator end;
  278. for (rd_iterator pos(srcPath); pos != end; ++pos)
  279. {
  280. if ((isDir ? boost::filesystem::is_directory(*pos) : !boost::filesystem::is_directory(*pos)) && boost::xpressive::regex_match(pos->path().filename().string(), rc[fileName]))
  281. ret.emplace_back(pos->path().string());
  282. }
  283. return ret;
  284. }
  285. bool deleteDir_byFileSystem(const std::string srcPath)
  286. {
  287. boost::system::error_code ec;
  288. return boost::filesystem::remove_all(srcPath, ec);
  289. }
  290. std::string generateTimeStr(bool isSimple)
  291. {
  292. auto tt = boost::chrono::system_clock::to_time_t(boost::chrono::system_clock::now());
  293. struct tm* ptm = localtime(&tt);
  294. char date[60] = { 0 };
  295. if (isSimple)
  296. sprintf(date, "%02d%02d%02d", (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
  297. else
  298. 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);
  299. return std::string(date);
  300. }
  301. void InitTranslateFile(std::string srcFile)
  302. {
  303. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitTranslateFile %s", srcFile.c_str());
  304. g_usercodeTranslateFile = srcFile;
  305. }
  306. void InitUserCodeToMsgTip(CAutoArray<CSimpleStringA>& strErrorCodeArr, CAutoArray<CSimpleStringA>& strDescriptionArr, CAutoArray<CSimpleStringA>& strRemarkArr)
  307. {
  308. g_UserCodeToMsgTip.clear();//should not be inited muli times
  309. for (int i = 0; i < strErrorCodeArr.GetCount(); i++)
  310. {
  311. std::string dstDescribe = "[" + std::string(strErrorCodeArr[i].GetData()) + "]" + std::string(strDescriptionArr[i].GetData());
  312. if (g_UserCodeToMsgTip.find(strRemarkArr[i].GetData()) != g_UserCodeToMsgTip.end())
  313. {
  314. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitUserCodeToMsgTip repeated usercode:%s", strRemarkArr[i].GetData());
  315. continue;
  316. }
  317. std::string curRemark = strRemarkArr[i].GetData();
  318. std::transform(curRemark.begin(), curRemark.end(), curRemark.begin(), [](unsigned char c) { return std::tolower(c); });
  319. g_UserCodeToMsgTip.insert(std::make_pair(curRemark.c_str(), ErrMsgStruct(strErrorCodeArr[i].GetData(), dstDescribe, curRemark.c_str())));
  320. }
  321. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitUserCodeToMsgTip size:%d", g_UserCodeToMsgTip.size());
  322. }
  323. std::pair<unsigned long, ErrMsgStruct> getErrMsgByRemark(std::string srcMsg)
  324. {
  325. const std::string headerStr = "UserError=";
  326. if (srcMsg.find(headerStr) != 0)
  327. return std::make_pair(0, ErrMsgStruct("", srcMsg, ""));
  328. unsigned long userCode = std::stoi(srcMsg.substr(headerStr.length()));
  329. std::string userCodeStr = CSimpleString::Format("0x%X", userCode).GetData();
  330. std::transform(userCodeStr.begin(), userCodeStr.end(), userCodeStr.begin(), [](unsigned char c) { return std::tolower(c); });
  331. if (g_UserCodeToMsgTip.size() == 0)
  332. {
  333. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA42F0").setAPI(__FUNCTION__)("[RTA42F0]微服务异常|(%s)", srcMsg.c_str());
  334. return std::make_pair(0, ErrMsgStruct("RTA42F0", CSimpleString::Format("[RTA42F0]微服务异常|(%s)", srcMsg.c_str()).GetData(), userCodeStr));
  335. }
  336. if (g_UserCodeToMsgTip.find(userCodeStr) != g_UserCodeToMsgTip.end())
  337. {
  338. ErrMsgStruct curMsg(g_UserCodeToMsgTip[userCodeStr]);
  339. return std::make_pair(userCode, curMsg);
  340. }
  341. else
  342. {
  343. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA42F1").setAPI(__FUNCTION__)("[RTA42F1]错误映射异常|(%s)", srcMsg.c_str());
  344. return std::make_pair(userCode, ErrMsgStruct("RTA42F1", CSimpleString::Format("[RTA42F1]错误映射异常|(%s)", srcMsg.c_str()).GetData(), userCodeStr));
  345. }
  346. }
  347. std::pair<unsigned long, std::string> splitStrToUserCodeAndErrMsg(std::string srcMsg)
  348. {
  349. const std::string headerStr = "UserError=";
  350. if (srcMsg.find(headerStr) != 0)
  351. return std::make_pair(0, srcMsg);
  352. unsigned long userCode = std::stoi(srcMsg.substr(headerStr.length()));
  353. std::string userCodeStr = CSimpleString::Format("0x%X", userCode).GetData();
  354. if (g_usercodeTranslateFile.length() == 0)
  355. return std::make_pair(userCode, srcMsg);
  356. try
  357. {
  358. boost::property_tree::ptree ptr, tag;
  359. boost::property_tree::ini_parser::read_ini(g_usercodeTranslateFile, ptr);
  360. tag = ptr.get_child("UserCodeToMsgTip");
  361. std::string tipMsg = tag.get<std::string>(userCodeStr);
  362. return std::make_pair(userCode, UtfToGbk(tipMsg.c_str()));
  363. }
  364. catch (std::exception &e) {
  365. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ini_parse failed, reason:%s", e.what());
  366. }
  367. return std::make_pair(userCode, srcMsg);
  368. }
  369. std::string hexdumpToString(const char* buf, const int num)
  370. {
  371. char str[8192 * 2] = { 0 };
  372. int i = 0;
  373. char c[5] = { 0 };
  374. if (num > 100)
  375. {
  376. for (i = 0; i < 50; i++)
  377. {
  378. sprintf(c, "%02X ", (unsigned char)buf[i]);
  379. strcat(str, c);
  380. }
  381. return CSimpleStringA::Format("buffer too long to show!show pre 50 hex! CSocketClient hex buf len = %d : %s", num, str).GetData();
  382. }
  383. for (i = 0; i < num; i++)
  384. {
  385. sprintf(c, "%02X ", (unsigned char)buf[i]);
  386. strcat(str, c);
  387. }
  388. return CSimpleStringA::Format("CSocketClient hex buf len = %d : %s", num, str).GetData();
  389. }
  390. void hexdump(const char* buf, const int num) {
  391. auto hexStr = hexdumpToString(buf, num);
  392. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)(hexStr.c_str());
  393. }
  394. bool modifyBySpecialStr(std::wstring& src)
  395. {
  396. #if 0
  397. clock_t cur = clock();
  398. std::set<wchar_t> srcArr;
  399. static std::set<wchar_t> compareArr;
  400. for (auto it = src.begin(); it != src.end(); it++)
  401. srcArr.insert(*it);
  402. if (compareArr.size() == 0)
  403. {
  404. for (auto it = specialStr.begin(); it != specialStr.end(); it++)
  405. compareArr.insert(*it);
  406. }
  407. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr insert cost:%d", clock() - cur);
  408. cur = clock();
  409. std::set<wchar_t> result;
  410. std::set_intersection(std::begin(srcArr), std::end(srcArr), std::begin(compareArr), std::end(compareArr), std::inserter(result, std::begin(result)));
  411. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr intersection cost:%d", clock() - cur);
  412. cur = clock();
  413. if (result.size() == 0)
  414. return false;
  415. for (auto it = result.begin(); it != result.end(); it++)
  416. {
  417. int pos = 0;
  418. for (int pos = 0; pos < src.length();)
  419. {
  420. pos = src.find(*it, pos);
  421. if (pos < 0)
  422. break;
  423. if (pos + 1 < src.length() && src[pos + 1] == '\\')
  424. src.erase(pos + 1, 1);
  425. else
  426. pos++;
  427. }
  428. }
  429. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr modify cost:%d", clock() - cur);
  430. cur = clock();
  431. return true;
  432. #endif
  433. clock_t cur = clock();
  434. wchar_t specialone = L'碶';
  435. if (src.find(specialone, 0) == -1)
  436. return false;
  437. int pos = 0;
  438. for (int pos = 0; pos < src.length();)
  439. {
  440. pos = src.find(specialone, pos);
  441. if (pos < 0)
  442. break;
  443. if (pos + 1 < src.length() && src[pos + 1] == '\\')
  444. src.erase(pos + 1, 1);
  445. else
  446. pos++;
  447. }
  448. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr modify cost:%d", clock() - cur);
  449. return true;
  450. }
  451. #include <boost/stacktrace.hpp>
  452. #if (defined _WIN32 || defined _WIN64)
  453. long WINAPI printSEG(struct _EXCEPTION_POINTERS* ExceptionInfo)
  454. #else
  455. long printSEG()
  456. #endif
  457. {
  458. auto dumpArr = boost::stacktrace::stacktrace().as_vector();
  459. if (dumpArr.size() > 20)
  460. {
  461. for (auto i = 0; i < 10; i++)
  462. 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());
  463. for (auto i = dumpArr.size() - 10; i < dumpArr.size(); i++)
  464. 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());
  465. }
  466. else
  467. {
  468. for (auto i = 0; i < dumpArr.size(); i++)
  469. 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());
  470. }
  471. return 0;
  472. }
  473. //singal,退出函数
  474. #if (defined _WIN32 || defined _WIN64)
  475. #else
  476. #include <signal.h> // ::signal, ::raise
  477. #include <boost/stacktrace.hpp>
  478. #include "CModTools.h"
  479. #include "CWebsocketServer.h"
  480. #include <winpr/sysinfo.h>
  481. #include <winpr/timezone.h>
  482. std::string g_backtracePath = "";
  483. void seg_signal_handler(int signum)
  484. {
  485. //boost::stacktrace::safe_dump_to(g_backtracePath.c_str());
  486. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, seg_signal_handler", signum);
  487. printSEG();
  488. Chromium::CModTools::get_mutable_instance().killAllChromium();
  489. Chromium::CWebsocketServer::stopServer();
  490. signal(signum, SIG_DFL);
  491. raise(signum);
  492. }
  493. void normal_signal_handle(int signum)
  494. {
  495. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, normal_signal_handle", signum);
  496. signal(signum, SIG_DFL);
  497. raise(signum);
  498. }
  499. void set_traceback_path(std::string path)
  500. {
  501. g_backtracePath = path + "/mod_chromium/" + generateTimeStr(true) + "_chromium_backtrace.dump";
  502. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set_traceback_path %s", g_backtracePath.c_str());
  503. }
  504. #endif
  505. void receivehexdump(const char* buf, const int num) {
  506. char str[8192 * 2] = { 0 };
  507. int i = 0;
  508. char c[5] = { 0 };
  509. if (num > 100)
  510. {
  511. for (i = 0; i < 50; i++)
  512. {
  513. sprintf(c, "%02X ", (unsigned char)buf[i]);
  514. strcat(str, c);
  515. }
  516. 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);
  517. return;
  518. }
  519. for (i = 0; i < num; i++)
  520. {
  521. sprintf(c, "%02X ", (unsigned char)buf[i]);
  522. strcat(str, c);
  523. }
  524. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receivehexdump hex buf len = %d : %s", num, str);
  525. return;
  526. }
  527. void doWithDebugModeData(const char* strMethod, const char* buf)
  528. {
  529. boost::lock_guard<boost::mutex> lock(g_networkMutex);
  530. if(std::string(strMethod).find("Network.") == 0)
  531. {
  532. /*for example
  533. {
  534. "method": "Network.requestWillBeSent",
  535. "params": {
  536. "documentURL": "https://www.btbtt12.com/",
  537. "frameId": "8F58093A23334B311DB645BA3652E63C",
  538. "hasUserGesture": false,
  539. "initiator": {
  540. "type": "other"
  541. },
  542. "loaderId": "9F7B28B896C791554C69C5985CA92E79",
  543. "request": {
  544. "headers": {
  545. "Referer": "https://www.btbtt12.com/",
  546. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36"
  547. },
  548. "initialPriority": "Low",
  549. "method": "GET",
  550. "mixedContentType": "none",
  551. "referrerPolicy": "no-referrer-when-downgrade",
  552. "url": "https://pic.picnewsss.com/tu-2022290039/960-60.gif"
  553. },
  554. "requestId": "18476.34",
  555. "timestamp": 19338.811603,
  556. "type": "Image",
  557. "wallTime": 1666099893.800733
  558. }
  559. }
  560. */
  561. std::shared_ptr<cJSON> pJson(cJSON_Parse(buf), [](cJSON* p) {
  562. if (nullptr != p)
  563. cJSON_Delete(p);
  564. });
  565. auto paramsItem = cJSON_GetObjectItem(pJson.get(), "params");
  566. if (paramsItem == nullptr)
  567. return;
  568. auto requestIdItem = cJSON_GetObjectItem(paramsItem, "requestId");
  569. if (requestIdItem == nullptr)
  570. return;
  571. std::string requestId_str = requestIdItem->valuestring;
  572. /*
  573. ['Network.loadingFailed', 'Network.loadingFinished', 'Network.resourceChangedPriority',
  574. 'Network.requestServedFromCache', 'Network.requestWillBeSent', 'Network.requestWillBeSentExtraInfo',
  575. 'Network.responseReceived', 'Network.responseReceivedExtraInfo', 'Network.dataReceived',
  576. 'Page.frameAttached', 'Page.frameRequestedNavigation', 'Page.frameStoppedLoading',
  577. 'Page.frameClearedScheduledNavigation', 'Page.loadEventFired', 'Page.frameStartedLoading',
  578. 'Page.frameDetached', 'Page.frameScheduledNavigation', 'Page.frameNavigated', 'Page.frameResized',
  579. 'Page.domContentEventFired']
  580. */
  581. if(std::string(strMethod) == "Network.loadingFinished")
  582. {
  583. if (g_networkParse.find(requestId_str) != g_networkParse.end())
  584. g_networkParse.erase(requestId_str);
  585. if (g_networkExpiredData.find(requestId_str) != g_networkExpiredData.end())
  586. g_networkExpiredData.erase(requestId_str);
  587. if (g_networkExpiredData.size() < 30)
  588. return;
  589. for(auto it = g_networkExpiredData.begin(); it != g_networkExpiredData.end();)
  590. {
  591. if((clock() - it -> second) < 100000)
  592. {
  593. it++;
  594. continue;
  595. }
  596. if (g_networkParse.find(it->first) != g_networkParse.end())
  597. g_networkParse.erase(it->first);
  598. g_networkExpiredData.erase(it++);
  599. }
  600. }
  601. else if(std::string(strMethod) == "Network.loadingFailed"
  602. || std::string(strMethod) == "Network.webSocketFrameError"
  603. || std::string(strMethod) == "Network.requestServedFromCache")
  604. {
  605. if (g_networkParse.find(requestId_str) != g_networkParse.end())
  606. {
  607. for(auto it = g_networkParse[requestId_str].begin(); it != g_networkParse[requestId_str].end(); it++)
  608. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402402Z00001").setResultMsg(it->c_str())();
  609. g_networkParse.erase(requestId_str);
  610. }
  611. else//此时,上一轮记录已结束
  612. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402402Z00001").setResultMsg(buf)();
  613. if (g_networkExpiredData.find(requestId_str) != g_networkExpiredData.end())
  614. g_networkExpiredData.erase(requestId_str);
  615. }
  616. else
  617. {
  618. if (g_networkParse.find(requestId_str) != g_networkParse.end())
  619. g_networkParse[requestId_str].push_back(buf);
  620. else
  621. {
  622. std::vector<std::string> tmp;
  623. tmp.push_back(buf);
  624. g_networkParse[requestId_str] = tmp;
  625. g_networkExpiredData[requestId_str] = clock();
  626. }
  627. }
  628. }
  629. if (std::string(strMethod) == "Network.webSocketFrameError" ||
  630. std::string(strMethod) == "Network.loadingFailed" ||
  631. std::string(strMethod) == "Runtime.exceptionThrown")
  632. {
  633. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_CHROMIUM_OPENWEBWARN, buf);
  634. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402402Z00002").setResultMsg(buf)();
  635. }
  636. }
  637. std::pair<bool, CSimpleStringA> json_deal::getStringFromCjsonObj(void* object, const char* name)
  638. {
  639. if (object == NULL)
  640. return std::make_pair(false, "");
  641. auto curNode = cJSON_GetObjectItem((cJSON*)object, name);
  642. if (curNode && curNode->type == cJSON_String) {
  643. return std::make_pair(true, curNode->valuestring);
  644. }
  645. else
  646. return std::make_pair(false, "");
  647. }
  648. std::pair<bool, int> json_deal::getIntergerFromCjsonObj(void* object, const char* name)
  649. {
  650. if (object == NULL)
  651. return std::make_pair(false, 0);
  652. auto curNode = cJSON_GetObjectItem((cJSON*)object, name);
  653. if (curNode && curNode->type == cJSON_Number) {
  654. return std::make_pair(true, curNode->valueint);
  655. }
  656. else
  657. return std::make_pair(false, 0);
  658. }
  659. std::pair<bool, double> json_deal::getDoubleFromCjsonObj(void* object, const char* name)
  660. {
  661. if (object == NULL)
  662. return std::make_pair(false, 0);
  663. auto curNode = cJSON_GetObjectItem((cJSON*)object, name);
  664. if (curNode && curNode->type == cJSON_Number) {
  665. return std::make_pair(true, curNode->valuedouble);
  666. }
  667. else
  668. return std::make_pair(false, 0);
  669. }
  670. SM2_Encrypt_Manager::SM2_Encrypt_Manager()
  671. :m_public_key_buf_len(DEFAULT_KEY_LEN),
  672. m_private_key_buf_len(DEFAULT_KEY_LEN),
  673. m_opposite_public_key_buf_len(DEFAULT_KEY_LEN)
  674. {
  675. memset(m_public_key_buf, 0, DEFAULT_KEY_LEN);
  676. memset(m_private_key_buf, 0, DEFAULT_KEY_LEN);
  677. memset(m_opposite_public_key_buf, 0, DEFAULT_KEY_LEN);
  678. GenerateSM2_key(m_public_key, m_private_key);
  679. m_state = SM2ProtocolState::WAIT_KEY_EXCHANGE;
  680. }
  681. SM2_Encrypt_Manager::~SM2_Encrypt_Manager()
  682. {
  683. }
  684. bool SM2_Encrypt_Manager::GenerateSM2_key(std::string& pub, std::string& pri)
  685. {
  686. if (!::CreateSM2KeyPair(m_public_key_buf, &m_public_key_buf_len, m_private_key_buf, &m_private_key_buf_len))
  687. return false;
  688. pub = binToHex(m_public_key_buf, m_public_key_buf_len);
  689. pri = binToHex(m_private_key_buf, m_private_key_buf_len);
  690. return true;
  691. }
  692. std::string SM2_Encrypt_Manager::binToHex(const unsigned char* data, int len)
  693. {
  694. std::string hexString;
  695. // 使用 boost::algorithm::hex 进行编码
  696. boost::algorithm::hex(data, data + len, std::back_inserter(hexString));
  697. return hexString;
  698. }
  699. void SM2_Encrypt_Manager::hexToBin(const std::string& hexStr, unsigned char* binData, int& binLen)
  700. {
  701. binLen = hexStr.size() / 2;
  702. if (binData == nullptr) {
  703. // 如果 binData 为 nullptr,仅返回计算出的 binLen,不执行实际的转换
  704. return;
  705. }
  706. // 使用 boost::algorithm::unhex 进行解码
  707. boost::algorithm::unhex(hexStr.begin(), hexStr.end(), binData);
  708. }
  709. void SM2_Encrypt_Manager::setOpposite(const std::string pub)
  710. {
  711. m_opposite_public_key = pub;
  712. hexToBin(m_opposite_public_key, m_opposite_public_key_buf, m_opposite_public_key_buf_len);
  713. }
  714. std::pair<bool, std::string> SM2_Encrypt_Manager::checkSM2Enable()
  715. {
  716. if (m_public_key.length() == 0)
  717. return std::make_pair(false, "public_key is empty");
  718. if (m_private_key.length() == 0)
  719. return std::make_pair(false, "private_key is empty");
  720. if (m_opposite_public_key.length() == 0)
  721. return std::make_pair(false, "opposite public_key is empty");
  722. return std::make_pair(true, "");
  723. }
  724. std::pair<std::string, std::string> SM2_Encrypt_Manager::EncryptMsg(std::string msg)
  725. {
  726. unsigned char sign[DEFAULT_KEY_LEN] = "";
  727. int sign_len = DEFAULT_KEY_LEN;
  728. unsigned char* dstMsg = new unsigned char[msg.length() * 2];
  729. int dstMsgLen = msg.length() * 2;
  730. std::shared_ptr<void> msgClean((void*)0, [&](void*) {
  731. if (dstMsg)
  732. {
  733. delete[]dstMsg;
  734. dstMsg = nullptr;
  735. }
  736. });
  737. if (!SM2SignWithSM3(m_private_key_buf, m_private_key_buf_len, (unsigned char*)msg.c_str(), msg.length(), sign, &sign_len))
  738. {
  739. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SM2SignWithSM3::err, can not sign msg");
  740. return std::make_pair("", "");
  741. }
  742. if(!EncWithSM2PubKey((unsigned char*)msg.c_str(), msg.length(), dstMsg, &dstMsgLen, m_opposite_public_key_buf, m_opposite_public_key_buf_len))
  743. {
  744. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("EncWithSM2PubKey::err, can not encrypt msg");
  745. return std::make_pair("", "");
  746. }
  747. return std::make_pair(binToHex(sign, sign_len), binToHex(dstMsg, dstMsgLen));
  748. }
  749. std::pair<bool, std::string> SM2_Encrypt_Manager::DecryptMsg(std::string sign, std::string msg)
  750. {
  751. 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
  752. int binMsgLen = msg.length(), outMsgLen = msg.length() * 2, signLen = sign.length();
  753. std::shared_ptr<void> msgClean((void*)0, [&](void*) {
  754. if (binMsg) {
  755. delete[] binMsg;
  756. binMsg = nullptr;
  757. }
  758. if (outMsg) {
  759. delete[] outMsg;
  760. outMsg = nullptr;
  761. }
  762. if (binSign) {
  763. delete[] binSign;
  764. binSign = nullptr;
  765. }
  766. });
  767. hexToBin(msg, binMsg, binMsgLen);
  768. hexToBin(sign, binSign, signLen);
  769. if (!DecWithSM2PriKey(binMsg, binMsgLen, outMsg, &outMsgLen, m_private_key_buf, m_private_key_buf_len))
  770. return std::make_pair(false, "DecWithSM2PriKey::err, can not dectrypt msg");
  771. if (!SM2VerifyWithSM3(m_opposite_public_key_buf, m_opposite_public_key_buf_len, outMsg, outMsgLen, binSign, signLen))
  772. return std::make_pair(false, "SM2VerifyWithSM3::err, can not verify sign");
  773. return std::make_pair(true, (char*)outMsg);
  774. }
  775. std::pair<bool, std::string> SM2_Encrypt_Manager::GenerateEncPubKey()
  776. {
  777. if(!verifySM2Manager())
  778. return std::make_pair(false, "GenerateEncPubKey::verifySM2Manager err");
  779. unsigned char encPubKey[DEFAULT_KEY_LEN] = "";
  780. int encPubKey_len = DEFAULT_KEY_LEN;
  781. 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))
  782. return std::make_pair(false, "GenerateEncPubKey::EncWithSM2PubKey err");
  783. return std::make_pair(true, binToHex(encPubKey, encPubKey_len));
  784. }
  785. bool SM2_Encrypt_Manager::verifySM2Manager()
  786. {
  787. if (m_opposite_public_key.length() == 0 || m_public_key.length() == 0 || m_private_key.length() == 0)
  788. return false;
  789. if (m_opposite_public_key_buf == NULL || m_public_key_buf == NULL || m_private_key_buf == NULL)
  790. return false;
  791. return true;
  792. }
  793. #ifdef RVC_OS_LINUX
  794. std::vector<int> getUosBrowserPIDs(int UseUOSBrowser)
  795. {
  796. std::vector<int> pids;
  797. FILE* fp = nullptr;
  798. if(UseUOSBrowser == 1)
  799. fp = popen("ps -ef | grep uosbrowser | grep -v grep | awk '{print $2}'", "r");
  800. else if(UseUOSBrowser == 2)
  801. fp = popen("ps -ef | grep browser | grep -v grep | awk '{print $2}'", "r");
  802. if (fp) {
  803. char buffer[256];
  804. while (fgets(buffer, sizeof(buffer), fp) != NULL) {
  805. pids.push_back(static_cast<pid_t>(std::atoi(buffer)));
  806. }
  807. pclose(fp);
  808. }
  809. return pids;
  810. }
  811. #endif
  812. ConfigManager& ConfigManager::getInstance() {
  813. static ConfigManager instance;
  814. return instance;
  815. }
  816. ConfigManager::ConfigManager()
  817. : m_iTcpBridgePort(4504), m_strCustomMainUrl(""), m_strCustomAdUrl(""), m_runAd(false), m_runMain(false), m_runExtend(false), m_runLogin(false), m_withBrowser(false), m_withMin(false), m_withClose(false)
  818. , m_withDebugMode(false), m_withMagic(false), m_withNoFileLog(false), m_installMode(false), m_withMedia(false), m_withSpecialTest(false), m_withConsole(false),
  819. m_withLinkLog(false), m_withUnsafeAd(false), m_noStartupPage(false), m_extension_debugOpen(false), m_extension_withTerminal(false)
  820. {
  821. void* logProducer = nullptr;
  822. std::map<std::string, void*> g_logProducerArr;
  823. bool g_useMagic = false;
  824. bool g_loggerInitSuccess = false;
  825. bool g_withSpecialTest = false;
  826. bool g_hasInitCfg = false;//can discard
  827. int g_sogouForce = 0;
  828. m_extensionPath = "";
  829. }
  830. LogManager& LogManager::getInstance() {
  831. static LogManager instance;
  832. return instance;
  833. }
  834. void LogManager::logWebSocketBuild(int64_t hdl, const std::string& url, const std::string& isSecurity) {
  835. Json::Value log;
  836. log["hdl"] = hdl;
  837. log["78173721_logType"] = "ws_build";
  838. Json::Value detail;
  839. detail["url"] = url;
  840. detail["isSecurity"] = isSecurity;
  841. log["detail"] = detail;
  842. log["timestamp"] = getCurrentTimestamp();
  843. log["threadId"] = Json::Int64(GetCurrentThreadId());
  844. writeLog(log);
  845. }
  846. void LogManager::writeLog(const Json::Value& log) {
  847. Json::FastWriter writer;
  848. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)(writer.write(log).c_str());
  849. }
  850. std::string LogManager::getCurrentTimestamp() {
  851. /*
  852. FILETIME ft;
  853. SYSTEMTIME st;
  854. GetSystemTime(&st);
  855. SystemTimeToFileTime(&st, &ft);
  856. FILETIME utc_ft, local_ft;
  857. #ifdef _WIN32
  858. utc_ft.dwLowDateTime = (DWORD)ft.dwLowDateTime;
  859. utc_ft.dwHighDateTime = (DWORD)ft.dwHighDateTime;
  860. FileTimeToLocalFileTime(&utc_ft, &local_ft);
  861. FileTimeToSystemTime(&local_ft, &st);
  862. #else
  863. GetLocalTime(&st);
  864. #endif // _WIN32
  865. */
  866. using namespace std::chrono;
  867. auto now = system_clock::now();
  868. auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
  869. auto timer = system_clock::to_time_t(now);
  870. std::ostringstream oss;
  871. oss << std::put_time(std::localtime(&timer), "%Y-%m-%d %H:%M:%S")
  872. << '.' << std::setfill('0') << std::setw(3) << ms.count();
  873. return oss.str();
  874. }
  875. void LogManager::logWebSocketBeginSession(int64_t hdl,
  876. int64_t web_transID,
  877. int64_t inner_transID,
  878. const std::string& entity,
  879. const std::string& entityClass,
  880. int ret,
  881. const std::string& operate,
  882. const std::string& payload,
  883. int retDetail,
  884. const std::string& reason) {
  885. Json::Value log;
  886. log["hdl"] = hdl;
  887. log["78173721_logType"] = "ws_beginSession";
  888. Json::Value detail;
  889. detail["web_transID"] = web_transID;
  890. detail["inner_transID"] = inner_transID;
  891. detail["entity"] = entity;
  892. detail["class"] = entityClass;
  893. detail["ret"] = ret;
  894. detail["retDetail"] = retDetail;
  895. detail["reason"] = reason;
  896. detail["operate"] = operate;
  897. #ifdef OUTPUT_DETAIL_LOG
  898. detail["payload"] = payload;
  899. #endif
  900. log["detail"] = detail;
  901. log["timestamp"] = getCurrentTimestamp();
  902. log["threadId"] = Json::Int64(GetCurrentThreadId());
  903. writeLog(log);
  904. }
  905. void LogManager::logWebSocketClose(int64_t hdl) {
  906. Json::Value log;
  907. log["hdl"] = hdl;
  908. log["78173721_logType"] = "ws_close";
  909. log["timestamp"] = getCurrentTimestamp();
  910. log["threadId"] = Json::Int64(GetCurrentThreadId());
  911. writeLog(log);
  912. }
  913. void LogManager::logWebSocketInfo(int64_t hdl,
  914. int64_t web_transID,
  915. int64_t sessionId,
  916. const std::string& entity,
  917. const std::string& function,
  918. int ret,
  919. const std::string& operate,
  920. int retDetail,
  921. const std::string& reason,
  922. const std::string& payload) {
  923. Json::Value log;
  924. log["hdl"] = Json::Int64(hdl);
  925. log["78173721_logType"] = "ws_info";
  926. Json::Value detail;
  927. detail["web_transID"] = Json::Int64(web_transID);
  928. detail["sessionId"] = Json::Int64(sessionId);
  929. detail["entity"] = entity;
  930. detail["function"] = function;
  931. detail["ret"] = ret;
  932. detail["operate"] = operate;
  933. detail["retDetail"] = retDetail;
  934. detail["reason"] = reason;
  935. #ifdef OUTPUT_DETAIL_LOG
  936. detail["payload"] = payload;
  937. #endif
  938. log["detail"] = detail;
  939. log["timestamp"] = getCurrentTimestamp();
  940. log["threadId"] = Json::Int64(GetCurrentThreadId());
  941. writeLog(log);
  942. }
  943. void LogManager::logWebSocketRegister(int64_t hdl,
  944. int64_t web_transID,
  945. int64_t inner_transID,
  946. const std::string& entity,
  947. const std::string& entityClass,
  948. int ret,
  949. const std::string& operate,
  950. const std::string& payload,
  951. int retDetail,
  952. const std::string& reason) {
  953. Json::Value log;
  954. log["hdl"] = Json::Int64(hdl);
  955. log["78173721_logType"] = "ws_register";
  956. Json::Value detail;
  957. detail["web_transID"] = Json::Int64(web_transID);
  958. detail["inner_transID"] = Json::Int64(inner_transID);
  959. detail["entity"] = entity;
  960. detail["class"] = entityClass;
  961. detail["ret"] = ret;
  962. detail["operate"] = operate;
  963. #ifdef OUTPUT_DETAIL_LOG
  964. detail["payload"] = payload;
  965. #endif
  966. detail["retDetail"] = retDetail;
  967. detail["reason"] = reason;
  968. log["detail"] = detail;
  969. log["timestamp"] = getCurrentTimestamp();
  970. log["threadId"] = Json::Int64(GetCurrentThreadId());
  971. writeLog(log);
  972. }
  973. void LogManager::logWebSocketRequest(int64_t hdl,
  974. int64_t web_transID,
  975. int64_t inner_transID,
  976. int64_t sessionId,
  977. const std::string& entity,
  978. const std::string& function,
  979. int ret,
  980. const std::string& operate,
  981. const std::string& payload,
  982. int retDetail,
  983. const std::string& reason) {
  984. Json::Value log;
  985. log["hdl"] = Json::Int64(hdl);
  986. log["78173721_logType"] = "ws_request";
  987. Json::Value detail;
  988. detail["web_transID"] = Json::Int64(web_transID);
  989. detail["inner_transID"] = Json::Int64(inner_transID);
  990. detail["sessionId"] = Json::Int64(sessionId);
  991. detail["entity"] = entity;
  992. detail["function"] = function;
  993. detail["ret"] = ret;
  994. detail["operate"] = operate;
  995. detail["retDetail"] = retDetail;
  996. detail["reason"] = reason;
  997. #ifdef OUTPUT_DETAIL_LOG
  998. detail["payload"] = payload;
  999. #endif
  1000. log["detail"] = detail;
  1001. log["timestamp"] = getCurrentTimestamp();
  1002. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1003. writeLog(log);
  1004. }
  1005. void LogManager::logWebSocketSetVar(int64_t hdl,
  1006. int64_t web_transID,
  1007. int64_t inner_transID,
  1008. const std::string& name,
  1009. const std::string& value,
  1010. int ret,
  1011. const std::string& operate,
  1012. const std::string& payload,
  1013. int retDetail,
  1014. const std::string& reason) {
  1015. Json::Value log;
  1016. log["hdl"] = Json::Int64(hdl);
  1017. log["78173721_logType"] = "ws_setvar";
  1018. Json::Value detail;
  1019. detail["web_transID"] = Json::Int64(web_transID);
  1020. detail["inner_transID"] = Json::Int64(inner_transID);
  1021. detail["name"] = name;
  1022. detail["value"] = value;
  1023. detail["ret"] = ret;
  1024. detail["operate"] = operate;
  1025. detail["retDetail"] = retDetail;
  1026. detail["reason"] = reason;
  1027. #ifdef OUTPUT_DETAIL_LOG
  1028. detail["payload"] = payload;
  1029. #endif
  1030. log["detail"] = detail;
  1031. log["timestamp"] = getCurrentTimestamp();
  1032. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1033. writeLog(log);
  1034. }
  1035. void LogManager::logWebSocketGetVar(int64_t hdl,
  1036. int64_t web_transID,
  1037. int64_t inner_transID,
  1038. const std::string& name,
  1039. int ret,
  1040. const std::string& operate,
  1041. const std::string& payload,
  1042. int retDetail,
  1043. const std::string& reason) {
  1044. Json::Value log;
  1045. log["hdl"] = Json::Int64(hdl);
  1046. log["78173721_logType"] = "ws_getvar";
  1047. Json::Value detail;
  1048. detail["web_transID"] = Json::Int64(web_transID);
  1049. detail["inner_transID"] = Json::Int64(inner_transID);
  1050. detail["name"] = name;
  1051. detail["ret"] = ret;
  1052. detail["operate"] = operate;
  1053. detail["retDetail"] = retDetail;
  1054. detail["reason"] = reason;
  1055. #ifdef OUTPUT_DETAIL_LOG
  1056. detail["payload"] = payload;
  1057. #endif
  1058. log["detail"] = detail;
  1059. log["timestamp"] = getCurrentTimestamp();
  1060. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1061. writeLog(log);
  1062. }
  1063. void LogManager::logWebSocketBroadcast(int64_t hdl,
  1064. const std::string& entity,
  1065. int ret,
  1066. const std::string& operate,
  1067. const std::string& payload,
  1068. int retDetail,
  1069. const std::string& reason) {
  1070. Json::Value log;
  1071. log["hdl"] = Json::Int64(hdl);
  1072. log["78173721_logType"] = "ws_broadcast";
  1073. Json::Value detail;
  1074. detail["entity"] = entity;
  1075. detail["ret"] = ret;
  1076. detail["operate"] = operate;
  1077. detail["retDetail"] = retDetail;
  1078. detail["reason"] = reason;
  1079. #ifdef OUTPUT_DETAIL_LOG
  1080. detail["payload"] = payload;
  1081. #endif
  1082. log["detail"] = detail;
  1083. log["timestamp"] = getCurrentTimestamp();
  1084. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1085. writeLog(log);
  1086. }
  1087. void LogManager::logVtmEndSession(int64_t hdl,
  1088. const std::string& entity,
  1089. int64_t sessionId,
  1090. int ret,
  1091. const std::string& operate,
  1092. const std::string& payload,
  1093. int retDetail,
  1094. const std::string& reason) {
  1095. Json::Value log;
  1096. log["hdl"] = Json::Int64(hdl);
  1097. log["78173721_logType"] = "vtm_endsession";
  1098. Json::Value detail;
  1099. detail["entity"] = entity;
  1100. detail["sessionId"] = Json::Int64(sessionId);
  1101. detail["ret"] = ret;
  1102. detail["operate"] = operate;
  1103. detail["retDetail"] = retDetail;
  1104. detail["reason"] = reason;
  1105. #ifdef OUTPUT_DETAIL_LOG
  1106. detail["payload"] = payload;
  1107. #endif
  1108. log["detail"] = detail;
  1109. log["timestamp"] = getCurrentTimestamp();
  1110. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1111. writeLog(log);
  1112. }
  1113. void LogManager::logVtmRequestAck(int64_t hdl,
  1114. int64_t web_transID,
  1115. int64_t inner_transID,
  1116. int64_t sessionId,
  1117. const std::string& entity,
  1118. const std::string& function,
  1119. int ret,
  1120. const std::string& operate,
  1121. const std::string& payload,
  1122. const std::string& srcByte,
  1123. int retDetail,
  1124. const std::string& reason) {
  1125. Json::Value log;
  1126. log["hdl"] = Json::Int64(hdl);
  1127. log["78173721_logType"] = "vtm_requestAck";
  1128. Json::Value detail;
  1129. detail["web_transID"] = Json::Int64(web_transID);
  1130. detail["inner_transID"] = Json::Int64(inner_transID);
  1131. detail["sessionId"] = Json::Int64(sessionId);
  1132. detail["entity"] = entity;
  1133. detail["function"] = function;
  1134. detail["ret"] = ret;
  1135. detail["operate"] = operate;
  1136. #ifdef OUTPUT_DETAIL_LOG
  1137. detail["payload"] = payload;
  1138. detail["srcByte"] = srcByte;
  1139. #endif
  1140. detail["retDetail"] = retDetail;
  1141. detail["reason"] = reason;
  1142. log["detail"] = detail;
  1143. log["timestamp"] = getCurrentTimestamp();
  1144. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1145. writeLog(log);
  1146. }
  1147. void LogManager::logVtmEvent(int64_t hdl,
  1148. int64_t inner_transID,
  1149. int64_t sessionId,
  1150. const std::string& entity,
  1151. int ret,
  1152. const std::string& operate,
  1153. const std::vector<std::pair<int, int>>& transIdAndhdl_arr,
  1154. const std::string& payload,
  1155. const std::string& srcByte,
  1156. int retDetail,
  1157. const std::string& reason) {
  1158. Json::Value log;
  1159. log["hdl"] = Json::Int64(hdl);
  1160. log["78173721_logType"] = "vtm_event";
  1161. Json::Value detail;
  1162. detail["inner_transID"] = Json::Int64(inner_transID);
  1163. detail["sessionId"] = Json::Int64(sessionId);
  1164. detail["entity"] = entity;
  1165. detail["ret"] = ret;
  1166. detail["operate"] = operate;
  1167. Json::Value transIdAndhdl_json(Json::arrayValue);
  1168. for (const auto& pair : transIdAndhdl_arr) {
  1169. Json::Value pairJson(Json::objectValue);
  1170. pairJson["transId"] = Json::Int64(pair.first);
  1171. pairJson["hdl"] = Json::Int64(pair.second);
  1172. transIdAndhdl_json.append(pairJson);
  1173. }
  1174. detail["transIdAndhdl_arr"] = transIdAndhdl_json;
  1175. #ifdef OUTPUT_DETAIL_LOG
  1176. detail["payload"] = payload;
  1177. detail["srcByte"] = srcByte;
  1178. #endif
  1179. detail["retDetail"] = retDetail;
  1180. detail["reason"] = reason;
  1181. log["detail"] = detail;
  1182. log["timestamp"] = getCurrentTimestamp();
  1183. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1184. writeLog(log);
  1185. }
  1186. void LogManager::logVtmSessionAck(int64_t hdl,
  1187. int64_t web_transID,
  1188. int64_t inner_transID,
  1189. int64_t sessionId,
  1190. const std::string& entity,
  1191. int ret,
  1192. const std::string& operate,
  1193. const std::string& payload,
  1194. const std::string& srcByte,
  1195. int retDetail,
  1196. const std::string& reason) {
  1197. Json::Value log;
  1198. log["hdl"] = Json::Int64(hdl);
  1199. log["78173721_logType"] = "vtm_sessionAck";
  1200. Json::Value detail;
  1201. detail["web_transID"] = Json::Int64(web_transID);
  1202. detail["inner_transID"] = Json::Int64(inner_transID);
  1203. detail["sessionId"] = Json::Int64(sessionId);
  1204. detail["entity"] = entity;
  1205. detail["ret"] = ret;
  1206. detail["operate"] = operate;
  1207. #ifdef OUTPUT_DETAIL_LOG
  1208. detail["payload"] = payload;
  1209. detail["srcByte"] = srcByte;
  1210. #endif
  1211. detail["retDetail"] = retDetail;
  1212. detail["reason"] = reason;
  1213. log["detail"] = detail;
  1214. log["timestamp"] = getCurrentTimestamp();
  1215. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1216. writeLog(log);
  1217. }
  1218. void LogManager::logWsLogEvent(
  1219. int64_t hdl,
  1220. int securityLevel,
  1221. int eventCode,
  1222. const std::string& message,
  1223. int ret,
  1224. const std::string& operate,
  1225. const std::string& payload,
  1226. int retDetail,
  1227. const std::string& reason
  1228. ) {
  1229. Json::Value log;
  1230. log["hdl"] = Json::Int64(hdl);
  1231. log["78173721_logType"] = "ws_logEvent";
  1232. Json::Value detail;
  1233. detail["securityLevel"] = securityLevel;
  1234. detail["eventCode"] = eventCode;
  1235. detail["message"] = message;
  1236. detail["ret"] = ret;
  1237. detail["operate"] = operate;
  1238. detail["retDetail"] = retDetail;
  1239. detail["reason"] = reason;
  1240. #ifdef OUTPUT_DETAIL_LOG
  1241. detail["payload"] = payload;
  1242. #endif
  1243. log["detail"] = detail;
  1244. log["timestamp"] = getCurrentTimestamp();
  1245. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1246. writeLog(log);
  1247. }
  1248. void LogManager::logWsLogWarn(
  1249. int64_t hdl,
  1250. int securityLevel,
  1251. int eventCode,
  1252. const std::string& message,
  1253. int ret,
  1254. const std::string& operate,
  1255. const std::string& payload,
  1256. int retDetail,
  1257. const std::string& reason
  1258. ) {
  1259. Json::Value log;
  1260. log["hdl"] = Json::Int64(hdl);
  1261. log["78173721_logType"] = "ws_logWarn";
  1262. Json::Value detail;
  1263. detail["securityLevel"] = securityLevel;
  1264. detail["eventCode"] = eventCode;
  1265. detail["ret"] = ret;
  1266. detail["operate"] = operate;
  1267. detail["retDetail"] = retDetail;
  1268. detail["reason"] = reason;
  1269. #ifdef OUTPUT_DETAIL_LOG
  1270. detail["payload"] = payload;
  1271. detail["message"] = message;
  1272. #endif
  1273. log["detail"] = detail;
  1274. log["timestamp"] = getCurrentTimestamp();
  1275. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1276. writeLog(log);
  1277. }
  1278. void LogManager::logEntityOnLog(
  1279. const std::string& entity,
  1280. int64_t usercode,
  1281. const std::string& usercodeStr,
  1282. int ret,
  1283. const std::string& operate,
  1284. int retDetail,
  1285. const std::string& reason
  1286. ) {
  1287. Json::Value log;
  1288. log["78173721_logType"] = "entity_onlog";
  1289. Json::Value detail;
  1290. detail["entity"] = entity;
  1291. detail["usercode"] = Json::Int64(usercode);
  1292. detail["usercodeStr"] = usercodeStr;
  1293. detail["ret"] = ret;
  1294. detail["operate"] = operate;
  1295. detail["retDetail"] = retDetail;
  1296. detail["reason"] = reason;
  1297. log["detail"] = detail;
  1298. log["timestamp"] = getCurrentTimestamp();
  1299. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1300. writeLog(log);
  1301. }
  1302. void LogManager::logEntityBegin(int no_startup) {
  1303. Json::Value log;
  1304. log["78173721_logType"] = "entity_begin";
  1305. Json::Value detail;
  1306. detail["no_startup"] = no_startup;
  1307. log["detail"] = detail;
  1308. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1309. log["timestamp"] = getCurrentTimestamp();
  1310. writeLog(log);
  1311. }
  1312. void LogManager::logEntityOpenPage(
  1313. const std::string& pageType,
  1314. int64_t pid,
  1315. int ret,
  1316. const std::string& operate,
  1317. int retDetail,
  1318. const std::string& reason
  1319. ) {
  1320. Json::Value log;
  1321. log["78173721_logType"] = "entity_openPage";
  1322. Json::Value detail;
  1323. detail["pageType"] = pageType;
  1324. detail["pid"] = Json::Int64(pid);
  1325. detail["ret"] = ret;
  1326. detail["operate"] = operate;
  1327. detail["retDetail"] = retDetail;
  1328. detail["reason"] = reason;
  1329. log["detail"] = detail;
  1330. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1331. log["timestamp"] = getCurrentTimestamp();
  1332. writeLog(log);
  1333. }
  1334. void LogManager::logEntityStageChange(
  1335. const std::string& stage,
  1336. int ret,
  1337. const std::string& operate,
  1338. int retDetail,
  1339. const std::string& reason
  1340. ) {
  1341. Json::Value log;
  1342. log["78173721_logType"] = "entity_stageChange";
  1343. Json::Value detail;
  1344. detail["stage"] = stage;
  1345. detail["ret"] = ret;
  1346. detail["operate"] = operate;
  1347. detail["retDetail"] = retDetail;
  1348. detail["reason"] = reason;
  1349. log["detail"] = detail;
  1350. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1351. log["timestamp"] = getCurrentTimestamp();
  1352. writeLog(log);
  1353. }
  1354. void LogManager::logEntityStatus(
  1355. const std::string& status,
  1356. int level,
  1357. int ret,
  1358. const std::string& operate,
  1359. int retDetail,
  1360. const std::string& reason
  1361. ) {
  1362. Json::Value log;
  1363. log["78173721_logType"] = "entity_status";
  1364. Json::Value detail;
  1365. detail["status"] = status;
  1366. detail["level"] = level;
  1367. detail["ret"] = ret;
  1368. detail["operate"] = operate;
  1369. detail["retDetail"] = retDetail;
  1370. detail["reason"] = reason;
  1371. log["detail"] = detail;
  1372. log["threadId"] = Json::Int64(GetCurrentThreadId());
  1373. log["timestamp"] = getCurrentTimestamp();
  1374. writeLog(log);
  1375. }