1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/w32svrapi.c,v $
5 * Purpose : Win32 Services API for Privoxy.
6 * Provides the implementation of an Win32 service to
7 * allow the code to directly register and run as a
8 * native Windows service application.
10 * Since Win9x/ME platforms don't provide or support
11 * running programs as services, this code uses runtime
12 * loading and calling of the Win32 Service API, to
13 * prevent the possibility of getting "entry point not
14 * found" type errors on unsupported platforms. This adds
15 * a little more complexity to the code, but it is worth
16 * doing to provide that isolation.
18 * Copyright : Written by and Copyright (C) 2003, 2006 members of
19 * the Privoxy team. http://www.privoxy.org/
21 * Written by and Copyright (C) 2003 Ian Cummings
22 * <ian_a_c@hotmail.com>
24 * Special thanks to Mates Dolák <matesek@post.cz> for
25 * some very helpful feedback and suggestions during the
26 * development of this code.
28 * This program is free software; you can redistribute it
29 * and/or modify it under the terms of the GNU General
30 * Public License as published by the Free Software
31 * Foundation; either version 2 of the License, or (at
32 * your option) any later version.
34 * This program is distributed in the hope that it will
35 * be useful, but WITHOUT ANY WARRANTY; without even the
36 * implied warranty of MERCHANTABILITY or FITNESS FOR A
37 * PARTICULAR PURPOSE. See the GNU General Public
38 * License for more details.
40 * The GNU General Public License should be included with
41 * this file. If not, you can view it at
42 * http://www.gnu.org/copyleft/gpl.html
43 * or write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
46 *********************************************************************/
63 #endif /* ndef _WIN_CONSOLE */
65 #include "w32svrapi.h"
67 /* Only the ANSI Win32 APIs are used at this time. If for some
68 * reason, we're building under unicode then we must stop
71 #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! :)"
75 /* Default to not running as service, unless the command line says so */
76 BOOL bRunAsService = FALSE;
78 /* According to the Win32 docs for CreateService,
79 * the max length for the service name is 256 chars
81 char szThisServiceName[260];
83 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize);
84 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* psz);
85 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode);
86 SERVICE_TABLE_ENTRY w32ServiceDispatchTable[] = {{"", privoxy_w32_service_start}, {NULL, NULL}};
87 static SERVICE_STATUS_HANDLE hSrv_status = 0;
88 static SERVICE_STATUS srv_status;
92 /*********************************************************************
93 * This function returns TRUE if we are running on an OS that can
94 * support services, like NT, etc. It returns FALSE for Win9x/ME.
95 *********************************************************************/
96 static BOOL HasServiceControlManager()
102 /* Load the DLL with the SCM functions or return a failure status */
103 hDll = LoadLibrary("Advapi32.dll");
106 printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
110 /* Get the address of the ANSI OpenSCManager function, or return a failure status */
111 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
114 printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
119 /* Try and connect to the SCM. If it fails check and see if the error
120 * code is ERROR_CALL_NOT_IMPLEMENTED, which means:
121 * "This function is not supported on this system."
123 hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
126 DWORD dwErr = GetLastError();
127 if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
129 /* Expected error under Win9x/Me, so don't print any debug info
130 * here as we'll leave that up to the calling function to do
136 printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
141 w32_close_service_handle(hScm);
143 /* OpenSCManager function exists and works, so we're on an NT type platform */
148 } /* -END- HasServiceControlManager */
151 BOOL CanSystemSupportServices()
153 BOOL bHasScm = HasServiceControlManager();
156 } /* -END- CanSystemSupportServices */
160 /*********************************************************************
162 * The Service functions are defined in <winsvc.h> which is where
163 * the declarations used in this file are taken from
165 *********************************************************************/
168 /*********************************************************************
169 * Open a connection to the service control manager
170 *********************************************************************/
171 SC_HANDLE w32_open_sc_manager(
172 LPCTSTR lpMachineName, /* computer name */
173 LPCTSTR lpDatabaseName, /* SCM database name */
174 DWORD dwDesiredAccess) /* access type */
177 SC_HANDLE hScm = NULL;
178 FARPROC pFunc = NULL;
181 /* Load the DLL with the SCM functions or return failure */
182 hDll = LoadLibrary("Advapi32.dll");
188 /* Get the address of the ANSI OpenSCManager function, or return failure */
189 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
196 /* Call the SCM function, and save the error code */
197 hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
198 dwLastErr = GetLastError();
200 /* Release the library and then restore the last error
201 * code, in case FreeLibrary altered it.
204 SetLastError(dwLastErr);
208 } /* -END- w32_open_sc_manager */
212 BOOL w32_close_service_handle(
213 SC_HANDLE hSCObject) /* handle to service or SCM object */
216 FARPROC pFunc = NULL;
220 /* Load the DLL with the SCM functions or return a failure status */
221 hDll = LoadLibrary("Advapi32.dll");
227 /* Get the address of the CloseServiceHandle function, or return a failure status */
228 pFunc = GetProcAddress(hDll, "CloseServiceHandle");
235 /* Close the handle, and save the error code */
236 bRet = (BOOL)(*pFunc)(hSCObject);
237 dwLastErr = GetLastError();
239 /* Release the library and then restore the last error
240 * code, in case FreeLibrary altered it.
243 SetLastError(dwLastErr);
247 } /* -END- w32_close_service_handle */
251 /*********************************************************************
253 *********************************************************************/
254 SC_HANDLE w32_open_service(
255 SC_HANDLE hSCManager, /* handle to SCM database */
256 LPCTSTR lpServiceName, /* service name */
257 DWORD dwDesiredAccess) /* access */
260 SC_HANDLE hSrv = NULL;
261 FARPROC pFunc = NULL;
264 /* Load the DLL with the SCM functions or return failure */
265 hDll = LoadLibrary("Advapi32.dll");
271 /* Get the address of the ANSI OpenService function, or return failure */
272 pFunc = GetProcAddress(hDll, "OpenServiceA");
279 /* Call the SCM function, and save the error code */
280 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
281 dwLastErr = GetLastError();
283 /* Release the library and then restore the last error
284 * code, in case FreeLibrary altered it.
287 SetLastError(dwLastErr);
291 } /* -END- w32_open_service */
295 SC_HANDLE w32_create_service(
296 SC_HANDLE hSCManager, /* handle to SCM database */
297 LPCTSTR lpServiceName, /* name of service to start */
298 LPCTSTR lpDisplayName, /* display name */
299 DWORD dwDesiredAccess, /* type of access to service */
300 DWORD dwServiceType, /* type of service */
301 DWORD dwStartType, /* when to start service */
302 DWORD dwErrorControl, /* severity of service failure */
303 LPCTSTR lpBinaryPathName, /* name of binary file */
304 LPCTSTR lpLoadOrderGroup, /* name of load ordering group */
305 LPDWORD lpdwTagId, /* tag identifier */
306 LPCTSTR lpDependencies, /* array of dependency names */
307 LPCTSTR lpServiceStartName, /* account name */
308 LPCTSTR lpPassword) /* account password */
311 SC_HANDLE hSrv = NULL;
312 FARPROC pFunc = NULL;
315 /* Load the DLL with the SCM functions or return failure */
316 hDll = LoadLibrary("Advapi32.dll");
322 /* Get the address of the ANSI CreateService function, or return failure */
323 pFunc = GetProcAddress(hDll, "CreateServiceA");
330 /* Call the SCM function, and save the error code */
331 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, /* handle to SCM database */
332 lpServiceName, /* name of service to start */
333 lpDisplayName, /* display name */
334 dwDesiredAccess, /* type of access to service */
335 dwServiceType, /* type of service */
336 dwStartType, /* when to start service */
337 dwErrorControl, /* severity of service failure */
338 lpBinaryPathName, /* name of binary file */
339 lpLoadOrderGroup, /* name of load ordering group */
340 lpdwTagId, /* tag identifier */
341 lpDependencies, /* array of dependency names */
342 lpServiceStartName, /* account name */
343 lpPassword); /* account password */
344 dwLastErr = GetLastError();
346 /* Release the library and then restore the last error
347 * code, in case FreeLibrary altered it.
350 SetLastError(dwLastErr);
354 } /* -END- w32_create_service */
358 BOOL w32_delete_service(
359 SC_HANDLE hService) /* handle to service */
362 FARPROC pFunc = NULL;
366 /* Load the DLL with the SCM functions or return a failure status */
367 hDll = LoadLibrary("Advapi32.dll");
373 /* Get the address of the DeleteService function, or return a failure status */
374 pFunc = GetProcAddress(hDll, "DeleteService");
381 /* Close the handle, and save the error code */
382 bRet = (BOOL)(*pFunc)(hService);
383 dwLastErr = GetLastError();
385 /* Release the library and then restore the last error
386 * code, in case FreeLibrary altered it.
389 SetLastError(dwLastErr);
393 } /* -END- w32_delete_service */
397 BOOL w32_query_service_config(
398 SC_HANDLE hService, /* handle to service */
399 LPQUERY_SERVICE_CONFIG lpServiceConfig, /* buffer */
400 DWORD cbBufSize, /* size of buffer */
401 LPDWORD pcbBytesNeeded) /* bytes needed */
404 FARPROC pFunc = NULL;
408 /* Load the DLL with the SCM functions or return a failure status */
409 hDll = LoadLibrary("Advapi32.dll");
415 /* Get the address of the QueryServiceConfig function, or return a failure status */
416 pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
423 /* Close the handle, and save the error code */
424 bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
425 dwLastErr = GetLastError();
427 /* Release the library and then restore the last error
428 * code, in case FreeLibrary altered it.
431 SetLastError(dwLastErr);
435 } /* -END- w32_query_service_config */
438 BOOL w32_start_service_ctrl_dispatcher(
439 CONST LPSERVICE_TABLE_ENTRY lpServiceTable) /* service table */
442 FARPROC pFunc = NULL;
446 /* Load the DLL with the SCM functions or return a failure status */
447 hDll = LoadLibrary("Advapi32.dll");
453 /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
454 pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
461 /* Close the handle, and save the error code */
462 bRet = (BOOL)(*pFunc)(lpServiceTable);
463 dwLastErr = GetLastError();
465 /* Release the library and then restore the last error
466 * code, in case FreeLibrary altered it.
469 SetLastError(dwLastErr);
473 } /* -END- w32_start_service_ctrl_dispatcher */
477 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
478 LPCTSTR lpServiceName, /* service name */
479 LPHANDLER_FUNCTION lpHandlerProc) /* handler function */
482 FARPROC pFunc = NULL;
484 SERVICE_STATUS_HANDLE hServStat = (SERVICE_STATUS_HANDLE)0;
486 /* Load the DLL with the SCM functions or return a failure status */
487 hDll = LoadLibrary("Advapi32.dll");
493 /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
494 pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
501 /* Close the handle, and save the error code */
502 hServStat = (SERVICE_STATUS_HANDLE)(*pFunc)(lpServiceName, lpHandlerProc);
503 dwLastErr = GetLastError();
505 /* Release the library and then restore the last error
506 * code, in case FreeLibrary altered it.
509 SetLastError(dwLastErr);
513 } /* -END- w32_register_service_ctrl_handler */
517 BOOL w32_set_service_status(
518 SERVICE_STATUS_HANDLE hServiceStatus, /* service status handle */
519 LPSERVICE_STATUS lpServiceStatus) /* status buffer */
522 FARPROC pFunc = NULL;
526 /* Load the DLL with the SCM functions or return a failure status */
527 hDll = LoadLibrary("Advapi32.dll");
533 /* Get the address of the SetServiceStatus function, or return a failure status */
534 pFunc = GetProcAddress(hDll, "SetServiceStatus");
541 /* Close the handle, and save the error code */
542 bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
543 dwLastErr = GetLastError();
545 /* Release the library and then restore the last error
546 * code, in case FreeLibrary altered it.
549 SetLastError(dwLastErr);
553 } /* -END- w32_set_service_status */
556 static void display_win32_msg(BOOL bIsError, char *msg)
563 MessageBox(NULL, msg, "Privoxy Error",
564 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
568 MessageBox(NULL, msg, "Privoxy Information",
569 MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
573 } /* -END- display_win32_msg */
576 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
578 /*********************************************************************
579 * Create a simple display name
580 *********************************************************************/
581 strcpy(pszDisplayName, "Privoxy (");
582 strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
583 strcat(pszDisplayName, ")");
590 BOOL install_service(const char *service_name)
592 char szModule[(MAX_PATH*2)+1];
593 char szDisplayName[MAX_PATH+2];
597 /*********************************************************************
598 * First check if this system can support a service architecture
599 *********************************************************************/
600 if (!CanSystemSupportServices())
602 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
606 /* Use a default service name if none was supplied */
607 if ((service_name == NULL) || (strlen(service_name) == 0))
609 service_name = "privoxy";
612 /*********************************************************************
613 * Open a handle to the Service Control Manager with full access rights
614 *********************************************************************/
615 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
618 display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n Administrator rights are required to create a service.\n");
623 /*********************************************************************
624 * Work out the full image path plus command line for the service
625 * We'll temporarily use szDisplayName as a second buffer.
626 *********************************************************************/
627 GetModuleFileName(NULL, szDisplayName, MAX_PATH);
628 sprintf(szModule, "\"%s\" --service", szDisplayName);
631 /*********************************************************************
632 * Get the display name for the service
633 *********************************************************************/
634 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
637 /*********************************************************************
639 *********************************************************************/
640 hService = w32_create_service(hSCM,
641 service_name, /* the internal service name */
642 szDisplayName, /* the display name */
643 SERVICE_ALL_ACCESS, /* get full access during creation */
644 SERVICE_WIN32_OWN_PROCESS /* run in our own process */
646 + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
649 SERVICE_DEMAND_START, /* For now, only start when asked to */
650 SERVICE_ERROR_NORMAL, /* Normal error handling by the SCM */
651 szModule, /* The executable service file */
652 NULL, /* No load order info needed */
653 NULL, /* No load order info needed */
654 NULL, /* No dependencies */
655 NULL, /* Default to LocalSystem... */
656 NULL); /* ...which doesn't require a password */
657 if (hService == NULL)
659 display_win32_msg(TRUE, "Can't install service!\n");
660 w32_close_service_handle(hSCM);
664 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");
667 w32_close_service_handle(hService);
668 w32_close_service_handle(hSCM);
671 } /* -END- install_service */
675 BOOL uninstall_service(const char *service_name)
677 char szDisplayName[MAX_PATH+2];
680 BOOL bResult = FALSE;
683 /*********************************************************************
684 * First check if this system can support a service architecture
685 *********************************************************************/
686 if (!CanSystemSupportServices())
688 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
693 /* Use a default service name if none was supplied */
694 if ((service_name == NULL) || (strlen(service_name) == 0))
696 service_name = "privoxy";
700 /*********************************************************************
701 * Open a handle to the Service Control Manager with full access rights
702 *********************************************************************/
703 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
706 display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n Administrator rights are required to delete a service.\n");
711 /*********************************************************************
712 * Get the display name for the service
713 *********************************************************************/
714 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
717 /*********************************************************************
718 * Open and then delete the service
719 *********************************************************************/
720 hService = w32_open_service(hSCM, service_name, DELETE);
721 if (hService == NULL)
723 display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
724 w32_close_service_handle(hSCM);
728 if (w32_delete_service(hService))
730 display_win32_msg(FALSE, "Service was deleted successfully.\n");
735 display_win32_msg(TRUE, "Service could not be deleted!\n");
739 w32_close_service_handle(hService);
740 w32_close_service_handle(hSCM);
743 } /* -END- uninstall_service */
747 /*********************************************************************
749 * Function : privoxy_w32_service_start
751 * Description : This is the entry point function for the service.
752 * In other words, it's the ServiceMain function.
754 * Parameters : Defined by the Win32 API, but not used here
758 *********************************************************************/
759 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
763 /* Arg zero is always the service name, and we need to
764 * know it when we call RegisterServiceCtrlHandler.
766 strcpy(szThisServiceName, pszArgs[0]);
768 /* Tell the SCM we are running */
769 srv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
770 srv_status.dwCurrentState = SERVICE_RUNNING;
771 srv_status.dwCheckPoint = 0;
772 srv_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
773 srv_status.dwWin32ExitCode = NO_ERROR;
774 srv_status.dwServiceSpecificExitCode = 0;
775 srv_status.dwWaitHint = 0;
777 hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
782 w32_set_service_status(hSrv_status, &srv_status);
784 #ifndef FEATURE_PTHREAD
785 /* NOTE: a cygwin cross-compiler build for --host=i686-w64-mingw32 must disable POSIX threading - eg
786 * ./configure --host=i686-w64-mingw32 --disable-pthread
788 child_id = _beginthread(w32_service_listen_loop, 0, NULL);
791 #error "FIXME: Do pthread stuff here!"
794 w32_set_service_status(hSrv_status, &srv_status);
798 srv_status.dwCurrentState = SERVICE_STOPPED;
799 srv_status.dwCheckPoint = 0;
800 srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
801 srv_status.dwServiceSpecificExitCode = ERROR_SERVICE_NO_THREAD;
802 w32_set_service_status(hSrv_status, &srv_status);
807 /*********************************************************************
809 * Function : w32_set_service_cwd
811 * Description : Simple function to change the current directory to
812 * the same location as the service executable.
818 *********************************************************************/
819 void w32_set_service_cwd(void)
821 char exe_name[MAX_PATH+1];
822 char dir_name[MAX_PATH+1];
823 char *pszFile = NULL;
825 /* Get the exe name and path of the service */
826 if (GetModuleFileName(NULL, exe_name, MAX_PATH))
828 /* Ask the API to tell us where the filename portion starts */
829 if (GetFullPathName(exe_name, MAX_PATH, dir_name, &pszFile))
831 /* remove the filename from the string */
835 /* We have just a directory path now, so make it current */
836 SetCurrentDirectory(dir_name);
843 /*********************************************************************
845 * Function : w32_service_exit_notify
847 * Description : This is a simple atexit function that is called by the
848 * C runtime after exit has been called. It allows the
849 * service code to detect when the app is about to die and
850 * send an quick notification to the SCM that the service
857 *********************************************************************/
858 void w32_service_exit_notify(void)
860 if (hSrv_status != 0)
862 if (srv_status.dwCurrentState != SERVICE_STOPPED)
864 srv_status.dwCurrentState = SERVICE_STOPPED;
865 srv_status.dwCheckPoint = 0;
866 srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
867 srv_status.dwServiceSpecificExitCode = ERROR_PROCESS_ABORTED;
868 w32_set_service_status(hSrv_status, &srv_status);
874 static void w32_mini_exit(void *p)
880 PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
881 #endif /* def _WIN_CONSOLE */
885 /*********************************************************************
887 * Function : privoxy_w32_service_handler
889 * Description : This is the control message handler function for
892 * Parameters : dwOpcode
893 * requested control code sent by SCM
897 *********************************************************************/
898 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode)
902 case SERVICE_CONTROL_STOP:
905 srv_status.dwCurrentState = SERVICE_STOPPED;
906 srv_status.dwCheckPoint = 0;
907 srv_status.dwWin32ExitCode = NO_ERROR;
908 srv_status.dwServiceSpecificExitCode = 0;
910 /* Maybe there is a more friendly way to stop, but this will do for now! */
911 w32_set_service_status(hSrv_status, &srv_status);
913 /* During testing, I kept getting error 109 (ERROR_BROKEN_PIPE) and
914 * as far as the SCM was concerned the service was still stopping,
915 * even after the process had disappeared.
917 * It seems that if we call exit in the ServiceMain thread, it causes
918 * the SCM to not receive the status we sent in the line above. The
919 * simple fix was to create a new thread to actually call exit for us
920 * whilst this thread continues and returns to its caller.
923 if (_beginthread(w32_mini_exit, 0, NULL) < 0)
925 /* we failed to create the exit thread, so just force an exit here
926 * and the SCM will just have to go and whistle!
936 w32_set_service_status(hSrv_status, &srv_status);
940 #endif /* ifdef _WIN32 */