-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathKeeperDlg.cpp
2732 lines (2471 loc) · 71.5 KB
/
KeeperDlg.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// KeeperDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "Keeper.h"
#include "KeeperDlg.h"
#include "afxdialogex.h"
#include <io.h>
#include "Resource.h"
#include "confReader.h"
#include "KeeperSettings.h"
#include "cmdList.h"
#if USING_GLOG
#include "log.h"
#include <direct.h>
#endif
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#include <Tlhelp32.h>
#include <direct.h>
#include "Afx_MessageBox.h"
#include <iostream>
#include <fstream>
#include <string>
#include "Downloader.h"
#include <DbgHelp.h>
#pragma comment(lib, "Dbghelp.lib")
#include <wininet.h>
#pragma comment(lib, "wininet.lib")
#pragma comment(lib, "Urlmon.lib")
// #include <timeapi.h>
#include <mmsystem.h>
#pragma comment(lib, "winmm.lib")
#define __return(p) { SendMessage(WM_CLOSE); return p; }
// 全局唯一的对话框指针
CKeeperDlg *g_KeeperDlg = NULL;
// ffmpeg进程句柄
HANDLE g_ffmpeg = NULL;
// 线程计数器
NoticeNum NoticeThreaNum;
// 频繁崩溃间隔(秒)
#define TIME_SEC 60
#pragma comment(lib, "version.lib")
/************************************************************************
* @class NoticeParam
* @brief Notice结构(提示信息+声音+提示时长)
************************************************************************/
class NoticeParam
{
private:
const char *title; // 窗口标题
char *str; // 提示信息
char *sound; // 声音文件
int tm; // 提示时长
~NoticeParam() { delete [] str; delete [] sound; }
public:
NoticeParam(const char *wnd, const char *src, const char *wave, int t) :
title(wnd),
str(new char[strlen(src)+1]()),
sound(new char[strlen(wave)+1]()), tm(t)
{
memcpy(str, src, strlen(src));
memcpy(sound, wave, strlen(wave));
}
const char *window() const { return title; } // 窗口标题
const char *c_str() const { return str; } // 提示信息
const char *music() const { return sound; } // 声音文件
int getTime() const { return tm; } // 提示时长
void destroy() { delete this; } // 调用析构函数
};
// 获取文件大小(Mb)
float GetFileSize(const char *path)
{
CFileStatus fileStatus;
USES_CONVERSION;
return CFile::GetStatus(A2W(path), fileStatus) ? fileStatus.m_size / (1024.f * 1024.f) : 0;
}
// 获取exe文件的版本信息
void GetExeVersion(const char *exePath, char *version, char *strFileDescription = NULL)
{
version[0] = 0;
UINT sz = GetFileVersionInfoSizeA(exePath, NULL);
if (sz)
{
char *pBuf = new char[sz + 1]();
if (GetFileVersionInfoA(exePath, NULL, sz, pBuf))
{
VS_FIXEDFILEINFO *pVsInfo = NULL;
if (VerQueryValueA(pBuf, "\\", (void**)&pVsInfo, &sz))
{
sprintf(version, "%d.%d.%d.%d",
HIWORD(pVsInfo->dwFileVersionMS),
LOWORD(pVsInfo->dwFileVersionMS),
HIWORD(pVsInfo->dwFileVersionLS),
LOWORD(pVsInfo->dwFileVersionLS));
}
if (strFileDescription &&
VerQueryValueA(pBuf, "\\StringFileInfo\\080404b0\\FileDescription", (void**)&pVsInfo, &sz))
strcpy(strFileDescription, (const char *)pVsInfo);
}
delete [] pBuf;
}
}
#define POSTFIX "_update.exe" //待升级程序的后缀名称
/**
* @brief 程序遇到未知BUG导致终止时调用此函数,不弹框
* 并且转储dump文件到当前目录.
*/
long WINAPI whenbuged(_EXCEPTION_POINTERS *excp)
{
char path[_MAX_PATH], *p = path;
GetModuleFileNameA(NULL, path, _MAX_PATH);
while (*p) ++p;
while ('\\' != *p) --p;
time_t TIME(time(0));
strftime(p, 64, "\\Keeper_%Y-%m-%d %H%M%S.dmp", localtime(&TIME));
HANDLE hFile = ::CreateFileA(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if(INVALID_HANDLE_VALUE != hFile)
{
MINIDUMP_EXCEPTION_INFORMATION einfo = {::GetCurrentThreadId(), excp, FALSE};
::MiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
hFile, MiniDumpWithFullMemory, &einfo, NULL, NULL);
::CloseHandle(hFile);
}
return EXCEPTION_EXECUTE_HANDLER;
}
// 一种基于socket的下载器
Downloader D;
/**
* @brief 下载文件
* @param[in] name 文件名称
* @param[in] postfix 缓存文件后缀
* @param[in] isKeeper 是否守护
* @param[in] type 文件类型
*/
bool CKeeperDlg::DownloadFile(const char *name, const char *postfix, BOOL isKeeper, const char *type)
{
const bool b64Bit = 8 == sizeof(int*);// 是否64位
char src[_MAX_PATH];
const char *remote = GetRemoteIp();
if (strlen(remote) < 7)
{
const char *ip = ControlIp();
D.Connect(ip, atoi(remote));
return D.DownloadFile(name, postfix, isKeeper, type);
}
b64Bit ? (TRUE==isKeeper ? sprintf_s(src, "http://%s/x64/%s.%s", remote, name, type)
: sprintf_s(src, "http://%s/x64/%s/%s.%s", remote, m_moduleName, name, type)):
(TRUE==isKeeper ? sprintf_s(src, "http://%s/%s.%s", remote, name, type)
: sprintf_s(src, "http://%s/%s/%s.%s", remote, m_moduleName, name, type));
DeleteUrlCacheEntryA(src);
if (isKeeper)
{
int nWait = rand() / (float)RAND_MAX * 2000;
Sleep(max(nWait, 1));// 随机等待 1---2000 ms
}
char dst[_MAX_PATH], *p = dst;
strcpy_s(dst, GetModulePath());
while (*p) ++p;
while ('\\' != *p) --p;
sprintf(p + 1 , "%s%s", name, postfix);
HRESULT hr = -1;
const int times = 10; // 尝试下载的次数
int k = times;
do{
hr = URLDownloadToFileA(NULL, src, dst, 0, NULL); --k;
if (S_OK == hr || m_bExit) break;
Sleep(20);
}while (k);
char szLog[300];
sprintf_s(szLog, "======> 下载\"%s\"%s。[尝试%d次]\n", src, S_OK == hr ? "成功" : "失败", times - k);
OutputDebugStringA(szLog);
return (S_OK == hr && 0 == _access(dst, 0));
}
/************************************************************************
* @brief 根据"filelist.txt"下载文件
* @param[in] dst 守护程序目录
* @param[in] p 指向目录结尾的指针
* @note 文件需要以ANSI编码,否则中文名文件无法下载
************************************************************************/
void CKeeperDlg::DownloadFilelist(const char *dst, char *p)
{
DownloadFile("filelist", ".txt", -1, "txt");// 下载filelist.txt文件
sprintf(p + 1 , "filelist.txt");
if (0 == _access(dst, 0)) // 根据列表下载文件
{
ifstream fin(dst);
while (!fin.eof())
{
string str;
getline(fin, str);
const char *p0 = str.c_str(), *p = p0 + str.length();
while ('.' != *p && p0 != p) --p;
if (p0 != p)
{
char buf[64] = { 0 };
memcpy(buf, p0, min(p-p0, 64));
const char *lwr = _strlwr(buf);
// 应用程序单独由update程序进行升级
if (0 == strcmp(lwr, m_moduleName) || 0 == strcmp(lwr, "keeper.exe"))
continue;
DownloadFile(buf, p, -1, p + 1);
Sleep(10);
}
}
fin.close();
}
}
/************************************************************************/
/* 函数说明:释放资源中某类型的文件
/* 参 数:新文件名、资源ID、资源类型
/* 返 回 值:成功返回TRUE,否则返回FALSE
/* By:Koma 2009.07.24 23:30
/* https://www.cnblogs.com/Browneyes/p/4916299.html
/************************************************************************/
BOOL CKeeperDlg::ReleaseRes(const char *strFileName, WORD wResID, const CString &strFileType)
{
// 资源大小
DWORD dwWrite=0;
// 创建文件
HANDLE hFile = CreateFileA(strFileName, GENERIC_WRITE,FILE_SHARE_WRITE,NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if ( hFile == INVALID_HANDLE_VALUE )
return FALSE;
// 查找资源文件中、加载资源到内存、得到资源大小
HRSRC hrsc = FindResource(NULL, MAKEINTRESOURCE(wResID), strFileType);
HGLOBAL hG = LoadResource(NULL, hrsc);
DWORD dwSize = SizeofResource( NULL, hrsc);
// 写入文件
WriteFile(hFile, hG, dwSize, &dwWrite, NULL);
CloseHandle( hFile );
SetFileAttributesA(strFileName, FILE_ATTRIBUTE_HIDDEN);
return TRUE;
}
std::string GetLocalAddressBySocket(SOCKET m_socket)
{
struct sockaddr_in m_address;
memset(&m_address, 0, sizeof(struct sockaddr_in));
int nAddrLen = sizeof(struct sockaddr_in);
//根据套接字获取地址信息
if(::getsockname(m_socket, (SOCKADDR*)&m_address, &nAddrLen) != 0)
{
return "";
}
const char* pIp = ::inet_ntoa(m_address.sin_addr);
return pIp;
}
// Keeper升级[需要在本机开启IIS网站,且把文件复制到指定目录, 如:C:\inetpub\wwwroot]
// 1.升级程序前先尝试下载升级器"updater.exe"
// 2.升级Keeper程序时会下载"pdb"文件用于调试
// 3.升级被守护程序会下载"filelist.txt"文件,根据文件中的名称列表,逐个下载对应文件
// 注意:须在IIS配置中添加新MIME类型(如果文件类型未知):application/octet-stream
void UpdateThread(void *param)
{
OutputDebugStringA("======> Begin UpdateThread\n");
const char *arg = (const char *)param;// 升级程序名
D.SetUpdateApp(arg);
CKeeperDlg *pThis = g_KeeperDlg;
bool isKeeper = 0 == strcmp("Keeper", arg); // 是否升级Keeper
char dst[_MAX_PATH]; // 当前目录
strcpy_s(dst, pThis->GetModulePath());
char *p = dst; // 指向当前目录结尾的指针
while (*p) ++p;
while ('\\' != *p) --p;
strcpy(p+1, "updater.exe");
if(!pThis->ReleaseRes(dst,(WORD)IDR_UPDATER, L"EXE"))
pThis->DownloadFile("updater");// 尝试下载"updater.exe"
do {
Sleep(200);
if (pThis->DownloadFile(arg, POSTFIX, isKeeper))
{
char up_ver[64]; // 升级程序的版本
sprintf(p + 1 , "%s%s", arg, POSTFIX);
GetExeVersion(dst, up_ver);
CString up_file = CString(dst); // exe升级文件
// 版本未更新不予升级
if ( theApp.is_debug
? true : strcmp(up_ver, isKeeper ? pThis->m_strKeeperVer : pThis->m_strVersion) > 0 )
{
theApp.is_debug = false;
sprintf(p + 1 , "updater.exe");
if (-1 == _access(dst, 0))
{
pThis->m_bUpdate = false;
break;
}
CString update = CString(dst);// 执行升级程序
CString file = CString(arg);// 升级文件
CString params = file + _T(" ") + CString(theApp.m_lpCmdLine);// 启动参数
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.lpFile = update;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.lpParameters = isKeeper ? params : file;// 守护程序带参数
int nWait = rand() / (float)RAND_MAX * 2000;
Sleep(max(nWait, 200));// 随机等待 200---2000 ms
clock_t tm = clock();
DWORD dWord = 0;
BOOL b = GetBinaryType(up_file, &dWord) ?
(SCS_32BIT_BINARY==dWord || SCS_64BIT_BINARY==dWord) : FALSE; // exe程序必须为32/64位
BOOL Fail = b ?
(32==GetSystemBits() && dWord==SCS_64BIT_BINARY):FALSE; // 64位程序不能在32位系统运行
if (!Fail && ShellExecuteEx(&ShExecInfo))
{
if (isKeeper)
{
pThis->DownloadFile("Keeper", ".pdb", true, "pdb");// 下载pdb文件
nWait = rand() / (float)RAND_MAX * 2000;
Sleep(max(nWait, 200));// 随机等待 200---2000 ms
pThis->DownloadFile("ffmpeg", ".exe", true, "exe");// 下载ffmpeg文件
nWait = rand() / (float)RAND_MAX * 2000;
Sleep(max(nWait, 200));// 随机等待 200---2000 ms
pThis->m_bUpdate = false;
pThis->ExitKeeper(false);// 退出守护
tm = clock() - tm;
TRACE("======> Exit Keeper Using: %d ms.\n", tm);
}else
{
char notice[_MAX_PATH];
sprintf_s(notice, "正在升级应用程序\"%s\",请勿进行任何操作,否则可能导致升级失败。"
"升级完成后将自动启动应用程序。", pThis->GetAppName());
pThis->Notice(notice, 8000);
pThis->Stop(true);
WaitForSingleObject(ShExecInfo.hProcess, 30000);
pThis->DownloadFilelist(dst, p);
pThis->Start();
pThis->m_bUpdate = false;
}
}else
{
pThis->m_bUpdate = false;
OutputDebugStringA("======> ShellExecuteEx updater失败.\n");
if (Fail)
{
#if _DEBUG
Afx_MessageBox box(_T("64位程序不能在32位系统运行.")); box.DoModal();
#else
OutputDebugStringA("======> 64位程序不能在32位系统运行.\n");
#endif
}
}
}else
{
pThis->DownloadFilelist(dst, p);
pThis->m_bUpdate = false;
OutputDebugStringA("======> 升级文件的版本不高于目标程序, 不予升级.\n");
}
}else{
pThis->DownloadFilelist(dst, p);
pThis->m_bUpdate = false;
}
}while(false);
D.Disconnect();
OutputDebugStringA("======> End UpdateThread\n");
}
/************************************************************************
* @brief 还原目标目录的文件
* @param[in] backup 备份文件目录("\\"结尾)
* @param[in] dstDir 被还原的目标文件目录("\\"结尾)
************************************************************************/
void recovery(const std::string &backup, const std::string &dstDir)
{
//文件句柄
intptr_t hFile = 0;
//文件信息
struct _finddata_t fileinfo;
std::string s, dst = dstDir;
BOOL bSuccess = TRUE;
try
{
if ((hFile = _findfirst(s.assign(backup).append("*.*").c_str(), &fileinfo)) != -1)
{
do{
_strlwr(fileinfo.name);
if (IS_DIR == fileinfo.attrib)
{
// 子目录
if(strcmp(fileinfo.name, ".") && strcmp(fileinfo.name, "..")){
recovery(backup + fileinfo.name + "\\", dstDir + fileinfo.name + "\\");
}
}
else if (strcmp(fileinfo.name, ".") && strcmp(fileinfo.name, "..")
&& strcmp(fileinfo.name, "keeper.exe"))
{
std::string cur = s.assign(backup).append(fileinfo.name);
std::string d = dst.append(fileinfo.name);
for(int k = 100; !DeleteFileA(d.c_str()) && --k; ) Sleep(200);
if(FALSE == MoveFileA(cur.c_str(), d.c_str())) // 开始还原,移动文件
{
TRACE("======> 还原文件失败: %s\n", d.c_str());
bSuccess = FALSE;
}
DeleteFileA(cur.c_str());
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
RemoveDirectoryA(backup.c_str());
}catch (std::exception e){ if(hFile) _findclose(hFile); }
}
// 程序还原
void RecoverThread(void *param)
{
OutputDebugStringA("======> Begin RecoverThread\n");
const char *arg = (const char *)param;// 降级程序名
CKeeperDlg *pThis = g_KeeperDlg;
char dst[_MAX_PATH]; // 当前目录
strcpy_s(dst, pThis->GetModulePath());
char *p = dst; // 指向当前目录结尾的指针
while (*p) ++p;
while ('\\' != *p) --p;
sprintf(p+1, ".old\\%s.exe", arg);
if (0 == _access(dst, 0))
{
char notice[_MAX_PATH];
sprintf_s(notice, "正在对应用程序\"%s\"降级,请勿进行任何操作,否则可能导致还原失败。"
"降级完成后将自动启动应用程序。", arg);
pThis->Notice(notice, 8000);
pThis->Stop(true);
*(p+1) = 0;
std::string root(dst); // 还原文件所在目录
strcpy(p+1, ".old\\");
std::string logDir(dst);// 备份文件所在目录
recovery(logDir, root);
pThis->Start();
}else
{
OutputDebugStringA("======> 不需要还原被守护程序.\n");
pThis->SendInfo("提示", "没有备份文件,不需要还原被守护程序。");
}
pThis->m_bUpdate = false;
OutputDebugStringA("======> End RecoverThread\n");
}
// FILETIME转time_t
time_t FileTime2TimeT(FILETIME ft)
{
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
return (ui.QuadPart - 116444736000000000) / 10000000;
}
// 获取进程启动时间
int GetStartTime(HANDLE _hProcess)
{
FILETIME creation_time, exit_time, kernel_time, user_time;
if (GetProcessTimes(_hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
{
time_t TM = FileTime2TimeT(creation_time);
tm *date = localtime(&TM);
char szLog[64];
strftime(szLog, 64, "%Y-%m-%d %H:%M:%S", date);
TRACE("======> 被守护程序已经启动: %s\n", szLog);
return TM;
}
return time(NULL);
}
// 获取父进程ID:https://blog.csdn.net/shaochat/article/details/38731365
ULONG_PTR GetParentProcessId(int pid)
{
ULONG_PTR pbi[6], id = (ULONG_PTR)-1;
ULONG ulSize = 0;
LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
*(FARPROC *)&NtQueryInformationProcess = GetProcAddress(LoadLibraryA("NTDLL.DLL"), "NtQueryInformationProcess");
if(NtQueryInformationProcess){
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if(NtQueryInformationProcess(hProcess, 0, &pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
id = pbi[5];
CloseHandle(hProcess);
}
return id;
}
// 安全的取得真实系统信息
void SafeGetNativeSystemInfo(__out LPSYSTEM_INFO lpSystemInfo)
{
typedef void (WINAPI *LPFN_GetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo);
LPFN_GetNativeSystemInfo fnGetNativeSystemInfo = (LPFN_GetNativeSystemInfo)
GetProcAddress(GetModuleHandle(_T("kernel32")), "GetNativeSystemInfo");
if (NULL != fnGetNativeSystemInfo)
{
fnGetNativeSystemInfo(lpSystemInfo);
}
else
{
GetSystemInfo(lpSystemInfo);
}
}
// 获取操作系统位数
int GetSystemBits()
{
SYSTEM_INFO si;
SafeGetNativeSystemInfo(&si);
return (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64 ) ? 64 : 32;
}
// 仅op为真时才提示64位
DWORD GetProcessId(const CString &processName, const CString &strFullPath, BOOL &op)
{
DWORD id = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnapshot, &pe))
return FALSE;
while (TRUE == Process32Next(hSnapshot, &pe))
{
id = 0;
_wcslwr_s(pe.szExeFile);
if (pe.szExeFile == processName)
{
id = pe.th32ProcessID;
MODULEENTRY32 me = { 0 };
me.dwSize = sizeof(MODULEENTRY32);
HANDLE hModule = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, id);
if (op && ERROR_PARTIAL_COPY == GetLastError())
{
if(CheckWowProcess(hModule) && 64==GetSystemBits())
{
AfxMessageBox(L"请使用64位守护程序, 否则可能导致意想不到的结果!"
, MB_ICONINFORMATION | MB_OK);
}
CloseHandle(hModule);
op = FALSE;
break;
}
Module32First(hModule, &me);
CloseHandle(hModule);
_wcslwr_s(me.szExePath);
if (me.szExePath == strFullPath)
break;
}
}
CloseHandle(hSnapshot);
return id;
}
// 返回值op:0表示失败、程序需退出,非0表示成功、程序继续运行
HANDLE CKeeperDlg::GetProcessHandle(const CString &processName, const CString &strFullPath, BOOL &op)
{
DWORD id = GetProcessId(processName, strFullPath, op);
return id ? OpenProcess(PROCESS_ALL_ACCESS, FALSE, id) : NULL;
}
// 获取进程的线程数量
int GetThreadCount(DWORD th32ProcessID)
{
int count = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnapshot, &pe))
return 0;
while (TRUE == Process32Next(hSnapshot, &pe))
{
if (pe.th32ProcessID == th32ProcessID)
{
count = pe.cntThreads;
break;
}
}
CloseHandle(hSnapshot);
return count;
}
const char* GetLocalHost()
{
static char localhost[128] = { "127.0.0.1" };
char hostname[128] = { 0 };
if (0 == gethostname(hostname, 128))
{
hostent *host = gethostbyname(hostname);
// 将ip转换为字符串
char *hostip = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);
memcpy(localhost, hostip, strlen(hostip));
}
return localhost;
}
// 去掉窗口的关闭按钮
HWND DeleteCloseMenu(HWND hWnd)
{
if (hWnd)
{
HMENU pMenu = GetSystemMenu(hWnd, FALSE);
if (pMenu)
{
EnableMenuItem(pMenu, SC_CLOSE, MF_GRAYED | MF_BYCOMMAND);
DrawMenuBar(hWnd);
}
}
return hWnd;
}
// 添加窗口的关闭按钮
HWND AddCloseMunu(HWND hWnd)
{
if (hWnd)
{
::ShowWindow(hWnd, SW_SHOW);
HMENU pMenu = GetSystemMenu(hWnd, FALSE);
if (pMenu)
{
EnableMenuItem(pMenu, SC_CLOSE, MF_ENABLED | MF_BYCOMMAND);
DrawMenuBar(hWnd);
}
}
return hWnd;
}
void
GetCurrentPath(char* path)
{
char cCurrentDir[_MAX_PATH]={0};
DWORD dword=::GetModuleFileNameA(NULL, cCurrentDir, _MAX_PATH);
DWORD dwCount=dword;
while(dwCount>0)
{
dwCount--;
if(cCurrentDir[dwCount]==0x5c)
break;
else
{
cCurrentDir[dwCount]=0;
}
}
strcpy(path, cCurrentDir);
}
void InitLog()
{
// 如果日志目录不存在,则创建
char m_sLogPath[_MAX_PATH];
GetCurrentPath(m_sLogPath);
strcat(m_sLogPath, "log");
if (_access(m_sLogPath, 0) == -1)
_mkdir(m_sLogPath);
#if USING_GLOG
// init log lib
const char *app = theApp.m_strTitle;
InitGoogleLogging(app);
char cInfoPath[_MAX_PATH] = { 0 };
sprintf(cInfoPath, "%s\\%sLog_", m_sLogPath, app);
//日志实时输出
FLAGS_logbufsecs = 0;
// 日志大于此值时,创建新的日志
FLAGS_max_log_size = 2;
//当磁盘被写满时,停止日志输出
FLAGS_stop_logging_if_full_disk = true;
// 关闭写日志到err
FLAGS_alsologtostderr = false;
google::SetLogDestination(google::GLOG_INFO, cInfoPath);
google::SetLogDestination(google::GLOG_WARNING, cInfoPath);
google::SetLogDestination(google::GLOG_ERROR, cInfoPath);
logInfo << "<<< Keeper Start. >>>";
#endif
}
void unInitLog()
{
#if USING_GLOG
logInfo << "<<< Keeper Stop. >>>";
google::ShutdownGoogleLogging();
#endif
}
// 获取操作系统版本[Windows 10版本为100及以上]
int getOsVersion()
{
OSVERSIONINFO info = {};
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
#pragma warning(disable: 4996) // 禁用 C4996 警告
GetVersionEx(&info);
DWORD dwMajor = info.dwMajorVersion;
DWORD dwMinor = info.dwMinorVersion;
return 10 * dwMajor + dwMinor;
}
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CKeeperDlg 对话框
CKeeperDlg::CKeeperDlg(const string& Icon, CWnd* pParent)
: CDialog(CKeeperDlg::IDD, pParent)
{
m_bExit = TRUE;
#undef new
m_strIcon = CString(Icon.c_str());
pBmp = NULL;
m_hIcon = NULL;
InitLog();
InitializeCriticalSection(&m_cs);
m_finder = NULL;
m_strCreateTime[0] = 0;
m_strModeTime[0] = 0;
m_fFileSize = 0;
strcpy_s(m_strVersion, "Unknown");
m_bIsStoped = S_RUN;
m_bUpdate = false;
m_nAliveTime = ALIVE_TIME;
memset(m_strUpServer, 0, sizeof(m_strUpServer));
}
CKeeperDlg::~CKeeperDlg()
{
unInitLog();
DeleteCriticalSection(&m_cs);
}
void CKeeperDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CKeeperDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_BUTTON_EXIT, &CKeeperDlg::OnOK)
ON_BN_CLICKED(IDC_BUTTON_SHOWCONSOLE, &CKeeperDlg::OnBnClickedButtonShowconsole)
ON_COMMAND(ID_APP_ABOUT, &CKeeperDlg::OnAppAbout)
ON_MESSAGE(WM_TRAY_MSG, &CKeeperDlg::OnTrayCallbackMsg)
ON_COMMAND(ID_EXIT_MENU, &CKeeperDlg::OnExitMenu)
ON_COMMAND(ID_SELF_START, &CKeeperDlg::OnSelfStart)
ON_UPDATE_COMMAND_UI(ID_SELF_START, &CKeeperDlg::OnUpdateSelfStart)
ON_WM_INITMENUPOPUP()
ON_WM_WINDOWPOSCHANGING()
ON_COMMAND(ID_SETTINGS, &CKeeperDlg::OnSettings)
ON_WM_TIMER()
ON_WM_CREATE()
ON_WM_HOTKEY()
END_MESSAGE_MAP()
// CKeeperDlg 消息处理程序
BOOL CKeeperDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
DeleteMenu(pSysMenu->GetSafeHmenu(), SC_CLOSE, MF_BYCOMMAND);// 删除关闭按钮
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
m_bTray = FALSE;
m_trayPopupMenu.LoadMenu(IDR_POP_MENU);
// TODO: 在此添加额外的初始化代码
// 获取当前程序路径
USES_CONVERSION;
GetModuleFileNameA(NULL, m_pKeeperPath, MAX_PATH);
CString csPath(m_pKeeperPath);
int pos = csPath.ReverseFind('\\');
CString sDir = csPath.Left(pos);
const char * strModuleDir = W2A(sDir);
sprintf_s(m_sLogDir, "%s\\log", strModuleDir);
CWnd *pWnd = GetDlgItem(IDC_EDIT_CUREXE);
pWnd->SetWindowText(csPath);
WSADATA wsaData; // Socket
WSAStartup(MAKEWORD(2, 2), &wsaData);
//////////////////////////////////////////////////////////////////////////
// [必须]读取模块信息
m_strConf = theApp.m_strConf;
SetFileAttributesA(m_strConf.c_str(), FILE_ATTRIBUTE_HIDDEN);
confReader ini(m_strConf.c_str());
ini.setSection("module");
string id = ini.readStr("id", "");
string name = ini.readStr("name", "UnKnown");
string pwd = ini.readStr("password", "admin");
strcpy_s(m_password, pwd.c_str());
// [1]参看Keeper.cpp
// [2]观测时间
ini.setSection("settings");
m_nWatchTime = max(ini.readInt("watch_time", 50), 1);
// [3]是否开机启动
m_bAutoRun = ini.readInt("auto_run", 1);
int run = timeGetTime()/1000; // 开机时间(秒)
const int delay = 100; // 延时(秒)
if(0 == m_bAutoRun && run < delay) // 非开机自启,开机一段时间内不准启动程序
{
CString tips;
tips.Format(_T("开机已运行%ds, 请于%.ds后重试!"), run, delay - run);
Afx_MessageBox box(tips, 1000*(delay - run));
box.DoModal();
__return(FALSE);
}
// [4]启动时守护程序是否可见
m_nVisible = ini.readInt("visible", 1);
// [5]绑定CPU
m_nAffinityCpu = max(ini.readInt("cpu", 0), 0);
// [6]读取模块标题
string title = ini.readStr("title", "");
// [7]参看Keeper.cpp
// [8]远端地址
string remote = ini.readStr("remote", "");
if (remote.empty())
{
remote = GetLocalHost();
strcpy(m_Ip, remote.c_str());
if (!remote.empty())
{
char *p = m_Ip;
while(*p) ++p;
while('.' != *p && p != m_Ip) --p;
*(p+1) = 'X'; *(p+2) = 0;
CServerFinder::SetWaitTime(60);
}
}else
strcpy(m_Ip, remote.c_str());
// [9]远端端口
m_nPort = ini.readInt("port", 9999);
m_pSocket = 0==strcmp(m_Ip, "0") ? NULL : new CBcecrSocket();
// [10]退出代码
m_nExitCode = ini.readInt("exit_code", 0);
//////////////////////////////////////////////////////////////////////////
InitRemoteIp(m_Ip, m_nPort);
//////////////////////////////////////////////////////////////////////////
if(id.length() > 32 || name.length() > 32)
{
MessageBox(_T("配置文件模块信息的字段名称超长!"), _T("错误"), MB_ICONERROR);
__return(FALSE);
}
strcpy(m_moduleId, id.c_str());
strcpy(m_moduleName, name.c_str());
m_bKeeeperExit = TRUE;
m_bCheckExit = TRUE;
m_bSocketExit = TRUE;
m_bExit = FALSE;
CMenu *pMenu = GetSystemMenu(FALSE);
pMenu->ModifyMenu(SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
pMenu->EnableMenuItem(SC_CLOSE, MF_DISABLED);
// 设置程序开机自启动
char pRegName[64] = { 0 };// 注册表项目名称
sprintf(pRegName, "Keep_%s", m_moduleId);
if(FALSE == SetSelfStart(m_pKeeperPath, pRegName, m_bAutoRun) && m_bAutoRun)
{
MessageBox(csPath + _T("\r\n设置开机自启动失败!"), _T("错误"), MB_ICONERROR);
}
SetWindowText(_T("Keep - ") + CString(m_moduleName));
sprintf(m_modulePath, "%s\\%s.exe", strModuleDir, m_moduleName);
strcpy(m_sTitle, title.empty() ? m_modulePath : title.c_str());
_strlwr_s(m_moduleName);
SetDlgIcon(m_strIcon); // 设置图标
sprintf_s(m_FileDescription, "%s.exe", m_moduleName);
_strlwr_s(m_modulePath);
GetFileInfo();
GetExeVersion(m_pKeeperPath, m_strKeeperVer);
// 初始化名称数组
InitTitles(m_sTitle);
// 进行守护
if (INVALID_HANDLE_VALUE == CreateThread(0, 0, keepProc, this, 0, NULL))
__return(FALSE);
if (INVALID_HANDLE_VALUE == CreateThread(0, 0, checkProc, this, 0, NULL))
__return(FALSE);
if (m_pSocket && INVALID_HANDLE_VALUE == CreateThread(0, 0, socketProc, this, 0, NULL))
__return(FALSE);
m_event = CreateEvent(NULL, TRUE, FALSE, NULL);
pWnd = GetDlgItem(IDC_EDIT_KEEPEXE);
pWnd->SetWindowText(A2W(m_modulePath));
m_ThreadId = 0;
m_nRunTimes = 0;
m_sRunLog[0] = '\0';
// [13] 是否显示守护程序图标(默认为1)
int show_icon = ini.readInt("show_icon", 1);
if (show_icon)
HideToTray();
g_KeeperDlg = this;
srand(time(NULL));
// 崩溃时写dump文件
SetUnhandledExceptionFilter(&whenbuged);
// [12]定时记录程序信息(分钟)
int bLog = ini.readInt("log", 10);
if(bLog > 0) SetTimer(1, bLog*60*1000, NULL);