CommEntityUtil.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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 "charset.h"
  31. #include <string>
  32. #include <iostream>
  33. #include <sstream>
  34. #include <map>
  35. #include "SpBase.h"
  36. #include "publicFunExport.h"
  37. #define MACSESION 6
  38. #define DIV (1024 * 1024)
  39. #define DAY_DIV (24 * 60 * 60)
  40. #define HOURS_DIV (60 * 60)
  41. #define MINUS_DIV (60)
  42. typedef unsigned long long ULLINT;
  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. static BOOL IsFirsRunAppAfterSystemBoot(CEntityBase* pEntity, DWORD theReportUserCode = 0)
  151. {
  152. BOOL result(FALSE);
  153. CSystemRunInfo runInfo = { 0 };
  154. ErrorCodeEnum ec = pEntity->GetFunction()->GetSystemRunInfo(runInfo);
  155. if (ec == Error_Succeed) {
  156. CBootInfo bootInfo = { 0 };
  157. CSmallDateTime dateTime;
  158. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
  159. ec = pEntity->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
  160. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
  161. CSmallDateTime systemBootTime;
  162. const BOOL bRet = System::GetSystemBootTime(systemBootTime);
  163. if (bRet && systemBootTime > bootInfo.tmStart) {
  164. result = TRUE;
  165. if (theReportUserCode != 0) {
  166. std::map<std::string, std::string> srcData;
  167. CSimpleStringA strData = CSimpleStringA::Format("{\"AppLastStartTime\":\"%s\",\"AppStartTime\":\"%s\",\"OSStartTime\":\"%s\"}"
  168. , (LPCTSTR)bootInfo.tmStart.ToTimeString(), (LPCTSTR)runInfo.tmStart.ToTimeString(), systemBootTime.ToTimeString().GetData());
  169. LogWarn(Severity_Low, Error_Debug, theReportUserCode, strData.GetData());
  170. }
  171. }
  172. }
  173. return result;
  174. }
  175. inline
  176. CSimpleStringA GetCurrMachineType(CEntityBase* pEntity)
  177. {
  178. CSystemStaticInfo sysInfo;
  179. pEntity->GetFunction()->GetSystemStaticInfo(sysInfo);
  180. return sysInfo.strMachineType;
  181. }
  182. enum Site
  183. {
  184. CMB_UNKNOWN,
  185. CMB_LIB, /** 行内大堂*/
  186. CMB_FLB, /** 离行机器*/
  187. };
  188. #define SITE_ENUM_TYPE(MACRO) \
  189. MACRO(LIB)\
  190. MACRO(FLB)
  191. #define ENUM_MAP_CONVERT(elem) \
  192. if (streq(lpcszSiteName, "CMB."#elem) == 0) return CMB_##elem;
  193. /*!
  194. * convert cmb site name to enum type.
  195. */
  196. static Site Str2Site(LPCSTR lpcszSiteName)
  197. {
  198. if (lpcszSiteName == NULL || strlen(lpcszSiteName) == 0)
  199. return CMB_UNKNOWN;
  200. SITE_ENUM_TYPE(ENUM_MAP_CONVERT)
  201. return CMB_UNKNOWN;
  202. }
  203. #undef ENUM_MAP_CONVERT
  204. #define ENUM_MAP_CONVERT(elem) case CMB_##elem: return "CMB."#elem;
  205. static LPCSTR Site2Str(Site site)
  206. {
  207. switch (site) {
  208. SITE_ENUM_TYPE(ENUM_MAP_CONVERT)
  209. default:
  210. break;
  211. }
  212. return "Unkown";
  213. }
  214. enum What
  215. {
  216. RVC_UNKNOWN,
  217. RVC_Stand2S, /** 落地式大机*/
  218. RVC_PAD, /** PAD*/
  219. RVC_Desk2S, /** 低柜双屏*/
  220. RVC_CardStore, /** 卡库*/
  221. RVC_CardPrinter, /** 制卡机*/
  222. RVC_Stand1SPlus /** 单屏大机*/
  223. };
  224. #define MACHINE_ENUM_TYPE(MACRO) \
  225. MACRO(Stand2S)\
  226. MACRO(PAD)\
  227. MACRO(Desk2S)\
  228. MACRO(CardStore)\
  229. MACRO(CardPrinter)\
  230. MACRO(Stand1SPlus)
  231. #undef ENUM_MAP_CONVERT
  232. #define ENUM_MAP_CONVERT(elem) \
  233. if (streq(lpcszTypeName, "RVC."#elem) == 0) return RVC_##elem;
  234. /*!
  235. * convert cmb site name to enum type.
  236. */
  237. static What Str2Type(LPCSTR lpcszTypeName)
  238. {
  239. if (lpcszTypeName == NULL || strlen(lpcszTypeName) == 0)
  240. return RVC_UNKNOWN;
  241. MACHINE_ENUM_TYPE(ENUM_MAP_CONVERT)
  242. return RVC_UNKNOWN;
  243. }
  244. #undef ENUM_MAP_CONVERT
  245. #define ENUM_MAP_CONVERT(elem) case RVC_##elem: return "RVC."#elem;
  246. static LPCSTR Type2Str(What what)
  247. {
  248. switch (what) {
  249. MACHINE_ENUM_TYPE(ENUM_MAP_CONVERT)
  250. default:
  251. break;
  252. }
  253. return "Unkown";
  254. }
  255. struct TerminalMachineInfo
  256. {
  257. Site site;
  258. What type;
  259. struct {
  260. WORD minor;
  261. WORD major;
  262. } gen;
  263. };
  264. inline TerminalMachineInfo GetTerminalMachineInfo(CEntityBase* pEntity)
  265. {
  266. CSystemStaticInfo sysInfo;
  267. TerminalMachineInfo termInfo;
  268. pEntity->GetFunction()->GetSystemStaticInfo(sysInfo);
  269. termInfo.site = Str2Site(sysInfo.strSite);
  270. termInfo.type = Str2Type(sysInfo.strMachineType);
  271. termInfo.gen.major = sysInfo.MachineVersion.GetMajor();
  272. termInfo.gen.minor = sysInfo.MachineVersion.GetMinor();
  273. return termInfo;
  274. }
  275. inline ULLINT RVCGetTickCount()
  276. {
  277. #ifdef RVC_OS_WIN
  278. return GetTickCount64();
  279. #else
  280. struct timespec ts;
  281. clock_gettime(CLOCK_MONOTONIC, &ts);
  282. return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
  283. #endif // RVC_OS_WIN
  284. }
  285. } // comm
  286. namespace Util
  287. {
  288. static int StrBuf2HexBuf(const char* strBuf, PBYTE* hexBuf)
  289. {
  290. int len = strlen(strBuf);
  291. if (len == 0 || len % 2 != 0)
  292. return 0;
  293. BYTE* buf = new BYTE[len / 2];
  294. if (buf == NULL)
  295. return 0;
  296. int j = 0;
  297. for (int i = 0; i < len;) {
  298. int tmpVal;
  299. sscanf(strBuf + i, "%2X", &tmpVal);
  300. buf[j] = tmpVal;
  301. i += 2;
  302. j++;
  303. }
  304. *hexBuf = buf;
  305. return j;
  306. }
  307. static int HexBuf2StrBuf(PBYTE hexBuf, char** strBuf, DWORD len)
  308. {
  309. char* tmpStr = *strBuf;
  310. DWORD count = 0;
  311. for (DWORD i = 0; i < len; ++i) {
  312. sprintf(tmpStr + count, "%0.2X", hexBuf[i]);
  313. count += 2;
  314. }
  315. return 0;
  316. }
  317. /*
  318. //tips: need to delete result char*
  319. static char* ConvertBytesToHexStr(BYTE* pBuf, int nLen)
  320. {
  321. char* pRet = (char*)new char[nLen * 2 + 1];
  322. memset(pRet, '\0', nLen * 2 + 1);
  323. char* p = pRet;
  324. for (int i = 0; i < nLen; i++) {
  325. BYTE b = pBuf[i];
  326. BYTE l = (b >> 4) & 0x0F;
  327. if (l >= 10)
  328. *p = l - 10 + 'a';
  329. else
  330. *p = l + '0';
  331. p++;
  332. BYTE r = b & 0x0F;
  333. if (r >= 10)
  334. *p = r - 10 + 'a';
  335. else
  336. *p = r + '0';
  337. p++;
  338. }
  339. return pRet;
  340. }
  341. static char HexChar2Dec(char c)
  342. {
  343. if ((c >= '0') && (c <= '9'))
  344. return c - '0';
  345. else if ((c >= 'A') && (c <= 'F'))
  346. return c - 'A' + 10;
  347. else if ((c >= 'a') && (c <= 'f'))
  348. return c - 'a' + 10;
  349. else
  350. return 0x10;
  351. }
  352. static int Hex2Int(char* s)
  353. {
  354. int ret = 0;
  355. while (*s) {
  356. int t = HexChar2Dec(*s);
  357. ret = ret * 16 + t;
  358. ++s;
  359. }
  360. return ret;
  361. }
  362. static void ConvAscii(unsigned char* Hex, char* Ascii, unsigned int len)
  363. {
  364. const unsigned char hextable[] = { "0123456789ABCDEF" };
  365. unsigned int i;
  366. for (i = 0; i < len; i++) {
  367. Ascii[2 * i] = hextable[Hex[i] >> 4];
  368. Ascii[2 * i + 1] = hextable[Hex[i] & 0xf];
  369. }
  370. Ascii[2 * len] = 0;
  371. }
  372. static void AsciiToHex(char* Ascii, unsigned char* Hex, int len)
  373. {
  374. int i;
  375. unsigned char ch;
  376. for (i = 0; i < len; i = i + 2) {
  377. ch = (Ascii[i] & 0xf);
  378. if (Ascii[i] > '9')
  379. ch += 9;
  380. Hex[i / 2] = ch << 4;
  381. ch = Ascii[i + 1] & 0xf;
  382. if (Ascii[i + 1] > '9')
  383. ch += 9;
  384. Hex[i / 2] += ch;
  385. }
  386. }
  387. static bool IsNoStr(const char* str)
  388. {
  389. int len = strlen(str);
  390. if (len == 0)
  391. return true;
  392. for (int i = 0; i < len; ++i) {
  393. if (*(str + i) != ' ')
  394. return false;
  395. }
  396. return true;
  397. }*/
  398. static std::string formatTime(const SYSTEMTIME& time)
  399. {
  400. char tBuf[1024] = "";
  401. sprintf(tBuf, "%04u-%02u-%02u %02u:%02u:%02u:%03u", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
  402. return tBuf;
  403. }
  404. static bool ShellExecute(const std::string& cmd, std::string& succResult, std::string& errResult)
  405. {
  406. succResult = errResult = "";
  407. char ps[1024] = { 0 };
  408. strcpy(ps, cmd.c_str());
  409. #if defined(_MSC_VER)
  410. STARTUPINFO si;
  411. PROCESS_INFORMATION pi;
  412. ZeroMemory(&si, sizeof(si));
  413. si.cb = sizeof(si);
  414. si.wShowWindow = SW_HIDE;
  415. ZeroMemory(&pi, sizeof(pi));
  416. if (!CreateProcess(NULL, ps, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
  417. errResult = errResult + "CreateProcess failed with error:" + strerror(GetLastError());
  418. return false;
  419. }
  420. // 等待程序结束,并获取其退出状态
  421. WaitForSingleObject(pi.hProcess, INFINITE);
  422. DWORD exitCode;
  423. if (!GetExitCodeProcess(pi.hProcess, &exitCode)) {
  424. errResult = errResult + "GetExitCodeProcess failed with error code " + strerror(GetLastError());
  425. return false;
  426. }
  427. CloseHandle(pi.hProcess);
  428. CloseHandle(pi.hThread);
  429. if (exitCode != 0)
  430. {
  431. errResult = errResult + "The program exited with code:" + strerror(exitCode);
  432. return false;
  433. }
  434. return true;
  435. #else
  436. char buf_ps[1024];
  437. char result[2049] = { 0 };
  438. FILE* ptr;
  439. if ((ptr = popen(ps, "r")) != NULL) {
  440. while (fgets(buf_ps, 1024, ptr) != NULL) {
  441. if (strlen(result) + strlen(buf_ps) > 2048)
  442. break;
  443. strcat(result, buf_ps);
  444. }
  445. pclose(ptr);
  446. const int len = strlen(result);
  447. for (int i = len - 1; i >= 0 && (result[i] == '\r' || result[i] == '\n'); --i) {
  448. result[i] = '\0';
  449. }
  450. succResult = result;
  451. return true;
  452. } else {
  453. sprintf(result, "popen %s error: %d", ps, errno);
  454. errResult = result;
  455. return false;
  456. }
  457. #endif //_MSC_VER
  458. }
  459. static CSimpleStringA generateConsumeTimeJson(const CSimpleStringA& entityName, const CSimpleStringA& startTime, int cost)
  460. {
  461. return CSimpleStringA::Format("{\"name\":\"%s\",\"time\":\"%s\",\"cost\":%d}", entityName.GetData(), startTime.GetData(), cost);
  462. }
  463. #if defined(_MSC_VER)
  464. static void ConvertUtf82GBK(std::string& str)
  465. {
  466. char* dst = ConvertUtf8ToGBK(str.c_str());
  467. str = dst;
  468. if(dst) free(dst);
  469. }
  470. static void ConvertGBK2Utf8(std::string& str)
  471. {
  472. int len = 0;
  473. char* dst = ConvertGBKToUtf8(str.c_str(), &len);
  474. str = dst;
  475. if (dst) free(dst);
  476. }
  477. #else
  478. static void ConvertUtf82GBK(std::string& str)
  479. {
  480. std::string notrans(str);
  481. }
  482. static void ConvertGBK2Utf8(std::string& str)
  483. {
  484. std::string notrans(str);
  485. }
  486. #endif //_MSC_VER
  487. } //namespace Util
  488. namespace Net{
  489. struct NetworkAdapterItem
  490. {
  491. int idx;
  492. std::string friend_name;
  493. std::string adapter_name;
  494. std::string description;
  495. std::string ip;
  496. std::string mask;
  497. std::string mac;
  498. std::string gateway;
  499. std::string dhcp;
  500. bool is_physical;
  501. DWORD type;
  502. int operStatus;
  503. bool isLocal;
  504. NetworkAdapterItem() :idx(0), friend_name(""), adapter_name(""), description(""), ip(""), mask(""),
  505. mac(""), gateway(""), dhcp(""), is_physical(true), type(0), operStatus(0), isLocal(false)
  506. {
  507. }
  508. };
  509. static bool IsLocalAdapter(const std::string& name)
  510. {
  511. #if defined(_MSC_VER)
  512. if (name.length() <= 0) {
  513. return false;
  514. }
  515. std::string key("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
  516. HKEY h_sub_key = NULL;
  517. LONG ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_READ, &h_sub_key);
  518. if (ret != 0) {
  519. return false;
  520. }
  521. std::ostringstream str;
  522. str << name << "\\Connection";
  523. HKEY h_local_key = NULL;
  524. ret = RegOpenKeyEx(h_sub_key, str.str().c_str(), 0, KEY_READ, &h_local_key);
  525. if (0 != ret) {
  526. RegCloseKey(h_sub_key);
  527. return false;
  528. }
  529. DWORD type = REG_SZ;
  530. TCHAR buf[250];
  531. DWORD buf_size = 250;
  532. ret = RegQueryValueEx(h_local_key, "PnPInstanceId", 0, &type, (BYTE*)(buf), &buf_size);
  533. RegCloseKey(h_sub_key);
  534. RegCloseKey(h_local_key);
  535. if (0 != ret) {
  536. return false;
  537. }
  538. if (0 == strnicmp(buf, "PCI", strlen("PCI")) || 0 == strnicmp(buf, "USB", strlen("USB"))) {
  539. return true;
  540. }
  541. return false;
  542. #else
  543. ///*TODO(80374374@3/7/2023): */
  544. return true;
  545. #endif //_MSC_VER
  546. }
  547. static ErrorCodeEnum GetINETMacAddresses(CAutoArray<NetworkAdapterItem>& netLists)
  548. {
  549. #if defined(RVC_OS_WIN)
  550. PIP_ADAPTER_ADDRESSES pAddresses = NULL;
  551. ULONG family = AF_INET;
  552. ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
  553. ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
  554. // Make an initial call to GetAdaptersAddresses to get the
  555. // size needed into the outBufLen variable
  556. if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW) {
  557. pAddresses = static_cast<PIP_ADAPTER_ADDRESSES>(HeapAlloc(GetProcessHeap(), 0, outBufLen));
  558. }
  559. if (NULL == pAddresses) {
  560. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pAddresses = NULL");
  561. return Error_Unexpect;
  562. }
  563. DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
  564. /* MACAddresses vAddress;*/
  565. if (dwRetVal != ERROR_SUCCESS) {
  566. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("dwRetVal = %d", dwRetVal);
  567. return Error_Unexpect;
  568. }
  569. PIP_ADAPTER_ADDRESSES pFirst = pAddresses;
  570. while (pAddresses) {
  571. if (pAddresses->FirstUnicastAddress &&
  572. pAddresses->IfType != IF_TYPE_SOFTWARE_LOOPBACK &&
  573. pAddresses->OperStatus == IfOperStatusUp &&
  574. pAddresses->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET
  575. ) {
  576. NetworkAdapterItem netItem;
  577. BYTE* pa = pAddresses->PhysicalAddress;
  578. if (!pa) {
  579. pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
  580. continue;
  581. }
  582. CSimpleStringA strFriendlyName(true);
  583. CSimpleStringA strDescription(true);
  584. DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->FriendlyName, -1, NULL, 0, NULL, FALSE);
  585. char* psText = new char[dwNum];
  586. if (psText != NULL) {
  587. WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->FriendlyName, -1, psText, dwNum, NULL, FALSE);
  588. strFriendlyName = psText;
  589. delete[] psText;
  590. }
  591. dwNum = WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->Description, -1, NULL, 0, NULL, FALSE);
  592. psText = new char[dwNum];
  593. if (psText != NULL) {
  594. WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->Description, -1, psText, dwNum, NULL, FALSE);
  595. strDescription = psText;
  596. delete[] psText;
  597. }
  598. char bAddressBytes[MACSESION];
  599. int bAddressInt[MACSESION];
  600. memset(bAddressBytes, 0, MACSESION);
  601. size_t nAddressSize = pAddresses->PhysicalAddressLength;
  602. memcpy(bAddressBytes, pa, (nAddressSize < MACSESION ? nAddressSize : MACSESION));
  603. for (int i = 0; i < MACSESION; ++i) {
  604. bAddressInt[i] = bAddressBytes[i];
  605. bAddressInt[i] &= 0x000000ff; // avoid "ff" leading bytes when "char" is lager then 0x7f
  606. }
  607. CSimpleStringA tmpmac = CSimpleStringA::Format("%02x:%02x:%02x:%02x:%02x:%02x",
  608. bAddressInt[0],
  609. bAddressInt[1],
  610. bAddressInt[2],
  611. bAddressInt[3],
  612. bAddressInt[4],
  613. bAddressInt[5]);
  614. sockaddr_in* sa_in = (sockaddr_in*)pAddresses->FirstUnicastAddress->Address.lpSockaddr;
  615. char buf_addr[100] = { 0 };
  616. CSimpleStringA tmpip = CSimpleStringA(inet_ntop(AF_INET, &(sa_in->sin_addr), buf_addr, 100));
  617. if (tmpip.Compare("127.0.0.1") == 0 && tmpmac.Compare("00:00:00:00:00:00") == 0) {
  618. //skip
  619. }
  620. else
  621. {
  622. netItem.friend_name = strFriendlyName;
  623. netItem.description = strDescription;
  624. netItem.mac = tmpmac;
  625. netItem.ip = tmpip;
  626. netItem.operStatus = (pAddresses->OperStatus == IfOperStatusUp) ? 1 : 0;//stay the same value with Linux/UOS
  627. netItem.type = pAddresses->IfType;
  628. netLists.Append(&netItem, 0, 1);
  629. }
  630. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s, %s: OperStatus: %d, IfType = %d, ip=%s, mac=%s"
  631. , strFriendlyName.GetData(), strDescription.GetData()
  632. , pAddresses->OperStatus, pAddresses->IfType, tmpip.GetData(), tmpmac.GetData());
  633. }
  634. pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
  635. }
  636. HeapFree(GetProcessHeap(), 0, pFirst);
  637. return Error_Succeed;
  638. #else
  639. std::map<std::string, std::string> inteIPs;
  640. std::map<std::string, std::string> inteMacs;
  641. std::map<std::string, int> inteStatus;
  642. char buf[512];
  643. toolkit_interface_address_t* info;
  644. int count, i;
  645. toolkit_interface_addresses(&info, &count);
  646. i = count;
  647. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of interfaces: %d", count);
  648. while (i--) {
  649. toolkit_interface_address_t interface = info[i];
  650. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s", interface.name);
  651. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Internal? %s", interface.is_internal ? "Yes" : "No");
  652. if (interface.address.address4.sin_family == AF_INET) {
  653. toolkit_ip4_name(&interface.address.address4, buf, sizeof(buf));
  654. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("IPv4 address: %s", buf);
  655. inteIPs[interface.name] = buf;
  656. }
  657. else if (interface.address.address4.sin_family == AF_INET6) {
  658. toolkit_ip6_name(&interface.address.address6, buf, sizeof(buf));
  659. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("IPv6 address: %s", buf);
  660. //inteIPs[interface.name] = buf;
  661. }
  662. }
  663. toolkit_free_interface_addresses(info, count);
  664. int fd, interface;
  665. struct ifreq bufIfreq[16];
  666. struct ifconf ifc;
  667. char mac[32] = { 0 };
  668. if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
  669. int i = 0;
  670. ifc.ifc_len = sizeof(bufIfreq);
  671. ifc.ifc_buf = (caddr_t)bufIfreq;
  672. if (!ioctl(fd, SIOCGIFCONF, (char*)& ifc)) {
  673. interface = ifc.ifc_len / sizeof(struct ifreq);
  674. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("interface num is %d", interface);
  675. while (i < interface) {
  676. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s", bufIfreq[i].ifr_name);
  677. if (!(ioctl(fd, SIOCGIFHWADDR, (char*)& bufIfreq[i]))) {
  678. sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X",
  679. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[0],
  680. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[1],
  681. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[2],
  682. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[3],
  683. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[4],
  684. (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[5]);
  685. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("HWaddr %s", mac);
  686. inteMacs[bufIfreq[i].ifr_name] = mac;
  687. }
  688. struct ethtool_value edata;
  689. edata.cmd = ETHTOOL_GLINK;
  690. edata.data = 0;
  691. bufIfreq[i].ifr_data = (char*)& edata;
  692. //oiltmp@20231026 只检测了以太网卡
  693. if (ioctl(fd, SIOCETHTOOL, (char*)& bufIfreq[i]) == -1) {
  694. //up down
  695. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s is down", bufIfreq[i].ifr_name);
  696. inteStatus[bufIfreq[i].ifr_name] = 0;
  697. }
  698. else
  699. {
  700. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s is up", bufIfreq[i].ifr_name);
  701. inteStatus[bufIfreq[i].ifr_name] = 1;
  702. }
  703. i++;
  704. }
  705. }
  706. close(fd);
  707. }
  708. std::map<std::string, std::string>::const_iterator map_it = inteIPs.begin();
  709. while (map_it != inteIPs.end()) {
  710. NetworkAdapterItem netItem;
  711. CSimpleStringA tmpip(map_it->second.c_str());
  712. CSimpleStringA tmpmac(true);
  713. CSimpleStringA tmpname(true);
  714. auto it = inteMacs.find(std::string(map_it->first));
  715. if (it != inteMacs.end()) {
  716. tmpmac = it->second.c_str();
  717. }
  718. if (tmpip.Compare("127.0.0.1") == 0 && tmpmac.Compare("00:00:00:00:00:00") == 0) {
  719. //skip
  720. }
  721. else {
  722. tmpname = map_it->first.c_str();
  723. netItem.friend_name = "";//oiltmp
  724. netItem.description = tmpname;
  725. netItem.mac = tmpmac;
  726. netItem.ip = tmpip;
  727. netItem.operStatus = inteStatus[map_it->first];
  728. netItem.type = 6;//oiltest haven't find the in linux
  729. netLists.Append(&netItem, 0, 1);
  730. }
  731. ++map_it;
  732. }
  733. return Error_Succeed;
  734. #endif //RVC_OS_WIN
  735. }
  736. }//Net
  737. namespace FileSystem {
  738. static DWORD FetchFileSize(const char* filePath)
  739. {
  740. int fileSize = 0;
  741. #if defined(RVC_OS_LINUX)
  742. struct stat statbuf;
  743. ZeroMemory(&statbuf, sizeof(statbuf));
  744. stat(filePath, &statbuf);
  745. fileSize = statbuf.st_size;
  746. #else
  747. HANDLE hFile;
  748. hFile = CreateFile(filePath, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  749. if (hFile != INVALID_HANDLE_VALUE) {
  750. fileSize = GetFileSize(hFile, NULL);
  751. CloseHandle(hFile);
  752. }
  753. #endif //RVC_OS_LINUX
  754. return fileSize;
  755. }
  756. }
  757. } // mod
  758. } // sp
  759. #endif //RVC_MOD_COMM_ENTITY_UTIL_HPP_