//
// 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 = RegisterServiceCtrlHandler(
		SVCNAME,
		SvcCtrlHandler);
	SvcReportEvent(TEXT("hello from service"));

	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);
}
Example #2
0
//
// Purpose: 
//   The service code
//
// 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 SvcInit( DWORD dwArgc, LPTSTR *lpszArgv)
{
  // Get the real arguments from the registry
  char key[1024];
  snprintf(key, 1022, "SOFTWARE\\MTConnect\\%s", gService->name());
  key[1023] = '\0';

  HKEY adapter;
  LONG res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &adapter);
  if (res != ERROR_SUCCESS)
  {
    SvcReportEvent("RegOpenKey: Could not open Adapter");
    ReportSvcStatus( SERVICE_STOPPED, 1, 0 );
    return;
  }

  char *argp[64];
  BYTE arguments[2048];
  DWORD len = 2047, type, argc = 0;
  res = RegQueryValueEx(adapter, "Arguments", 0, &type, (BYTE*) arguments, &len);
  if (res == ERROR_SUCCESS)
  {
    DWORD i = 0;
    while (i < len) {
      argp[argc] = (char*) arguments + i;
      i += strlen((char*) arguments + i) + 1;
      argc++;
    }
    argp[argc] = 0;
  } else {
    SvcReportEvent("RegOpenKey: Could not get Arguments");
    RegCloseKey(adapter);
    ReportSvcStatus( SERVICE_STOPPED, 1, 0 );
    return;
  }

  gService->initialize(argc, (const char**) argp);

  // TO_DO: Declare and set any required variables.
  //   Be sure to periodically call ReportSvcStatus() with 
  //   SERVICE_START_PENDING. If initialization fails, call
  //   ReportSvcStatus with SERVICE_STOPPED.

  // Create an event. The control handler function, SvcCtrlHandler,
  // signals this event when it receives the stop control code.

  // Report running status when initialization is complete.

  ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );

  // TO_DO: Perform work until service stops.
  gService->start();

  ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
}
Example #3
0
void __cdecl _tmain(int argc, TCHAR *argv[])
{
	// If command-line parameter is "install", install the service. 
	// Otherwise, the service is probably being started by the SCM.

	if (lstrcmpi(argv[1], TEXT("install")) == 0)
	{
		SvcInstall();
		return;
	}

	// TO_DO: Add any additional services for the process to this table.
	SERVICE_TABLE_ENTRY DispatchTable[] =
	{
		{ SVCNAME, (LPSERVICE_MAIN_FUNCTION)SvcMain },
		{ NULL, NULL }
	};

	// This call returns when the service has stopped. 
	// The process should simply terminate when the call returns.

	if (!StartServiceCtrlDispatcher(DispatchTable))
	{
		SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
	}
}
Example #4
0
void SvcReportWinFuncError(LPTSTR szFunction)
{
	static const DWORD SVC_ERROR = STATUS_SEVERITY_ERROR | CUSTOMER_FLAG | FACILITY_RUNTIME | 1;

	TCHAR buffer[80];
	StringCchPrintf(buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());

	SvcReportEvent(EVENTLOG_ERROR_TYPE, SVC_ERROR, buffer);
}
Example #5
0
//
// Purpose: 
//   The service code
//
// 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 SvcInit( DWORD dwArgc, LPTSTR *lpszArgv)
{
// Get the real arguments from the registry
  char key[1024];
  snprintf(key, 1023, "SOFTWARE\\MTConnect\\%s", gService->name().c_str());
  
  HKEY agent;
  LONG res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &agent);
  if (res != ERROR_SUCCESS)
  {
    SvcReportEvent("RegOpenKey: Could not open MTConnect Agent Key");
    ReportSvcStatus( SERVICE_STOPPED, 1, 0 );
    return;
  }
  
  const char *argp[2];
  BYTE configFile[2048];
  DWORD len = sizeof(configFile) - 1, type;
  res = RegQueryValueEx(agent, "ConfigurationFile", 0, &type, (BYTE*) configFile, &len);
  RegCloseKey(agent);
  if (res != ERROR_SUCCESS)
  {
    SvcReportEvent("RegOpenKey: Could not open ConfigurationFile");
    ReportSvcStatus( SERVICE_STOPPED, 1, 0 );
    return;
  }

  argp[0] = (char*) configFile;
  argp[1] = 0;
  gService->initialize(1, argp);
    
  // Report running status when initialization is complete.

  ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );

  gService->start();

  ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
}
Example #6
0
void ServiceMain(int argc, wchar_t *argv[])
{
	gSvcStatusHandle = RegisterServiceCtrlHandler(szServiceName, SvcCtrlHandler);

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

	gSvcStatus.dwServiceType = SERVICE_WIN32; 
	gSvcStatus.dwServiceSpecificExitCode = 0;

	ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);

	SvcInit(argc, argv);
}
//
// Purpose: 
//   Entry point for the process
//
// Parameters:
//   None
// 
// Return value:
//   None
//
int MTConnectService::main(int argc, const char *argv[]) 
{ 
	// If command-line parameter is "install", install the service. 
	// Otherwise, the service is probably being started by the SCM.
	Trace("MTConnectService::main()\n");

	if(argc > 1) {
		OutputDebugString(argv[1]);
		if (stricmp( argv[1], "debug") == 0 ) {
			mDebug = true;
		}
		initialize(argc - 2, argv + 2);
		if (stricmp( argv[1], "install") == 0 )
		{
			install(argc - 2, argv + 2);
			return 0;
		} else if (stricmp( argv[1], "remove") == 0 ) {
			remove();
			return 0;
		} else if (stricmp( argv[1], "debug") == 0) {
			gLogger->setLogLevel(Logger::eDEBUG);
			start();
			return 0;
		} else if (stricmp( argv[1], "run") == 0) {
			start();
			return 0;
		}
	}

	Trace("MTConnectService::main() Service\n");
	mIsService = true;
	SERVICE_TABLE_ENTRY DispatchTable[] = 
	{ 
		{  mName, (LPSERVICE_MAIN_FUNCTION) SvcMain }, 
		{ NULL, NULL } 
	}; 

	gService = this;

	if (!StartServiceCtrlDispatcher( DispatchTable )) 
	{ 
		SvcReportEvent("StartServiceCtrlDispatcher"); 
	} 

	return 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
	char path[MAX_PATH];
	if( !GetModuleFileName(NULL, path, MAX_PATH ) )
	{
		Trace("Cannot get path of executable\n");//, GetLastError());
		return;
	}

	char *cp = strrchr(path, '\\');
	if (cp != NULL)
	{
		*cp = '\0';
		SetCurrentDirectory(path);
	}

	OutputDebugString("SvcMain setName\n");
	//gService->setName(lpszArgv[0]);
	gSvcStatusHandle = RegisterServiceCtrlHandler( 
		gService->name(), 
		SvcCtrlHandler);

	if( !gSvcStatusHandle )
	{ 
		SvcReportEvent("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, 10000 );

	// Perform service-specific initialization and work.
	Sleep(2000);


	SvcInit( dwArgc, lpszArgv );
}
Example #9
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
  gService->setName(lpszArgv[0]);

  char path[MAX_PATH];
  if( !GetModuleFileName(NULL, path, MAX_PATH ) )
  {
    sLogger << dlib::LERROR << "Cannot get path of executable (" << GetLastError() << ")";
    return;
  }

  std::string wd = path;
  size_t found = wd.rfind('\\');
  if (found != std::string::npos)
  {
    wd.erase(found);
    SetCurrentDirectory(wd.c_str());
  }

  gSvcStatusHandle = RegisterServiceCtrlHandler( 
    gService->name().c_str(), 
    SvcCtrlHandler);

  if( !gSvcStatusHandle )
  { 
    SvcReportEvent("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 );
}
Example #10
0
static void WINAPI
ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
	/* register the handler function for the service */
	statusHandle = RegisterServiceCtrlHandlerEx(SVCNAME, SvcCtrlHandler, NULL);
	if (!statusHandle)
	{
		SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
		return;
	}

	status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	status.dwServiceSpecificExitCode = 0;

	/* report initial status to the SCM */
	report_status(SERVICE_START_PENDING, NO_ERROR, 3000);

	/* report service-specific initialization and work */
	SvcInit(dwArgc, lpszArgv);
}
Example #11
0
static int regWinService()
{
	hStatus = RegisterServiceCtrlHandler(SERVICE_NAME, (LPHANDLER_FUNCTION)ControlHandler);
	if (!hStatus) {
		SvcReportEvent("RegisterServiceCtrlHandler");
		return -1;
	}

	char name[1024];
	GetModuleFileName(0, name, sizeof(name));

	char *p = strrchr(name, '\\');
	if (p) *p = 0;
	SetCurrentDirectory(name);

	ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	ServiceStatus.dwServiceSpecificExitCode = 0;

	ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);
	ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
	return 0;
}
Example #12
0
int MTConnectService::main(int argc, const char *argv[]) 
{
  std::set_terminate(agent_termination_handler);
  PrintMTConnectAgentVersion();
  try 
  {
    // If command-line parameter is "install", install the service. If debug or run
    // is specified than just run it as a command line process. 
    // Otherwise, the service is probably being started by the SCM.
    if(argc > 1) {
      if (stricmp( argv[1], "help") == 0 || strncmp(argv[1], "-h", 2) == 0)
      {
        printf("Usage: agent [help|install|debug|run] [configuration_file]\n"
               "       help           Prints this message\n"
               "       install        Installs the service\n"
               "                      install with -h will display additional options\n"
               "       remove         Remove the service\n"
               "       debug          Runs the agent on the command line with verbose logging\n"
               "       run            Runs the agent on the command line\n"
               "       config_file    The configuration file to load\n"
               "                      Default: agent.cfg in current directory\n\n"
               "When the agent is started without any arguments it is assumed it will be running\n"
               "as a service and will begin the service initialization sequence\n");
        exit(0);
      } else if (stricmp( argv[1], "install") == 0 ) {
        initialize(argc - 2, argv + 2);
        install();
        return 0;
      } else if (stricmp( argv[1], "remove") == 0 ) {
        initialize(argc - 2, argv + 2);
        remove();
        return 0;
      } else if (stricmp( argv[1], "debug") == 0 || stricmp( argv[1], "run") == 0) {
        if (stricmp( argv[1], "debug") == 0)
          mIsDebug = true;
          
        initialize(argc - 2, argv + 2);
        start();
        dlib::thread_function cmd(commandLine);
        return 0;
      }
    }
  
    gService = this;
    mIsService = true;
    SERVICE_TABLE_ENTRY DispatchTable[] = 
      { 
        {  "", (LPSERVICE_MAIN_FUNCTION) SvcMain }, 
        { NULL, NULL } 
      }; 

    if (!StartServiceCtrlDispatcher( DispatchTable )) 
    { 
      SvcReportEvent("StartServiceCtrlDispatcher"); 
    } 
  }
  catch (std::exception & e)
  {
    sLogger << dlib::LFATAL << "Agent top level exception: " << e.what();
    std::cerr << "Agent top level exception: " << e.what() << std::endl;
  }
  catch (std::string &s)
  {
    sLogger << dlib::LFATAL << "Agent top level exception: " << s;
    std::cerr << "Agent top level exception: " << s << std::endl;
  }
  
  return 0;
} 
Example #13
0
void SvcReportInfo(LPTSTR msg)
{
	static const DWORD SVC_INFO = STATUS_SEVERITY_INFORMATIONAL | CUSTOMER_FLAG | FACILITY_RUNTIME | 2;

	SvcReportEvent(EVENTLOG_INFORMATION_TYPE, SVC_INFO, msg);
}