+bool remove_service(void) {
+ manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
+ if(!manager) {
+ logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
+ return false;
+ }
+
+ service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
+
+ if(!service) {
+ logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
+ return false;
+ }
+
+ if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
+ logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
+ else
+ logger(LOG_INFO, "%s service stopped", identname);
+
+ if(!DeleteService(service)) {
+ logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
+ return false;
+ }
+
+ logger(LOG_INFO, "%s service removed", identname);
+
+ return true;
+}
+
+DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
+ switch(request) {
+ case SERVICE_CONTROL_INTERROGATE:
+ SetServiceStatus(statushandle, &status);
+ return NO_ERROR;
+ case SERVICE_CONTROL_STOP:
+ logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
+ break;
+ case SERVICE_CONTROL_SHUTDOWN:
+ logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
+ break;
+ default:
+ logger(LOG_WARNING, "Got unexpected request %d", request);
+ return ERROR_CALL_NOT_IMPLEMENTED;
+ }
+
+ if(running) {
+ running = false;
+ status.dwWaitHint = 30000;
+ status.dwCurrentState = SERVICE_STOP_PENDING;
+ SetServiceStatus(statushandle, &status);
+ return NO_ERROR;
+ } else {
+ status.dwWaitHint = 0;
+ status.dwCurrentState = SERVICE_STOPPED;
+ SetServiceStatus(statushandle, &status);
+ exit(1);
+ }
+
+}
+
+VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
+ int err = 1;
+ extern int main2(int argc, char **argv);
+
+
+ status.dwServiceType = SERVICE_WIN32;
+ status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
+ status.dwWin32ExitCode = 0;
+ status.dwServiceSpecificExitCode = 0;
+ status.dwCheckPoint = 0;
+
+ statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
+
+ if (!statushandle) {
+ logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
+ err = 1;
+ } else {
+ status.dwWaitHint = 30000;
+ status.dwCurrentState = SERVICE_START_PENDING;
+ SetServiceStatus(statushandle, &status);
+
+ status.dwWaitHint = 0;
+ status.dwCurrentState = SERVICE_RUNNING;
+ SetServiceStatus(statushandle, &status);
+
+ err = main2(argc, argv);
+
+ status.dwWaitHint = 0;
+ status.dwCurrentState = SERVICE_STOPPED;
+ //status.dwWin32ExitCode = err;
+ SetServiceStatus(statushandle, &status);
+ }