summaryrefslogtreecommitdiff
path: root/src/server_win32.c
blob: 6faac8ae489d983f5fb069fdcdfc0f5fb415214f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
 * server_win32 - _WIN32 winsvc
 *
 * Copyright(c) 2023 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
 * License: BSD 3-clause (same as lighttpd)
 *
 * intended for server.c to #include "server_win32.c"
 * - uses file-scoped static globals defined in server.c
 * - wraps server.c main()
 */
#include "first.h"

#include <winsvc.h>
#include <tchar.h>
#include <strsafe.h>


#if 0
static void SvcReportEvent (const LPTSTR szFunction)
{
    /*(XXX: would need separate event source message catalog for lighttpd)*/
    //HANDLE hEventSource = RegisterEventSource(NULL, "lighttpd");
    HANDLE hEventSource = OpenEventLogA(NULL, "System");
    if (NULL == hEventSource) return;

    TCHAR Buffer[1024];
    StringCchPrintf(Buffer, sizeof(Buffer), TEXT("%s GetLastError(%d)"),
                    szFunction, GetLastError());

    LPCTSTR lpszStrings[] = { "lighttpd", Buffer };
    ReportEvent(hEventSource,        // event log handle
                EVENTLOG_ERROR_TYPE, // event type
                0,                   // event category
                0x1, //SVC_ERROR     // event identifier
                NULL,                // no security identifier
                sizeof(lpszStrings)/sizeof(*lpszStrings), // lpszStrings size
                0,                   // no binary data
                lpszStrings,         // array of strings
                NULL);               // no binary data

    //DeregisterEventSource(hEventSource);
    CloseEventLog(hEventSource);
}
#endif


__attribute_cold__
__attribute_noinline__
static UINT lighttpd_ServiceCreate (int argc, char ** argv)
{
    /* https://learn.microsoft.com/en-us/windows/win32/services/svc-cpp */
    TCHAR szUnquotedPath[MAX_PATH];
    if (!GetModuleFileName(NULL, szUnquotedPath, MAX_PATH)) {
        fprintf(stderr, "Can not install service (%lu)\n", GetLastError());
        return GetLastError();
    }

    /* Command: "C:\path\to\lighttpd.exe" -f "C:\path\to\lighttpd.conf" */
    /* In case the path contains a space, it must be quoted so that
     * it is correctly interpreted. For example,
     * "d:\my share\myservice.exe" should be specified as
     * ""d:\my share\myservice.exe"". */
    TCHAR szCommandLine[MAX_PATH*3+16];
    StringCbPrintf(szCommandLine, sizeof(szCommandLine),
                   TEXT("\"%s\" -f \"%sf\""),
                   szUnquotedPath, szUnquotedPath);
    const size_t len = _tcslen(szCommandLine);
    memcpy(szCommandLine+len-5, "conf", 4);
  #ifndef LIGHTTPD_STATIC
    StringCbPrintf(szCommandLine+len, sizeof(szCommandLine)-len,
                   TEXT(" -m \"%s.libs\""), szUnquotedPath-12);
  #endif

    SC_HANDLE schSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
    if (!schSCM) {
        fprintf(stderr, "OpenSCManager failed (%lu)\n", GetLastError());
        return GetLastError();
    }

    /* LocalSystem is too powerful; this works but is overkill.
     * XXX: Recommended: dedicated account should be created and used.
     * "NT AUTHORITY\\NetworkService" might be used if files lighttpd.exe and
     * lighttpd.conf are installed in location accessible by NetWorkService acct
     */
    LPCSTR lpServiceStartName = ".\\LocalSystem";
    if (argc >= 4) {
        /* e.g. sc.exe config lighttpd obj= <AccountName> */
        if (0 == strcmp(argv[2], "obj="))
            lpServiceStartName = argv[3];
    }

    SC_HANDLE schSvc =
      CreateService(schSCM,
                    "lighttpd",
                    "lighttpd",
                    GENERIC_READ,
                    SERVICE_WIN32_OWN_PROCESS,
                    SERVICE_AUTO_START,
                    SERVICE_ERROR_NORMAL,
                    szCommandLine,
                    NULL,
                    NULL,
                    NULL,
                    lpServiceStartName,
                    NULL);

    if (schSvc)
        printf("Service installed successfully\n");
    else
        fprintf(stderr, "CreateService failed (%lu)\n", GetLastError());

    if (schSvc) {
        char desc[] = "lighttpd web service";
        SERVICE_DESCRIPTIONA svc_desc = { desc };
        ChangeServiceConfig2A(schSvc, SERVICE_CONFIG_DESCRIPTION, &svc_desc);
        /*(ignore if setting Description fails)*/
    }

  #ifdef __MINGW32__
    /* lighttpd service will fail to start unless mingw libs are available.
     * Append mingw libs path to PATH in OS System Environment, or set custom
     * PATH for lighttpd service and then restart the lighttpd service:
     * In powershell:
     *   reg add HKLM\SYSTEM\CurrentControlSet\Services\lighttpd /f /v Environment /t REG_MULTI_SZ /d "PATH=$env:Path;C:\cygwin64\usr\x86_64-w64-mingw32\sys-root\mingw\bin"
     *   sc.exe start lighttpd
     * Replace PATH above as appropriate, and separate PATH elements using ';'.
     * Note: there is no REG_MULTI_EXPAND_SZ, so the resulting value must be
     * expanded (and can not use %SystemRoot% or %SYSTEM32% or %PATH%) */
  #endif

    CloseServiceHandle(schSvc);
    CloseServiceHandle(schSCM);
    return schSvc ? 0 : GetLastError();
}


__attribute_cold__
__attribute_noinline__
static UINT lighttpd_ServiceDelete (void)
{
    /* https://learn.microsoft.com/en-us/windows/win32/services/svcconfig-cpp */
    SC_HANDLE schSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (!schSCM) {
        fprintf(stderr, "OpenSCManager failed (%lu)\n", GetLastError());
        return GetLastError();
    }

    SC_HANDLE schSvc = OpenService(schSCM, "lighttpd", DELETE);
    if (schSvc == NULL) {
        fprintf(stderr, "OpenService failed (%lu)\n", GetLastError());
        CloseServiceHandle(schSCM);
        return GetLastError();
    }

    BOOL rc = DeleteService(schSvc);
    if (rc)
        printf("Service removed successfully\n");
    else
        fprintf(stderr, "DeleteService failed (%lu)\n", GetLastError());

    CloseServiceHandle(schSvc);
    CloseServiceHandle(schSCM);
    return rc ? 0 : GetLastError();
}


static void signal_handler (int sig);

static void lighttpd_ServiceCtrlHandler (DWORD dwCtrl)
{
    switch (dwCtrl) {
      case SERVICE_CONTROL_PARAMCHANGE:
        signal_handler(SIGUSR1); /*(redefined to SIGBREAK)*/
        break;
      case SERVICE_CONTROL_STOP:
        signal_handler(SIGINT);
        break;
      case SERVICE_CONTROL_INTERROGATE:
      default:
        break;
    }
}


static SERVICE_STATUS_HANDLE hStatus;

__attribute_cold__
__attribute_noinline__
static void lighttpd_ServiceStatus (DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint)
{
    if (!hStatus) return;

    DWORD dwControlsAccepted = SERVICE_ACCEPT_STOP;
    if (dwCurrentState == SERVICE_RUNNING)
        dwControlsAccepted |= SERVICE_ACCEPT_PARAMCHANGE;
    else if (dwCurrentState == SERVICE_START_PENDING)
        dwControlsAccepted = 0;

    static DWORD gSvcCheckPoint;
    DWORD dwCheckPoint =
      (dwCurrentState == SERVICE_RUNNING || dwCurrentState == SERVICE_STOPPED)
        ? (gSvcCheckPoint = 0)
        : gSvcCheckPoint++;

    SERVICE_STATUS status = {
      SERVICE_WIN32_OWN_PROCESS,
      dwCurrentState,
      dwControlsAccepted,
      dwWin32ExitCode,
      0, /*dwServiceSpecificExitCode*/
      dwCheckPoint,
      dwWaitHint
    };
    SetServiceStatus(hStatus, &status);
}


#define server_status_running(srv) \
  lighttpd_ServiceStatus(SERVICE_RUNNING, NO_ERROR, 0);

#define server_status_stopping(srv) \
  DWORD dwWaitHint = (DWORD)(srv->graceful_expire_ts-log_monotonic_secs)*1000; \
  lighttpd_ServiceStatus(SERVICE_STOP_PENDING, NO_ERROR, dwWaitHint + 1000);


#ifndef main
#define main main
#define server_main_win32 main
#endif
__attribute_cold__
int server_main_win32 (int argc, char ** argv);

static int svc_main_argc;
static char ** svc_main_argv;

__attribute_cold__
__attribute_noinline__
static void lighttpd_ServiceMain (DWORD dwNumServicesArgs, LPSTR *lpServiceArgVectors)
{
    /* service thread; not main(); params are not program startup argc, argv */
    hStatus = RegisterServiceCtrlHandlerA("lighttpd",
                                          (LPHANDLER_FUNCTION)
                                          lighttpd_ServiceCtrlHandler);
    if (!hStatus) return; /*(unexpected; can not continue)*/
    lighttpd_ServiceStatus(SERVICE_START_PENDING, NO_ERROR, 1000);

    int argc = svc_main_argc;    /* saved in lighttpd_ServiceCtrlDispatcher() */
    char ** argv = svc_main_argv;/* saved in lighttpd_ServiceCtrlDispatcher() */
    /* allow manual override by lighttpd Service Properties "Start parameters"*/
    if (dwNumServicesArgs > 1) {
        argc = (int)dwNumServicesArgs;
        argv = lpServiceArgVectors;
    }

    server_main_win32(argc, argv);

    lighttpd_ServiceStatus(SERVICE_STOPPED, NO_ERROR, 0);
    CloseHandle(hStatus);
    hStatus = NULL;
}


__attribute_cold__
__attribute_noinline__
static void lighttpd_ServiceCtrlDispatcher (int argc, char ** argv)
{
    if (argc >= 2 && 0 == strcmp(argv[1], "svc-create"))
        ExitProcess(lighttpd_ServiceCreate(argc, argv));
    if (argc == 2 && 0 == strcmp(argv[1], "svc-delete"))
        ExitProcess(lighttpd_ServiceDelete());

    for (int i = 1; i < argc; ++i) {
        if (argv[i][0] == '-' && strchr(argv[i], 'D')) /*(stay in foreground)*/
            return;
    }

    /* save original service start argc and argv for use by lighttpd_ServiceMain
     * since lighttpd_ServiceMain() thread is passed service name "lighttpd" and
     * argc == 1.  (This is a single-service application; using globals this way
     * is probably not appropriate for multi-service applications.) */
    svc_main_argc = argc;
    svc_main_argv = argv;

    static const SERVICE_TABLE_ENTRYA lighttpd_ServiceDispatchTable[] = {
      { "lighttpd", (LPSERVICE_MAIN_FUNCTIONA)lighttpd_ServiceMain },
      { NULL, NULL }
    };
    UINT rc = StartServiceCtrlDispatcherA(lighttpd_ServiceDispatchTable)
      ? 0
      : GetLastError();
    /* https://learn.microsoft.com/en-us/windows/win32/services/debugging-a-service
     *  At times, it may be necessary to run a service as a console application
     *  for debugging purposes. In this scenario, the StartServiceCtrlDispatcher
     *  function will return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT. Therefore,
     *  be sure to structure your code such that service-specific code is not
     *  called when this error is returned. */
    if (rc != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
        ExitProcess(rc);
}


#include <signal.h>     /* sig_atomic_t */
void fdevent_win32_init (volatile sig_atomic_t *ptr);

#include <fcntl.h>      /* _O_BINARY */
#include <io.h>         /* _setmode() */
#include <stdlib.h>     /* _set_fmode() */
__attribute_cold__
int server_main_win32 (int argc, char ** argv)
{
    static int lighttpd_ServiceCtrlDispatcher_once;
    if (!lighttpd_ServiceCtrlDispatcher_once) {
        lighttpd_ServiceCtrlDispatcher_once = 1;
        lighttpd_ServiceCtrlDispatcher(argc, argv);
    }

    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);
    int rc = WSAStartup(wVersionRequested, &wsaData);
    if (rc != 0) {
        fprintf(stderr, "WSAStartup() failed: %d\n", rc);
        return -1;
    }

    /* https://docs.microsoft.com/en-us/cpp/c-runtime-library/fmode?view=msvc-160 */
    /* https://sourceforge.net/p/mingw-w64/bugs/857/ */
    /*_set_fmode(_O_BINARY);*/
    _fmode = _O_BINARY;
    (void)_setmode(_fileno(stdin),  _O_BINARY);
    (void)_setmode(_fileno(stdout), _O_BINARY);
    (void)_setmode(_fileno(stderr), _O_BINARY);

    fdevent_win32_init(&handle_sig_child);

    rc = server_main(argc, argv);

    fdevent_win32_init(NULL);

    WSACleanup();
    return rc;
}