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