#include #include #include "server.h" #include "service.h" #include "client.h" SERVICE_STATUS gSvcStatus; SERVICE_STATUS_HANDLE gSvcStatusHandle; HANDLE ghSvcStopEvent = NULL; HANDLE ghExecuteService = NULL; int _tmain(int argc, TCHAR *argv[]) { SERVICE_TABLE_ENTRY DispatchTable[] = { {SVCNAME, (LPSERVICE_MAIN_FUNCTION)SvcMain}, {NULL, NULL} }; if (argc == 2) { if (lstrcmpi(argv[1], TEXT("-s")) == 0) { StartShellServer(); return 0; } else if (lstrcmpi(argv[1], TEXT("-sc")) == 0) { if (!StartServiceCtrlDispatcher(DispatchTable)) { printf("Error while starting Dispatcher Table : %d\n", GetLastError()); ERROR_FAILED_SERVICE_CONTROLLER_CONNECT; SvcReportEvent(TEXT("StartServiceCtrlDispatcher")); } } else { goto help_message; } } else if (argc == 3) { if (lstrcmpi(argv[1], TEXT("-c")) == 0) { StartShellClient(argv[2]); return 0; } // TODO: implement service else if (lstrcmpi(argv[1], TEXT("-s")) == 0 && lstrcmpi(argv[2], TEXT("-service")) == 0) { // CreateService SvcInstall(); return 0; } else { goto help_message; } } else { goto help_message; } return 0; help_message: printf("Wrong usage\nUsage: %s [-c {remote ip} | -s [-service]]\n", argv[0]); return -1; } VOID WINAPI SvcMain(DWORD dwArgc, LPTSTR* lpszArgv) { // Register the handler function for the service gSvcStatusHandle = RegisterServiceCtrlHandler(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); } DWORD WINAPI ServerThreadStart(LPDWORD dummy) { UNREFERENCED_PARAMETER(dummy); StartShellServer(); return 0; } VOID SvcInit(DWORD dwArgc, LPTSTR* lpszArgv) { ghSvcStopEvent = CreateEvent(NULL, // default security attributes TRUE, // manual reset event FALSE, // not signaled NULL); // no name if (ghSvcStopEvent == NULL) { ReportSvcStatus(SERVICE_STOPPED, GetLastError(), 0); return; } // Report running status when initialization is complete. ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0); ghExecuteService = CreateThread(NULL, 0, ServerThreadStart, NULL, 0, NULL); while (1) { // Check whether to stop the service. WaitForSingleObject(ghSvcStopEvent, INFINITE); TerminateThread(ghExecuteService, 0); ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0); return; } }