www.pudn.com > FileGuard.zip > FGWatcher.cpp


////////////////////////////////////////////////////////////////////////////////////////////////////// 
// 
//FGWatcher.cpp------for watcher process. 
 
#include "StdAfx.h" 
#include "FileGuard.h" 
#include "..\HookShr\HookError.h" 
#include "FileGuardApp.h" 
 
BOOL bWatcher=FALSE;		//is the process is a watcher? 
 
//hWatchee: handle of a process to be watched. 
//return 0 if fail. 
HANDLE WatcherProc(HANDLE hWatchee) 
{ 
	//wait for the process to terminate. 
	WaitForSingleObject(hWatchee, INFINITE); 
 
	STARTUPINFO sinfo; 
	ZeroMemory(&sinfo, sizeof(sinfo)); 
	sinfo.cb=sizeof(sinfo); 
	sinfo.dwFlags=STARTF_FORCEOFFFEEDBACK;		//Not change cursor. 
	PROCESS_INFORMATION pinfo; 
	if(!bWatcher) 
	{ 
		char szHandle[16]; 
		sprintf(szHandle, "%u", OpenProcess(PROCESS_ALL_ACCESS, TRUE, GetCurrentProcessId()));  //debug 
		SetEnvironmentVariable("HANDLE", (char *)szHandle); 
	} 
	//Create a watcher process or a main process depent on bWatcher. 
	if(!CreateProcess("FILEGUARD.EXE", bWatcher? NULL: "FILEGUARD.EXE -Watcher", 0, 0, !bWatcher, 0, 0, 0, &sinfo, &pinfo)) 
		return 0; 
 
	CloseHandle(pinfo.hThread); 
	return pinfo.hProcess;			//debug //Remember to close hProcess. 
} 
 
//Create a new watcher to watch myself. 
HANDLE CreateWatcher() 
{ 
	return WatcherProc(NULL); 
} 
 
//Prevent watcher process to be closed. 
UINT WatchTheWatcher(LPVOID param) 
{ 
	HANDLE hNewWatcher; 
 
	while((hNewWatcher=WatcherProc(hWatcher))!=NULL) 
	{ 
		CloseHandle(hWatcher); 
		hWatcher=hNewWatcher; 
	} 
 
	//The only way to terminate the thread is to call terminatethread from parent thread. 
 
	//Cannot not create new watcher. 
	ErrorHandler(FG_ERR_NOT_ENOUGH_MEMORY); 
 
	return 1; 
} 
 
//hide process. 
void HideProcess() 
{ 
    HINSTANCE hDllInst = LoadLibrary("KERNEL32.DLL");  
 
    if(hDllInst)  
    {         
        typedef DWORD (WINAPI *WINPROC)(DWORD,DWORD);  
     
        WINPROC RegisterServiceProcessAlias = NULL;  
        RegisterServiceProcessAlias = (WINPROC)GetProcAddress(hDllInst, "RegisterServiceProcess");  
     
        if(RegisterServiceProcessAlias)  
            RegisterServiceProcessAlias(GetCurrentProcessId(),1);  
 
    FreeLibrary(hDllInst);  
    } 
}