1 // Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
3 // This file was part of the VNC system.
5 // The VNC system is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20 // If the source code for the VNC system is not available from the place
21 // whence you received this file, check http://www.uk.research.att.com/vnc or contact
22 // the authors on vnc@uk.research.att.com for information on obtaining it.
24 // This file has been adapted to the Win32 version of Bacula
25 // by Kern E. Sibbald. Many thanks to ATT and James Weatherall,
26 // the original author, for providing an excellent template.
28 // Copyright (C) 2000-2006 Kern E. Sibbald
34 // Implementation of service-oriented functionality of Bacula
35 // I.e. command line options that contact a running version of
36 // Bacula and ask it to do something (show about, show status,
41 #include "winbacula.h"
42 #include "winservice.h"
45 void set_service_description(SC_HANDLE hSCManager, SC_HANDLE hService,
48 // OS-SPECIFIC ROUTINES
50 // Create an instance of the bacService class to cause the static fields to be
51 // initialised properly
57 bacService::bacService()
59 OSVERSIONINFO osversioninfo;
60 osversioninfo.dwOSVersionInfoSize = sizeof(osversioninfo);
62 // Get the current OS version
63 if (!GetVersionEx(&osversioninfo)) {
66 g_platform_id = osversioninfo.dwPlatformId;
71 // IsWin95 - returns a BOOL indicating whether the current OS is Win95
75 return (g_platform_id == VER_PLATFORM_WIN32_WINDOWS);
78 // IsWinNT - returns a bool indicating whether the current OS is WinNT
82 return (g_platform_id == VER_PLATFORM_WIN32_NT);
85 // Internal routine to find the Bacula menu class window and
86 // post a message to it!
89 PostToBacula(UINT message, WPARAM wParam, LPARAM lParam)
91 // Locate the hidden Bacula menu window
92 HWND hservwnd = FindWindow(MENU_CLASS_NAME, NULL);
93 if (hservwnd == NULL) {
97 // Post the message to Bacula
98 PostMessage(hservwnd, message, wParam, lParam);
103 // Static routine to show the About dialog for a currently-running
104 // copy of Bacula, (usually a servicified version.)
107 bacService::ShowAboutBox()
109 // Post to the Bacula menu window
110 if (!PostToBacula(MENU_ABOUTBOX_SHOW, 0, 0)) {
111 MessageBox(NULL, _("No existing instance of Bacula File service could be contacted"), szAppName, MB_ICONEXCLAMATION | MB_OK);
117 // Static routine to show the Status dialog for a currently-running
118 // copy of Bacula, (usually a servicified version.)
121 bacService::ShowStatus()
123 // Post to the Bacula menu window
124 if (!PostToBacula(MENU_STATUS_SHOW, 0, 0)) {
125 MessageBox(NULL, _("No existing instance of Bacula File service could be contacted"), szAppName, MB_ICONEXCLAMATION | MB_OK);
131 // SERVICE-MODE ROUTINES
133 // Service-mode defines:
135 // Internal service name
136 #define BAC_SERVICENAME "Bacula-fd"
138 // Displayed service name
139 #define BAC_SERVICEDISPLAYNAME "Bacula File Server"
141 // List other required serves
142 #define BAC_DEPENDENCIES __TEXT("tcpip\0afd\0")
145 // Internal service state
146 SERVICE_STATUS g_srvstatus; // current status of the service
147 SERVICE_STATUS_HANDLE g_hstatus;
149 DWORD g_servicethread = 0;
150 char* g_errortext[256];
153 // Forward defines of internal service functions
154 void WINAPI ServiceMain(DWORD argc, char **argv);
155 DWORD WINAPI ServiceWorkThread(LPVOID lpwThreadParam);
157 void WINAPI ServiceCtrl(DWORD ctrlcode);
158 bool WINAPI CtrlHandler (DWORD ctrltype);
159 BOOL ReportStatus(DWORD state, DWORD exitcode, DWORD waithint);
161 // ROUTINE TO QUERY WHETHER THIS PROCESS IS RUNNING AS A SERVICE OR NOT
163 BOOL g_servicemode = FALSE;
166 bacService::RunningAsService()
168 return g_servicemode;
172 bacService::KillRunningCopy()
174 while (PostToBacula(WM_CLOSE, 0, 0)) {
180 // SERVICE MAIN ROUTINE
182 bacService::BaculaServiceMain()
184 // Mark that we are a service
185 g_servicemode = TRUE;
187 // How to run as a service depends upon the OS being used
188 switch (g_platform_id) {
191 case VER_PLATFORM_WIN32_WINDOWS:
193 // Obtain a handle to the kernel library
194 HINSTANCE kerneldll = LoadLibrary("KERNEL32.DLL");
195 if (kerneldll == NULL) {
196 MessageBox(NULL, _("KERNEL32.DLL not found: Bacula service not started"),
197 "Bacula Service", MB_OK);
201 // And find the RegisterServiceProcess function
202 DWORD (WINAPI *RegisterService)(DWORD, DWORD);
203 RegisterService = (DWORD (WINAPI *)(DWORD, DWORD))
204 GetProcAddress(kerneldll, "RegisterServiceProcess");
205 if (RegisterService == NULL) {
206 MessageBox(NULL, _("Registry service not found: Bacula service not started"),
207 "Bacula Service", MB_OK);
208 log_error_message(_("Registry service not found"));
212 // Register this process with the OS as a service!
213 RegisterService(0, 1);
215 // Run the main program as a service
218 // Then remove the service from the system service table
219 RegisterService(0, 0);
221 // Free the kernel library
222 FreeLibrary(kerneldll);
227 // Windows NT, Win2K, WinXP
228 case VER_PLATFORM_WIN32_NT:
230 // Create a service entry table
231 SERVICE_TABLE_ENTRY dispatchTable[] = {
232 {BAC_SERVICENAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
236 // Call the service control dispatcher with our entry table
237 if (!StartServiceCtrlDispatcher(dispatchTable)) {
238 log_error_message(_("StartServiceCtrlDispatcher failed."));
246 // SERVICE MAIN ROUTINE - NT ONLY !!!
247 // NT/Win2K/WinXP ONLY !!!
248 void WINAPI ServiceMain(DWORD argc, char **argv)
252 // Register the service control handler
253 g_hstatus = RegisterServiceCtrlHandler(BAC_SERVICENAME, ServiceCtrl);
255 if (g_hstatus == 0) {
256 log_error_message(_("RegisterServiceCtlHandler failed"));
257 MessageBox(NULL, _("Contact Register Service Handler failure"),
258 "Bacula service", MB_OK);
262 // Set up some standard service state values
263 g_srvstatus.dwServiceType = SERVICE_WIN32 | SERVICE_INTERACTIVE_PROCESS;
264 g_srvstatus.dwServiceSpecificExitCode = 0;
266 // Give this status to the SCM
268 SERVICE_START_PENDING, // Service state
269 NO_ERROR, // Exit code type
270 45000)) { // Hint as to how long Bacula should have hung before you assume error
272 ReportStatus(SERVICE_STOPPED, g_error, 0);
273 log_error_message(_("ReportStatus STOPPED failed 1"));
277 // Now start the service for real
278 (void)CreateThread(NULL, 0, ServiceWorkThread, NULL, 0, &dwThreadID);
282 // SERVICE START ROUTINE - thread that calls BaculaAppMain
284 DWORD WINAPI ServiceWorkThread(LPVOID lpwThreadParam)
287 // Save the current thread identifier
288 g_servicethread = GetCurrentThreadId();
290 // report the status to the service control manager.
293 SERVICE_RUNNING, // service state
294 NO_ERROR, // exit code
296 MessageBox(NULL, _("Report Service failure"), "Bacula Service", MB_OK);
297 log_error_message("ReportStatus RUNNING failed");
301 /* Call Bacula main code */
304 /* Mark that we're no longer running */
307 /* Tell the service manager that we've stopped */
308 ReportStatus(SERVICE_STOPPED, g_error, 0);
313 // SERVICE STOP ROUTINE - post a quit message to the relevant thread
316 // Post a quit message to the main service thread
317 if (g_servicethread != 0) {
318 PostThreadMessage(g_servicethread, WM_QUIT, 0, 0);
322 // SERVICE INSTALL ROUTINE
324 bacService::InstallService(const char *pszCmdLine)
326 const int pathlength = 2048;
327 char path[pathlength];
328 char servicecmd[pathlength];
331 // Get the filename of this executable
332 if (GetModuleFileName(NULL, path, pathlength-(strlen(BaculaRunService)+2)) == 0) {
333 MessageBox(NULL, _("Unable to install Bacula File service"), szAppName, MB_ICONEXCLAMATION | MB_OK);
337 // Append the service-start flag to the end of the path:
338 if ((int)strlen(path) + 5 + (int)strlen(BaculaRunService) + (int)strlen(pszCmdLine) < pathlength) {
339 sprintf(servicecmd, "\"%s\" %s %s", path, BaculaRunService, pszCmdLine);
341 log_error_message(_("Service command length too long"));
342 MessageBox(NULL, _("Service command length too long. Service not registered."),
343 szAppName, MB_ICONEXCLAMATION | MB_OK);
347 // How to add the Bacula service depends upon the OS
348 switch (g_platform_id) {
351 case VER_PLATFORM_WIN32_WINDOWS:
352 // Locate the RunService registry entry
354 if (RegCreateKey(HKEY_LOCAL_MACHINE,
355 "Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
356 &runservices) != ERROR_SUCCESS) {
357 log_error_message(_("Cannot write System Registry"));
358 MessageBox(NULL, _("The System Registry could not be updated - the Bacula service was not installed"), szAppName, MB_ICONEXCLAMATION | MB_OK);
362 // Attempt to add a Bacula key
363 if (RegSetValueEx(runservices, szAppName, 0, REG_SZ, (unsigned char *)servicecmd, strlen(servicecmd)+1) != ERROR_SUCCESS) {
364 RegCloseKey(runservices);
365 log_error_message(_("Cannot add Bacula key to System Registry"));
366 MessageBox(NULL, _("The Bacula service could not be installed"), szAppName, MB_ICONEXCLAMATION | MB_OK);
370 RegCloseKey(runservices);
372 // We have successfully installed the service!
375 _("The Bacula File service was successfully installed.\n"
376 "The service may be started by double clicking on the\n"
377 "Bacula \"Start\" icon and will be automatically\n"
378 "be run the next time this machine is rebooted. "),
380 MB_ICONINFORMATION | MB_OK);
384 // Windows NT, Win2K, WinXP
385 case VER_PLATFORM_WIN32_NT:
387 SC_HANDLE hsrvmanager;
389 // Open the default, local Service Control Manager database
390 hsrvmanager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
391 if (hsrvmanager == NULL) {
392 log_error_message("OpenSCManager failed");
394 _("The Service Control Manager could not be contacted - the Bacula service was not installed"),
395 szAppName, MB_ICONEXCLAMATION | MB_OK);
399 // Create an entry for the Bacula service
400 hservice = CreateService(
401 hsrvmanager, // SCManager database
402 BAC_SERVICENAME, // name of service
403 BAC_SERVICEDISPLAYNAME, // name to display
404 SERVICE_ALL_ACCESS, // desired access
405 SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
407 SERVICE_AUTO_START, // start type
408 SERVICE_ERROR_NORMAL, // error control type
409 servicecmd, // service's binary
410 NULL, // no load ordering group
411 NULL, // no tag identifier
412 BAC_DEPENDENCIES, // dependencies
413 NULL, // LocalSystem account
414 NULL); // no password
415 if (hservice == NULL) {
416 CloseServiceHandle(hsrvmanager);
417 log_error_message("CreateService failed");
419 _("The Bacula service could not be installed"),
420 szAppName, MB_ICONEXCLAMATION | MB_OK);
424 set_service_description(hsrvmanager,hservice,
425 _("Provides file backup and restore services. Bacula -- the network backup solution."));
427 CloseServiceHandle(hsrvmanager);
428 CloseServiceHandle(hservice);
430 // Everything went fine
433 _("The Bacula File service was successfully installed.\n"
434 "The service may be started from the Control Panel and will\n"
435 "automatically be run the next time this machine is rebooted."),
437 MB_ICONINFORMATION | MB_OK);
441 log_error_message("Unknown Windows System version");
443 _("Unknown Windows operating system.\n"
444 "Cannot install Bacula service.\n"),
445 szAppName, MB_ICONEXCLAMATION | MB_OK);
453 // SERVICE REMOVE ROUTINE
455 bacService::RemoveService()
457 // How to remove the Bacula service depends upon the OS
458 switch (g_platform_id) {
461 case VER_PLATFORM_WIN32_WINDOWS:
462 // Locate the RunService registry entry
464 if (RegOpenKey(HKEY_LOCAL_MACHINE,
465 "Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
466 &runservices) != ERROR_SUCCESS) {
468 _("Could not find registry entry.\nService probably not registerd - the Bacula service was not removed"), szAppName, MB_ICONEXCLAMATION | MB_OK);
470 // Attempt to delete the Bacula key
471 if (RegDeleteValue(runservices, szAppName) != ERROR_SUCCESS) {
472 RegCloseKey(runservices);
473 MessageBox(NULL, _("Could not delete Registry key.\nThe Bacula service could not be removed"), szAppName, MB_ICONEXCLAMATION | MB_OK);
476 RegCloseKey(runservices);
480 // Try to kill any running copy of Bacula
481 if (!KillRunningCopy()) {
483 _("Bacula could not be contacted, probably not running"),
484 szAppName, MB_ICONEXCLAMATION | MB_OK);
488 // We have successfully removed the service!
490 MessageBox(NULL, _("The Bacula service has been removed"), szAppName, MB_ICONINFORMATION | MB_OK);
494 // Windows NT, Win2K, WinXP
495 case VER_PLATFORM_WIN32_NT:
497 SC_HANDLE hsrvmanager;
500 hsrvmanager = OpenSCManager(
501 NULL, // machine (NULL == local)
502 NULL, // database (NULL == default)
503 SC_MANAGER_ALL_ACCESS // access required
506 hservice = OpenService(hsrvmanager, BAC_SERVICENAME, SERVICE_ALL_ACCESS);
507 if (hservice != NULL) {
508 SERVICE_STATUS status;
510 // Try to stop the Bacula service
511 if (ControlService(hservice, SERVICE_CONTROL_STOP, &status)) {
512 while(QueryServiceStatus(hservice, &status)) {
513 if (status.dwCurrentState == SERVICE_STOP_PENDING) {
520 if (status.dwCurrentState != SERVICE_STOPPED) {
521 MessageBox(NULL, _("The Bacula file service could not be stopped"), szAppName, MB_ICONEXCLAMATION | MB_OK);
525 // Now remove the service from the SCM
526 if (DeleteService(hservice)) {
528 MessageBox(NULL, _("The Bacula file service has been removed"), szAppName, MB_ICONINFORMATION | MB_OK);
531 MessageBox(NULL, _("The Bacula file service could not be removed"), szAppName, MB_ICONEXCLAMATION | MB_OK);
534 CloseServiceHandle(hservice);
536 MessageBox(NULL, _("The Bacula file service could not be found"), szAppName, MB_ICONEXCLAMATION | MB_OK);
539 CloseServiceHandle(hsrvmanager);
541 MessageBox(NULL, _("The SCM could not be contacted - the Bacula file service was not removed"), szAppName, MB_ICONEXCLAMATION | MB_OK);
548 // USEFUL SERVICE SUPPORT ROUTINES
550 // Service control routine
551 void WINAPI ServiceCtrl(DWORD ctrlcode)
553 // What control code have we been sent?
555 case SERVICE_CONTROL_STOP:
556 // STOP : The service must stop
557 g_srvstatus.dwCurrentState = SERVICE_STOP_PENDING;
561 case SERVICE_CONTROL_INTERROGATE:
562 // QUERY : Service control manager just wants to know our state
566 // Control code not recognised
570 // Tell the control manager what we're up to.
571 ReportStatus(g_srvstatus.dwCurrentState, NO_ERROR, 0);
574 // Service manager status reporting
575 BOOL ReportStatus(DWORD state,
579 static DWORD checkpoint = 1;
582 // If we're in the start state then we don't want the control manager
583 // sending us control messages because they'll confuse us.
584 if (state == SERVICE_START_PENDING) {
585 g_srvstatus.dwControlsAccepted = 0;
587 g_srvstatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
590 // Save the new status we've been given
591 g_srvstatus.dwCurrentState = state;
592 g_srvstatus.dwWin32ExitCode = exitcode;
593 g_srvstatus.dwWaitHint = waithint;
595 // Update the checkpoint variable to let the SCM know that we
596 // haven't died if requests take a long time
597 if ((state == SERVICE_RUNNING) || (state == SERVICE_STOPPED)) {
598 g_srvstatus.dwCheckPoint = 0;
600 g_srvstatus.dwCheckPoint = checkpoint++;
603 // Tell the SCM our new status
604 if (!(result = SetServiceStatus(g_hstatus, &g_srvstatus))) {
605 log_error_message(_("SetServiceStatus failed"));
612 void LogErrorMsg(char *message, char *fname, int lineno)
619 // Get the error code
620 g_error = GetLastError();
621 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
622 FORMAT_MESSAGE_FROM_SYSTEM,
630 // Use event logging to log the error
631 heventsrc = RegisterEventSource(NULL, BAC_SERVICENAME);
633 sprintf(msgbuff, _("\n\n%s error: %ld at %s:%d"),
634 BAC_SERVICENAME, g_error, fname, lineno);
635 strings[0] = msgbuff;
636 strings[1] = message;
639 if (heventsrc != NULL) {
643 heventsrc, // handle of event source
644 EVENTLOG_ERROR_TYPE, // event type
647 NULL, // current user's SID
648 3, // strings in 'strings'
649 0, // no bytes of raw data
650 (const char **)strings, // array of error strings
651 NULL); // no raw data
653 DeregisterEventSource(heventsrc);
657 typedef BOOL (WINAPI * WinAPI)(SC_HANDLE, DWORD, LPVOID);
659 void set_service_description(SC_HANDLE hSCManager, SC_HANDLE hService,
663 LPQUERY_SERVICE_LOCK_STATUS lpqslsBuf;
664 SERVICE_DESCRIPTION sdBuf;
666 WinAPI ChangeServiceDescription;
668 HINSTANCE hLib = LoadLibrary("ADVAPI32.DLL");
672 ChangeServiceDescription = (WinAPI)GetProcAddress(hLib,
673 "ChangeServiceConfig2A");
675 if (!ChangeServiceDescription) {
679 // Need to acquire database lock before reconfiguring.
680 sclLock = LockServiceDatabase(hSCManager);
682 // If the database cannot be locked, report the details.
683 if (sclLock == NULL) {
684 // Exit if the database is not locked by another process.
685 if (GetLastError() != ERROR_SERVICE_DATABASE_LOCKED) {
686 log_error_message("LockServiceDatabase");
690 // Allocate a buffer to get details about the lock.
691 lpqslsBuf = (LPQUERY_SERVICE_LOCK_STATUS)LocalAlloc(
692 LPTR, sizeof(QUERY_SERVICE_LOCK_STATUS)+256);
693 if (lpqslsBuf == NULL) {
694 log_error_message("LocalAlloc");
698 // Get and print the lock status information.
699 if (!QueryServiceLockStatus(
702 sizeof(QUERY_SERVICE_LOCK_STATUS)+256,
704 log_error_message("QueryServiceLockStatus");
707 if (lpqslsBuf->fIsLocked) {
708 printf(_("Locked by: %s, duration: %ld seconds\n"),
709 lpqslsBuf->lpLockOwner,
710 lpqslsBuf->dwLockDuration);
712 printf(_("No longer locked\n"));
715 LocalFree(lpqslsBuf);
716 log_error_message(_("Could not lock database"));
720 // The database is locked, so it is safe to make changes.
722 sdBuf.lpDescription = lpDesc;
724 if (!ChangeServiceDescription(
725 hService, // handle to service
726 SERVICE_CONFIG_DESCRIPTION, // change: description
727 &sdBuf) ) { // value: new description
728 log_error_message("ChangeServiceConfig2");
731 // Release the database lock.
732 UnlockServiceDatabase(sclLock);