CommEntityUtil.hpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. #ifndef RVC_MOD_COMM_ENTITY_UTIL_HPP_
  2. #define RVC_MOD_COMM_ENTITY_UTIL_HPP_
  3. #if defined(_MSC_VER)
  4. #include <Windows.h>
  5. #include <TlHelp32.h>
  6. #include <iphlpapi.h>
  7. #include <ws2tcpip.h>
  8. #include <Winsock2.h>
  9. #include <IPTypes.h>
  10. #include <WinInet.h>
  11. #include <ShlObj.h>
  12. #include <Pdh.h>
  13. #pragma comment(lib, "IPHLPAPI.lib")
  14. #pragma comment(lib, "Wininet.lib")
  15. #pragma comment(lib, "pdh.lib")
  16. #define streq stricmp
  17. #else
  18. #include <linux/ethtool.h>
  19. #include <linux/sockios.h>
  20. #include <net/if.h>
  21. #include <sys/ioctl.h>
  22. #include <sys/sysinfo.h>
  23. #include <unistd.h>
  24. #include <thread>
  25. #include <chrono>
  26. #define streq strcasecmp
  27. #endif //_MSC_VER
  28. #include "path.h"
  29. #include "toolkit.h"
  30. #include <string>
  31. #include <iostream>
  32. #include <sstream>
  33. #include <map>
  34. #include "SpBase.h"
  35. #include "publicFunExport.h"
  36. #define MACSESION 6
  37. #define DIV (1024 * 1024)
  38. #define DAY_DIV (24 * 60 * 60)
  39. #define HOURS_DIV (60 * 60)
  40. #define MINUS_DIV (60)
  41. typedef unsigned long long ULLINT;
  42. #define SLEEP(interval) std::this_thread::sleep_for(std::chrono::milliseconds(interval))
  43. namespace SP
  44. {
  45. namespace Module
  46. {
  47. namespace System
  48. {
  49. static BOOL GetSystemBootTime(CSmallDateTime& systemBootTime)
  50. {
  51. #if defined(_MSC_VER)
  52. const char* SystemElapsedQuery = "\\System\\System Up Time";
  53. PDH_STATUS Status;
  54. HQUERY Query = NULL;
  55. HCOUNTER hcElapsedTimeCount;
  56. BOOL fSuc = FALSE;
  57. /** 杀毒软件会对附件这几个系统调用函数有所监控,导致有时会耗费5s时间 Gifur@20221019]*/
  58. Status = PdhOpenQuery(NULL, NULL, &Query);
  59. PDH_FMT_COUNTERVALUE counterValue;
  60. if (Status != ERROR_SUCCESS) {
  61. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhOpenQuery failed with status 0x%x.", Status);
  62. goto Cleanup;
  63. }
  64. Status = PdhAddCounter(Query, SystemElapsedQuery, NULL, &hcElapsedTimeCount);
  65. if (Status != ERROR_SUCCESS) {
  66. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhAddCounter for SystemElapsedQuery failed with status 0x%x.", Status);
  67. goto Cleanup;
  68. }
  69. // 查询性能监视器数据
  70. Status = PdhCollectQueryData(Query);
  71. if (Status != ERROR_SUCCESS) {
  72. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhCollectQueryData failed with 0x%x.", Status);
  73. goto Cleanup;
  74. }
  75. Status = PdhGetFormattedCounterValue(hcElapsedTimeCount, PDH_FMT_LARGE, NULL, &counterValue);
  76. if (Status == ERROR_SUCCESS) {
  77. ULONGLONG ulSinceSeconds = counterValue.largeValue;
  78. ULONG days = 0, hours = 0, minutes = 0, seconds = 0;
  79. days = ULONG(ulSinceSeconds / DAY_DIV);
  80. ulSinceSeconds %= DAY_DIV;
  81. hours = ULONG(ulSinceSeconds / HOURS_DIV);
  82. ulSinceSeconds %= HOURS_DIV;
  83. minutes = ULONG(ulSinceSeconds / MINUS_DIV);
  84. ulSinceSeconds %= MINUS_DIV;
  85. seconds = ULONG(ulSinceSeconds);
  86. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SystemElapseTime: %uDays-%02u:%02u:%02u", days, hours, minutes, seconds);
  87. FILETIME ftCurTime, ftStartTime;
  88. GetSystemTimeAsFileTime(&ftCurTime);
  89. ULARGE_INTEGER uliCurTime;
  90. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  91. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  92. uliCurTime.QuadPart -= counterValue.largeValue * 1e7;
  93. ftStartTime.dwHighDateTime = uliCurTime.HighPart;
  94. ftStartTime.dwLowDateTime = uliCurTime.LowPart;
  95. SYSTEMTIME stUTC, stLocal;
  96. FileTimeToSystemTime(&ftStartTime, &stUTC);
  97. char temp[22];
  98. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  99. sprintf_s(temp, 22, "%d-%02d-%02d %02d:%02d:%02d",
  100. stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  101. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OSStartTime: %s", temp);
  102. systemBootTime.FromSystemTime(stLocal);
  103. fSuc = TRUE;
  104. }
  105. Cleanup:
  106. Status = PdhRemoveCounter(hcElapsedTimeCount);
  107. if (Query) {
  108. PdhCloseQuery(Query);
  109. }
  110. return fSuc;
  111. #else
  112. DWORD ticks = 0;
  113. SYSTEMTIME systemTime;
  114. struct sysinfo info;
  115. time_t curTime = 0;
  116. time_t bootTime = 0;
  117. struct tm* ptm = NULL;
  118. if (sysinfo(&info)) {
  119. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Failed to get sysinfo, errno:%u, reason:%s", errno, strerror(errno));
  120. return FALSE;
  121. }
  122. time(&curTime);
  123. if (curTime > info.uptime) {
  124. bootTime = curTime - info.uptime;
  125. }
  126. else
  127. {
  128. bootTime = info.uptime - curTime;
  129. }
  130. ptm = localtime(&bootTime);
  131. struct timespec ts;
  132. if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
  133. ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
  134. systemTime.wYear = (WORD)(ptm->tm_year + 1900);
  135. systemTime.wMonth = (WORD)(ptm->tm_mon + 1);
  136. systemTime.wDayOfWeek = (WORD)ptm->tm_wday;
  137. systemTime.wDay = (WORD)ptm->tm_mday;
  138. systemTime.wHour = (WORD)ptm->tm_hour;
  139. systemTime.wMinute = (WORD)ptm->tm_min;
  140. systemTime.wSecond = (WORD)ptm->tm_sec;
  141. systemTime.wMilliseconds = (WORD)(ticks % 1000);
  142. systemBootTime.FromSystemTime(systemTime);
  143. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OSStartTime: %s", systemBootTime.ToTimeString().GetData());
  144. return TRUE;
  145. #endif //_MSC_VER
  146. }
  147. }//system
  148. namespace Comm
  149. {
  150. /** Rely on ${OTHER_LIB_BASE_DIR}/libpublicFun and library target libpublicFun*/
  151. struct LogNotiyMessageStruct
  152. {
  153. std::string Reason;
  154. std::string ErrMsg;
  155. std::string RebootTime;
  156. LogNotiyMessageStruct(const CSimpleStringA& reason, const CSimpleStringA& errmsg, const CSimpleStringA& rebootTime)
  157. :Reason(reason.GetData()), ErrMsg(reason.GetData()), RebootTime(reason.GetData())
  158. {
  159. }
  160. LogNotiyMessageStruct(const std::string& reason, const std::string& errmsg, const std::string& rebootTime)
  161. :Reason(reason), ErrMsg(errmsg), RebootTime(rebootTime)
  162. {
  163. }
  164. LogNotiyMessageStruct(const char* reason, const char* errmsg, char* rebootTime)
  165. :Reason(reason), ErrMsg(errmsg), RebootTime(rebootTime)
  166. {
  167. }
  168. LogNotiyMessageStruct(const char* errmsg)
  169. :Reason(""), ErrMsg(errmsg), RebootTime("")
  170. {
  171. }
  172. std::string ToJsonString() const {
  173. std::map<std::string, std::string> srcData;
  174. srcData.insert(std::make_pair("reason", Reason));
  175. srcData.insert(std::make_pair("errmsg", ErrMsg));
  176. srcData.insert(std::make_pair("rebootTime", RebootTime));
  177. auto ret = generateJsonStr(srcData);
  178. if (ret.first) {
  179. return ret.second;
  180. } else {
  181. return ErrMsg;
  182. }
  183. }
  184. };
  185. struct LogCommNotiyStruct
  186. {
  187. NotifyLevelEnum eLevel;
  188. ErrorCodeEnum eSysCode;
  189. DWORD dwUserCode;
  190. LogCommNotiyStruct() :eLevel(Notify_None), eSysCode(Error_Unexpect), dwUserCode(0) {}
  191. LogCommNotiyStruct(NotifyLevelEnum level, ErrorCodeEnum errorCode, DWORD dwUserCode)
  192. :eLevel(level), eSysCode(errorCode), dwUserCode(dwUserCode) {}
  193. LogCommNotiyStruct(NotifyLevelEnum level, ErrorCodeEnum errorCode)
  194. :eLevel(level), eSysCode(errorCode), dwUserCode(0)
  195. { }
  196. virtual ~LogCommNotiyStruct() {}
  197. virtual void Notify(const LogNotiyMessageStruct& notifyMessage)
  198. {
  199. LogNotify(eLevel, eSysCode, dwUserCode, notifyMessage.ToJsonString().c_str());
  200. }
  201. };
  202. struct LogInfoNotiyStruct : public LogCommNotiyStruct
  203. {
  204. LogInfoNotiyStruct(ErrorCodeEnum errorCode, DWORD dwUserCode)
  205. :LogCommNotiyStruct(Notify_Info, errorCode, dwUserCode){}
  206. ~LogInfoNotiyStruct() {}
  207. };
  208. struct LogWarnNotiyStruct : public LogCommNotiyStruct
  209. {
  210. LogWarnNotiyStruct(ErrorCodeEnum errorCode, DWORD dwUserCode)
  211. :LogCommNotiyStruct(Notify_Warn, errorCode, dwUserCode)
  212. {
  213. }
  214. ~LogWarnNotiyStruct() {}
  215. };
  216. struct LogErrorNotiyStruct : public LogCommNotiyStruct
  217. {
  218. LogErrorNotiyStruct(ErrorCodeEnum errorCode, DWORD dwUserCode)
  219. :LogCommNotiyStruct(Notify_Error, errorCode, dwUserCode)
  220. {
  221. }
  222. ~LogErrorNotiyStruct() {}
  223. };
  224. static BOOL IsFirsRunAppAfterSystemBoot(CEntityBase* pEntity, DWORD theReportUserCode = 0)
  225. {
  226. BOOL result(FALSE);
  227. CSystemRunInfo runInfo = { 0 };
  228. ErrorCodeEnum ec = pEntity->GetFunction()->GetSystemRunInfo(runInfo);
  229. if (ec == Error_Succeed) {
  230. CBootInfo bootInfo = { 0 };
  231. CSmallDateTime dateTime;
  232. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
  233. ec = pEntity->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
  234. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
  235. CSmallDateTime systemBootTime;
  236. const BOOL bRet = System::GetSystemBootTime(systemBootTime);
  237. if (bRet && systemBootTime > bootInfo.tmStart) {
  238. result = TRUE;
  239. if (theReportUserCode != 0) {
  240. std::map<std::string, std::string> srcData;
  241. CSimpleStringA strData = CSimpleStringA::Format("{\"AppLastStartTime\":\"%s\",\"AppStartTime\":\"%s\",\"OSStartTime\":\"%s\"}"
  242. , (LPCTSTR)bootInfo.tmStart.ToTimeString(), (LPCTSTR)runInfo.tmStart.ToTimeString(), systemBootTime.ToTimeString().GetData());
  243. LogWarn(Severity_Low, Error_Debug, theReportUserCode, strData.GetData());
  244. }
  245. }
  246. }
  247. return result;
  248. }
  249. inline
  250. CSimpleStringA GetCurrMachineType(CEntityBase* pEntity)
  251. {
  252. CSystemStaticInfo sysInfo;
  253. pEntity->GetFunction()->GetSystemStaticInfo(sysInfo);
  254. return sysInfo.strMachineType;
  255. }
  256. enum Site
  257. {
  258. CMB_UNKNOWN,
  259. CMB_LIB, /** 行内大堂*/
  260. CMB_FLB, /** 离行机器*/
  261. };
  262. #define SITE_ENUM_TYPE(MACRO) \
  263. MACRO(LIB)\
  264. MACRO(FLB)
  265. #define ENUM_MAP_CONVERT(elem) \
  266. if (streq(lpcszSiteName, "CMB."#elem) == 0) return CMB_##elem;
  267. /*!
  268. * convert cmb site name to enum type.
  269. */
  270. static Site Str2Site(LPCSTR lpcszSiteName)
  271. {
  272. if (lpcszSiteName == NULL || strlen(lpcszSiteName) == 0)
  273. return CMB_UNKNOWN;
  274. SITE_ENUM_TYPE(ENUM_MAP_CONVERT)
  275. return CMB_UNKNOWN;
  276. }
  277. #undef ENUM_MAP_CONVERT
  278. #define ENUM_MAP_CONVERT(elem) case CMB_##elem: return "CMB."#elem;
  279. static LPCSTR Site2Str(Site site)
  280. {
  281. switch (site) {
  282. SITE_ENUM_TYPE(ENUM_MAP_CONVERT)
  283. default:
  284. break;
  285. }
  286. return "Unkown";
  287. }
  288. enum What
  289. {
  290. RVC_UNKNOWN,
  291. RVC_Stand2S, /** 落地式大机*/
  292. RVC_PAD, /** PAD*/
  293. RVC_Desk2S, /** 低柜双屏*/
  294. RVC_CardStore, /** 卡库*/
  295. RVC_CardPrinter, /** 制卡机*/
  296. RVC_Stand1SPlus /** 单屏大机*/
  297. };
  298. #define MACHINE_ENUM_TYPE(MACRO) \
  299. MACRO(Stand2S)\
  300. MACRO(PAD)\
  301. MACRO(Desk2S)\
  302. MACRO(CardStore)\
  303. MACRO(CardPrinter)\
  304. MACRO(Stand1SPlus)
  305. #undef ENUM_MAP_CONVERT
  306. #define ENUM_MAP_CONVERT(elem) \
  307. if (streq(lpcszTypeName, "RVC."#elem) == 0) return RVC_##elem;
  308. /*!
  309. * convert cmb site name to enum type.
  310. */
  311. static What Str2Type(LPCSTR lpcszTypeName)
  312. {
  313. if (lpcszTypeName == NULL || strlen(lpcszTypeName) == 0)
  314. return RVC_UNKNOWN;
  315. MACHINE_ENUM_TYPE(ENUM_MAP_CONVERT)
  316. return RVC_UNKNOWN;
  317. }
  318. #undef ENUM_MAP_CONVERT
  319. #define ENUM_MAP_CONVERT(elem) case RVC_##elem: return "RVC."#elem;
  320. static LPCSTR Type2Str(What what)
  321. {
  322. switch (what) {
  323. MACHINE_ENUM_TYPE(ENUM_MAP_CONVERT)
  324. default:
  325. break;
  326. }
  327. return "Unkown";
  328. }
  329. struct TerminalMachineInfo
  330. {
  331. Site site;
  332. What type;
  333. struct {
  334. WORD minor;
  335. WORD major;
  336. } gen;
  337. };
  338. inline TerminalMachineInfo GetTerminalMachineInfo(CEntityBase* pEntity)
  339. {
  340. CSystemStaticInfo sysInfo;
  341. TerminalMachineInfo termInfo;
  342. pEntity->GetFunction()->GetSystemStaticInfo(sysInfo);
  343. termInfo.site = Str2Site(sysInfo.strSite);
  344. termInfo.type = Str2Type(sysInfo.strMachineType);
  345. termInfo.gen.major = sysInfo.MachineVersion.GetMajor();
  346. termInfo.gen.minor = sysInfo.MachineVersion.GetMinor();
  347. return termInfo;
  348. }
  349. inline ULLINT RVCGetTickCount()
  350. {
  351. #ifdef RVC_OS_WIN
  352. return GetTickCount64();
  353. #else
  354. struct timespec ts;
  355. clock_gettime(CLOCK_MONOTONIC, &ts);
  356. return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
  357. #endif // RVC_OS_WIN
  358. }
  359. } // comm
  360. namespace Util
  361. {
  362. static int StrBuf2HexBuf(const char* strBuf, PBYTE* hexBuf)
  363. {
  364. int len = strlen(strBuf);
  365. if (len == 0 || len % 2 != 0)
  366. return 0;
  367. BYTE* buf = new BYTE[len / 2];
  368. if (buf == NULL)
  369. return 0;
  370. int j = 0;
  371. for (int i = 0; i < len;) {
  372. int tmpVal;
  373. sscanf(strBuf + i, "%2X", &tmpVal);
  374. buf[j] = tmpVal;
  375. i += 2;
  376. j++;
  377. }
  378. *hexBuf = buf;
  379. return j;
  380. }
  381. static int HexBuf2StrBuf(PBYTE hexBuf, char** strBuf, DWORD len)
  382. {
  383. char* tmpStr = *strBuf;
  384. DWORD count = 0;
  385. for (DWORD i = 0; i < len; ++i) {
  386. sprintf(tmpStr + count, "%0.2X", hexBuf[i]);
  387. count += 2;
  388. }
  389. return 0;
  390. }
  391. //tips: need to delete result char*
  392. static char* ConvertBytesToHexStr(BYTE* pBuf, int nLen)
  393. {
  394. char* pRet = (char*)new char[nLen * 2 + 1];
  395. memset(pRet, '\0', nLen * 2 + 1);
  396. char* p = pRet;
  397. for (int i = 0; i < nLen; i++) {
  398. BYTE b = pBuf[i];
  399. BYTE l = (b >> 4) & 0x0F;
  400. if (l >= 10)
  401. *p = l - 10 + 'a';
  402. else
  403. *p = l + '0';
  404. p++;
  405. BYTE r = b & 0x0F;
  406. if (r >= 10)
  407. *p = r - 10 + 'a';
  408. else
  409. *p = r + '0';
  410. p++;
  411. }
  412. return pRet;
  413. }
  414. static char HexChar2Dec(char c)
  415. {
  416. if ((c >= '0') && (c <= '9'))
  417. return c - '0';
  418. else if ((c >= 'A') && (c <= 'F'))
  419. return c - 'A' + 10;
  420. else if ((c >= 'a') && (c <= 'f'))
  421. return c - 'a' + 10;
  422. else
  423. return 0x10;
  424. }
  425. static int Hex2Int(char* s)
  426. {
  427. int ret = 0;
  428. while (*s) {
  429. int t = HexChar2Dec(*s);
  430. ret = ret * 16 + t;
  431. ++s;
  432. }
  433. return ret;
  434. }
  435. static void ConvAscii(unsigned char* Hex, char* Ascii, unsigned int len)
  436. {
  437. const unsigned char hextable[] = { "0123456789ABCDEF" };
  438. unsigned int i;
  439. for (i = 0; i < len; i++) {
  440. Ascii[2 * i] = hextable[Hex[i] >> 4];
  441. Ascii[2 * i + 1] = hextable[Hex[i] & 0xf];
  442. }
  443. Ascii[2 * len] = 0;
  444. }
  445. static void AsciiToHex(char* Ascii, unsigned char* Hex, int len)
  446. {
  447. int i;
  448. unsigned char ch;
  449. for (i = 0; i < len; i = i + 2) {
  450. ch = (Ascii[i] & 0xf);
  451. if (Ascii[i] > '9')
  452. ch += 9;
  453. Hex[i / 2] = ch << 4;
  454. ch = Ascii[i + 1] & 0xf;
  455. if (Ascii[i + 1] > '9')
  456. ch += 9;
  457. Hex[i / 2] += ch;
  458. }
  459. }
  460. static bool IsNoStr(const char* str)
  461. {
  462. int len = strlen(str);
  463. if (len == 0)
  464. return true;
  465. for (int i = 0; i < len; ++i) {
  466. if (*(str + i) != ' ')
  467. return false;
  468. }
  469. return true;
  470. }
  471. static DWORD GetDuration(const SYSTEMTIME& time1, const SYSTEMTIME& time2)
  472. {
  473. #if defined(RVC_OS_WIN)
  474. ULARGE_INTEGER fTime1;/*FILETIME*/
  475. ULARGE_INTEGER fTime2;/*FILETIME*/
  476. SystemTimeToFileTime(&time1, (FILETIME*)&fTime1);
  477. SystemTimeToFileTime(&time2, (FILETIME*)&fTime2);
  478. unsigned __int64 dft = fTime2.QuadPart - fTime1.QuadPart;
  479. return DWORD(dft / 10000);
  480. #else
  481. ///**TODO(Gifur@9/3/2021): Bug 不能这样简单的实现,考虑凌晨,切换月份甚至是年份 */
  482. DWORD s1, s2;
  483. s1 = (time1.wMinute * 60 + time1.wSecond) * 1000 + time1.wMilliseconds;
  484. s2 = (time2.wMinute * 60 + time2.wSecond) * 1000 + time2.wMilliseconds;
  485. return s2 - s1;
  486. #endif //RVC_OS_WIN
  487. }
  488. static std::string formatTime(const SYSTEMTIME& time)
  489. {
  490. char tBuf[1024] = "";
  491. sprintf(tBuf, "%04u-%02u-%02u %02u:%02u:%02u:%03u", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
  492. return tBuf;
  493. }
  494. static bool ShellExecute(const std::string& cmd, std::string& succResult, std::string& errResult)
  495. {
  496. succResult = errResult = "";
  497. char ps[1024] = { 0 };
  498. strcpy(ps, cmd.c_str());
  499. #if defined(_MSC_VER)
  500. STARTUPINFO si;
  501. PROCESS_INFORMATION pi;
  502. ZeroMemory(&si, sizeof(si));
  503. si.cb = sizeof(si);
  504. // 设置STARTUPINFO的wShowWindow成员为SW_HIDE,以隐藏窗口
  505. si.wShowWindow = SW_HIDE;
  506. ZeroMemory(&pi, sizeof(pi));
  507. // 使用CreateProcess启动程序
  508. if (!CreateProcess(NULL, // 不使用模块名
  509. ps, // 命令行
  510. NULL, // 不继承进程句柄
  511. NULL, // 不继承线程句柄
  512. FALSE, // 不继承句柄
  513. CREATE_NO_WINDOW, // 没有创建标志
  514. NULL, // 使用父进程的环境块
  515. NULL, // 使用父进程的当前目录
  516. &si, // 指向STARTUPINFO的指针
  517. &pi) // 指向PROCESS_INFORMATION的指针
  518. ) {
  519. errResult = errResult + "CreateProcess failed with error:" + strerror(GetLastError());
  520. return false;
  521. }
  522. // 等待程序结束,并获取其退出状态
  523. WaitForSingleObject(pi.hProcess, INFINITE);
  524. DWORD exitCode;
  525. if (!GetExitCodeProcess(pi.hProcess, &exitCode)) {
  526. errResult = errResult + "GetExitCodeProcess failed with error code " + strerror(GetLastError());
  527. return false;
  528. }
  529. // 关闭进程和线程句柄
  530. CloseHandle(pi.hProcess);
  531. CloseHandle(pi.hThread);
  532. if (exitCode != 0)
  533. {
  534. errResult = errResult + "The program exited with code:" + strerror(exitCode);
  535. return false;
  536. }
  537. return true;
  538. #else
  539. char buf_ps[1024];
  540. char result[2049] = { 0 };
  541. FILE* ptr;
  542. if ((ptr = popen(ps, "r")) != NULL) {
  543. while (fgets(buf_ps, 1024, ptr) != NULL) {
  544. if (strlen(result) + strlen(buf_ps) > 2048)
  545. break;
  546. strcat(result, buf_ps);
  547. }
  548. pclose(ptr);
  549. const int len = strlen(result);
  550. for (int i = len - 1; i >= 0 && (result[i] == '\r' || result[i] == '\n'); --i) {
  551. result[i] = '\0';
  552. }
  553. succResult = result;
  554. return true;
  555. } else {
  556. sprintf(result, "popen %s error: %d", ps, errno);
  557. errResult = result;
  558. return false;
  559. }
  560. #endif //_MSC_VER
  561. }
  562. static CSimpleStringA generateConsumeTimeJson(const CSimpleStringA& entityName, const CSimpleStringA& startTime, int cost)
  563. {
  564. return CSimpleStringA::Format("{\"name\":\"%s\",\"time\":\"%s\",\"cost\":%d}", entityName.GetData(), startTime.GetData(), cost);
  565. }
  566. #if defined(_MSC_VER)
  567. static char* ConvertUtf8ToGBK(const char* strUtf8)
  568. {
  569. int len = MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, NULL, 0);
  570. WCHAR* wszGBK = new WCHAR[len + 1];
  571. memset(wszGBK, 0, len * 2 + 2);
  572. MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, wszGBK, len);
  573. len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  574. char* szGBK = new char[len + 1];
  575. memset(szGBK, 0, len + 1);
  576. WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
  577. delete[] wszGBK;
  578. return szGBK;
  579. }
  580. static void ConvertUtf8ToGBK(std::string& str)
  581. {
  582. char* dst = ConvertUtf8ToGBK(str.c_str());
  583. str = dst;
  584. delete[] dst;
  585. }
  586. static char* ConvertGBKToUtf8(const char* gbk, int* n)
  587. {
  588. int len = MultiByteToWideChar(CP_ACP, 0, gbk, -1, NULL, 0);
  589. WCHAR* wszGBK = new WCHAR[len + 1];
  590. memset(wszGBK, 0, len * 2 + 2);
  591. MultiByteToWideChar(CP_ACP, 0, gbk, -1, wszGBK, len);
  592. len = WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  593. char* szUtf8 = new char[len + 1];
  594. memset(szUtf8, 0, len + 1);
  595. WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, szUtf8, len, NULL, NULL);
  596. delete[] wszGBK;
  597. *n = len - 1;
  598. return szUtf8;
  599. }
  600. static void ConvertGBKToUtf8(std::string& str)
  601. {
  602. int len = 0;
  603. char* dst = ConvertGBKToUtf8(str.c_str(), &len);
  604. str = dst;
  605. delete[] dst;
  606. }
  607. #endif //_MSC_VER
  608. static std::string W2S(const std::wstring wstr)
  609. {
  610. #if defined(_MSC_VER)
  611. char* str = NULL;
  612. int n = ::WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
  613. if (n > 0) {
  614. str = new char[n + 1];
  615. if (str == NULL) {
  616. return std::string();
  617. }
  618. std::memset(str, 0, sizeof(char) * (n + 1));
  619. ::WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &str[0], n, NULL, NULL);
  620. std::string strr(str);
  621. delete [] str;
  622. return strr;
  623. }
  624. #else
  625. ///*TODO(80374374@3/7/2023): */
  626. #endif //_MSC_VER
  627. return std::string();
  628. }
  629. static std::wstring S2W(const std::string str)
  630. {
  631. #if defined(_MSC_VER)
  632. wchar_t* wstr = NULL;
  633. int n = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
  634. if (n > 0) {
  635. wstr = new wchar_t[n + 1];
  636. if (wstr == NULL) {
  637. return std::wstring();
  638. }
  639. std::memset(wstr, 0, (n + 1) * sizeof(wchar_t));
  640. ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &wstr[0], n);
  641. std::wstring strr(wstr);
  642. delete [] wstr;
  643. return strr;
  644. }
  645. #else
  646. ///*TODO(80374374@3/7/2023): */
  647. #endif //_MSC_VER
  648. return std::wstring();
  649. }
  650. } //namespace Util
  651. namespace Net{
  652. struct NetworkAdapterItem
  653. {
  654. int idx;
  655. std::string friend_name;
  656. std::string adapter_name;
  657. std::string description;
  658. std::string ip;
  659. std::string mask;
  660. std::string mac;
  661. std::string gateway;
  662. std::string dhcp;
  663. bool is_physical;
  664. DWORD type;
  665. int operStatus;
  666. bool isLocal;
  667. NetworkAdapterItem() :idx(0), friend_name(""), adapter_name(""), description(""), ip(""), mask(""),
  668. mac(""), gateway(""), dhcp(""), is_physical(true), type(0), operStatus(0), isLocal(false)
  669. {
  670. }
  671. };
  672. static bool IsLocalAdapter(const std::string& name)
  673. {
  674. #if defined(_MSC_VER)
  675. if (name.length() <= 0) {
  676. return false;
  677. }
  678. std::string key("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
  679. HKEY h_sub_key = NULL;
  680. LONG ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_READ, &h_sub_key);
  681. if (ret != 0) {
  682. return false;
  683. }
  684. std::ostringstream str;
  685. str << name << "\\Connection";
  686. HKEY h_local_key = NULL;
  687. ret = RegOpenKeyEx(h_sub_key, str.str().c_str(), 0, KEY_READ, &h_local_key);
  688. if (0 != ret) {
  689. RegCloseKey(h_sub_key);
  690. return false;
  691. }
  692. DWORD type = REG_SZ;
  693. TCHAR buf[250];
  694. DWORD buf_size = 250;
  695. ret = RegQueryValueEx(h_local_key, "PnPInstanceId", 0, &type, (BYTE*)(buf), &buf_size);
  696. RegCloseKey(h_sub_key);
  697. RegCloseKey(h_local_key);
  698. if (0 != ret) {
  699. return false;
  700. }
  701. if (0 == strnicmp(buf, "PCI", strlen("PCI")) || 0 == strnicmp(buf, "USB", strlen("USB"))) {
  702. return true;
  703. }
  704. return false;
  705. #else
  706. ///*TODO(80374374@3/7/2023): */
  707. return true;
  708. #endif //_MSC_VER
  709. }
  710. static ErrorCodeEnum GetINETMacAddresses(CAutoArray<NetworkAdapterItem>& netLists)
  711. {
  712. #if defined(RVC_OS_WIN)
  713. PIP_ADAPTER_ADDRESSES pAddresses = NULL;
  714. ULONG family = AF_INET;
  715. ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
  716. ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
  717. // Make an initial call to GetAdaptersAddresses to get the
  718. // size needed into the outBufLen variable
  719. if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW) {
  720. pAddresses = static_cast<PIP_ADAPTER_ADDRESSES>(HeapAlloc(GetProcessHeap(), 0, outBufLen));
  721. }
  722. if (NULL == pAddresses) {
  723. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pAddresses = NULL");
  724. return Error_Unexpect;
  725. }
  726. DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
  727. /* MACAddresses vAddress;*/
  728. if (dwRetVal != ERROR_SUCCESS) {
  729. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("dwRetVal = %d", dwRetVal);
  730. return Error_Unexpect;
  731. }
  732. PIP_ADAPTER_ADDRESSES pFirst = pAddresses;
  733. while (pAddresses) {
  734. if (pAddresses->FirstUnicastAddress &&
  735. pAddresses->IfType != IF_TYPE_SOFTWARE_LOOPBACK &&
  736. pAddresses->OperStatus == IfOperStatusUp &&
  737. pAddresses->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET
  738. ) {
  739. NetworkAdapterItem netItem;
  740. BYTE* pa = pAddresses->PhysicalAddress;
  741. if (!pa) {
  742. pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
  743. continue;
  744. }
  745. CSimpleStringA strFriendlyName(true);
  746. CSimpleStringA strDescription(true);
  747. DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->FriendlyName, -1, NULL, 0, NULL, FALSE);
  748. char* psText = new char[dwNum];
  749. if (psText != NULL) {
  750. WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->FriendlyName, -1, psText, dwNum, NULL, FALSE);
  751. strFriendlyName = psText;
  752. delete[] psText;
  753. }
  754. dwNum = WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->Description, -1, NULL, 0, NULL, FALSE);
  755. psText = new char[dwNum];
  756. if (psText != NULL) {
  757. WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->Description, -1, psText, dwNum, NULL, FALSE);
  758. strDescription = psText;
  759. delete[] psText;
  760. }
  761. char bAddressBytes[MACSESION];
  762. int bAddressInt[MACSESION];
  763. memset(bAddressBytes, 0, MACSESION);
  764. size_t nAddressSize = pAddresses->PhysicalAddressLength;
  765. memcpy(bAddressBytes, pa, (nAddressSize < MACSESION ? nAddressSize : MACSESION));
  766. for (int i = 0; i < MACSESION; ++i) {
  767. bAddressInt[i] = bAddressBytes[i];
  768. bAddressInt[i] &= 0x000000ff; // avoid "ff" leading bytes when "char" is lager then 0x7f
  769. }
  770. CSimpleStringA tmpmac = CSimpleStringA::Format("%02x:%02x:%02x:%02x:%02x:%02x",
  771. bAddressInt[0],
  772. bAddressInt[1],
  773. bAddressInt[2],
  774. bAddressInt[3],
  775. bAddressInt[4],
  776. bAddressInt[5]);
  777. sockaddr_in* sa_in = (sockaddr_in*)pAddresses->FirstUnicastAddress->Address.lpSockaddr;
  778. char buf_addr[100] = { 0 };
  779. CSimpleStringA tmpip = CSimpleStringA(inet_ntop(AF_INET, &(sa_in->sin_addr), buf_addr, 100));
  780. if (tmpip.Compare("127.0.0.1") == 0 && tmpmac.Compare("00:00:00:00:00:00") == 0) {
  781. //skip
  782. }
  783. else
  784. {
  785. netItem.friend_name = strFriendlyName;
  786. netItem.description = strDescription;
  787. netItem.mac = tmpmac;
  788. netItem.ip = tmpip;
  789. netItem.operStatus = (pAddresses->OperStatus == IfOperStatusUp) ? 1 : 0;//stay the same value with Linux/UOS
  790. netItem.type = pAddresses->IfType;
  791. netLists.Append(&netItem, 0, 1);
  792. }
  793. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s, %s: OperStatus: %d, IfType = %d, ip=%s, mac=%s"
  794. , strFriendlyName.GetData(), strDescription.GetData()
  795. , pAddresses->OperStatus, pAddresses->IfType, tmpip.GetData(), tmpmac.GetData());
  796. }
  797. pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
  798. }
  799. HeapFree(GetProcessHeap(), 0, pFirst);
  800. return Error_Succeed;
  801. #else
  802. std::map<std::string, std::string> inteIPs;
  803. std::map<std::string, std::string> inteMacs;
  804. std::map<std::string, int> inteStatus;
  805. char buf[512];
  806. toolkit_interface_address_t* info;
  807. int count, i;
  808. toolkit_interface_addresses(&info, &count);
  809. i = count;
  810. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of interfaces: %d", count);
  811. while (i--) {
  812. toolkit_interface_address_t interface = info[i];
  813. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s", interface.name);
  814. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Internal? %s", interface.is_internal ? "Yes" : "No");
  815. if (interface.address.address4.sin_family == AF_INET) {
  816. toolkit_ip4_name(&interface.address.address4, buf, sizeof(buf));
  817. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("IPv4 address: %s", buf);
  818. inteIPs[interface.name] = buf;
  819. }
  820. else if (interface.address.address4.sin_family == AF_INET6) {
  821. toolkit_ip6_name(&interface.address.address6, buf, sizeof(buf));
  822. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("IPv6 address: %s", buf);
  823. //inteIPs[interface.name] = buf;
  824. }
  825. }
  826. toolkit_free_interface_addresses(info, count);
  827. int fd, interface;
  828. struct ifreq bufIfreq[16];
  829. struct ifconf ifc;
  830. char mac[32] = { 0 };
  831. if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
  832. int i = 0;
  833. ifc.ifc_len = sizeof(bufIfreq);
  834. ifc.ifc_buf = (caddr_t)bufIfreq;
  835. if (!ioctl(fd, SIOCGIFCONF, (char*)& ifc)) {
  836. interface = ifc.ifc_len / sizeof(struct ifreq);
  837. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("interface num is %d", interface);
  838. while (i < interface) {
  839. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s", bufIfreq[i].ifr_name);
  840. if (!(ioctl(fd, SIOCGIFHWADDR, (char*)& bufIfreq[i]))) {
  841. sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X",
  842. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[0],
  843. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[1],
  844. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[2],
  845. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[3],
  846. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[4],
  847. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[5]);
  848. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("HWaddr %s", mac);
  849. inteMacs[bufIfreq[i].ifr_name] = mac;
  850. }
  851. struct ethtool_value edata;
  852. edata.cmd = ETHTOOL_GLINK;
  853. edata.data = 0;
  854. bufIfreq[i].ifr_data = (char*)& edata;
  855. //oiltmp@20231026 只检测了以太网卡
  856. if (ioctl(fd, SIOCETHTOOL, (char*)& bufIfreq[i]) == -1) {
  857. //up down
  858. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s is down", bufIfreq[i].ifr_name);
  859. inteStatus[bufIfreq[i].ifr_name] = 0;
  860. }
  861. else
  862. {
  863. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s is up", bufIfreq[i].ifr_name);
  864. inteStatus[bufIfreq[i].ifr_name] = 1;
  865. }
  866. i++;
  867. }
  868. }
  869. close(fd);
  870. }
  871. std::map<std::string, std::string>::const_iterator map_it = inteIPs.begin();
  872. while (map_it != inteIPs.end()) {
  873. NetworkAdapterItem netItem;
  874. CSimpleStringA tmpip(map_it->second.c_str());
  875. CSimpleStringA tmpmac(true);
  876. CSimpleStringA tmpname(true);
  877. auto it = inteMacs.find(std::string(map_it->first));
  878. if (it != inteMacs.end()) {
  879. tmpmac = it->second.c_str();
  880. }
  881. if (tmpip.Compare("127.0.0.1") == 0 && tmpmac.Compare("00:00:00:00:00:00") == 0) {
  882. //skip
  883. }
  884. else {
  885. tmpname = map_it->first.c_str();
  886. netItem.friend_name = "";//oiltmp
  887. netItem.description = tmpname;
  888. netItem.mac = tmpmac;
  889. netItem.ip = tmpip;
  890. netItem.operStatus = inteStatus[map_it->first];
  891. netItem.type = 6;//oiltest haven't find the in linux
  892. netLists.Append(&netItem, 0, 1);
  893. }
  894. ++map_it;
  895. }
  896. return Error_Succeed;
  897. #endif //RVC_OS_WIN
  898. }
  899. static std::vector<NetworkAdapterItem> GetNetAdapterItems()
  900. {
  901. std::vector<NetworkAdapterItem> results;
  902. #if defined(_MSC_VER)
  903. ULONG flags = GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_INCLUDE_GATEWAYS;
  904. ULONG family = AF_UNSPEC;
  905. PIP_ADAPTER_ADDRESSES address_ptr = nullptr;
  906. ULONG out_buf_len = 15000;
  907. DWORD ret_val = 0;
  908. PIP_ADAPTER_ADDRESSES cur_addr_ptr = nullptr;
  909. PIP_ADAPTER_UNICAST_ADDRESS unicast_ptr = nullptr;
  910. PIP_ADAPTER_ANYCAST_ADDRESS anycast_ptr = nullptr;
  911. PIP_ADAPTER_MULTICAST_ADDRESS multicast_ptr = nullptr;
  912. PIP_ADAPTER_DNS_SERVER_ADDRESS dns_server_ptr = nullptr;
  913. IP_ADAPTER_PREFIX* prefix_ptr = nullptr;
  914. do {
  915. address_ptr = (PIP_ADAPTER_ADDRESSES)malloc(out_buf_len);
  916. if (address_ptr == nullptr) {
  917. return results;
  918. }
  919. ret_val = GetAdaptersAddresses(family, flags, NULL, address_ptr, &out_buf_len);
  920. if (ERROR_BUFFER_OVERFLOW == ret_val) {
  921. free(address_ptr);
  922. }
  923. } while (ret_val == ERROR_BUFFER_OVERFLOW);
  924. if (NO_ERROR == ret_val) {
  925. cur_addr_ptr = address_ptr;
  926. while (cur_addr_ptr) {
  927. std::string description = Util::W2S(cur_addr_ptr->Description);
  928. bool is_local = IsLocalAdapter(cur_addr_ptr->AdapterName);
  929. std::string friend_name = Util::W2S(cur_addr_ptr->FriendlyName);
  930. NetworkAdapterItem item;
  931. item.idx = cur_addr_ptr->IfIndex;
  932. item.adapter_name = cur_addr_ptr->AdapterName;
  933. item.description = description;
  934. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)(">>>>>>>>>>>>>>> friendly name: %s", friend_name.c_str());
  935. item.friend_name = friend_name;
  936. if (is_local) {
  937. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Adapter Desc: %s", description.c_str());
  938. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Adapter Name: %s", cur_addr_ptr->AdapterName);
  939. item.isLocal = true;
  940. }
  941. if (cur_addr_ptr->PhysicalAddressLength != 0) {
  942. char sz_addr[32] = { 0 };
  943. std::stringstream str;
  944. for (int i = 0; i < (int)cur_addr_ptr->PhysicalAddressLength; i++) {
  945. if (i == ((int)cur_addr_ptr->PhysicalAddressLength - 1))
  946. sprintf_s(sz_addr, "%.2X", (int)cur_addr_ptr->PhysicalAddress[i]);
  947. else
  948. sprintf_s(sz_addr, "%.2X:", (int)cur_addr_ptr->PhysicalAddress[i]);
  949. str << sz_addr;
  950. }
  951. item.mac = str.str();
  952. }
  953. item.type = cur_addr_ptr->IfType;
  954. item.operStatus = cur_addr_ptr->OperStatus;
  955. switch (cur_addr_ptr->IfType) {
  956. case MIB_IF_TYPE_OTHER:
  957. break;
  958. case MIB_IF_TYPE_ETHERNET:
  959. break;
  960. case MIB_IF_TYPE_TOKENRING:
  961. break;
  962. case MIB_IF_TYPE_FDDI:
  963. break;
  964. case MIB_IF_TYPE_PPP:
  965. break;
  966. case MIB_IF_TYPE_LOOPBACK:
  967. break;
  968. case MIB_IF_TYPE_SLIP:
  969. break;
  970. case IF_TYPE_IEEE80211:
  971. break;
  972. case IF_TYPE_WWANPP:
  973. case IF_TYPE_WWANPP2:
  974. //WWAN devices
  975. break;
  976. default:
  977. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unknown type %d", cur_addr_ptr->IfType);
  978. break;
  979. }
  980. unicast_ptr = cur_addr_ptr->FirstUnicastAddress;
  981. while (unicast_ptr) {
  982. char ip[120] = { 0 };
  983. if (AF_INET == unicast_ptr->Address.lpSockaddr->sa_family) {
  984. inet_ntop(PF_INET, &((sockaddr_in*)unicast_ptr->Address.lpSockaddr)->sin_addr, ip, sizeof(ip));
  985. } else if (AF_INET6 == unicast_ptr->Address.lpSockaddr->sa_family) {
  986. inet_ntop(PF_INET6, &((sockaddr_in*)unicast_ptr->Address.lpSockaddr)->sin_addr, ip, sizeof(ip));
  987. }
  988. unicast_ptr = unicast_ptr->Next;
  989. }
  990. if (cur_addr_ptr->Dhcpv4Server.lpSockaddr) {
  991. char ip[120] = { 0 };
  992. if (AF_INET == cur_addr_ptr->Dhcpv4Server.lpSockaddr->sa_family) {
  993. inet_ntop(PF_INET, &((sockaddr_in*)cur_addr_ptr->Dhcpv4Server.lpSockaddr)->sin_addr, ip, sizeof(ip));
  994. } else if (AF_INET6 == cur_addr_ptr->Dhcpv4Server.lpSockaddr->sa_family) {
  995. inet_ntop(PF_INET6, &((sockaddr_in*)cur_addr_ptr->Dhcpv4Server.lpSockaddr)->sin_addr, ip, sizeof(ip));
  996. }
  997. item.dhcp = ip;
  998. }
  999. dns_server_ptr = cur_addr_ptr->FirstDnsServerAddress;
  1000. while (dns_server_ptr) {
  1001. char ip[120] = { 0 };
  1002. if (AF_INET == dns_server_ptr->Address.lpSockaddr->sa_family) {
  1003. inet_ntop(PF_INET, &((sockaddr_in*)dns_server_ptr->Address.lpSockaddr)->sin_addr, ip, sizeof(ip));
  1004. } else if (AF_INET6 == dns_server_ptr->Address.lpSockaddr->sa_family) {
  1005. inet_ntop(PF_INET6, &((sockaddr_in*)dns_server_ptr->Address.lpSockaddr)->sin_addr, ip, sizeof(ip));
  1006. }
  1007. dns_server_ptr = dns_server_ptr->Next;
  1008. }
  1009. auto gateway_ptr = cur_addr_ptr->FirstGatewayAddress;
  1010. while (gateway_ptr) {
  1011. char ip[120] = { 0 };
  1012. if (AF_INET == gateway_ptr->Address.lpSockaddr->sa_family) {
  1013. inet_ntop(PF_INET, &((sockaddr_in*)gateway_ptr->Address.lpSockaddr)->sin_addr, ip, sizeof(ip));
  1014. } else if (AF_INET6 == gateway_ptr->Address.lpSockaddr->sa_family) {
  1015. inet_ntop(PF_INET6, &((sockaddr_in*)gateway_ptr->Address.lpSockaddr)->sin_addr, ip, sizeof(ip));
  1016. }
  1017. gateway_ptr = gateway_ptr->Next;
  1018. }
  1019. results.push_back(item);
  1020. cur_addr_ptr = cur_addr_ptr->Next;
  1021. }
  1022. } else {
  1023. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("GetAdaptersAddresses failed with error: %d", ret_val);
  1024. }
  1025. free(address_ptr);
  1026. #else
  1027. ///*TODO(80374374@3/7/2023): */
  1028. #endif //_MSC_VER
  1029. return results;
  1030. }
  1031. static BOOL CheckLANConnectStatus()
  1032. {
  1033. #if defined(_MSC_VER)
  1034. DWORD dwFlag(0);
  1035. BOOL bRet = InternetGetConnectedState(&dwFlag, 0);
  1036. if ((dwFlag & INTERNET_CONNECTION_CONFIGURED) == INTERNET_CONNECTION_CONFIGURED) {
  1037. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Local system has a valid connection to the Internet, but it might or might not be currently connected.");
  1038. }
  1039. if ((dwFlag & INTERNET_CONNECTION_LAN) == INTERNET_CONNECTION_LAN) {
  1040. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Local system uses a local area network to connect to the Internet.");
  1041. }
  1042. if ((dwFlag & INTERNET_CONNECTION_MODEM) == INTERNET_CONNECTION_MODEM) {
  1043. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Local system uses a modem to connect to the Internet.");
  1044. }
  1045. if ((dwFlag & INTERNET_CONNECTION_MODEM_BUSY) == INTERNET_CONNECTION_MODEM_BUSY) {
  1046. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("No longer used: INTERNET_CONNECTION_MODEM_BUSY");
  1047. }
  1048. if ((dwFlag & INTERNET_CONNECTION_OFFLINE) == INTERNET_CONNECTION_OFFLINE) {
  1049. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Local system is in offline mode.");
  1050. }
  1051. if ((dwFlag & INTERNET_CONNECTION_PROXY) == INTERNET_CONNECTION_PROXY) {
  1052. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Local system uses a proxy server to connect to the Internet.");
  1053. }
  1054. if ((dwFlag & INTERNET_RAS_INSTALLED) == INTERNET_RAS_INSTALLED) {
  1055. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Local system has RAS installed.");
  1056. }
  1057. if (bRet) {
  1058. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("InternetGetConnectedState Succeed: 0x%08X", dwFlag);
  1059. } else {
  1060. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("InternetGetConnectedState failed: 0x%08X, GLE=%u", dwFlag, GetLastError());
  1061. }
  1062. return bRet;
  1063. #else
  1064. return FALSE;
  1065. #endif //_MSC_VER
  1066. }
  1067. static std::string GetWWWInfoThroughDig(const std::string& wwwUrl)
  1068. {
  1069. std::string succStr, errStr;
  1070. std::string runStr("dig ");
  1071. runStr += wwwUrl;
  1072. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  1073. return succStr;
  1074. } else {
  1075. return std::string("ShellExecute(") + wwwUrl + ") failed";
  1076. }
  1077. }
  1078. }//Net
  1079. namespace FileSystem {
  1080. static DWORD FetchFileSize(const char* filePath)
  1081. {
  1082. int fileSize = 0;
  1083. #if defined(RVC_OS_LINUX)
  1084. struct stat statbuf;
  1085. ZeroMemory(&statbuf, sizeof(statbuf));
  1086. stat(filePath, &statbuf);
  1087. fileSize = statbuf.st_size;
  1088. #else
  1089. HANDLE hFile;
  1090. hFile = CreateFile(filePath, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1091. if (hFile != INVALID_HANDLE_VALUE) {
  1092. fileSize = GetFileSize(hFile, NULL);
  1093. CloseHandle(hFile);
  1094. }
  1095. #endif //RVC_OS_LINUX
  1096. return fileSize;
  1097. }
  1098. }
  1099. } // mod
  1100. } // sp
  1101. #endif //RVC_MOD_COMM_ENTITY_UTIL_HPP_