Beispiel #1
0
/*--------------------------------------------------------------------------*/
void SLPDCmdStopService()
/*--------------------------------------------------------------------------*/
{
	 SC_HANDLE schService; 
	 SC_HANDLE schSCManager; 

	 schSCManager = OpenSCManager(
	 									  NULL,                   /* machine (NULL == local)    */
	 									  NULL,                   /* database (NULL == default) */
	 									  SC_MANAGER_ALL_ACCESS); /* access required    		  */
	 if(schSCManager)
	 {
	 	  schService = OpenService(schSCManager, G_SERVICENAME, SERVICE_ALL_ACCESS); 

	 	  if(schService)
	 	  {
	 			SLPDHlpStopService(schService);
	 			CloseServiceHandle(schService); 
	 	  }
	 	  else
	 	  {
	 			printf("OpenService failed - %s\n", GetLastErrorText(szErr,256)); 
	 	  }
	 	  CloseServiceHandle(schSCManager); 
	 }
	 else
	 {
	 	  printf("OpenSCManager failed - %s\n", GetLastErrorText(szErr,256)); 
	 }
}
//停止服务
BOOL wx_service::StopService()
{
	char szError[512]={0};
	bool bRet = false;
	bPause = true;
	hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

	if( hSCM)               //   如果打开SERVICE管理器成功   
	{   
		hService   =  ::OpenService(         //获取SERVICE控制句柄的API   
			hSCM,                         //SCM管理器句柄   
			szServiceName,                 //SERVICE内部名称,控制名称   
			SERVICE_ALL_ACCESS);         //打开的权限,删除就要全部权限

		if(hService){
			if(QueryServiceStatus(hService,   &status)){
				if ( status.dwCurrentState != SERVICE_STOPPED )
				{
					if( ControlService(hService,   SERVICE_CONTROL_STOP, &status) ){
						bRet = true;
					}else
						LogEvent( GetLastErrorText(szError, 512) );
				}
			}
		}else
			LogEvent( GetLastErrorText(szError, 512) );

		::CloseServiceHandle(hService);
		::CloseServiceHandle(hSCM);
	}else{
		LogEvent( GetLastErrorText(szError, 512) );
	}
	return bRet;
}
Beispiel #3
0
static int install_service()
{
    SC_HANDLE schService, schSCManager;
    char filename[_MAX_PATH+10];

    if (GetModuleFileName(NULL, filename, _MAX_PATH) == 0) {
        printf("Unable to install Mixmaster Service: %s\n", GetLastErrorText());
        return 1;
    }
    strcat(filename, " --run-svc");

    if (!(schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS))) {
        printf("OpenSCManager failed: %s\n", GetLastErrorText());
        return 1;
    }
    schService = CreateService(schSCManager, SVCNAME, SVCDISPLAYNAME,
                               SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
                               filename, NULL, NULL, NULL, NULL, NULL);

    if (schService) {
        printf("Mixmaster Service installed.\n");
        CloseServiceHandle(schService);
    } else {
        printf("CreateService failed: %s\n", GetLastErrorText());
    }

    CloseServiceHandle(schSCManager);
    return 0;
} /* install_service */
BOOL wx_service::Install()
{
	char szError[512]={0};
	bool bRet = false;
	//这里列出主要的两个函数,其它的可以在代码里找。
	//打开服务控制管理器

	hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	long ret = GetLastError();
	if(hSCM==NULL){
		LogEvent( GetLastErrorText(szError, 512) );
		return false;
	}

	//创建服务

	hService = ::CreateService(
		hSCM, szServiceName, szServiceName, // szServiceName  "TF-信帧APP服务监控"
		SERVICE_ALL_ACCESS, SERVICE_WIN32_SHARE_PROCESS,
		SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
		m_lpServicePathName, NULL, NULL, (""), NULL, NULL);
	if(hService)
		bRet = true;
	else
		LogEvent( GetLastErrorText(szError, 512) );

	::CloseServiceHandle(hService);

	::CloseServiceHandle(hSCM);

	return bRet;
}
Beispiel #5
0
void CmdRemoveService(LPCSTR name)
{
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;
    char        realName[512];

    sprintf(realName,"shibd_%s",name);

    schSCManager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
    if ( schSCManager )
    {
        schService = OpenService(schSCManager, realName, SERVICE_ALL_ACCESS);

        if (schService)
        {
            // try to stop the service
            if ( ControlService( schService, SERVICE_CONTROL_STOP, &ssStatus ) )
            {
                printf("Stopping shibd (%s).", name);
                Sleep( 1000 );

                while( QueryServiceStatus( schService, &ssStatus ) )
                {
                    if ( ssStatus.dwCurrentState == SERVICE_STOP_PENDING )
                    {
                        printf(".");
                        Sleep( 1000 );
                    }
                    else
                        break;
                }

                if ( ssStatus.dwCurrentState == SERVICE_STOPPED )
                    printf("\n%s stopped.\n", realName);
                else
                    printf("\n%s failed to stop.\n", realName);

            }

            // now remove the service
            if( DeleteService(schService) )
                printf("%s removed.\n", realName);
            else
                printf("DeleteService failed - %s\n", GetLastErrorText(szErr,256));


            CloseServiceHandle(schService);
        }
        else
            printf("OpenService failed - %s\n", GetLastErrorText(szErr,256));

        CloseServiceHandle(schSCManager);
    }
    else
        printf("OpenSCManager failed - %s\n", GetLastErrorText(szErr,256));
}
static int
CmdStartService (openvpn_service_type type)
{
  int ret = 1;
  SC_HANDLE svc_ctl_mgr;
  SC_HANDLE service;

  svc_ctl_mgr = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
  if (svc_ctl_mgr == NULL)
    {
      _tprintf (TEXT("OpenSCManager failed - %s\n"), GetLastErrorText ());
      return 1;
    }

  service = OpenService (svc_ctl_mgr, openvpn_service[type].name, SERVICE_ALL_ACCESS);
  if (service)
    {
      if (StartService (service, 0, NULL))
        {
          _tprintf (TEXT("Service Started\n"));
          ret = 0;
        }
      else
        _tprintf (TEXT("StartService failed - %s\n"), GetLastErrorText ());

      CloseServiceHandle(service);
    }
  else
    {
      _tprintf (TEXT("OpenService failed - %s\n"), GetLastErrorText ());
    }

  CloseServiceHandle(svc_ctl_mgr);
  return ret;
}
Beispiel #7
0
///////////////////////////////////////////////////////////////////
//
//  The following code handles service installation and removal
//
//
//  FUNCTION: CmdInstallService()
//
//  PURPOSE: Installs the service and Starts it
//
//  PARAMETERS:
//    argc: number of arguments
//	argv: all of the arguments including the program's name
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//
void CmdInstallService(int argc, char **argv) {
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    TCHAR szPath[512];

    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ) {
        _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(SZSERVICEDISPLAYNAME), GetLastErrorText(szErr, 256));
        return;
    }

    schSCManager = OpenSCManager(
                                NULL,                   // machine (NULL == local)
                                NULL,                   // database (NULL == default)
                                SC_MANAGER_ALL_ACCESS   // access required
                                );
    if ( schSCManager ) {
        schService = OpenService(schSCManager, TEXT(SZSERVICENAME), SERVICE_ALL_ACCESS);
        if ( !schService ) {
            schService = CreateService(
                                      schSCManager,               // SCManager database
                                      TEXT(SZSERVICENAME),        // name of service
                                      TEXT(SZSERVICEDISPLAYNAME), // name to display
                                      SERVICE_ALL_ACCESS,         // desired access
                                      SERVICE_WIN32_OWN_PROCESS,  // service type
                                      SERVICE_DEMAND_START,       // start type
                                      SERVICE_ERROR_NORMAL,       // error control type
                                      szPath,                     // service's binary
                                      NULL,                       // no load ordering group
                                      NULL,                       // no tag identifier
                                      TEXT(SZDEPENDENCIES),       // dependencies
                                      NULL,                       // LocalSystem account
                                      NULL);                      // no password
        } else {
            _tprintf(TEXT("%s already installed.\n"), TEXT(SZSERVICEDISPLAYNAME) );
        }
        if ( schService ) {
            if ( QueryServiceStatus( schService, &ssStatus ) ) {
                int rc;
                if ( ssStatus.dwCurrentState == SERVICE_STOPPED ) {
                    rc = StartService(schService, argc-1, argv+1);
                }


                if ( rc != 0 )
                    _tprintf(TEXT("%s started.\n"), TEXT(SZSERVICEDISPLAYNAME) );
            }

            CloseServiceHandle(schService);
        } else {
            _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256));
        }

        CloseServiceHandle(schSCManager);
    } else
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));


}
BOOL wx_service::Uninstall()
{
	char szError[512]={0};
	bool bRet = false;
	long times = 0;
	hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if( hSCM)               //   如果打开SERVICE管理器成功   
	{   
		hService   =  ::OpenService(         //获取SERVICE控制句柄的API   
			hSCM,                         //SCM管理器句柄   
			szServiceName,                 //SERVICE内部名称,控制名称   
			SERVICE_ALL_ACCESS);         //打开的权限,删除就要全部权限

		if(hService){
			if( ControlService(hService,   SERVICE_CONTROL_STOP, &status) ){
				//直接向SERVICE发STOP命令,如果能够执行到这里,说明SERVICE正运行   
				//那就需要停止程序执行后才能删除   
				Sleep(3000)   ;   //等3秒使系统有时间执行STOP命令  
				while( QueryServiceStatus(hService,   &status)   )   {
					times ++;
					if(status.dwCurrentState   ==   SERVICE_STOP_PENDING)   
					{         //如果SERVICE还正在执行(PENDING)停止任务   
						Sleep(1000)   ;         //那就等1秒钟后再检查SERVICE是否停止OK  
					}else {
						break ; //STOP命令处理完毕,跳出循环   
					}
					if(times>10)
						break;// time out 

				}//循环检查SERVICE状态结束   
				
			}else
				LogEvent( GetLastErrorText(szError, 512) );

			if(status.dwCurrentState   !=   SERVICE_STOPPED)  
			{          //如果SERVICE接受STOP命令后还没有STOPPED   
				LogEvent( GetLastErrorText(szError, 512) );
				;         //那就返回FALSE报错,用GetLastError取错误代码   
			}else{
				//删除指令在这里   
				if( ::DeleteService(hService))
					bRet = true;
				else
					LogEvent( GetLastErrorText(szError, 512) );
			} 

		}//if(hService)
		else
			LogEvent( GetLastErrorText(szError, 512) );
		

		::CloseServiceHandle(hService);
		::CloseServiceHandle(hSCM);
	}else{
		LogEvent( GetLastErrorText(szError, 512) );
	}
	return bRet;
}
Beispiel #9
0
//
//  FUNCTION: CmdRemoveService()
//
//  PURPOSE: Stops and removes the service
//
//  PARAMETERS:
//    none
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//
void CmdRemoveService()
{
   SC_HANDLE   schService;
   SC_HANDLE   schSCManager;

   schSCManager = OpenSCManager(
                               NULL,                   // machine (NULL == local)
                               NULL,                   // database (NULL == default)
                               SC_MANAGER_CONNECT   // access required
                               );
   if ( schSCManager )
   {
      schService = OpenService(schSCManager, TEXT(SZSERVICENAME), DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);

      if (schService)
      {
         // try to stop the service
         if ( ControlService( schService, SERVICE_CONTROL_STOP, &ssStatus ) )
         {
            _tprintf(TEXT("Stopping %s."), TEXT(SZSERVICEDISPLAYNAME));
            Sleep( 1000 );

            while ( QueryServiceStatus( schService, &ssStatus ) )
            {
               if ( ssStatus.dwCurrentState == SERVICE_STOP_PENDING )
               {
                  _tprintf(TEXT("."));
                  Sleep( 1000 );
               }
               else
                  break;
            }

            if ( ssStatus.dwCurrentState == SERVICE_STOPPED )
               _tprintf(TEXT("\n%s stopped.\n"), TEXT(SZSERVICEDISPLAYNAME) );
            else
               _tprintf(TEXT("\n%s failed to stop.\n"), TEXT(SZSERVICEDISPLAYNAME) );

         }

         // now remove the service
         if ( DeleteService(schService) )
            _tprintf(TEXT("%s removed.\n"), TEXT(SZSERVICEDISPLAYNAME) );
         else
            _tprintf(TEXT("DeleteService failed - %s\n"), GetLastErrorText(szErr,256));


         CloseServiceHandle(schService);
      }
      else
         _tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr,256));

      CloseServiceHandle(schSCManager);
   }
   else
      _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
}
Beispiel #10
0
//
//  FUNCTION: CmdInstallService()
//
//  PURPOSE: Installs the service
//
//  PARAMETERS:
//    none
//
//  RETURN VALUE:
//    0 if success
//
//  COMMENTS:
//
int CmdInstallService()
{
   SC_HANDLE   schService;
   SC_HANDLE   schSCManager;

   TCHAR szPath[512];

   int ret = 0;

   if ( GetModuleFileName( NULL, szPath, 512 ) == 0 )
   {
      _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(SZSERVICEDISPLAYNAME), GetLastErrorText(szErr, 256));
      return 1;
   }

   schSCManager = OpenSCManager(
                               NULL,                   // machine (NULL == local)
                               NULL,                   // database (NULL == default)
                               SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE  // access required
                               );
   if ( schSCManager )
   {
      schService = CreateService(
                                schSCManager,               // SCManager database
                                TEXT(SZSERVICENAME),        // name of service
                                TEXT(SZSERVICEDISPLAYNAME), // name to display
                                SERVICE_QUERY_STATUS,         // desired access
                                SERVICE_WIN32_OWN_PROCESS,  // service type
            SERVICE_DEMAND_START,        // start type -- alternative: SERVICE_AUTO_START
                                SERVICE_ERROR_NORMAL,       // error control type
                                szPath,                     // service's binary
                                NULL,                       // no load ordering group
                                NULL,                       // no tag identifier
                                NULL, // TEXT(SZDEPENDENCIES),       // dependencies
                                NULL,                       // LocalSystem account
                                NULL);                      // no password

      if ( schService )
      {
         _tprintf(TEXT("%s installed.\n"), TEXT(SZSERVICEDISPLAYNAME) );
         CloseServiceHandle(schService);
      }
      else
      {
         _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256));
    ret = 1;
      }

      CloseServiceHandle(schSCManager);
   }
   else
     {
      _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
       ret = 1;
     }
   return ret;
}
Beispiel #11
0
//	PURPOSE:  Stops and removes the service
void CNTService::CmdRemoveService()
{
	char szErr[256];

	ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Removing Service.");

	SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if ( !schSCManager )
	{
		ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Remove OpenSCManager failed", GetLastErrorText(szErr, sizeof(szErr)));
		return;
	}

	// Try to obtain the handle of this service
	char szInternalName[MAX_PATH];
	sprintf(szInternalName, GRAY_TITLE " - %s", g_Serv.GetName());

	SC_HANDLE schService = OpenService(schSCManager, szInternalName, SERVICE_ALL_ACCESS);
	if ( !schService )
	{
		ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Remove OpenService failed", GetLastErrorText(szErr, sizeof(szErr)));

		CloseServiceHandle(schSCManager);
		return;
	}

	// Check to see if the service is started, if so try to stop it.
	if ( ControlService(schService, SERVICE_CONTROL_STOP, &m_sStatus) )
	{
		ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Stopping");

		Sleep(1000);
		while ( QueryServiceStatus(schService, &m_sStatus) )	// wait the service to stop
		{
			if ( m_sStatus.dwCurrentState == SERVICE_STOP_PENDING )
				Sleep(1000);
			else
				break;
		}

		if (m_sStatus.dwCurrentState == SERVICE_STOPPED)
			ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Stopped");
		else
			ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Failed to Stop");
	}

	// Remove the service
	if ( DeleteService(schService) )
		ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Removed OK");
	else
		ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Remove Fail", GetLastErrorText(szErr, sizeof(szErr)));

	CloseServiceHandle(schService);
	CloseServiceHandle(schSCManager);
}
Beispiel #12
0
static void DoSetPriority(DWORD priority)
{
    LVITEMW          lvitem;
    ULONG            Index, Count;
    DWORD            dwProcessId;
    HANDLE           hProcess;
    WCHAR            wstrErrorText[256];

    WCHAR    wszWarnMsg[255];
    WCHAR    wszWarnTitle[255];
    WCHAR    wszUnable2Change[255];

    LoadStringW(hInst, IDS_PRIORITY_CHANGE_MESSAGE, wszWarnMsg, sizeof(wszWarnMsg)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_WARNING_TITLE, wszWarnTitle, sizeof(wszWarnTitle)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_PRIORITY_UNABLE2CHANGE, wszUnable2Change, sizeof(wszUnable2Change)/sizeof(WCHAR));

    Count = SendMessageW(hProcessPageListCtrl, LVM_GETITEMCOUNT, 0, 0);
    for (Index=0; Index<Count; Index++)
    {
        lvitem.mask = LVIF_STATE;
        lvitem.stateMask = LVIS_SELECTED;
        lvitem.iItem = Index;
        lvitem.iSubItem = 0;

        SendMessageW(hProcessPageListCtrl, LVM_GETITEMW, 0, (LPARAM)&lvitem);

        if (lvitem.state & LVIS_SELECTED)
            break;
    }

    Count = SendMessageW(hProcessPageListCtrl, LVM_GETSELECTEDCOUNT, 0, 0);
    dwProcessId = PerfDataGetProcessId(Index);
    if ((Count != 1) || (dwProcessId == 0))
        return;

    if (MessageBoxW(hMainWnd, wszWarnMsg, wszWarnTitle, MB_YESNO|MB_ICONWARNING) != IDYES)
        return;

    hProcess = OpenProcess(PROCESS_SET_INFORMATION, FALSE, dwProcessId);

    if (!hProcess)
    {
        GetLastErrorText(wstrErrorText, sizeof(wstrErrorText)/sizeof(WCHAR));
        MessageBoxW(hMainWnd, wstrErrorText, wszUnable2Change, MB_OK|MB_ICONSTOP);
        return;
    }

    if (!SetPriorityClass(hProcess, priority))
    {
        GetLastErrorText(wstrErrorText, sizeof(wstrErrorText)/sizeof(WCHAR));
        MessageBoxW(hMainWnd, wstrErrorText, wszUnable2Change, MB_OK|MB_ICONSTOP);
    }

    CloseHandle(hProcess);
}
Beispiel #13
0
// 
//  FUNCTION: CmdInstallService() 
// 
//  PURPOSE: Installs the service 
// 
//  PARAMETERS: 
//    none 
// 
//  RETURN VALUE: 
//    none 
// 
//  COMMENTS: 
// 
void CmdInstallService() 
{ 
    SC_HANDLE   schService; 
    SC_HANDLE   schSCManager; 
 
    TCHAR szPath[512]; 
 
    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ) 
    { 
        _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(SZSERVICEDISPLAYNAME), GetLastErrorText(szErr, 256)); 
        return; 
    } 
 
    schSCManager = OpenSCManager( 
                        NULL,                   // machine (NULL == local) 
                        NULL,                   // database (NULL == default) 
                        SC_MANAGER_ALL_ACCESS   // access required 
                        ); 
    if ( schSCManager ) 
    { 
        schService = CreateService( 
            schSCManager,               // SCManager database 
            TEXT(SZSERVICENAME),        // name of service 
            TEXT(SZSERVICEDISPLAYNAME), // name to display 
            SERVICE_ALL_ACCESS,         // desired access 
            SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS ,  // service type 
            SERVICE_AUTO_START,       // start type 
            SERVICE_ERROR_NORMAL,       // error control type 
            szPath,                     // service's binary 
            NULL,                       // no load ordering group 
            NULL,                       // no tag identifier 
            TEXT(SZDEPENDENCIES),       // dependencies 
            NULL,                       // LocalSystem account 
            NULL);                      // no password 
 
        if ( schService ) 
        {   Sleep(1001);
            StartService(schService,0,0);
                        SC_ACTION sa={SC_ACTION_RESTART,60000};
                        SERVICE_FAILURE_ACTIONS sfa={60,0,0,1,&sa};
            ChangeServiceConfig2(schService,SERVICE_CONFIG_FAILURE_ACTIONS,&sfa);
            _tprintf(TEXT("%s installed.\n"), TEXT(SZSERVICEDISPLAYNAME) ); 
            CloseServiceHandle(schService); 
        } 
        else 
        { 
            _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256)); 
        } 
 
        CloseServiceHandle(schSCManager); 
    } 
    else 
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256)); 
} 
Beispiel #14
0
//
//  FUNCTION: CmdInstallService()
//
//  PURPOSE: Installs the service
//
//  PARAMETERS:
//    none
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//
void CmdInstallService(char *Account,char *Password)
{
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    TCHAR szPath[512];

    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 )
    {
        _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(SZSERVICEDISPLAYNAME), GetLastErrorText(szErr, 256));
        return;
    }

    schSCManager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
    if ( schSCManager )
    {
        schService = CreateService(
            schSCManager,               // SCManager database
            TEXT(SZSERVICENAME),        // name of service
            TEXT(SZSERVICEDISPLAYNAME), // name to display
            SERVICE_ALL_ACCESS,         // desired access
            SERVICE_WIN32_OWN_PROCESS,  // service type
            SERVICE_DEMAND_START,       // start type
            SERVICE_ERROR_NORMAL,       // error control type
            szPath,                     // service's binary
            NULL,                       // no load ordering group
            NULL,                       // no tag identifier
            TEXT(SZDEPENDENCIES),       // dependencies
            Account,                    // Administrator account
            Password);                  // password

        if ( schService )
        {
            _tprintf(TEXT("%s installed.\n"), TEXT(SZSERVICEDISPLAYNAME) );
            CloseServiceHandle(schService);
			      AddEventSource();
            AddParametersRegistry();
        }
        else
        {
            _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256));
        }

        CloseServiceHandle(schSCManager);
    }
    else
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
}
Beispiel #15
0
static int
CmdInstallServices()
{
    SC_HANDLE service;
    SC_HANDLE svc_ctl_mgr;
    TCHAR path[512];
    int i, ret = _service_max;

    if (GetModuleFileName(NULL, path + 1, 510) == 0)
    {
        _tprintf(TEXT("Unable to install service - %s\n"), GetLastErrorText());
        return 1;
    }

    path[0] = TEXT('\"');
    _tcscat(path, TEXT("\""));

    svc_ctl_mgr = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
    if (svc_ctl_mgr == NULL)
    {
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText());
        return 1;
    }

    for (i = 0; i < _service_max; i++)
    {
        service = CreateService(svc_ctl_mgr,
                                openvpn_service[i].name,
                                openvpn_service[i].display_name,
                                SERVICE_QUERY_STATUS,
                                SERVICE_WIN32_SHARE_PROCESS,
                                openvpn_service[i].start_type,
                                SERVICE_ERROR_NORMAL,
                                path, NULL, NULL,
                                openvpn_service[i].dependencies,
                                NULL, NULL);
        if (service)
        {
            _tprintf(TEXT("%s installed.\n"), openvpn_service[i].display_name);
            CloseServiceHandle(service);
            --ret;
        }
        else
        {
            _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText());
        }
    }

    CloseServiceHandle(svc_ctl_mgr);
    return ret;
}
//
//  FUNCTION: CmdInstallService()
//
//  PURPOSE: Installs the service
//
//  PARAMETERS:
//    none
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//
void CmdInstallService()
{
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    TCHAR szPath[512];

    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 )
    {
        _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(szServiceDisplayName), GetLastErrorText(szErr, 256));
        return;
    }

    schSCManager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
    if ( schSCManager )
    {
        schService = CreateService(
            schSCManager,               // SCManager database
            TEXT(szServiceName),        // name of service
            TEXT(szServiceDisplayName), // name to display
            SERVICE_ALL_ACCESS,         // desired access
            SERVICE_WIN32_OWN_PROCESS,  // service type
            SERVICE_DEMAND_START,       // start type
            SERVICE_ERROR_NORMAL,       // error control type
            szPath,                     // service's binary
            NULL,                       // no load ordering group
            NULL,                       // no tag identifier
            TEXT(""),                   // dependencies
            NULL,                       // LocalSystem account
            NULL);                      // no password

        if ( schService )
        {
            _tprintf(TEXT("%s installed.\n"), TEXT(szServiceDisplayName) );
            CloseServiceHandle(schService);
        }
        else
        {
            _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256));
        }

        CloseServiceHandle(schSCManager);
    }
    else
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
}
Beispiel #17
0
static BOOL CmdRemoveService(void)
{
	SC_HANDLE schService = NULL;
	SC_HANDLE schSCManager = NULL;

	if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) != NULL) {
		schService = OpenService(schSCManager, szServiceName, SERVICE_ALL_ACCESS);

		if (schService != NULL) {
			if (ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus)) {
				_tprintf(_T("Stopping %s."), szServiceDispName);
				Sleep(1000);

				while (QueryServiceStatus(schService, &ssStatus)) {
					if (ssStatus.dwCurrentState == SERVICE_STOP_PENDING) {
						_tprintf(_T("."));
						Sleep(1000);
					} else
						break;
				}

				if (ssStatus.dwCurrentState == SERVICE_STOPPED)
					_tprintf(_T("\n%s stopped.\n"), szServiceDispName);
				else
					_tprintf(_T("\n%s failed to stop.\n"), szServiceDispName);

			}

			if (DeleteService(schService)) {
				_tprintf(_T("%s removed.\n"), szServiceDispName);
				CloseServiceHandle(schService);
				CloseServiceHandle(schSCManager);

				return TRUE;
			} else
				_tprintf(_T("DeleteService failed - %s\n"),
					 GetLastErrorText(szErr, CountOf(szErr)));

			CloseServiceHandle(schService);
		} else
			_tprintf(_T("OpenService failed - %s\n"),
				 GetLastErrorText(szErr, CountOf(szErr)));

		CloseServiceHandle(schSCManager);
	} else
		_tprintf(_T("OpenSCManager failed - %s\n"),
			 GetLastErrorText(szErr, CountOf(szErr)));

	return FALSE;
}
Beispiel #18
0
    void Acceptor::listen()
    {
        socket_t fd = SocketOps::createSocket();

        if(fd < 0)
        {
            LOG_PRINT(LogType_Fatal, "create socket failed:%s %s:%d",
                      GetLastErrorText().c_str(), __FUNCTION__, __LINE__);
            return;
        }

        if(!SocketOps::bindSocket(fd, &listenAddr_.getSockAddr()))
        {
            LOG_PRINT(LogType_Fatal, "bind socket failed:%s %s:%d",
                      GetLastErrorText().c_str(), __FUNCTION__, __LINE__);
            goto err;
        }

        if(!SocketOps::listen(fd))
        {
            LOG_PRINT(LogType_Fatal, "listen socket failed:%s %s:%d",
                      GetLastErrorText().c_str(), __FUNCTION__, __LINE__);
            goto err;
        }

        if(!SocketOps::setSocketNoneBlocking(fd))
        {
            LOG_PRINT(LogType_Fatal, "enable socket noneBlocking failed:%s %s:%d",
                      GetLastErrorText().c_str(), __FUNCTION__, __LINE__);
            goto err;
        }

        LOG_PRINT(LogType_Info, "Acceptor listen at ip:%s port:%u", listenAddr_.ip().c_str(),
                  listenAddr_.port());

        listenFd_ = fd;
        acceptChannelPtr_ = std::make_shared<Channel>(loop_, listenFd_);
        acceptChannelPtr_->setReadCallback(std::bind(&Acceptor::handleRead, this));
        acceptChannelPtr_->setOwner(shared_from_this());
        acceptChannelPtr_->enableReading();
        listenning_ = true;

        return;

err:
        SocketOps::closeSocket(fd);
        return;
    }
Beispiel #19
0
void ProcessPage_OnEndProcessTree(void)
{
    LVITEMW          lvitem;
    ULONG            Index;
    DWORD            dwProcessId;
    HANDLE           hProcess;
    WCHAR            wstrErrorText[256];

    load_message_strings();

    for (Index=0; Index<(ULONG)ListView_GetItemCount(hProcessPageListCtrl); Index++)
    {
        lvitem.mask = LVIF_STATE;
        lvitem.stateMask = LVIS_SELECTED;
        lvitem.iItem = Index;
        lvitem.iSubItem = 0;

        SendMessageW(hProcessPageListCtrl, LVM_GETITEMW, 0, (LPARAM) &lvitem);

        if (lvitem.state & LVIS_SELECTED)
            break;
    }

    dwProcessId = PerfDataGetProcessId(Index);

    if ((ListView_GetSelectedCount(hProcessPageListCtrl) != 1) || (dwProcessId == 0))
        return;

    if (MessageBoxW(hMainWnd, wszWarnMsg, wszWarnTitle, MB_YESNO|MB_ICONWARNING) != IDYES)
        return;

    hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessId);

    if (!hProcess)
    {
        GetLastErrorText(wstrErrorText, sizeof(wstrErrorText)/sizeof(WCHAR));
        MessageBoxW(hMainWnd, wstrErrorText,wszUnable2Terminate, MB_OK|MB_ICONSTOP);
        return;
    }

    if (!TerminateProcess(hProcess, 0))
    {
        GetLastErrorText(wstrErrorText, sizeof(wstrErrorText)/sizeof(WCHAR));
        MessageBoxW(hMainWnd, wstrErrorText,wszUnable2Terminate, MB_OK|MB_ICONSTOP);
    }

    CloseHandle(hProcess);
}
Beispiel #20
0
//
//  FUNCTION: CmdStartService()
//
//  PURPOSE: Start service if it exists
//
//  PARAMETERS:
//    argc: number of arguments
//	argv: arguments including program's name
//
//  RETURN VALUE:
//    TRUE: service exists and is started
//	FALSE: service doesn't exist
//
//  COMMENTS:
//
BOOL CmdStartService(int argc, char **argv) {
    BOOL isExist = FALSE;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    schSCManager = OpenSCManager(
                                NULL,                   // machine (NULL == local)
                                NULL,                   // database (NULL == default)
                                SC_MANAGER_ALL_ACCESS   // access required
                                );
    if ( schSCManager ) {
        schService = OpenService(schSCManager, TEXT(SZSERVICENAME), SERVICE_ALL_ACCESS);

        if ( schService ) {
            isExist = TRUE;
            if ( QueryServiceStatus( schService, &ssStatus ) ) {
                int rc;
                if ( ssStatus.dwCurrentState == SERVICE_STOPPED ) {
                    rc = StartService(schService, argc-1, argv+1);
                }


                if ( rc != 0 )
                    _tprintf(TEXT("%s started.\n"), TEXT(SZSERVICEDISPLAYNAME) );
            }
            CloseServiceHandle(schService);            
        }
        CloseServiceHandle(schSCManager);
    } else
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));

    return isExist;
}
Beispiel #21
0
//	PURPOSE:  Sets the current status of the service and reports it to the Service Control Manager
BOOL CNTService::SetServiceStatus( DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint )
{
	if ( dwCurrentState == SERVICE_START_PENDING )
		m_sStatus.dwControlsAccepted = 0;
	else
		m_sStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;

	m_sStatus.dwCurrentState = dwCurrentState;
	m_sStatus.dwWin32ExitCode = dwWin32ExitCode;
	m_sStatus.dwWaitHint = dwWaitHint;

	static DWORD dwCheckPoint = 1;
	if (( dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED))
		m_sStatus.dwCheckPoint = 0;
	else
		m_sStatus.dwCheckPoint = dwCheckPoint++;

	// Report the status of the service to the Service Control Manager
	BOOL fResult = ::SetServiceStatus(m_hStatusHandle, &m_sStatus);
	if ( !fResult && m_fIsNTService )
	{
		// if fResult is not 0, then an error occurred.  Throw this in the event log.
		char szErr[256];
		ReportEvent(EVENTLOG_ERROR_TYPE, 0, "SetServiceStatus", GetLastErrorText(szErr, sizeof(szErr)));
	}
	return fResult;
}
Beispiel #22
0
/*========================================================================
	Name:		连接到数据源.
	-----------------------------------------------------
	Params:		[lpszConnect]: 连接字符串, 包含连接信息.
				[lOptions]:	可选. 决定该方法是以同步还是异步的方式连接数据
						源. 可以是如下某个常量:
		[常量]					[说明] 
		----------------------------------
		adConnectUnspecified	(默认)同步方式打开连接. 
		adAsyncConnect			异步方式打开连接. Ado用 ConnectComplete 事
						件来通知已经完成连接. 
==========================================================================*/
BOOL CAdoConnection::Open(LPCTSTR lpszConnect, long lOptions)
{
	ASSERT(m_pConnection != NULL);
	ASSERT(AfxIsValidString(lpszConnect));
	
	if (strcmp(lpszConnect, _T("")) != 0)
	{
		m_strConnect = lpszConnect;
	}

	if (m_strConnect.IsEmpty())
	{
		ASSERT(FALSE);
		return FALSE;
	}

	if (IsOpen()) Close();

	try
	{
		// 连接数据库 ---------------------------------------------
		return (m_pConnection->Open(_bstr_t(LPCTSTR(m_strConnect)), "", "", lOptions) == S_OK);
	}
	catch (_com_error e)
	{
		TRACE(_T("Warning: 连接数据库发生异常. 错误信息: %s; 文件: %s; 行: %d\n"), e.ErrorMessage(), __FILE__, __LINE__);
		TRACE(_T("%s\r\n"), GetLastErrorText());
		return FALSE;
	} 
	catch (...)
	{
		TRACE(_T("Warning: 连接数据库时发生未知错误:"));
	}
	return FALSE;
}
DWORD
MsgToEventLog (DWORD flags, LPCTSTR format, ...)
{
  HANDLE hEventSource;
  TCHAR msg[2][256];
  DWORD error = 0;
  LPCTSTR err_msg = TEXT("");
  va_list arglist;

  if (flags & MSG_FLAGS_SYS_CODE)
    {
      error = GetLastError ();
      err_msg = GetLastErrorText ();
    }

  hEventSource = RegisterEventSource (NULL, APPNAME);
  if (hEventSource != NULL)
    {
      openvpn_sntprintf (msg[0], _countof (msg[0]),
                         TEXT("%s%s: %s"), APPNAME,
                         (flags & MSG_FLAGS_ERROR) ? TEXT(" error") : TEXT(""), err_msg);

      va_start (arglist, format);
      openvpn_vsntprintf (msg[1], _countof (msg[1]), format, arglist);
      va_end (arglist);

      const TCHAR *mesg[] = { msg[0], msg[1] };
      ReportEvent (hEventSource, flags & MSG_FLAGS_ERROR ?
                   EVENTLOG_ERROR_TYPE : EVENTLOG_INFORMATION_TYPE,
                   0, 0, NULL, 2, 0, mesg, NULL);
      DeregisterEventSource (hEventSource);
    }

  return error;
}
Beispiel #24
0
static VOID AddToMessageLog(LPCTSTR lpszMsg)
{
	HANDLE hEventSource = NULL;
	LPTSTR lpszStrings[2];
	TCHAR szMsg[512] = _T("");
	TCHAR szErrMsg[2048] = _T("");

	if (!bDebug) {
		dwErr = GetLastError();

		GetLastErrorText(szErr, CountOf(szErr));

		_stprintf(szMsg, _T("%s error: %d"), szServiceName, dwErr);
		_stprintf(szErrMsg, _T("{%s}: %s"), lpszMsg, szErr);

		lpszStrings[0] = szMsg;
		lpszStrings[1] = szErrMsg;

		if ((hEventSource = RegisterEventSource(NULL, szServiceName)) != NULL) {
			ReportEvent(hEventSource,	// handle of event source
				    EVENTLOG_ERROR_TYPE,	// event type
				    0,	// event category
				    0,	// event ID
				    NULL,	// current user's SID
				    2,	// strings in lpszStrings
				    0,	// no bytes of raw data
				    (const char **) lpszStrings,	// array of error strings
				    NULL);	// no raw data

			DeregisterEventSource(hEventSource);
		}
	}

}
Beispiel #25
0
void ProcessPage_OnSetAffinity(void)
{
    LV_ITEM            lvitem;
    ULONG            Index;
    DWORD            dwProcessId;
    TCHAR            strErrorText[260];

    for (Index=0; Index<(ULONG)ListView_GetItemCount(hProcessPageListCtrl); Index++) {
        memset(&lvitem, 0, sizeof(LV_ITEM));
        lvitem.mask = LVIF_STATE;
        lvitem.stateMask = LVIS_SELECTED;
        lvitem.iItem = Index;
        SendMessage(hProcessPageListCtrl, LVM_GETITEM, 0, (LPARAM) &lvitem);
        if (lvitem.state & LVIS_SELECTED)
            break;
    }
    dwProcessId = PerfDataGetProcessId(Index);
    if ((ListView_GetSelectedCount(hProcessPageListCtrl) != 1) || (dwProcessId == 0))
        return;
    hProcessAffinityHandle = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION, FALSE, dwProcessId);
    if (!hProcessAffinityHandle) {
        GetLastErrorText(strErrorText, 260);
        MessageBox(hMainWnd, strErrorText, _T("Unable to Access or Set Process Affinity"), MB_OK|MB_ICONSTOP);
        return;
    }
    DialogBox(hInst, MAKEINTRESOURCE(IDD_AFFINITY_DIALOG), hMainWnd, AffinityDialogWndProc);
    if (hProcessAffinityHandle)    {
        CloseHandle(hProcessAffinityHandle);
        hProcessAffinityHandle = NULL;
    }
}
Beispiel #26
0
void Exec::Execute(tstring const &folder, FileEvent *fileEvent, vector<HANDLE> &handles)
{
	using ch = tstring::value_type;
	tstring c = Format($("cmd /c %s"), ReplaceAllTokens(mCommand, fileEvent).c_str());
	ptr<ch> cmd(new ch[c.size() + 1]);
	memcpy(cmd.get(), c.c_str(), c.size() + 1);
	STARTUPINFO si = { 0 };
	PROCESS_INFORMATION pi = { 0 };
	si.cb = sizeof(si);
	ansi_printf($("%s..."), c.c_str());
	if (!CreateProcess(NULL, cmd.get(), NULL, NULL, TRUE, 0, NULL, folder.c_str(), &si, &pi))
	{
		error($("error: %s\n"), GetLastErrorText().c_str());
		return;
	}
	else
	{
		handles.push_back(pi.hProcess);
		if (!mAsync)
		{
			WaitForSingleObject(pi.hProcess, INFINITE);
			ansi_printf($("complete\n"), mCommand.c_str());
		}
		else
		{
			ansi_printf($("spawned\n"));
		}
	}
}
void log(LPCTSTR format, ...)
{
	char szError[512]={0};
	time_t t=0;  
	char *pTime = 0;

	// format msg 
	char buf[4096]={0}, *p=buf;
	va_list args;
	va_start(args, format);
	p += _vsnprintf(p, sizeof buf - 1, format, args);
	va_end(args);
	// while ( p > buf && isspace(p[-1]) )    *--p = '\0';
	*p++ = '\n';
	*p++ = '\0';


	// open  log file
	FILE *fp = fopen( logFilePath, "a+");
	if( fp == 0){
		LogEvent( "fopen Error : ",  GetLastErrorText(szError, 512) );
		return ;
	}

	time(&t);  
	pTime = asctime(localtime(&t));
	pTime[strlen(pTime)-1] = '\0';
	fprintf( fp, "[%s] %s ", pTime, buf);
	fclose(fp);

}
Beispiel #28
0
int CmdStopService()
{
  int ret = 0;

  SC_HANDLE schSCManager;
  SC_HANDLE schService;

  SERVICE_STATUS ServiceStatus;

    // Open a handle to the SC Manager database.
    schSCManager = OpenSCManager(
       NULL,                    // local machine
       NULL,                    // ServicesActive database
       SC_MANAGER_ALL_ACCESS);  // full access rights

    if (NULL == schSCManager) {
       _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
       ret = 1;
    }

    schService = OpenService(
        schSCManager,          // SCM database
        SZSERVICENAME,         // service name
        SERVICE_ALL_ACCESS);

    if (schService == NULL) {
      _tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr,256));
       ret = 1;
    }

    if (!ControlService(
            schService,  // handle to service
            SERVICE_CONTROL_STOP,           // number of arguments
            &ServiceStatus) )
    {
      _tprintf(TEXT("ControlServicefailed - %s\n"), GetLastErrorText(szErr,256));
       ret = 1;
    }
    else
   {
      _tprintf(TEXT("Service Stopped\n"));
       ret = 0;
   }
    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);
    return ret;
}
Beispiel #29
0
static void DoSetPriority(DWORD priority)
{
    LVITEM            lvitem;
    ULONG            Index;
    DWORD            dwProcessId;
    HANDLE            hProcess;
    TCHAR            strErrorText[260];

    for (Index=0; Index<(ULONG)ListView_GetItemCount(hProcessPageListCtrl); Index++)
    {
        lvitem.mask = LVIF_STATE;
        lvitem.stateMask = LVIS_SELECTED;
        lvitem.iItem = Index;
        lvitem.iSubItem = 0;

        SendMessage(hProcessPageListCtrl, LVM_GETITEM, 0, (LPARAM)&lvitem);

        if (lvitem.state & LVIS_SELECTED)
            break;
    }

    dwProcessId = PerfDataGetProcessId(Index);

    if ((ListView_GetSelectedCount(hProcessPageListCtrl) != 1) || (dwProcessId == 0))
        return;

    if (MessageBox(hMainWnd, _T("WARNING: Changing the priority class of this process may\ncause undesired results including system instability. Are you\nsure you want to change the priority class?"), _T("Task Manager Warning"), MB_YESNO|MB_ICONWARNING) != IDYES)
        return;

    hProcess = OpenProcess(PROCESS_SET_INFORMATION, FALSE, dwProcessId);

    if (!hProcess)
    {
        GetLastErrorText(strErrorText, 260);
        MessageBox(hMainWnd, strErrorText, _T("Unable to Change Priority"), MB_OK|MB_ICONSTOP);
        return;
    }

    if (!SetPriorityClass(hProcess, priority))
    {
        GetLastErrorText(strErrorText, 260);
        MessageBox(hMainWnd, strErrorText, _T("Unable to Change Priority"), MB_OK|MB_ICONSTOP);
    }

    CloseHandle(hProcess);
}
int _tmain(int argc, TCHAR * argv[]) {
    // process the command line to extract that flags for SimpleOpt 
    int nFlags = SO_O_USEALL;
    CSimpleOpt args(argc, argv, g_rgFlags, SO_O_NOERR|SO_O_EXACT);
    while (args.Next()) {
        nFlags |= args.OptionId();
    }

    // now process the remainder of the command line with these flags
    args.Init(args.FileCount(), args.Files(), g_rgOptions, nFlags);
    while (args.Next()) {
        if (args.LastError() != SO_SUCCESS) {
            _tprintf(
                _T("%s: '%s' (use --help to get command line help)\n"),
                GetLastErrorText(args.LastError()), args.OptionText());
            continue;
        }

        switch (args.OptionId()) {
        case OPT_HELP:
            ShowUsage();
            return 0;
        case OPT_MULTI:  
            DoMultiArgs(args, -1);
            break;
        case OPT_MULTI0: 
            DoMultiArgs(args, 0);
            break;
        case OPT_MULTI1: 
            DoMultiArgs(args, 1);
            break;
        case OPT_MULTI2: 
            DoMultiArgs(args, 2);
            break;
        case OPT_STOP:
            args.Stop();
            break;
        default:
            if (args.OptionArg()) {
                _tprintf(_T("option: %2d, text: '%s', arg: '%s'\n"),
                    args.OptionId(), args.OptionText(), args.OptionArg());
            }
            else {
                _tprintf(_T("option: %2d, text: '%s'\n"),
                    args.OptionId(), args.OptionText());
            }
        }
    }

    /* process files from command line */
    ShowFiles(args.FileCount(), args.Files());

	return 0;
}