Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Service.cxx 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. *
  3. * This is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This software is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this software; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  16. * USA.
  17. */
  18. // -=- Service.cxx
  19. #include <rfb_win32/Service.h>
  20. #include <rfb_win32/MsgWindow.h>
  21. #include <rfb_win32/DynamicFn.h>
  22. #include <rfb_win32/ModuleFileName.h>
  23. #include <rfb_win32/Registry.h>
  24. #include <rfb_win32/OSVersion.h>
  25. #include <rfb/Threading.h>
  26. #include <logmessages/messages.h>
  27. #include <rdr/Exception.h>
  28. #include <rfb/LogWriter.h>
  29. using namespace rdr;
  30. using namespace rfb;
  31. using namespace win32;
  32. static LogWriter vlog("Service");
  33. // - Internal service implementation functions
  34. Service* service = 0;
  35. bool runAsService = false;
  36. VOID WINAPI serviceHandler(DWORD control) {
  37. switch (control) {
  38. case SERVICE_CONTROL_INTERROGATE:
  39. vlog.info("cmd: report status");
  40. service->setStatus();
  41. return;
  42. case SERVICE_CONTROL_PARAMCHANGE:
  43. vlog.info("cmd: param change");
  44. service->readParams();
  45. return;
  46. case SERVICE_CONTROL_SHUTDOWN:
  47. vlog.info("cmd: OS shutdown");
  48. service->osShuttingDown();
  49. return;
  50. case SERVICE_CONTROL_STOP:
  51. vlog.info("cmd: stop");
  52. service->setStatus(SERVICE_STOP_PENDING);
  53. service->stop();
  54. return;
  55. };
  56. vlog.debug("cmd: unknown %lu", control);
  57. }
  58. // -=- Message window derived class used under Win9x to implement stopService
  59. #define WM_SMSG_SERVICE_STOP WM_USER
  60. class ServiceMsgWindow : public MsgWindow {
  61. public:
  62. ServiceMsgWindow(const TCHAR* name) : MsgWindow(name) {}
  63. LRESULT processMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
  64. switch (msg) {
  65. case WM_SMSG_SERVICE_STOP:
  66. service->stop();
  67. return TRUE;
  68. }
  69. return MsgWindow::processMessage(msg, wParam, lParam);
  70. }
  71. static const TCHAR* baseName;
  72. };
  73. const TCHAR* ServiceMsgWindow::baseName = _T("ServiceWindow:");
  74. // -=- Service main procedure, used under WinNT/2K/XP by the SCM
  75. VOID WINAPI serviceProc(DWORD dwArgc, LPTSTR* lpszArgv) {
  76. vlog.debug("entering %s serviceProc", service->getName());
  77. vlog.info("registering handler...");
  78. service->status_handle = RegisterServiceCtrlHandler(service->getName(), serviceHandler);
  79. if (!service->status_handle) {
  80. DWORD err = GetLastError();
  81. vlog.error("failed to register handler: %lu", err);
  82. ExitProcess(err);
  83. }
  84. vlog.debug("registered handler (%lx)", service->status_handle);
  85. service->setStatus(SERVICE_START_PENDING);
  86. vlog.debug("entering %s serviceMain", service->getName());
  87. service->status.dwWin32ExitCode = service->serviceMain(dwArgc, lpszArgv);
  88. vlog.debug("leaving %s serviceMain", service->getName());
  89. service->setStatus(SERVICE_STOPPED);
  90. }
  91. // -=- Service
  92. Service::Service(const TCHAR* name_) : name(name_) {
  93. vlog.debug("Service");
  94. status_handle = 0;
  95. status.dwControlsAccepted = SERVICE_CONTROL_INTERROGATE | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP;
  96. status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
  97. status.dwWin32ExitCode = NO_ERROR;
  98. status.dwServiceSpecificExitCode = 0;
  99. status.dwCheckPoint = 0;
  100. status.dwWaitHint = 30000;
  101. status.dwCurrentState = SERVICE_STOPPED;
  102. }
  103. void
  104. Service::start() {
  105. if (osVersion.isPlatformNT) {
  106. SERVICE_TABLE_ENTRY entry[2];
  107. entry[0].lpServiceName = (TCHAR*)name;
  108. entry[0].lpServiceProc = serviceProc;
  109. entry[1].lpServiceName = NULL;
  110. entry[1].lpServiceProc = NULL;
  111. vlog.debug("entering dispatcher");
  112. if (!SetProcessShutdownParameters(0x100, 0))
  113. vlog.error("unable to set shutdown parameters: %d", GetLastError());
  114. service = this;
  115. if (!StartServiceCtrlDispatcher(entry))
  116. throw SystemException("unable to start service", GetLastError());
  117. } else {
  118. // - Create the service window, so the service can be stopped
  119. TCharArray wndName(_tcslen(getName()) + _tcslen(ServiceMsgWindow::baseName) + 1);
  120. _tcscpy(wndName.buf, ServiceMsgWindow::baseName);
  121. _tcscat(wndName.buf, getName());
  122. ServiceMsgWindow service_window(wndName.buf);
  123. // - Locate the RegisterServiceProcess function
  124. typedef DWORD (WINAPI * _RegisterServiceProcess_proto)(DWORD, DWORD);
  125. DynamicFn<_RegisterServiceProcess_proto> _RegisterServiceProcess(_T("kernel32.dll"), "RegisterServiceProcess");
  126. if (!_RegisterServiceProcess.isValid())
  127. throw Exception("unable to find RegisterServiceProcess");
  128. // - Run the service
  129. (*_RegisterServiceProcess)(NULL, 1);
  130. service = this;
  131. serviceMain(0, 0);
  132. (*_RegisterServiceProcess)(NULL, 0);
  133. }
  134. }
  135. void
  136. Service::setStatus() {
  137. setStatus(status.dwCurrentState);
  138. }
  139. void
  140. Service::setStatus(DWORD state) {
  141. if (!osVersion.isPlatformNT)
  142. return;
  143. if (status_handle == 0) {
  144. vlog.debug("warning - cannot setStatus");
  145. return;
  146. }
  147. status.dwCurrentState = state;
  148. status.dwCheckPoint++;
  149. if (!SetServiceStatus(status_handle, &status)) {
  150. status.dwCurrentState = SERVICE_STOPPED;
  151. status.dwWin32ExitCode = GetLastError();
  152. vlog.error("unable to set service status:%u", status.dwWin32ExitCode);
  153. }
  154. vlog.debug("set status to %u(%u)", state, status.dwCheckPoint);
  155. }
  156. Service::~Service() {
  157. vlog.debug("~Service");
  158. service = 0;
  159. }
  160. // Find out whether this process is running as the WinVNC service
  161. bool thisIsService() {
  162. return service && (service->status.dwCurrentState != SERVICE_STOPPED);
  163. }
  164. // -=- Desktop handling code
  165. // Switch the current thread to the specified desktop
  166. static bool
  167. switchToDesktop(HDESK desktop) {
  168. HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
  169. if (!SetThreadDesktop(desktop)) {
  170. vlog.debug("switchToDesktop failed:%u", GetLastError());
  171. return false;
  172. }
  173. if (!CloseDesktop(old_desktop))
  174. vlog.debug("unable to close old desktop:%u", GetLastError());
  175. return true;
  176. }
  177. // Determine whether the thread's current desktop is the input one
  178. static bool
  179. inputDesktopSelected() {
  180. HDESK current = GetThreadDesktop(GetCurrentThreadId());
  181. HDESK input = OpenInputDesktop(0, FALSE,
  182. DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
  183. DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
  184. DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
  185. DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
  186. if (!input) {
  187. vlog.debug("unable to OpenInputDesktop(1):%u", GetLastError());
  188. return false;
  189. }
  190. DWORD size;
  191. char currentname[256];
  192. char inputname[256];
  193. if (!GetUserObjectInformation(current, UOI_NAME, currentname, 256, &size)) {
  194. vlog.debug("unable to GetUserObjectInformation(1):%u", GetLastError());
  195. CloseDesktop(input);
  196. return false;
  197. }
  198. if (!GetUserObjectInformation(input, UOI_NAME, inputname, 256, &size)) {
  199. vlog.debug("unable to GetUserObjectInformation(2):%u", GetLastError());
  200. CloseDesktop(input);
  201. return false;
  202. }
  203. if (!CloseDesktop(input))
  204. vlog.debug("unable to close input desktop:%u", GetLastError());
  205. // *** vlog.debug("current=%s, input=%s", currentname, inputname);
  206. bool result = strcmp(currentname, inputname) == 0;
  207. return result;
  208. }
  209. // Switch the current thread into the input desktop
  210. static bool
  211. selectInputDesktop() {
  212. // - Open the input desktop
  213. HDESK desktop = OpenInputDesktop(0, FALSE,
  214. DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
  215. DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
  216. DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
  217. DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
  218. if (!desktop) {
  219. vlog.debug("unable to OpenInputDesktop(2):%u", GetLastError());
  220. return false;
  221. }
  222. // - Switch into it
  223. if (!switchToDesktop(desktop)) {
  224. CloseDesktop(desktop);
  225. return false;
  226. }
  227. // ***
  228. DWORD size = 256;
  229. char currentname[256];
  230. if (GetUserObjectInformation(desktop, UOI_NAME, currentname, 256, &size)) {
  231. vlog.debug("switched to %s", currentname);
  232. }
  233. // ***
  234. vlog.debug("switched to input desktop");
  235. return true;
  236. }
  237. // -=- Access points to desktop-switching routines
  238. bool
  239. rfb::win32::desktopChangeRequired() {
  240. if (!osVersion.isPlatformNT)
  241. return false;
  242. return !inputDesktopSelected();
  243. }
  244. bool
  245. rfb::win32::changeDesktop() {
  246. if (!osVersion.isPlatformNT)
  247. return true;
  248. if (osVersion.cannotSwitchDesktop)
  249. return false;
  250. return selectInputDesktop();
  251. }
  252. // -=- Ctrl-Alt-Del emulation
  253. class CADThread : public Thread {
  254. public:
  255. CADThread() : Thread("CtrlAltDel Emulator"), result(false) {}
  256. virtual void run() {
  257. HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
  258. if (switchToDesktop(OpenDesktop(_T("Winlogon"), 0, FALSE, DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
  259. DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
  260. DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
  261. DESKTOP_SWITCHDESKTOP | GENERIC_WRITE))) {
  262. PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG(MOD_ALT | MOD_CONTROL, VK_DELETE));
  263. switchToDesktop(old_desktop);
  264. result = true;
  265. }
  266. }
  267. bool result;
  268. };
  269. bool
  270. rfb::win32::emulateCtrlAltDel() {
  271. if (!osVersion.isPlatformNT)
  272. return false;
  273. if (osVersion.dwMajorVersion >= 6) {
  274. rfb::win32::Handle sessionEventCad =
  275. CreateEvent(0, FALSE, FALSE, "Global\\SessionEventTigerVNCCad");
  276. SetEvent(sessionEventCad);
  277. return true;
  278. }
  279. CADThread* cad_thread = new CADThread();
  280. vlog.debug("emulate Ctrl-Alt-Del");
  281. if (cad_thread) {
  282. cad_thread->start();
  283. cad_thread->join();
  284. bool result = cad_thread->result;
  285. delete cad_thread;
  286. return result;
  287. }
  288. return false;
  289. }
  290. // -=- Application Event Log target Logger class
  291. class Logger_EventLog : public Logger {
  292. public:
  293. Logger_EventLog(const TCHAR* srcname) : Logger("EventLog") {
  294. eventlog = RegisterEventSource(NULL, srcname);
  295. if (!eventlog)
  296. printf("Unable to open event log:%ld\n", GetLastError());
  297. }
  298. ~Logger_EventLog() {
  299. if (eventlog)
  300. DeregisterEventSource(eventlog);
  301. }
  302. virtual void write(int level, const char *logname, const char *message) {
  303. if (!eventlog) return;
  304. TStr log(logname), msg(message);
  305. const TCHAR* strings[] = {log, msg};
  306. WORD type = EVENTLOG_INFORMATION_TYPE;
  307. if (level == 0) type = EVENTLOG_ERROR_TYPE;
  308. if (!ReportEvent(eventlog, type, 0, VNC4LogMessage, NULL, 2, 0, strings, NULL)) {
  309. // *** It's not at all clear what is the correct behaviour if this fails...
  310. printf("ReportEvent failed:%ld\n", GetLastError());
  311. }
  312. }
  313. protected:
  314. HANDLE eventlog;
  315. };
  316. static Logger_EventLog* logger = 0;
  317. bool rfb::win32::initEventLogLogger(const TCHAR* srcname) {
  318. if (logger)
  319. return false;
  320. if (osVersion.isPlatformNT) {
  321. logger = new Logger_EventLog(srcname);
  322. logger->registerLogger();
  323. return true;
  324. } else {
  325. return false;
  326. }
  327. }
  328. // -=- Registering and unregistering the service
  329. bool rfb::win32::registerService(const TCHAR* name, const TCHAR* desc,
  330. int argc, char** argv) {
  331. // - Initialise the default service parameters
  332. const TCHAR* defaultcmdline;
  333. if (osVersion.isPlatformNT)
  334. defaultcmdline = _T("-service");
  335. else
  336. defaultcmdline = _T("-noconsole -service");
  337. // - Get the full pathname of our executable
  338. ModuleFileName buffer;
  339. // - Calculate the command-line length
  340. int cmdline_len = _tcslen(buffer.buf) + 4;
  341. int i;
  342. for (i=0; i<argc; i++) {
  343. cmdline_len += strlen(argv[i]) + 3;
  344. }
  345. // - Add the supplied extra parameters to the command line
  346. TCharArray cmdline(cmdline_len+_tcslen(defaultcmdline));
  347. _stprintf(cmdline.buf, _T("\"%s\" %s"), buffer.buf, defaultcmdline);
  348. for (i=0; i<argc; i++) {
  349. _tcscat(cmdline.buf, _T(" \""));
  350. _tcscat(cmdline.buf, TStr(argv[i]));
  351. _tcscat(cmdline.buf, _T("\""));
  352. }
  353. // - Register the service
  354. if (osVersion.isPlatformNT) {
  355. // - Open the SCM
  356. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  357. if (!scm)
  358. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  359. ServiceHandle service = CreateService(scm,
  360. name, desc, SC_MANAGER_ALL_ACCESS,
  361. SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
  362. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  363. cmdline.buf, NULL, NULL, NULL, NULL, NULL);
  364. if (!service)
  365. throw rdr::SystemException("unable to create service", GetLastError());
  366. // - Register the event log source
  367. RegKey hk, hk2;
  368. hk2.createKey(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"));
  369. hk.createKey(hk2, name);
  370. for (i=_tcslen(buffer.buf); i>0; i--) {
  371. if (buffer.buf[i] == _T('\\')) {
  372. buffer.buf[i+1] = 0;
  373. break;
  374. }
  375. }
  376. const TCHAR* dllFilename = _T("logmessages.dll");
  377. TCharArray dllPath(_tcslen(buffer.buf) + _tcslen(dllFilename) + 1);
  378. _tcscpy(dllPath.buf, buffer.buf);
  379. _tcscat(dllPath.buf, dllFilename);
  380. hk.setExpandString(_T("EventMessageFile"), dllPath.buf);
  381. hk.setInt(_T("TypesSupported"), EVENTLOG_ERROR_TYPE | EVENTLOG_INFORMATION_TYPE);
  382. } else {
  383. RegKey services;
  384. services.createKey(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\RunServices"));
  385. services.setString(name, cmdline.buf);
  386. }
  387. Sleep(500);
  388. return true;
  389. }
  390. bool rfb::win32::unregisterService(const TCHAR* name) {
  391. if (osVersion.isPlatformNT) {
  392. // - Open the SCM
  393. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  394. if (!scm)
  395. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  396. // - Create the service
  397. ServiceHandle service = OpenService(scm, name, SC_MANAGER_ALL_ACCESS);
  398. if (!service)
  399. throw rdr::SystemException("unable to locate the service", GetLastError());
  400. if (!DeleteService(service))
  401. throw rdr::SystemException("unable to remove the service", GetLastError());
  402. // - Register the event log source
  403. RegKey hk;
  404. hk.openKey(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"));
  405. hk.deleteKey(name);
  406. } else {
  407. RegKey services;
  408. services.openKey(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\RunServices"));
  409. services.deleteValue(name);
  410. }
  411. Sleep(500);
  412. return true;
  413. }
  414. // -=- Starting and stopping the service
  415. HWND findServiceWindow(const TCHAR* name) {
  416. TCharArray wndName(_tcslen(ServiceMsgWindow::baseName)+_tcslen(name)+1);
  417. _tcscpy(wndName.buf, ServiceMsgWindow::baseName);
  418. _tcscat(wndName.buf, name);
  419. vlog.debug("searching for %s window", wndName.buf);
  420. return FindWindow(0, wndName.buf);
  421. }
  422. bool rfb::win32::startService(const TCHAR* name) {
  423. if (osVersion.isPlatformNT) {
  424. // - Open the SCM
  425. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  426. if (!scm)
  427. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  428. // - Locate the service
  429. ServiceHandle service = OpenService(scm, name, SERVICE_START);
  430. if (!service)
  431. throw rdr::SystemException("unable to open the service", GetLastError());
  432. // - Start the service
  433. if (!StartService(service, 0, NULL))
  434. throw rdr::SystemException("unable to start the service", GetLastError());
  435. } else {
  436. // - Check there is no service window
  437. if (findServiceWindow(name))
  438. throw rdr::Exception("the service is already running");
  439. // - Find the RunServices registry key
  440. RegKey services;
  441. services.openKey(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\RunServices"));
  442. // - Read the command-line from it
  443. TCharArray cmdLine(services.getString(name));
  444. // - Start the service
  445. PROCESS_INFORMATION proc_info;
  446. STARTUPINFO startup_info;
  447. ZeroMemory(&startup_info, sizeof(startup_info));
  448. startup_info.cb = sizeof(startup_info);
  449. if (!CreateProcess(0, cmdLine.buf, 0, 0, FALSE, CREATE_NEW_CONSOLE, 0, 0, &startup_info, &proc_info)) {
  450. throw SystemException("unable to start service", GetLastError());
  451. }
  452. }
  453. Sleep(500);
  454. return true;
  455. }
  456. bool rfb::win32::stopService(const TCHAR* name) {
  457. if (osVersion.isPlatformNT) {
  458. // - Open the SCM
  459. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  460. if (!scm)
  461. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  462. // - Locate the service
  463. ServiceHandle service = OpenService(scm, name, SERVICE_STOP);
  464. if (!service)
  465. throw rdr::SystemException("unable to open the service", GetLastError());
  466. // - Start the service
  467. SERVICE_STATUS status;
  468. if (!ControlService(service, SERVICE_CONTROL_STOP, &status))
  469. throw rdr::SystemException("unable to stop the service", GetLastError());
  470. } else {
  471. // - Find the service window
  472. HWND service_window = findServiceWindow(name);
  473. if (!service_window)
  474. throw Exception("unable to locate running service");
  475. // Tell it to quit
  476. vlog.debug("sending service stop request");
  477. if (!SendMessage(service_window, WM_SMSG_SERVICE_STOP, 0, 0))
  478. throw Exception("unable to stop service");
  479. // Check it's quitting...
  480. DWORD process_id = 0;
  481. HANDLE process = 0;
  482. if (!GetWindowThreadProcessId(service_window, &process_id))
  483. throw SystemException("unable to verify service has quit", GetLastError());
  484. process = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, FALSE, process_id);
  485. if (!process)
  486. throw SystemException("unable to obtain service handle", GetLastError());
  487. int retries = 5;
  488. vlog.debug("checking status");
  489. while (retries-- && (WaitForSingleObject(process, 1000) != WAIT_OBJECT_0)) {}
  490. if (!retries) {
  491. vlog.debug("failed to quit - terminating");
  492. // May not have quit because of silly Win9x registry watching bug..
  493. if (!TerminateProcess(process, 1))
  494. throw SystemException("unable to terminate process!", GetLastError());
  495. throw Exception("service failed to quit - called TerminateProcess");
  496. }
  497. }
  498. Sleep(500);
  499. return true;
  500. }
  501. DWORD rfb::win32::getServiceState(const TCHAR* name) {
  502. if (osVersion.isPlatformNT) {
  503. // - Open the SCM
  504. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  505. if (!scm)
  506. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  507. // - Locate the service
  508. ServiceHandle service = OpenService(scm, name, SERVICE_INTERROGATE);
  509. if (!service)
  510. throw rdr::SystemException("unable to open the service", GetLastError());
  511. // - Get the service status
  512. SERVICE_STATUS status;
  513. if (!ControlService(service, SERVICE_CONTROL_INTERROGATE, (SERVICE_STATUS*)&status))
  514. throw rdr::SystemException("unable to query the service", GetLastError());
  515. return status.dwCurrentState;
  516. } else {
  517. HWND service_window = findServiceWindow(name);
  518. return service_window ? SERVICE_RUNNING : SERVICE_STOPPED;
  519. }
  520. }
  521. char* rfb::win32::serviceStateName(DWORD state) {
  522. switch (state) {
  523. case SERVICE_RUNNING: return strDup("Running");
  524. case SERVICE_STOPPED: return strDup("Stopped");
  525. case SERVICE_STOP_PENDING: return strDup("Stopping");
  526. };
  527. CharArray tmp(32);
  528. sprintf(tmp.buf, "Unknown (%lu)", state);
  529. return tmp.takeBuf();
  530. }
  531. bool rfb::win32::isServiceProcess() {
  532. return runAsService;
  533. }