1 const char w32_svrapi_rcs[] = "$Id$";
2 /*********************************************************************
6 * Purpose : Win32 Services API for Privoxy.
7 * Provides the implementation of an Win32 service to
8 * allow the code to directly register and run as a
9 * native Windows service application.
11 * Since Win9x/ME platforms don't provide or support
12 * running programs as services, this code uses runtime
13 * loading and calling of the Win32 Service API, to
14 * prevent the possibility of getting "entry point not
15 * found" type errors on unsupported platforms. This adds
16 * a little more complexity to the code, but it is worth
17 * doing to provide that isolation.
19 * Copyright : Written by and Copyright (C) 2003 members of
20 * the Privoxy team. http://www.privoxy.org/
22 * Written by and Copyright (C) 2003 Ian Cummings
23 * <ian_a_c@hotmail.com>
25 * Special thanks to Mates Dolák <matesek@post.cz> for
26 * some very helpful feedback and suggestions during the
27 * development of this code.
29 * This program is free software; you can redistribute it
30 * and/or modify it under the terms of the GNU General
31 * Public License as published by the Free Software
32 * Foundation; either version 2 of the License, or (at
33 * your option) any later version.
35 * This program is distributed in the hope that it will
36 * be useful, but WITHOUT ANY WARRANTY; without even the
37 * implied warranty of MERCHANTABILITY or FITNESS FOR A
38 * PARTICULAR PURPOSE. See the GNU General Public
39 * License for more details.
41 * The GNU General Public License should be included with
42 * this file. If not, you can view it at
43 * http://www.gnu.org/copyleft/gpl.html
44 * or write to the Free Software Foundation, Inc., 59
45 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
51 *********************************************************************/
68 #endif /* ndef _WIN_CONSOLE */
70 #include "w32svrapi.h"
71 const char w32_svrapi_h_rcs[] = W32_SVRAPI_H_VERSION;
74 /* Only the ANSI Win32 APIs are used at this time. If for some
75 * reason, we're building under unicode then we must stop
78 #error "Privoxy interface to Win32 Services only runs under ANSI builds. Unicode is not supported at present, but you can volunteer for the job if you like! :)"
82 /* Default to not running as service, unless the command line says so */
83 BOOL bRunAsService = FALSE;
85 /* According to the Win32 docs for CreateService,
86 * the max length for the service name is 256 chars
88 char szThisServiceName[260];
90 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize);
91 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* psz);
92 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode);
93 SERVICE_TABLE_ENTRY w32ServiceDispatchTable[] = {{"", privoxy_w32_service_start}, {NULL, NULL}};
94 static SERVICE_STATUS_HANDLE hSrv_status = 0;
95 static SERVICE_STATUS srv_status;
99 /*********************************************************************
100 * This function returns TRUE if we are running on an OS that can
101 * support services, like NT, etc. It returns FALSE for Win9x/ME.
102 *********************************************************************/
103 static BOOL HasServiceControlManager()
109 /* Load the DLL with the SCM functions or return a failure status */
110 hDll = LoadLibrary("Advapi32.dll");
113 printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
117 /* Get the address of the ANSI OpenSCManager function, or return a failure status */
118 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
121 printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
126 /* Try and connect to the SCM. If it fails check and see if the error
127 * code is ERROR_CALL_NOT_IMPLEMENTED, which means:
128 * "This function is not supported on this system."
130 hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
133 DWORD dwErr = GetLastError();
134 if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
136 /* Expected error under Win9x/Me, so don't print any debug info
137 * here as we'll leave that up to the calling function to do
143 printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
148 w32_close_service_handle(hScm);
150 /* OpenSCManager function exists and works, so we're on an NT type platform */
155 } /* -END- HasServiceControlManager */
158 BOOL CanSystemSupportServices()
160 BOOL bHasScm = HasServiceControlManager();
163 } /* -END- CanSystemSupportServices */
167 /*********************************************************************
169 * The Service functions are defined in <winsvc.h> which is where
170 * the declarations used in this file are taken from
172 *********************************************************************/
175 /*********************************************************************
176 * Open a connection to the service control manager
177 *********************************************************************/
178 SC_HANDLE w32_open_sc_manager(
179 LPCTSTR lpMachineName, /* computer name */
180 LPCTSTR lpDatabaseName, /* SCM database name */
181 DWORD dwDesiredAccess) /* access type */
184 SC_HANDLE hScm = NULL;
185 FARPROC pFunc = NULL;
188 /* Load the DLL with the SCM functions or return failure */
189 hDll = LoadLibrary("Advapi32.dll");
195 /* Get the address of the ANSI OpenSCManager function, or return failure */
196 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
203 /* Call the SCM function, and save the error code */
204 hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
205 dwLastErr = GetLastError();
207 /* Release the library and then restore the last error
208 * code, in case FreeLibrary altered it.
211 SetLastError(dwLastErr);
215 } /* -END- w32_open_sc_manager */
219 BOOL w32_close_service_handle(
220 SC_HANDLE hSCObject) /* handle to service or SCM object */
223 FARPROC pFunc = NULL;
227 /* Load the DLL with the SCM functions or return a failure status */
228 hDll = LoadLibrary("Advapi32.dll");
234 /* Get the address of the CloseServiceHandle function, or return a failure status */
235 pFunc = GetProcAddress(hDll, "CloseServiceHandle");
242 /* Close the handle, and save the error code */
243 bRet = (BOOL)(*pFunc)(hSCObject);
244 dwLastErr = GetLastError();
246 /* Release the library and then restore the last error
247 * code, in case FreeLibrary altered it.
250 SetLastError(dwLastErr);
254 } /* -END- w32_close_service_handle */
258 /*********************************************************************
260 *********************************************************************/
261 SC_HANDLE w32_open_service(
262 SC_HANDLE hSCManager, /* handle to SCM database */
263 LPCTSTR lpServiceName, /* service name */
264 DWORD dwDesiredAccess) /* access */
267 SC_HANDLE hSrv = NULL;
268 FARPROC pFunc = NULL;
271 /* Load the DLL with the SCM functions or return failure */
272 hDll = LoadLibrary("Advapi32.dll");
278 /* Get the address of the ANSI OpenService function, or return failure */
279 pFunc = GetProcAddress(hDll, "OpenServiceA");
286 /* Call the SCM function, and save the error code */
287 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
288 dwLastErr = GetLastError();
290 /* Release the library and then restore the last error
291 * code, in case FreeLibrary altered it.
294 SetLastError(dwLastErr);
298 } /* -END- w32_open_service */
302 SC_HANDLE w32_create_service(
303 SC_HANDLE hSCManager, /* handle to SCM database */
304 LPCTSTR lpServiceName, /* name of service to start */
305 LPCTSTR lpDisplayName, /* display name */
306 DWORD dwDesiredAccess, /* type of access to service */
307 DWORD dwServiceType, /* type of service */
308 DWORD dwStartType, /* when to start service */
309 DWORD dwErrorControl, /* severity of service failure */
310 LPCTSTR lpBinaryPathName, /* name of binary file */
311 LPCTSTR lpLoadOrderGroup, /* name of load ordering group */
312 LPDWORD lpdwTagId, /* tag identifier */
313 LPCTSTR lpDependencies, /* array of dependency names */
314 LPCTSTR lpServiceStartName, /* account name */
315 LPCTSTR lpPassword) /* account password */
318 SC_HANDLE hSrv = NULL;
319 FARPROC pFunc = NULL;
322 /* Load the DLL with the SCM functions or return failure */
323 hDll = LoadLibrary("Advapi32.dll");
329 /* Get the address of the ANSI CreateService function, or return failure */
330 pFunc = GetProcAddress(hDll, "CreateServiceA");
337 /* Call the SCM function, and save the error code */
338 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, /* handle to SCM database */
339 lpServiceName, /* name of service to start */
340 lpDisplayName, /* display name */
341 dwDesiredAccess, /* type of access to service */
342 dwServiceType, /* type of service */
343 dwStartType, /* when to start service */
344 dwErrorControl, /* severity of service failure */
345 lpBinaryPathName, /* name of binary file */
346 lpLoadOrderGroup, /* name of load ordering group */
347 lpdwTagId, /* tag identifier */
348 lpDependencies, /* array of dependency names */
349 lpServiceStartName, /* account name */
350 lpPassword); /* account password */
351 dwLastErr = GetLastError();
353 /* Release the library and then restore the last error
354 * code, in case FreeLibrary altered it.
357 SetLastError(dwLastErr);
361 } /* -END- w32_create_service */
365 BOOL w32_delete_service(
366 SC_HANDLE hService) /* handle to service */
369 FARPROC pFunc = NULL;
373 /* Load the DLL with the SCM functions or return a failure status */
374 hDll = LoadLibrary("Advapi32.dll");
380 /* Get the address of the DeleteService function, or return a failure status */
381 pFunc = GetProcAddress(hDll, "DeleteService");
388 /* Close the handle, and save the error code */
389 bRet = (BOOL)(*pFunc)(hService);
390 dwLastErr = GetLastError();
392 /* Release the library and then restore the last error
393 * code, in case FreeLibrary altered it.
396 SetLastError(dwLastErr);
400 } /* -END- w32_delete_service */
404 BOOL w32_query_service_config(
405 SC_HANDLE hService, /* handle to service */
406 LPQUERY_SERVICE_CONFIG lpServiceConfig, /* buffer */
407 DWORD cbBufSize, /* size of buffer */
408 LPDWORD pcbBytesNeeded) /* bytes needed */
411 FARPROC pFunc = NULL;
415 /* Load the DLL with the SCM functions or return a failure status */
416 hDll = LoadLibrary("Advapi32.dll");
422 /* Get the address of the QueryServiceConfig function, or return a failure status */
423 pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
430 /* Close the handle, and save the error code */
431 bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
432 dwLastErr = GetLastError();
434 /* Release the library and then restore the last error
435 * code, in case FreeLibrary altered it.
438 SetLastError(dwLastErr);
442 } /* -END- w32_query_service_config */
445 BOOL w32_start_service_ctrl_dispatcher(
446 CONST LPSERVICE_TABLE_ENTRY lpServiceTable) /* service table */
449 FARPROC pFunc = NULL;
453 /* Load the DLL with the SCM functions or return a failure status */
454 hDll = LoadLibrary("Advapi32.dll");
460 /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
461 pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
468 /* Close the handle, and save the error code */
469 bRet = (BOOL)(*pFunc)(lpServiceTable);
470 dwLastErr = GetLastError();
472 /* Release the library and then restore the last error
473 * code, in case FreeLibrary altered it.
476 SetLastError(dwLastErr);
480 } /* -END- w32_start_service_ctrl_dispatcher */
484 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
485 LPCTSTR lpServiceName, /* service name */
486 LPHANDLER_FUNCTION lpHandlerProc) /* handler function */
489 FARPROC pFunc = NULL;
493 /* Load the DLL with the SCM functions or return a failure status */
494 hDll = LoadLibrary("Advapi32.dll");
500 /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
501 pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
508 /* Close the handle, and save the error code */
509 bRet = (BOOL)(*pFunc)(lpServiceName, lpHandlerProc);
510 dwLastErr = GetLastError();
512 /* Release the library and then restore the last error
513 * code, in case FreeLibrary altered it.
516 SetLastError(dwLastErr);
520 } /* -END- w32_register_service_ctrl_handler */
524 BOOL w32_set_service_status(
525 SERVICE_STATUS_HANDLE hServiceStatus, /* service status handle */
526 LPSERVICE_STATUS lpServiceStatus) /* status buffer */
529 FARPROC pFunc = NULL;
533 /* Load the DLL with the SCM functions or return a failure status */
534 hDll = LoadLibrary("Advapi32.dll");
540 /* Get the address of the SetServiceStatus function, or return a failure status */
541 pFunc = GetProcAddress(hDll, "SetServiceStatus");
548 /* Close the handle, and save the error code */
549 bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
550 dwLastErr = GetLastError();
552 /* Release the library and then restore the last error
553 * code, in case FreeLibrary altered it.
556 SetLastError(dwLastErr);
560 } /* -END- w32_set_service_status */
563 static void display_win32_msg(BOOL bIsError, char *msg)
570 MessageBox(NULL, msg, "Privoxy Error",
571 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
575 MessageBox(NULL, msg, "Privoxy Information",
576 MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
580 } /* -END- display_win32_msg */
583 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
585 /*********************************************************************
586 * Create a simple display name
587 *********************************************************************/
588 strcpy(pszDisplayName, "Privoxy (");
589 strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
590 strcat(pszDisplayName, ")");
597 BOOL install_service(const char *service_name)
599 char szModule[(MAX_PATH*2)+1];
600 char szDisplayName[MAX_PATH+2];
604 /*********************************************************************
605 * First check if this system can support a service architecture
606 *********************************************************************/
607 if (!CanSystemSupportServices())
609 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
613 /* Use a default service name if none was supplied */
614 if ((service_name == NULL) || (strlen(service_name) == 0))
616 service_name = "privoxy";
619 /*********************************************************************
620 * Open a handle to the Service Control Manager with full access rights
621 *********************************************************************/
622 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
625 display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n Administrator rights are required to create a service.\n");
630 /*********************************************************************
631 * Work out the full image path plus command line for the service
632 * We'll temporarily use szDisplayName as a second buffer.
633 *********************************************************************/
634 GetModuleFileName(NULL, szDisplayName, MAX_PATH);
635 sprintf(szModule, "\"%s\" --service", szDisplayName);
638 /*********************************************************************
639 * Get the display name for the service
640 *********************************************************************/
641 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
644 /*********************************************************************
646 *********************************************************************/
647 hService = w32_create_service(hSCM,
648 service_name, /* the internal service name */
649 szDisplayName, /* the display name */
650 SERVICE_ALL_ACCESS, /* get full access during creation */
651 SERVICE_WIN32_OWN_PROCESS /* run in our own process */
653 + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
656 SERVICE_DEMAND_START, /* For now, only start when asked to */
657 SERVICE_ERROR_NORMAL, /* Normal error handling by the SCM */
658 szModule, /* The executable service file */
659 NULL, /* No load order info needed */
660 NULL, /* No load order info needed */
661 NULL, /* No dependencies */
662 NULL, /* Default to LocalSystem... */
663 NULL); /* ...which doesn't require a password */
664 if (hService == NULL)
666 display_win32_msg(TRUE, "Can't install service!\n");
667 w32_close_service_handle(hSCM);
671 display_win32_msg(FALSE, "Service was successfully created.\n*** IMPORTANT NOTE: You should now use the Services control panel to\n*** configure the startup type and user account details for the service.\n\n");
674 w32_close_service_handle(hService);
675 w32_close_service_handle(hSCM);
678 } /* -END- install_service */
682 BOOL uninstall_service(const char *service_name)
684 char szDisplayName[MAX_PATH+2];
687 BOOL bResult = FALSE;
690 /*********************************************************************
691 * First check if this system can support a service architecture
692 *********************************************************************/
693 if (!CanSystemSupportServices())
695 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
700 /* Use a default service name if none was supplied */
701 if ((service_name == NULL) || (strlen(service_name) == 0))
703 service_name = "privoxy";
707 /*********************************************************************
708 * Open a handle to the Service Control Manager with full access rights
709 *********************************************************************/
710 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
713 display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n Administrator rights are required to delete a service.\n");
718 /*********************************************************************
719 * Get the display name for the service
720 *********************************************************************/
721 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
724 /*********************************************************************
725 * Open and then delete the service
726 *********************************************************************/
727 hService = w32_open_service(hSCM, service_name, DELETE);
728 if (hService == NULL)
730 display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
731 w32_close_service_handle(hSCM);
735 if (w32_delete_service(hService))
737 display_win32_msg(FALSE, "Service was deleted successfully.\n");
742 display_win32_msg(TRUE, "Service could not be deleted!\n");
746 w32_close_service_handle(hService);
747 w32_close_service_handle(hSCM);
750 } /* -END- uninstall_service */
754 /*********************************************************************
756 * Function : privoxy_w32_service_start
758 * Description : This is the entry point function for the service.
759 * In other words, it's the ServiceMain function.
761 * Parameters : Defined by the Win32 API, but not used here
765 *********************************************************************/
766 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
770 /* Arg zero is always the service name, and we need to
771 * know it when we call RegisterServiceCtrlHandler.
773 strcpy(szThisServiceName, pszArgs[0]);
775 /* Tell the SCM we are running */
776 srv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
777 srv_status.dwCurrentState = SERVICE_RUNNING;
778 srv_status.dwCheckPoint = 0;
779 srv_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
780 srv_status.dwWin32ExitCode = NO_ERROR;
781 srv_status.dwServiceSpecificExitCode = 0;
782 srv_status.dwWaitHint = 0;
784 hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
789 w32_set_service_status(hSrv_status, &srv_status);
791 #ifndef FEATURE_PTHREAD
792 child_id = _beginthread(w32_service_listen_loop, 0, NULL);
795 #error "FIXME: Do pthread stuff here!"
798 w32_set_service_status(hSrv_status, &srv_status);
802 srv_status.dwCurrentState = SERVICE_STOPPED;
803 srv_status.dwCheckPoint = 0;
804 srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
805 srv_status.dwServiceSpecificExitCode = ERROR_SERVICE_NO_THREAD;
806 w32_set_service_status(hSrv_status, &srv_status);
811 /*********************************************************************
813 * Function : w32_set_service_cwd
815 * Description : Simple function to change the current directory to
816 * the same location as the service executable.
822 *********************************************************************/
823 void w32_set_service_cwd(void)
825 char exe_name[MAX_PATH+1];
826 char dir_name[MAX_PATH+1];
827 char *pszFile = NULL;
829 /* Get the exe name and path of the service */
830 if (GetModuleFileName(NULL, exe_name, MAX_PATH))
832 /* Ask the API to tell us where the filename portion starts */
833 if (GetFullPathName(exe_name, MAX_PATH, dir_name, &pszFile))
835 /* remove the filename from the string */
839 /* We have just a directory path now, so make it current */
840 SetCurrentDirectory(dir_name);
847 /*********************************************************************
849 * Function : w32_service_exit_notify
851 * Description : This is a simple atexit function that is called by the
852 * C runtime after exit has been called. It allows the
853 * service code to detect when the app is about to die and
854 * send an quick notification to the SCM that the service
861 *********************************************************************/
862 void w32_service_exit_notify(void)
864 if (hSrv_status != 0)
866 if (srv_status.dwCurrentState != SERVICE_STOPPED)
868 srv_status.dwCurrentState = SERVICE_STOPPED;
869 srv_status.dwCheckPoint = 0;
870 srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
871 srv_status.dwServiceSpecificExitCode = ERROR_PROCESS_ABORTED;
872 w32_set_service_status(hSrv_status, &srv_status);
878 static void w32_mini_exit(void *p)
884 PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
885 #endif /* def _WIN_CONSOLE */
889 /*********************************************************************
891 * Function : privoxy_w32_service_handler
893 * Description : This is the control message handler function for
896 * Parameters : dwOpcode
897 * requested control code sent by SCM
901 *********************************************************************/
902 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode)
906 case SERVICE_CONTROL_STOP:
909 srv_status.dwCurrentState = SERVICE_STOPPED;
910 srv_status.dwCheckPoint = 0;
911 srv_status.dwWin32ExitCode = NO_ERROR;
912 srv_status.dwServiceSpecificExitCode = 0;
914 /* Maybe there is a more friendly way to stop, but this will do for now! */
915 w32_set_service_status(hSrv_status, &srv_status);
917 /* During testing, I kept getting error 109 (ERROR_BROKEN_PIPE) and
918 * as far as the SCM was concerned the service was still stopping,
919 * even after the process had disappeared.
921 * It seems that if we call exit in the ServiceMain thread, it causes
922 * the SCM to not recieve the status we sent in the line above. The
923 * simple fix was to create a new thread to actually call exit for us
924 * whilst this thread continues and returns to its caller.
927 if (_beginthread(w32_mini_exit, 0, NULL) < 0)
929 /* we failed to create the exit thread, so just force an exit here
930 * and the SCM will just have to go and whistle!
940 w32_set_service_status(hSrv_status, &srv_status);
944 #endif /* ifdef _WIN32 */