⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usbcontroller.cpp

📁 Also since the domain name--against which the retrieved domain name is to be matched--is currently h
💻 CPP
📖 第 1 页 / 共 2 页
字号:


#include "stdafx.h"
#include "USBControl.h"
#include <dbt.h>
//#include "DriveLetter.h"
#include "initguid.h"
//#include "guiddef.h"

static DWORD PrevDrives;
static DWORD CurDrives;
static DWORD USBDrives;

DEFINE_GUID(GUID_DEVINTERFACE_USBSTOR,0xa5dcbf10,0x6530,0x11d2,0x90,0x1f,0x00,0xc0,0x4f,0xb9,0x51,0xed);

/*static /*const*/ /*GUID GUID_DEVINTERFACE_USBSTOR =
{ 0x36FC9E60L, 0xC465, 0x11CF, { 0x80, 0x56, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00 } };*/

/*static /*const*/ /*GUID GUID_DEVINTERFACE_USB_DEVICE =
{ 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };*/

/*Function Declarations*/
static VOID WINAPI service_main();
void CmdInstallService();
void CmdRemoveService();
VOID CmdDebugService(int argc, TCHAR **argv);
BOOL WINAPI ControlHandler ( DWORD dwCtrlType );
LPTSTR GetLastErrorText( LPTSTR lpszBuf, DWORD dwSize );

//static VOID WINAPI service_main();
static DWORD WINAPI service_ctrl(DWORD dwCtrlCode,DWORD evtype, PVOID evdata, PVOID Context);
static BOOL ReportStatusToSCMgr(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint);
static BOOL ResumeService();
static BOOL PauseService();
static VOID StopService();
static BOOL RegisterForDeviceNotify();




/*End Function Declarations*/

/*Global Variables*/
static CUSBControl *pSrv = NULL;
static SERVICE_STATUS			ssStatus;       // current status of the service
static SERVICE_STATUS_HANDLE	sshStatusHandle;
static BOOL						bRunningService = FALSE;	// Service beginning flag
static BOOL						bPauseService = FALSE;		// Stop flag at one o'clock of service
static BOOL						bDebug = FALSE;
static TCHAR					szErr[256];
/*End Global Variables*/


/*Main Function*/
int _tmain(int argc, TCHAR* argv[] /*, TCHAR* envp[] */)
{
//    LOG_DBG(_T("Start"));
	OutputDebugString(L"tmain Start");
	int nRetCode = 0;
	SC_HANDLE hSCM = NULL;
	SC_HANDLE hService = NULL;
	pSrv = new CUSBControl();
	if (pSrv == NULL) 
	{
		printf( "Object Create Error : %d\n", ::GetLastError() );
		return -1;
	} else if (!pSrv->Init()) {   //This initialization will create a event..
		printf( "DtsRsrcCtrlSrv Init() Error : %d\n", ::GetLastError() );
		return -1;
	}

	SERVICE_TABLE_ENTRY dispatchTable[] =
	{
		{ pSrv->GetServiceName(), (LPSERVICE_MAIN_FUNCTION)service_main},
		{ NULL, NULL}
	};
//#ifdef _DEBUG
	if ( (argc > 1) &&
		((*argv[1] == '-') || (*argv[1] == '/')) )
	{
		if ( _tcsicmp( _T("install"), argv[1]+1 ) == 0 )
		{
//			LOG_DBG(_T("Service Installed"));
			CmdInstallService();
		}
		else if ( _tcsicmp( _T("remove"), argv[1]+1 ) == 0 )
		{
//			LOG_DBG(_T("Service Removed"));
			CmdRemoveService();
		}
		else if ( _tcsicmp( _T("debug"), argv[1]+1 ) == 0 )
		{
//			LOG_DBG(_T("Service Debug"));
			bDebug = TRUE;
			CmdDebugService(argc, argv);
		}
		else
		{
			goto dispatch;
		}
		if (pSrv != NULL) delete pSrv;
		return nRetCode;
	}
	
	// if it doesn't match any of the above parameters
	// the service control manager may be starting the service
	// so we must call StartServiceCtrlDispatcher
dispatch:
	// this is just to be friendly
	printf( "%s -install          to install the service\n", pSrv->GetModuleName() );
	printf( "%s -remove           to remove the service\n", pSrv->GetModuleName() );
	printf( "%s -debug <params>   to run as a console app for debugging\n", pSrv->GetModuleName() );
	printf( "\nStartServiceCtrlDispatcher being called.\n" );
	printf( "This may take several seconds.  Please wait.\n" );

//#endif // _DEBUG

	nRetCode = -1;
	try{	// Exception handling
		
		hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if(hSCM == NULL){
//			LOG_ERRC(_T("OpenSCManger Failed"),GetLastError());
			
		}

		hService = ::OpenService(hSCM, pSrv->GetServiceName(), SERVICE_CHANGE_CONFIG|SERVICE_START);
		if(hService == NULL){
//			LOG_ERRC(_T("OpenService Failed"),GetLastError());
			
		}

		SERVICE_FAILURE_ACTIONS actions = {0};
		SC_ACTION info[] = {{SC_ACTION_RESTART,1000}, {SC_ACTION_RESTART,1000}, {SC_ACTION_RESTART,1000}};
		actions.cActions = sizeof(info) / sizeof(SC_ACTION);
		actions.lpsaActions = info;
		if(!::ChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, &actions)){
//			LOG_ERRC(_T("ChangeServiceConfig Failed"),GetLastError());
			
		}

		if(hService) ::CloseServiceHandle(hService);
		if(hSCM) ::CloseServiceHandle(hSCM);


		if (!StartServiceCtrlDispatcher(dispatchTable))
		{
//			LOG_ERRC(_T("StartServiceCtrlDispatcher Error"),GetLastError());
			printf( "StartServiceCtrlDispatcher Error : %d\n", ::GetLastError() );
		} else {
			nRetCode = 0;
		}
	}catch(...){
	}

	if (pSrv != NULL) delete pSrv;
//	LOG_DBG(_T("Stop"));
	OutputDebugString(L"tmain End");
	return nRetCode;

	
}

static void WINAPI service_main(
)
{
	OutputDebugString(L"service_main Start");
	DWORD	dwExitCode = 0;
	char str[100];
	
//Sleep(20000);
	try{	// Exception handling
//		LOG_DBG(_T("Service Started"));
		
		//Setting of service control
		if( bDebug == FALSE ){
			// register our service control handler:
			//
			sshStatusHandle = RegisterServiceCtrlHandlerEx(pSrv->GetServiceName(), (LPHANDLER_FUNCTION_EX)service_ctrl,(LPVOID)0);
			if (!sshStatusHandle)
			{
//				LOG_FTLC(_T("RegisterServiceCtrlHandler Failed"),GetLastError());
				goto cleanup;
			}
		}

			// SERVICE_STATUS members that don't change in example
		ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
		ssStatus.dwServiceSpecificExitCode = 0;

		// report the status to the service control manager.
		// PENDING !!
		if (!ReportStatusToSCMgr(
								SERVICE_START_PENDING, // service state
								NO_ERROR,              // exit code
								3000))                 // wait hint
		{
//			LOG_ERR(_T("ReportStatusToSCMgr"));
			goto cleanup;
		}

		MessageBox(NULL,L"Inside ServiceMain",L"Information",MB_OK);
		// report the status to the service control manager.
		// RUNNING !!
		if (!ReportStatusToSCMgr(
								SERVICE_RUNNING, // service state
								NO_ERROR,        // exit code
								0))              // wait hint
		{
//			LOG_ERR(_T("ReportStatusToSCMgr"));
			goto cleanup;
		}

		// Service beginning flag ON
		bRunningService = TRUE;

		//Get already present volumes
		PrevDrives=GetLogicalDrives();
		USBDrives=/*(USBDrives)|*/(PrevDrives^CurDrives);
		sprintf(str,"\n At Service start: Prev Drive = %lu,Cur Drive=%lu,USB Drive=%lu",PrevDrives,CurDrives,USBDrives);
		OutputDebugStringA(str);

		if(!RegisterForDeviceNotify())
		{
			goto cleanup;
		}

		pSrv->setUSBDrives(PrevDrives);
		//Sleep(15000);
		// Service main processing
		pSrv->Run(USBDrives);

	}
	catch(...){	// Exception obtaining
	}

cleanup:

//	try{	// 椺奜張棟
//
//
//	}catch(...){
//	}

	// try to report the stopped status to the service control manager.
	//
	(VOID)ReportStatusToSCMgr(
								SERVICE_STOPPED,
								dwExitCode,
								0);
	OutputDebugString(L"service_main End");
	return;
	


}
/****************************************************************************
* FUNCTION : service_ctrl
* ABSTRACT : Control handler function of service
*****************************************************************************/
static DWORD WINAPI service_ctrl(
	DWORD dwCtrlCode		/* (I)   Control code   */,
	DWORD evtype/* Device Event Type*/, 
	PVOID evdata/* Device Event Data*/, 
	PVOID Context /*Context*/
	
)
{
//	LOG_DBG(_T("Start"));
	DWORD dwErr = 0;
	TCHAR szMsg[260];
	_DEV_BROADCAST_HEADER* pdb = NULL;
	DEV_BROADCAST_DEVICEINTERFACE* pddb = NULL;
	char str[100];
	TCHAR DriveStrings[128];
	DWORD VolumeMask;
	DWORD len;
	int i=0;
	// Handle the requested control code.
	//
	//DWORD CurDrives;
	switch (dwCtrlCode)
	{
	// Stop the service.
	//
	// SERVICE_STOP_PENDING should be reported before
	// setting the Stop Event - hServerStopEvent - in
	// ServiceStop().  This avoids a race condition
	// which may result in a 1053 - The Service did not respond...
	// error.
	case SERVICE_CONTROL_STOP:
//		LOG_DBG(_T("SERVICE_CONTROL_STOP Event"));
		OutputDebugString(L"SERVICE_CONTROL_STOP Received");
		ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 0);
		//The service stop event is set. 
		StopService();
		ReportStatusToSCMgr(SERVICE_STOPPED,NO_ERROR,0);
		dwErr = NO_ERROR;
		return dwErr;

#ifdef _DEBUG

	// The temporary suspension of service and the restart are deleted from the processing object in this application because it doesn't support it. 

	// Pause the service
	case SERVICE_CONTROL_PAUSE:
//		LOG_DBG(_T("SERVICE_CONTROL_PAUSE Event"));
		if (bRunningService == TRUE && bPauseService == FALSE){
			// Tell the SCM what's happening
			ReportStatusToSCMgr(SERVICE_PAUSE_PENDING, NO_ERROR, 1000);
			if(PauseService() == TRUE){
				ssStatus.dwCurrentState = SERVICE_PAUSED;
			}else{
				// To the service stop
				ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 0);
				StopService();
				dwErr = NO_ERROR;
				return dwErr;
			}
		}
		break;

	// Resume from a pause
	case SERVICE_CONTROL_CONTINUE:
//		LOG_DBG(_T("SERVICE_CONTROL_CONTINUE"));
		if (bRunningService == TRUE && bPauseService == TRUE){
			// Tell the SCM what's happening
			ReportStatusToSCMgr(SERVICE_CONTINUE_PENDING, NO_ERROR, 1000);
			if(ResumeService() == TRUE){
				ssStatus.dwCurrentState = SERVICE_RUNNING;
			}else{
				// To the service stop
				ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 0);
				StopService();
				dwErr = NO_ERROR;
				return dwErr;
			}
		}
		break;
#endif

      // Update the service status.
      //
	case SERVICE_CONTROL_INTERROGATE:
		dwErr = NO_ERROR;
		break;

		// device event
		//
	case SERVICE_CONTROL_DEVICEEVENT:
		OutputDebugString(L"SERVICE_CONTROL_DEVICEEVENT Received");
		pSrv->SetDevChangeEvent();

		switch(evtype)
		{
		case DBT_DEVICEARRIVAL:
			OutputDebugString(L"DBT_DEVICEARRIVAL caught");
			/*
			pdb = (_DEV_BROADCAST_HEADER*)evdata;
			switch(pdb->dbcd_devicetype)
			{
			case DBT_DEVTYP_DEVICEINTERFACE:
				OutputDebugString(L"DBT_DEVTYP_DEVICEINTERFACE caught");
				pddb = (DEV_BROADCAST_DEVICEINTERFACE*)evdata;
				swprintf_s(szMsg,L"Device Name : %s",pddb->dbcc_name);
				OutputDebugString(szMsg);
				break;
			case DBT_DEVTYP_HANDLE:
				OutputDebugString(L"DBT_DEVTYP_HANDLE caught");
				break;
			case DBT_DEVTYP_OEM:
				OutputDebugString(L"DBT_DEVTYP_OEM caught");
				break;
			case DBT_DEVTYP_PORT:
				OutputDebugString(L"DBT_DEVTYP_PORT caught");
				break;
			case DBT_DEVTYP_VOLUME:
				OutputDebugString(L"DBT_DEVTYP_VOLUME caught");
				break;
			}
			*/
			/*
			if(	(((DEV_BROADCAST_HDR*)(evdata))->dbch_devicetype)==DBT_DEVTYP_VOLUME)
			{
				VolumeMask=(((DEV_BROADCAST_VOLUME*)(evdata))->dbcv_unitmask);
				sprintf(str,"\n At Device Arrival : VolumeMask=%lu",VolumeMask);
				OutputDebugStringA(str);

			}
			*/

			//Sleep(5000);
			//CurDrives=GetLogicalDrives();
			//USBDrives=(PrevDrives^CurDrives);
			//sprintf(str,"\n At Device Arrival : Prev Drive = %lu,Cur Drive=%lu,USB Drive=%lu",PrevDrives,CurDrives,USBDrives);
			//pSrv->setUSBDrives(USBDrives);
			//OutputDebugStringA(str);
			//pSrv->SetDevChangeEvent();
			/*
			memset(DriveStrings,0x00,128*sizeof(TCHAR));
			len=GetLogicalDriveStrings(128,DriveStrings);
			
			while(i<127)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -