handle_established_connection(): Fix format specifiers in log messages
[privoxy.git] / w32svrapi.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/w32svrapi.c,v $
4  *
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.
9  *
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.
17  *
18  * Copyright   :  Written by and Copyright (C) 2003, 2006 members of
19  *                the Privoxy team.  https://www.privoxy.org/
20  *
21  *                Written by and Copyright (C) 2003 Ian Cummings
22  *                <ian_a_c@hotmail.com>
23  *
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.
27  *
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.
33  *
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.
39  *
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.
45  *
46  *********************************************************************/
47
48
49 #include "config.h"
50
51 #ifdef _WIN32
52
53 #include <stdio.h>
54
55 #ifndef STRICT
56 #define STRICT
57 #endif
58 #include <windows.h>
59 #include <process.h>
60
61 #ifndef _WIN_CONSOLE
62 #  include "w32log.h"
63 #endif /* ndef _WIN_CONSOLE */
64
65 #include "w32svrapi.h"
66
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
69  */
70 #ifdef UNICODE
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! :)"
72 #endif
73
74
75 /* Default to not running as service, unless the command line says so */
76 BOOL bRunAsService = FALSE;
77
78 /* According to the Win32 docs for CreateService,
79  * the max length for the service name is 256 chars
80  */
81 char szThisServiceName[260];
82
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;
89
90
91
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()
97 {
98    HMODULE     hDll;
99    FARPROC     pFunc;
100    SC_HANDLE   hScm;
101
102    /* Load the DLL with the SCM functions or return a failure status */
103    hDll = LoadLibrary("Advapi32.dll");
104    if (hDll == NULL)
105    {
106       printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
107       return FALSE;
108    }
109
110    /* Get the address of the ANSI OpenSCManager function, or return a failure status */
111    pFunc = GetProcAddress(hDll, "OpenSCManagerA");
112    if (pFunc == NULL)
113    {
114       printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
115       FreeLibrary(hDll);
116       return FALSE;
117    }
118
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."
122     */
123    hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
124    if (hScm == NULL)
125    {
126       DWORD dwErr = GetLastError();
127       if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
128       {
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
131           */
132          FreeLibrary(hDll);
133          return FALSE;
134       }
135
136       printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
137       FreeLibrary(hDll);
138       return FALSE;
139    }
140
141    w32_close_service_handle(hScm);
142
143    /* OpenSCManager function exists and works, so we're on an NT type platform */
144    FreeLibrary(hDll);
145
146    return TRUE;
147
148 } /* -END- HasServiceControlManager */
149
150
151 BOOL CanSystemSupportServices()
152 {
153    BOOL bHasScm = HasServiceControlManager();
154    return bHasScm;
155
156 } /* -END- CanSystemSupportServices */
157
158
159
160 /*********************************************************************
161  *
162  * The Service functions are defined in <winsvc.h> which is where
163  * the declarations used in this file are taken from
164  *
165  *********************************************************************/
166
167
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 */
175 {
176    HMODULE     hDll = NULL;
177    SC_HANDLE   hScm = NULL;
178    FARPROC     pFunc = NULL;
179    DWORD       dwLastErr = 0;
180
181    /* Load the DLL with the SCM functions or return failure */
182    hDll = LoadLibrary("Advapi32.dll");
183    if (hDll == NULL)
184    {
185       return NULL;
186    }
187
188    /* Get the address of the ANSI OpenSCManager function, or return failure */
189    pFunc = GetProcAddress(hDll, "OpenSCManagerA");
190    if (pFunc == NULL)
191    {
192       FreeLibrary(hDll);
193       return NULL;
194    }
195
196    /* Call the SCM function, and save the error code */
197    hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
198    dwLastErr = GetLastError();
199
200    /* Release the library and then restore the last error
201     * code, in case FreeLibrary altered it.
202     */
203    FreeLibrary(hDll);
204    SetLastError(dwLastErr);
205
206    return hScm;
207
208 } /* -END- w32_open_sc_manager */
209
210
211
212 BOOL w32_close_service_handle(
213   SC_HANDLE hSCObject)   /* handle to service or SCM object */
214 {
215    HMODULE     hDll = NULL;
216    FARPROC     pFunc = NULL;
217    DWORD       dwLastErr = 0;
218    BOOL        bRet;
219
220    /* Load the DLL with the SCM functions or return a failure status */
221    hDll = LoadLibrary("Advapi32.dll");
222    if (hDll == NULL)
223    {
224       return FALSE;
225    }
226
227    /* Get the address of the CloseServiceHandle function, or return a failure status */
228    pFunc = GetProcAddress(hDll, "CloseServiceHandle");
229    if (pFunc == NULL)
230    {
231       FreeLibrary(hDll);
232       return FALSE;
233    }
234
235    /* Close the handle, and save the error code */
236    bRet = (BOOL)(*pFunc)(hSCObject);
237    dwLastErr = GetLastError();
238
239    /* Release the library and then restore the last error
240     * code, in case FreeLibrary altered it.
241     */
242    FreeLibrary(hDll);
243    SetLastError(dwLastErr);
244
245    return bRet;
246
247 } /* -END- w32_close_service_handle */
248
249
250
251 /*********************************************************************
252  * Open a service
253  *********************************************************************/
254 SC_HANDLE w32_open_service(
255   SC_HANDLE hSCManager,   /* handle to SCM database */
256   LPCTSTR lpServiceName,  /* service name */
257   DWORD dwDesiredAccess)  /* access */
258 {
259    HMODULE     hDll = NULL;
260    SC_HANDLE   hSrv = NULL;
261    FARPROC     pFunc = NULL;
262    DWORD       dwLastErr = 0;
263
264    /* Load the DLL with the SCM functions or return failure */
265    hDll = LoadLibrary("Advapi32.dll");
266    if (hDll == NULL)
267    {
268       return NULL;
269    }
270
271    /* Get the address of the ANSI OpenService function, or return failure */
272    pFunc = GetProcAddress(hDll, "OpenServiceA");
273    if (pFunc == NULL)
274    {
275       FreeLibrary(hDll);
276       return NULL;
277    }
278
279    /* Call the SCM function, and save the error code */
280    hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
281    dwLastErr = GetLastError();
282
283    /* Release the library and then restore the last error
284     * code, in case FreeLibrary altered it.
285     */
286    FreeLibrary(hDll);
287    SetLastError(dwLastErr);
288
289    return hSrv;
290
291 } /* -END- w32_open_service */
292
293
294
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 */
309 {
310    HMODULE     hDll = NULL;
311    SC_HANDLE   hSrv = NULL;
312    FARPROC     pFunc = NULL;
313    DWORD       dwLastErr = 0;
314
315    /* Load the DLL with the SCM functions or return failure */
316    hDll = LoadLibrary("Advapi32.dll");
317    if (hDll == NULL)
318    {
319       return NULL;
320    }
321
322    /* Get the address of the ANSI CreateService function, or return failure */
323    pFunc = GetProcAddress(hDll, "CreateServiceA");
324    if (pFunc == NULL)
325    {
326       FreeLibrary(hDll);
327       return NULL;
328    }
329
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();
345
346    /* Release the library and then restore the last error
347     * code, in case FreeLibrary altered it.
348     */
349    FreeLibrary(hDll);
350    SetLastError(dwLastErr);
351
352    return hSrv;
353
354 } /* -END- w32_create_service */
355
356
357
358 BOOL w32_delete_service(
359   SC_HANDLE hService)   /* handle to service */
360 {
361    HMODULE     hDll = NULL;
362    FARPROC     pFunc = NULL;
363    DWORD       dwLastErr = 0;
364    BOOL        bRet;
365
366    /* Load the DLL with the SCM functions or return a failure status */
367    hDll = LoadLibrary("Advapi32.dll");
368    if (hDll == NULL)
369    {
370       return FALSE;
371    }
372
373    /* Get the address of the DeleteService function, or return a failure status */
374    pFunc = GetProcAddress(hDll, "DeleteService");
375    if (pFunc == NULL)
376    {
377       FreeLibrary(hDll);
378       return FALSE;
379    }
380
381    /* Close the handle, and save the error code */
382    bRet = (BOOL)(*pFunc)(hService);
383    dwLastErr = GetLastError();
384
385    /* Release the library and then restore the last error
386     * code, in case FreeLibrary altered it.
387     */
388    FreeLibrary(hDll);
389    SetLastError(dwLastErr);
390
391    return bRet;
392
393 } /* -END- w32_delete_service */
394
395
396
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 */
402 {
403    HMODULE     hDll = NULL;
404    FARPROC     pFunc = NULL;
405    DWORD       dwLastErr = 0;
406    BOOL        bRet;
407
408    /* Load the DLL with the SCM functions or return a failure status */
409    hDll = LoadLibrary("Advapi32.dll");
410    if (hDll == NULL)
411    {
412       return FALSE;
413    }
414
415    /* Get the address of the QueryServiceConfig function, or return a failure status */
416    pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
417    if (pFunc == NULL)
418    {
419       FreeLibrary(hDll);
420       return FALSE;
421    }
422
423    /* Close the handle, and save the error code */
424    bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
425    dwLastErr = GetLastError();
426
427    /* Release the library and then restore the last error
428     * code, in case FreeLibrary altered it.
429     */
430    FreeLibrary(hDll);
431    SetLastError(dwLastErr);
432
433    return bRet;
434
435 } /* -END- w32_query_service_config */
436
437
438 BOOL w32_start_service_ctrl_dispatcher(
439   CONST LPSERVICE_TABLE_ENTRY lpServiceTable)   /* service table */
440 {
441    HMODULE     hDll = NULL;
442    FARPROC     pFunc = NULL;
443    DWORD       dwLastErr = 0;
444    BOOL        bRet;
445
446    /* Load the DLL with the SCM functions or return a failure status */
447    hDll = LoadLibrary("Advapi32.dll");
448    if (hDll == NULL)
449    {
450       return FALSE;
451    }
452
453    /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
454    pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
455    if (pFunc == NULL)
456    {
457       FreeLibrary(hDll);
458       return FALSE;
459    }
460
461    /* Close the handle, and save the error code */
462    bRet = (BOOL)(*pFunc)(lpServiceTable);
463    dwLastErr = GetLastError();
464
465    /* Release the library and then restore the last error
466     * code, in case FreeLibrary altered it.
467     */
468    FreeLibrary(hDll);
469    SetLastError(dwLastErr);
470
471    return bRet;
472
473 } /* -END- w32_start_service_ctrl_dispatcher */
474
475
476
477 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
478   LPCTSTR lpServiceName,               /* service name */
479   LPHANDLER_FUNCTION lpHandlerProc)    /* handler function */
480 {
481    HMODULE     hDll = NULL;
482    FARPROC     pFunc = NULL;
483    DWORD       dwLastErr = 0;
484    SERVICE_STATUS_HANDLE hServStat = (SERVICE_STATUS_HANDLE)0;
485
486    /* Load the DLL with the SCM functions or return a failure status */
487    hDll = LoadLibrary("Advapi32.dll");
488    if (hDll == NULL)
489    {
490       return hServStat;
491    }
492
493    /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
494    pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
495    if (pFunc == NULL)
496    {
497       FreeLibrary(hDll);
498       return hServStat;
499    }
500
501    /* Close the handle, and save the error code */
502    hServStat = (SERVICE_STATUS_HANDLE)(*pFunc)(lpServiceName, lpHandlerProc);
503    dwLastErr = GetLastError();
504
505    /* Release the library and then restore the last error
506     * code, in case FreeLibrary altered it.
507     */
508    FreeLibrary(hDll);
509    SetLastError(dwLastErr);
510
511    return hServStat;
512
513 } /* -END- w32_register_service_ctrl_handler */
514
515
516
517 BOOL w32_set_service_status(
518   SERVICE_STATUS_HANDLE hServiceStatus,   /* service status handle */
519   LPSERVICE_STATUS lpServiceStatus)       /* status buffer */
520 {
521    HMODULE     hDll = NULL;
522    FARPROC     pFunc = NULL;
523    DWORD       dwLastErr = 0;
524    BOOL        bRet;
525
526    /* Load the DLL with the SCM functions or return a failure status */
527    hDll = LoadLibrary("Advapi32.dll");
528    if (hDll == NULL)
529    {
530       return FALSE;
531    }
532
533    /* Get the address of the SetServiceStatus function, or return a failure status */
534    pFunc = GetProcAddress(hDll, "SetServiceStatus");
535    if (pFunc == NULL)
536    {
537       FreeLibrary(hDll);
538       return FALSE;
539    }
540
541    /* Close the handle, and save the error code */
542    bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
543    dwLastErr = GetLastError();
544
545    /* Release the library and then restore the last error
546     * code, in case FreeLibrary altered it.
547     */
548    FreeLibrary(hDll);
549    SetLastError(dwLastErr);
550
551    return bRet;
552
553 } /* -END- w32_set_service_status */
554
555
556 static void display_win32_msg(BOOL bIsError, char *msg)
557 {
558 #ifdef _WIN_CONSOLE
559    printf("%s", msg);
560 #else
561    if (bIsError)
562    {
563       MessageBox(NULL, msg, "Privoxy Error",
564          MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
565    }
566    else
567    {
568       MessageBox(NULL, msg, "Privoxy Information",
569          MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
570    }
571 #endif
572
573 } /* -END- display_win32_msg */
574
575
576 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
577 {
578    /*********************************************************************
579     * Create a simple display name
580     *********************************************************************/
581    strcpy(pszDisplayName, "Privoxy (");
582    strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
583    strcat(pszDisplayName, ")");
584
585    return TRUE;
586 }
587
588
589
590 BOOL install_service(const char *service_name)
591 {
592    char szModule[(MAX_PATH*2)+1];
593    char szDisplayName[MAX_PATH+2];
594    SC_HANDLE hSCM;
595    SC_HANDLE hService;
596
597    /*********************************************************************
598     * First check if this system can support a service architecture
599     *********************************************************************/
600    if (!CanSystemSupportServices())
601    {
602       display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
603       return FALSE;
604    }
605
606    /* Use a default service name if none was supplied */
607    if ((service_name == NULL) || (strlen(service_name) == 0))
608    {
609       service_name = "privoxy";
610    }
611
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);
616    if (hSCM == NULL)
617    {
618       display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n  Administrator rights are required to create a service.\n");
619       return FALSE;
620    }
621
622
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);
629
630
631    /*********************************************************************
632     * Get the display name for the service
633     *********************************************************************/
634    get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
635
636
637    /*********************************************************************
638     * Create the service
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 */
645 #ifndef _WIN_CONSOLE
646                          + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
647 #endif
648                            ,
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)
658    {
659       display_win32_msg(TRUE, "Can't install service!\n");
660       w32_close_service_handle(hSCM);
661       return FALSE;
662    }
663
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");
665
666    /* tidy up */
667    w32_close_service_handle(hService);
668    w32_close_service_handle(hSCM);
669    return TRUE;
670
671 } /* -END- install_service */
672
673
674
675 BOOL uninstall_service(const char *service_name)
676 {
677    char szDisplayName[MAX_PATH+2];
678    SC_HANDLE hSCM;
679    SC_HANDLE hService;
680    BOOL bResult = FALSE;
681
682
683    /*********************************************************************
684     * First check if this system can support a service architecture
685     *********************************************************************/
686    if (!CanSystemSupportServices())
687    {
688       display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
689       return FALSE;
690    }
691
692
693    /* Use a default service name if none was supplied */
694    if ((service_name == NULL) || (strlen(service_name) == 0))
695    {
696       service_name = "privoxy";
697    }
698
699
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);
704    if (hSCM == NULL)
705    {
706       display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n  Administrator rights are required to delete a service.\n");
707       return FALSE;
708    }
709
710
711    /*********************************************************************
712     * Get the display name for the service
713     *********************************************************************/
714    get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
715
716
717    /*********************************************************************
718     * Open and then delete the service
719     *********************************************************************/
720    hService = w32_open_service(hSCM, service_name, DELETE);
721    if (hService == NULL)
722    {
723       display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
724       w32_close_service_handle(hSCM);
725       return FALSE;
726    }
727
728    if (w32_delete_service(hService))
729    {
730       display_win32_msg(FALSE, "Service was deleted successfully.\n");
731       bResult = TRUE;
732    }
733    else
734    {
735       display_win32_msg(TRUE, "Service could not be deleted!\n");
736       bResult = FALSE;
737    }
738
739    w32_close_service_handle(hService);
740    w32_close_service_handle(hSCM);
741    return bResult;
742
743 } /* -END- uninstall_service */
744
745
746
747 /*********************************************************************
748  *
749  * Function    :  privoxy_w32_service_start
750  *
751  * Description :  This is the entry point function for the service.
752  *                In other words, it's the ServiceMain function.
753  *
754  * Parameters  :  Defined by the Win32 API, but not used here
755  *
756  * Returns     :  void
757  *
758  *********************************************************************/
759 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
760 {
761    int child_id;
762
763    /* Arg zero is always the service name, and we need to
764     * know it when we call RegisterServiceCtrlHandler.
765     */
766    strcpy(szThisServiceName, pszArgs[0]);
767
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;
776
777    hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
778    if (!hSrv_status)
779    {
780       return;
781    }
782    w32_set_service_status(hSrv_status, &srv_status);
783
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
787     */
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 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.
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