#include "stdafx.h" #include "baseEx.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "EventCode.h" #include "exLog/log.h" #include "cJSON.h" #include "RVCComm.h" using namespace boost::interprocess; //read ini #include #include #if (defined _WIN32 || defined _WIN64) #define BOOST_INTERPROCESS_SHARED_DIR_PATH "C:\\" #endif void* logProducer = nullptr; std::map g_logProducerArr; bool g_useMagic = false; bool g_loggerInitSuccess = false; bool g_logToFile = true; bool g_withMedia = false; bool g_withConsole = false; bool g_withSpecialTest = false; bool g_withLinkLog = false; bool g_hasInitCfg = false; std::string g_usercodeTranslateFile = ""; std::map> g_networkParse; std::map g_networkExpiredData; std::map g_UserCodeToMsgTip; boost::mutex g_networkMutex; const std::wstring WCHAR_NULL = L""; const std::wstring specialStr = L"乗俓僜刓匼哱圽塡奬媆峔嶾廫慭怽揬昞朶梊榎橽歕沑漒瀄焅燶猏玕琝甛璡痋盶癨瞈砛碶穃竆筡篭糪絓綷縗繺羂耚肻腬臶臷芢蒤薥蚛蝄蟎衆蟎裓覾譢豛赲踈躙輁郳醆鈂鉢鎈鏫閈闬隲頫颸餦馶骪鯸鮘鳿鵟鸤黒齖"; #define NOR_LEN 50 #define MAX_LOG_LEN 4096 #define MAX_CEFLOG_LEN 5120 #if (defined _WIN32 || defined _WIN64) #include std::string UtfToGbk(const char* utf8) { int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); wchar_t* wstr = new wchar_t[len + 1]; memset(wstr, 0, len + 1); MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len); len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL); char* str = new char[len + 1]; memset(str, 0, len + 1); WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL); if (wstr) delete[] wstr; return str; } //GBK转化为UTF8格式 std::string ConvertGBKToUtf8(std::string& strGBK) { int len = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK.c_str(), -1, NULL, 0); wchar_t* wszUtf8 = new wchar_t[len]; memset(wszUtf8, 0, len); MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK.c_str(), -1, wszUtf8, len); len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL); char* szUtf8 = new char[len + 1]; memset(szUtf8, 0, len + 1); WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL); std::string ret = szUtf8; delete[] szUtf8; delete[] wszUtf8; return ret; } #else std::string UtfToGbk(const char* utf8) { return utf8; } std::string ConvertGBKToUtf8(std::string& strGBK) { return strGBK; } #endif struct cefclientLog { LOG_LEVEL_E m_level; LOG_TYPE_E m_type; char m_logTime[NOR_LEN]; char m_filename[NOR_LEN]; int m_filePos; char m_cefLog[MAX_CEFLOG_LEN]; 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) { m_level = t_level; m_type = t_type; strcpy_s(m_logTime, NOR_LEN, t_logTime); strcpy_s(m_filename, NOR_LEN, t_filename); m_filePos = t_filePos; strcpy_s(m_cefLog, MAX_CEFLOG_LEN, t_cefLog); } cefclientLog() :m_level(LOG_LEVEL_DEBUG), m_type(LOG_TYPE_SYSTEM), m_filePos(0) { memset(m_logTime, 0, NOR_LEN); memset(m_filename, 0, NOR_LEN); memset(m_cefLog, 0, MAX_CEFLOG_LEN); } }; #define CEF_GUID "{5ED197CD-9D64-4D10-9839-2A0773B6F5D2}" bool InitFileLogger(std::string dbgPath) { return g_loggerInitSuccess = logger::init(dbgPath.c_str(), "cefLog"); } void DbgToFileLogger(std::string msg) { if(g_loggerInitSuccess) logger::showLog(msg); } void DbgEx(const char* str, ...) { va_list arg; va_start(arg, str); #if (defined _WIN32 || defined _WIN64) int n = _vscprintf(str, arg); char* buf = (char*)malloc(n + 1); vsprintf(buf, str, arg); auto modifyStr = CSimpleString::Format("%s", buf); DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).withExtendLog(g_logToFile).setResultMsg(modifyStr.GetData())(); free(buf); #else auto modifyStr = CSimpleString::Format("%s", str); vDbg(modifyStr.GetData(), arg); #endif va_end(arg); } bool SYSTEM_ON(std::string cmdLine, bool isWait) { #if (defined _WIN32 || defined _WIN64) auto waitSystem = [](const std::string cmd, const std::string par, BOOL nShow) ->DWORD { SHELLEXECUTEINFO ShExecInfo = { 0 }; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = cmd.c_str(); //调用的程序名 ShExecInfo.lpParameters = par.c_str(); //调用程序的命令行参数 ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = nShow ? SW_SHOW : SW_HIDE; //窗口状态为隐藏 ShExecInfo.hInstApp = NULL; if (ShellExecuteEx(&ShExecInfo) && ShExecInfo.hProcess)//如果设置了 SEE_MASK_NOCLOSEPROCESS ,并且调用成功则该值大于32,调用失败者被设置错误值 { //创建进程成功 WaitForSingleObject(ShExecInfo.hProcess, INFINITE); //等到该进程结束 DWORD exitCode = 0; GetExitCodeProcess(ShExecInfo.hProcess, &exitCode); return exitCode; } else { std::string errMsg; auto errorCode = GetLastError(); switch (errorCode) { #define CASE(code) \ case code: \ errMsg = #code; \ break CASE(ERROR_FILE_NOT_FOUND); CASE(ERROR_PATH_NOT_FOUND); CASE(ERROR_DDE_FAIL); CASE(ERROR_NO_ASSOCIATION); CASE(ERROR_ACCESS_DENIED); CASE(ERROR_DLL_NOT_FOUND); CASE(ERROR_CANCELLED); CASE(ERROR_NOT_ENOUGH_MEMORY); CASE(ERROR_SHARING_VIOLATION); default: errMsg = "UNKNOWN"; } 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()); return false; } }; std::string strCmd, strPar; if (isWait) { strPar = std::string("/c ") + cmdLine; strCmd = std::string("cmd ") + strPar; return waitSystem("cmd.exe", strPar, FALSE); } else { strCmd = cmdLine; unsigned int result = WinExec(strCmd.c_str(), SW_HIDE); if (result > 31) return true; else { DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setAPI(__FUNCTION__)("SYSTEM_ON nowait with %s failed, reason:%d", result); return false; } } #else system(cmdLine.c_str()); return true; #endif return false; } DWORD SaveCefclientLog(std::string magicStr) { std::string dstGuid = magicStr + "_" + CEF_GUID; try { auto removeRet = message_queue::remove(dstGuid.c_str()); if (!removeRet) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("message_queue did not remove!"); boost::interprocess::permissions cur; cur.set_unrestricted(); message_queue mq(create_only, dstGuid.c_str(), 100, sizeof(cefclientLog), cur); g_useMagic = true; DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SaveCefclientLog thread begin"); while (true) { cefclientLog t_data; #if (defined _WIN32 || defined _WIN64) unsigned int t_recvSize = 0; #else unsigned long t_recvSize = 0; #endif unsigned int t_priority = 0; mq.receive(&t_data, sizeof(cefclientLog), t_recvSize, t_priority); std::string source = std::string(t_data.m_filename) + "(" + std::to_string((ULONGLONG)t_data.m_filePos) + ")"; #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/ DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(logProducer).setSourceType(source.c_str()).withExtendLog(true).setResultMsg(t_data.m_cefLog)(); #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/ DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(logProducer).setSourceType(source.c_str()).withExtendLog(true).setResultMsg(t_data.m_cefLog)(); #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/ DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(logProducer).setSourceType(source.c_str()).withExtendLog(false).setResultMsg(t_data.m_cefLog)(); #else DbgWithLink(t_data.m_level, t_data.m_type).withLogProducer(logProducer).setSourceType(source.c_str()).withExtendLog(true).setResultMsg(t_data.m_cefLog)(); #endif // DEVOPS if (sizeof(cefclientLog) != t_recvSize) break; /*特么制品库太恶心了 cefclientLog tmp; std::istringstream iss(t_data); boost::archive::binary_iarchive iarchive(iss); iarchive >> tmp;//从一个保存序列化数据的string里面反序列化,从而得到原来的对象 std::string source = tmp.m_filename + "(" + std::to_string((ULONGLONG)tmp.m_filePos) + ")"; DbgWithLink(tmp.m_level, tmp.m_type).setSourceType(source.c_str())(tmp.m_cefLog.c_str()); */ } DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SaveCefclientLog thread end"); } catch (interprocess_exception& ex) { message_queue::remove(dstGuid.c_str()); g_useMagic = false; DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s run exception, for %s", dstGuid.c_str(), ex.what()); return 1; } g_useMagic = false; message_queue::remove(dstGuid.c_str()); return 0; } std::vector find_files(const std::string srcPath, const std::string fileName, bool isDir) { static boost::xpressive::sregex_compiler rc; if (!rc[fileName].regex_id()) { std::string str = boost::algorithm::replace_all_copy( boost::algorithm::replace_all_copy(fileName, ".", "\\."), "*", ".*"); rc[fileName] = rc.compile(str); } std::vector ret; if (!boost::filesystem::exists(srcPath) || !boost::filesystem::is_directory(srcPath)) return ret; typedef boost::filesystem::recursive_directory_iterator rd_iterator; rd_iterator end; for (rd_iterator pos(srcPath); pos != end; ++pos) { if ((isDir ? boost::filesystem::is_directory(*pos) : !boost::filesystem::is_directory(*pos)) && boost::xpressive::regex_match(pos->path().filename().string(), rc[fileName])) ret.emplace_back(pos->path().string()); } return ret; } bool deleteDir_byFileSystem(const std::string srcPath) { boost::system::error_code ec; return boost::filesystem::remove_all(srcPath, ec); } std::string generateTimeStr(bool isSimple) { auto tt = boost::chrono::system_clock::to_time_t(boost::chrono::system_clock::now()); struct tm* ptm = localtime(&tt); char date[60] = { 0 }; if (isSimple) sprintf(date, "%02d%02d%02d", (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec); else 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); return std::string(date); } void InitTranslateFile(std::string srcFile) { DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitTranslateFile %s", srcFile.c_str()); g_usercodeTranslateFile = srcFile; } void InitUserCodeToMsgTip(CAutoArray& strErrorCodeArr, CAutoArray& strDescriptionArr, CAutoArray& strRemarkArr) { g_UserCodeToMsgTip.clear();//should not be inited muli times for (int i = 0; i < strErrorCodeArr.GetCount(); i++) { std::string dstDescribe = std::string(strErrorCodeArr[i].GetData()) + "|" + std::string(strDescriptionArr[i].GetData()); if(g_UserCodeToMsgTip.find(strRemarkArr[i].GetData()) != g_UserCodeToMsgTip.end()) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitUserCodeToMsgTip repeated usercode:%s", strRemarkArr[i].GetData()); g_UserCodeToMsgTip.insert(std::make_pair(strRemarkArr[i].GetData(), ErrMsgStruct(strErrorCodeArr[i].GetData(), dstDescribe))); } DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("InitUserCodeToMsgTip size:%d", g_UserCodeToMsgTip.size()); } std::pair getErrMsgByRemark(std::string srcMsg) { const std::string headerStr = "UserError="; if (srcMsg.find(headerStr) != 0) return std::make_pair(0, ErrMsgStruct("", srcMsg)); unsigned long userCode = std::stoi(srcMsg.substr(headerStr.length())); std::string userCodeStr = CSimpleString::Format("0x%X", userCode).GetData(); if(g_UserCodeToMsgTip.size() == 0) return std::make_pair(0, ErrMsgStruct("RTA42F0", CSimpleString::Format("RTA42F0|微服务异常|(%s)", srcMsg.c_str()).GetData())); if (g_UserCodeToMsgTip.find(userCodeStr) != g_UserCodeToMsgTip.end()) { auto curMsg = g_UserCodeToMsgTip[userCodeStr]; return std::make_pair(userCode, curMsg); } else return std::make_pair(userCode, ErrMsgStruct("RTA42F1", CSimpleString::Format("RTA42F1|错误映射异常|(%s)", srcMsg.c_str()).GetData())); } std::pair splitStrToUserCodeAndErrMsg(std::string srcMsg) { const std::string headerStr = "UserError="; if (srcMsg.find(headerStr) != 0) return std::make_pair(0, srcMsg); unsigned long userCode = std::stoi(srcMsg.substr(headerStr.length())); std::string userCodeStr = CSimpleString::Format("0x%X", userCode).GetData(); if (g_usercodeTranslateFile.length() == 0) return std::make_pair(userCode, srcMsg); try { boost::property_tree::ptree ptr, tag; boost::property_tree::ini_parser::read_ini(g_usercodeTranslateFile, ptr); tag = ptr.get_child("UserCodeToMsgTip"); std::string tipMsg = tag.get(userCodeStr); return std::make_pair(userCode, UtfToGbk(tipMsg.c_str())); } catch (std::exception &e) { DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ini_parse failed, reason:%s", e.what()); } return std::make_pair(userCode, srcMsg); } std::string hexdumpToString(const char* buf, const int num) { char str[8192 * 2] = { 0 }; int i = 0; char c[5] = { 0 }; if (num > 100) { for (i = 0; i < 50; i++) { sprintf(c, "%02X ", (unsigned char)buf[i]); strcat(str, c); } return CSimpleStringA::Format("buffer too long to show!show pre 50 hex! CSocketClient hex buf len = %d : %s", num, str).GetData(); } for (i = 0; i < num; i++) { sprintf(c, "%02X ", (unsigned char)buf[i]); strcat(str, c); } return CSimpleStringA::Format("CSocketClient hex buf len = %d : %s", num, str).GetData(); } void hexdump(const char* buf, const int num) { auto hexStr = hexdumpToString(buf, num); DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)(hexStr.c_str()); } bool modifyBySpecialStr(std::wstring& src) { #if 0 clock_t cur = clock(); std::set srcArr; static std::set compareArr; for (auto it = src.begin(); it != src.end(); it++) srcArr.insert(*it); if (compareArr.size() == 0) { for (auto it = specialStr.begin(); it != specialStr.end(); it++) compareArr.insert(*it); } DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr insert cost:%d", clock() - cur); cur = clock(); std::set result; std::set_intersection(std::begin(srcArr), std::end(srcArr), std::begin(compareArr), std::end(compareArr), std::inserter(result, std::begin(result))); DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr intersection cost:%d", clock() - cur); cur = clock(); if (result.size() == 0) return false; for (auto it = result.begin(); it != result.end(); it++) { int pos = 0; for (int pos = 0; pos < src.length();) { pos = src.find(*it, pos); if (pos < 0) break; if (pos + 1 < src.length() && src[pos + 1] == '\\') src.erase(pos + 1, 1); else pos++; } } DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr modify cost:%d", clock() - cur); cur = clock(); return true; #endif clock_t cur = clock(); wchar_t specialone = L'碶'; if (src.find(specialone, 0) == -1) return false; int pos = 0; for (int pos = 0; pos < src.length();) { pos = src.find(specialone, pos); if (pos < 0) break; if (pos + 1 < src.length() && src[pos + 1] == '\\') src.erase(pos + 1, 1); else pos++; } DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("modifyBySpecialStr modify cost:%d", clock() - cur); return true; } #include #if (defined _WIN32 || defined _WIN64) long WINAPI printSEG(struct _EXCEPTION_POINTERS* ExceptionInfo) #else long printSEG() #endif { auto dumpArr = boost::stacktrace::stacktrace().as_vector(); if (dumpArr.size() > 20) { for (auto i = 0; i < 10; i++) 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()); for (auto i = dumpArr.size() - 10; i < dumpArr.size(); i++) 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()); } else { for (auto i = 0; i < dumpArr.size(); i++) 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()); } return 0; } //singal,退出函数 #if (defined _WIN32 || defined _WIN64) #else #include // ::signal, ::raise #include #include "CModTools.h" #include "CWebsocketServer.h" std::string g_backtracePath = ""; void seg_signal_handler(int signum) { //boost::stacktrace::safe_dump_to(g_backtracePath.c_str()); DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, seg_signal_handler", signum); printSEG(); Chromium::CModTools::get_mutable_instance().killAllChromium(); Chromium::CWebsocketServer::stopServer(); signal(signum, SIG_DFL); raise(signum); } void normal_signal_handle(int signum) { DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, normal_signal_handle", signum); signal(signum, SIG_DFL); raise(signum); } void set_traceback_path(std::string path) { g_backtracePath = path + "/mod_chromium/" + generateTimeStr(true) + "_chromium_backtrace.dump"; DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set_traceback_path %s", g_backtracePath.c_str()); } #endif void receivehexdump(const char* buf, const int num) { char str[8192 * 2] = { 0 }; int i = 0; char c[5] = { 0 }; if (num > 100) { for (i = 0; i < 50; i++) { sprintf(c, "%02X ", (unsigned char)buf[i]); strcat(str, c); } 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); return; } for (i = 0; i < num; i++) { sprintf(c, "%02X ", (unsigned char)buf[i]); strcat(str, c); } DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receivehexdump hex buf len = %d : %s", num, str); return; } void doWithDebugModeData(const char* strMethod, const char* buf) { boost::lock_guard lock(g_networkMutex); if(std::string(strMethod).find("Network.") == 0) { /*for example { "method": "Network.requestWillBeSent", "params": { "documentURL": "https://www.btbtt12.com/", "frameId": "8F58093A23334B311DB645BA3652E63C", "hasUserGesture": false, "initiator": { "type": "other" }, "loaderId": "9F7B28B896C791554C69C5985CA92E79", "request": { "headers": { "Referer": "https://www.btbtt12.com/", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36" }, "initialPriority": "Low", "method": "GET", "mixedContentType": "none", "referrerPolicy": "no-referrer-when-downgrade", "url": "https://pic.picnewsss.com/tu-2022290039/960-60.gif" }, "requestId": "18476.34", "timestamp": 19338.811603, "type": "Image", "wallTime": 1666099893.800733 } } */ std::shared_ptr pJson(cJSON_Parse(buf), [](cJSON* p) { if (nullptr != p) cJSON_Delete(p); }); auto paramsItem = cJSON_GetObjectItem(pJson.get(), "params"); if (paramsItem == nullptr) return; auto requestIdItem = cJSON_GetObjectItem(paramsItem, "requestId"); if (requestIdItem == nullptr) return; std::string requestId_str = requestIdItem->valuestring; /* ['Network.loadingFailed', 'Network.loadingFinished', 'Network.resourceChangedPriority', 'Network.requestServedFromCache', 'Network.requestWillBeSent', 'Network.requestWillBeSentExtraInfo', 'Network.responseReceived', 'Network.responseReceivedExtraInfo', 'Network.dataReceived', 'Page.frameAttached', 'Page.frameRequestedNavigation', 'Page.frameStoppedLoading', 'Page.frameClearedScheduledNavigation', 'Page.loadEventFired', 'Page.frameStartedLoading', 'Page.frameDetached', 'Page.frameScheduledNavigation', 'Page.frameNavigated', 'Page.frameResized', 'Page.domContentEventFired'] */ if(std::string(strMethod) == "Network.loadingFinished") { if (g_networkParse.find(requestId_str) != g_networkParse.end()) g_networkParse.erase(requestId_str); if (g_networkExpiredData.find(requestId_str) != g_networkExpiredData.end()) g_networkExpiredData.erase(requestId_str); if (g_networkExpiredData.size() < 30) return; for(auto it = g_networkExpiredData.begin(); it != g_networkExpiredData.end();) { if((clock() - it -> second) < 100000) { it++; continue; } if (g_networkParse.find(it->first) != g_networkParse.end()) g_networkParse.erase(it->first); g_networkExpiredData.erase(it++); } } else if(std::string(strMethod) == "Network.loadingFailed" || std::string(strMethod) == "Network.webSocketFrameError" || std::string(strMethod) == "Network.requestServedFromCache") { if (g_networkParse.find(requestId_str) != g_networkParse.end()) { for(auto it = g_networkParse[requestId_str].begin(); it != g_networkParse[requestId_str].end(); it++) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402402Z00001").setResultMsg(it->c_str())(); g_networkParse.erase(requestId_str); } else//此时,上一轮记录已结束 DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402402Z00001").setResultMsg(buf)(); if (g_networkExpiredData.find(requestId_str) != g_networkExpiredData.end()) g_networkExpiredData.erase(requestId_str); } else { if (g_networkParse.find(requestId_str) != g_networkParse.end()) g_networkParse[requestId_str].push_back(buf); else { std::vector tmp; tmp.push_back(buf); g_networkParse[requestId_str] = tmp; g_networkExpiredData[requestId_str] = clock(); } } } if (std::string(strMethod) == "Network.webSocketFrameError" || std::string(strMethod) == "Network.loadingFailed" || std::string(strMethod) == "Runtime.exceptionThrown") { LogWarn(Severity_Middle, Error_Debug, LOG_WARN_CHROMIUM_OPENWEBWARN, buf); DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402402Z00002").setResultMsg(buf)(); } } std::pair json_deal::getStringFromCjsonObj(void* object, const char* name) { if (object == NULL) return std::make_pair(false, ""); auto curNode = cJSON_GetObjectItem((cJSON*)object, name); if (curNode && curNode->type == cJSON_String) { return std::make_pair(true, curNode->valuestring); } else return std::make_pair(false, ""); } std::pair json_deal::getIntergerFromCjsonObj(void* object, const char* name) { if (object == NULL) return std::make_pair(false, 0); auto curNode = cJSON_GetObjectItem((cJSON*)object, name); if (curNode && curNode->type == cJSON_Number) { return std::make_pair(true, curNode->valueint); } else return std::make_pair(false, 0); } std::pair json_deal::getDoubleFromCjsonObj(void* object, const char* name) { if (object == NULL) return std::make_pair(false, 0); auto curNode = cJSON_GetObjectItem((cJSON*)object, name); if (curNode && curNode->type == cJSON_Number) { return std::make_pair(true, curNode->valuedouble); } else return std::make_pair(false, 0); } SM2_Encrypt_Manager::SM2_Encrypt_Manager() :m_public_key_buf_len(DEFAULT_KEY_LEN), m_private_key_buf_len(DEFAULT_KEY_LEN), m_opposite_public_key_buf_len(DEFAULT_KEY_LEN) { memset(m_public_key_buf, 0, DEFAULT_KEY_LEN); memset(m_private_key_buf, 0, DEFAULT_KEY_LEN); memset(m_opposite_public_key_buf, 0, DEFAULT_KEY_LEN); GenerateSM2_key(m_public_key, m_private_key); m_state = SM2ProtocolState::WAIT_KEY_EXCHANGE; } SM2_Encrypt_Manager::~SM2_Encrypt_Manager() { } bool SM2_Encrypt_Manager::GenerateSM2_key(std::string& pub, std::string& pri) { if (!::CreateSM2KeyPair(m_public_key_buf, &m_public_key_buf_len, m_private_key_buf, &m_private_key_buf_len)) return false; pub = binToHex(m_public_key_buf, m_public_key_buf_len); pri = binToHex(m_private_key_buf, m_private_key_buf_len); return true; } std::string SM2_Encrypt_Manager::binToHex(const unsigned char* data, int len) { std::string hexString; // 使用 boost::algorithm::hex 进行编码 boost::algorithm::hex(data, data + len, std::back_inserter(hexString)); return hexString; } void SM2_Encrypt_Manager::hexToBin(const std::string& hexStr, unsigned char* binData, int& binLen) { binLen = hexStr.size() / 2; if (binData == nullptr) { // 如果 binData 为 nullptr,仅返回计算出的 binLen,不执行实际的转换 return; } // 使用 boost::algorithm::unhex 进行解码 boost::algorithm::unhex(hexStr.begin(), hexStr.end(), binData); } void SM2_Encrypt_Manager::setOpposite(const std::string pub) { m_opposite_public_key = pub; hexToBin(m_opposite_public_key, m_opposite_public_key_buf, m_opposite_public_key_buf_len); } std::pair SM2_Encrypt_Manager::checkSM2Enable() { if (m_public_key.length() == 0) return std::make_pair(false, "public_key is empty"); if (m_private_key.length() == 0) return std::make_pair(false, "private_key is empty"); if (m_opposite_public_key.length() == 0) return std::make_pair(false, "opposite public_key is empty"); return std::make_pair(true, ""); } std::pair SM2_Encrypt_Manager::EncryptMsg(std::string msg) { unsigned char sign[DEFAULT_KEY_LEN] = ""; int sign_len = DEFAULT_KEY_LEN; unsigned char* dstMsg = new unsigned char[msg.length() * 2]; int dstMsgLen = msg.length() * 2; std::shared_ptr msgClean((void*)0, [&](void*) { if (dstMsg) { delete[]dstMsg; dstMsg = nullptr; } }); if (!SM2SignWithSM3(m_private_key_buf, m_private_key_buf_len, (unsigned char*)msg.c_str(), msg.length(), sign, &sign_len)) { DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SM2SignWithSM3::err, can not sign msg"); return std::make_pair("", ""); } if(!EncWithSM2PubKey((unsigned char*)msg.c_str(), msg.length(), dstMsg, &dstMsgLen, m_opposite_public_key_buf, m_opposite_public_key_buf_len)) { DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("EncWithSM2PubKey::err, can not encrypt msg"); return std::make_pair("", ""); } return std::make_pair(binToHex(sign, sign_len), binToHex(dstMsg, dstMsgLen)); } std::pair SM2_Encrypt_Manager::DecryptMsg(std::string sign, std::string msg) { 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 int binMsgLen = msg.length(), outMsgLen = msg.length() * 2, signLen = sign.length(); std::shared_ptr msgClean((void*)0, [&](void*) { if (binMsg) { delete[] binMsg; binMsg = nullptr; } if (outMsg) { delete[] outMsg; outMsg = nullptr; } if (binSign) { delete[] binSign; binSign = nullptr; } }); hexToBin(msg, binMsg, binMsgLen); hexToBin(sign, binSign, signLen); if (!DecWithSM2PriKey(binMsg, binMsgLen, outMsg, &outMsgLen, m_private_key_buf, m_private_key_buf_len)) return std::make_pair(false, "DecWithSM2PriKey::err, can not dectrypt msg"); if (!SM2VerifyWithSM3(m_opposite_public_key_buf, m_opposite_public_key_buf_len, outMsg, outMsgLen, binSign, signLen)) return std::make_pair(false, "SM2VerifyWithSM3::err, can not verify sign"); return std::make_pair(true, (char*)outMsg); } std::pair SM2_Encrypt_Manager::GenerateEncPubKey() { if(!verifySM2Manager()) return std::make_pair(false, "GenerateEncPubKey::verifySM2Manager err"); unsigned char encPubKey[DEFAULT_KEY_LEN] = ""; int encPubKey_len = DEFAULT_KEY_LEN; 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)) return std::make_pair(false, "GenerateEncPubKey::EncWithSM2PubKey err"); return std::make_pair(true, binToHex(encPubKey, encPubKey_len)); } bool SM2_Encrypt_Manager::verifySM2Manager() { if (m_opposite_public_key.length() == 0 || m_public_key.length() == 0 || m_private_key.length() == 0) return false; if (m_opposite_public_key_buf == NULL || m_public_key_buf == NULL || m_private_key_buf == NULL) return false; return true; }