Ejemplo n.º 1
0
int _tmain(int argc, TCHAR * argv[])
{
	if (GetModuleFileName(NULL, szServicePath, CountOf(szServicePath)) == 0) {
		_tprintf(_T("Unable to get module name - %s\n"),
			 GetLastErrorText(szErr, CountOf(szErr)));
		return 1;
	}
	GetServiceNameFromModule(szServicePath, szServiceName, CountOf(szServiceName));
	_stprintf(szServiceDispName, _T("%s Server"), szServiceName);

	SERVICE_TABLE_ENTRY DispTable[] = {
		{ szServiceName, (LPSERVICE_MAIN_FUNCTION) ServiceMain },
		{ NULL, NULL }
	};

	if (argc > 1) {
		if (_tcsicmp(_T("--install"), argv[1]) == 0) {
			CmdInstallService(SERVICE_DEMAND_START);
			return 0;
		}
		if (_tcsicmp(_T("--install-auto"), argv[1]) == 0) {
			CmdInstallService(SERVICE_AUTO_START);
			return 0;
		} else if (_tcsicmp(_T("--remove"), argv[1]) == 0) {
			CmdRemoveService();
			return 0;
		} else if (_tcsicmp(_T("--debug"), argv[1]) == 0) {
			bDebug = TRUE;
			CmdDebugService(argc, argv);
			return 0;
		}
	}

	_tprintf(_T("%s --install          = Install the service\n"), argv[0]);
	_tprintf(_T("%s --remove           = Remove the service\n"), argv[0]);
	_tprintf(_T("%s --debug [params]   = Run as a console app for debugging\n"), argv[0]);

	_tprintf(_T("\nStartServiceCtrlDispatcher being called.\n"));
	_tprintf(_T("This may take several seconds.  Please wait.\n"));

	/* Setup std handles */
	if (MnSetupStdHandles() < 0)
		return 1;

	/* Service loop */
	if (!StartServiceCtrlDispatcher(DispTable))
		AddToMessageLog(_T("StartServiceCtrlDispatcher"));

	return 0;
}
Ejemplo n.º 2
0
//
//  FUNCTION: main
//
//  PURPOSE: entrypoint for service
//
//  PARAMETERS:
//    argc - number of command line arguments
//    argv - array of command line arguments
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//    main() either performs the command line task, or
//    call StartServiceCtrlDispatcher to register the
//    main service thread.  When the this call returns,
//    the service has stopped, so exit.
//
void main(int argc, char **argv)
{
char *Account;
char *Password;

    SERVICE_TABLE_ENTRY dispatchTable[] =
    {
        { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main },
        { NULL, NULL }
    };

    if ( (argc > 1) &&
         ((*argv[1] == '-') || (*argv[1] == '/')) )
    {
        if ( _stricmp( "install", argv[1]+1 ) == 0 )
        {
		      /*check the account*/
		      /*WCG. Install it with domain or without domain*/
		      if(argc<3)
			      Account=NULL;
		      else
			      Account=argv[2];
		      /*check the account*/
		      if(argc<4)
			      Password=NULL;
		      else
            Password=argv[3];
              CmdInstallService(Account,Password);
        }
        else if ( _stricmp( "remove", argv[1]+1 ) == 0 )
        {
            CmdRemoveService();
        }
        else if ( _stricmp( "debug", argv[1]+1 ) == 0 )
        {
            bDebug = TRUE;
            CmdDebugService(argc, argv);
        }
        else
        {
            goto dispatch;
        }
        exit(0);
    }

    // if it doesn't match any of the above parameters
    // the service control manager may be starting the service
    // so we must call StartServiceCtrlDispatcher
    dispatch:
        // this is just to be friendly
        printf( "%s -install administrator_account password   to install the service\n", SZAPPNAME );
        printf( "%s -remove                to remove the service\n", SZAPPNAME );
        printf( "%s -debug <params>        to run as a console app for debugging\n", SZAPPNAME );
        printf( "\nStartServiceCtrlDispatcher being called.\n" );
        printf( "This may take several seconds.  Please wait.\n" );

        if (!StartServiceCtrlDispatcher(dispatchTable))
		   AddToMessageLog(NULL,0,EVENTLOG_ERROR_TYPE,SC_SYSTEM,
			   EVLG_STD_STARTSERVICECTRLDISPATCHER_FAILED);
}
Ejemplo n.º 3
0
//
//  FUNCTION: main
//
//  PURPOSE: entrypoint for service
//
//  PARAMETERS:
//    argc - number of command line arguments
//    argv - array of command line arguments
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//    main() either performs the command line task, or
//    call StartServiceCtrlDispatcher to register the
//    main service thread.  When the this call returns,
//    the service has stopped, so exit.
//
int __cdecl main(int argc, char **argv)
{
   SERVICE_TABLE_ENTRY dispatchTable[] =
   {
      { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
      { NULL, NULL}
   };

   if ( (argc > 1) &&
        ((*argv[1] == '-') || (*argv[1] == '/')) )
   {
      if ( _stricmp( "install", argv[1]+1 ) == 0 )
      {
         return CmdInstallService();
      }
      else if ( _stricmp( "remove", argv[1]+1 ) == 0 )
      {
         return CmdRemoveService();
      }
      else if ( _stricmp( "start", argv[1]+1 ) == 0)
      {
         return CmdStartService();
      }
      else if ( _stricmp( "stop", argv[1]+1 ) == 0)
      {
         return CmdStopService();
      }
      else if ( _stricmp( "debug", argv[1]+1 ) == 0 )
      {
         bDebug = TRUE;
         CmdDebugService(argc, argv);
      }
      else
      {
         goto dispatch;
      }
      return 0;
   }

   // if it doesn't match any of the above parameters
   // the service control manager may be starting the service
   // so we must call StartServiceCtrlDispatcher
   dispatch:
   // this is just to be friendly
   printf( "%s -install          to install the service\n", SZAPPNAME );
   printf( "%s -start            to start the service\n", SZAPPNAME );
   printf( "%s -stop             to start the service\n", SZAPPNAME );
   printf( "%s -remove           to remove the service\n", SZAPPNAME );
   printf( "%s -debug <params>   to run as a console app for debugging\n", SZAPPNAME );
   printf( "\nStartServiceCtrlDispatcher being called.\n" );
   printf( "This may take several seconds.  Please wait.\n" );

   if (!StartServiceCtrlDispatcher(dispatchTable))
      AddToMessageLog(MSG_FLAGS_ERROR, TEXT("StartServiceCtrlDispatcher failed."));

   return 0;
}
//
//  FUNCTION: main
//
//  PURPOSE: entrypoint for service
//
//  PARAMETERS:
//    argc - number of command line arguments
//    argv - array of command line arguments
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//    main() either performs the command line task, or
//    call StartServiceCtrlDispatcher to register the
//    main service thread.  When the this call returns,
//    the service has stopped, so exit.
//
void _CRTAPI1 main(int argc, char **argv)
{
    SERVICE_TABLE_ENTRY dispatchTable[] =
    {
        { NULL, (LPSERVICE_MAIN_FUNCTION)service_main },
        { NULL, NULL }
    };
        
    if (!InitPrologService()) {
    	AddToMessageLog(TEXT("Prolog Service Initilization failed."));
    	exit(0);
    }
    
    dispatchTable[0].lpServiceName = szServiceName;

    if ( (argc > 1) &&
         ((*argv[1] == '-') || (*argv[1] == '/')) )
    {
        if ( _stricmp( "install", argv[1]+1 ) == 0 )
        {
            CmdInstallService();
        }
        else if ( _stricmp( "remove", argv[1]+1 ) == 0 )
        {
            CmdRemoveService();
        }
        else if ( _stricmp( "debug", argv[1]+1 ) == 0 )
        {
            bDebug = TRUE;
            CmdDebugService(argc, argv);
        }
        else
        {
            goto dispatch;
        }
        exit(0);
    }

    // if it doesn't match any of the above parameters
    // the service control manager may be starting the service
    // so we must call StartServiceCtrlDispatcher
    dispatch:
        // this is just to be friendly
        printf( "%s -install          to install the service\n", szAppName );
        printf( "%s -remove           to remove the service\n", szAppName );
        printf( "%s -debug <params>   to run as a console app for debugging\n", szAppName );
        printf( "\nStartServiceCtrlDispatcher being called.\n" );
        printf( "This may take several seconds.  Please wait.\n" );

        if (!StartServiceCtrlDispatcher(dispatchTable))
            AddToMessageLog(TEXT("StartServiceCtrlDispatcher failed."));
}
Ejemplo n.º 5
0
void CPPgNTService::OnBnClickedInstall()
{
	OnApply(); // MORPH - Added by Stulle, Adjustable NT Service Strings
	if (CmdInstallService((IsDlgButtonChecked(IDC_SVC_STARTWITHSYSTEM))==BST_CHECKED )==0)
	{
		FillStatus();
		if(AfxMessageBox(GetResString(IDS_APPLY_SETTINGS),MB_YESNO) == IDYES)
			OnBnAllSettings();
		SetModified();
		if (thePrefs.m_nCurrentUserDirMode == 0) // my documents and running as a service is not a good idea. but leave it to user
			AfxMessageBox(GetResString(IDS_CHANGEUSERASSERVICE),MB_OK);
	}
	else
		SetDlgItemText(IDC_SVC_CURRENT_STATUS,GetResString(IDS_SVC_INSTALLFAILED)); 
}
Ejemplo n.º 6
0
//
//  FUNCTION: main
//
//  PURPOSE: entrypoint for service
//
//  PARAMETERS:
//    argc - number of command line arguments
//    argv - array of command line arguments
//
//  RETURN VALUE:
//    none
//
//  COMMENTS:
//    main() either performs the command line task, or
//    call StartServiceCtrlDispatcher to register the
//    main service thread.  When the this call returns,
//    the service has stopped, so exit.
//
void _CRTAPI1 main(int argc, char **argv)
{
    SERVICE_TABLE_ENTRY dispatchTable[] =
    {
        { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main },
        { NULL, NULL }
    };

    if ( (argc > 1) &&
         ((*argv[1] == '-') || (*argv[1] == '/')) )
    {
        if ( _stricmp( "install", argv[1]+1 ) == 0 )
        {
            CmdInstallService();
        }
        else if ( _stricmp( "remove", argv[1]+1 ) == 0 )
        {
            CmdRemoveService();
        }
        else
        {
            goto dispatch;
        }
        exit(0);
    }

    // if it doesn't match any of the above parameters
    // the service control manager may be starting the service
    // so we must call StartServiceCtrlDispatcher
    dispatch:
        // this is just to be friendly
        printf( "%s -install          to install the service\n", SZAPPNAME );
        printf( "%s -remove           to remove the service\n", SZAPPNAME );
        printf( "\nStartServiceCtrlDispatcher being called.\n" );
        printf( "This may take several seconds.  Please wait.\n" );

        if (!StartServiceCtrlDispatcher(dispatchTable))
            AddToMessageLog(TEXT("StartServiceCtrlDispatcher failed."));
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    int i=1;
    while ((argc > i) && ((*argv[i] == '-') || (*argv[i] == '/')))
    {
        if (_stricmp("install", argv[i]+1) == 0)
        {
            if (argc > ++i)
                lpszInstall = argv[i++];
        }
        else if (_stricmp("remove", argv[i]+1) == 0)
        {
            if (argc > ++i)
                lpszRemove = argv[i++];
        }
        else if (_stricmp( "console", argv[i]+1) == 0)
        {
            i++;
            bConsole = TRUE;
        }
        else if (_stricmp( "check", argv[i]+1) == 0)
        {
            i++;
            bConsole = TRUE;
            shar_checkonly=true;
        }
        else if (_stricmp( "config", argv[i]+1) == 0)
        {
            if (argc > ++i)
                shar_config = argv[i++];
        }
        else if (_stricmp( "schemadir", argv[i]+1) == 0)
        {
            if (argc > ++i)
                shar_schemadir = argv[i++];
        }
        else
        {
            goto dispatch;
        }
    }
    
    if (bConsole)
    {
        // Install break handler, then run the C routine twice, once to setup, once to start running.
        SetConsoleCtrlHandler(&BreakHandler,TRUE);
        if (real_main(1)!=0)
        {
            LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "shibd startup failed, check shibd.log for further details");
            return -1;
        }
        return real_main(0);
    }
    else if (lpszInstall)
    {
        CmdInstallService(lpszInstall);
        return 0;
    }
    else if (lpszRemove)
    {
        CmdRemoveService(lpszRemove);
        return 0;
    }
    

    // if it doesn't match any of the above parameters
    // the service control manager may be starting the service
    // so we must call StartServiceCtrlDispatcher
    dispatch:
        // this is just to be friendly
        printf("%s -install <name>   to install the named service\n", argv[0]);
        printf("%s -remove <name>    to remove the named service\n", argv[0]);
        printf("%s -console          to run as a console app for debugging\n", argv[0]);
        printf("%s -check            to run as a console app and check configuration\n", argv[0]);
        printf("\t-config <file> to specify the config file to use\n");
        printf("\t-schemadir <dir> to specify where schemas are\n");
        printf("\nService starting.\nThis may take several seconds. Please wait.\n" );

    SERVICE_TABLE_ENTRY dispatchTable[] =
    {
        { "SHIBD", (LPSERVICE_MAIN_FUNCTION)service_main },
        { NULL, NULL }
    };

    if (!StartServiceCtrlDispatcher(dispatchTable))
        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "StartServiceCtrlDispatcher failed.");
    return 0;
}
Ejemplo n.º 8
0
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
int main( int argc, char **argv ) {
#ifdef WIN32
    // Start winsock
    WSADATA wsaData;
    int rc;
#endif

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
#ifndef WIN32 // SIGALRM=14, _NSIG=3...
    my_signal( SIGALRM,  Sig_Interupt );
#endif

#ifndef WIN32
	// Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#endif

#ifdef WIN32 
    // Start winsock
    rc = WSAStartup( 0x202, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, "WSAStartup" );
    if (rc == SOCKET_ERROR)
        return 0;

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif

    // Initialize global mutexes and conditions
    Condition_Initialize ( &ReportCond );
    Condition_Initialize ( &ReportDoneCond );
    Mutex_Initialize( &groupCond );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

    // perform any cleanup when quitting Iperf
    atexit( cleanup );

    // Allocate the "global" settings
    thread_Settings* ext_gSettings = new thread_Settings;

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }

        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");

                return 0;
            }
        }
#endif
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        {
            thread_Settings *into = NULL;
            // Create the settings structure for the reporter thread
            Settings_Copy( ext_gSettings, &into );
            into->mThreadMode = kMode_Reporter;

            // Have the reporter launch the client or listener
            into->runNow = ext_gSettings;

            // Start all the threads that are ready to go
            thread_start( into );
        }
#else
        // No need to make a reporter thread because we don't have threads
        thread_start( ext_gSettings );
#endif
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
    thread_joinall();

    // all done!
    return 0;
} // end main
Ejemplo n.º 9
0
int WIN32_CDECL
main(int argc, char **argv)
{

  SERVICE_TABLE_ENTRY dispatchTable[] = {
    {THIS_SERVICE, (LPSERVICE_MAIN_FUNCTION) service_main},
    {NULL, NULL}
  };

  SERVICE_STATUS svcstatus;
  DWORD status;

/*
   Get the command line parameters and see what the user wants us to do.
 */

  if ((argc == 2) &&
      ((*argv[1] == '-') || (*argv[1] == '/') || (*argv[1] == '\\'))) {
    if (!_stricmp("install", argv[1] + 1))
      CmdInstallService(argc, argv);
    else if (!_stricmp("remove", argv[1] + 1))
      CmdRemoveService();
    else if (!_stricmp("start", argv[1] + 1))
      CmdStartService();
    else if (!_stricmp("stop", argv[1] + 1))
      CmdStopService();
    else if (!_stricmp("status", argv[1] + 1))
      CmdStatusService();
    else if (!_stricmp("run", argv[1] + 1)) {

/*  do not start the MUSH if it is already a running service */

      status = get_service_status(&svcstatus, TRUE);
      if (status == 0 && svcstatus.dwCurrentState == SERVICE_RUNNING) {
        fprintf(stderr, "The MUSH is already running as a service.\n");
        return 1;
      }
      worker_thread(NULL);
    } else
      CmdDisplayFormat();
  } else if (argc != 1)
    CmdDisplayFormat();
  else {

    /*  do not start the MUSH if it is already a running service */

    status = get_service_status(&svcstatus, TRUE);
    if (status == 0 && svcstatus.dwCurrentState == SERVICE_RUNNING) {
      fprintf(stderr, "The MUSH is already running as a service.\n");
      return 1;
    }
    /*  Under Windows 95 they won't be able to use the service manager */

    if (status == ERROR_CALL_NOT_IMPLEMENTED) {
      worker_thread(NULL);
      return 0;
    }
    /*
       Register the dispatch table with the service controller.

       If this fails then we are running interactively.

     */

    fprintf(stderr, "Attempting to start PennMUSH as a service ...\n");
    if (!StartServiceCtrlDispatcher(dispatchTable)) {
      fprintf(stderr,
              "Unable to start service, assuming running console-mode application.\n");
      fprintf(stderr,
              "You can save time on the next invocation by specifying: pennmush /run\n");
      worker_thread(NULL);
    }
  }                             /*  end of argc == 1 */

  return 0;
}                               /* end of main */
Ejemplo n.º 10
0
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C"
#endif /* __cplusplus */
int IPERF_MAIN( int argc, char **argv ) {
#ifdef NO_EXIT
    should_exit = 0;
#endif /* NO_EXIT */
#ifdef IPERF_DEBUG
    debug_init();
#endif /* IPERF_DEBUG */

#ifndef NO_INTERRUPTS
#ifdef WIN32
    setsigalrmfunc(call_sigalrm);
#endif /* WIN32 */

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
    my_signal( SIGALRM,  Sig_Interupt );

#ifndef WIN32
    // Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#else
    // Start winsock
    WORD wVersionRequested;
    WSADATA wsaData;

    // Using MAKEWORD macro, Winsock version request 2.2
    wVersionRequested = MAKEWORD(2, 2);

    int rc = WSAStartup( wVersionRequested, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, ( "WSAStartup failed.\n" ) );
	if (rc != 0) {
	    fprintf(stderr, "The Winsock DLL was not found!\n");
		return 1;
	}

    /*
     * Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports
	 * versions greater than 2.2 in addition to 2.2, it will still return 2.2 in
	 * wVersion since that is the version we requested.
     */
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 ) {
        /* Tell the user that we could not find a usable WinSock DLL. */
        fprintf(stderr, "The DLL does not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
        WSACleanup();
        return 1;
    }

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif /* WIN32 */
#endif /* NO_INTERRUPTS */

    // Initialize global mutexes and conditions
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report condition.\n" ) );
    Condition_Initialize ( &ReportCond );
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report done condition.\n" ) );
    Condition_Initialize ( &ReportDoneCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing group condition mutex.\n" ) );
    Mutex_Initialize( &groupCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing clients mutex.\n" ) );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Initializing the thread subsystem.\n" ) );
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

#ifndef NO_EXIT
    // perform any cleanup when quitting Iperf
    atexit( cleanup );
#endif /* NO_EXIT */

    // Allocate the "global" settings
    thread_Settings *ext_gSettings = (thread_Settings*) malloc( sizeof( thread_Settings ) );
    FAIL( ext_gSettings == NULL, ( "Unable to allocate memory for thread_Settings ext_gSettings.\n" ), NULL );
    IPERF_DEBUGF( MEMALLOC_DEBUG, IPERF_MEMALLOC_MSG( ext_gSettings, sizeof( thread_Settings ) ) );

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
#ifndef NO_ENVIRONMENT
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
#endif /* NO_ENVIORNMENT */
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

#ifdef NO_EXIT
    if (should_exit) {
        IPERF_DEBUGF( MEMFREE_DEBUG | IPERF_DBG_TRACE, IPERF_MEMFREE_MSG( ext_gSettings ) );
        FREE_PTR( ext_gSettings );

        IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) );
        Condition_Destroy( &ReportCond );
        IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) );
        Condition_Destroy( &ReportDoneCond );
        IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) );
        Mutex_Destroy( &groupCond );
        IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) );
        Mutex_Destroy( &clients_mutex );

        return 0;
    }
#endif /* NO_EXIT */

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client 
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
#ifndef NO_DAEMON
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }
#endif /* NO_DAEMON */

#ifndef NO_SERVICE
        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");
                return 0;
            }
        }
#endif /* NO_SERVICE */
#endif /* WIN32 */
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Initializing client(s)...\n" ) );
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        thread_Settings *into = NULL;
        // Create the settings structure for the reporter thread
        IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | REPORTER_DEBUG | IPERF_DBG_TRACE, ( "Creating the settings structure for the reporter thread.\n" ) );
        Settings_Copy( ext_gSettings, &into );
        into->mThreadMode = kMode_Reporter;

        // Have the reporter launch the client or listener
        IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Setting the reporter to launch the client or listener before launching itself.\n" ) );
        into->runNow = ext_gSettings;
        
        // Start all the threads that are ready to go
        IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting all the threads...\n" ) );
        thread_start( into );
#else
        // No need to make a reporter thread because we don't have threads
        IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting iperf in a single thread...\n" ) );
        thread_start( ext_gSettings );
#endif /* HAVE_THREAD */
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT((char *) SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

#ifndef NO_DAEMON
        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif /* NO_DAEMON */
#endif /* WIN32 */
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
//    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Waiting for other (client, server) threads to complete...\n" ) );
//    thread_joinall();
    
#ifdef NO_EXIT
	/* We can't run the atexit function */
#ifdef WIN32
    // Shutdown Winsock
    WSACleanup();
#endif /* WIN32 */
    // clean up the list of clients
    Iperf_destroy ( &clients );

    // shutdown the thread subsystem
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Deinitializing the thread subsystem.\n" ) );

    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) );
    Condition_Destroy( &ReportCond );
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) );
    Condition_Destroy( &ReportDoneCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) );
    Mutex_Destroy( &groupCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) );
    Mutex_Destroy( &clients_mutex );

#ifdef IPERF_DEBUG
    debug_init();
#endif /* IPERF_DEBUG */
#endif /* NO_EXIT */
	
    // all done!
    IPERF_DEBUGF( IPERF_DBG_TRACE | IPERF_DBG_STATE, ( "Done!\n" ) );
    return 0;
} // end main
// parseCommandLine ///////////////////////////////////////////////////////////
//
// check for command line parameters and set various flags 
//
void parseCommandLine (int *argc, char** argv[])
{
    /*
    // A little snipet of code to test the update feature.
    // Uncomment this code, compile, run mpd -update, then run mpd -loser to see if this new functionality exists
    if (GetOpt(*argc, *argv, "-loser"))
    {
	printf("you are a winner\n");
	ExitProcess(0);
    }
    //*/
    if (GetOpt(*argc, *argv, "-norestart"))
	bSetupRestart = false;
    if (GetOpt(*argc, *argv, "-interact"))
    {
	interact = true;
    }
    if (GetOpt(*argc, *argv, "-remove") || GetOpt(*argc, *argv, "-unregserver") || GetOpt(*argc, *argv, "-uninstall"))
    {
	RegDeleteKey(HKEY_CURRENT_USER, MPICHKEY);
	CmdRemoveService(TRUE);
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-install") || GetOpt(*argc, *argv, "-regserver"))
    {
	bool bMPDUserCapable = false;
	char account[100]="", password[100]="", phrase[MPD_PASSPHRASE_MAX_LENGTH+1]="", port[10]="";
	char version[100]="";

	if (CmdRemoveService(FALSE) == FALSE)
	{
	    printf("Unable to remove the previous installation, install failed.\n");
	    ExitProcess(0);
	}
	
	easy_socket_init();
	CreateMPDRegistry();
	bMPDUserCapable = GetOpt(*argc, *argv, "-mpduser");
	if (GetOpt(*argc, *argv, "-phrase", phrase))
	    WriteMPDRegistry("phrase", phrase);
	if (GetOpt(*argc, *argv, "-getphrase"))
	{
	    GetPassword("passphrase for mpd: ", NULL, phrase);
	    WriteMPDRegistry("phrase", phrase);
	}
	if (GetOpt(*argc, *argv, "-port", port))
	    WriteMPDRegistry("port", port);
	if (GetOpt(*argc, *argv, "-account", account))
	{
	    if (!GetOpt(*argc, *argv, "-password", password))
		GetPassword(NULL, account, password);
	    WriteMPDRegistry("SingleUser", "yes");
	    ParseRegistry(true);
	    CmdInstallService(account, password, bMPDUserCapable);
	}
	else
	{
	    WriteMPDRegistry("SingleUser", "no");
	    ParseRegistry(true);
	    CmdInstallService(NULL, NULL, bMPDUserCapable);
	}
	GetMPDVersion(version, 100);
	WriteMPDRegistry("version", version);
	easy_socket_finalize();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-update"))
    {
	char account[100]="", password[100]="", phrase[MPD_PASSPHRASE_MAX_LENGTH+1]="", port[10]="";
	int nPort;
	char pszHost[MAX_HOST_LENGTH], pszHostFile[MAX_PATH];
	char pszFileName[MAX_PATH];
	char pszError[256];

	if (!GetOpt(*argc, *argv, "-mpd", pszFileName))
	{
	    HMODULE hModule = GetModuleHandle(NULL);
	    if (!GetModuleFileName(hModule, pszFileName, MAX_PATH))
	    {
		printf("Please specify the location of the new mpd.exe with the -mpd option, (-mpd c:\\some\\path\\mpd.exe)\n");
		ExitProcess(0);
	    }
	    printf("updating mpd to '%s'\n", pszFileName);
	}
	if (!GetOpt(*argc, *argv, "-singleuser"))
	{
	    if (GetOpt(*argc, *argv, "-account", account))
	    {
		if (!GetOpt(*argc, *argv, "-password", password))
		    GetPassword(NULL, account, password);
	    }
	    else
	    {
		printf("Enter a user to connect to the remote machines as.\naccount: ");fflush(stdout);
		gets(account);
		GetPassword(NULL, account, password);
	    }
	}

	easy_socket_init();
	nPort = MPD_DEFAULT_PORT;
	if (!ReadMPDRegistry("phrase", phrase, false))
	    strcpy(phrase, MPD_DEFAULT_PASSPHRASE);
	GetOpt(*argc, *argv, "-phrase", phrase);
	if (GetOpt(*argc, *argv, "-getphrase"))
	{
	    GetPassword("passphrase for mpd: ", NULL, phrase);
	}
	if (GetOpt(*argc, *argv, "-port", port))
	    nPort = atoi(port);
	if (GetOpt(*argc, *argv, "-hostfile", pszHostFile))
	{
	    FILE *fin = fopen(pszHostFile, "r");
	    if (fin == NULL)
	    {
		char pszStr[1024];
		Translate_Error(GetLastError(), pszStr);
		printf("Unable to open the host file '%s', %s\n", pszHostFile, pszStr);
		easy_socket_finalize();
		ExitProcess(0);
	    }

	    while (GetNextHost(fin, pszHost))
	    {
		pszError[0] = '\0';
		if (!UpdateMPD(pszHost, account, password, nPort, phrase, pszFileName, pszError, 256))
		{
		    printf("Failed to update mpd on %s:\n%s\n", pszHost, pszError);
		}
	    }
	    fclose(fin);
	}
	else
	{
	    if (!GetOpt(*argc, *argv, "-host", pszHost))
	    {
		printf("Enter the hostname where the mpd that you wish to update is running.\nhost: ");fflush(stdout);
		gets(pszHost);
	    }
	    pszError[0] = '\0';
	    if (!UpdateMPD(pszHost, account, password, nPort, phrase, pszFileName, pszError, 256))
	    {
		printf("Failed to update mpd on %s:\n%s\n", pszHost, pszError);
	    }
	}

	easy_socket_finalize();
	printf("Finished.\n");
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-iupdate"))
    {
	// This option is used internally by the update feature
	char pszOldFileName[MAX_PATH], pszNewFileName[MAX_PATH];
	char pszPid[10];
	if (GetOpt(*argc, *argv, "-pid", pszPid) && 
	    GetOpt(*argc, *argv, "-old", pszOldFileName) && 
	    GetOpt(*argc, *argv, "-new", pszNewFileName))
	{
	    UpdateMPD(pszOldFileName, pszNewFileName, atoi(pszPid));
	}
	ExitProcess(0);
    }
    char host[100];
    if (GetOpt(*argc, *argv, "-console", host))
    {
	char phrase[MPD_PASSPHRASE_MAX_LENGTH+1];
	int port = -1;
	GetOpt(*argc, *argv, "-port", &port);
	/* DoConsole destroys phrase after using it */
	DoConsole(
	    host, port, 
	    GetOpt(*argc, *argv, "-getphrase"),
	    GetOpt(*argc, *argv, "-phrase", phrase) ? phrase : NULL);
	easy_socket_finalize();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-console"))
    {
	char phrase[MPD_PASSPHRASE_MAX_LENGTH+1];
	int port = -1;
	GetOpt(*argc, *argv, "-port", &port);
	/* DoConsole destroys phrase after using it */
	DoConsole(
	    NULL, port, 
	    GetOpt(*argc, *argv, "-getphrase"),
	    GetOpt(*argc, *argv, "-phrase", phrase) ? phrase : NULL);
	easy_socket_finalize();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-start"))
    {
	CmdStartService();
	ExitProcess(0);
    }
    char pszFileName[MAX_PATH];
    if (GetOpt(*argc, *argv, "-startdelete", pszFileName))
    {
	// This option is used by the update feature to start the new service and delete the old one.
	char version[100];
	// update the version
	GetMPDVersion(version, 100);
	WriteMPDRegistry("version", version);
	// start the new mpd
	CmdStartService();
	// Give the temporary mpd time to exit
	Sleep(1000);
	// Then delete it.
	DeleteFile(pszFileName);
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-stop"))
    {
	CmdStopService();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-restart", host))
    {
	ConnectAndRestart(argc, argv, host);
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-restart"))
    {
	CmdStopService();
	Sleep(1000);
	CmdStartService();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-clean"))
    {
	CleanMPDRegistry();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-d"))
    {
	char account[100]="", password[100]="", phrase[MPD_PASSPHRASE_MAX_LENGTH+1]="", pszPort[20]="";
	char str_temp[10];
	easy_socket_init();
	CreateMPDRegistry();
	if (GetOpt(*argc, *argv, "-phrase", phrase))
	    WriteMPDRegistry("phrase", phrase);
	if (GetOpt(*argc, *argv, "-getphrase"))
	{
	    GetPassword("passphrase for mpd: ", NULL, phrase);
	    WriteMPDRegistry("phrase", phrase);
	}
	if (GetOpt(*argc, *argv, "-port", pszPort))
	{
	    int g_nSavedPort = g_nPort;
	    g_nPort = atoi(pszPort);
	    if (g_nPort > 0)
	    {
		sprintf(pszPort, "%d", g_nPort);
		WriteMPDRegistry("port", pszPort);
		//printf("using port %d\n", g_nPort);
	    }
	    else
		g_nPort = g_nSavedPort;
	}
	g_bSingleUser = true;
	g_bStartAlone = GetOpt(*argc, *argv, "-startalone");
	if (ReadMPDRegistry("SingleUser", str_temp, false))
	{
	    if (stricmp(str_temp, "no") == 0)
	    {
		WriteMPDRegistry("RevertToMultiUser", "yes");
	    }
	}
	WriteMPDRegistry("SingleUser", "yes");

	ParseRegistry(true);
	CmdDebugService(*argc, *argv);
	easy_socket_finalize();
	ExitProcess(0);
    }
    if (GetOpt(*argc, *argv, "-v") || GetOpt(*argc, *argv, "-version"))
    {
/*#define USE_BAD_NONREDIRECTABLE_VERSION*/
#ifdef USE_BAD_NONREDIRECTABLE_VERSION
	/* stdin, stdout, stderr don't get redirected for some reason when I launch this application
	   with pipes for redirecting output.  If the HANDLE version of stderr is used like the code 
	   after the else, then everything works fine. */
	char str[100];
	GetMPDVersion(str, 100);
	fprintf(stderr, "\nMPD - mpich daemon for Microsoft Windows, version %s\n%s\n", str, COPYRIGHT);
	fflush(stderr);
	ExitProcess(0);
#else
	HANDLE hErr = GetStdHandle(STD_ERROR_HANDLE);
	char str[100], out[200];
	DWORD num_written;

	GetMPDVersion(str, 100);
	sprintf(out, "\nMPD - mpich daemon for Microsoft Windows, version %s\n%s\n", str, COPYRIGHT);
	WriteFile(hErr, out, strlen(out), &num_written, NULL);
	ExitProcess(0);
#endif
    }
    if (GetOpt(*argc, *argv, "-h") || GetOpt(*argc, *argv, "-?") || GetOpt(*argc, *argv, "-help"))
    {
	char str[100];
	GetMPDVersion(str, 100);
	fprintf(stderr, "\nMPD - mpich daemon for Windows NT, version %s\n%s\n", str, COPYRIGHT);
	fprintf(stderr, "Usage:\n  mpd [ -v -h -install -remove -console ]\n\nCommand line options:\n");
	fprintf(stderr, "  -install \t:install the service\n  -install -interact    :allows the mpd to interact with the desktop\n");
	fprintf(stderr, "  -install -mpduser\t:install the service with single user commands enabled.\n");
	fprintf(stderr, "  -remove\t:remove the service\n");
	fprintf(stderr, "  -v\t\t:display version\n");
	fprintf(stderr, "  -h\t\t:this help screen\n");
	fprintf(stderr, "  -console\t:start a console session with the mpd on the current host\n");
	fprintf(stderr, "  -console host [-port x] :start a console session with the mpd on 'host:port'\n");
	fprintf(stderr, "  -d\t\t:run the mpd from the console\n");
	ExitProcess(0);
    }
}
Ejemplo n.º 12
0
BOOL CPPgNTService::OnApply()
{
	if(m_bModified)
	{
		int b_installed;
		int  i_startupmode;
		int rights;
		// Startup with system, store in service.
		NTServiceGet(b_installed,i_startupmode,	rights);

		//MORPH START - Added by Stulle, Adjustable NT Service Strings
		CString strServiceName, strServiceDispName, strServiceDescr;
		GetDlgItem(IDC_SERVICE_NAME)->GetWindowText(strServiceName);
		GetDlgItem(IDC_SERVICE_DISP_NAME)->GetWindowText(strServiceDispName);
		GetDlgItem(IDC_SERVICE_DESCR)->GetWindowText(strServiceDescr);

		int iChangedStr = 0; // nothing changed
		if(strServiceName.Compare(thePrefs.GetServiceName()) != 0)
			iChangedStr = 1; // name under which we install changed, this is important!
		else if((strServiceDispName.Compare(thePrefs.GetServiceDispName()) != 0) || (strServiceDescr.Compare(thePrefs.GetServiceDescr()) != 0))
			iChangedStr = 2; // only visual strings changed, not so important...

		if(iChangedStr>0)
		{
			if(b_installed == 0)
			{
				thePrefs.SetServiceName(strServiceName);
				thePrefs.SetServiceDispName(strServiceDispName);
				thePrefs.SetServiceDescr(strServiceDescr);
				FillStatus();
			}
			else
			{
				int iResult = IDCANCEL;
				if(iChangedStr == 1)
					iResult = MessageBox(GetResString(IDS_SERVICE_NAME_CHANGED),GetResString(IDS_SERVICE_STR_CHANGED),MB_YESNOCANCEL|MB_ICONQUESTION|MB_DEFBUTTON3);
				else if(iChangedStr == 2)
				{
					if(NTServiceChangeDisplayStrings(strServiceDispName,strServiceDescr) != 0)
					{
						if(MessageBox(GetResString(IDS_SERVICE_DISP_CHANGE_FAIL),GetResString(IDS_SERVICE_STR_CHANGE_FAIL),MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDYES)
						{
							iChangedStr = 1;
							iResult = IDYES;
						}
					}
					else
						iResult = IDNO;
				}

				if(iChangedStr == 1 && iResult == IDYES) // reinstall service
				{
					if(CmdRemoveService()==0)
					{
						thePrefs.SetServiceName(strServiceName);
						thePrefs.SetServiceDispName(strServiceDispName);
						thePrefs.SetServiceDescr(strServiceDescr);
						if(CmdInstallService(i_startupmode == 1) != 0)
							MessageBox(GetResString(IDS_SERVICE_INSTALL_FAIL), GetResString(IDS_SERVICE_INSTALL_TITLE), MB_OK|MB_ICONWARNING);
					}
					else
					{
						MessageBox(GetResString(IDS_SERVICE_UNINSTALL_FAIL),GetResString(IDS_SERVICE_UNINSTALL_TITLE),MB_OK|MB_ICONWARNING);
						GetDlgItem(IDC_SERVICE_NAME)->SetWindowText(thePrefs.GetServiceName());
						GetDlgItem(IDC_SERVICE_DISP_NAME)->SetWindowText(thePrefs.GetServiceDispName());
						GetDlgItem(IDC_SERVICE_DESCR)->SetWindowText(thePrefs.GetServiceDescr());
					}
					FillStatus();
				}
				else if(iResult == IDNO) // just save settings
				{
					thePrefs.SetServiceName(strServiceName);
					thePrefs.SetServiceDispName(strServiceDispName);
					thePrefs.SetServiceDescr(strServiceDescr);
					FillStatus();
				}
				else // revert settings
				{
					GetDlgItem(IDC_SERVICE_NAME)->SetWindowText(thePrefs.GetServiceName());
					GetDlgItem(IDC_SERVICE_DISP_NAME)->SetWindowText(thePrefs.GetServiceDispName());
					GetDlgItem(IDC_SERVICE_DESCR)->SetWindowText(thePrefs.GetServiceDescr());
				}
			}
		}
		//MORPH END   - Added by Stulle, Adjustable NT Service Strings

		if (b_installed==1 && 
				(i_startupmode ==0 && (IsDlgButtonChecked(IDC_SVC_STARTWITHSYSTEM)==BST_CHECKED))||
				(i_startupmode ==1 && (IsDlgButtonChecked(IDC_SVC_MANUALSTART)==BST_CHECKED)))
			NTServiceSetStartupMode(IsDlgButtonChecked(IDC_SVC_STARTWITHSYSTEM)==BST_CHECKED);
	   // TODO: Apply setting 
		if ( IsDlgButtonChecked(IDC_SVC_RUNBROWSER)==BST_CHECKED)
		   thePrefs.m_iServiceStartupMode=1;
		else 
		   thePrefs.m_iServiceStartupMode=2;

		int iSel = m_cbOptLvl.GetCurSel();
		thePrefs.m_iServiceOptLvl = m_cbOptLvl.GetItemData(iSel);

		SetModified(FALSE);
		LoadSettings();
	}
	return CPropertyPage::OnApply();
}
Ejemplo n.º 13
0
int main(int argc, char* args[])
{
    SERVICE_TABLE_ENTRY dispatchTable[] =
    {
        {(wchar_t*)SZSERVICENAME, (LPSERVICE_MAIN_FUNCTION)service_main},
        {NULL, NULL}
    };

    if (argc > 1)
    {
        if (((args[1][0] == '-') || (args[1][0] == '/')))
        {
            if (!strcmp("install", args[1]+1))
            {
                bStop = FALSE;
                CmdInstallService(argc > 2);
                return 0;
            }
            else if (!strcmp("remove", args[1]+1))
            {
                bStop = TRUE;
                CmdRemoveService();
                return 0;
            }
            else
            {
                goto dispatch;
            }
        }
    }
    else
    {
        SC_HANDLE       schService = NULL;
        SC_HANDLE       schSCManager = NULL;
        SERVICE_STATUS  ssStatus;
        char buff[8];

        getDataFromRegistry(KEY_DELETE, buff);
        if (buff[0] == '+')
        {
            debug (D_NOTICE, "Called main while service is stopping!");
            return 1;
        }

        StartServiceCtrlDispatcher(dispatchTable);
        schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
        if (schSCManager)
        {
            schService = OpenService(schSCManager, SZSERVICENAME, SERVICE_ALL_ACCESS);
            if (schService)
            {
                debug(D_NOTICE, "called main function - no args");
                QueryServiceStatus(schService, &ssStatus);
                if (ssStatus.dwCurrentState != SERVICE_STOPPED)
                {
                    debug(D_NOTICE, "called main function - status %lu", ssStatus.dwCurrentState);
                    return 1;
                }
                if (StartService(schService, 0, NULL))
                {
                    printf("Starting %S.\n", SZSERVICEDISPLAYNAME);
                    Sleep(1000);
                    int retry = 5;
                    while(QueryServiceStatus(schService, &ssStatus) && retry)
                    {
                        --retry;
                        if (ssStatus.dwCurrentState == SERVICE_START_PENDING)
                            Sleep(1000);
                        else
                            break;
                    }
                    if (ssStatus.dwCurrentState == SERVICE_RUNNING)
                    {
                        printf("\n%S started.\n", SZSERVICENAME);
                    }
                    else
                    {
                        printf("\n%S failed to start.\n", SZSERVICENAME);
                    }
                }
                else
                {
                    printf("\nFailed to start %S.\n", SZSERVICENAME);
                }
                CloseServiceHandle(schService);
            }
            else
            {
                printf("Failed to load the service... \n");
                return 1;
            }
        }

        CloseServiceHandle(schSCManager);
        return 0;
    }

dispatch:
    printf("Usage\n"
           "  -install\t\tinstall the service\n"
           "  -remove \t\tremove the service\n");
    return 1;
}