e6f236389d9352cf9546bf4a9968aea0c5e154fe
[privoxy.git] / w32svrapi.c
1 const char w32_svrapi_rcs[] = "$Id$";
2 /*********************************************************************
3  *
4  * File        :  $Source$
5  *
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.
10  *
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.
18  *
19  * Copyright   :  Written by and Copyright (C) 2003 members of
20  *                the Privoxy team.  http://www.privoxy.org/
21  *
22  *                Written by and Copyright (C) 2003 Ian Cummings
23  *                <ian_a_c@hotmail.com>
24  *
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.
28  *
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.
34  *
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.
40  *
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.
46  *
47  * Revisions   :
48  *    $Log$
49  *
50  *
51  *********************************************************************/
52 \f
53
54 #include "config.h"
55
56 #ifdef _WIN32
57
58 #include <stdio.h>
59
60 #ifndef STRICT
61 #define STRICT
62 #endif
63 #include <windows.h>
64 #include <process.h>
65
66 #ifndef _WIN_CONSOLE
67 #  include "w32log.h"
68 #endif /* ndef _WIN_CONSOLE */
69
70 #include "w32svrapi.h"
71 const char w32_svrapi_h_rcs[] = W32_SVRAPI_H_VERSION;
72
73
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
76  */
77 #ifdef UNICODE
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! :)"
79 #endif
80
81
82 /* Default to not running as service, unless the command line says so */
83 BOOL bRunAsService = FALSE;
84
85 /* According to the Win32 docs for CreateService,
86  * the max length for the service name is 256 chars
87  */
88 char szThisServiceName[260];
89
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;
96
97
98
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()
104 {
105    HMODULE     hDll;
106    FARPROC     pFunc;
107    SC_HANDLE   hScm;
108
109    /* Load the DLL with the SCM functions or return a failure status */
110    hDll = LoadLibrary("Advapi32.dll");
111    if (hDll == NULL)
112    {
113       printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
114       return FALSE;
115    }
116
117    /* Get the address of the ANSI OpenSCManager function, or return a failure status */
118    pFunc = GetProcAddress(hDll, "OpenSCManagerA");
119    if (pFunc == NULL)
120    {
121       printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
122       FreeLibrary(hDll);
123       return FALSE;
124    }
125
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."
129     */
130    hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
131    if (hScm == NULL)
132    {
133       DWORD dwErr = GetLastError();
134       if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
135       {
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
138           */
139          FreeLibrary(hDll);
140          return FALSE;
141       }
142
143       printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
144       FreeLibrary(hDll);
145       return FALSE;
146    }
147
148    w32_close_service_handle(hScm);
149
150    /* OpenSCManager function exists and works, so we're on an NT type platform */
151    FreeLibrary(hDll);
152
153    return TRUE;
154
155 } /* -END- HasServiceControlManager */
156
157
158 BOOL CanSystemSupportServices()
159 {
160    BOOL bHasScm = HasServiceControlManager();
161    return bHasScm;
162
163 } /* -END- CanSystemSupportServices */
164
165
166
167 /*********************************************************************
168  *
169  * The Service functions are defined in <winsvc.h> which is where
170  * the declarations used in this file are taken from
171  *
172  *********************************************************************/ 
173
174
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 */
182 {
183    HMODULE     hDll = NULL;
184    SC_HANDLE   hScm = NULL;
185    FARPROC     pFunc = NULL;
186    DWORD       dwLastErr = 0;
187
188    /* Load the DLL with the SCM functions or return failure */
189    hDll = LoadLibrary("Advapi32.dll");
190    if (hDll == NULL)
191    {
192       return NULL;
193    }
194
195    /* Get the address of the ANSI OpenSCManager function, or return failure */
196    pFunc = GetProcAddress(hDll, "OpenSCManagerA");
197    if (pFunc == NULL)
198    {
199       FreeLibrary(hDll);
200       return NULL;
201    }
202
203    /* Call the SCM function, and save the error code */
204    hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
205    dwLastErr = GetLastError();
206
207    /* Release the library and then restore the last error
208     * code, in case FreeLibrary altered it.
209     */
210    FreeLibrary(hDll);
211    SetLastError(dwLastErr);
212      
213    return hScm;
214
215 } /* -END- w32_open_sc_manager */
216
217
218
219 BOOL w32_close_service_handle(
220   SC_HANDLE hSCObject)   /* handle to service or SCM object */
221 {
222    HMODULE     hDll = NULL;
223    FARPROC     pFunc = NULL;
224    DWORD       dwLastErr = 0;
225    BOOL        bRet;
226
227    /* Load the DLL with the SCM functions or return a failure status */
228    hDll = LoadLibrary("Advapi32.dll");
229    if (hDll == NULL)
230    {
231       return FALSE;
232    }
233
234    /* Get the address of the CloseServiceHandle function, or return a failure status */
235    pFunc = GetProcAddress(hDll, "CloseServiceHandle");
236    if (pFunc == NULL)
237    {
238       FreeLibrary(hDll);
239       return FALSE;
240    }
241
242    /* Close the handle, and save the error code */
243    bRet = (BOOL)(*pFunc)(hSCObject);
244    dwLastErr = GetLastError();
245
246    /* Release the library and then restore the last error
247     * code, in case FreeLibrary altered it.
248     */
249    FreeLibrary(hDll);
250    SetLastError(dwLastErr);
251
252    return bRet;
253
254 } /* -END- w32_close_service_handle */
255
256
257
258 /*********************************************************************
259  * Open a service
260  *********************************************************************/ 
261 SC_HANDLE w32_open_service(
262   SC_HANDLE hSCManager,   /* handle to SCM database */
263   LPCTSTR lpServiceName,  /* service name */
264   DWORD dwDesiredAccess)  /* access */
265 {
266    HMODULE     hDll = NULL;
267    SC_HANDLE   hSrv = NULL;
268    FARPROC     pFunc = NULL;
269    DWORD       dwLastErr = 0;
270
271    /* Load the DLL with the SCM functions or return failure */
272    hDll = LoadLibrary("Advapi32.dll");
273    if (hDll == NULL)
274    {
275       return NULL;
276    }
277
278    /* Get the address of the ANSI OpenService function, or return failure */
279    pFunc = GetProcAddress(hDll, "OpenServiceA");
280    if (pFunc == NULL)
281    {
282       FreeLibrary(hDll);
283       return NULL;
284    }
285
286    /* Call the SCM function, and save the error code */
287    hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
288    dwLastErr = GetLastError();
289
290    /* Release the library and then restore the last error
291     * code, in case FreeLibrary altered it.
292     */
293    FreeLibrary(hDll);
294    SetLastError(dwLastErr);
295      
296    return hSrv;
297
298 } /* -END- w32_open_service */
299
300
301
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 */
316 {
317    HMODULE     hDll = NULL;
318    SC_HANDLE   hSrv = NULL;
319    FARPROC     pFunc = NULL;
320    DWORD       dwLastErr = 0;
321
322    /* Load the DLL with the SCM functions or return failure */
323    hDll = LoadLibrary("Advapi32.dll");
324    if (hDll == NULL)
325    {
326       return NULL;
327    }
328
329    /* Get the address of the ANSI CreateService function, or return failure */
330    pFunc = GetProcAddress(hDll, "CreateServiceA");
331    if (pFunc == NULL)
332    {
333       FreeLibrary(hDll);
334       return NULL;
335    }
336
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();
352
353    /* Release the library and then restore the last error
354     * code, in case FreeLibrary altered it.
355     */
356    FreeLibrary(hDll);
357    SetLastError(dwLastErr);
358      
359    return hSrv;
360
361 } /* -END- w32_create_service */
362
363
364
365 BOOL w32_delete_service(
366   SC_HANDLE hService)   /* handle to service */
367 {
368    HMODULE     hDll = NULL;
369    FARPROC     pFunc = NULL;
370    DWORD       dwLastErr = 0;
371    BOOL        bRet;
372
373    /* Load the DLL with the SCM functions or return a failure status */
374    hDll = LoadLibrary("Advapi32.dll");
375    if (hDll == NULL)
376    {
377       return FALSE;
378    }
379
380    /* Get the address of the DeleteService function, or return a failure status */
381    pFunc = GetProcAddress(hDll, "DeleteService");
382    if (pFunc == NULL)
383    {
384       FreeLibrary(hDll);
385       return FALSE;
386    }
387
388    /* Close the handle, and save the error code */
389    bRet = (BOOL)(*pFunc)(hService);
390    dwLastErr = GetLastError();
391
392    /* Release the library and then restore the last error
393     * code, in case FreeLibrary altered it.
394     */
395    FreeLibrary(hDll);
396    SetLastError(dwLastErr);
397
398    return bRet;
399
400 } /* -END- w32_delete_service */
401
402
403
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 */
409 {
410    HMODULE     hDll = NULL;
411    FARPROC     pFunc = NULL;
412    DWORD       dwLastErr = 0;
413    BOOL        bRet;
414
415    /* Load the DLL with the SCM functions or return a failure status */
416    hDll = LoadLibrary("Advapi32.dll");
417    if (hDll == NULL)
418    {
419       return FALSE;
420    }
421
422    /* Get the address of the QueryServiceConfig function, or return a failure status */
423    pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
424    if (pFunc == NULL)
425    {
426       FreeLibrary(hDll);
427       return FALSE;
428    }
429
430    /* Close the handle, and save the error code */
431    bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
432    dwLastErr = GetLastError();
433
434    /* Release the library and then restore the last error
435     * code, in case FreeLibrary altered it.
436     */
437    FreeLibrary(hDll);
438    SetLastError(dwLastErr);
439
440    return bRet;
441
442 } /* -END- w32_query_service_config */
443
444
445 BOOL w32_start_service_ctrl_dispatcher(
446   CONST LPSERVICE_TABLE_ENTRY lpServiceTable)   /* service table */
447 {
448    HMODULE     hDll = NULL;
449    FARPROC     pFunc = NULL;
450    DWORD       dwLastErr = 0;
451    BOOL        bRet;
452
453    /* Load the DLL with the SCM functions or return a failure status */
454    hDll = LoadLibrary("Advapi32.dll");
455    if (hDll == NULL)
456    {
457       return FALSE;
458    }
459
460    /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
461    pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
462    if (pFunc == NULL)
463    {
464       FreeLibrary(hDll);
465       return FALSE;
466    }
467
468    /* Close the handle, and save the error code */
469    bRet = (BOOL)(*pFunc)(lpServiceTable);
470    dwLastErr = GetLastError();
471
472    /* Release the library and then restore the last error
473     * code, in case FreeLibrary altered it.
474     */
475    FreeLibrary(hDll);
476    SetLastError(dwLastErr);
477
478    return bRet;
479
480 } /* -END- w32_start_service_ctrl_dispatcher */
481
482
483
484 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
485   LPCTSTR lpServiceName,               /* service name */
486   LPHANDLER_FUNCTION lpHandlerProc)    /* handler function */
487 {
488    HMODULE     hDll = NULL;
489    FARPROC     pFunc = NULL;
490    DWORD       dwLastErr = 0;
491    BOOL        bRet;
492
493    /* Load the DLL with the SCM functions or return a failure status */
494    hDll = LoadLibrary("Advapi32.dll");
495    if (hDll == NULL)
496    {
497       return FALSE;
498    }
499
500    /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
501    pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
502    if (pFunc == NULL)
503    {
504       FreeLibrary(hDll);
505       return FALSE;
506    }
507
508    /* Close the handle, and save the error code */
509    bRet = (BOOL)(*pFunc)(lpServiceName, lpHandlerProc);
510    dwLastErr = GetLastError();
511
512    /* Release the library and then restore the last error
513     * code, in case FreeLibrary altered it.
514     */
515    FreeLibrary(hDll);
516    SetLastError(dwLastErr);
517
518    return bRet;
519
520 } /* -END- w32_register_service_ctrl_handler */
521
522
523
524 BOOL w32_set_service_status(
525   SERVICE_STATUS_HANDLE hServiceStatus,   /* service status handle */
526   LPSERVICE_STATUS lpServiceStatus)       /* status buffer */
527 {
528    HMODULE     hDll = NULL;
529    FARPROC     pFunc = NULL;
530    DWORD       dwLastErr = 0;
531    BOOL        bRet;
532
533    /* Load the DLL with the SCM functions or return a failure status */
534    hDll = LoadLibrary("Advapi32.dll");
535    if (hDll == NULL)
536    {
537       return FALSE;
538    }
539
540    /* Get the address of the SetServiceStatus function, or return a failure status */
541    pFunc = GetProcAddress(hDll, "SetServiceStatus");
542    if (pFunc == NULL)
543    {
544       FreeLibrary(hDll);
545       return FALSE;
546    }
547
548    /* Close the handle, and save the error code */
549    bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
550    dwLastErr = GetLastError();
551
552    /* Release the library and then restore the last error
553     * code, in case FreeLibrary altered it.
554     */
555    FreeLibrary(hDll);
556    SetLastError(dwLastErr);
557
558    return bRet;
559
560 } /* -END- w32_set_service_status */
561
562
563 static void display_win32_msg(BOOL bIsError, char *msg)
564 {
565 #ifdef _WIN_CONSOLE
566    printf("%s", msg);
567 #else
568    if (bIsError)
569    {
570       MessageBox(NULL, msg, "Privoxy Error", 
571          MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
572    }
573    else
574    {
575       MessageBox(NULL, msg, "Privoxy Information", 
576          MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
577    }
578 #endif
579
580 } /* -END- display_win32_msg */
581
582
583 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
584 {
585    /*********************************************************************
586     * Create a simple display name
587     *********************************************************************/
588    strcpy(pszDisplayName, "Privoxy (");
589    strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
590    strcat(pszDisplayName, ")");
591
592    return TRUE;
593 }
594
595
596
597 BOOL install_service(const char *service_name)
598 {
599    char szModule[(MAX_PATH*2)+1];
600    char szDisplayName[MAX_PATH+2];
601    SC_HANDLE hSCM;
602    SC_HANDLE hService;
603
604    /*********************************************************************
605     * First check if this system can support a service architecture
606     *********************************************************************/
607    if (!CanSystemSupportServices())
608    {
609       display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
610       return FALSE;
611    }
612
613    /* Use a default service name if none was supplied */
614    if ((service_name == NULL) || (strlen(service_name) == 0))
615    {
616       service_name = "privoxy";
617    }
618
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);
623    if (hSCM == NULL)
624    {
625       display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n  Administrator rights are required to create a service.\n");
626       return FALSE;
627    }
628
629
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); 
636
637    
638    /*********************************************************************
639     * Get the display name for the service
640     *********************************************************************/
641    get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
642
643
644    /*********************************************************************
645     * Create the service
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 */
652 #ifndef _WIN_CONSOLE
653                          + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
654 #endif
655                            ,
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)
665    {
666       display_win32_msg(TRUE, "Can't install service!\n");
667       w32_close_service_handle(hSCM);
668       return FALSE;
669    }
670
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");
672
673    /* tidy up */
674    w32_close_service_handle(hService);
675    w32_close_service_handle(hSCM);
676    return TRUE;
677
678 } /* -END- install_service */
679
680
681
682 BOOL uninstall_service(const char *service_name)
683 {
684    char szDisplayName[MAX_PATH+2];
685    SC_HANDLE hSCM;
686    SC_HANDLE hService;
687    BOOL bResult = FALSE;
688
689
690    /*********************************************************************
691     * First check if this system can support a service architecture
692     *********************************************************************/
693    if (!CanSystemSupportServices())
694    {
695       display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
696       return FALSE;
697    }
698
699
700    /* Use a default service name if none was supplied */
701    if ((service_name == NULL) || (strlen(service_name) == 0))
702    {
703       service_name = "privoxy";
704    }
705
706
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);
711    if (hSCM == NULL)
712    {
713       display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n  Administrator rights are required to delete a service.\n");
714       return FALSE;
715    }
716
717
718    /*********************************************************************
719     * Get the display name for the service
720     *********************************************************************/
721    get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
722
723
724    /*********************************************************************
725     * Open and then delete the service
726     *********************************************************************/
727    hService = w32_open_service(hSCM, service_name, DELETE);
728    if (hService == NULL)
729    {
730       display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
731       w32_close_service_handle(hSCM);
732       return FALSE;
733    }
734
735    if (w32_delete_service(hService))
736    {
737       display_win32_msg(FALSE, "Service was deleted successfully.\n");
738       bResult = TRUE;
739    }
740    else
741    {
742       display_win32_msg(TRUE, "Service could not be deleted!\n");
743       bResult = FALSE;
744    }
745
746    w32_close_service_handle(hService);
747    w32_close_service_handle(hSCM);
748    return bResult;
749
750 } /* -END- uninstall_service */
751
752
753
754 /*********************************************************************
755  *
756  * Function    :  privoxy_w32_service_start
757  *
758  * Description :  This is the entry point function for the service.
759  *                In other words, it's the ServiceMain function.
760  *
761  * Parameters  :  Defined by the Win32 API, but not used here
762  *
763  * Returns     :  void
764  *
765  *********************************************************************/
766 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
767 {
768    int child_id;
769
770    /* Arg zero is always the service name, and we need to 
771     * know it when we call RegisterServiceCtrlHandler.
772     */
773    strcpy(szThisServiceName, pszArgs[0]);
774
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;
783
784    hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
785    if (!hSrv_status)
786    {
787       return;
788    }
789    w32_set_service_status(hSrv_status, &srv_status);
790
791 #ifndef FEATURE_PTHREAD
792    child_id = _beginthread(w32_service_listen_loop, 0, NULL);
793    if (child_id > 0)
794 #else
795 #error "FIXME: Do pthread stuff here!"
796 #endif
797    {
798       w32_set_service_status(hSrv_status, &srv_status);
799    }
800    else
801    {
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);
807    }
808 }
809
810
811 /*********************************************************************
812  *
813  * Function    :  w32_set_service_cwd
814  *
815  * Description :  Simple function to change the current directory to
816  *                the same location as the service executable.
817  *
818  * Parameters  :  void
819  *
820  * Returns     :  void
821  *
822  *********************************************************************/
823 void w32_set_service_cwd(void)
824 {
825    char exe_name[MAX_PATH+1];
826    char dir_name[MAX_PATH+1];
827    char *pszFile = NULL;
828
829    /* Get the exe name and path of the service */
830    if (GetModuleFileName(NULL, exe_name, MAX_PATH))
831    {
832       /* Ask the API to tell us where the filename portion starts */
833       if (GetFullPathName(exe_name, MAX_PATH, dir_name, &pszFile))
834       {
835          /* remove the filename from the string */
836          if (pszFile != NULL)
837          {
838             *pszFile = '\0';
839             /* We have just a directory path now, so make it current */
840             SetCurrentDirectory(dir_name);
841          }
842       }
843    }
844 }
845
846
847 /*********************************************************************
848  *
849  * Function    :  w32_service_exit_notify
850  *
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
855  *                now stopped.
856  *
857  * Parameters  :  void
858  *
859  * Returns     :  void
860  *
861  *********************************************************************/
862 void w32_service_exit_notify(void)
863 {
864    if (hSrv_status != 0)
865    {
866       if (srv_status.dwCurrentState != SERVICE_STOPPED)
867       {
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);
873       }
874    }
875 }
876
877
878 static void w32_mini_exit(void *p)
879 {
880    Sleep(100);
881 #ifdef _WIN_CONSOLE
882    exit(0);
883 #else
884    PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
885 #endif /* def _WIN_CONSOLE */
886 }
887
888
889 /*********************************************************************
890  *
891  * Function    :  privoxy_w32_service_handler
892  *
893  * Description :  This is the control message handler function for
894  *                the service.
895  *
896  * Parameters  :  dwOpcode
897  *                   requested control code sent by SCM
898  *
899  * Returns     :  void
900  *
901  *********************************************************************/
902 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode)
903 {
904    switch(dwOpcode)
905    {
906       case SERVICE_CONTROL_STOP:
907          /* We've stopped
908           */
909          srv_status.dwCurrentState = SERVICE_STOPPED;
910          srv_status.dwCheckPoint = 0;
911          srv_status.dwWin32ExitCode = NO_ERROR;
912          srv_status.dwServiceSpecificExitCode = 0;
913
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);
916
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.
920           *
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.
925           */
926
927          if (_beginthread(w32_mini_exit, 0, NULL) < 0)
928          {
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!
931              */
932             exit(0);
933          }
934          break;
935
936       default:
937          break;
938    }
939
940    w32_set_service_status(hSrv_status, &srv_status);
941 }
942
943
944 #endif /* ifdef _WIN32 */
945