You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Service.cxx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. #ifdef HAVE_CONFIG_H
  20. #include <config.h>
  21. #endif
  22. #include <rfb_win32/Service.h>
  23. #include <rfb_win32/MsgWindow.h>
  24. #include <rfb_win32/ModuleFileName.h>
  25. #include <rfb_win32/Registry.h>
  26. #include <rfb_win32/Handle.h>
  27. #include <logmessages/messages.h>
  28. #include <rdr/Exception.h>
  29. #include <rfb/LogWriter.h>
  30. using namespace rdr;
  31. using namespace rfb;
  32. using namespace win32;
  33. static LogWriter vlog("Service");
  34. // - Internal service implementation functions
  35. Service* service = 0;
  36. bool runAsService = false;
  37. VOID WINAPI serviceHandler(DWORD control) {
  38. switch (control) {
  39. case SERVICE_CONTROL_INTERROGATE:
  40. vlog.info("cmd: report status");
  41. service->setStatus();
  42. return;
  43. case SERVICE_CONTROL_PARAMCHANGE:
  44. vlog.info("cmd: param change");
  45. service->readParams();
  46. return;
  47. case SERVICE_CONTROL_SHUTDOWN:
  48. vlog.info("cmd: OS shutdown");
  49. service->osShuttingDown();
  50. return;
  51. case SERVICE_CONTROL_STOP:
  52. vlog.info("cmd: stop");
  53. service->setStatus(SERVICE_STOP_PENDING);
  54. service->stop();
  55. return;
  56. };
  57. vlog.debug("cmd: unknown %lu", control);
  58. }
  59. // -=- Service main procedure
  60. VOID WINAPI serviceProc(DWORD dwArgc, LPTSTR* lpszArgv) {
  61. vlog.debug("entering %s serviceProc", service->getName());
  62. vlog.info("registering handler...");
  63. service->status_handle = RegisterServiceCtrlHandler(service->getName(), serviceHandler);
  64. if (!service->status_handle) {
  65. DWORD err = GetLastError();
  66. vlog.error("failed to register handler: %lu", err);
  67. ExitProcess(err);
  68. }
  69. vlog.debug("registered handler (%p)", service->status_handle);
  70. service->setStatus(SERVICE_START_PENDING);
  71. vlog.debug("entering %s serviceMain", service->getName());
  72. service->status.dwWin32ExitCode = service->serviceMain(dwArgc, lpszArgv);
  73. vlog.debug("leaving %s serviceMain", service->getName());
  74. service->setStatus(SERVICE_STOPPED);
  75. }
  76. // -=- Service
  77. Service::Service(const TCHAR* name_) : name(name_) {
  78. vlog.debug("Service");
  79. status_handle = 0;
  80. status.dwControlsAccepted = SERVICE_CONTROL_INTERROGATE | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP;
  81. status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
  82. status.dwWin32ExitCode = NO_ERROR;
  83. status.dwServiceSpecificExitCode = 0;
  84. status.dwCheckPoint = 0;
  85. status.dwWaitHint = 30000;
  86. status.dwCurrentState = SERVICE_STOPPED;
  87. }
  88. void
  89. Service::start() {
  90. SERVICE_TABLE_ENTRY entry[2];
  91. entry[0].lpServiceName = (TCHAR*)name;
  92. entry[0].lpServiceProc = serviceProc;
  93. entry[1].lpServiceName = NULL;
  94. entry[1].lpServiceProc = NULL;
  95. vlog.debug("entering dispatcher");
  96. if (!SetProcessShutdownParameters(0x100, 0))
  97. vlog.error("unable to set shutdown parameters: %lu", GetLastError());
  98. service = this;
  99. if (!StartServiceCtrlDispatcher(entry))
  100. throw SystemException("unable to start service", GetLastError());
  101. }
  102. void
  103. Service::setStatus() {
  104. setStatus(status.dwCurrentState);
  105. }
  106. void
  107. Service::setStatus(DWORD state) {
  108. if (status_handle == 0) {
  109. vlog.debug("warning - cannot setStatus");
  110. return;
  111. }
  112. status.dwCurrentState = state;
  113. status.dwCheckPoint++;
  114. if (!SetServiceStatus(status_handle, &status)) {
  115. status.dwCurrentState = SERVICE_STOPPED;
  116. status.dwWin32ExitCode = GetLastError();
  117. vlog.error("unable to set service status:%lu", status.dwWin32ExitCode);
  118. }
  119. vlog.debug("set status to %lu(%lu)", state, status.dwCheckPoint);
  120. }
  121. Service::~Service() {
  122. vlog.debug("~Service");
  123. service = 0;
  124. }
  125. // Find out whether this process is running as the WinVNC service
  126. bool thisIsService() {
  127. return service && (service->status.dwCurrentState != SERVICE_STOPPED);
  128. }
  129. // -=- Desktop handling code
  130. // Switch the current thread to the specified desktop
  131. static bool
  132. switchToDesktop(HDESK desktop) {
  133. HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
  134. if (!SetThreadDesktop(desktop)) {
  135. vlog.debug("switchToDesktop failed:%lu", GetLastError());
  136. return false;
  137. }
  138. if (!CloseDesktop(old_desktop))
  139. vlog.debug("unable to close old desktop:%lu", GetLastError());
  140. return true;
  141. }
  142. // Determine whether the thread's current desktop is the input one
  143. static bool
  144. inputDesktopSelected() {
  145. HDESK current = GetThreadDesktop(GetCurrentThreadId());
  146. HDESK input = OpenInputDesktop(0, FALSE,
  147. DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
  148. DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
  149. DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
  150. DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
  151. if (!input) {
  152. vlog.debug("unable to OpenInputDesktop(1):%lu", GetLastError());
  153. return false;
  154. }
  155. DWORD size;
  156. char currentname[256];
  157. char inputname[256];
  158. if (!GetUserObjectInformation(current, UOI_NAME, currentname, 256, &size)) {
  159. vlog.debug("unable to GetUserObjectInformation(1):%lu", GetLastError());
  160. CloseDesktop(input);
  161. return false;
  162. }
  163. if (!GetUserObjectInformation(input, UOI_NAME, inputname, 256, &size)) {
  164. vlog.debug("unable to GetUserObjectInformation(2):%lu", GetLastError());
  165. CloseDesktop(input);
  166. return false;
  167. }
  168. if (!CloseDesktop(input))
  169. vlog.debug("unable to close input desktop:%lu", GetLastError());
  170. // *** vlog.debug("current=%s, input=%s", currentname, inputname);
  171. bool result = strcmp(currentname, inputname) == 0;
  172. return result;
  173. }
  174. // Switch the current thread into the input desktop
  175. static bool
  176. selectInputDesktop() {
  177. // - Open the input desktop
  178. HDESK desktop = OpenInputDesktop(0, FALSE,
  179. DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
  180. DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
  181. DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
  182. DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
  183. if (!desktop) {
  184. vlog.debug("unable to OpenInputDesktop(2):%lu", GetLastError());
  185. return false;
  186. }
  187. // - Switch into it
  188. if (!switchToDesktop(desktop)) {
  189. CloseDesktop(desktop);
  190. return false;
  191. }
  192. // ***
  193. DWORD size = 256;
  194. char currentname[256];
  195. if (GetUserObjectInformation(desktop, UOI_NAME, currentname, 256, &size)) {
  196. vlog.debug("switched to %s", currentname);
  197. }
  198. // ***
  199. vlog.debug("switched to input desktop");
  200. return true;
  201. }
  202. // -=- Access points to desktop-switching routines
  203. bool
  204. rfb::win32::desktopChangeRequired() {
  205. return !inputDesktopSelected();
  206. }
  207. bool
  208. rfb::win32::changeDesktop() {
  209. return selectInputDesktop();
  210. }
  211. // -=- Ctrl-Alt-Del emulation
  212. bool
  213. rfb::win32::emulateCtrlAltDel() {
  214. rfb::win32::Handle sessionEventCad =
  215. CreateEvent(0, FALSE, FALSE, "Global\\SessionEventTigerVNCCad");
  216. SetEvent(sessionEventCad);
  217. return true;
  218. }
  219. // -=- Application Event Log target Logger class
  220. class Logger_EventLog : public Logger {
  221. public:
  222. Logger_EventLog(const TCHAR* srcname) : Logger("EventLog") {
  223. eventlog = RegisterEventSource(NULL, srcname);
  224. if (!eventlog)
  225. printf("Unable to open event log:%ld\n", GetLastError());
  226. }
  227. ~Logger_EventLog() {
  228. if (eventlog)
  229. DeregisterEventSource(eventlog);
  230. }
  231. virtual void write(int level, const char *logname, const char *message) {
  232. if (!eventlog) return;
  233. TStr log(logname), msg(message);
  234. const TCHAR* strings[] = {log, msg};
  235. WORD type = EVENTLOG_INFORMATION_TYPE;
  236. if (level == 0) type = EVENTLOG_ERROR_TYPE;
  237. if (!ReportEvent(eventlog, type, 0, VNC4LogMessage, NULL, 2, 0, strings, NULL)) {
  238. // *** It's not at all clear what is the correct behaviour if this fails...
  239. printf("ReportEvent failed:%ld\n", GetLastError());
  240. }
  241. }
  242. protected:
  243. HANDLE eventlog;
  244. };
  245. static Logger_EventLog* logger = 0;
  246. bool rfb::win32::initEventLogLogger(const TCHAR* srcname) {
  247. if (logger)
  248. return false;
  249. logger = new Logger_EventLog(srcname);
  250. logger->registerLogger();
  251. return true;
  252. }
  253. // -=- Registering and unregistering the service
  254. bool rfb::win32::registerService(const TCHAR* name,
  255. const TCHAR* display,
  256. const TCHAR* desc,
  257. int argc, char** argv) {
  258. // - Initialise the default service parameters
  259. const TCHAR* defaultcmdline;
  260. defaultcmdline = _T("-service");
  261. // - Get the full pathname of our executable
  262. ModuleFileName buffer;
  263. // - Calculate the command-line length
  264. int cmdline_len = _tcslen(buffer.buf) + 4;
  265. int i;
  266. for (i=0; i<argc; i++) {
  267. cmdline_len += strlen(argv[i]) + 3;
  268. }
  269. // - Add the supplied extra parameters to the command line
  270. TCharArray cmdline(cmdline_len+_tcslen(defaultcmdline));
  271. _stprintf(cmdline.buf, _T("\"%s\" %s"), buffer.buf, defaultcmdline);
  272. for (i=0; i<argc; i++) {
  273. _tcscat(cmdline.buf, _T(" \""));
  274. _tcscat(cmdline.buf, TStr(argv[i]));
  275. _tcscat(cmdline.buf, _T("\""));
  276. }
  277. // - Register the service
  278. // - Open the SCM
  279. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  280. if (!scm)
  281. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  282. // - Add the service
  283. ServiceHandle service = CreateService(scm,
  284. name, display, SC_MANAGER_ALL_ACCESS,
  285. SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
  286. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  287. cmdline.buf, NULL, NULL, NULL, NULL, NULL);
  288. if (!service)
  289. throw rdr::SystemException("unable to create service", GetLastError());
  290. // - Set a description
  291. SERVICE_DESCRIPTION sdesc = {(LPTSTR)desc};
  292. ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &sdesc);
  293. // - Register the event log source
  294. RegKey hk, hk2;
  295. hk2.createKey(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"));
  296. hk.createKey(hk2, name);
  297. for (i=_tcslen(buffer.buf); i>0; i--) {
  298. if (buffer.buf[i] == _T('\\')) {
  299. buffer.buf[i+1] = 0;
  300. break;
  301. }
  302. }
  303. const TCHAR* dllFilename = _T("logmessages.dll");
  304. TCharArray dllPath(_tcslen(buffer.buf) + _tcslen(dllFilename) + 1);
  305. _tcscpy(dllPath.buf, buffer.buf);
  306. _tcscat(dllPath.buf, dllFilename);
  307. hk.setExpandString(_T("EventMessageFile"), dllPath.buf);
  308. hk.setInt(_T("TypesSupported"), EVENTLOG_ERROR_TYPE | EVENTLOG_INFORMATION_TYPE);
  309. Sleep(500);
  310. return true;
  311. }
  312. bool rfb::win32::unregisterService(const TCHAR* name) {
  313. // - Open the SCM
  314. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  315. if (!scm)
  316. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  317. // - Create the service
  318. ServiceHandle service = OpenService(scm, name, SC_MANAGER_ALL_ACCESS);
  319. if (!service)
  320. throw rdr::SystemException("unable to locate the service", GetLastError());
  321. if (!DeleteService(service))
  322. throw rdr::SystemException("unable to remove the service", GetLastError());
  323. // - Register the event log source
  324. RegKey hk;
  325. hk.openKey(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"));
  326. hk.deleteKey(name);
  327. Sleep(500);
  328. return true;
  329. }
  330. // -=- Starting and stopping the service
  331. bool rfb::win32::startService(const TCHAR* name) {
  332. // - Open the SCM
  333. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  334. if (!scm)
  335. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  336. // - Locate the service
  337. ServiceHandle service = OpenService(scm, name, SERVICE_START);
  338. if (!service)
  339. throw rdr::SystemException("unable to open the service", GetLastError());
  340. // - Start the service
  341. if (!StartService(service, 0, NULL))
  342. throw rdr::SystemException("unable to start the service", GetLastError());
  343. Sleep(500);
  344. return true;
  345. }
  346. bool rfb::win32::stopService(const TCHAR* name) {
  347. // - Open the SCM
  348. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  349. if (!scm)
  350. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  351. // - Locate the service
  352. ServiceHandle service = OpenService(scm, name, SERVICE_STOP);
  353. if (!service)
  354. throw rdr::SystemException("unable to open the service", GetLastError());
  355. // - Start the service
  356. SERVICE_STATUS status;
  357. if (!ControlService(service, SERVICE_CONTROL_STOP, &status))
  358. throw rdr::SystemException("unable to stop the service", GetLastError());
  359. Sleep(500);
  360. return true;
  361. }
  362. DWORD rfb::win32::getServiceState(const TCHAR* name) {
  363. // - Open the SCM
  364. ServiceHandle scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  365. if (!scm)
  366. throw rdr::SystemException("unable to open Service Control Manager", GetLastError());
  367. // - Locate the service
  368. ServiceHandle service = OpenService(scm, name, SERVICE_INTERROGATE);
  369. if (!service)
  370. throw rdr::SystemException("unable to open the service", GetLastError());
  371. // - Get the service status
  372. SERVICE_STATUS status;
  373. if (!ControlService(service, SERVICE_CONTROL_INTERROGATE, (SERVICE_STATUS*)&status))
  374. throw rdr::SystemException("unable to query the service", GetLastError());
  375. return status.dwCurrentState;
  376. }
  377. char* rfb::win32::serviceStateName(DWORD state) {
  378. switch (state) {
  379. case SERVICE_RUNNING: return strDup("Running");
  380. case SERVICE_STOPPED: return strDup("Stopped");
  381. case SERVICE_STOP_PENDING: return strDup("Stopping");
  382. };
  383. CharArray tmp(32);
  384. sprintf(tmp.buf, "Unknown (%lu)", state);
  385. return tmp.takeBuf();
  386. }
  387. bool rfb::win32::isServiceProcess() {
  388. return runAsService;
  389. }