Anchor a few regexes in handle_loglevel_connect().
[privoxy.git] / w32svrapi.c
1 const char w32_svrapi_rcs[] = "$Id: w32svrapi.c,v 1.1 2006/08/12 03:54:37 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  * Revisions   :
48  *    $Log: w32svrapi.c,v $
49  *    Revision 1.1  2006/08/12 03:54:37  david__schmidt
50  *    Windows service integration
51  *
52  *
53  *
54  *********************************************************************/
55 \f
56
57 #include "config.h"
58
59 #ifdef _WIN32
60
61 #include <stdio.h>
62
63 #ifndef STRICT
64 #define STRICT
65 #endif
66 #include <windows.h>
67 #include <process.h>
68
69 #ifndef _WIN_CONSOLE
70 #  include "w32log.h"
71 #endif /* ndef _WIN_CONSOLE */
72
73 #include "w32svrapi.h"
74 const char w32_svrapi_h_rcs[] = W32_SVRAPI_H_VERSION;
75
76
77 /* Only the ANSI Win32 APIs are used at this time. If for some
78  * reason, we're building under unicode then we must stop
79  */
80 #ifdef UNICODE
81 #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! :)"
82 #endif
83
84
85 /* Default to not running as service, unless the command line says so */
86 BOOL bRunAsService = FALSE;
87
88 /* According to the Win32 docs for CreateService,
89  * the max length for the service name is 256 chars
90  */
91 char szThisServiceName[260];
92
93 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize);
94 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* psz);
95 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode);
96 SERVICE_TABLE_ENTRY w32ServiceDispatchTable[] = {{"", privoxy_w32_service_start}, {NULL, NULL}};
97 static SERVICE_STATUS_HANDLE hSrv_status = 0;
98 static SERVICE_STATUS srv_status;
99
100
101
102 /*********************************************************************
103  * This function returns TRUE if we are running on an OS that can
104  * support services, like NT, etc. It returns FALSE for Win9x/ME.
105  *********************************************************************/
106 static BOOL HasServiceControlManager()
107 {
108    HMODULE     hDll;
109    FARPROC     pFunc;
110    SC_HANDLE   hScm;
111
112    /* Load the DLL with the SCM functions or return a failure status */
113    hDll = LoadLibrary("Advapi32.dll");
114    if (hDll == NULL)
115    {
116       printf("Can't load Advapi32.dll -- LoadLibrary failed!\n");
117       return FALSE;
118    }
119
120    /* Get the address of the ANSI OpenSCManager function, or return a failure status */
121    pFunc = GetProcAddress(hDll, "OpenSCManagerA");
122    if (pFunc == NULL)
123    {
124       printf("Can't find OpenSCManagerA -- GetProcAddress failed!\n");
125       FreeLibrary(hDll);
126       return FALSE;
127    }
128
129    /* Try and connect to the SCM. If it fails check and see if the error 
130     * code is ERROR_CALL_NOT_IMPLEMENTED, which means:
131     *    "This function is not supported on this system."
132     */
133    hScm = (SC_HANDLE)(*pFunc)(NULL, NULL, SC_MANAGER_CONNECT);
134    if (hScm == NULL)
135    {
136       DWORD dwErr = GetLastError();
137       if (dwErr == ERROR_CALL_NOT_IMPLEMENTED)
138       {
139          /* Expected error under Win9x/Me, so don't print any debug info
140           * here as we'll leave that up to the calling function to do
141           */
142          FreeLibrary(hDll);
143          return FALSE;
144       }
145
146       printf("Call to OpenSCManager failed -- GetLastError() returned %lu!\n", dwErr);
147       FreeLibrary(hDll);
148       return FALSE;
149    }
150
151    w32_close_service_handle(hScm);
152
153    /* OpenSCManager function exists and works, so we're on an NT type platform */
154    FreeLibrary(hDll);
155
156    return TRUE;
157
158 } /* -END- HasServiceControlManager */
159
160
161 BOOL CanSystemSupportServices()
162 {
163    BOOL bHasScm = HasServiceControlManager();
164    return bHasScm;
165
166 } /* -END- CanSystemSupportServices */
167
168
169
170 /*********************************************************************
171  *
172  * The Service functions are defined in <winsvc.h> which is where
173  * the declarations used in this file are taken from
174  *
175  *********************************************************************/ 
176
177
178 /*********************************************************************
179  * Open a connection to the service control manager
180  *********************************************************************/ 
181 SC_HANDLE w32_open_sc_manager(
182   LPCTSTR lpMachineName,   /* computer name */
183   LPCTSTR lpDatabaseName,  /* SCM database name */
184   DWORD dwDesiredAccess)   /* access type */
185 {
186    HMODULE     hDll = NULL;
187    SC_HANDLE   hScm = NULL;
188    FARPROC     pFunc = NULL;
189    DWORD       dwLastErr = 0;
190
191    /* Load the DLL with the SCM functions or return failure */
192    hDll = LoadLibrary("Advapi32.dll");
193    if (hDll == NULL)
194    {
195       return NULL;
196    }
197
198    /* Get the address of the ANSI OpenSCManager function, or return failure */
199    pFunc = GetProcAddress(hDll, "OpenSCManagerA");
200    if (pFunc == NULL)
201    {
202       FreeLibrary(hDll);
203       return NULL;
204    }
205
206    /* Call the SCM function, and save the error code */
207    hScm = (SC_HANDLE)(*pFunc)(lpMachineName, lpDatabaseName, dwDesiredAccess);
208    dwLastErr = GetLastError();
209
210    /* Release the library and then restore the last error
211     * code, in case FreeLibrary altered it.
212     */
213    FreeLibrary(hDll);
214    SetLastError(dwLastErr);
215      
216    return hScm;
217
218 } /* -END- w32_open_sc_manager */
219
220
221
222 BOOL w32_close_service_handle(
223   SC_HANDLE hSCObject)   /* handle to service or SCM object */
224 {
225    HMODULE     hDll = NULL;
226    FARPROC     pFunc = NULL;
227    DWORD       dwLastErr = 0;
228    BOOL        bRet;
229
230    /* Load the DLL with the SCM functions or return a failure status */
231    hDll = LoadLibrary("Advapi32.dll");
232    if (hDll == NULL)
233    {
234       return FALSE;
235    }
236
237    /* Get the address of the CloseServiceHandle function, or return a failure status */
238    pFunc = GetProcAddress(hDll, "CloseServiceHandle");
239    if (pFunc == NULL)
240    {
241       FreeLibrary(hDll);
242       return FALSE;
243    }
244
245    /* Close the handle, and save the error code */
246    bRet = (BOOL)(*pFunc)(hSCObject);
247    dwLastErr = GetLastError();
248
249    /* Release the library and then restore the last error
250     * code, in case FreeLibrary altered it.
251     */
252    FreeLibrary(hDll);
253    SetLastError(dwLastErr);
254
255    return bRet;
256
257 } /* -END- w32_close_service_handle */
258
259
260
261 /*********************************************************************
262  * Open a service
263  *********************************************************************/ 
264 SC_HANDLE w32_open_service(
265   SC_HANDLE hSCManager,   /* handle to SCM database */
266   LPCTSTR lpServiceName,  /* service name */
267   DWORD dwDesiredAccess)  /* access */
268 {
269    HMODULE     hDll = NULL;
270    SC_HANDLE   hSrv = NULL;
271    FARPROC     pFunc = NULL;
272    DWORD       dwLastErr = 0;
273
274    /* Load the DLL with the SCM functions or return failure */
275    hDll = LoadLibrary("Advapi32.dll");
276    if (hDll == NULL)
277    {
278       return NULL;
279    }
280
281    /* Get the address of the ANSI OpenService function, or return failure */
282    pFunc = GetProcAddress(hDll, "OpenServiceA");
283    if (pFunc == NULL)
284    {
285       FreeLibrary(hDll);
286       return NULL;
287    }
288
289    /* Call the SCM function, and save the error code */
290    hSrv = (SC_HANDLE)(*pFunc)(hSCManager, lpServiceName, dwDesiredAccess);
291    dwLastErr = GetLastError();
292
293    /* Release the library and then restore the last error
294     * code, in case FreeLibrary altered it.
295     */
296    FreeLibrary(hDll);
297    SetLastError(dwLastErr);
298      
299    return hSrv;
300
301 } /* -END- w32_open_service */
302
303
304
305 SC_HANDLE w32_create_service(
306   SC_HANDLE hSCManager,       /* handle to SCM database */
307   LPCTSTR lpServiceName,      /* name of service to start */
308   LPCTSTR lpDisplayName,      /* display name */
309   DWORD dwDesiredAccess,      /* type of access to service */
310   DWORD dwServiceType,        /* type of service */
311   DWORD dwStartType,          /* when to start service */
312   DWORD dwErrorControl,       /* severity of service failure */
313   LPCTSTR lpBinaryPathName,   /* name of binary file */
314   LPCTSTR lpLoadOrderGroup,   /* name of load ordering group */
315   LPDWORD lpdwTagId,          /* tag identifier */
316   LPCTSTR lpDependencies,     /* array of dependency names */
317   LPCTSTR lpServiceStartName, /* account name */
318   LPCTSTR lpPassword)         /* account password */
319 {
320    HMODULE     hDll = NULL;
321    SC_HANDLE   hSrv = NULL;
322    FARPROC     pFunc = NULL;
323    DWORD       dwLastErr = 0;
324
325    /* Load the DLL with the SCM functions or return failure */
326    hDll = LoadLibrary("Advapi32.dll");
327    if (hDll == NULL)
328    {
329       return NULL;
330    }
331
332    /* Get the address of the ANSI CreateService function, or return failure */
333    pFunc = GetProcAddress(hDll, "CreateServiceA");
334    if (pFunc == NULL)
335    {
336       FreeLibrary(hDll);
337       return NULL;
338    }
339
340    /* Call the SCM function, and save the error code */
341    hSrv = (SC_HANDLE)(*pFunc)(hSCManager,          /* handle to SCM database */
342                               lpServiceName,       /* name of service to start */
343                               lpDisplayName,       /* display name */
344                               dwDesiredAccess,     /* type of access to service */
345                               dwServiceType,       /* type of service */
346                               dwStartType,         /* when to start service */
347                               dwErrorControl,      /* severity of service failure */
348                               lpBinaryPathName,    /* name of binary file */
349                               lpLoadOrderGroup,    /* name of load ordering group */
350                               lpdwTagId,           /* tag identifier */
351                               lpDependencies,      /* array of dependency names */
352                               lpServiceStartName,  /* account name */
353                               lpPassword);         /* account password */
354    dwLastErr = GetLastError();
355
356    /* Release the library and then restore the last error
357     * code, in case FreeLibrary altered it.
358     */
359    FreeLibrary(hDll);
360    SetLastError(dwLastErr);
361      
362    return hSrv;
363
364 } /* -END- w32_create_service */
365
366
367
368 BOOL w32_delete_service(
369   SC_HANDLE hService)   /* handle to service */
370 {
371    HMODULE     hDll = NULL;
372    FARPROC     pFunc = NULL;
373    DWORD       dwLastErr = 0;
374    BOOL        bRet;
375
376    /* Load the DLL with the SCM functions or return a failure status */
377    hDll = LoadLibrary("Advapi32.dll");
378    if (hDll == NULL)
379    {
380       return FALSE;
381    }
382
383    /* Get the address of the DeleteService function, or return a failure status */
384    pFunc = GetProcAddress(hDll, "DeleteService");
385    if (pFunc == NULL)
386    {
387       FreeLibrary(hDll);
388       return FALSE;
389    }
390
391    /* Close the handle, and save the error code */
392    bRet = (BOOL)(*pFunc)(hService);
393    dwLastErr = GetLastError();
394
395    /* Release the library and then restore the last error
396     * code, in case FreeLibrary altered it.
397     */
398    FreeLibrary(hDll);
399    SetLastError(dwLastErr);
400
401    return bRet;
402
403 } /* -END- w32_delete_service */
404
405
406
407 BOOL w32_query_service_config(
408   SC_HANDLE hService,                     /* handle to service */
409   LPQUERY_SERVICE_CONFIG lpServiceConfig, /* buffer */
410   DWORD cbBufSize,                        /* size of buffer */
411   LPDWORD pcbBytesNeeded)                 /* bytes needed */
412 {
413    HMODULE     hDll = NULL;
414    FARPROC     pFunc = NULL;
415    DWORD       dwLastErr = 0;
416    BOOL        bRet;
417
418    /* Load the DLL with the SCM functions or return a failure status */
419    hDll = LoadLibrary("Advapi32.dll");
420    if (hDll == NULL)
421    {
422       return FALSE;
423    }
424
425    /* Get the address of the QueryServiceConfig function, or return a failure status */
426    pFunc = GetProcAddress(hDll, "QueryServiceConfigA");
427    if (pFunc == NULL)
428    {
429       FreeLibrary(hDll);
430       return FALSE;
431    }
432
433    /* Close the handle, and save the error code */
434    bRet = (BOOL)(*pFunc)(hService, lpServiceConfig, cbBufSize, pcbBytesNeeded);
435    dwLastErr = GetLastError();
436
437    /* Release the library and then restore the last error
438     * code, in case FreeLibrary altered it.
439     */
440    FreeLibrary(hDll);
441    SetLastError(dwLastErr);
442
443    return bRet;
444
445 } /* -END- w32_query_service_config */
446
447
448 BOOL w32_start_service_ctrl_dispatcher(
449   CONST LPSERVICE_TABLE_ENTRY lpServiceTable)   /* service table */
450 {
451    HMODULE     hDll = NULL;
452    FARPROC     pFunc = NULL;
453    DWORD       dwLastErr = 0;
454    BOOL        bRet;
455
456    /* Load the DLL with the SCM functions or return a failure status */
457    hDll = LoadLibrary("Advapi32.dll");
458    if (hDll == NULL)
459    {
460       return FALSE;
461    }
462
463    /* Get the address of the StartServiceCtrlDispatcher function, or return a failure status */
464    pFunc = GetProcAddress(hDll, "StartServiceCtrlDispatcherA");
465    if (pFunc == NULL)
466    {
467       FreeLibrary(hDll);
468       return FALSE;
469    }
470
471    /* Close the handle, and save the error code */
472    bRet = (BOOL)(*pFunc)(lpServiceTable);
473    dwLastErr = GetLastError();
474
475    /* Release the library and then restore the last error
476     * code, in case FreeLibrary altered it.
477     */
478    FreeLibrary(hDll);
479    SetLastError(dwLastErr);
480
481    return bRet;
482
483 } /* -END- w32_start_service_ctrl_dispatcher */
484
485
486
487 SERVICE_STATUS_HANDLE w32_register_service_ctrl_handler(
488   LPCTSTR lpServiceName,               /* service name */
489   LPHANDLER_FUNCTION lpHandlerProc)    /* handler function */
490 {
491    HMODULE     hDll = NULL;
492    FARPROC     pFunc = NULL;
493    DWORD       dwLastErr = 0;
494    SERVICE_STATUS_HANDLE hServStat = (SERVICE_STATUS_HANDLE)0;
495
496    /* Load the DLL with the SCM functions or return a failure status */
497    hDll = LoadLibrary("Advapi32.dll");
498    if (hDll == NULL)
499    {
500       return hServStat;
501    }
502
503    /* Get the address of the RegisterServiceCtrlHandler function, or return a failure status */
504    pFunc = GetProcAddress(hDll, "RegisterServiceCtrlHandlerA");
505    if (pFunc == NULL)
506    {
507       FreeLibrary(hDll);
508       return hServStat;
509    }
510
511    /* Close the handle, and save the error code */
512    hServStat = (SERVICE_STATUS_HANDLE)(*pFunc)(lpServiceName, lpHandlerProc);
513    dwLastErr = GetLastError();
514
515    /* Release the library and then restore the last error
516     * code, in case FreeLibrary altered it.
517     */
518    FreeLibrary(hDll);
519    SetLastError(dwLastErr);
520
521    return hServStat;
522
523 } /* -END- w32_register_service_ctrl_handler */
524
525
526
527 BOOL w32_set_service_status(
528   SERVICE_STATUS_HANDLE hServiceStatus,   /* service status handle */
529   LPSERVICE_STATUS lpServiceStatus)       /* status buffer */
530 {
531    HMODULE     hDll = NULL;
532    FARPROC     pFunc = NULL;
533    DWORD       dwLastErr = 0;
534    BOOL        bRet;
535
536    /* Load the DLL with the SCM functions or return a failure status */
537    hDll = LoadLibrary("Advapi32.dll");
538    if (hDll == NULL)
539    {
540       return FALSE;
541    }
542
543    /* Get the address of the SetServiceStatus function, or return a failure status */
544    pFunc = GetProcAddress(hDll, "SetServiceStatus");
545    if (pFunc == NULL)
546    {
547       FreeLibrary(hDll);
548       return FALSE;
549    }
550
551    /* Close the handle, and save the error code */
552    bRet = (BOOL)(*pFunc)(hServiceStatus, lpServiceStatus);
553    dwLastErr = GetLastError();
554
555    /* Release the library and then restore the last error
556     * code, in case FreeLibrary altered it.
557     */
558    FreeLibrary(hDll);
559    SetLastError(dwLastErr);
560
561    return bRet;
562
563 } /* -END- w32_set_service_status */
564
565
566 static void display_win32_msg(BOOL bIsError, char *msg)
567 {
568 #ifdef _WIN_CONSOLE
569    printf("%s", msg);
570 #else
571    if (bIsError)
572    {
573       MessageBox(NULL, msg, "Privoxy Error", 
574          MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
575    }
576    else
577    {
578       MessageBox(NULL, msg, "Privoxy Information", 
579          MB_OK | MB_ICONINFORMATION | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
580    }
581 #endif
582
583 } /* -END- display_win32_msg */
584
585
586 static BOOL get_service_description(const char *pszServiceName, char *pszDisplayName, DWORD dwDispSize)
587 {
588    /*********************************************************************
589     * Create a simple display name
590     *********************************************************************/
591    strcpy(pszDisplayName, "Privoxy (");
592    strncat(pszDisplayName, pszServiceName, dwDispSize - strlen(pszDisplayName) - 2);
593    strcat(pszDisplayName, ")");
594
595    return TRUE;
596 }
597
598
599
600 BOOL install_service(const char *service_name)
601 {
602    char szModule[(MAX_PATH*2)+1];
603    char szDisplayName[MAX_PATH+2];
604    SC_HANDLE hSCM;
605    SC_HANDLE hService;
606
607    /*********************************************************************
608     * First check if this system can support a service architecture
609     *********************************************************************/
610    if (!CanSystemSupportServices())
611    {
612       display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
613       return FALSE;
614    }
615
616    /* Use a default service name if none was supplied */
617    if ((service_name == NULL) || (strlen(service_name) == 0))
618    {
619       service_name = "privoxy";
620    }
621
622    /*********************************************************************
623     * Open a handle to the Service Control Manager with full access rights
624     *********************************************************************/
625    hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
626    if (hSCM == NULL)
627    {
628       display_win32_msg(TRUE, "Can't open Service Control Manager - Service install failed!\n  Administrator rights are required to create a service.\n");
629       return FALSE;
630    }
631
632
633    /*********************************************************************
634     * Work out the full image path plus command line for the service
635     * We'll temporarily use szDisplayName as a second buffer.
636     *********************************************************************/
637    GetModuleFileName(NULL, szDisplayName, MAX_PATH);
638    sprintf(szModule, "\"%s\" --service", szDisplayName); 
639
640    
641    /*********************************************************************
642     * Get the display name for the service
643     *********************************************************************/
644    get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
645
646
647    /*********************************************************************
648     * Create the service
649     *********************************************************************/
650    hService = w32_create_service(hSCM, 
651                            service_name,              /* the internal service name */
652                            szDisplayName,             /* the display name */
653                            SERVICE_ALL_ACCESS,        /* get full access during creation */
654                            SERVICE_WIN32_OWN_PROCESS  /* run in our own process */
655 #ifndef _WIN_CONSOLE
656                          + SERVICE_INTERACTIVE_PROCESS /* GUI also wants interactive rights */
657 #endif
658                            ,
659                            SERVICE_DEMAND_START,      /* For now, only start when asked to */
660                            SERVICE_ERROR_NORMAL,      /* Normal error handling by the SCM */
661                            szModule,                  /* The executable service file */
662                            NULL,                      /* No load order info needed */
663                            NULL,                      /* No load order info needed */
664                            NULL,                      /* No dependencies */
665                            NULL,                      /* Default to LocalSystem... */
666                            NULL);                     /* ...which doesn't require a password */
667    if (hService == NULL)
668    {
669       display_win32_msg(TRUE, "Can't install service!\n");
670       w32_close_service_handle(hSCM);
671       return FALSE;
672    }
673
674    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");
675
676    /* tidy up */
677    w32_close_service_handle(hService);
678    w32_close_service_handle(hSCM);
679    return TRUE;
680
681 } /* -END- install_service */
682
683
684
685 BOOL uninstall_service(const char *service_name)
686 {
687    char szDisplayName[MAX_PATH+2];
688    SC_HANDLE hSCM;
689    SC_HANDLE hService;
690    BOOL bResult = FALSE;
691
692
693    /*********************************************************************
694     * First check if this system can support a service architecture
695     *********************************************************************/
696    if (!CanSystemSupportServices())
697    {
698       display_win32_msg(TRUE, "This system doesn't support installing Privoxy as a service.\nWinNT/2000/XP are required for this feature.\n");
699       return FALSE;
700    }
701
702
703    /* Use a default service name if none was supplied */
704    if ((service_name == NULL) || (strlen(service_name) == 0))
705    {
706       service_name = "privoxy";
707    }
708
709
710    /*********************************************************************
711     * Open a handle to the Service Control Manager with full access rights
712     *********************************************************************/
713    hSCM = w32_open_sc_manager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
714    if (hSCM == NULL)
715    {
716       display_win32_msg(TRUE, "Can't open Service Control Manager - Service uninstall failed!\n  Administrator rights are required to delete a service.\n");
717       return FALSE;
718    }
719
720
721    /*********************************************************************
722     * Get the display name for the service
723     *********************************************************************/
724    get_service_description(service_name, szDisplayName, sizeof(szDisplayName)/sizeof(char));
725
726
727    /*********************************************************************
728     * Open and then delete the service
729     *********************************************************************/
730    hService = w32_open_service(hSCM, service_name, DELETE);
731    if (hService == NULL)
732    {
733       display_win32_msg(TRUE, "Can't open service for delete access rights!\n");
734       w32_close_service_handle(hSCM);
735       return FALSE;
736    }
737
738    if (w32_delete_service(hService))
739    {
740       display_win32_msg(FALSE, "Service was deleted successfully.\n");
741       bResult = TRUE;
742    }
743    else
744    {
745       display_win32_msg(TRUE, "Service could not be deleted!\n");
746       bResult = FALSE;
747    }
748
749    w32_close_service_handle(hService);
750    w32_close_service_handle(hSCM);
751    return bResult;
752
753 } /* -END- uninstall_service */
754
755
756
757 /*********************************************************************
758  *
759  * Function    :  privoxy_w32_service_start
760  *
761  * Description :  This is the entry point function for the service.
762  *                In other words, it's the ServiceMain function.
763  *
764  * Parameters  :  Defined by the Win32 API, but not used here
765  *
766  * Returns     :  void
767  *
768  *********************************************************************/
769 static void WINAPI privoxy_w32_service_start(DWORD dw, LPSTR* pszArgs)
770 {
771    int child_id;
772
773    /* Arg zero is always the service name, and we need to 
774     * know it when we call RegisterServiceCtrlHandler.
775     */
776    strcpy(szThisServiceName, pszArgs[0]);
777
778    /* Tell the SCM we are running */
779    srv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
780    srv_status.dwCurrentState = SERVICE_RUNNING;
781    srv_status.dwCheckPoint = 0;
782    srv_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
783    srv_status.dwWin32ExitCode = NO_ERROR;
784    srv_status.dwServiceSpecificExitCode = 0;
785    srv_status.dwWaitHint = 0;
786
787    hSrv_status = w32_register_service_ctrl_handler(szThisServiceName, privoxy_w32_service_handler);
788    if (!hSrv_status)
789    {
790       return;
791    }
792    w32_set_service_status(hSrv_status, &srv_status);
793
794 #ifndef FEATURE_PTHREAD
795    child_id = _beginthread(w32_service_listen_loop, 0, NULL);
796    if (child_id > 0)
797 #else
798 #error "FIXME: Do pthread stuff here!"
799 #endif
800    {
801       w32_set_service_status(hSrv_status, &srv_status);
802    }
803    else
804    {
805       srv_status.dwCurrentState = SERVICE_STOPPED;
806       srv_status.dwCheckPoint = 0;
807       srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
808       srv_status.dwServiceSpecificExitCode = ERROR_SERVICE_NO_THREAD;
809       w32_set_service_status(hSrv_status, &srv_status);
810    }
811 }
812
813
814 /*********************************************************************
815  *
816  * Function    :  w32_set_service_cwd
817  *
818  * Description :  Simple function to change the current directory to
819  *                the same location as the service executable.
820  *
821  * Parameters  :  void
822  *
823  * Returns     :  void
824  *
825  *********************************************************************/
826 void w32_set_service_cwd(void)
827 {
828    char exe_name[MAX_PATH+1];
829    char dir_name[MAX_PATH+1];
830    char *pszFile = NULL;
831
832    /* Get the exe name and path of the service */
833    if (GetModuleFileName(NULL, exe_name, MAX_PATH))
834    {
835       /* Ask the API to tell us where the filename portion starts */
836       if (GetFullPathName(exe_name, MAX_PATH, dir_name, &pszFile))
837       {
838          /* remove the filename from the string */
839          if (pszFile != NULL)
840          {
841             *pszFile = '\0';
842             /* We have just a directory path now, so make it current */
843             SetCurrentDirectory(dir_name);
844          }
845       }
846    }
847 }
848
849
850 /*********************************************************************
851  *
852  * Function    :  w32_service_exit_notify
853  *
854  * Description :  This is a simple atexit function that is called by the
855  *                C runtime after exit has been called. It allows the
856  *                service code to detect when the app is about to die and
857  *                send an quick notification to the SCM that the service
858  *                now stopped.
859  *
860  * Parameters  :  void
861  *
862  * Returns     :  void
863  *
864  *********************************************************************/
865 void w32_service_exit_notify(void)
866 {
867    if (hSrv_status != 0)
868    {
869       if (srv_status.dwCurrentState != SERVICE_STOPPED)
870       {
871          srv_status.dwCurrentState = SERVICE_STOPPED;
872          srv_status.dwCheckPoint = 0;
873          srv_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
874          srv_status.dwServiceSpecificExitCode = ERROR_PROCESS_ABORTED;
875          w32_set_service_status(hSrv_status, &srv_status);
876       }
877    }
878 }
879
880
881 static void w32_mini_exit(void *p)
882 {
883    Sleep(100);
884 #ifdef _WIN_CONSOLE
885    exit(0);
886 #else
887    PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
888 #endif /* def _WIN_CONSOLE */
889 }
890
891
892 /*********************************************************************
893  *
894  * Function    :  privoxy_w32_service_handler
895  *
896  * Description :  This is the control message handler function for
897  *                the service.
898  *
899  * Parameters  :  dwOpcode
900  *                   requested control code sent by SCM
901  *
902  * Returns     :  void
903  *
904  *********************************************************************/
905 static void WINAPI privoxy_w32_service_handler(DWORD dwOpcode)
906 {
907    switch(dwOpcode)
908    {
909       case SERVICE_CONTROL_STOP:
910          /* We've stopped
911           */
912          srv_status.dwCurrentState = SERVICE_STOPPED;
913          srv_status.dwCheckPoint = 0;
914          srv_status.dwWin32ExitCode = NO_ERROR;
915          srv_status.dwServiceSpecificExitCode = 0;
916
917          /* Maybe there is a more friendly way to stop, but this will do for now! */
918          w32_set_service_status(hSrv_status, &srv_status);
919
920          /* During testing, I kept getting error 109 (ERROR_BROKEN_PIPE) and
921           * as far as the SCM was concerned the service was still stopping,
922           * even after the process had disappeared.
923           *
924           * It seems that if we call exit in the ServiceMain thread, it causes
925           * the SCM to not recieve the status we sent in the line above. The
926           * simple fix was to create a new thread to actually call exit for us
927           * whilst this thread continues and returns to its caller.
928           */
929
930          if (_beginthread(w32_mini_exit, 0, NULL) < 0)
931          {
932             /* we failed to create the exit thread, so just force an exit here
933              * and the SCM will just have to go and whistle!
934              */
935             exit(0);
936          }
937          break;
938
939       default:
940          break;
941    }
942
943    w32_set_service_status(hSrv_status, &srv_status);
944 }
945
946
947 #endif /* ifdef _WIN32 */
948