Global.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. #include "StdAfx.h"
  2. #include "Global.h"
  3. // 获取文件版本号函数头文件;
  4. #include <WinVer.h>
  5. #pragma comment(lib,"version.lib")
  6. using namespace std;
  7. #include <psapi.h>
  8. #pragma comment(lib,"Psapi.lib")
  9. #include <locale.h>
  10. #include <io.h>//_access头文件;
  11. namespace GLOBAL
  12. {
  13. CIOCPPipe g_IOCP;
  14. CONFIG g_config;
  15. TCHAR g_szModulePath[MAX_PATH] = _T(""); // 软件目录;
  16. TCHAR g_szModuleFileName[MAX_PATH] = _T(""); // 软件名称;
  17. TCHAR g_szConfigFile[MAX_PATH] = _T("");
  18. PROC_WND_INFO g_procWndInfo;
  19. // DLL注入状态;
  20. BOOL g_bInjected = FALSE;
  21. #define TRACE4(sz, p1, p2, p3, p4) TRACE(_T(sz), p1, p2, p3, p4)
  22. BOOL GetConfigInfo(LPCTSTR lpIniDir /* = NULL */, LPCTSTR lpConfigName /* = NULL */)
  23. {
  24. TCHAR szDrive[_MAX_DRIVE] = { 0 };
  25. TCHAR szDir[_MAX_DIR] = { 0 };
  26. TCHAR szFna[_MAX_DIR] = { 0 };
  27. TCHAR szExt[_MAX_DIR] = { 0 };
  28. ::GetModuleFileName(NULL, g_szModulePath, sizeof(g_szModulePath) / sizeof(TCHAR));
  29. _stprintf_s(g_szModuleFileName, _T("%s"), g_szModulePath);
  30. _tsplitpath_s(g_szModulePath, szDrive, szDir, szFna, szExt);
  31. _tcscpy_s(g_szModulePath, szDrive);
  32. _tcscat_s(g_szModulePath, szDir);
  33. if (lpIniDir != NULL && lpConfigName != NULL)
  34. _stprintf_s(g_szConfigFile, _T("%s%s"), lpIniDir, lpConfigName);
  35. else
  36. _stprintf_s(g_szConfigFile, _T("%s%s.ini"), g_szModulePath, szFna);
  37. HANDLE hFile = CreateFile(g_szConfigFile, 0/*GENERIC_READ*/, 0, NULL, OPEN_EXISTING, 0, NULL);
  38. if (ERROR_FILE_NOT_FOUND == GetLastError())
  39. {
  40. return FALSE;
  41. }
  42. CloseHandle(hFile);
  43. hFile = NULL;
  44. #pragma region 获取配置文件信息;
  45. TCHAR szValue[MAX_PATH] = {0};
  46. // LOGIN;
  47. GetPrivateProfileString(_T("LOGIN"), _T("account"), _T(""), g_config.szAccount, MAX_PATH, g_szConfigFile);
  48. GetPrivateProfileString(_T("LOGIN"), _T("password"), _T(""), g_config.szPassword, MAX_PATH, g_szConfigFile);
  49. GetPrivateProfileString(_T("LOGIN"), _T("line"), _T(""), g_config.szLine, MAX_PATH, g_szConfigFile);
  50. g_config.nOffline = GetPrivateProfileInt(_T("LOGIN"), _T("offline"), 0, g_szConfigFile);
  51. // SYSTEM;
  52. g_config.nStdOut = GetPrivateProfileInt(_T("SYSTEM"), _T("stdprint"), 0, g_szConfigFile);
  53. GetPrivateProfileString(_T("SYSTEM"), _T("OGCTool"), _T(""), g_config.szOGCToolProgram, MAX_PATH, g_szConfigFile);
  54. // BATCH;
  55. g_config.nDeltaEType = GetPrivateProfileInt(_T("BATCH"), _T("EType"), 0, g_szConfigFile);
  56. GetPrivateProfileString(_T("BATCH"), _T("EValue"), _T(""), szValue, MAX_PATH, g_szConfigFile);
  57. g_config.dDeltaEValue = _tstof(szValue);
  58. GetPrivateProfileString(_T("BATCH"), _T("batchNumber"), _T(""), g_config.szBatchNumber, MAX_PATH, g_szConfigFile);
  59. #pragma endregion
  60. if ( g_config.nStdOut ) {
  61. AllocConsole(); // 开辟控制台;
  62. SetConsoleTitle(_T("调试输出")); // 设置控制台窗口标题;
  63. freopen("CONOUT$", "w+t", stdout); // 重定向输出;
  64. freopen("CONIN$", "r+t", stdin); // 重定向输入;
  65. HWND hWnd = NULL;
  66. again:
  67. hWnd = ::FindWindow(NULL, _T("调试输出"));
  68. if( hWnd ) {
  69. if (!::SetWindowPos(hWnd, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE)) {
  70. _tprintf_s(_T("前置设置失败\n"));
  71. } else {
  72. _tprintf_s(_T("前置设置成功\n"));
  73. }
  74. } else {
  75. goto again;
  76. }
  77. }
  78. return TRUE;
  79. }
  80. DWORD FindProcess(LPCTSTR lpProName)
  81. {
  82. ASSERT(lpProName!=NULL);
  83. DWORD dwProcId = 0;
  84. PROCESSENTRY32 pe32 = { 0 };
  85. HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  86. if (hSnapshot == NULL)
  87. {
  88. return 0;
  89. }
  90. pe32.dwSize = sizeof(PROCESSENTRY32);
  91. if (Process32First(hSnapshot, &pe32))
  92. {
  93. do {
  94. if (_tcsicmp(lpProName, pe32.szExeFile) == 0)
  95. {
  96. dwProcId = pe32.th32ProcessID;
  97. break;
  98. }
  99. } while (Process32Next(hSnapshot, &pe32));
  100. }
  101. CloseHandle(hSnapshot);
  102. return dwProcId;
  103. }
  104. vector<DWORD> FindAllProcess(LPCTSTR lpProName)
  105. {
  106. ASSERT(lpProName!=NULL);
  107. vector<DWORD> vtPID;
  108. PROCESSENTRY32 pe32 = { 0 };
  109. HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  110. if (hSnapshot == NULL)
  111. return vector<DWORD>();
  112. pe32.dwSize = sizeof(PROCESSENTRY32);
  113. if (Process32First(hSnapshot, &pe32))
  114. {
  115. do {
  116. if (_tcsicmp(lpProName, pe32.szExeFile) == 0)
  117. {
  118. vtPID.push_back(pe32.th32ProcessID);
  119. }
  120. } while (Process32Next(hSnapshot, &pe32));
  121. }
  122. CloseHandle(hSnapshot);
  123. return vtPID;
  124. }
  125. void FindAllProcess(std::vector<PROC_INFO> &vtProInfo)
  126. {
  127. PROCESSENTRY32 pe32 = { 0 };
  128. HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  129. if (hSnapshot == NULL)
  130. return;
  131. pe32.dwSize = sizeof(PROCESSENTRY32);
  132. if (!Process32First(hSnapshot, &pe32))
  133. goto end;
  134. do
  135. {
  136. PROC_INFO proinfo;
  137. proinfo.dwProcId = pe32.th32ProcessID;
  138. proinfo.strProcName = pe32.szExeFile;
  139. vtProInfo.push_back(proinfo);
  140. } while (Process32Next(hSnapshot, &pe32));
  141. end:
  142. CloseHandle(hSnapshot);
  143. }
  144. HANDLE FindModule(LPCTSTR lpModuleName, DWORD dwProcId)
  145. {
  146. ASSERT(lpModuleName!=NULL);
  147. DWORD dwMID = 0;
  148. MODULEENTRY32 me32 = { 0 };
  149. HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, dwProcId);
  150. if (hSnapshot == NULL)
  151. return NULL;
  152. me32.dwSize = sizeof(MODULEENTRY32);
  153. if (Module32First(hSnapshot, &me32))
  154. {
  155. do {
  156. if (_tcsicmp(lpModuleName, me32.szModule) == 0)
  157. {
  158. break;
  159. }
  160. } while (Module32Next(hSnapshot, &me32));
  161. }
  162. CloseHandle(hSnapshot);
  163. return me32.hModule;
  164. }
  165. LPCTSTR GetModulePath(LPCTSTR lpModuleName, DWORD dwProcId)
  166. {
  167. ASSERT(lpModuleName!=NULL);
  168. DWORD dwMID = 0;
  169. MODULEENTRY32 me32 = { 0 };
  170. HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, dwProcId);
  171. if (hSnapshot == NULL)
  172. return NULL;
  173. BOOL bFound = FALSE;
  174. me32.dwSize = sizeof(MODULEENTRY32);
  175. if (Module32First(hSnapshot, &me32)) {
  176. do
  177. {
  178. if (_tcsicmp(lpModuleName, me32.szModule) == 0) {
  179. bFound = TRUE;
  180. break;
  181. }
  182. } while (Module32Next(hSnapshot, &me32));
  183. }
  184. CloseHandle(hSnapshot);
  185. return bFound ? me32.szExePath : NULL;
  186. }
  187. HANDLE FindModuleEx(LPCTSTR lpModuleName, DWORD dwProcId)
  188. {
  189. HMODULE hMods[1024] = {0};
  190. DWORD cbNeeded = 0;
  191. TCHAR szModName[MAX_PATH];
  192. BOOL Wow64Process;
  193. HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ|PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwProcId);
  194. IsWow64Process(hProcess, &Wow64Process); //判断是32位还是64位进程
  195. if ( EnumProcessModulesEx(hProcess, hMods, sizeof(hMods), &cbNeeded, Wow64Process?LIST_MODULES_32BIT:LIST_MODULES_64BIT) )
  196. {
  197. for (UINT i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
  198. {
  199. GetModuleFileNameEx(hProcess, hMods[i], szModName, _countof(szModName));
  200. #ifdef _DEBUG
  201. WriteTextLog(_T("目标=%s, 原始=%s, 地址=%p"), szModName, lpModuleName, hMods[i]);
  202. #endif
  203. if (_tcsicmp(lpModuleName, szModName) == 0)
  204. {
  205. CloseHandle(hProcess);
  206. WriteTextLog(_T("【目标=%s, 原始=%s, 地址=%p】"), szModName, lpModuleName, hMods[i]);
  207. return hMods[i];
  208. }
  209. }
  210. }
  211. CloseHandle(hProcess);
  212. return NULL;
  213. }
  214. // WINDOWS NT 以上的内核需要提权,才能对系统进行高级管理;
  215. BOOL GetDebugPriv()
  216. {
  217. // 返回的访问令牌指针;
  218. HANDLE hToken;
  219. // 接收所返回的制定特权名称的信息;
  220. LUID sedebugnameValue;
  221. // 新特权信息的指针(结构体);
  222. TOKEN_PRIVILEGES tkp;
  223. //DWORD dwCurProcId = GetCurrentProcessId();
  224. // 要修改访问权限的进程句柄;
  225. HANDLE hCurProc = ::GetCurrentProcess();
  226. //hCurProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwCurProcId);
  227. if (!::OpenProcessToken(hCurProc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  228. {
  229. return FALSE;
  230. }
  231. if (!::LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue))
  232. {
  233. CloseHandle(hToken);
  234. return FALSE;
  235. }
  236. tkp.PrivilegeCount = 1;
  237. tkp.Privileges[0].Luid = sedebugnameValue;
  238. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  239. if (!::AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof tkp, NULL, NULL))
  240. {
  241. CloseHandle(hToken);
  242. return FALSE;
  243. }
  244. CloseHandle(hCurProc);
  245. CloseHandle(hToken);
  246. return TRUE;
  247. }
  248. /************************************************************************/
  249. /*
  250. 函数:GetFileVersion
  251. 描述:获取可执行文件的文件版号;
  252. 参数:
  253. hModule[IN] 可执行文件模块句柄;
  254. dwArray[OUT] 返回的文件版本号;
  255. 返回:
  256. 成功返回TRUE,失败返回FALSE;
  257. 注意:
  258. 当hModule为空时,表示要获取的可执行文件为本程序的文件版本号;
  259. */
  260. /************************************************************************/
  261. BOOL GetFileVersion( IN HMODULE hModule, OUT DWORD (&dwArray)[4])
  262. {
  263. TCHAR fname[MAX_PATH];
  264. VS_FIXEDFILEINFO *pVi;
  265. DWORD dwHandle;
  266. if ( GetModuleFileName(hModule, fname, MAX_PATH))
  267. {
  268. INT nSize = GetFileVersionInfoSize(fname, &dwHandle);
  269. if (nSize > 0)
  270. {
  271. BYTE *pBuffer = new BYTE[nSize];
  272. memset(pBuffer, 0, nSize);
  273. if (GetFileVersionInfo(fname, dwHandle, nSize, pBuffer))
  274. {
  275. if (VerQueryValue(pBuffer, _T("\\"), (LPVOID *)&pVi, (PUINT)&nSize))
  276. {
  277. dwArray[0] = HIWORD(pVi->dwFileVersionMS);
  278. dwArray[1] = LOWORD(pVi->dwFileVersionMS);
  279. dwArray[2] = HIWORD(pVi->dwFileVersionLS);
  280. dwArray[3] = LOWORD(pVi->dwFileVersionLS);
  281. delete[]pBuffer;
  282. return TRUE;
  283. }
  284. }
  285. if ( pBuffer )
  286. delete[]pBuffer;
  287. }
  288. }
  289. return FALSE;
  290. }
  291. /************************************************************************/
  292. /*
  293. 函数:GetFileVersion
  294. 描述:获取可执行文件的文件版号;
  295. 参数:
  296. lpFileName[IN] 可执行文件名全路径;
  297. dwArray[OUT] 返回的文件版本号;
  298. 返回:
  299. 成功返回TRUE,失败返回FALSE;
  300. 注意:
  301. */
  302. /************************************************************************/
  303. BOOL GetFileVersionEx( IN LPCTSTR lpFileName, IN DWORD (&dwArray)[4] )
  304. {
  305. if ( lpFileName == NULL || !PathFileExists(lpFileName) )
  306. {
  307. OutputDebugString(_T("文件名错误或文件不存在\n"));
  308. return FALSE;
  309. }
  310. DWORD dwHandle = 0;
  311. VS_FIXEDFILEINFO *pVi = NULL;
  312. INT nSize = GetFileVersionInfoSize(lpFileName, &dwHandle);
  313. if ( nSize > 0 )
  314. {
  315. BYTE *pBuffer = new BYTE[nSize];
  316. memset(pBuffer, 0, nSize);
  317. if ( GetFileVersionInfo(lpFileName, dwHandle, nSize, pBuffer) )
  318. {
  319. if (VerQueryValue(pBuffer, _T("\\"), (LPVOID *)&pVi, (PUINT)&nSize))
  320. {
  321. dwArray[0] = HIWORD(pVi->dwFileVersionMS);
  322. dwArray[1] = LOWORD(pVi->dwFileVersionMS);
  323. dwArray[2] = HIWORD(pVi->dwFileVersionLS);
  324. dwArray[3] = LOWORD(pVi->dwFileVersionLS);
  325. if (pBuffer)
  326. delete[]pBuffer;
  327. return TRUE;
  328. }
  329. }
  330. if (pBuffer)
  331. delete[]pBuffer;
  332. }
  333. return FALSE;
  334. }
  335. /************************************************************************/
  336. /*
  337. 函数:GetProductVersion
  338. 描述:获取可执行文件的产品版号;
  339. 参数:
  340. hModule[IN] 可执行文件模块句柄;
  341. dwArray[OUT] 返回的产品版本号;
  342. 返回:
  343. 成功返回TRUE,失败返回FALSE;
  344. 注意:
  345. 当hModule为空时,表示要获取的可执行文件为本程序的产品版本号;
  346. */
  347. /************************************************************************/
  348. BOOL GetProductVersion(IN HMODULE hModule, IN DWORD (&dwArray)[4] )
  349. {
  350. TCHAR fname[MAX_PATH];
  351. VS_FIXEDFILEINFO *pVi;
  352. DWORD dwHandle;
  353. if (::GetModuleFileName(hModule, fname, MAX_PATH))
  354. {
  355. INT nSize = GetFileVersionInfoSize(fname, &dwHandle);
  356. if (nSize > 0)
  357. {
  358. BYTE *pBuffer = new BYTE[nSize];
  359. memset(pBuffer, 0, nSize);
  360. if (GetFileVersionInfo(fname, dwHandle, nSize, pBuffer))
  361. {
  362. if (VerQueryValue(pBuffer, _T("\\"), (LPVOID *)&pVi, (PUINT)&nSize))
  363. {
  364. dwArray[0] = HIWORD(pVi->dwProductVersionMS);
  365. dwArray[1] = LOWORD(pVi->dwProductVersionMS);
  366. dwArray[2] = HIWORD(pVi->dwProductVersionLS);
  367. dwArray[3] = LOWORD(pVi->dwProductVersionLS);
  368. if(pBuffer)
  369. delete[]pBuffer;
  370. return TRUE;
  371. }
  372. }
  373. if(pBuffer)
  374. delete[]pBuffer;
  375. }
  376. }
  377. return FALSE;
  378. }
  379. /************************************************************************/
  380. /*
  381. 函数:GetProductVersion
  382. 描述:获取可执行文件的产品版号;
  383. 参数:
  384. lpFileName[IN] 可执行文件名全路径;
  385. dwArray[OUT] 返回的产品版本号;
  386. 返回:
  387. 成功返回TRUE,失败返回FALSE;
  388. 注意:
  389. */
  390. /************************************************************************/
  391. BOOL GetProductVersionEx( IN LPCTSTR lpFileName, IN DWORD (&dwArray)[4] )
  392. {
  393. if ( lpFileName == NULL || !PathFileExists(lpFileName) )
  394. {
  395. OutputDebugString(_T("文件名错误或文件不存在\n"));
  396. return FALSE;
  397. }
  398. DWORD dwHandle = 0;
  399. VS_FIXEDFILEINFO *pVi = NULL;
  400. INT nSize = GetFileVersionInfoSize(lpFileName, &dwHandle);
  401. if ( nSize > 0 )
  402. {
  403. BYTE *pBuffer = new BYTE[nSize];
  404. memset(pBuffer, 0, nSize);
  405. if ( GetFileVersionInfo(lpFileName, dwHandle, nSize, pBuffer) )
  406. {
  407. if (VerQueryValue(pBuffer, _T("\\"), (LPVOID *)&pVi, (PUINT)&nSize))
  408. {
  409. dwArray[0] = HIWORD(pVi->dwProductVersionMS);
  410. dwArray[1] = LOWORD(pVi->dwProductVersionMS);
  411. dwArray[2] = HIWORD(pVi->dwProductVersionLS);
  412. dwArray[3] = LOWORD(pVi->dwProductVersionLS);
  413. if (pBuffer)
  414. delete[]pBuffer;
  415. return TRUE;
  416. }
  417. }
  418. if (pBuffer)
  419. delete[]pBuffer;
  420. }
  421. return FALSE;
  422. }
  423. /************************************************************************/
  424. /* 函数:WriteTextLog[7/28/2016 IT];
  425. /* 描述:写文本日志;
  426. /* 参数:;
  427. /* [IN] :;
  428. /* 返回:void;
  429. /* 注意:;
  430. /* 示例:;
  431. /*
  432. /* 修改:;
  433. /* 日期:;
  434. /* 内容:;
  435. /************************************************************************/
  436. void WriteTextLog(const TCHAR *format, ...)
  437. {
  438. #if 0
  439. try
  440. {
  441. //static ThreadSection _critSection;
  442. //AutoThreadSection aSection(&_critSection);
  443. // 解析出日志路径;
  444. TCHAR szlogpath[MAX_PATH] = {0};
  445. static TCHAR szModulePath[MAX_PATH] = {0};
  446. static TCHAR szFna[_MAX_DIR] = { 0 };
  447. if ( szModulePath[0] == _T('\0') )
  448. {
  449. TCHAR szDrive[_MAX_DRIVE] = { 0 };
  450. TCHAR szDir[_MAX_DIR] = { 0 };
  451. TCHAR szExt[_MAX_DIR] = { 0 };
  452. ::GetModuleFileName(NULL, szModulePath, sizeof(szModulePath) / sizeof(TCHAR));
  453. _tsplitpath_s(szModulePath, szDrive, szDir, szFna, szExt);
  454. _tcscpy_s(szModulePath, szDrive);
  455. _tcscat_s(szModulePath, szDir);
  456. }
  457. _stprintf_s(szlogpath, _T("%s日志\\%s%s.txt"), szModulePath, szFna, CTime::GetCurrentTime().Format("[%Y-%m-%d]"));
  458. // 打开或创建文件;
  459. CStdioFile fp;
  460. if (PathFileExists(szlogpath))
  461. {
  462. if (fp.Open(szlogpath, CFile::modeWrite) == FALSE)
  463. {
  464. return;
  465. }
  466. fp.SeekToEnd();
  467. }
  468. else
  469. {
  470. fp.Open(szlogpath, CFile::modeCreate | CFile::modeWrite);
  471. }
  472. // 格式化前设置语言区域;
  473. TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL));
  474. _tsetlocale(LC_CTYPE, _T("chs"));//设定中文;
  475. // 格式化日志内容;
  476. va_list args = NULL;
  477. int len = 0;
  478. TCHAR *buffer = NULL;
  479. va_start( args, format );
  480. // _vscprintf doesn't count. terminating '\0'
  481. len = _vsctprintf( format, args ) + 1;
  482. buffer = (TCHAR*)malloc( len * sizeof(TCHAR) );
  483. _vstprintf_s( buffer, len, format, args ); // C4996
  484. // Note: vsprintf is deprecated; consider using vsprintf_s instead
  485. // 将日志内容输入到文件中;
  486. fp.WriteString( CTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S ")) );
  487. fp.WriteString(buffer);
  488. fp.WriteString(_T("\n"));
  489. // 关闭文件,释放资源并设置回原语言区域;
  490. free( buffer );
  491. _tsetlocale(LC_CTYPE, old_locale);
  492. free(old_locale);//还原区域设定;
  493. fp.Close();
  494. }
  495. catch (CException *e)
  496. {
  497. e->ReportError();
  498. e->Delete();
  499. }
  500. #else
  501. // 解析出日志路径;
  502. TCHAR szlogpath[MAX_PATH] = { 0 };
  503. static TCHAR szModulePath[MAX_PATH] = { 0 };
  504. static TCHAR szFna[MAX_PATH] = { 0 };
  505. if (szModulePath[0] == _T('\0'))
  506. {
  507. TCHAR szDrive[MAX_PATH] = { 0 };
  508. TCHAR szDir[MAX_PATH] = { 0 };
  509. TCHAR szExt[MAX_PATH] = { 0 };
  510. ::GetModuleFileName(NULL, szModulePath, sizeof(szModulePath) / sizeof(TCHAR));
  511. _tsplitpath_s(szModulePath, szDrive, szDir, szFna, szExt);
  512. _tcscpy_s(szModulePath, szDrive);
  513. _tcscat_s(szModulePath, szDir);
  514. }
  515. _stprintf_s(szlogpath, _T("%s%s.txt"), szModulePath, szFna);
  516. // 打开或创建文件;
  517. FILE *fp = NULL;
  518. //if (_taccess(szlogpath, 0) != -1)
  519. #ifndef UNICODE
  520. if (_access(szlogpath, 0) != -1)
  521. #else
  522. if (_taccess(szlogpath, 0) != -1)
  523. #endif
  524. {// 存在;
  525. fp = _tfopen(szlogpath, _T("a+"));
  526. // 移动到末尾;
  527. fseek(fp, 0, SEEK_END);
  528. }
  529. else
  530. {// 不存在;
  531. fp = _tfopen(szlogpath, _T("w+"));
  532. }
  533. if (fp == NULL)
  534. return;
  535. // 格式化前设置语言区域;
  536. TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL));
  537. _tsetlocale(LC_CTYPE, _T("chs"));//设定中文;
  538. // 格式化日志内容;
  539. va_list args = NULL;
  540. int len = 0;
  541. TCHAR *buffer = NULL;
  542. va_start(args, format);
  543. // _vscprintf doesn't count. terminating '\0'
  544. len = _vsctprintf(format, args) + 1;
  545. buffer = (TCHAR*)malloc(len * sizeof(TCHAR));
  546. _vstprintf_s(buffer, len, format, args);
  547. // 将日志内容输入到文件中;
  548. // 获取今年年份;
  549. __time64_t gmt = time(NULL);// 获取当前日历时间(1900-01-01开始的Unix时间戳);
  550. struct tm gmtm = { 0 };
  551. localtime_s(&gmtm, &gmt); // 时间戳转成本地时间;
  552. _ftprintf(fp, _T("%04d-%02d-%02d %02d:%02d:%02d %s\n"), gmtm.tm_year + 1990, gmtm.tm_mon + 1, gmtm.tm_mday, gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec, buffer);
  553. // 关闭文件,释放资源并设置回原语言区域;
  554. free(buffer);
  555. fclose(fp);
  556. _tsetlocale(LC_CTYPE, old_locale);
  557. free(old_locale);//还原区域设定;
  558. #endif
  559. }
  560. //---------------------------------------------------------------------
  561. // add by Jeff 2014.10.27
  562. // 函数:全局函数IsDirectoryLegitimate,多字节版本,非UNICODE
  563. // 描述:判断一个目录路径字符串,是否属于合法的、可创建的目录路径。
  564. // 参数:strDirectory 被验证的路径字符串;
  565. //
  566. // 返回:合法路径返回TRUE;
  567. //---------------------------------------------------------------------
  568. BOOL IsDirectoryLegitimate(const CString &strDirectory)
  569. {
  570. if (strDirectory.Find('/') != -1 ||
  571. strDirectory.Find('\\') != -1 ||
  572. strDirectory.Find(':') != -1 ||
  573. strDirectory.Find('*') != -1 ||
  574. strDirectory.Find('?') != -1 ||
  575. strDirectory.Find('\"') != -1 ||
  576. strDirectory.Find('>') != -1 ||
  577. strDirectory.Find('<') != -1 ||
  578. strDirectory.Find('|') != -1
  579. )
  580. return FALSE;
  581. return TRUE;
  582. }
  583. //--------------------------------------------------------------------------------
  584. // Jeff add 2014.06.23;
  585. // 函数:ErrorExit
  586. // 描述:
  587. // 参数:
  588. // lpszFunction:函数名;
  589. // dwError:错误码;
  590. //
  591. //--------------------------------------------------------------------------------
  592. void ShowSystemErrorInfo(CString strDescription, const DWORD &dwError)
  593. {
  594. #if 1
  595. LPVOID lpMsgBuf;
  596. BOOL fOk = FormatMessage(
  597. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  598. FORMAT_MESSAGE_FROM_SYSTEM |
  599. FORMAT_MESSAGE_IGNORE_INSERTS,
  600. NULL,
  601. dwError,
  602. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  603. (LPTSTR)&lpMsgBuf,
  604. 0, NULL);
  605. if (!fOk)
  606. {
  607. // Is it a network-related error?
  608. HMODULE hDll = LoadLibraryEx(TEXT("netmsg.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES);
  609. if (hDll != NULL)
  610. {
  611. FormatMessage(
  612. FORMAT_MESSAGE_FROM_HMODULE |
  613. FORMAT_MESSAGE_FROM_SYSTEM |
  614. FORMAT_MESSAGE_IGNORE_INSERTS,
  615. hDll,
  616. dwError,
  617. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  618. (LPTSTR)&lpMsgBuf,
  619. 0,
  620. NULL);
  621. FreeLibrary(hDll);
  622. }
  623. }
  624. if (lpMsgBuf != NULL)
  625. {
  626. CString strDisplay;
  627. strDisplay.Format(_T("%s.错误码=%d,Windows描述:%s"), strDescription, dwError, (PCTSTR)LocalLock(lpMsgBuf));
  628. //WriteLog(strDisplay);
  629. LocalFree(lpMsgBuf);
  630. }
  631. else
  632. {
  633. //WriteLog(strDescription);
  634. }
  635. #else
  636. HLOCAL hlocal = NULL; // Buffer that gets the error message string
  637. // Get the error code's textual description
  638. BOOL fOk = FormatMessage(
  639. FORMAT_MESSAGE_FROM_SYSTEM |
  640. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  641. FORMAT_MESSAGE_IGNORE_INSERTS,
  642. NULL,
  643. dwError,
  644. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  645. (PTSTR)&hlocal,
  646. 0,
  647. NULL);
  648. if (!fOk)
  649. {
  650. // Is it a network-related error?
  651. HMODULE hDll = LoadLibraryEx(TEXT("netmsg.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES);
  652. if (hDll != NULL)
  653. {
  654. FormatMessage(
  655. FORMAT_MESSAGE_FROM_HMODULE |
  656. FORMAT_MESSAGE_FROM_SYSTEM |
  657. FORMAT_MESSAGE_IGNORE_INSERTS,
  658. hDll,
  659. dwError,
  660. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  661. (PTSTR)&hlocal,
  662. 0,
  663. NULL);
  664. FreeLibrary(hDll);
  665. }
  666. }
  667. if (hlocal != NULL)
  668. {
  669. CString strDisplay;
  670. strDisplay.Format("%s 失败错误码=%d,Windows系统描述:%s", strDescription, dwError, (PCTSTR)LocalLock(hlocal));
  671. //WriteLog(strDisplay);
  672. LocalFree(hlocal);
  673. }
  674. else
  675. {
  676. //WriteLog("Error number not found.");
  677. }
  678. #endif
  679. }
  680. // The system displays a dialog box with a custom message and a message to the user to close applications within the specified time-out interval (30 seconds).
  681. // After the time-out interval elapses, the system is restarted.
  682. //The application must enable the SE_SHUTDOWN_NAME privilege before calling InitiateSystemShutdown
  683. BOOL MySystemShutdown(LPTSTR lpMsg)
  684. {
  685. HANDLE hToken; // handle to process token
  686. TOKEN_PRIVILEGES tkp; // pointer to token structure
  687. BOOL fResult; // system shutdown flag
  688. // Get the current process token handle so we can get shutdown
  689. // privilege.
  690. if (!OpenProcessToken(GetCurrentProcess(),
  691. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  692. return FALSE;
  693. // Get the LUID for shutdown privilege.
  694. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
  695. &tkp.Privileges[0].Luid);
  696. tkp.PrivilegeCount = 1; // one privilege to set
  697. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  698. // Get shutdown privilege for this process.
  699. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  700. (PTOKEN_PRIVILEGES)NULL, 0);
  701. // Cannot test the return value of AdjustTokenPrivileges.
  702. if (GetLastError() != ERROR_SUCCESS)
  703. return FALSE;
  704. // Display the shutdown dialog box and start the countdown.
  705. fResult = InitiateSystemShutdown(
  706. NULL, // shut down local computer
  707. lpMsg, // message for user
  708. 30, // time-out period, in seconds
  709. FALSE, // ask user to close apps
  710. TRUE); // reboot after shutdown
  711. if (!fResult)
  712. return FALSE;
  713. // Disable shutdown privilege.
  714. tkp.Privileges[0].Attributes = 0;
  715. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  716. (PTOKEN_PRIVILEGES)NULL, 0);
  717. return TRUE;
  718. }
  719. // If the AbortSystemShutdown function is executed in the time-out period specified by InitiateSystemShutdown,
  720. // the system does not shut down. For example, if PreventSystemShutdown is called after MySystemShutdown,
  721. // the system closes the dialog box and does not restart the system.
  722. BOOL PreventSystemShutdown()
  723. {
  724. HANDLE hToken; // handle to process token
  725. TOKEN_PRIVILEGES tkp; // pointer to token structure
  726. // Get the current process token handle so we can get shutdown
  727. // privilege.
  728. if (!OpenProcessToken(GetCurrentProcess(),
  729. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  730. return FALSE;
  731. // Get the LUID for shutdown privilege.
  732. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
  733. &tkp.Privileges[0].Luid);
  734. tkp.PrivilegeCount = 1; // one privilege to set
  735. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  736. // Get shutdown privilege for this process.
  737. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  738. (PTOKEN_PRIVILEGES)NULL, 0);
  739. if (GetLastError() != ERROR_SUCCESS)
  740. return FALSE;
  741. // Prevent the system from shutting down.
  742. if (!AbortSystemShutdown(NULL))
  743. return FALSE;
  744. // Disable shutdown privilege.
  745. tkp.Privileges[0].Attributes = 0;
  746. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  747. (PTOKEN_PRIVILEGES)NULL, 0);
  748. return TRUE;
  749. }
  750. // Shutting down flushes file buffers to disk and brings the system to a condition in which it is safe to turn off the computer
  751. // The application must first enable the SE_SHUTDOWN_NAME privilege.
  752. // The final parameter in the call to ExitWindowsEx indicates that the system was shut down for a planning update of the operating system.
  753. BOOL MySystemShutdown()
  754. {
  755. HANDLE hToken;
  756. TOKEN_PRIVILEGES tkp;
  757. // Get a token for this process.
  758. if (!OpenProcessToken(GetCurrentProcess(),
  759. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  760. return(FALSE);
  761. // Get the LUID for the shutdown privilege.
  762. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
  763. &tkp.Privileges[0].Luid);
  764. tkp.PrivilegeCount = 1; // one privilege to set
  765. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  766. // Get the shutdown privilege for this process.
  767. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  768. (PTOKEN_PRIVILEGES)NULL, 0);
  769. if (GetLastError() != ERROR_SUCCESS)
  770. return FALSE;
  771. // Shut down the system and force all applications to close.
  772. if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
  773. SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
  774. SHTDN_REASON_MINOR_UPGRADE |
  775. SHTDN_REASON_FLAG_PLANNED))
  776. return FALSE;
  777. return TRUE;
  778. }
  779. HWND GetProcessMainWnd(const DWORD& dwTagetProcessId, LPCTSTR lpTagetWndName)
  780. {
  781. DWORD dwCurPorcessId = 0;
  782. HWND hTagetProcessWnd = NULL;
  783. TCHAR szWndName[MAX_PATH] = { 0 };
  784. TCHAR szClassName[MAX_PATH] = { 0 };
  785. // 取得第一个窗口句柄;
  786. for (HWND hCurWnd = ::GetTopWindow(NULL); hCurWnd != NULL; hCurWnd = ::GetNextWindow(hCurWnd, GW_HWNDNEXT)) {
  787. // 重置为0;
  788. dwCurPorcessId = 0;
  789. // 通过窗口句柄反查进程pid;
  790. DWORD dwThreadId = ::GetWindowThreadProcessId(hCurWnd, &dwCurPorcessId);
  791. if (dwThreadId != 0) {
  792. // 判断当前进程id是否和目标进程id相同;
  793. if (dwCurPorcessId == dwTagetProcessId) {
  794. if (lpTagetWndName == NULL) {
  795. hTagetProcessWnd = hCurWnd;
  796. break;
  797. }
  798. else {
  799. // 获取窗口名称;
  800. ::GetWindowText(hCurWnd, szWndName, sizeof(szWndName) / sizeof(TCHAR));
  801. // 获取窗口类名;
  802. ::GetClassName(hCurWnd, szClassName, sizeof(szClassName) / sizeof(TCHAR));
  803. #ifdef _DEBUG
  804. TCHAR szLogMsg[MAX_PATH] = { 0 };
  805. _stprintf_s(szLogMsg, _T("类名:%s, 窗口名:%s,窗口地址:%p \n"), szClassName, szWndName, hCurWnd);
  806. OutputDebugString(szLogMsg);
  807. #endif
  808. if (_tcsstr(szWndName, lpTagetWndName) != NULL) {
  809. hTagetProcessWnd = hCurWnd;
  810. break;
  811. }
  812. }
  813. }
  814. }
  815. }
  816. // 当前窗口有可能不是进程父窗口;
  817. HWND hParentWnd = hTagetProcessWnd;
  818. while (hParentWnd) {
  819. hParentWnd = ::GetParent(hTagetProcessWnd);
  820. if (hParentWnd == NULL)
  821. break;
  822. hTagetProcessWnd = hParentWnd;
  823. }
  824. return hTagetProcessWnd;
  825. }
  826. BOOL CALLBACK EnumChildWindowCallBack(HWND hWnd, LPARAM lParam)
  827. {
  828. DWORD dwPid = 0;
  829. LPPROC_WND_INFO lpWndData = (LPPROC_WND_INFO)lParam;
  830. GetWindowThreadProcessId(hWnd, &dwPid); // 获得找到窗口所属的进程
  831. if(dwPid == lpWndData->dwProcId) // 判断是否是目标进程的窗口
  832. {
  833. WND_INFO wndInfo;
  834. wndInfo.hWnd=hWnd;
  835. SendMessage(hWnd, WM_GETTEXT, MAX_PATH, (LPARAM)wndInfo.szWndTitle);
  836. GetClassName(hWnd, wndInfo.szClassName, MAX_PATH);
  837. wndInfo.dwCtrlId = ::GetDlgCtrlID(hWnd);
  838. lpWndData->AddWnd(wndInfo);
  839. // 输出窗口信息
  840. TRACE4("A-0x%08X, %ld, %s, %s\n", hWnd, wndInfo.dwCtrlId, wndInfo.szClassName, wndInfo.szWndTitle);
  841. // 此处如果再递归,会导致重复查找2次子窗口;
  842. //EnumChildWindows(hWnd, EnumChildWindowCallBack, lParam); // 递归查找子窗口
  843. return TRUE;
  844. }
  845. return FALSE;
  846. }
  847. BOOL CALLBACK EnumWindowCallBack(HWND hWnd, LPARAM lParam)
  848. {
  849. DWORD dwPid = 0;
  850. LPPROC_WND_INFO lpWndData = (LPPROC_WND_INFO)lParam;
  851. GetWindowThreadProcessId(hWnd, &dwPid); // 获得找到窗口所属的进程
  852. if(dwPid == lpWndData->dwProcId) // 判断是否是目标进程的窗口
  853. {
  854. WND_INFO wndInfo;
  855. wndInfo.hWnd=hWnd;
  856. SendMessage(hWnd, WM_GETTEXT, MAX_PATH, (LPARAM)wndInfo.szWndTitle);
  857. GetClassName(hWnd, wndInfo.szClassName, MAX_PATH);
  858. wndInfo.dwCtrlId = ::GetDlgCtrlID(hWnd);
  859. lpWndData->AddWnd(wndInfo);
  860. // 输出窗口信息
  861. TRACE4("A-0x%08X, %ld, %s, %s\n", hWnd, wndInfo.dwCtrlId, wndInfo.szClassName, wndInfo.szWndTitle);
  862. EnumChildWindows(hWnd, EnumChildWindowCallBack, lParam); // 继续查找子窗口
  863. }
  864. return TRUE;
  865. }
  866. BOOL EnumProcessAllWnd(LPPROC_WND_INFO lpProcWndInfo)
  867. {
  868. lpProcWndInfo->vtWndInfo.clear();
  869. return EnumWindows(EnumWindowCallBack, (LPARAM)lpProcWndInfo);
  870. }
  871. BOOL StartProcess(LPCTSTR lpPath, BOOL bShowWnd, BOOL bSuspend)
  872. {
  873. STARTUPINFO si;
  874. PROCESS_INFORMATION pi;
  875. ZeroMemory(&si, sizeof(si));
  876. si.cb = sizeof(si);
  877. ZeroMemory(&pi, sizeof(pi));
  878. CString strDir = lpPath;
  879. strDir = strDir.Left(strDir.ReverseFind(_T('\\')));
  880. si.dwFlags = STARTF_USESHOWWINDOW; // 指定wShowWindow成员有效
  881. si.wShowWindow = bShowWnd ? SW_SHOW : SW_HIDE; // 设置创建进程时,窗口不显示,
  882. // 为FALSE的话则不显示
  883. BOOL bRet = ::CreateProcess (
  884. lpPath, // 不在此指定可执行文件的文件名
  885. NULL, // 命令行参数
  886. NULL, // 默认进程安全性
  887. NULL, // 默认线程安全性
  888. FALSE, // 指定当前进程内的句柄不可以被子进程继承
  889. bSuspend ? CREATE_SUSPENDED : NULL,
  890. NULL, // 使用本进程的环境变量
  891. strDir, // 使用本进程的驱动器和目录
  892. &si,
  893. &pi);
  894. if(bRet)
  895. {
  896. // 进程挂起后,仍能成功注入dll;
  897. // TCHAR szDllPath[MAX_PATH];
  898. // ZeroMemory(szDllPath,MAX_PATH);
  899. // _stprintf_s(szDllPath, _T("%shook.dll"), g_szModulePath);
  900. // for (int i = 0; i < 10; i++)
  901. // {
  902. // CInjection inject(pi.dwProcessId,szDllPath);
  903. // inject.InjectDynamicLibrary();
  904. // inject.EjectDynamicLibrary();
  905. // }
  906. g_procWndInfo.dwProcId = pi.dwProcessId;
  907. // 既然我们不使用两个句柄,最好是立刻将它们关闭
  908. ::CloseHandle (pi.hThread);
  909. ::CloseHandle (pi.hProcess);
  910. }
  911. return bRet;
  912. }
  913. };