Esempio n. 1
0
void ServiceMain(int argc, char** argv)
{
	serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	serviceStatus.dwCurrentState = SERVICE_START_PENDING;
	serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	serviceStatus.dwWin32ExitCode = 0;
	serviceStatus.dwServiceSpecificExitCode = 0;
	serviceStatus.dwCheckPoint = 0;
	serviceStatus.dwWaitHint = 0;

	serviceStatusHandle = RegisterServiceCtrlHandlerW(serviceName, (LPHANDLER_FUNCTION)ControlHandler);

	if (serviceStatusHandle == (SERVICE_STATUS_HANDLE)0)
		return;

	serviceStatus.dwCurrentState = SERVICE_RUNNING;
	SetServiceStatus(serviceStatusHandle, &serviceStatus);

	SocketManager *sock = new SocketManager();
	sock->start();

	while (serviceStatus.dwCurrentState == SERVICE_RUNNING)
	{
		Sleep(1000);
	}
}
Esempio n. 2
0
/*
** This is the main entry point for the service.
** When the service control manager receives a request to start the service,
** it starts the service process (if it is not already running). The main
** thread of the service process calls the StartServiceCtrlDispatcher
** function with a pointer to an array of SERVICE_TABLE_ENTRY structures.
** Then the service control manager sends a start request to the service
** control dispatcher for this service process. The service control dispatcher
** creates a new thread to execute the ServiceMain function (this function)
** of the service being started.
*/
static void WINAPI win32_http_service_main(
  DWORD argc,              /* Number of arguments in argv */
  LPWSTR *argv             /* Arguments passed */
){

  /* Update the service information. */
  hsData.isRunningAsService = 1;
  if( argc>0 ){
    hsData.zServiceName = argv[0];
  }

  /* Register the service control handler function */
  sshStatusHandle = RegisterServiceCtrlHandlerW(L"", win32_http_service_ctrl);
  if( !sshStatusHandle ){
    win32_report_service_status(SERVICE_STOPPED, NO_ERROR, 0);
    return;
  }

  /* Set service specific data and report that the service is starting. */
  ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  ssStatus.dwServiceSpecificExitCode = 0;
  win32_report_service_status(SERVICE_START_PENDING, NO_ERROR, 3000);

   /* Execute the http server */
  win32_http_server(hsData.port, hsData.port,
                    NULL, NULL, hsData.zNotFound, hsData.flags);

  /* Service has stopped now. */
  win32_report_service_status(SERVICE_STOPPED, NO_ERROR, 0);
  return;
}
Esempio n. 3
0
//
// Purpose: 
//   Entry point for the service
//
// Parameters:
//   dwArgc - Number of arguments in the lpszArgv array
//   lpszArgv - Array of strings. The first string is the name of
//     the service and subsequent strings are passed by the process
//     that called the StartService function to start the service.
// 
// Return value:
//   None.
//
VOID WINAPI SvcMain( DWORD dwArgc, LPTSTR *lpszArgv )
{
    // Register the handler function for the service
    gSvcStatusHandle = RegisterServiceCtrlHandlerW( 
        SVCNAME, 
        SvcCtrlHandler);

    if( !gSvcStatusHandle )
    { 
        SvcReportEvent(TEXT("RegisterServiceCtrlHandler")); 
        return; 
    } 

    // These SERVICE_STATUS members remain as set here

    gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 
    gSvcStatus.dwServiceSpecificExitCode = 0;    

    // Report initial status to the SCM

    ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );

    // Perform service-specific initialization and work.

    SvcInit( dwArgc, lpszArgv );
}
Esempio n. 4
0
/**
 * Main entry point when running as a service.
 */
void WINAPI
SvcMain(DWORD argc, LPWSTR *argv)
{
  // Setup logging, and backup the old logs
  WCHAR updatePath[MAX_PATH + 1];
  if (GetLogDirectoryPath(updatePath)) {
    BackupOldLogs(updatePath, LOGS_TO_KEEP);
    LogInit(updatePath, L"maintenanceservice.log");
  }

  // Disable every privilege we don't need. Processes started using
  // CreateProcess will use the same token as this process.
  UACHelper::DisablePrivileges(NULL);

  // Register the handler function for the service
  gSvcStatusHandle = RegisterServiceCtrlHandlerW(SVC_NAME, SvcCtrlHandler);
  if (!gSvcStatusHandle) {
    LOG(("RegisterServiceCtrlHandler failed (%d)\n", GetLastError()));
    ExecuteServiceCommand(argc, argv);  
    LogFinish();
    exit(1);
  } 

  // These values will be re-used later in calls involving gSvcStatus
  gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  gSvcStatus.dwServiceSpecificExitCode = 0;

  // Report initial status to the SCM
  ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);

  // This event will be used to tell the SvcCtrlHandler when the work is
  // done for when a stop comamnd is manually issued.
  gWorkDoneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (!gWorkDoneEvent) {
    ReportSvcStatus(SERVICE_STOPPED, 1, 0);
    StartTerminationThread();
    return;
  }

  // Initialization complete and we're about to start working on
  // the actual command.  Report the service state as running to the SCM.
  ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);

  // The service command was executed, stop logging and set an event
  // to indicate the work is done in case someone is waiting on a
  // service stop operation.
  ExecuteServiceCommand(argc, argv);  
  LogFinish();

  SetEvent(gWorkDoneEvent);

  // If we aren't already in a stopping state then tell the SCM we're stopped
  // now.  If we are already in a stopping state then the SERVICE_STOPPED state
  // will be set by the SvcCtrlHandler.
  if (!gServiceControlStopping) {
    ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
    StartTerminationThread();
  }
}
Esempio n. 5
0
 void Service::main()
 {
   mStatusHandle = RegisterServiceCtrlHandlerW( mName.c_str(),
     _serviceControlHandler );
   if ( !mStatusHandle )
     EXCEPT_WINAPI( L"Couldn't register service control handler" );
   setState( SERVICE_START_PENDING, 0 );
   doInitialize();
   setState( SERVICE_START_PENDING, 1 );
   doStart();
   WaitForSingleObject( mRunEvent, INFINITE );
   setState( SERVICE_RUNNING, 0 );
   WaitForSingleObject( mStopEvent, INFINITE );
   doCleanup();
 }
Esempio n. 6
0
// 
//   FUNCTION: CServiceBase::ServiceMain(DWORD, PWSTR *) 
// 
//   PURPOSE: Entry point for the service. It registers the handler function  
//   for the service and starts the service. 
// 
//   PARAMETERS: 
//   * dwArgc   - number of command line arguments 
//   * lpszArgv - array of command line arguments 
// 
void WINAPI CServiceBase::ServiceMain(DWORD dwArgc, PWSTR *pszArgv) 
{ 
    assert(s_service != NULL); 
 
    // Register the handler function for the service 
    s_service->m_statusHandle = RegisterServiceCtrlHandlerW( 
        s_service->m_name, ServiceCtrlHandler); 
    if (s_service->m_statusHandle == NULL) 
    { 
        throw GetLastError(); 
    } 
 
    // Start the service. 
    s_service->Start(dwArgc, pszArgv); 
} 
Esempio n. 7
0
//Service Main function
size_t WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{
	ServiceStatusHandle = RegisterServiceCtrlHandlerW(DEFAULT_LOCAL_SERVICE_NAME, (LPHANDLER_FUNCTION)ServiceControl);
	if (!ServiceStatusHandle || !UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1U, UPDATE_SERVICE_TIME * SECOND_TO_MILLISECOND))
		return FALSE;

	ServiceEvent = CreateEventW(0, TRUE, FALSE, 0);
	if (!ServiceEvent || !UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2U, STANDARD_TIMEOUT) || !ExecuteService())
		return FALSE;

	ServiceCurrentStatus = SERVICE_RUNNING;
	if (!UpdateServiceStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0))
		return FALSE;

	WaitForSingleObject(ServiceEvent, INFINITE);
	CloseHandle(ServiceEvent);
	return EXIT_SUCCESS;
}
Esempio n. 8
0
VOID
WINAPI
AbortSvchostService (
    _In_ LPCWSTR lpServiceName,
    _In_ DWORD dwExitCode
    )
{
    SERVICE_STATUS_HANDLE scHandle;
    SERVICE_STATUS ServiceStatus;

    /* Make us stopped and accept only query commands */
    ServiceStatus.dwCheckPoint = 0;
    ServiceStatus.dwWaitHint = 0;
    ServiceStatus.dwServiceSpecificExitCode = 0;
    ServiceStatus.dwCurrentState = SERVICE_STOPPED;
    ServiceStatus.dwControlsAccepted = SERVICE_QUERY_CONFIG;
    ServiceStatus.dwServiceType = SERVICE_WIN32;
    ServiceStatus.dwWin32ExitCode = dwExitCode;

    /* Register a handler that will do nothing while we are being stopped */
    scHandle = RegisterServiceCtrlHandlerW(lpServiceName,
                                           DummySvchostCtrlHandler);
    if (scHandle)
    {
        /* Stop us */
        if (!SetServiceStatus(scHandle, &ServiceStatus))
        {
            /* Tell the debugger if this didn't work */
            DBG_ERR("AbortSvchostService: SetServiceStatus error %ld\n",
                    GetLastError());
        }
    }
    else
    {
        /* Tell the debugger if we couldn't register the handler */
        DBG_ERR("AbortSvchostService: RegisterServiceCtrlHandler failed %d\n",
                GetLastError());
    }
}
Esempio n. 9
0
/**********************************************************************
 *	RegisterServiceCtrlHandlerA
 *
 * @implemented
 */
SERVICE_STATUS_HANDLE WINAPI
RegisterServiceCtrlHandlerA(LPCSTR lpServiceName,
                            LPHANDLER_FUNCTION lpHandlerProc)
{
    ANSI_STRING ServiceNameA;
    UNICODE_STRING ServiceNameU;
    SERVICE_STATUS_HANDLE SHandle;

    RtlInitAnsiString(&ServiceNameA, (LPSTR)lpServiceName);
    if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&ServiceNameU, &ServiceNameA, TRUE)))
    {
        SetLastError(ERROR_OUTOFMEMORY);
        return (SERVICE_STATUS_HANDLE)0;
    }

    SHandle = RegisterServiceCtrlHandlerW(ServiceNameU.Buffer,
                                          lpHandlerProc);

    RtlFreeUnicodeString(&ServiceNameU);

    return SHandle;
}
Esempio n. 10
0
static
VOID WINAPI 
    ServiceMain
    (
        DWORD  dwArgc,
        RPCHAR lpszArgv
    )
{
    RU32 memUsed = 0;
    RWCHAR svcName[] = { _SERVICE_NAME };
    RU32 i = 0;

    UNREFERENCED_PARAMETER( dwArgc );
    UNREFERENCED_PARAMETER( lpszArgv );


    if( NULL == ( g_svc_status_handle = RegisterServiceCtrlHandlerW( svcName, SvcCtrlHandler ) ) )
    {
        return;
    }

    rpal_memory_zero( &g_svc_status, sizeof( g_svc_status ) );
    g_svc_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_svc_status.dwControlsAccepted = 0;
    g_svc_status.dwCurrentState = SERVICE_START_PENDING;
    g_svc_status.dwWin32ExitCode = 0;
    g_svc_status.dwServiceSpecificExitCode = 0;
    g_svc_status.dwCheckPoint = 0;
    SetServiceStatus( g_svc_status_handle, &g_svc_status );

    if( NULL == ( g_timeToQuit = rEvent_create( TRUE ) ) )
    {
        g_svc_status.dwControlsAccepted = 0;
        g_svc_status.dwCurrentState = SERVICE_STOPPED;
        g_svc_status.dwWin32ExitCode = GetLastError();
        g_svc_status.dwCheckPoint = 1;
        SetServiceStatus( g_svc_status_handle, &g_svc_status );
        return;
    }

    rpal_debug_info( "initialising rpHCP." );
    if( !rpHostCommonPlatformLib_launch( g_svc_primary, g_svc_secondary ) )
    {
        rpal_debug_warning( "error launching hcp." );
    }

    for( i = 0; i < ARRAY_N_ELEM( g_manual_loads ); i++ )
    {
        if( NULL != g_manual_loads[ i ].modPath )
        {
            if( 0 != g_manual_loads[ i ].nMod )
            {
#ifdef HCP_EXE_ENABLE_MANUAL_LOAD
                rpHostCommonPlatformLib_load( g_manual_loads[ i ].modPath, g_manual_loads[ i ].nMod );
#endif
            }
            else
            {
                rpal_debug_error( "Mismatched number of -m modulePath and -n moduleId statements provided!" );
            }

            rpal_memory_free( g_manual_loads[ i ].modPath );
            g_manual_loads[ i ].modPath = NULL;
        }
        else
        {
            break;
        }
    }

    g_svc_status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    g_svc_status.dwCurrentState = SERVICE_RUNNING;
    g_svc_status.dwWin32ExitCode = 0;
    g_svc_status.dwCheckPoint = 1;
    SetServiceStatus( g_svc_status_handle, &g_svc_status );

    rpal_debug_info( "...running, waiting to exit..." );
    rEvent_wait( g_timeToQuit, RINFINITE );
    rEvent_free( g_timeToQuit );

    rpal_debug_info( "...exiting..." );
    rpal_Context_cleanup();

    memUsed = rpal_memory_totalUsed();
    if( 0 != memUsed )
    {
        rpal_debug_critical( "Memory leak: %d bytes.\n", memUsed );
        //rpal_memory_findMemory();
#ifdef RPAL_FEATURE_MEMORY_ACCOUNTING
        rpal_memory_printDetailedUsage();
#endif
    }

    g_svc_status.dwControlsAccepted = 0;
    g_svc_status.dwCurrentState = SERVICE_STOPPED;
    g_svc_status.dwWin32ExitCode = 0;
    g_svc_status.dwCheckPoint = 3;
    SetServiceStatus( g_svc_status_handle, &g_svc_status );
}
Esempio n. 11
0
//---------------------------------------------------------------------------
Service & Service::serviceMain(uintptr_t n,DWORD dwArgc,LPWSTR * lpszArgv)
{
  uintptr_t i;
  int32_t err;
  try {
    for( i = 0; i < dwArgc; i++ ) argv().add(lpszArgv[i]);
    statusHandle_ = RegisterServiceCtrlHandlerW(
      serviceName_.getUNICODEString(),
      Services::handlers_[n]
    );
    if( statusHandle_ == 0 ){
      err = GetLastError() + errorOffset;
      newObjectV1C2<Exception>(err,__PRETTY_FUNCTION__)->throwSP();
    }
    serviceStatus_.dwServiceType = serviceType_;
    serviceStatus_.dwCurrentState = SERVICE_START_PENDING;
    serviceStatus_.dwWin32ExitCode = NO_ERROR;
    serviceStatus_.dwServiceSpecificExitCode = ERROR_SUCCESS;
    serviceStatus_.dwCheckPoint = 0;
    if( SetServiceStatus(statusHandle_,&serviceStatus_) == 0 ){
      err = GetLastError() + errorOffset;
      newObjectV1C2<Exception>(err,__PRETTY_FUNCTION__)->throwSP();
    }
    start();
    serviceStatus_.dwCurrentState = SERVICE_RUNNING;
    if( SetServiceStatus(statusHandle_,&serviceStatus_) == 0 ){
      err = GetLastError() + errorOffset;
      newObjectV1C2<Exception>(err,__PRETTY_FUNCTION__)->throwSP();
    }
/*    MSG msg;
    for(;;){
      if( PeekMessage(&msg,NULL,0,0,PM_REMOVE) != 0 ){
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
      if( msg.message == WM_QUIT ) break;
      if( WaitMessage() == 0 ){
        long err = GetLastError() + errorOffset;
        newObjectV1C2<Exception>(err,__PRETTY_FUNCTION__)->throwSP();
      }
    }*/
    semaphore_.wait();
    serviceStatus_.dwCurrentState = SERVICE_STOP_PENDING;
    if( SetServiceStatus(statusHandle_,&serviceStatus_) == 0 ){
      err = GetLastError() + errorOffset;
      newObjectV1C2<Exception>(err,__PRETTY_FUNCTION__)->throwSP();
    }
    stop();
  }
  catch( ExceptionSP & e ){
    e->writeStdError();
    serviceStatus_.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
    serviceStatus_.dwServiceSpecificExitCode = e->code() >= errorOffset ? e->code() - errorOffset : e->code();
  }
  catch( ... ){
    serviceStatus_.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
    serviceStatus_.dwServiceSpecificExitCode = DWORD(-1);
  }
  serviceStatus_.dwCurrentState = SERVICE_STOPPED;
  BOOL r = SetServiceStatus(statusHandle_,&serviceStatus_);
  assert( r != 0 );
  if( r == 0 ) abort();
  return *this;
}