123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847 |
- #ifndef RVC_MOD_COMM_ENTITY_UTIL_HPP_
- #define RVC_MOD_COMM_ENTITY_UTIL_HPP_
- #if defined(_MSC_VER)
- #include <Windows.h>
- #include <TlHelp32.h>
- #include <iphlpapi.h>
- #include <ws2tcpip.h>
- #include <Winsock2.h>
- #include <IPTypes.h>
- #include <WinInet.h>
- #include <ShlObj.h>
- #include <Pdh.h>
- #pragma comment(lib, "IPHLPAPI.lib")
- #pragma comment(lib, "Wininet.lib")
- #pragma comment(lib, "pdh.lib")
- #define streq stricmp
- #else
- #include <linux/ethtool.h>
- #include <linux/sockios.h>
- #include <net/if.h>
- #include <sys/ioctl.h>
- #include <sys/sysinfo.h>
- #include <unistd.h>
- #include <thread>
- #include <chrono>
- #define streq strcasecmp
- #endif //_MSC_VER
- #include "path.h"
- #include "toolkit.h"
- #include "charset.h"
- #include <string>
- #include <iostream>
- #include <sstream>
- #include <map>
- #include "SpBase.h"
- #include "publicFunExport.h"
- #define MACSESION 6
- #define DIV (1024 * 1024)
- #define DAY_DIV (24 * 60 * 60)
- #define HOURS_DIV (60 * 60)
- #define MINUS_DIV (60)
- typedef unsigned long long ULLINT;
- namespace SP
- {
- namespace Module
- {
- namespace System
- {
- static BOOL GetSystemBootTime(CSmallDateTime& systemBootTime)
- {
- #if defined(_MSC_VER)
- const char* SystemElapsedQuery = "\\System\\System Up Time";
- PDH_STATUS Status;
- HQUERY Query = NULL;
- HCOUNTER hcElapsedTimeCount;
- BOOL fSuc = FALSE;
- /** 杀毒软件会对附件这几个系统调用函数有所监控,导致有时会耗费5s时间 Gifur@20221019]*/
- Status = PdhOpenQuery(NULL, NULL, &Query);
- PDH_FMT_COUNTERVALUE counterValue;
- if (Status != ERROR_SUCCESS) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhOpenQuery failed with status 0x%x.", Status);
- goto Cleanup;
- }
- Status = PdhAddCounter(Query, SystemElapsedQuery, NULL, &hcElapsedTimeCount);
- if (Status != ERROR_SUCCESS) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhAddCounter for SystemElapsedQuery failed with status 0x%x.", Status);
- goto Cleanup;
- }
- // 查询性能监视器数据
- Status = PdhCollectQueryData(Query);
- if (Status != ERROR_SUCCESS) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhCollectQueryData failed with 0x%x.", Status);
- goto Cleanup;
- }
- Status = PdhGetFormattedCounterValue(hcElapsedTimeCount, PDH_FMT_LARGE, NULL, &counterValue);
- if (Status == ERROR_SUCCESS) {
- ULONGLONG ulSinceSeconds = counterValue.largeValue;
- ULONG days = 0, hours = 0, minutes = 0, seconds = 0;
- days = ULONG(ulSinceSeconds / DAY_DIV);
- ulSinceSeconds %= DAY_DIV;
- hours = ULONG(ulSinceSeconds / HOURS_DIV);
- ulSinceSeconds %= HOURS_DIV;
- minutes = ULONG(ulSinceSeconds / MINUS_DIV);
- ulSinceSeconds %= MINUS_DIV;
- seconds = ULONG(ulSinceSeconds);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SystemElapseTime: %uDays-%02u:%02u:%02u", days, hours, minutes, seconds);
- FILETIME ftCurTime, ftStartTime;
- GetSystemTimeAsFileTime(&ftCurTime);
- ULARGE_INTEGER uliCurTime;
- uliCurTime.HighPart = ftCurTime.dwHighDateTime;
- uliCurTime.LowPart = ftCurTime.dwLowDateTime;
- uliCurTime.QuadPart -= counterValue.largeValue * 1e7;
- ftStartTime.dwHighDateTime = uliCurTime.HighPart;
- ftStartTime.dwLowDateTime = uliCurTime.LowPart;
- SYSTEMTIME stUTC, stLocal;
- FileTimeToSystemTime(&ftStartTime, &stUTC);
- char temp[22];
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- sprintf_s(temp, 22, "%d-%02d-%02d %02d:%02d:%02d",
- stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OSStartTime: %s", temp);
- systemBootTime.FromSystemTime(stLocal);
- fSuc = TRUE;
- }
- Cleanup:
- Status = PdhRemoveCounter(hcElapsedTimeCount);
- if (Query) {
- PdhCloseQuery(Query);
- }
- return fSuc;
- #else
- DWORD ticks = 0;
- SYSTEMTIME systemTime;
- struct sysinfo info;
- time_t curTime = 0;
- time_t bootTime = 0;
- struct tm* ptm = NULL;
- if (sysinfo(&info)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Failed to get sysinfo, errno:%u, reason:%s", errno, strerror(errno));
- return FALSE;
- }
- time(&curTime);
- if (curTime > info.uptime) {
- bootTime = curTime - info.uptime;
- }
- else
- {
- bootTime = info.uptime - curTime;
- }
- ptm = localtime(&bootTime);
- struct timespec ts;
- if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
- ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
- systemTime.wYear = (WORD)(ptm->tm_year + 1900);
- systemTime.wMonth = (WORD)(ptm->tm_mon + 1);
- systemTime.wDayOfWeek = (WORD)ptm->tm_wday;
- systemTime.wDay = (WORD)ptm->tm_mday;
- systemTime.wHour = (WORD)ptm->tm_hour;
- systemTime.wMinute = (WORD)ptm->tm_min;
- systemTime.wSecond = (WORD)ptm->tm_sec;
- systemTime.wMilliseconds = (WORD)(ticks % 1000);
- systemBootTime.FromSystemTime(systemTime);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OSStartTime: %s", systemBootTime.ToTimeString().GetData());
- return TRUE;
- #endif //_MSC_VER
- }
- }//system
- namespace Comm
- {
- static BOOL IsFirsRunAppAfterSystemBoot(CEntityBase* pEntity, DWORD theReportUserCode = 0)
- {
- BOOL result(FALSE);
- CSystemRunInfo runInfo = { 0 };
- ErrorCodeEnum ec = pEntity->GetFunction()->GetSystemRunInfo(runInfo);
- if (ec == Error_Succeed) {
- CBootInfo bootInfo = { 0 };
- CSmallDateTime dateTime;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
- ec = pEntity->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
- CSmallDateTime systemBootTime;
- const BOOL bRet = System::GetSystemBootTime(systemBootTime);
- if (bRet && systemBootTime > bootInfo.tmStart) {
- result = TRUE;
- if (theReportUserCode != 0) {
- std::map<std::string, std::string> srcData;
- CSimpleStringA strData = CSimpleStringA::Format("{\"AppLastStartTime\":\"%s\",\"AppStartTime\":\"%s\",\"OSStartTime\":\"%s\"}"
- , (LPCTSTR)bootInfo.tmStart.ToTimeString(), (LPCTSTR)runInfo.tmStart.ToTimeString(), systemBootTime.ToTimeString().GetData());
- LogWarn(Severity_Low, Error_Debug, theReportUserCode, strData.GetData());
- }
- }
- }
- return result;
- }
- inline
- CSimpleStringA GetCurrMachineType(CEntityBase* pEntity)
- {
- CSystemStaticInfo sysInfo;
- pEntity->GetFunction()->GetSystemStaticInfo(sysInfo);
- return sysInfo.strMachineType;
- }
- enum Site
- {
- CMB_UNKNOWN,
- CMB_LIB, /** 行内大堂*/
- CMB_FLB, /** 离行机器*/
- };
- #define SITE_ENUM_TYPE(MACRO) \
- MACRO(LIB)\
- MACRO(FLB)
- #define ENUM_MAP_CONVERT(elem) \
- if (streq(lpcszSiteName, "CMB."#elem) == 0) return CMB_##elem;
- /*!
- * convert cmb site name to enum type.
- */
- static Site Str2Site(LPCSTR lpcszSiteName)
- {
- if (lpcszSiteName == NULL || strlen(lpcszSiteName) == 0)
- return CMB_UNKNOWN;
- SITE_ENUM_TYPE(ENUM_MAP_CONVERT)
- return CMB_UNKNOWN;
- }
- #undef ENUM_MAP_CONVERT
- #define ENUM_MAP_CONVERT(elem) case CMB_##elem: return "CMB."#elem;
- static LPCSTR Site2Str(Site site)
- {
- switch (site) {
- SITE_ENUM_TYPE(ENUM_MAP_CONVERT)
- default:
- break;
- }
- return "Unkown";
- }
- enum What
- {
- RVC_UNKNOWN,
- RVC_Stand2S, /** 落地式大机*/
- RVC_PAD, /** PAD*/
- RVC_Desk2S, /** 低柜双屏*/
- RVC_CardStore, /** 卡库*/
- RVC_CardPrinter, /** 制卡机*/
- RVC_Stand1SPlus /** 单屏大机*/
- };
- #define MACHINE_ENUM_TYPE(MACRO) \
- MACRO(Stand2S)\
- MACRO(PAD)\
- MACRO(Desk2S)\
- MACRO(CardStore)\
- MACRO(CardPrinter)\
- MACRO(Stand1SPlus)
- #undef ENUM_MAP_CONVERT
- #define ENUM_MAP_CONVERT(elem) \
- if (streq(lpcszTypeName, "RVC."#elem) == 0) return RVC_##elem;
- /*!
- * convert cmb site name to enum type.
- */
- static What Str2Type(LPCSTR lpcszTypeName)
- {
- if (lpcszTypeName == NULL || strlen(lpcszTypeName) == 0)
- return RVC_UNKNOWN;
- MACHINE_ENUM_TYPE(ENUM_MAP_CONVERT)
- return RVC_UNKNOWN;
- }
- #undef ENUM_MAP_CONVERT
- #define ENUM_MAP_CONVERT(elem) case RVC_##elem: return "RVC."#elem;
- static LPCSTR Type2Str(What what)
- {
- switch (what) {
- MACHINE_ENUM_TYPE(ENUM_MAP_CONVERT)
- default:
- break;
- }
- return "Unkown";
- }
- struct TerminalMachineInfo
- {
- Site site;
- What type;
- struct {
- WORD minor;
- WORD major;
- } gen;
- };
- inline TerminalMachineInfo GetTerminalMachineInfo(CEntityBase* pEntity)
- {
- CSystemStaticInfo sysInfo;
- TerminalMachineInfo termInfo;
- pEntity->GetFunction()->GetSystemStaticInfo(sysInfo);
- termInfo.site = Str2Site(sysInfo.strSite);
- termInfo.type = Str2Type(sysInfo.strMachineType);
- termInfo.gen.major = sysInfo.MachineVersion.GetMajor();
- termInfo.gen.minor = sysInfo.MachineVersion.GetMinor();
- return termInfo;
- }
- inline ULLINT RVCGetTickCount()
- {
- #ifdef RVC_OS_WIN
- return GetTickCount64();
- #else
- struct timespec ts;
- clock_gettime(CLOCK_MONOTONIC, &ts);
- return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
- #endif // RVC_OS_WIN
- }
- } // comm
- namespace Util
- {
- static int StrBuf2HexBuf(const char* strBuf, PBYTE* hexBuf)
- {
- int len = strlen(strBuf);
- if (len == 0 || len % 2 != 0)
- return 0;
- BYTE* buf = new BYTE[len / 2];
- if (buf == NULL)
- return 0;
- int j = 0;
- for (int i = 0; i < len;) {
- int tmpVal;
- sscanf(strBuf + i, "%2X", &tmpVal);
- buf[j] = tmpVal;
- i += 2;
- j++;
- }
- *hexBuf = buf;
- return j;
- }
- static int HexBuf2StrBuf(PBYTE hexBuf, char** strBuf, DWORD len)
- {
- char* tmpStr = *strBuf;
- DWORD count = 0;
- for (DWORD i = 0; i < len; ++i) {
- sprintf(tmpStr + count, "%0.2X", hexBuf[i]);
- count += 2;
- }
- return 0;
- }
- /*
- //tips: need to delete result char*
- static char* ConvertBytesToHexStr(BYTE* pBuf, int nLen)
- {
- char* pRet = (char*)new char[nLen * 2 + 1];
- memset(pRet, '\0', nLen * 2 + 1);
- char* p = pRet;
- for (int i = 0; i < nLen; i++) {
- BYTE b = pBuf[i];
- BYTE l = (b >> 4) & 0x0F;
- if (l >= 10)
- *p = l - 10 + 'a';
- else
- *p = l + '0';
- p++;
- BYTE r = b & 0x0F;
- if (r >= 10)
- *p = r - 10 + 'a';
- else
- *p = r + '0';
- p++;
- }
- return pRet;
- }
- static char HexChar2Dec(char c)
- {
- if ((c >= '0') && (c <= '9'))
- return c - '0';
- else if ((c >= 'A') && (c <= 'F'))
- return c - 'A' + 10;
- else if ((c >= 'a') && (c <= 'f'))
- return c - 'a' + 10;
- else
- return 0x10;
- }
- static int Hex2Int(char* s)
- {
- int ret = 0;
- while (*s) {
- int t = HexChar2Dec(*s);
- ret = ret * 16 + t;
- ++s;
- }
- return ret;
- }
- static void ConvAscii(unsigned char* Hex, char* Ascii, unsigned int len)
- {
- const unsigned char hextable[] = { "0123456789ABCDEF" };
- unsigned int i;
- for (i = 0; i < len; i++) {
- Ascii[2 * i] = hextable[Hex[i] >> 4];
- Ascii[2 * i + 1] = hextable[Hex[i] & 0xf];
- }
- Ascii[2 * len] = 0;
- }
- static void AsciiToHex(char* Ascii, unsigned char* Hex, int len)
- {
- int i;
- unsigned char ch;
- for (i = 0; i < len; i = i + 2) {
- ch = (Ascii[i] & 0xf);
- if (Ascii[i] > '9')
- ch += 9;
- Hex[i / 2] = ch << 4;
- ch = Ascii[i + 1] & 0xf;
- if (Ascii[i + 1] > '9')
- ch += 9;
- Hex[i / 2] += ch;
- }
- }
- static bool IsNoStr(const char* str)
- {
- int len = strlen(str);
- if (len == 0)
- return true;
- for (int i = 0; i < len; ++i) {
- if (*(str + i) != ' ')
- return false;
- }
- return true;
- }*/
- static std::string formatTime(const SYSTEMTIME& time)
- {
- char tBuf[1024] = "";
- sprintf(tBuf, "%04u-%02u-%02u %02u:%02u:%02u:%03u", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
- return tBuf;
- }
- static bool ShellExecute(const std::string& cmd, std::string& succResult, std::string& errResult)
- {
- succResult = errResult = "";
- char ps[1024] = { 0 };
- strcpy(ps, cmd.c_str());
- #if defined(_MSC_VER)
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
- ZeroMemory(&si, sizeof(si));
- si.cb = sizeof(si);
- si.wShowWindow = SW_HIDE;
- ZeroMemory(&pi, sizeof(pi));
- if (!CreateProcess(NULL, ps, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
- errResult = errResult + "CreateProcess failed with error:" + strerror(GetLastError());
- return false;
- }
- // 等待程序结束,并获取其退出状态
- WaitForSingleObject(pi.hProcess, INFINITE);
- DWORD exitCode;
- if (!GetExitCodeProcess(pi.hProcess, &exitCode)) {
- errResult = errResult + "GetExitCodeProcess failed with error code " + strerror(GetLastError());
- return false;
- }
- CloseHandle(pi.hProcess);
- CloseHandle(pi.hThread);
- if (exitCode != 0)
- {
- errResult = errResult + "The program exited with code:" + strerror(exitCode);
- return false;
- }
- return true;
- #else
- char buf_ps[1024];
- char result[2049] = { 0 };
- FILE* ptr;
- if ((ptr = popen(ps, "r")) != NULL) {
- while (fgets(buf_ps, 1024, ptr) != NULL) {
- if (strlen(result) + strlen(buf_ps) > 2048)
- break;
- strcat(result, buf_ps);
- }
- pclose(ptr);
- const int len = strlen(result);
- for (int i = len - 1; i >= 0 && (result[i] == '\r' || result[i] == '\n'); --i) {
- result[i] = '\0';
- }
- succResult = result;
- return true;
- } else {
- sprintf(result, "popen %s error: %d", ps, errno);
- errResult = result;
- return false;
- }
- #endif //_MSC_VER
- }
- static CSimpleStringA generateConsumeTimeJson(const CSimpleStringA& entityName, const CSimpleStringA& startTime, int cost)
- {
- return CSimpleStringA::Format("{\"name\":\"%s\",\"time\":\"%s\",\"cost\":%d}", entityName.GetData(), startTime.GetData(), cost);
- }
- #if defined(_MSC_VER)
- static void ConvertUtf82GBK(std::string& str)
- {
- char* dst = ConvertUtf8ToGBK(str.c_str());
- str = dst;
- if(dst) free(dst);
- }
- static void ConvertGBK2Utf8(std::string& str)
- {
- int len = 0;
- char* dst = ConvertGBKToUtf8(str.c_str(), &len);
- str = dst;
- if (dst) free(dst);
- }
- #else
- static void ConvertUtf82GBK(std::string& str)
- {
- std::string notrans(str);
- }
- static void ConvertGBK2Utf8(std::string& str)
- {
- std::string notrans(str);
- }
- #endif //_MSC_VER
- } //namespace Util
- namespace Net{
- struct NetworkAdapterItem
- {
- int idx;
- std::string friend_name;
- std::string adapter_name;
- std::string description;
- std::string ip;
- std::string mask;
- std::string mac;
- std::string gateway;
- std::string dhcp;
- bool is_physical;
- DWORD type;
- int operStatus;
- bool isLocal;
- NetworkAdapterItem() :idx(0), friend_name(""), adapter_name(""), description(""), ip(""), mask(""),
- mac(""), gateway(""), dhcp(""), is_physical(true), type(0), operStatus(0), isLocal(false)
- {
- }
- };
- static bool IsLocalAdapter(const std::string& name)
- {
- #if defined(_MSC_VER)
- if (name.length() <= 0) {
- return false;
- }
- std::string key("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
- HKEY h_sub_key = NULL;
- LONG ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_READ, &h_sub_key);
- if (ret != 0) {
- return false;
- }
- std::ostringstream str;
- str << name << "\\Connection";
- HKEY h_local_key = NULL;
- ret = RegOpenKeyEx(h_sub_key, str.str().c_str(), 0, KEY_READ, &h_local_key);
- if (0 != ret) {
- RegCloseKey(h_sub_key);
- return false;
- }
- DWORD type = REG_SZ;
- TCHAR buf[250];
- DWORD buf_size = 250;
- ret = RegQueryValueEx(h_local_key, "PnPInstanceId", 0, &type, (BYTE*)(buf), &buf_size);
- RegCloseKey(h_sub_key);
- RegCloseKey(h_local_key);
- if (0 != ret) {
- return false;
- }
- if (0 == strnicmp(buf, "PCI", strlen("PCI")) || 0 == strnicmp(buf, "USB", strlen("USB"))) {
- return true;
- }
- return false;
- #else
- ///*TODO(80374374@3/7/2023): */
- return true;
- #endif //_MSC_VER
- }
- static ErrorCodeEnum GetINETMacAddresses(CAutoArray<NetworkAdapterItem>& netLists)
- {
- #if defined(RVC_OS_WIN)
- PIP_ADAPTER_ADDRESSES pAddresses = NULL;
- ULONG family = AF_INET;
- ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
- ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
- // Make an initial call to GetAdaptersAddresses to get the
- // size needed into the outBufLen variable
- if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW) {
- pAddresses = static_cast<PIP_ADAPTER_ADDRESSES>(HeapAlloc(GetProcessHeap(), 0, outBufLen));
- }
- if (NULL == pAddresses) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pAddresses = NULL");
- return Error_Unexpect;
- }
- DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
- /* MACAddresses vAddress;*/
- if (dwRetVal != ERROR_SUCCESS) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("dwRetVal = %d", dwRetVal);
- return Error_Unexpect;
- }
- PIP_ADAPTER_ADDRESSES pFirst = pAddresses;
- while (pAddresses) {
- if (pAddresses->FirstUnicastAddress &&
- pAddresses->IfType != IF_TYPE_SOFTWARE_LOOPBACK &&
- pAddresses->OperStatus == IfOperStatusUp &&
- pAddresses->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET
- ) {
- NetworkAdapterItem netItem;
- BYTE* pa = pAddresses->PhysicalAddress;
- if (!pa) {
- pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
- continue;
- }
- CSimpleStringA strFriendlyName(true);
- CSimpleStringA strDescription(true);
- DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->FriendlyName, -1, NULL, 0, NULL, FALSE);
- char* psText = new char[dwNum];
- if (psText != NULL) {
- WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->FriendlyName, -1, psText, dwNum, NULL, FALSE);
- strFriendlyName = psText;
- delete[] psText;
- }
- dwNum = WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->Description, -1, NULL, 0, NULL, FALSE);
- psText = new char[dwNum];
- if (psText != NULL) {
- WideCharToMultiByte(CP_OEMCP, NULL, pAddresses->Description, -1, psText, dwNum, NULL, FALSE);
- strDescription = psText;
- delete[] psText;
- }
- char bAddressBytes[MACSESION];
- int bAddressInt[MACSESION];
- memset(bAddressBytes, 0, MACSESION);
- size_t nAddressSize = pAddresses->PhysicalAddressLength;
- memcpy(bAddressBytes, pa, (nAddressSize < MACSESION ? nAddressSize : MACSESION));
- for (int i = 0; i < MACSESION; ++i) {
- bAddressInt[i] = bAddressBytes[i];
- bAddressInt[i] &= 0x000000ff; // avoid "ff" leading bytes when "char" is lager then 0x7f
- }
- CSimpleStringA tmpmac = CSimpleStringA::Format("%02x:%02x:%02x:%02x:%02x:%02x",
- bAddressInt[0],
- bAddressInt[1],
- bAddressInt[2],
- bAddressInt[3],
- bAddressInt[4],
- bAddressInt[5]);
- sockaddr_in* sa_in = (sockaddr_in*)pAddresses->FirstUnicastAddress->Address.lpSockaddr;
- char buf_addr[100] = { 0 };
- CSimpleStringA tmpip = CSimpleStringA(inet_ntop(AF_INET, &(sa_in->sin_addr), buf_addr, 100));
-
- if (tmpip.Compare("127.0.0.1") == 0 && tmpmac.Compare("00:00:00:00:00:00") == 0) {
- //skip
- }
- else
- {
- netItem.friend_name = strFriendlyName;
- netItem.description = strDescription;
- netItem.mac = tmpmac;
- netItem.ip = tmpip;
- netItem.operStatus = (pAddresses->OperStatus == IfOperStatusUp) ? 1 : 0;//stay the same value with Linux/UOS
- netItem.type = pAddresses->IfType;
- netLists.Append(&netItem, 0, 1);
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s, %s: OperStatus: %d, IfType = %d, ip=%s, mac=%s"
- , strFriendlyName.GetData(), strDescription.GetData()
- , pAddresses->OperStatus, pAddresses->IfType, tmpip.GetData(), tmpmac.GetData());
- }
- pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
- }
- HeapFree(GetProcessHeap(), 0, pFirst);
- return Error_Succeed;
- #else
- std::map<std::string, std::string> inteIPs;
- std::map<std::string, std::string> inteMacs;
- std::map<std::string, int> inteStatus;
- char buf[512];
- toolkit_interface_address_t* info;
- int count, i;
- toolkit_interface_addresses(&info, &count);
- i = count;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of interfaces: %d", count);
- while (i--) {
- toolkit_interface_address_t interface = info[i];
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s", interface.name);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Internal? %s", interface.is_internal ? "Yes" : "No");
- if (interface.address.address4.sin_family == AF_INET) {
- toolkit_ip4_name(&interface.address.address4, buf, sizeof(buf));
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("IPv4 address: %s", buf);
- inteIPs[interface.name] = buf;
- }
- else if (interface.address.address4.sin_family == AF_INET6) {
- toolkit_ip6_name(&interface.address.address6, buf, sizeof(buf));
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("IPv6 address: %s", buf);
- //inteIPs[interface.name] = buf;
- }
- }
- toolkit_free_interface_addresses(info, count);
- int fd, interface;
- struct ifreq bufIfreq[16];
- struct ifconf ifc;
- char mac[32] = { 0 };
- if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
- int i = 0;
- ifc.ifc_len = sizeof(bufIfreq);
- ifc.ifc_buf = (caddr_t)bufIfreq;
- if (!ioctl(fd, SIOCGIFCONF, (char*)& ifc)) {
- interface = ifc.ifc_len / sizeof(struct ifreq);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("interface num is %d", interface);
- while (i < interface) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s", bufIfreq[i].ifr_name);
- if (!(ioctl(fd, SIOCGIFHWADDR, (char*)& bufIfreq[i]))) {
- sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X",
- (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[0],
- (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[1],
- (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[2],
- (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[3],
- (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[4],
- (unsigned char)bufIfreq[i].ifr_hwaddr.sa_data[5]);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("HWaddr %s", mac);
- inteMacs[bufIfreq[i].ifr_name] = mac;
- }
- struct ethtool_value edata;
- edata.cmd = ETHTOOL_GLINK;
- edata.data = 0;
- bufIfreq[i].ifr_data = (char*)& edata;
- //oiltmp@20231026 只检测了以太网卡
- if (ioctl(fd, SIOCETHTOOL, (char*)& bufIfreq[i]) == -1) {
- //up down
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s is down", bufIfreq[i].ifr_name);
- inteStatus[bufIfreq[i].ifr_name] = 0;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Name: %s is up", bufIfreq[i].ifr_name);
- inteStatus[bufIfreq[i].ifr_name] = 1;
- }
- i++;
- }
- }
- close(fd);
- }
- std::map<std::string, std::string>::const_iterator map_it = inteIPs.begin();
- while (map_it != inteIPs.end()) {
- NetworkAdapterItem netItem;
- CSimpleStringA tmpip(map_it->second.c_str());
- CSimpleStringA tmpmac(true);
- CSimpleStringA tmpname(true);
- auto it = inteMacs.find(std::string(map_it->first));
- if (it != inteMacs.end()) {
- tmpmac = it->second.c_str();
- }
- if (tmpip.Compare("127.0.0.1") == 0 && tmpmac.Compare("00:00:00:00:00:00") == 0) {
- //skip
- }
- else {
- tmpname = map_it->first.c_str();
- netItem.friend_name = "";//oiltmp
- netItem.description = tmpname;
- netItem.mac = tmpmac;
- netItem.ip = tmpip;
- netItem.operStatus = inteStatus[map_it->first];
- netItem.type = 6;//oiltest haven't find the in linux
- netLists.Append(&netItem, 0, 1);
- }
- ++map_it;
- }
- return Error_Succeed;
- #endif //RVC_OS_WIN
- }
- }//Net
- namespace FileSystem {
- static DWORD FetchFileSize(const char* filePath)
- {
- int fileSize = 0;
- #if defined(RVC_OS_LINUX)
- struct stat statbuf;
- ZeroMemory(&statbuf, sizeof(statbuf));
- stat(filePath, &statbuf);
- fileSize = statbuf.st_size;
- #else
-
- HANDLE hFile;
- hFile = CreateFile(filePath, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
- if (hFile != INVALID_HANDLE_VALUE) {
- fileSize = GetFileSize(hFile, NULL);
- CloseHandle(hFile);
- }
- #endif //RVC_OS_LINUX
- return fileSize;
- }
- }
- } // mod
- } // sp
- #endif //RVC_MOD_COMM_ENTITY_UTIL_HPP_
|