static bool DumpModuleInfo(HANDLE LogFile, HINSTANCE ModuleHandle, int nIndex)
{
	TCHAR szModName[MAX_PATH] = {0};
	__try
	{
		if (GetModuleFileName(ModuleHandle, szModName, MAX_PATH) > 0)
		{
			// If GetModuleFileName returns greater than zero then this must
			// be a valid code module address. Therefore we can try to walk
			// our way through its structures to find the link time stamp.
			IMAGE_DOS_HEADER *DosHeader = (IMAGE_DOS_HEADER*)ModuleHandle;
			if (IMAGE_DOS_SIGNATURE != DosHeader->e_magic)
				return false;

			IMAGE_NT_HEADERS *NTHeader = (IMAGE_NT_HEADERS*)((TCHAR *)DosHeader
				+ DosHeader->e_lfanew);
			if (IMAGE_NT_SIGNATURE != NTHeader->Signature)
				return false;

			WriteLogFile(LogFile, _T("Module Index %d, Name:%s\r\n"), nIndex, szModName);
			WriteLogFile(LogFile, _T("Image Base: 0x%08x  Image Size: 0x%08x\r\n"), NTHeader->OptionalHeader.ImageBase, NTHeader->OptionalHeader.SizeOfImage);
			WriteLogFile(LogFile, _T("Checksum:   0x%08x  Time Stamp: 0x%08x\r\n"), NTHeader->OptionalHeader.CheckSum, NTHeader->FileHeader.TimeDateStamp);
			return true;
		}
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
	}
	return true;
}
void DumpSystemInformation(HANDLE hLogFile, TCHAR* lpModuleName)
{
	//system user name
	DWORD nUserNameSize = 120;
	TCHAR szTemp[120] = {0};
	if (!GetUserName(szTemp, &nUserNameSize))
		strcpy_s(szTemp, 120, "UnKnow");

	WriteLogFile(hLogFile, "%s run by %s.\r\n", lpModuleName, szTemp);

	//system version
	TCHAR szWinVer[50] = {0};
	TCHAR szMajorMinorBuild[50] = {0};
	int nWinVer;
	GetWinVer(szWinVer, &nWinVer, szMajorMinorBuild);
	WriteLogFile(hLogFile, "Operating system version:%s(%s).\r\n", szWinVer, szMajorMinorBuild);

	//process state
	SYSTEM_INFO sysinfo;
	GetSystemInfo(&sysinfo);
	WriteLogFile(hLogFile, "%d process, type %d.\r\n", sysinfo.dwNumberOfProcessors, sysinfo.dwProcessorType);

	//memory state
	MEMORYSTATUS meminfo;
	GlobalMemoryStatus(&meminfo);
	WriteLogFile(hLogFile, _T("%d%% memory in use.\r\n"), meminfo.dwMemoryLoad);
	WriteLogFile(hLogFile, _T("%d MBytes physical memory.\r\n"), (meminfo.dwTotalPhys+ONEM-1)/ONEM);
	WriteLogFile(hLogFile, _T("%d MBytes physical memory free.\r\n"), (meminfo.dwAvailPhys+ONEM-1)/ONEM);
	WriteLogFile(hLogFile, _T("%d MBytes paging file.\r\n"), (meminfo.dwTotalPageFile+ONEM-1)/ONEM);
	WriteLogFile(hLogFile, _T("%d MBytes paging file free.\r\n"), (meminfo.dwAvailPageFile+ONEM-1)/ONEM);
	WriteLogFile(hLogFile, _T("%d MBytes user address space.\r\n"), (meminfo.dwTotalVirtual+ONEM-1)/ONEM);
	WriteLogFile(hLogFile, _T("%d MBytes user address space free.\r\n"), (meminfo.dwAvailVirtual+ONEM-1)/ONEM);
}
Esempio n. 3
0
int Encrypt_MAC_Str (const char* szStr ,char* szOutput ) 
{//To caculate the MAC Value
	char szLogBuff [MAXCONTLEN] ;
	bzero (szLogBuff,sizeof(szLogBuff));
	
	if (strlen(szStr)||szStr==NULL){ //To handle the exception.
		sprintf (szLogBuff,"[%s-line:%d] You have passed an invalid String to Encrypt,pls chck your sytem...",__FILE__,__LINE__) ;
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
		return -1 ;	
	}
	char szMAC [48+1];
	bzero (szMAC,sizeof(szMAC)) ;
	read_config_file ("./sysconfig.cfg","MAC_VALUE",szMAC) ;	
	if (!strlen(szMAC)){
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d]Can not read MAC from configuration file properly...",__FILE__,__LINE__) ;
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
		WriteLogFileInHex_Ex (szMAC,__SYS_TYPE_LOGFILE_RAW__);
		return -1 ;
	}
	
	char szOrigStr [MAXCONTLEN] ;
	bzero (szOrigStr,sizeof(szOrigStr)) ;	//To hold the original string,which will be sent to encrypt
	sprintf (szOrigStr,"80001%s%03d%s%s",szMAC,strlen(szStr),szStr,szStr); //Just like 80001005ASDFGASDFG
	
	bzero (szOutput,sizeof(szOutput)) ;
	return	Encrypt_str_Encrypt (szOrigStr,szOutput) ;
}
Esempio n. 4
0
void PrintLn(const char* message)
{
	INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
	GetCurrentTimeAndDate(date_time);
	WriteLogFile(date_time);

	WriteLogFile(message);
	WriteLogFile("\n");
}
Esempio n. 5
0
/*
 *	函数介绍:服务控制函数
 *  输入参数:控制码Opcode
 *  输出参数: 无
 *  返回值:无
 */
VOID WINAPI sch_ServiceCtrlHandler(DWORD Opcode) 
{ 
    switch(Opcode) 
    { 
        case SERVICE_CONTROL_PAUSE: //暂停服务
        // Do whatever it takes to pause here. 
            sch_ServiceStatus.dwCurrentState = SERVICE_PAUSED; 
			//AddToLog("Pause Service\r\n");
            break; 
 
        case SERVICE_CONTROL_CONTINUE: //继续服务
        // Do whatever it takes to continue here. 
            sch_ServiceStatus.dwCurrentState = SERVICE_RUNNING; 

			//AddToLog("Continue Service\r\n");
            break; 
 
        case SERVICE_CONTROL_STOP: //停止服务
        // Do whatever it takes to stop here. 
            
            sch_ServiceStatus.dwWin32ExitCode = 0; 
            sch_ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
            sch_ServiceStatus.dwCheckPoint    = 0; 
            sch_ServiceStatus.dwWaitHint      = 0; 
            
			//smsPort.CloseCom();
			CAlertMain::CloseSerialPort();

            if(!SetServiceStatus(sch_ServiceStatusHandle, &sch_ServiceStatus))
            { 
				g_strMessage.Format("SetServiceStatus error %ld\r\n", GetLastError());
				WriteLogFile(g_strMessage);
            } 

            return; 
 
        case SERVICE_CONTROL_INTERROGATE: 
        // Fall through to send current status. 
            break; 
 
        default:
			g_strMessage.Format("Unrecognized opcode %ld\r\n", Opcode);
			WriteLogFile(g_strMessage);
    } 
 
    // Send current status. 
    if (!SetServiceStatus (sch_ServiceStatusHandle,  &sch_ServiceStatus)) 
    { 
		g_strMessage.Format("SetServiceStatus error %ld\r\n", GetLastError());
		WriteLogFile(g_strMessage);
		return;
    } 
} 
Esempio n. 6
0
void PrintLn(int line)
{
	INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
	GetCurrentTimeAndDate(date_time);
	WriteLogFile(date_time);

	char code[1024];
	sprintf_s(code, sizeof(code), "%d", line);

	WriteLogFile(code);
	WriteLogFile("\n");
}
Esempio n. 7
0
void PrintLn(const wchar_t *message, int line)
{
	INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
	GetCurrentTimeAndDate(date_time);
	WriteLogFile(date_time);

	wchar_t code[1024];
	swprintf_s(code, sizeof(code), message, line);

	//	OutputDebugStringW(message);
	WriteLogFile(code);
	WriteLogFile("\n");
}
Esempio n. 8
0
int GetTerminalID (char* szOutput) 
{
	
	char szLogBuffer [1024] ;	
	bzero (szLogBuffer,sizeof(szLogBuffer)) ; //reflush the logbuffer .
	
	int iRet  = pthread_mutex_init (&mtx_getTerminalID,NULL) ;
	if (iRet) {
		sprintf (szLogBuffer,"[%s-line:%d]Can not initialize the mutext successfully[Err:%d],pls check your system...",__FILE__,__LINE__,iRet)  ;
			
		WriteLogFile (&szLogBuffer,__SYS_TYPE_LOGFILE_RAW__) ;	
		pthread_mutex_destroy (&mtx_getTerminalID) ;
		return  -1 ;
	}; 
		
	
	char szBuffer  [1024*2] ;			
	bzero (&szBuffer,sizeof(szBuffer)) ; //reflush the buffer .	
	pthread_mutex_lock (&mtx_getTerminalID) ; //to hold the terminalid read from config
	
	read_config_file ("./sysconfig.cfg","TERMINAL",szBuffer) ;
	if (!strlen(szBuffer)) {
		
		bzero (szLogBuffer,sizeof(szLogBuffer)) ;
		sprintf (szLogBuffer,"[%s-line:%d]Can not read the terminal from config file, pls check your system...",__FILE__,__LINE__) ;	
		
		WriteLogFile (szLogBuffer,__SYS_TYPE_LOGFILE_RAW__) ;
		pthread_mutex_unlock (&mtx_getTerminalID) ;	//Unlock the mutex .
		pthread_mutex_destroy (&mtx_getTerminalID) ;    //clean up 
		
		return -1 ;
		
	}
	char* szTerminalArr [200] ;
	int iTermArrLen = splitString  (szBuffer,szTerminalArr,';') ;
	
	if (iTermArrLen <= 0){
		pthread_mutex_unlock (&mtx_getTerminalID) ;
		return -1 ;
	}
	
	int j = -1 ; //To generate a random number between 0 and iTermArrLen ;
	j = 0 + (int) (iTermArrLen*1.0 * (rand() / (RAND_MAX + 0.0)));
	if (j>= iTermArrLen) 
		j  =  0 ; //IF the random number is greater than iTermArrLen, set j  to 0 ;
	
	sprintf (szOutput,"%s",szTerminalArr [j]); 	
	pthread_mutex_unlock (&mtx_getTerminalID) ; //Unlock 
	pthread_mutex_destroy (&mtx_getTerminalID) ; //clean up the resource .
	return  0 ;	
}
Esempio n. 9
0
void IisRequestBarrierLog::LogTextArgs(char* szFormat, va_list args)
{
    char    szOutput[MAX_DEBUG_OUTPUT];
    int     nWritten = 0;

    nWritten = _vsnprintf( szOutput + nWritten,
                           MAX_DEBUG_OUTPUT,
                           szFormat,
                           args );

    if ( nWritten == -1 )
    {
        if ( MAX_DEBUG_OUTPUT < 3 )
        {
            return;
        }

        szOutput[MAX_DEBUG_OUTPUT - 3] = '\r';
        szOutput[MAX_DEBUG_OUTPUT - 2] = '\n';
        szOutput[MAX_DEBUG_OUTPUT - 1] = '\0';

		nWritten = MAX_DEBUG_OUTPUT-1;
    }

	WriteLogFile(szOutput, nWritten);
}
Esempio n. 10
0
CLogFile::~CLogFile()
{
    if (hLogFile != INVALID_HANDLE_VALUE)
    {
        WriteLogFile(LOG_LINE_TIME, "close file\r\n\r\n\r\n\r\n");
        CloseHandle(hLogFile);//关闭句柄
    }
}
Esempio n. 11
0
static int Encrypt_Socket_Open () 
{
	
	char szLogBuff [MAXCONTLEN] ;
	bzero (szLogBuff,sizeof(szLogBuff));	
	char szTmp [30] ;
	bzero (szTmp,sizeof(szTmp));
	isActive  = 0 ;	
	
	read_config_file ("./sysconfig.cfg","ENCRYPT_IP",szTmp) ;
	if (!strlen(szTmp)){
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] can not read the addr of Encryp from cfg file...",__FILE__,__LINE__);
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
		return -1  ;
	}
	sfd  = socket (AF_INET,SOCK_STREAM,0) ;
	if (sfd ==-1) {
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] Can not create a socket handle, pls check your system...",__FILE__,__LINE__) ;
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
		return -1 ;
	}
	
	struct sockaddr_in sin ;
	bzero (&sin,sizeof(struct sockaddr_in)) ;
	sin.sin_addr.s_addr = inet_addr (szTmp) ;
	sin.sin_family = AF_INET ;
	bzero (szTmp,sizeof(szTmp)) ;
	read_config_file ("./sysconfig.cfg","ENCRYPT_PORT",szTmp) ;
	if (!strlen(szTmp))	
		sprintf (szTmp,"%s","8888") ;	
	sin.sin_port = htons (atoi(szTmp)) ;
	
	int ret  = connect (sfd,(struct sockaddr*) &sin,sizeof(struct sockaddr_in));		
	if (ret==-1 ){
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] can not connect to encryption,pls check your system...",__FILE__,__LINE__) ;
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
		return -1 ;
	}
	isActive  = 1 ; //To set flag of connection.
	return sfd ; 
}
Esempio n. 12
0
int Encrypt_PIN_str (const char* szStr, char* szOutput) 
{ //To caculate the PIN value
	char szLogBuff [MAXCONTLEN] ;
	bzero (szLogBuff,sizeof(szLogBuff)) ;
	if (!strlen(szStr)){
		sprintf (szLogBuff,"[%s-line:%d] You have passed an invalid PIN,pls chck your ssytem...",__FILE__,__LINE__);
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
		return  -1; 	
	}
	
	char szOriginalStr [MAXCONTLEN] ; //To hold the original string.
	bzero (szOriginalStr,sizeof(szOriginalStr));
		
	char szTmp [MAXCONTLEN] ;
	bzero (szTmp,sizeof(szTmp));
	read_config_file ("./sysconfig.cfg","PIN_VALUE",szTmp);
	if (!strlen(szTmp)){
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] Can not read PIN value from configuration file properlly...",__FILE__,__LINE__) ;
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
		WriteLogFileInHex_Ex (szTmp,__SYS_TYPE_LOGFILE_RAW__) ;
		return -1;
	}
	
	sprintf (szOriginalStr,"601001%s0%d%s",szTmp,strlen(szStr),szStr) ;
	bzero (szTmp,sizeof(szTmp));
	StringOfChar('F',14-strlen(szStr),szTmp);	
	strcat (szOriginalStr,szTmp) ;
	
	bzero(szTmp,sizeof(szTmp));
	bzero (szOutput,sizeof(szOutput));
	if (!Encrypt_str_Encrypt (szOriginalStr,szTmp)){
		strncpy (szOutput,szTmp,strlen(szTmp)) ;
		return 0;		
	} else 
		return -1; 	
	

}
Esempio n. 13
0
BOOL CLogFile::WriteLogData()
{
	if (log_size > 0) {
		log_data[log_size / sizeof(TCHAR)] = TEXT('\0');
		if (WriteLogFile(log_data)) {
			log_size = 0;
			log_count = 0;
			return TRUE;
		}
		else
			return FALSE;
	}
	else
		return TRUE;
}
Esempio n. 14
0
/*
 *	函数介绍:服务启动函数
 */
VOID  WINAPI StartAlertService(DWORD argc, LPTSTR *argv)
{

 
    sch_ServiceStatus.dwServiceType        = SERVICE_WIN32; 
    sch_ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
    sch_ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; 
    sch_ServiceStatus.dwWin32ExitCode      = 0; 
    sch_ServiceStatus.dwServiceSpecificExitCode = 0; 
    sch_ServiceStatus.dwCheckPoint         = 0; 
    sch_ServiceStatus.dwWaitHint           = 0; 
 
    sch_ServiceStatusHandle = RegisterServiceCtrlHandler("AlertService7", sch_ServiceCtrlHandler);

	if(sch_ServiceStatusHandle == 0)
	{
		g_strMessage.Format("RegisterServiceCtrlHandler failed %d\r\n", GetLastError());
		WriteLogFile(g_strMessage);
		return;
	}

    // Initialization complete - report running status. 
    sch_ServiceStatus.dwCurrentState       = SERVICE_RUNNING; 
    sch_ServiceStatus.dwCheckPoint         = 0; 
    sch_ServiceStatus.dwWaitHint           = 0; 
 
    if (!SetServiceStatus (sch_ServiceStatusHandle, &sch_ServiceStatus)) 
    { 
		g_strMessage.Format("SetServiceStatus error %ld\r\n", GetLastError());
		WriteLogFile(g_strMessage);
		return;
    } 
	
	//InitService();//启动实际工作线程
	Run();
}
Esempio n. 15
0
static int Encrypt_Socket_Close (int fd)
{
	char szLogBuff [MAXCONTLEN] ;
	
	//if (isActive){
		shutdown(sfd,2) ;
		close (sfd); 
		sfd  =-1  ;
		isActive =0 ;
		bzero (szLogBuff,sizeof(szLogBuff));
		sprintf (szLogBuff,"[%s-line:%d] ",__FILE__,__LINE__);
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
	//}
	return 0 ;
}
Esempio n. 16
0
void PrintLn(const wchar_t *message, const wchar_t *message2, const wchar_t *message3, const wchar_t *message4)
{
	INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
	GetCurrentTimeAndDate(date_time);
	WriteLogFile(date_time);

	WriteLogFile(message);
	WriteLogFile(message2);
	WriteLogFile(message3);
	WriteLogFile(message4);
	WriteLogFile("\n");
}
Esempio n. 17
0
void server::run() {

  	// Create a pool of threads to run all of the io_services.
  	std::vector<boost::shared_ptr<boost::thread> > threads;
  	for (std::size_t i = 0; i < thread_pool_size_; ++i) {
    	boost::shared_ptr<boost::thread> thread(new boost::thread( boost::bind(&boost::asio::io_service::run, &io_service_)) );
    	threads.push_back(thread);
		asOP_->mthreadList[thread->get_id()] = i;
  	}

	asOP_->Initialize();

    WriteLogFile("%-40s : %s", "Started..........", "OK");
	fflush(stdout);

  	// Wait for all threads in the pool to exit.
	for (std::size_t i = 0; i < threads.size(); ++i) {
		threads[i]->join();
	}

}
void DumpModuleList(HANDLE LogFile)
{
	SYSTEM_INFO	SystemInfo;
	GetSystemInfo(&SystemInfo);

	// Set NumPages to the number of pages in the 4GByte address space
	const size_t PageSize = SystemInfo.dwPageSize;
	const size_t NumPages = 4 * size_t(ONEG / PageSize);
	size_t pageNum = 0;
	void *LastAllocationBase = 0;
	int nModuleIndex = 1;

	WriteLogFile(LogFile, "\r\n\r\nModule list of process\r\n");
	while (pageNum < NumPages)
	{
		MEMORY_BASIC_INFORMATION MemInfo;
		if (VirtualQuery((void *)(pageNum * PageSize), &MemInfo, sizeof(MemInfo)) && MemInfo.RegionSize > 0)
		{
			//Next module start address
			pageNum += MemInfo.RegionSize / PageSize;
			if (MemInfo.State == MEM_COMMIT && MemInfo.AllocationBase > LastAllocationBase)
			{
				// Look for new blocks of committed memory, and try
				// recording their module names - this will fail
				// gracefully if they aren't code modules
				LastAllocationBase = MemInfo.AllocationBase;
				DumpModuleInfo(LogFile, (HINSTANCE)LastAllocationBase, nModuleIndex);
				nModuleIndex++;
			}
		}
		else
		{
			// If VirtualQuery fails we advance by 64K because that is the
			// granularity of address space doled out by VirtualAlloc()
			pageNum += SIXTYFOURK / PageSize;
		}
	}
}
Esempio n. 19
0
/*
 *	函数介绍:程序入口函数  
 *  输入参数:argv[1]为-install是安装服务,-remove时删除服务,argv[2]安装时为服务控制台显示服务名称
    删除时为注册服务名称,此程序为AlertService
 *  输出参数:无
 *  返回值:
 */
int _tmain(int argc, _TCHAR* argv[])
{
	int nRetCode = 0;
	if(WriteIniFileString("testsection","testkey","testvalue","alert.ini"))
	{
		DeleteIniFileSection("testsection","alert.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","TxtTemplate.ini"))
	{
		DeleteIniFileSection("testsection","TxtTemplate.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","smsconfig.ini"))
	{
		DeleteIniFileSection("testsection","smsconfig.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","general.ini"))
	{
		DeleteIniFileSection("testsection","general.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","itsmConfig.ini"))
	{
		DeleteIniFileSection("testsection","itsmConfig.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","watchsheetcfg.ini"))
	{
		DeleteIniFileSection("testsection","watchsheetcfg.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","email.ini"))
	{
		DeleteIniFileSection("testsection","email.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","emailAdress.ini"))
	{
		DeleteIniFileSection("testsection","emailAdress.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","smsphoneset.ini"))
	{
		DeleteIniFileSection("testsection","smsphoneset.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","interfacedll.ini"))
	{
		DeleteIniFileSection("testsection","interfacedll.ini");
	}
	if(WriteIniFileString("testsection","testkey","testvalue","OfbizConfig.ini"))
	{
		DeleteIniFileSection("testsection","OfbizConfig.ini");
	}

#if 1
    try
	{
		if(hasrun())
			return 0;

		CAlertMain alertmain;
		
		alertmain.Init();
		
		//MSG msg;
		//BOOL bRet=TRUE;
		//while((bRet=::GetMessage(&msg,NULL,0,0))!=0)
		//{
		//	if(bRet==-1)
		//	{
		//		continue;
		//	}

		//	TranslateMessage(&msg);
		//	::DispatchMessage(&msg);
		//}
		MSG msg;
		while(::GetMessage(&msg,NULL,0,0))
		{
			TranslateMessage(&msg);
			::DispatchMessage(&msg);
			switch(msg.message)
			{
				case WM_QUIT:
					exit(1);
					break;
				default:
					break;
			}
		}
	}
	catch(...)
	{
	}
#else
//   argc = 2;
//	argv[1] = "-remove";
//	argv[2] = "AlertService";
//#if 1
//    RunThread(NULL);
//#else

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		cerr << _T("Fatal Error: MFC initialization failed") << endl;
		nRetCode = 1;
	}

	g_strRootPath= FuncGetInstallRootPath();
	SERVICE_TABLE_ENTRY Table[] = 
	{
		{"AlertService7",StartAlertService},
		{NULL,        NULL}
	};
	CString outStr = "parameter required in the command line";
	if(argc <= 1)
	{
		
		cout << (LPCTSTR)outStr << endl;
	}
	else
	{
		if(_stricmp(argv[1],"-install") == 0)
		{
			InstallService(argv[2]);
		}
		else if(_stricmp(argv[1],"-remove") == 0)
		{
			StopService(argv[2]);
		}
		else
		{
			cout << outStr << endl;
		}
	}



	if(!StartServiceCtrlDispatcher(Table))
    { 
		g_strMessage.Format("StartServiceCtrlDispatcher error = %d\r\n", GetLastError());
		WriteLogFile(g_strMessage);
    } 	
#endif
	//CAlertMain::pSender.Release();
	return nRetCode;
}
Esempio n. 20
0
BOOL TRAFFIC_MONITOR(char *server, int port, char *community, int ifindex, 
					 int timeout, int retrydelay, CString strMonitorID, 
					 char *custpath, char *szReturn)
{
	int s;
	struct sockaddr_in serv;

	int		i = 0, ret = 0;
	int		count = 1;
	struct	snval *ptmp = NULL;
	struct	snval *ptmpnext = NULL;

	long	ifOperStatus = 0;
	Gauge	ifSpeed = 0;
	Counter ifInOctets = 0, ifOutOctets = 0;
	Counter ifInErrors = 0, ifOutErrors = 0;

	if((ret = MakeSocket(server, port, s, serv)) < 0)
	{
		if(ret == -1)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Traffic_1%>"));
		else if(ret == -2)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Traffic_2%>"));
		else
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Traffic_3%>"));

		return FALSE;
	}

	struct oid *poid = NULL, *ptmpoid = NULL;
	oid ifInOctets_oid = {{0x2b, 6, 1, 2, 1, 2, 2, 1, 10}, 9};
	oid ifOutOctets_oid = {{0x2b, 6, 1, 2, 1, 2, 2, 1, 16}, 9};
	ifInOctets_oid.id[ifInOctets_oid.len++] = ifindex;
	poid = ptmpoid = &ifInOctets_oid;
	ifOutOctets_oid.id[ifOutOctets_oid.len++] = ifindex;
	ptmpoid->next = &ifOutOctets_oid;
	ptmpoid = ptmpoid->next;

	struct snval *psnval = NULL;
	if((ret = SN_VALUES(s, serv, community, 1, poid, &psnval)) < 0)
	{
		if(ret == -1)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_4%>"));//<%IDS_Dynamo_4%>
		else if(ret == -2)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_5%>"));//<%IDS_Dynamo_5%>
		else if(ret == -3)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_6%>"));//<%IDS_Dynamo_6%>
		else if(ret == -4)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_7%>"));//<%IDS_Dynamo_7%>
		else if(ret == -5)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_8%>"));//<%IDS_Dynamo_8%>
		else if(ret == -6)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_9%>"));//<%IDS_Dynamo_9%>
		else if(ret == -7)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_10%>"));//<%IDS_Dynamo_10%>
		else if(ret == -8)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_11%>"));//<%IDS_Dynamo_11%>
		else
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_12%>"));//<%IDS_Dynamo_12%>

		goto w;
	}

	ptmp = psnval;
	ptmpnext = NULL;
	while(ptmp)
	{
		switch(count)
		{
		case 1:
			switch(ptmp->sv_type)
			{
			case ASN1_INT:
			case ASN1_COUNTER:
			case ASN1_GAUGE:
			case ASN1_TIMETICKS:
			case ASN1_COUNTER64:
			case ASN1_UINTEGER32:
				ifInOctets = ptmp->sv_val.sv_int;
				break;
			default:
				ifInOctets = 0;
				break;
			}
			break;
		case 2:
			switch(ptmp->sv_type)
			{
			case ASN1_INT:
			case ASN1_COUNTER:
			case ASN1_GAUGE:
			case ASN1_TIMETICKS:
			case ASN1_COUNTER64:
			case ASN1_UINTEGER32:
				ifOutOctets = ptmp->sv_val.sv_int;
				break;
			default:
				ifOutOctets = 0;
				break;
			}
			break;
		}
		count ++;
		ptmp = ptmp->next;
	}

	// computer the traffic 
	{
	char ciniFile[256] = {0}, 
		 cinifile[256] = {0};
	char cifIndex[256] = {0};
	sprintf(cinifile, "snmp_%s_%s.ini", server, strMonitorID);
	sprintf(ciniFile, "%s\\%s", custpath, cinifile);
	sprintf(cifIndex, "ifIndex_%ld", ifindex);

	long	ifTime = 0;
	Counter inOctets = 0, outOctets = 0;

	CTime curTime = CTime::GetCurrentTime();

	ifTime = DFN_GetPrivateProfileInt(cifIndex, "ifTime", -99, ciniFile);
	inOctets = DFN_GetPrivateProfileInt(cifIndex, "ifInOctets", -99, ciniFile);
	outOctets = DFN_GetPrivateProfileInt(cifIndex, "ifOutOctets", -99, ciniFile);

	if(ifTime == -99 || inOctets == -99 || outOctets == -99)
	{
		CString strSection = _T("");
		strSection.Format("ifIndex_%ld", ifindex);

		curTime = CTime::GetCurrentTime();
		CString strMsg = _T("");
		strMsg.Format("%ld", curTime.GetTime());
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifTime", (LPCTSTR)strMsg, ciniFile);

		strMsg.Format("%ld", ifInOctets);
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifInOctets", (LPCTSTR)strMsg, ciniFile);
		strMsg.Format("%ld", ifOutOctets);
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifOutOctets", (LPCTSTR)strMsg, ciniFile);
		WriteLogFile(strMonitorID, "读配置文件失败");
	}
	else
	{
		float ifInOctetsRate = 0.0, ifOutOctetsRate = 0.0;
		Counter	InOctets = 0, OutOctets = 0;

		CTime bTime(ifTime);
		curTime = CTime::GetCurrentTime();
		CTimeSpan spanTime = curTime - bTime;
		long lInterval = spanTime.GetTotalSeconds();
		
		if(lInterval == 0) lInterval = 1;
		if(lInterval <= 12 * 60 * 60 && lInterval >= 0)
		{
			InOctets = (unsigned int)(ifInOctets - inOctets < 0 ? (COUNTER_MAX - inOctets + ifInOctets) : (ifInOctets - inOctets));
			//ifInOctetsRate = (float)InOctets / lInterval;
			//k
			ifInOctetsRate = (float)InOctets / lInterval/1024;

			OutOctets = (unsigned int)(ifOutOctets - outOctets < 0 ? (COUNTER_MAX - outOctets + ifOutOctets) : (ifOutOctets - outOctets));
			// wang peng /1024 =k
            //Edit By Kevin.Yang PM: 14:55 2004.10.21
            //Reason: 根据张鹏所提供的资料目前Cisio的MIF库中单位为KB,因此在
            //得到的数据后不再需要除以1024
			ifOutOctetsRate = (float)OutOctets / lInterval /1024;
			//ifOutOctetsRate = (float)OutOctets / lInterval;

			sprintf(szReturn, 
					"ifIndex=%ld$ifInOctetsRate=%.2f$ifOutOctetsRate=%.2f$",
					ifindex, 
					ifInOctetsRate * 8, 
					ifOutOctetsRate * 8);
		}
		else
		{
			CString strLog;
			strLog.Format("时间总秒数%d", lInterval);
//			WriteLogFile(strMonitorID, strLog);		
		}
//		WriteLogFile(strMonitorID, szReturn);
		//if(strlen(szReturn) == 0)
		//{
		//	printf("%d年%d月%d日 %d时%d分%d秒 \n%d年%d月%d日 %d时%d分%d秒 \n",
		//		curTime.GetYear(), curTime.GetMonth(), curTime.GetDay(), 
		//		curTime.GetHour(), curTime.GetMinute(), curTime.GetSecond(),
		//		bTime.GetYear(), bTime.GetMonth(), bTime.GetDay(),
		//		bTime.GetHour(), bTime.GetMinute(), bTime.GetSecond());
		//}
		char buff[256] = {0};
		memset(buff, 0, 256);
		ltoa(curTime.GetTime(), buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifTime", buff, ciniFile);
		memset(buff, 0, 256);
		ltoa(ifInOctets, buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifInOctets", buff, ciniFile);
		memset(buff, 0, 256);
		ltoa(ifOutOctets, buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifOutOctets", buff, ciniFile);
	}
	}

w:	ptmp = psnval;
	if(ptmp) ptmpnext = ptmp->next;
	while(ptmp)
	{
		free(ptmp);
		ptmp = ptmpnext;
		if(ptmp) ptmpnext = ptmp->next;
	}

	return !ret;
}
void DumpStackStak(HANDLE hLogFile, PEXCEPTION_POINTERS lpExcetion)
{
	STACKFRAME stackFrame;
#ifdef _X86_
	stackFrame.AddrPC.Offset = lpExcetion->ContextRecord->Eip;
	stackFrame.AddrPC.Mode = AddrModeFlat;
	stackFrame.AddrStack.Offset = lpExcetion->ContextRecord->Esp;
	stackFrame.AddrStack.Mode = AddrModeFlat;
	stackFrame.AddrFrame.Offset = lpExcetion->ContextRecord->Ebp;
	stackFrame.AddrFrame.Mode = AddrModeFlat;
#else
	stackFrame.AddrPC.Offset       = (DWORD)lpExcetion->ContextRecord->Fir ;
	stackFrame.AddrPC.Mode         = AddrModeFlat ;
	stackFrame.AddrReturn.Offset   = (DWORD)lpExcetion->ContextRecord->IntRa;
	stackFrame.AddrReturn.Mode     = AddrModeFlat ;
	stackFrame.AddrStack.Offset    = (DWORD)lpExcetion->ContextRecord->IntSp;
	stackFrame.AddrStack.Mode      = AddrModeFlat ;
	stackFrame.AddrFrame.Offset    = (DWORD)lpExcetion->ContextRecord->IntFp;
	stackFrame.AddrFrame.Mode      = AddrModeFlat ;
#endif

	//set up symbol engine
	DWORD dwOpts = SymGetOptions();
	SymSetOptions(dwOpts|SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
	SymInitialize(GetCurrentProcess(), NULL, TRUE);

#ifdef _WIN64
#define CH_MACHINE IMAGE_FILE_MACHINE_IA64
#else
#define CH_MACHINE IMAGE_FILE_MACHINE_I386
#endif

	WriteLogFile(hLogFile, "\r\n\r\nStack trace list:\r\n");
	do 
	{
		BOOL bRet = StackWalk(CH_MACHINE, GetCurrentProcess(), GetCurrentThread(), &stackFrame, lpExcetion->ContextRecord,
			(PREAD_PROCESS_MEMORY_ROUTINE)ReadProcessMemory, SymFunctionTableAccess, SymGetModuleBase, NULL);
		if (bRet == FALSE || stackFrame.AddrFrame.Offset == 0)
			break;

		DWORD dwModuleBase = SymGetModuleBase(GetCurrentProcess(), stackFrame.AddrPC.Offset);
		if (dwModuleBase == 0)
			break;

		//module name of call
		TCHAR szModuleName[MAX_PATH] = {0};
		GetModuleFileName((HMODULE)dwModuleBase, szModuleName, MAX_PATH);

		//funtion name
		DWORD dwDisp = 0;
		TCHAR szFuntionName[MAX_PATH+sizeof(IMAGEHLP_SYMBOL)] = {0};
		PIMAGEHLP_SYMBOL lpSymb = (PIMAGEHLP_SYMBOL)szFuntionName;
		lpSymb->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
		lpSymb->MaxNameLength = MAX_PATH;
		SymGetSymFromAddr(GetCurrentProcess(), stackFrame.AddrPC.Offset, &dwDisp, lpSymb);

		//line number and filename
		IMAGEHLP_LINE hlpLine;
		SymGetLineFromAddr(GetCurrentProcess(), (DWORD)stackFrame.AddrPC.Offset, &dwDisp, &hlpLine);
		WriteLogFile(hLogFile, "%s-%s %s::%d\r\n", lpSymb->Name, GetFilePart(szModuleName), hlpLine.FileName, hlpLine.LineNumber);
	} while (1);
}
void ExceptionHandler(unsigned int, PEXCEPTION_POINTERS lpCeption)
{
	//Get time
	SYSTEMTIME st;
	GetLocalTime(&st);
	TCHAR szTime[120] = {0};
	sprintf_s(szTime, 120, "%d-%d-%d-%d-%d-%d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);

	//Get current module name
	TCHAR* lpCurModuleName = _T("Current Module name");
	TCHAR szModuleName[MAX_PATH] = {0};
	if (GetModuleFileName(NULL, szModuleName, MAX_PATH) > 0)
		lpCurModuleName = GetFilePart(szModuleName);

	//Create log file
	TCHAR szFilePath[MAX_PATH] = {0};
	TCHAR szLogPath[MAX_PATH] = {0};
	GetCurrentDirectory(MAX_PATH, szFilePath);
	sprintf_s(szLogPath, MAX_PATH, "%s\\Exception-%s.log", szFilePath, szTime);

	HANDLE hLogFile = CreateFile(szLogPath, GENERIC_WRITE, 0, 0, 
		CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
	if (hLogFile == INVALID_HANDLE_VALUE)
		return;// EXCEPTION_CONTINUE_SEARCH;

	PEXCEPTION_RECORD Exception = lpCeption->ExceptionRecord;
	PCONTEXT          Context   = lpCeption->ContextRecord;
	TCHAR szCrashModuleName[MAX_PATH] = {0};
	TCHAR* lpCrashName = _T("Exception Process Name");
	MEMORY_BASIC_INFORMATION memInfo;
	// VirtualQuery can be used to get the allocation base associated with a
	// code address, which is the same as the ModuleHandle. This can be used
	// to get the filename of the module that the crash happened in.
	if (VirtualQuery((LPCVOID)Context->Eip, &memInfo, sizeof(memInfo)) && (GetModuleFileName((HMODULE)memInfo.AllocationBase, szCrashModuleName, MAX_PATH) > 0))
		lpCrashName = GetFilePart(szCrashModuleName);
	WriteLogFile(hLogFile, "%s caused %s(0x%08x) in module %s at %04x:%08x.\r\n",
		lpCurModuleName, GetExceptionDescription(Exception->ExceptionCode), Exception->ExceptionCode, lpCrashName, Context->SegCs, Context->Eip);

	//Write system info to logfile
	DumpSystemInformation(hLogFile, lpCurModuleName);

	// Print out the bytes of code at the instruction pointer. Since the
	// crash may have been caused by an instruction pointer that was bad,
	// this code needs to be wrapped in an exception handler, in case there
	// is no memory to read. If the dereferencing of code[] fails, the
	// exception handler will print '??'.
	WriteLogFile(hLogFile, _T("\r\n\r\nCode Start CS:EIP:\r\n"));
	BYTE * code = (BYTE *)Context->Eip;
	for (int codebyte = 0; codebyte < 16; codebyte++)
	{
		__try
		{
			WriteLogFile(hLogFile, _T("%02x "), code[codebyte]);
		}
		__except(EXCEPTION_EXECUTE_HANDLER)
		{
			WriteLogFile(hLogFile, _T("?? "));
		}
	}
	//Write Stack information to logfile
	DumpStackStak(hLogFile, lpCeption);
	//Write module of process information to logfile
	DumpModuleList(hLogFile);
	CloseHandle(hLogFile);
	
	//Create dump file
	sprintf_s(szLogPath, MAX_PATH, "%s\\Exception-%s.dmp", szFilePath, szTime);
	HANDLE hDumpFile = CreateFile(szLogPath, GENERIC_WRITE, 0, 0, 
		CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
	if (hDumpFile == INVALID_HANDLE_VALUE)
		return;// EXCEPTION_CONTINUE_SEARCH;
	
	MINIDUMP_EXCEPTION_INFORMATION eInfo;
	eInfo.ThreadId = GetCurrentThreadId();
	eInfo.ExceptionPointers = lpCeption;
	eInfo.ClientPointers = FALSE;
	MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &eInfo, NULL, NULL);
	CloseHandle(hDumpFile);
}
Esempio n. 23
0
BOOL CLogFile::PutLog(LPCTSTR log_message)
{
	DWORD len = _tcslen(log_message) * sizeof(TCHAR);
	BOOL result = TRUE;

	EnterCriticalSection(&cs);
	if (file_type != LOGFILE_ONE_FILE) {
		BOOL write = FALSE;
		SYSTEMTIME st;

		GetLocalTime(&st);
		switch (file_type) {
		case LOGFILE_PER_YEAR:
			if (st.wYear != last_date.wYear)
				write = TRUE;
			break;
		case LOGFILE_PER_MONTH:
			if (st.wMonth != last_date.wMonth || st.wYear != last_date.wYear)
				write = TRUE;
			break;
		case LOGFILE_PER_DAY:
			if (st.wDay != last_date.wDay || st.wMonth != last_date.wMonth || st.wYear != last_date.wYear)
				write = TRUE;
			break;
		case LOGFILE_PER_HOUR:
			if (st.wHour != last_date.wHour || st.wDay != last_date.wDay || st.wMonth != last_date.wMonth || st.wYear != last_date.wYear)
				write = TRUE;
			break;
		case LOGFILE_PER_TENMIN:
			if (st.wMinute / 10 != last_date.wMinute / 10 || st.wHour != last_date.wHour || st.wDay != last_date.wDay || st.wMonth != last_date.wMonth || st.wYear != last_date.wYear)
				write = TRUE;
			break;
		}
		if (write)
			result = WriteLogData();
		last_date = st;
	}

	if (log_size + len >= max_log_size - 1)
		result = WriteLogData();
	if (result) {
		if (len >= max_log_size)
			result = WriteLogFile(log_message);
		else {
			if (log_data) {
				memcpy(log_data + log_size / sizeof(TCHAR), log_message, len);
				log_size += len;
				log_count++;

				if (logCountExpired() || logTimeExpired()) {
					result = WriteLogData();
					if (result == FALSE) {
						log_size -= len;
						log_count--;
					}
				}
			}
		}
	}
	LeaveCriticalSection(&cs);

	return result;
}
Esempio n. 24
0
int Encrypt_str_Encrypt (const char* szMacStr,char* szOutput)
{
	char szLogBuff [MAXCONTLEN] ;
	bzero (szLogBuff,sizeof(szLogBuff)) ;
	
	int fd = Encrypt_Socket_Open() ;
	if (fd==-1|| fd<0){
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] Open the socket failed...",__FILE__,__LINE__) ;
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
		Encrypt_Socket_Close(fd);
		return -1 ;
	}
	char szTmp [30] ;
	bzero (szTmp,sizeof(szTmp));	
	read_config_file ("./sysconfig.cfg","TIMEOUT_VAL",szTmp); 
	if (!strlen(szTmp))	
		sprintf (szTmp,"%d" ,3)  ;
	struct timeval tv;
	bzero (&tv ,sizeof(struct timeval)) ;
	tv.tv_sec = atoi (szTmp);	
	tv.tv_usec = atoi (szTmp);
	
	fd_set rset ,wset  ;
	FD_ZERO (&rset) ;
	FD_ZERO (&wset) ;
	
	//To set the readable and writable set .
	FD_SET (fd,&rset) ;
	FD_SET (fd,&wset) ;
	
	int iRet  = select (1024,NULL,&wset,NULL,&tv);
	if (iRet){
		//Here ,we will assemble the mac string,then send it.
		int ilen = strlen (szMacStr) ;	
		char sllen  [5] ;
		bzero (sllen,sizeof(sllen)) ;
		sprintf (sllen,"%d",ilen) ; //same as fj
		
		int ymod  = ilen % 256 ;
		ilen = ilen/ 256  ;
		char szSentMsg [MAXCONTLEN] ;
		bzero (szSentMsg,sizeof(szSentMsg)) ;
		char szReadMsg [MAXCONTLEN] ;	//To hold the response message .
		bzero (szReadMsg,sizeof(szReadMsg));
		
		sprintf (szSentMsg,"%x%x%s",ilen,ymod,szMacStr) ;		
		iRet  = write (fd,szSentMsg,strlen(szSentMsg)) ;
		if (iRet== strlen(szSentMsg)) {
			bzero (szLogBuff,sizeof(szLogBuff));
			sprintf (szLogBuff,"Send the request msg to Encrypt Successfully...") ;
			WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
			WriteLogFileInHex_Ex (&szSentMsg,__SYS_TYPE_LOGFILE_RAW__) ;	
		} else{	//Can not send data totally.
			bzero (szLogBuff,sizeof(szLogBuff)) ;
			sprintf (szLogBuff,"[%s-line:%d] Send the request msg to Encrypt Failed,pls chck your system...",__FILE__,__LINE__) ;
			WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
			WriteLogFileInHex_Ex (szSentMsg,__SYS_TYPE_LOGFILE_RAW__) ;
			Encrypt_Socket_Close(fd) ;
			strncpy (szOutput,"-1",2);
			return  -1 ;	
		}
		//Here , we will read the response msg from encryption mechine.
		iRet  = select (1024,&rset,NULL,NULL,&tv) ;
		if (iRet){
			if (FD_ISSET (fd,&rset)){
				iRet = read (fd,szReadMsg,2) ; //First 2 character are length of following
				if (iRet!=2){ //Can not read properlly.
				 	bzero (szLogBuff,sizeof(szLogBuff)) ;
					sprintf (szLogBuff,"[%s-line:%d] can not read length,pls chck your sys...",__FILE__,__LINE__) ;
					WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
					WriteLogFileInHex_Ex (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
					strncpy (szOutput,"-1",sizeof("-1")) ; //The Value of executation.
					Encrypt_Socket_Close(fd) ;
					return -1; 
				}
				ilen = CharToInt(szReadMsg[0])*256+CharToInt(szReadMsg[1]) ;
				bzero (szReadMsg,sizeof(szReadMsg)) ;
				iRet = read (fd,szReadMsg,ilen);	
				if (iRet!= ilen) {
					bzero (szLogBuff,sizeof(szLogBuff)) ;
					sprintf (szLogBuff,"[%s-line:%d] Read The following data error,pls check your system...",__FILE__,__LINE__) ;
					
					WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
					WriteLogFileInHex_Ex(szReadMsg,__SYS_TYPE_LOGFILE_RAW__) ;
					Encrypt_Socket_Close(fd) ;
					strncpy (szOutput,"-1",sizeof("-1")) ;
					return -1; 	
				}
				char sResCode  [3] ;
				bzero (sResCode,sizeof(sResCode)) ;//________________________
				strncpy (sResCode,szReadMsg+2,2) ;//|_0_|_1_|_2_|_3_|_4_|_5_|
				if (strcmp ("00",sResCode)==0){
					bzero (szLogBuff,sizeof(szLogBuff)) ;
					if (strlen(szReadMsg)==4) {
						sprintf (szLogBuff,"Send the reponse to server...") ;
						strncpy (szOutput,"0",1) ;
						WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
					}else {
						sprintf (szLogBuff,"send the Response message to server...") ;
						strncpy (szOutput,szReadMsg+4,strlen(szReadMsg)-4) ;
						WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__) ;
						WriteLogFile (szReadMsg+4,__SYS_TYPE_LOGFILE_RAW__) ;
					}
				}else{
					strncpy (szOutput,"-1",sizeof("-1"));
					Encrypt_Socket_Close(fd) ;
					return  -1 ;
				}	
			}
		}else if (iRet==-1){
			bzero (szLogBuff,sizeof(szLogBuff)) ;
			sprintf (szLogBuff,"[%s-line:%d] select() Exceptions occur,pls check your system...",__FILE__,__LINE__) ;
			WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
			Encrypt_Socket_Close(fd);
			strncpy (szOutput,"-1",sizeof("-1"));
			return  -1; 
		}else{
			bzero (szLogBuff,sizeof(szLogBuff)) ;
			sprintf (szLogBuff,"[%s-line:%d] Timeout Exceptions occur,pls check your system...",__FILE__,__LINE__) ;
			WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
			Encrypt_Socket_Close(fd);
			strncpy (szOutput,"-1",sizeof("-1")) ;
			return -1 ;
		}
	} else if (iRet==-1){
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] Select() exceptions occur...",__FILE__,__LINE__);	
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
		Encrypt_Socket_Close(fd)  ;
		strncpy (szOutput,"-1",sizeof("-1")) ;
		return -1 ;	
	} else {
		bzero (szLogBuff,sizeof(szLogBuff)) ;
		sprintf (szLogBuff,"[%s-line:%d] Select() timeout occur...",__FILE__,__LINE__);	
		WriteLogFile (szLogBuff,__SYS_TYPE_LOGFILE_RAW__);
		Encrypt_Socket_Close(fd)  ;
		strncpy (szOutput,"-1",sizeof("-1")) ;
		return -1 ;	
	}	
	
	return 0 ;
}
Esempio n. 25
0
/****************************************************************************
   FUNCTION: NPLogonNotify

   PURPOSE:  This entry point is called when a user logs on.  If the user
             authentication fails here, the user will still be logged on
             to the local machine.

*******************************************************************************/
DWORD
WINAPI
NPLogonNotify (
              PLUID               lpLogonId,
              LPCWSTR             lpAuthentInfoType,
              LPVOID              lpAuthentInfo,
              LPCWSTR             lpPreviousAuthentInfoType,
              LPVOID              lpPreviousAuthentInfo,
              LPWSTR              lpStationName,
              LPVOID              StationHandle,
              LPWSTR              *lpLogonScript
              )
{
   PMSV1_0_INTERACTIVE_LOGON pAuthInfo;

   #ifdef DEBUG
   TCHAR szBuf[1024];

   // For debugging purposes only
   MessageBeep(0xFFFFFFFF);

   //
   // Write out some information about the logon attempt
   //
   wsprintf(szBuf, L"lpAuthentInfoType=%s lpStationName=%s\r\n",
            lpAuthentInfoType, lpStationName);

   WriteLogFile(szBuf);
   #endif


   //
   // If the primary authenticator is not MSV1_0, return success.
   // Why? Because this is the only auth info structure that we
   // understand and we don't want to interact with other types.
   //
   if ( lstrcmpiW (MSV1_0_AUTH_TYPE, lpAuthentInfoType) )
   {

      #ifdef DEBUG
      wsprintf(szBuf, L"Authenticator is not MSV1_0 - Returning.\n");

      WriteLogFile(szBuf);
      #endif

      SetLastError(NO_ERROR);
      return NO_ERROR;
   }

   //
   // Do something with the authentication information
   //
   pAuthInfo = (PMSV1_0_INTERACTIVE_LOGON) lpAuthentInfo;

   #ifdef DEBUG
   wsprintf(szBuf, L"LogonDomain=%s User=%s\r\n",
            pAuthInfo->LogonDomainName.Buffer,
            pAuthInfo->UserName.Buffer);

   WriteLogFile(szBuf);
   #endif

   //
   // Let's utilize the logon script capability to display
   // our logon information
   //

   // The Caller MUST free this memory
   *lpLogonScript = LocalAlloc(LPTR,1024);

   #ifdef DEBUG
   wsprintf(*lpLogonScript,L"notepad %s",LOGFILE);
   #endif

   return NO_ERROR;
}
Esempio n. 26
0
/*
 *	函数介绍:安装服务函数
 *  输入参数:strServiceName为在服务控制台中显示的名称
 *  输出参数:无
 *  返回值:服务启动正确返回TRUE,否则返回FALSE
 */
BOOL InstallService(CString strServiceName) 
{ 
    DWORD			dwOldCheckPoint; 
    DWORD			dwStartTickCount;
    DWORD			dwWaitTime;
    SERVICE_STATUS	ssStatus; 

	SC_HANDLE		schService;
	SC_HANDLE		schSCManager;

	if((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL)
	{
		WriteLogFile("OpenSCManager Failed");
		return FALSE;
	}
    CString path = g_strRootPath + "\\cgi-bin\\AlertService.exe";
	if((schService = CreateService(schSCManager,"AlertService7", strServiceName, SERVICE_ALL_ACCESS,
                    SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START,
                    SERVICE_ERROR_IGNORE,path,NULL,NULL,NULL,NULL,NULL)) == NULL)
	{
		WriteLogFile("OpenService Failed");
		CloseServiceHandle(schSCManager);
		return FALSE;
	}

	if(!StartService(schService, 0,	NULL))
	{
		
		WriteLogFile("StartService Failed");

		CloseServiceHandle(schService);
		CloseServiceHandle(schSCManager);
		return FALSE;
	}
	else 
	{
	}

	// Check the status until the service is no longer start pending. 
 	if (!QueryServiceStatus(schService, &ssStatus))
	{
		CloseServiceHandle(schService);
		CloseServiceHandle(schSCManager);
		return FALSE;
	}

	// Save the tick count and initial checkpoint.
	dwStartTickCount = GetTickCount();
	dwOldCheckPoint = ssStatus.dwCheckPoint;

	while (ssStatus.dwCurrentState == SERVICE_START_PENDING) 
	{ 
		// Do not wait longer than the wait hint. A good interval is 
		// one tenth the wait hint, but no less than 1 second and no 
		// more than 10 seconds. 

		dwWaitTime = ssStatus.dwWaitHint / 10;

		if( dwWaitTime < 1000 )
			dwWaitTime = 1000;
		else if ( dwWaitTime > 10000 )
			dwWaitTime = 10000;

		Sleep( dwWaitTime );

		// Check the status again. 
		if (!QueryServiceStatus(schService,   // handle to service 
								&ssStatus) )  // address of structure
			break; 

		if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
		{
			// The service is making progress.

			dwStartTickCount = GetTickCount();
			dwOldCheckPoint = ssStatus.dwCheckPoint;
		}
		else
		{
			if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
			{
				// No progress made within the wait hint
				break;
			}
		}
	} 

	if (ssStatus.dwCurrentState == SERVICE_RUNNING) 
	{
		CloseServiceHandle(schService);
		CloseServiceHandle(schSCManager);
		return TRUE;
	}
	else 
	{ 
		CloseServiceHandle(schService); 
		CloseServiceHandle(schSCManager);
		return FALSE;
	} 

	return TRUE;
} 
Esempio n. 27
0
void main( int argc, char** argv)
{
	//struct Position Pos;
	int Ix;

	strcpy( ConfigFile, "config.dat");

	Parity = NoneParity;
	DataBits = 8;
	StopBits = 1;

	CalledByGuideFlag = No;
	KeepGoingFlag = No;
	ReadSlewFlag = No;
	StartScrollFlag = No;

	/* if '-k' and '-s' (after full init): slew to Ra, Dec in slew.dat and keep going, exiting when
	desired, writing slew_out.dat file;
	if '-k' (before full init): (no slew.dat), keep going until centered on init position, write
	slew_out.dat file and exit;
	if '-s': slew to Ra, Dec in slew.dat and exit, writing slew_out.dat file;
	if no '-k' and no '-s': write slew_out.dat file and exit;

	if -c, then use following string as configuration file name, ie scope.exe -c config.dat will
	result in config.dat being used

	if -x, then use following string as scroll file name, and execute scroll file upon program
	startup, ie scope.exe -x nan.scr	will cause nan.scr to be loaded and started */

	/* argv[0] is name of executing program */
	for( Ix = 1; Ix < argc; Ix++)
		if( argv[Ix][0] == '-')
			if( strcmpi( &argv[Ix][1], "GUIDE") == 0)
				CalledByGuideFlag = Yes;
			else if( argv[Ix][1] == 'k')
				KeepGoingFlag = Yes;
			else if( argv[Ix][1] == 's')
				ReadSlewFlag = Yes;
			else if( (argv[Ix][1] == 'c' || argv[Ix][1] == 'C') && Ix < argc-1)
				strcpy( ConfigFile, argv[Ix+1]);
			else if( (argv[Ix][1] == 'x' || argv[Ix][1] == 'X') && Ix < argc-1)
			{
				strcpy( ScrollFilename, argv[Ix+1]);
				StartScrollFlag = Yes;
			}

	InitCommonVars();
	ReadConfig();

	/*
		Pos.Ra = Pos.Dec = 0;
		applyCorrectionsFromDataFileCoordYearToEpochNow(&Pos);
		printf("\n%f %f %f %f %f %f %f %f", Pos.Precession.A*RadToArcsec, Pos.Precession.Z*RadToArcsec,
		Pos.Nutation.A*RadToArcsec, Pos.Nutation.Z*RadToArcsec, Pos.AnnualAberration.A*RadToArcsec,
		Pos.AnnualAberration.Z*RadToArcsec, Pos.Ra*RadToArcsec, Pos.Dec*RadToArcsec);
		ContMsgRoutine();
	*/
	/*
		HsRecFile = fopen( HsRecFilename, "w");
		if( HsRecFile == NULL)
			BadExit( strcat( "Could not create ", HsRecFilename));
		HsRecIx = 0;
	*/

	/*
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		InitConvert();
		TestConvert();
		getch();
		TestAltAltAzTrack();
	*/


	if( DisplayOpeningMsgs)
	{
		printf( "\nCopyright BBAstroDesigns Inc. 2009\n");
		printf( "\nLIMITED WARRANTY This software is provided ``as is'' and any express or");
		printf( "\nimplied warranties, including, but not limited to, the implied warranties");
		printf( "\nof merchantability and fitness for a particular purpose are disclaimed.");
		printf( "\nIn no event shall BBAstroDesigns be liable for any direct, indirect,");
		printf( "\nincidental, special, exemplary, nor consequential damages (including, but");
		printf( "\nnot limited to, procurement of substitute goods or services, loss of use,");
		printf( "\ndate, or profits, or business interruption) however caused and on any");
		printf( "\ntheory of liability, whether in contract, strict liability, or tort");
		printf( "\n(including negligence or otherwise) arising in any way out of the use of");
		printf( "\nthis software, even if advised of the possibility of such damage.\n");
		printf( "\nThis software licensed under the GNU GENERAL PUBLIC LICENSE. You may");
		printf( "\ndistribute this software per the GNU GPL. See the enclosed gpl.txt.\n\n");
		ContMsgRoutine();
	}

	if( DisplayOpeningMsgs)
		printf( "\ncalled by guide: %d, keep_going: %d, read slew.dat file %d",
		CalledByGuideFlag, KeepGoingFlag, ReadSlewFlag);

	/* if( strcmpi( TestString, "TestSerial") == 0)
	{
		InitSerial( EncoderComPort, EncoderBaudRate, Parity, DataBits, StopBits);
		TestSerial( EncoderComPort);
		CloseSerial( EncoderComPort);
	} */
	/* else if( strcmpi( TestString, "TestVideo") == 0)
	{
		InitVideo( DisplayOpeningMsgs);
		TestVideo();
	} */
	/* else if( strcmpi( TestString, "TestATimes") == 0)
	{
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		TestTimes();
	} */
	/* else if( strcmpi( TestString, "TestParallelPort") == 0)
	{
		InitPPort();
		TestPPort();
		ClosePPort();
	} */
	/* else if( strcmpi( TestString, "TestRefract") == 0)
	{
		InitRefract();
		TestRefract();
	} */
	/* else if( strcmpi( TestString, "TestMouse") == 0)
	{
		TestMouse();
	} */
	/* else if( strcmpi( TestString, "TestEncoders") == 0)
	{
		InitSerial( EncoderComPort, EncoderBaudRate, Parity, DataBits, StopBits);
		InitEncoders();
		TestEncoders();
		CloseSerial( EncoderComPort);
	} */
	/* else if( strcmpi( TestString, "TestHandpad") == 0)
	{
		InitPPort();
		InitializeHandpad();
		TestHandpad();
		ClosePPort();
	} */
	/* else if( strcmpi( TestString, "TestConversion") == 0)
	{
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		InitConvert();
		TestConvert();
	} */
	/* else if( strcmpi( TestString, "TestAltOffset") == 0)
	{
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		InitConvert();
		TestAltOffset();
	} */
	/* else if( strcmpi( TestString, "TestIACA") == 0)
	{
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		TestIACA();
		InitIACA();
	} */
	/* else if( strcmpi( TestString, "WritePWMValues") == 0)
	{
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		InitVideo( DisplayOpeningMsgs);
		InitPPort();
		InitMotors();
		WritePWMValues();
		CloseSteppers();
		ClosePPort();
	}
	else */
	{
		if( strcmpi( TestString, "NoTest") != 0
		&& strcmpi( TestString, "PreloadGuidexx.dat") != 0
		&& strcmpi( TestString, "Track") != 0)
		{
			if( DisplayOpeningMsgs)
				printf( "\nsetting unrecognized TestString to 'NoTest'");
			strcpy( TestString, "NoTest");
		}
		InitSerial( EncoderComPort, EncoderBaudRate, Parity, DataBits, StopBits);
		InitEncoders();
		InitMouseControl();
		InitTimes( DisplayOpeningMsgs, Tz, DST, LongitudeDeg);
		InitVideo( DisplayOpeningMsgs);
		InitPPort();
		InitializeHandpad();
		InitMotors();
		InitConvert();
		InitRefract();
		InitPEC();
		InitGuide();
		if( strcmpi( TestString, "PreloadGuidexx.dat") == 0)
		{
			LoadGuideAlts();
			LoadGuideAzs();
		}
		InitIACA();
		InitLX200Input();
		InitHPEvent();
		if( !CalledByGuideFlag ||
		(CalledByGuideFlag && (KeepGoingFlag || ReadSlewFlag)))
		{
			InitKBEvent();
			if( ReadSlewFlag)
				InputEquatSlewDat();
			if( StartScrollFlag)
				LoadScrollFileFromFile();
			if( strcmpi( TestString, "Track") == 0)
				Start2MotorTrackWithDefaultValues();
			while( !QuitFlag)
			{
				SequentialTaskController();
				/* GrandTourFlag used to flag next object: set in ProcessHPEventsModeSwitch() */
				if( GrandTourLoaded && GrandTourFlag)
					ProcessGrandTour();
				else
					if( ScrollLoaded && ScrollFlag)
						ProcessScroll();
					else
						if( HPPolarAlignLoaded && HPPolarAlignFlag)
							ProcessHPPolarAlign();
						else
						{
							if( UseMouseFlag && ProcessMouseEvent())
								;
							else
								if( KeyStroke)
									ProcessKBEvents();
								else
									ProcessHPEvents();
						}
			}
			CloseKBEvent();
			if( DisplayOpeningMsgs)
			{
				AskAndWriteConfig();
				WriteLogFile();
			}
		}
		CloseSteppers();
		ClosePPort();
		CloseEncoderResetLogFile();
		CloseSerial( EncoderComPort);
		CloseSerial( LX200ComPort);
		if( CalledByGuideFlag)
			WriteAltazSlewOutFile();
		CloseMouseControl();
	}

	/*
		for( Ix = 0; Ix < HsRecSize; Ix++)
			fprintf( HsRecFile, "%8ld   %8ld\n", HsRec[Ix].A, HsRec[Ix].Z);
		// first position is index 0
		fprintf( HsRecFile, " last entry in circular queue at position %d", HsRecIx);
		fclose( HsRecFile);
	*/
}