1 const char w32_svrapi_rcs[] = "$Id: w32svrapi.c,v 1.3 2009/05/16 13:27:20 fabiankeil 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.
47 *********************************************************************/
64 #endif /* ndef _WIN_CONSOLE */
66 #include "w32svrapi.h"
67 const char w32_svrapi_h_rcs[] = W32_SVRAPI_H_VERSION;
70 /* Only the ANSI Win32 APIs are used at this time. If for some
71 * reason, we're building under unicode then we must stop
74 #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! :)"
78 /* Default to not running as service, unless the command line says so */
79 BOOL bRunAsService = FALSE;
81 /* According to the Win32 docs for CreateService,
82 * the max length for the service name is 256 chars
84 char szThisServiceName[260];
86 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize);
87 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* psz);
88 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode);
89 SERVICE_TABLE_ENTRY w32ServiceDispatchTable[] = {{"", privoxy_w32_service_start}, {NULL, NULL}};
90 static SERVICE_STATUS_HANDLE hSrv_status = 0;
91 static SERVICE_STATUS srv_status;
95 /*********************************************************************
96 * This function returns TRUE if we are running on an OS that can
97 * support services, like NT, etc. It returns FALSE for Win9x/ME.
98 *********************************************************************/
99 static BOOL HasServiceControlManager()
105 /* Load the DLL with the SCM functions or return a failure status */
106 hDll = LoadLibrary("Advapi32.dll");
109 printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
113 /* Get the address of the ANSI OpenSCManager function, or return a failure status */
114 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
117 printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
122 /* Try and connect to the SCM. If it fails check and see if the error
123 * code is ERROR_CALL_NOT_IMPLEMENTED, which means:
124 * "This function is not supported on this system."
126 hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
129 DWORD dwErr = GetLastError();
130 if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
132 /* Expected error under Win9x/Me, so don't print any debug info
133 * here as we'll leave that up to the calling function to do
139 printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
144 w32_close_service_handle(hScm);
146 /* OpenSCManager function exists and works, so we're on an NT type platform */
151 } /* -END- HasServiceControlManager */
154 BOOL CanSystemSupportServices()
156 BOOL bHasScm = HasServiceControlManager();
159 } /* -END- CanSystemSupportServices */
163 /*********************************************************************
165 * The Service functions are defined in <winsvc.h> which is where
166 * the declarations used in this file are taken from
168 *********************************************************************/
171 /*********************************************************************
172 * Open a connection to the service control manager
173 *********************************************************************/
174 SC_HANDLE w32_open_sc_manager(
175 LPCTSTR lpMachineName, /* computer name */
176 LPCTSTR lpDatabaseName, /* SCM database name */
177 DWORD dwDesiredAccess) /* access type */
180 SC_HANDLE hScm = NULL;
181 FARPROC pFunc = NULL;
184 /* Load the DLL with the SCM functions or return failure */
185 hDll = LoadLibrary("Advapi32.dll");
191 /* Get the address of the ANSI OpenSCManager function, or return failure */
192 pFunc = GetProcAddress(hDll, "OpenSCManagerA");
199 /* Call the SCM function, and save the error code */
200 hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
201 dwLastErr = GetLastError();
203 /* Release the library and then restore the last error
204 * code, in case FreeLibrary altered it.
207 SetLastError(dwLastErr);
211 } /* -END- w32_open_sc_manager */
215 BOOL w32_close_service_handle(
216 SC_HANDLE hSCObject) /* handle to service or SCM object */
219 FARPROC pFunc = NULL;
223 /* Load the DLL with the SCM functions or return a failure status */
224 hDll = LoadLibrary("Advapi32.dll");
230 /* Get the address of the CloseServiceHandle function, or return a failure status */
231 pFunc = GetProcAddress(hDll, "CloseServiceHandle");
238 /* Close the handle, and save the error code */
239 bRet = (BOOL)(*pFunc)(hSCObject);
240 dwLastErr = GetLastError();
242 /* Release the library and then restore the last error
243 * code, in case FreeLibrary altered it.
246 SetLastError(dwLastErr);
250 } /* -END- w32_close_service_handle */
254 /*********************************************************************
256 *********************************************************************/
257 SC_HANDLE w32_open_service(
258 SC_HANDLE hSCManager, /* handle to SCM database */
259 LPCTSTR lpServiceName, /* service name */
260 DWORD dwDesiredAccess) /* access */
263 SC_HANDLE hSrv = NULL;
264 FARPROC pFunc = NULL;
267 /* Load the DLL with the SCM functions or return failure */
268 hDll = LoadLibrary("Advapi32.dll");
274 /* Get the address of the ANSI OpenService function, or return failure */
275 pFunc = GetProcAddress(hDll, "OpenServiceA");
282 /* Call the SCM function, and save the error code */
283 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
284 dwLastErr = GetLastError();
286 /* Release the library and then restore the last error
287 * code, in case FreeLibrary altered it.
290 SetLastError(dwLastErr);
294 } /* -END- w32_open_service */
298 SC_HANDLE w32_create_service(
299 SC_HANDLE hSCManager, /* handle to SCM database */
300 LPCTSTR lpServiceName, /* name of service to start */
301 LPCTSTR lpDisplayName, /* display name */
302 DWORD dwDesiredAccess, /* type of access to service */
303 DWORD dwServiceType, /* type of service */
304 DWORD dwStartType, /* when to start service */
305 DWORD dwErrorControl, /* severity of service failure */
306 LPCTSTR lpBinaryPathName, /* name of binary file */
307 LPCTSTR lpLoadOrderGroup, /* name of load ordering group */
308 LPDWORD lpdwTagId, /* tag identifier */
309 LPCTSTR lpDependencies, /* array of dependency names */
310 LPCTSTR lpServiceStartName, /* account name */
311 LPCTSTR lpPassword) /* account password */
314 SC_HANDLE hSrv = NULL;
315 FARPROC pFunc = NULL;
318 /* Load the DLL with the SCM functions or return failure */
319 hDll = LoadLibrary("Advapi32.dll");
325 /* Get the address of the ANSI CreateService function, or return failure */
326 pFunc = GetProcAddress(hDll, "CreateServiceA");
333 /* Call the SCM function, and save the error code */
334 hSrv = (SC_HANDLE)(*pFunc)(hSCManager, /* handle to SCM database */
335 lpServiceName, /* name of service to start */
336 lpDisplayName, /* display name */
337 dwDesiredAccess, /* type of access to service */
338 dwServiceType, /* type of service */
339 dwStartType, /* when to start service */
340 dwErrorControl, /* severity of service failure */
341 lpBinaryPathName, /* name of binary file */
342 lpLoadOrderGroup, /* name of load ordering group */
343 lpdwTagId, /* tag identifier */
344 lpDependencies, /* array of dependency names */
345 lpServiceStartName, /* account name */
346 lpPassword); /* account password */
347 dwLastErr = GetLastError();
349 /* Release the library and then restore the last error
350 * code, in case FreeLibrary altered it.
353 SetLastError(dwLastErr);
357 } /* -END- w32_create_service */
361 BOOL w32_delete_service(
362 SC_HANDLE hService) /* handle to service */
365 FARPROC pFunc = NULL;
369 /* Load the DLL with the SCM functions or return a failure status */
370 hDll = LoadLibrary("Advapi32.dll");
376 /* Get the address of the DeleteService function, or return a failure status */
377 pFunc = GetProcAddress(hDll, "DeleteService");
384 /* Close the handle, and save the error code */
385 bRet = (BOOL)(*pFunc)(hService);
386 dwLastErr = GetLastError();
388 /* Release the library and then restore the last error
389 * code, in case FreeLibrary altered it.
392 SetLastError(dwLastErr);
396 } /* -END- w32_delete_service */
400 BOOL w32_query_service_config(
401 SC_HANDLE hService, /* handle to service */
402 LPQUERY_SERVICE_CONFIG lpServiceConfig, /* buffer */
403 DWORD cbBufSize, /* size of buffer */
404 LPDWORD pcbBytesNeeded) /* bytes needed */
407 FARPROC pFunc = NULL;
411 /* Load the DLL with the SCM functions or return a failure status */
412 hDll = LoadLibrary("Advapi32.dll");
418 /* Get the address of the QueryServiceConfig function, or return a failure status */
419 pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
426 /* Close the handle, and save the error code */
427 bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
428 dwLastErr = GetLastError();
430 /* Release the library and then restore the last error
431 * code, in case FreeLibrary altered it.
434 SetLastError(dwLastErr);
438 } /* -END- w32_query_service_config */
441 BOOL w32_start_service_ctrl_dispatcher(
442 CONST LPSERVICE_TABLE_ENTRY lpServiceTable) /* service table */
445 FARPROC pFunc = NULL;
449 /* Load the DLL with the SCM functions or return a failure status */
450 hDll = LoadLibrary("Advapi32.dll");
456 /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
457 pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
464 /* Close the handle, and save the error code */
465 bRet = (BOOL)(*pFunc)(lpServiceTable);
466 dwLastErr = GetLastError();
468 /* Release the library and then restore the last error
469 * code, in case FreeLibrary altered it.
472 SetLastError(dwLastErr);
476 } /* -END- w32_start_service_ctrl_dispatcher */
480 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
481 LPCTSTR lpServiceName, /* service name */
482 LPHANDLER_FUNCTION lpHandlerProc) /* handler function */
485 FARPROC pFunc = NULL;
487 SERVICE_STATUS_HANDLE hServStat = (SERVICE_STATUS_HANDLE)0;
489 /* Load the DLL with the SCM functions or return a failure status */
490 hDll = LoadLibrary("Advapi32.dll");
496 /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
497 pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
504 /* Close the handle, and save the error code */
505 hServStat = (SERVICE_STATUS_HANDLE)(*pFunc)(lpServiceName, lpHandlerProc);
506 dwLastErr = GetLastError();
508 /* Release the library and then restore the last error
509 * code, in case FreeLibrary altered it.
512 SetLastError(dwLastErr);
516 } /* -END- w32_register_service_ctrl_handler */
520 BOOL w32_set_service_status(
521 SERVICE_STATUS_HANDLE hServiceStatus, /* service status handle */
522 LPSERVICE_STATUS lpServiceStatus) /* status buffer */
525 FARPROC pFunc = NULL;
529 /* Load the DLL with the SCM functions or return a failure status */
530 hDll = LoadLibrary("Advapi32.dll");
536 /* Get the address of the SetServiceStatus function, or return a failure status */
537 pFunc = GetProcAddress(hDll, "SetServiceStatus");
544 /* Close the handle, and save the error code */
545 bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
546 dwLastErr = GetLastError();
548 /* Release the library and then restore the last error
549 * code, in case FreeLibrary altered it.
552 SetLastError(dwLastErr);
556 } /* -END- w32_set_service_status */
559 static void display_win32_msg(BOOL bIsError, char *msg)
566 MessageBox(NULL, msg, "Privoxy Error",
567 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
571 MessageBox(NULL, msg, "Privoxy Information",
572 MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
576 } /* -END- display_win32_msg */
579 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
581 /*********************************************************************
582 * Create a simple display name
583 *********************************************************************/
584 strcpy(pszDisplayName, "Privoxy (");
585 strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
586 strcat(pszDisplayName, ")");
593 BOOL install_service(const char *service_name)
595 char szModule[(MAX_PATH*2)+1];
596 char szDisplayName[MAX_PATH+2];
600 /*********************************************************************
601 * First check if this system can support a service architecture
602 *********************************************************************/
603 if (!CanSystemSupportServices())
605 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
609 /* Use a default service name if none was supplied */
610 if ((service_name == NULL) || (strlen(service_name) == 0))
612 service_name = "privoxy";
615 /*********************************************************************
616 * Open a handle to the Service Control Manager with full access rights
617 *********************************************************************/
618 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
621 display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n Administrator rights are required to create a service.\n");
626 /*********************************************************************
627 * Work out the full image path plus command line for the service
628 * We'll temporarily use szDisplayName as a second buffer.
629 *********************************************************************/
630 GetModuleFileName(NULL, szDisplayName, MAX_PATH);
631 sprintf(szModule, "\"%s\" --service", szDisplayName);
634 /*********************************************************************
635 * Get the display name for the service
636 *********************************************************************/
637 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
640 /*********************************************************************
642 *********************************************************************/
643 hService = w32_create_service(hSCM,
644 service_name, /* the internal service name */
645 szDisplayName, /* the display name */
646 SERVICE_ALL_ACCESS, /* get full access during creation */
647 SERVICE_WIN32_OWN_PROCESS /* run in our own process */
649 + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
652 SERVICE_DEMAND_START, /* For now, only start when asked to */
653 SERVICE_ERROR_NORMAL, /* Normal error handling by the SCM */
654 szModule, /* The executable service file */
655 NULL, /* No load order info needed */
656 NULL, /* No load order info needed */
657 NULL, /* No dependencies */
658 NULL, /* Default to LocalSystem... */
659 NULL); /* ...which doesn't require a password */
660 if (hService == NULL)
662 display_win32_msg(TRUE, "Can't install service!\n");
663 w32_close_service_handle(hSCM);
667 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");
670 w32_close_service_handle(hService);
671 w32_close_service_handle(hSCM);
674 } /* -END- install_service */
678 BOOL uninstall_service(const char *service_name)
680 char szDisplayName[MAX_PATH+2];
683 BOOL bResult = FALSE;
686 /*********************************************************************
687 * First check if this system can support a service architecture
688 *********************************************************************/
689 if (!CanSystemSupportServices())
691 display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
696 /* Use a default service name if none was supplied */
697 if ((service_name == NULL) || (strlen(service_name) == 0))
699 service_name = "privoxy";
703 /*********************************************************************
704 * Open a handle to the Service Control Manager with full access rights
705 *********************************************************************/
706 hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
709 display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n Administrator rights are required to delete a service.\n");
714 /*********************************************************************
715 * Get the display name for the service
716 *********************************************************************/
717 get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
720 /*********************************************************************
721 * Open and then delete the service
722 *********************************************************************/
723 hService = w32_open_service(hSCM, service_name, DELETE);
724 if (hService == NULL)
726 display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
727 w32_close_service_handle(hSCM);
731 if (w32_delete_service(hService))
733 display_win32_msg(FALSE, "Service was deleted successfully.\n");
738 display_win32_msg(TRUE, "Service could not be deleted!\n");
742 w32_close_service_handle(hService);
743 w32_close_service_handle(hSCM);
746 } /* -END- uninstall_service */
750 /*********************************************************************
752 * Function : privoxy_w32_service_start
754 * Description : This is the entry point function for the service.
755 * In other words, it's the ServiceMain function.
757 * Parameters : Defined by the Win32 API, but not used here
761 *********************************************************************/
762 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
766 /* Arg zero is always the service name, and we need to
767 * know it when we call RegisterServiceCtrlHandler.
769 strcpy(szThisServiceName, pszArgs[0]);
771 /* Tell the SCM we are running */
772 srv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
773 srv_status.dwCurrentState = SERVICE_RUNNING;
774 srv_status.dwCheckPoint = 0;
775 srv_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
776 srv_status.dwWin32ExitCode = NO_ERROR;
777 srv_status.dwServiceSpecificExitCode = 0;
778 srv_status.dwWaitHint = 0;
780 hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
785 w32_set_service_status(hSrv_status, &srv_status);
787 #ifndef FEATURE_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 */