1 const char w32_svrapi_rcs[] = "$Id: w32svrapi.c,v 1.1 2006/08/12 03:54:37 david__schmidt Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/w32svrapi.c,v $
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, 2006 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.
48 * $Log: w32svrapi.c,v $
49 * Revision 1.1 2006/08/12 03:54:37 david__schmidt
50 * Windows service integration
54 *********************************************************************/
71 #endif /* ndef _WIN_CONSOLE */
73 #include "w32svrapi.h"
74 const char w32_svrapi_h_rcs[] = W32_SVRAPI_H_VERSION;
77 /* Only the ANSI Win32 APIs are used at this time. If for some
78 * reason, we're building under unicode then we must stop
81 #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! :)"
85 /* Default to not running as service, unless the command line says so */
86 BOOL bRunAsService = FALSE;
88 /* According to the Win32 docs for CreateService,
89 * the max length for the service name is 256 chars
91 char szThisServiceName[260];
93 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize);
94 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* psz);
95 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode);
96 SERVICE_TABLE_ENTRY w32ServiceDispatchTable[] = {{"", privoxy_w32_service_start}, {NULL, NULL}};
97 static SERVICE_STATUS_HANDLE hSrv_status = 0;
98 static SERVICE_STATUS srv_status;
102 /*********************************************************************
103 * This function returns TRUE if we are running on an OS that can
104 * support services, like NT, etc. It returns FALSE for Win9x/ME.
105 *********************************************************************/
106 static BOOL HasServiceControlManager()
112 /* Load the DLL with the SCM functions or return a failure status */
113 hDll = LoadLibrary("Advapi32.dll");
116 printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
120 /* Get the address of the ANSI OpenSCManager function, or return a failure status */
121 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
124 printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
129 /* Try and connect to the SCM. If it fails check and see if the error
130 * code is ERROR_CALL_NOT_IMPLEMENTED, which means:
131 * "This function is not supported on this system."
133 hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
136 DWORD dwErr = GetLastError();
137 if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
139 /* Expected error under Win9x/Me, so don't print any debug info
140 * here as we'll leave that up to the calling function to do
146 printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
151 w32_close_service_handle(hScm);
153 /* OpenSCManager function exists and works, so we're on an NT type platform */
158 } /* -END- HasServiceControlManager */
161 BOOL CanSystemSupportServices()
163 BOOL bHasScm = HasServiceControlManager();
166 } /* -END- CanSystemSupportServices */
170 /*********************************************************************
172 * The Service functions are defined in <winsvc.h> which is where
173 * the declarations used in this file are taken from
175 *********************************************************************/
178 /*********************************************************************
179 * Open a connection to the service control manager
180 *********************************************************************/
181 SC_HANDLE w32_open_sc_manager(
182 LPCTSTR lpMachineName, /* computer name */
183 LPCTSTR lpDatabaseName, /* SCM database name */
184 DWORD dwDesiredAccess) /* access type */
187 SC_HANDLE hScm = NULL;
188 FARPROC pFunc = NULL;
191 /* Load the DLL with the SCM functions or return failure */
192 hDll = LoadLibrary("Advapi32.dll");
198 /* Get the address of the ANSI OpenSCManager function, or return failure */
199 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
206 /* Call the SCM function, and save the error code */
207 hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
208 dwLastErr = GetLastError();
210 /* Release the library and then restore the last error
211 * code, in case FreeLibrary altered it.
214 SetLastError(dwLastErr);
218 } /* -END- w32_open_sc_manager */
222 BOOL w32_close_service_handle(
223 SC_HANDLE hSCObject) /* handle to service or SCM object */
226 FARPROC pFunc = NULL;
230 /* Load the DLL with the SCM functions or return a failure status */
231 hDll = LoadLibrary("Advapi32.dll");
237 /* Get the address of the CloseServiceHandle function, or return a failure status */
238 pFunc = GetProcAddress(hDll, "CloseServiceHandle");
245 /* Close the handle, and save the error code */
246 bRet = (BOOL)(*pFunc)(hSCObject);
247 dwLastErr = GetLastError();
249 /* Release the library and then restore the last error
250 * code, in case FreeLibrary altered it.
253 SetLastError(dwLastErr);
257 } /* -END- w32_close_service_handle */
261 /*********************************************************************
263 *********************************************************************/
264 SC_HANDLE w32_open_service(
265 SC_HANDLE hSCManager, /* handle to SCM database */
266 LPCTSTR lpServiceName, /* service name */
267 DWORD dwDesiredAccess) /* access */
270 SC_HANDLE hSrv = NULL;
271 FARPROC pFunc = NULL;
274 /* Load the DLL with the SCM functions or return failure */
275 hDll = LoadLibrary("Advapi32.dll");
281 /* Get the address of the ANSI OpenService function, or return failure */
282 pFunc = GetProcAddress(hDll, "OpenServiceA");
289 /* Call the SCM function, and save the error code */
290 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
291 dwLastErr = GetLastError();
293 /* Release the library and then restore the last error
294 * code, in case FreeLibrary altered it.
297 SetLastError(dwLastErr);
301 } /* -END- w32_open_service */
305 SC_HANDLE w32_create_service(
306 SC_HANDLE hSCManager, /* handle to SCM database */
307 LPCTSTR lpServiceName, /* name of service to start */
308 LPCTSTR lpDisplayName, /* display name */
309 DWORD dwDesiredAccess, /* type of access to service */
310 DWORD dwServiceType, /* type of service */
311 DWORD dwStartType, /* when to start service */
312 DWORD dwErrorControl, /* severity of service failure */
313 LPCTSTR lpBinaryPathName, /* name of binary file */
314 LPCTSTR lpLoadOrderGroup, /* name of load ordering group */
315 LPDWORD lpdwTagId, /* tag identifier */
316 LPCTSTR lpDependencies, /* array of dependency names */
317 LPCTSTR lpServiceStartName, /* account name */
318 LPCTSTR lpPassword) /* account password */
321 SC_HANDLE hSrv = NULL;
322 FARPROC pFunc = NULL;
325 /* Load the DLL with the SCM functions or return failure */
326 hDll = LoadLibrary("Advapi32.dll");
332 /* Get the address of the ANSI CreateService function, or return failure */
333 pFunc = GetProcAddress(hDll, "CreateServiceA");
340 /* Call the SCM function, and save the error code */
341 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, /* handle to SCM database */
342 lpServiceName, /* name of service to start */
343 lpDisplayName, /* display name */
344 dwDesiredAccess, /* type of access to service */
345 dwServiceType, /* type of service */
346 dwStartType, /* when to start service */
347 dwErrorControl, /* severity of service failure */
348 lpBinaryPathName, /* name of binary file */
349 lpLoadOrderGroup, /* name of load ordering group */
350 lpdwTagId, /* tag identifier */
351 lpDependencies, /* array of dependency names */
352 lpServiceStartName, /* account name */
353 lpPassword); /* account password */
354 dwLastErr = GetLastError();
356 /* Release the library and then restore the last error
357 * code, in case FreeLibrary altered it.
360 SetLastError(dwLastErr);
364 } /* -END- w32_create_service */
368 BOOL w32_delete_service(
369 SC_HANDLE hService) /* handle to service */
372 FARPROC pFunc = NULL;
376 /* Load the DLL with the SCM functions or return a failure status */
377 hDll = LoadLibrary("Advapi32.dll");
383 /* Get the address of the DeleteService function, or return a failure status */
384 pFunc = GetProcAddress(hDll, "DeleteService");
391 /* Close the handle, and save the error code */
392 bRet = (BOOL)(*pFunc)(hService);
393 dwLastErr = GetLastError();
395 /* Release the library and then restore the last error
396 * code, in case FreeLibrary altered it.
399 SetLastError(dwLastErr);
403 } /* -END- w32_delete_service */
407 BOOL w32_query_service_config(
408 SC_HANDLE hService, /* handle to service */
409 LPQUERY_SERVICE_CONFIG lpServiceConfig, /* buffer */
410 DWORD cbBufSize, /* size of buffer */
411 LPDWORD pcbBytesNeeded) /* bytes needed */
414 FARPROC pFunc = NULL;
418 /* Load the DLL with the SCM functions or return a failure status */
419 hDll = LoadLibrary("Advapi32.dll");
425 /* Get the address of the QueryServiceConfig function, or return a failure status */
426 pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
433 /* Close the handle, and save the error code */
434 bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
435 dwLastErr = GetLastError();
437 /* Release the library and then restore the last error
438 * code, in case FreeLibrary altered it.
441 SetLastError(dwLastErr);
445 } /* -END- w32_query_service_config */
448 BOOL w32_start_service_ctrl_dispatcher(
449 CONST LPSERVICE_TABLE_ENTRY lpServiceTable) /* service table */
452 FARPROC pFunc = NULL;
456 /* Load the DLL with the SCM functions or return a failure status */
457 hDll = LoadLibrary("Advapi32.dll");
463 /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
464 pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
471 /* Close the handle, and save the error code */
472 bRet = (BOOL)(*pFunc)(lpServiceTable);
473 dwLastErr = GetLastError();
475 /* Release the library and then restore the last error
476 * code, in case FreeLibrary altered it.
479 SetLastError(dwLastErr);
483 } /* -END- w32_start_service_ctrl_dispatcher */
487 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
488 LPCTSTR lpServiceName, /* service name */
489 LPHANDLER_FUNCTION lpHandlerProc) /* handler function */
492 FARPROC pFunc = NULL;
494 SERVICE_STATUS_HANDLE hServStat = (SERVICE_STATUS_HANDLE)0;
496 /* Load the DLL with the SCM functions or return a failure status */
497 hDll = LoadLibrary("Advapi32.dll");
503 /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
504 pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
511 /* Close the handle, and save the error code */
512 hServStat = (SERVICE_STATUS_HANDLE)(*pFunc)(lpServiceName, lpHandlerProc);
513 dwLastErr = GetLastError();
515 /* Release the library and then restore the last error
516 * code, in case FreeLibrary altered it.
519 SetLastError(dwLastErr);
523 } /* -END- w32_register_service_ctrl_handler */
527 BOOL w32_set_service_status(
528 SERVICE_STATUS_HANDLE hServiceStatus, /* service status handle */
529 LPSERVICE_STATUS lpServiceStatus) /* status buffer */
532 FARPROC pFunc = NULL;
536 /* Load the DLL with the SCM functions or return a failure status */
537 hDll = LoadLibrary("Advapi32.dll");
543 /* Get the address of the SetServiceStatus function, or return a failure status */
544 pFunc = GetProcAddress(hDll, "SetServiceStatus");
551 /* Close the handle, and save the error code */
552 bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
553 dwLastErr = GetLastError();
555 /* Release the library and then restore the last error
556 * code, in case FreeLibrary altered it.
559 SetLastError(dwLastErr);
563 } /* -END- w32_set_service_status */
566 static void display_win32_msg(BOOL bIsError, char *msg)
573 MessageBox(NULL, msg, "Privoxy Error",
574 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
578 MessageBox(NULL, msg, "Privoxy Information",
579 MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
583 } /* -END- display_win32_msg */
586 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
588 /*********************************************************************
589 * Create a simple display name
590 *********************************************************************/
591 strcpy(pszDisplayName, "Privoxy (");
592 strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
593 strcat(pszDisplayName, ")");
600 BOOL install_service(const char *service_name)
602 char szModule[(MAX_PATH*2)+1];
603 char szDisplayName[MAX_PATH+2];
607 /*********************************************************************
608 * First check if this system can support a service architecture
609 *********************************************************************/
610 if (!CanSystemSupportServices())
612 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
616 /* Use a default service name if none was supplied */
617 if ((service_name == NULL) || (strlen(service_name) == 0))
619 service_name = "privoxy";
622 /*********************************************************************
623 * Open a handle to the Service Control Manager with full access rights
624 *********************************************************************/
625 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
628 display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n Administrator rights are required to create a service.\n");
633 /*********************************************************************
634 * Work out the full image path plus command line for the service
635 * We'll temporarily use szDisplayName as a second buffer.
636 *********************************************************************/
637 GetModuleFileName(NULL, szDisplayName, MAX_PATH);
638 sprintf(szModule, "\"%s\" --service", szDisplayName);
641 /*********************************************************************
642 * Get the display name for the service
643 *********************************************************************/
644 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
647 /*********************************************************************
649 *********************************************************************/
650 hService = w32_create_service(hSCM,
651 service_name, /* the internal service name */
652 szDisplayName, /* the display name */
653 SERVICE_ALL_ACCESS, /* get full access during creation */
654 SERVICE_WIN32_OWN_PROCESS /* run in our own process */
656 + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
659 SERVICE_DEMAND_START, /* For now, only start when asked to */
660 SERVICE_ERROR_NORMAL, /* Normal error handling by the SCM */
661 szModule, /* The executable service file */
662 NULL, /* No load order info needed */
663 NULL, /* No load order info needed */
664 NULL, /* No dependencies */
665 NULL, /* Default to LocalSystem... */
666 NULL); /* ...which doesn't require a password */
667 if (hService == NULL)
669 display_win32_msg(TRUE, "Can't install service!\n");
670 w32_close_service_handle(hSCM);
674 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");
677 w32_close_service_handle(hService);
678 w32_close_service_handle(hSCM);
681 } /* -END- install_service */
685 BOOL uninstall_service(const char *service_name)
687 char szDisplayName[MAX_PATH+2];
690 BOOL bResult = FALSE;
693 /*********************************************************************
694 * First check if this system can support a service architecture
695 *********************************************************************/
696 if (!CanSystemSupportServices())
698 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
703 /* Use a default service name if none was supplied */
704 if ((service_name == NULL) || (strlen(service_name) == 0))
706 service_name = "privoxy";
710 /*********************************************************************
711 * Open a handle to the Service Control Manager with full access rights
712 *********************************************************************/
713 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
716 display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n Administrator rights are required to delete a service.\n");
721 /*********************************************************************
722 * Get the display name for the service
723 *********************************************************************/
724 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
727 /*********************************************************************
728 * Open and then delete the service
729 *********************************************************************/
730 hService = w32_open_service(hSCM, service_name, DELETE);
731 if (hService == NULL)
733 display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
734 w32_close_service_handle(hSCM);
738 if (w32_delete_service(hService))
740 display_win32_msg(FALSE, "Service was deleted successfully.\n");
745 display_win32_msg(TRUE, "Service could not be deleted!\n");
749 w32_close_service_handle(hService);
750 w32_close_service_handle(hSCM);
753 } /* -END- uninstall_service */
757 /*********************************************************************
759 * Function : privoxy_w32_service_start
761 * Description : This is the entry point function for the service.
762 * In other words, it's the ServiceMain function.
764 * Parameters : Defined by the Win32 API, but not used here
768 *********************************************************************/
769 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
773 /* Arg zero is always the service name, and we need to
774 * know it when we call RegisterServiceCtrlHandler.
776 strcpy(szThisServiceName, pszArgs[0]);
778 /* Tell the SCM we are running */
779 srv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
780 srv_status.dwCurrentState = SERVICE_RUNNING;
781 srv_status.dwCheckPoint = 0;
782 srv_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
783 srv_status.dwWin32ExitCode = NO_ERROR;
784 srv_status.dwServiceSpecificExitCode = 0;
785 srv_status.dwWaitHint = 0;
787 hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
792 w32_set_service_status(hSrv_status, &srv_status);
794 #ifndef FEATURE_PTHREAD
795 child_id = _beginthread(w32_service_listen_loop, 0, NULL);
798 #error "FIXME: Do pthread stuff here!"
801 w32_set_service_status(hSrv_status, &srv_status);
805 srv_status.dwCurrentState = SERVICE_STOPPED;
806 srv_status.dwCheckPoint = 0;
807 srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
808 srv_status.dwServiceSpecificExitCode = ERROR_SERVICE_NO_THREAD;
809 w32_set_service_status(hSrv_status, &srv_status);
814 /*********************************************************************
816 * Function : w32_set_service_cwd
818 * Description : Simple function to change the current directory to
819 * the same location as the service executable.
825 *********************************************************************/
826 void w32_set_service_cwd(void)
828 char exe_name[MAX_PATH+1];
829 char dir_name[MAX_PATH+1];
830 char *pszFile = NULL;
832 /* Get the exe name and path of the service */
833 if (GetModuleFileName(NULL, exe_name, MAX_PATH))
835 /* Ask the API to tell us where the filename portion starts */
836 if (GetFullPathName(exe_name, MAX_PATH, dir_name, &pszFile))
838 /* remove the filename from the string */
842 /* We have just a directory path now, so make it current */
843 SetCurrentDirectory(dir_name);
850 /*********************************************************************
852 * Function : w32_service_exit_notify
854 * Description : This is a simple atexit function that is called by the
855 * C runtime after exit has been called. It allows the
856 * service code to detect when the app is about to die and
857 * send an quick notification to the SCM that the service
864 *********************************************************************/
865 void w32_service_exit_notify(void)
867 if (hSrv_status != 0)
869 if (srv_status.dwCurrentState != SERVICE_STOPPED)
871 srv_status.dwCurrentState = SERVICE_STOPPED;
872 srv_status.dwCheckPoint = 0;
873 srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
874 srv_status.dwServiceSpecificExitCode = ERROR_PROCESS_ABORTED;
875 w32_set_service_status(hSrv_status, &srv_status);
881 static void w32_mini_exit(void *p)
887 PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
888 #endif /* def _WIN_CONSOLE */
892 /*********************************************************************
894 * Function : privoxy_w32_service_handler
896 * Description : This is the control message handler function for
899 * Parameters : dwOpcode
900 * requested control code sent by SCM
904 *********************************************************************/
905 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode)
909 case SERVICE_CONTROL_STOP:
912 srv_status.dwCurrentState = SERVICE_STOPPED;
913 srv_status.dwCheckPoint = 0;
914 srv_status.dwWin32ExitCode = NO_ERROR;
915 srv_status.dwServiceSpecificExitCode = 0;
917 /* Maybe there is a more friendly way to stop, but this will do for now! */
918 w32_set_service_status(hSrv_status, &srv_status);
920 /* During testing, I kept getting error 109 (ERROR_BROKEN_PIPE) and
921 * as far as the SCM was concerned the service was still stopping,
922 * even after the process had disappeared.
924 * It seems that if we call exit in the ServiceMain thread, it causes
925 * the SCM to not recieve the status we sent in the line above. The
926 * simple fix was to create a new thread to actually call exit for us
927 * whilst this thread continues and returns to its caller.
930 if (_beginthread(w32_mini_exit, 0, NULL) < 0)
932 /* we failed to create the exit thread, so just force an exit here
933 * and the SCM will just have to go and whistle!
943 w32_set_service_status(hSrv_status, &srv_status);
947 #endif /* ifdef _WIN32 */