Fossil

Check-in [e506ebb7]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Improved support for both IPv4 and IPv6 on "fossil server" on Windows. Patches from Olivier Mascia.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: e506ebb764e93715e9514d6c0078d3eb82580bee78f18180fa18a21b3d7edd03
User & Date: drh 2018-01-05 14:34:59.875
Context
2018-01-05
15:25
Always try to extract the IP address and PORT number from the --port option to "fossil server" if the option contains a ':' character. ... (check-in: 4d3cb0da user: drh tags: trunk)
14:34
Improved support for both IPv4 and IPv6 on "fossil server" on Windows. Patches from Olivier Mascia. ... (check-in: e506ebb7 user: drh tags: trunk)
13:37
Improved parsing of the --port option on the "fossil server" command. ... (check-in: f8f2c8d2 user: drh tags: trunk)
Changes
Unified Diff Ignore Whitespace Patch
Changes to src/winhttp.c.
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
#include <windows.h>
#include <process.h>
#include "winhttp.h"

#ifndef IPV6_V6ONLY
# define IPV6_V6ONLY 27  /* Because this definition is missing in MinGW */
#endif






































































































































































































/*
** The HttpServer structure holds information about an instance of
** the HTTP server itself.
*/
typedef struct HttpServer HttpServer;
struct HttpServer {
  HANDLE hStoppedEvent; /* Event to signal when server is stopped,
                        ** must be closed by callee. */
  char *zStopper;       /* The stopper file name, must be freed by
                        ** callee. */
  SOCKET listener;      /* Socket on which the server is listening,
                        ** may be closed by callee. */
};

/*
** The HttpRequest structure holds information about each incoming
** HTTP request.
*/
typedef struct HttpRequest HttpRequest;
struct HttpRequest {
  int id;                /* ID counter */
  SOCKET s;              /* Socket on which to receive data */
  SOCKADDR_IN6 addr;     /* Address from which data is coming */
  int flags;             /* Flags passed to win32_http_server() */
  const char *zOptions;  /* --baseurl, --notfound, --localauth, --th-trace */
};

/*
** Prefix for a temporary file.
*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











|











|







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
#include <windows.h>
#include <process.h>
#include "winhttp.h"

#ifndef IPV6_V6ONLY
# define IPV6_V6ONLY 27  /* Because this definition is missing in MinGW */
#endif

/*
** The SocketAddr structure holds a SOCKADDR_STORAGE and its content size.
*/
typedef struct SocketAddr SocketAddr;
struct SocketAddr {
  SOCKADDR_STORAGE addr;
  int len;
};

static char* SocketAddr_toString(const SocketAddr* pAddr){
  SocketAddr addr;
  char* zIp;
  DWORD nIp = 50;
  assert( pAddr!=NULL );
  memcpy(&addr, pAddr, sizeof(SocketAddr));
  if( addr.len==sizeof(SOCKADDR_IN6) ){
    ((SOCKADDR_IN6*)&addr)->sin6_port = 0;
  }else{
    ((SOCKADDR_IN*)&addr)->sin_port = 0;
  }
  zIp = fossil_malloc(nIp);
  if( WSAAddressToStringA((SOCKADDR*)&addr, addr.len, NULL, zIp, &nIp)!=0 ){
    zIp[0] = 0;
  }
  return zIp;
}

/*
** The DualAddr structure holds two SocketAddr (one IPv4 and on IPv6).
*/
typedef struct DualAddr DualAddr;
struct DualAddr {
  SocketAddr a4;  /* IPv4 SOCKADDR_IN */
  SocketAddr a6;  /* IPv6 SOCKADDR_IN6 */
};

static void DualAddr_init(DualAddr* pDA){
  assert( pDA!=NULL );
  memset(pDA, 0, sizeof(DualAddr));
  pDA->a4.len = sizeof(SOCKADDR_IN);
  pDA->a6.len = sizeof(SOCKADDR_IN6);
}

/*
** The DualSocket structure holds two SOCKETs. One or both could be
** used or INVALID_SOCKET.  One is dedicated to IPv4, the other to IPv6.
*/
typedef struct DualSocket DualSocket;
struct DualSocket {
  SOCKET s4;    /* IPv4 socket or INVALID_SOCKET */
  SOCKET s6;    /* IPv6 socket or INVALID_SOCKET */
};

/*
** Initializes a DualSocket.
*/
static void DualSocket_init(DualSocket* ds){
  assert( ds!=NULL );
  ds->s4 = INVALID_SOCKET;
  ds->s6 = INVALID_SOCKET;
};

/*
** Close and reset a DualSocket.
*/
static void DualSocket_close(DualSocket* ds){
  assert( ds!=NULL );
  if( ds->s4!=INVALID_SOCKET ){
    closesocket(ds->s4);
    ds->s4 = INVALID_SOCKET;
  }
  if( ds->s6!=INVALID_SOCKET ){
    closesocket(ds->s6);
    ds->s6 = INVALID_SOCKET;
  }
};

/*
** When ip is "W", listen to wildcard address (IPv4/IPv6 as available).
** When ip is "L", listen to loopback address (IPv4/IPv6 as available).
** Else listen only the specified ip, which is either IPv4 or IPv6 or invalid.
** Returns 1 on success, 0 on failure.
*/
static int DualSocket_listen(DualSocket* ds, const char* zIp, int iPort){
  SOCKADDR_IN addr4;
  SOCKADDR_IN6 addr6;
  assert( ds!=NULL && zIp!=NULL && iPort!=0 );
  DualSocket_close(ds);
  memset(&addr4, 0, sizeof(addr4));
  memset(&addr6, 0, sizeof(addr6));
  if (strcmp(zIp, "W")==0 || strcmp(zIp, "L")==0 ){
    ds->s4 = socket(AF_INET, SOCK_STREAM, 0);
    ds->s6 = socket(AF_INET6, SOCK_STREAM, 0);
    if( ds->s4==INVALID_SOCKET && ds->s6==INVALID_SOCKET ){
      return 0;
    }
    if (ds->s4!=INVALID_SOCKET ) {
      addr4.sin_family = AF_INET;
      addr4.sin_port = htons(iPort);
      if( strcmp(zIp, "L")==0 ){
        addr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
      }else{
        addr4.sin_addr.s_addr = INADDR_ANY;
      }
    }
    if( ds->s6!=INVALID_SOCKET ) {
      DWORD ipv6only = 1; /* don't want a dual-stack socket */
      setsockopt(ds->s6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only,
                 sizeof(ipv6only));
      addr6.sin6_family = AF_INET6;
      addr6.sin6_port = htons(iPort);
      if( strcmp(zIp, "L")==0 ){
        memcpy(&addr6.sin6_addr, &in6addr_loopback, sizeof(in6addr_loopback));
      }else{
        memcpy(&addr6.sin6_addr, &in6addr_any, sizeof(in6addr_any));
      }
    }
  }else{
    if( strstr(zIp, ".") ){
      int addrlen = sizeof(addr4);
      ds->s4 = socket(AF_INET, SOCK_STREAM, 0);
      if( ds->s4==INVALID_SOCKET ){
        return 0;
      }
      addr4.sin_family = AF_INET;
      if (WSAStringToAddress((char*)zIp, AF_INET, NULL,
                             (struct sockaddr *)&addr4, &addrlen) != 0){
        return 0;
      }
      addr4.sin_port = htons(iPort);
    }else{
      DWORD ipv6only = 1; /* don't want a dual-stack socket */
      int addrlen = sizeof(addr6);
      ds->s6 = socket(AF_INET6, SOCK_STREAM, 0);
      if( ds->s6==INVALID_SOCKET ){
        return 0;
      }
      setsockopt(ds->s6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only,
                 sizeof(ipv6only));
      addr6.sin6_family = AF_INET6;
      if (WSAStringToAddress((char*)zIp, AF_INET6, NULL,
                             (struct sockaddr *)&addr6, &addrlen) != 0){
        return 0;
      }
      addr6.sin6_port = htons(iPort);
    }
  }
  assert( ds->s4!=INVALID_SOCKET || ds->s6!=INVALID_SOCKET );
  if( ds->s4!=INVALID_SOCKET && bind(ds->s4, (struct sockaddr*)&addr4,
                                 sizeof(addr4))==SOCKET_ERROR ){
    return 0;
  }
  if( ds->s6!=INVALID_SOCKET && bind(ds->s6, (struct sockaddr*)&addr6,
                                 sizeof(addr6))==SOCKET_ERROR ){
    return 0;
  }
  if( ds->s4!=INVALID_SOCKET && listen(ds->s4, SOMAXCONN)==SOCKET_ERROR ){
    return 0;
  }
  if( ds->s6!=INVALID_SOCKET && listen(ds->s6, SOMAXCONN)==SOCKET_ERROR ){
    return 0;
  }
  return 1;
};

/*
** Accepts connections on DualSocket.
*/
static void DualSocket_accept(DualSocket* pListen, DualSocket* pClient,
                              DualAddr* pClientAddr){
	fd_set rs;
  int rs_count = 0;
  assert( pListen!=NULL && pClient!=NULL && pClientAddr!= NULL );
  DualSocket_init(pClient);
  DualAddr_init(pClientAddr);
  FD_ZERO(&rs);
	if( pListen->s4!=INVALID_SOCKET ){
    FD_SET(pListen->s4, &rs);
    ++rs_count;
  }
	if( pListen->s6!=INVALID_SOCKET ){
    FD_SET(pListen->s6, &rs);
    ++rs_count;
  }
	if( select(rs_count, &rs, 0, 0, 0 /*blocking*/)==SOCKET_ERROR ){
		return;
  }
  if( FD_ISSET(pListen->s4, &rs) ){
    pClient->s4 = accept(pListen->s4, (struct sockaddr*)&pClientAddr->a4.addr,
                         &pClientAddr->a4.len);
  }
  if( FD_ISSET(pListen->s6, &rs) ){
    pClient->s6 = accept(pListen->s6, (struct sockaddr*)&pClientAddr->a6.addr,
                         &pClientAddr->a6.len);
  }
}

/*
** The HttpServer structure holds information about an instance of
** the HTTP server itself.
*/
typedef struct HttpServer HttpServer;
struct HttpServer {
  HANDLE hStoppedEvent; /* Event to signal when server is stopped,
                        ** must be closed by callee. */
  char *zStopper;       /* The stopper file name, must be freed by
                        ** callee. */
  DualSocket listener;  /* Sockets on which the server is listening,
                        ** may be closed by callee. */
};

/*
** The HttpRequest structure holds information about each incoming
** HTTP request.
*/
typedef struct HttpRequest HttpRequest;
struct HttpRequest {
  int id;                /* ID counter */
  SOCKET s;              /* Socket on which to receive data */
  SocketAddr addr;       /* Address from which data is coming */
  int flags;             /* Flags passed to win32_http_server() */
  const char *zOptions;  /* --baseurl, --notfound, --localauth, --th-trace */
};

/*
** Prefix for a temporary file.
*/
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
** is found.  If there is no stopper file name, do nothing.
*/
static void win32_server_stopper(void *pAppData){
  HttpServer *p = (HttpServer*)pAppData;
  if( p!=0 ){
    HANDLE hStoppedEvent = p->hStoppedEvent;
    const char *zStopper = p->zStopper;
    SOCKET listener = p->listener;
    if( hStoppedEvent!=NULL && zStopper!=0 && listener!=INVALID_SOCKET ){
      while( 1 ){
        DWORD dwResult = WaitForMultipleObjectsEx(1, &hStoppedEvent, FALSE,
                                                  1000, TRUE);
        if( dwResult!=WAIT_IO_COMPLETION && dwResult!=WAIT_TIMEOUT ){
          /* The event is either invalid, signaled, or abandoned.  Bail
          ** out now because those conditions should indicate the parent
          ** thread is dead or dying. */
          break;
        }
        if( file_size(zStopper, ExtFILE)>=0 ){
          /* The stopper file has been found.  Attempt to close the server
          ** listener socket now and then exit. */
          closesocket(listener);
          p->listener = INVALID_SOCKET;
          break;
        }
      }
    }
    if( hStoppedEvent!=NULL ){
      CloseHandle(hStoppedEvent);
      p->hStoppedEvent = NULL;







<
|












<
|







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
** is found.  If there is no stopper file name, do nothing.
*/
static void win32_server_stopper(void *pAppData){
  HttpServer *p = (HttpServer*)pAppData;
  if( p!=0 ){
    HANDLE hStoppedEvent = p->hStoppedEvent;
    const char *zStopper = p->zStopper;

    if( hStoppedEvent!=NULL && zStopper!=0 ){
      while( 1 ){
        DWORD dwResult = WaitForMultipleObjectsEx(1, &hStoppedEvent, FALSE,
                                                  1000, TRUE);
        if( dwResult!=WAIT_IO_COMPLETION && dwResult!=WAIT_TIMEOUT ){
          /* The event is either invalid, signaled, or abandoned.  Bail
          ** out now because those conditions should indicate the parent
          ** thread is dead or dying. */
          break;
        }
        if( file_size(zStopper, ExtFILE)>=0 ){
          /* The stopper file has been found.  Attempt to close the server
          ** listener socket now and then exit. */

          DualSocket_close(&p->listener);
          break;
        }
      }
    }
    if( hStoppedEvent!=NULL ){
      CloseHandle(hStoppedEvent);
      p->hStoppedEvent = NULL;
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
*/
static void win32_http_request(void *pAppData){
  HttpRequest *p = (HttpRequest*)pAppData;
  FILE *in = 0, *out = 0, *aux = 0;
  int amt, got, i;
  int wanted = 0;
  char *z;
  char zIp[50];
  DWORD nIp = sizeof(zIp);
  char zCmdFName[MAX_PATH];
  char zRequestFName[MAX_PATH];
  char zReplyFName[MAX_PATH];
  char zCmd[2000];          /* Command-line to process the request */
  char zHdr[4000];          /* The HTTP request header */

  sqlite3_snprintf(MAX_PATH, zCmdFName,







|
<







333
334
335
336
337
338
339
340

341
342
343
344
345
346
347
*/
static void win32_http_request(void *pAppData){
  HttpRequest *p = (HttpRequest*)pAppData;
  FILE *in = 0, *out = 0, *aux = 0;
  int amt, got, i;
  int wanted = 0;
  char *z;
  char *zIp;

  char zCmdFName[MAX_PATH];
  char zRequestFName[MAX_PATH];
  char zReplyFName[MAX_PATH];
  char zCmd[2000];          /* Command-line to process the request */
  char zHdr[4000];          /* The HTTP request header */

  sqlite3_snprintf(MAX_PATH, zCmdFName,
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
  }

  /*
  ** The repository name is only needed if there was no open checkout.  This
  ** is designed to allow the open checkout for the interactive user to work
  ** with the local Fossil server started via the "ui" command.
  */
  p->addr.sin6_port = 0;
  if( WSAAddressToStringA((SOCKADDR*)&p->addr, sizeof(p->addr),
                          NULL, zIp, &nIp)!=0 ){
    zIp[0] = 0;
  }
  if( (p->flags & HTTP_SERVER_HAD_CHECKOUT)==0 ){
    assert( g.zRepositoryName && g.zRepositoryName[0] );
    sqlite3_snprintf(sizeof(zCmd), zCmd, "%s%s\n%s\n%s\n%s",
      get_utf8_bom(0), zRequestFName, zReplyFName, zIp, g.zRepositoryName
    );
  }else{
    sqlite3_snprintf(sizeof(zCmd), zCmd, "%s%s\n%s\n%s",
      get_utf8_bom(0), zRequestFName, zReplyFName, zIp
    );
  }

  aux = fossil_fopen(zCmdFName, "wb");
  if( aux==0 ) goto end_request;
  fwrite(zCmd, 1, strlen(zCmd), aux);

  sqlite3_snprintf(sizeof(zCmd), zCmd, "\"%s\" http -args \"%s\" --nossl%s",
    g.nameOfExe, zCmdFName, p->zOptions
  );







|
<
<
<
<










>







382
383
384
385
386
387
388
389




390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
  }

  /*
  ** The repository name is only needed if there was no open checkout.  This
  ** is designed to allow the open checkout for the interactive user to work
  ** with the local Fossil server started via the "ui" command.
  */
  zIp = SocketAddr_toString(&p->addr);




  if( (p->flags & HTTP_SERVER_HAD_CHECKOUT)==0 ){
    assert( g.zRepositoryName && g.zRepositoryName[0] );
    sqlite3_snprintf(sizeof(zCmd), zCmd, "%s%s\n%s\n%s\n%s",
      get_utf8_bom(0), zRequestFName, zReplyFName, zIp, g.zRepositoryName
    );
  }else{
    sqlite3_snprintf(sizeof(zCmd), zCmd, "%s%s\n%s\n%s",
      get_utf8_bom(0), zRequestFName, zReplyFName, zIp
    );
  }
  fossil_free(zIp);
  aux = fossil_fopen(zCmdFName, "wb");
  if( aux==0 ) goto end_request;
  fwrite(zCmd, 1, strlen(zCmd), aux);

  sqlite3_snprintf(sizeof(zCmd), zCmd, "\"%s\" http -args \"%s\" --nossl%s",
    g.nameOfExe, zCmdFName, p->zOptions
  );
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
** Process a single incoming SCGI request.
*/
static void win32_scgi_request(void *pAppData){
  HttpRequest *p = (HttpRequest*)pAppData;
  FILE *in = 0, *out = 0;
  int amt, got, nHdr, i;
  int wanted = 0;
  char zIp[50];
  DWORD nIp = sizeof(zIp);
  char zRequestFName[MAX_PATH];
  char zReplyFName[MAX_PATH];
  char zCmd[2000];          /* Command-line to process the request */
  char zHdr[4000];          /* The SCGI request header */

  sqlite3_snprintf(MAX_PATH, zRequestFName,
                   "%s_%06d_in.txt", zTempPrefix, p->id);







|
<







435
436
437
438
439
440
441
442

443
444
445
446
447
448
449
** Process a single incoming SCGI request.
*/
static void win32_scgi_request(void *pAppData){
  HttpRequest *p = (HttpRequest*)pAppData;
  FILE *in = 0, *out = 0;
  int amt, got, nHdr, i;
  int wanted = 0;
  char *zIp;

  char zRequestFName[MAX_PATH];
  char zReplyFName[MAX_PATH];
  char zCmd[2000];          /* Command-line to process the request */
  char zHdr[4000];          /* The SCGI request header */

  sqlite3_snprintf(MAX_PATH, zRequestFName,
                   "%s_%06d_in.txt", zTempPrefix, p->id);
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292

293
294
295
296
297
298
299
  while( wanted>amt ){
    got = recv(p->s, zHdr, wanted<sizeof(zHdr) ? wanted : sizeof(zHdr), 0);
    if( got<=0 ) break;
    fwrite(zHdr, 1, got, out);
    wanted += got;
  }
  assert( g.zRepositoryName && g.zRepositoryName[0] );
  p->addr.sin6_port = 0;
  if (WSAAddressToStringA((SOCKADDR*)&p->addr, sizeof(p->addr),
                          NULL, zIp, &nIp)!=0){
    zIp[0] = 0;
  }
  sqlite3_snprintf(sizeof(zCmd), zCmd,
    "\"%s\" http \"%s\" \"%s\" %s \"%s\" --scgi --nossl%s",
    g.nameOfExe, zRequestFName, zReplyFName, zIp,
    g.zRepositoryName, p->zOptions
  );

  in = fossil_fopen(zReplyFName, "w+b");
  fflush(out);
  fossil_system(zCmd);
  if( in ){
    while( (got = fread(zHdr, 1, sizeof(zHdr), in))>0 ){
      send(p->s, zHdr, got, 0);
    }







|
<
<
<
<





>







466
467
468
469
470
471
472
473




474
475
476
477
478
479
480
481
482
483
484
485
486
  while( wanted>amt ){
    got = recv(p->s, zHdr, wanted<sizeof(zHdr) ? wanted : sizeof(zHdr), 0);
    if( got<=0 ) break;
    fwrite(zHdr, 1, got, out);
    wanted += got;
  }
  assert( g.zRepositoryName && g.zRepositoryName[0] );
  zIp = SocketAddr_toString(&p->addr);




  sqlite3_snprintf(sizeof(zCmd), zCmd,
    "\"%s\" http \"%s\" \"%s\" %s \"%s\" --scgi --nossl%s",
    g.nameOfExe, zRequestFName, zReplyFName, zIp,
    g.zRepositoryName, p->zOptions
  );
  fossil_free(zIp);
  in = fossil_fopen(zReplyFName, "w+b");
  fflush(out);
  fossil_system(zCmd);
  if( in ){
    while( (got = fread(zHdr, 1, sizeof(zHdr), in))>0 ){
      send(p->s, zHdr, got, 0);
    }
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
342
  ** software keeps the files open for a few seconds, preventing the file
  ** from being deleted on the first try. */
  for(i=1; i<=10 && file_delete(zRequestFName); i++){ Sleep(1000*i); }
  for(i=1; i<=10 && file_delete(zReplyFName); i++){ Sleep(1000*i); }
  fossil_free(p);
}




/*
** Start a listening socket and process incoming HTTP requests on
** that socket.
*/
void win32_http_server(
  int mnPort, int mxPort,   /* Range of allowed TCP port numbers */
  const char *zBrowser,     /* Command to launch browser.  (Or NULL) */
  const char *zStopper,     /* Stop server when this file is exists (Or NULL) */
  const char *zBaseUrl,     /* The --baseurl option, or NULL */
  const char *zNotFound,    /* The --notfound option, or NULL */
  const char *zFileGlob,    /* The --fileglob option, or NULL */
  const char *zIpAddr,      /* Bind to this IP address, if not NULL */
  int flags                 /* One or more HTTP_SERVER_ flags */
){
  HANDLE hStoppedEvent;
  WSADATA wd;
  SOCKET s = INVALID_SOCKET;
  SOCKADDR_IN6 addr;
  int addrlen;
  int idCnt = 0;
  int iPort = mnPort;
  Blob options;
  wchar_t zTmpPath[MAX_PATH];
  const char *zSkin;
#if USE_SEE
  const char *zSavedKey = 0;







>
>

















<
<
|







496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521


522
523
524
525
526
527
528
529
  ** software keeps the files open for a few seconds, preventing the file
  ** from being deleted on the first try. */
  for(i=1; i<=10 && file_delete(zRequestFName); i++){ Sleep(1000*i); }
  for(i=1; i<=10 && file_delete(zReplyFName); i++){ Sleep(1000*i); }
  fossil_free(p);
}

/* forward reference */
static void win32_http_service_running(DualSocket* pS);

/*
** Start a listening socket and process incoming HTTP requests on
** that socket.
*/
void win32_http_server(
  int mnPort, int mxPort,   /* Range of allowed TCP port numbers */
  const char *zBrowser,     /* Command to launch browser.  (Or NULL) */
  const char *zStopper,     /* Stop server when this file is exists (Or NULL) */
  const char *zBaseUrl,     /* The --baseurl option, or NULL */
  const char *zNotFound,    /* The --notfound option, or NULL */
  const char *zFileGlob,    /* The --fileglob option, or NULL */
  const char *zIpAddr,      /* Bind to this IP address, if not NULL */
  int flags                 /* One or more HTTP_SERVER_ flags */
){
  HANDLE hStoppedEvent;
  WSADATA wd;


  DualSocket ds;
  int idCnt = 0;
  int iPort = mnPort;
  Blob options;
  wchar_t zTmpPath[MAX_PATH];
  const char *zSkin;
#if USE_SEE
  const char *zSavedKey = 0;
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396

397
398
399
400
401
402
403
404
405
406
407
408


409
410
411
412
413

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    blob_appendf(&options, " --usepidkey %lu:%p:%u", GetCurrentProcessId(),
                 zSavedKey, savedKeySize);
  }
#endif
  if( WSAStartup(MAKEWORD(2,0), &wd) ){
    fossil_fatal("unable to initialize winsock");
  }
  if( flags & HTTP_SERVER_LOCALHOST ){
    zIpAddr = "::1";
  }
  while( iPort<=mxPort ){
    DWORD ipv6only = 0;
    s = socket(AF_INET6, SOCK_STREAM, 0);
    if( s==INVALID_SOCKET ){
      fossil_fatal("unable to create a socket");
    }
    setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only,
               sizeof(ipv6only));
    memset(&addr, 0, sizeof(addr));
    addrlen = sizeof(addr);
    if( zIpAddr ){
      char* zIp;
      if( strstr(zIpAddr, ".") ){
        zIp = mprintf("::ffff:%s", zIpAddr);

      }else{
        zIp = mprintf("%s", zIpAddr);
      }
      addr.sin6_family = AF_INET6;
      if (WSAStringToAddress(zIp, AF_INET6, NULL,
                             (struct sockaddr *)&addr, &addrlen) != 0){
        fossil_fatal("not a valid IP address: %s", zIpAddr);
      }
      ((SOCKADDR_IN6*)&addr)->sin6_port = htons(iPort);
      fossil_free(zIp);
    }else{
      addr.sin6_family = AF_INET6;


      addr.sin6_port = htons(iPort);
      memcpy(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any));
    }
    if( bind(s, (struct sockaddr*)&addr, sizeof(addr))==SOCKET_ERROR ){
      closesocket(s);

      iPort++;
      continue;
    }
    if( listen(s, SOMAXCONN)==SOCKET_ERROR ){
      closesocket(s);
      iPort++;
      continue;
    }
    break;
  }
  if( iPort>mxPort ){
    if( mnPort==mxPort ){
      fossil_fatal("unable to open listening socket on ports %d", mnPort);
    }else{
      fossil_fatal("unable to open listening socket on any"
                   " port in the range %d..%d", mnPort, mxPort);
    }
  }
  if( !GetTempPathW(MAX_PATH, zTmpPath) ){
    fossil_fatal("unable to get path to the temporary directory.");







|
<
<

<
<
<
<
<
<
<
<
<

<
|
<
>
|
<

<
<
<
<
<
<
<

<
>
>
|
<
<
<
<
>
|
|
|
<
<
<
<





|







560
561
562
563
564
565
566
567


568









569

570

571
572

573







574

575
576
577




578
579
580
581




582
583
584
585
586
587
588
589
590
591
592
593
594
    blob_appendf(&options, " --usepidkey %lu:%p:%u", GetCurrentProcessId(),
                 zSavedKey, savedKeySize);
  }
#endif
  if( WSAStartup(MAKEWORD(2,0), &wd) ){
    fossil_fatal("unable to initialize winsock");
  }
  DualSocket_init(&ds);


  while( iPort<=mxPort ){









    if( zIpAddr ){

      if( DualSocket_listen(&ds, zIpAddr, iPort)==0 ){

        iPort++;
        continue;

      }







    }else{

      if( DualSocket_listen(&ds,
                            (flags & HTTP_SERVER_LOCALHOST) ? "L" : "W",
                            iPort




                           )==0 ){
        iPort++;
        continue;
      }




    }
    break;
  }
  if( iPort>mxPort ){
    if( mnPort==mxPort ){
      fossil_fatal("unable to open listening socket on port %d", mnPort);
    }else{
      fossil_fatal("unable to open listening socket on any"
                   " port in the range %d..%d", mnPort, mxPort);
    }
  }
  if( !GetTempPathW(MAX_PATH, zTmpPath) ){
    fossil_fatal("unable to get path to the temporary directory.");
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

479
480
481
482
483
484
485
486
487

488
489
490

491












492
493
494
495
496
497
498
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525

526
527
528
529
530
531
532
    HttpServer *pServer = fossil_malloc(sizeof(HttpServer));
    memset(pServer, 0, sizeof(HttpServer));
    DuplicateHandle(GetCurrentProcess(), hStoppedEvent,
                    GetCurrentProcess(), &pServer->hStoppedEvent,
                    0, FALSE, DUPLICATE_SAME_ACCESS);
    assert( pServer->hStoppedEvent!=NULL );
    pServer->zStopper = fossil_strdup(zStopper);
    pServer->listener = s;
    file_delete(zStopper);
    _beginthread(win32_server_stopper, 0, (void*)pServer);
  }
  /* Set the service status to running and pass the listener socket to the
  ** service handling procedures. */
  win32_http_service_running(s);
  for(;;){
    SOCKET client;
    SOCKADDR_IN6 client_addr;
    HttpRequest *pRequest;
    int len = sizeof(client_addr);
    int wsaError;

    client = accept(s, (struct sockaddr*)&client_addr, &len);
    if( client==INVALID_SOCKET ){
      /* If the service control handler has closed the listener socket,
      ** cleanup and return, otherwise report a fatal error. */
      wsaError =  WSAGetLastError();

      if( (wsaError==WSAEINTR) || (wsaError==WSAENOTSOCK) ){
        WSACleanup();
        return;
      }else{
        closesocket(s);
        WSACleanup();
        fossil_fatal("error from accept()");
      }
    }

    pRequest = fossil_malloc(sizeof(HttpRequest));
    pRequest->id = ++idCnt;
    pRequest->s = client;

    pRequest->addr = client_addr;












    pRequest->flags = flags;
    pRequest->zOptions = blob_str(&options);
    if( flags & HTTP_SERVER_SCGI ){
      _beginthread(win32_scgi_request, 0, (void*)pRequest);
    }else{
      _beginthread(win32_http_request, 0, (void*)pRequest);
    }
  }

  closesocket(s);
  WSACleanup();
  SetEvent(hStoppedEvent);
  CloseHandle(hStoppedEvent);
}

/*
** The HttpService structure is used to pass information to the service main
** function and to the service control handler function.
*/
typedef struct HttpService HttpService;
struct HttpService {
  int port;                 /* Port on which the http server should run */
  const char *zBaseUrl;     /* The --baseurl option, or NULL */
  const char *zNotFound;    /* The --notfound option, or NULL */
  const char *zFileGlob;    /* The --files option, or NULL */
  int flags;                /* One or more HTTP_SERVER_ flags */
  int isRunningAsService;   /* Are we running as a service ? */
  const wchar_t *zServiceName;/* Name of the service */
  SOCKET s;                 /* Socket on which the http server listens */
};

/*
** Variables used for running as windows service.
*/
static HttpService hsData = {8080, NULL, NULL, NULL, 0, 0, NULL, INVALID_SOCKET};

static SERVICE_STATUS ssStatus;
static SERVICE_STATUS_HANDLE sshStatusHandle;

/*
** Get message string of the last system error. Return a pointer to the
** message string. Call fossil_unicode_free() to deallocate any memory used
** to store the message string when done.







|





|

|
|

<


|
|



>




<




>
|
|
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
>
|


















|





|
>







614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

632
633
634
635
636
637
638
639
640
641
642
643

644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
    HttpServer *pServer = fossil_malloc(sizeof(HttpServer));
    memset(pServer, 0, sizeof(HttpServer));
    DuplicateHandle(GetCurrentProcess(), hStoppedEvent,
                    GetCurrentProcess(), &pServer->hStoppedEvent,
                    0, FALSE, DUPLICATE_SAME_ACCESS);
    assert( pServer->hStoppedEvent!=NULL );
    pServer->zStopper = fossil_strdup(zStopper);
    pServer->listener = ds;
    file_delete(zStopper);
    _beginthread(win32_server_stopper, 0, (void*)pServer);
  }
  /* Set the service status to running and pass the listener socket to the
  ** service handling procedures. */
  win32_http_service_running(&ds);
  for(;;){
    DualSocket client;
    DualAddr client_addr;
    HttpRequest *pRequest;

    int wsaError;

    DualSocket_accept(&ds, &client, &client_addr);
    if( client.s4==INVALID_SOCKET && client.s6==INVALID_SOCKET ){
      /* If the service control handler has closed the listener socket,
      ** cleanup and return, otherwise report a fatal error. */
      wsaError =  WSAGetLastError();
      DualSocket_close(&ds);
      if( (wsaError==WSAEINTR) || (wsaError==WSAENOTSOCK) ){
        WSACleanup();
        return;
      }else{

        WSACleanup();
        fossil_fatal("error from accept()");
      }
    }
    if( client.s4!=INVALID_SOCKET ){
      pRequest = fossil_malloc(sizeof(HttpRequest));
      pRequest->id = ++idCnt;
      pRequest->s = client.s4;
      memcpy(&pRequest->addr, &client_addr.a4, sizeof(client_addr.a4));
      pRequest->flags = flags;
      pRequest->zOptions = blob_str(&options);
      if( flags & HTTP_SERVER_SCGI ){
        _beginthread(win32_scgi_request, 0, (void*)pRequest);
      }else{
        _beginthread(win32_http_request, 0, (void*)pRequest);
      }
    }
    if( client.s6!=INVALID_SOCKET ){
      pRequest = fossil_malloc(sizeof(HttpRequest));
      pRequest->id = ++idCnt;
      pRequest->s = client.s6;
      memcpy(&pRequest->addr, &client_addr.a6, sizeof(client_addr.a6));
      pRequest->flags = flags;
      pRequest->zOptions = blob_str(&options);
      if( flags & HTTP_SERVER_SCGI ){
        _beginthread(win32_scgi_request, 0, (void*)pRequest);
      }else{
        _beginthread(win32_http_request, 0, (void*)pRequest);
      }
    }
  }
  DualSocket_close(&ds);
  WSACleanup();
  SetEvent(hStoppedEvent);
  CloseHandle(hStoppedEvent);
}

/*
** The HttpService structure is used to pass information to the service main
** function and to the service control handler function.
*/
typedef struct HttpService HttpService;
struct HttpService {
  int port;                 /* Port on which the http server should run */
  const char *zBaseUrl;     /* The --baseurl option, or NULL */
  const char *zNotFound;    /* The --notfound option, or NULL */
  const char *zFileGlob;    /* The --files option, or NULL */
  int flags;                /* One or more HTTP_SERVER_ flags */
  int isRunningAsService;   /* Are we running as a service ? */
  const wchar_t *zServiceName;/* Name of the service */
  DualSocket s;             /* Sockets on which the http server listens */
};

/*
** Variables used for running as windows service.
*/
static HttpService hsData = {8080, NULL, NULL, NULL, 0, 0, NULL,
                             {INVALID_SOCKET, INVALID_SOCKET}};
static SERVICE_STATUS ssStatus;
static SERVICE_STATUS_HANDLE sshStatusHandle;

/*
** Get message string of the last system error. Return a pointer to the
** message string. Call fossil_unicode_free() to deallocate any memory used
** to store the message string when done.
609
610
611
612
613
614
615

616
617
618
619
620
621
622
623
624
625
626
627
** control manager.
*/
static void WINAPI win32_http_service_ctrl(
  DWORD dwCtrlCode
){
  switch( dwCtrlCode ){
    case SERVICE_CONTROL_STOP: {

      win32_report_service_status(SERVICE_STOP_PENDING, NO_ERROR, 0);
      if( hsData.s != INVALID_SOCKET ){
        closesocket(hsData.s);
      }
      win32_report_service_status(ssStatus.dwCurrentState, NO_ERROR, 0);
      break;
    }
    default: {
      break;
    }
  }
  return;







>

<
<
<
<







785
786
787
788
789
790
791
792
793




794
795
796
797
798
799
800
** control manager.
*/
static void WINAPI win32_http_service_ctrl(
  DWORD dwCtrlCode
){
  switch( dwCtrlCode ){
    case SERVICE_CONTROL_STOP: {
      DualSocket_close(&hsData.s);
      win32_report_service_status(SERVICE_STOP_PENDING, NO_ERROR, 0);




      break;
    }
    default: {
      break;
    }
  }
  return;
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
}

/*
** When running as service, update the HttpService structure with the
** listener socket and update the service status. This procedure must be
** called from the http server when he is ready to accept connections.
*/
LOCAL void win32_http_service_running(SOCKET s){
  if( hsData.isRunningAsService ){
    hsData.s = s;
    win32_report_service_status(SERVICE_RUNNING, NO_ERROR, 0);
  }
}

/*
** Try to start the http server as a windows service. If we are running in
** a interactive console session, this routine fails and returns a non zero







|

|







845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
}

/*
** When running as service, update the HttpService structure with the
** listener socket and update the service status. This procedure must be
** called from the http server when he is ready to accept connections.
*/
static void win32_http_service_running(DualSocket *pS){
  if( hsData.isRunningAsService ){
    hsData.s = *pS;
    win32_report_service_status(SERVICE_RUNNING, NO_ERROR, 0);
  }
}

/*
** Try to start the http server as a windows service. If we are running in
** a interactive console session, this routine fails and returns a non zero
702
703
704
705
706
707
708


709
710
711
712
713
714
715

  /* Initialize the HttpService structure. */
  hsData.port = nPort;
  hsData.zBaseUrl = zBaseUrl;
  hsData.zNotFound = zNotFound;
  hsData.zFileGlob = zFileGlob;
  hsData.flags = flags;



  /* Try to start the control dispatcher thread for the service. */
  if( !StartServiceCtrlDispatcherW(ServiceTable) ){
    if( GetLastError()==ERROR_FAILED_SERVICE_CONTROLLER_CONNECT ){
      return 1;
    }else{
      fossil_fatal("error from StartServiceCtrlDispatcher()");







>
>







875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890

  /* Initialize the HttpService structure. */
  hsData.port = nPort;
  hsData.zBaseUrl = zBaseUrl;
  hsData.zNotFound = zNotFound;
  hsData.zFileGlob = zFileGlob;
  hsData.flags = flags;

  if( GetStdHandle(STD_INPUT_HANDLE)!=NULL ){ return 1; }

  /* Try to start the control dispatcher thread for the service. */
  if( !StartServiceCtrlDispatcherW(ServiceTable) ){
    if( GetLastError()==ERROR_FAILED_SERVICE_CONTROLLER_CONNECT ){
      return 1;
    }else{
      fossil_fatal("error from StartServiceCtrlDispatcher()");
961
962
963
964
965
966
967

968
969

970
971
972
973

974



975
976
977
978
979
980
981
    QueryServiceStatus(hSvc, &sstat);
    if( sstat.dwCurrentState!=SERVICE_STOPPED ){
      fossil_print("Stopping service '%s'", zSvcName);
      if( sstat.dwCurrentState!=SERVICE_STOP_PENDING ){
        if( !ControlService(hSvc, SERVICE_CONTROL_STOP, &sstat) ){
          winhttp_fatal("delete", zSvcName, win32_get_last_errmsg());
        }

      }
      while( sstat.dwCurrentState!=SERVICE_STOPPED ){

        Sleep(100);
        fossil_print(".");
        QueryServiceStatus(hSvc, &sstat);
      }

      fossil_print("\nService '%s' stopped.\n", zSvcName);



    }
    if( !DeleteService(hSvc) ){
      if( GetLastError()==ERROR_SERVICE_MARKED_FOR_DELETE ){
        fossil_warning("Service '%s' already marked for delete.\n", zSvcName);
      }else{
        winhttp_fatal("delete", zSvcName, win32_get_last_errmsg());
      }







>

|
>




>
|
>
>
>







1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
    QueryServiceStatus(hSvc, &sstat);
    if( sstat.dwCurrentState!=SERVICE_STOPPED ){
      fossil_print("Stopping service '%s'", zSvcName);
      if( sstat.dwCurrentState!=SERVICE_STOP_PENDING ){
        if( !ControlService(hSvc, SERVICE_CONTROL_STOP, &sstat) ){
          winhttp_fatal("delete", zSvcName, win32_get_last_errmsg());
        }
        QueryServiceStatus(hSvc, &sstat);
      }
      while( sstat.dwCurrentState==SERVICE_STOP_PENDING  ||
             sstat.dwCurrentState==SERVICE_RUNNING ){
        Sleep(100);
        fossil_print(".");
        QueryServiceStatus(hSvc, &sstat);
      }
      if( sstat.dwCurrentState==SERVICE_STOPPED ){
        fossil_print("\nService '%s' stopped.\n", zSvcName);
      }else{
        winhttp_fatal("delete", zSvcName, win32_get_last_errmsg());
      }
    }
    if( !DeleteService(hSvc) ){
      if( GetLastError()==ERROR_SERVICE_MARKED_FOR_DELETE ){
        fossil_warning("Service '%s' already marked for delete.\n", zSvcName);
      }else{
        winhttp_fatal("delete", zSvcName, win32_get_last_errmsg());
      }
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116

1117
1118

1119
1120
1121
1122

1123



1124
1125
1126
1127
1128
1129
1130
    if( !hScm ) winhttp_fatal("start", zSvcName, win32_get_last_errmsg());
    hSvc = OpenServiceW(hScm, fossil_utf8_to_unicode(zSvcName),
                        SERVICE_ALL_ACCESS);
    if( !hSvc ) winhttp_fatal("start", zSvcName, win32_get_last_errmsg());
    QueryServiceStatus(hSvc, &sstat);
    if( sstat.dwCurrentState!=SERVICE_RUNNING ){
      fossil_print("Starting service '%s'", zSvcName);
      if( sstat.dwCurrentState!=SERVICE_START_PENDING ){
        if( !StartServiceW(hSvc, 0, NULL) ){
          winhttp_fatal("start", zSvcName, win32_get_last_errmsg());
        }

      }
      while( sstat.dwCurrentState!=SERVICE_RUNNING ){

        Sleep(100);
        fossil_print(".");
        QueryServiceStatus(hSvc, &sstat);
      }

      fossil_print("\nService '%s' started.\n", zSvcName);



    }else{
      fossil_print("Service '%s' is already started.\n", zSvcName);
    }
    CloseServiceHandle(hSvc);
    CloseServiceHandle(hScm);
  }else
  if( strncmp(zMethod, "stop", n)==0 ){







|
|
|
|
>
|
|
>




>
|
>
>
>







1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
    if( !hScm ) winhttp_fatal("start", zSvcName, win32_get_last_errmsg());
    hSvc = OpenServiceW(hScm, fossil_utf8_to_unicode(zSvcName),
                        SERVICE_ALL_ACCESS);
    if( !hSvc ) winhttp_fatal("start", zSvcName, win32_get_last_errmsg());
    QueryServiceStatus(hSvc, &sstat);
    if( sstat.dwCurrentState!=SERVICE_RUNNING ){
      fossil_print("Starting service '%s'", zSvcName);
      if( sstat.dwCurrentState!=SERVICE_START_PENDING ){ 
        if( !StartServiceW(hSvc, 0, NULL) ){ 
          winhttp_fatal("start", zSvcName, win32_get_last_errmsg()); 
        } 
        QueryServiceStatus(hSvc, &sstat); 
      } 
      while( sstat.dwCurrentState==SERVICE_START_PENDING ||
             sstat.dwCurrentState==SERVICE_STOPPED ){
        Sleep(100);
        fossil_print(".");
        QueryServiceStatus(hSvc, &sstat);
      }
      if( sstat.dwCurrentState==SERVICE_RUNNING ){
        fossil_print("\nService '%s' started.\n", zSvcName);
      }else{
        winhttp_fatal("start", zSvcName, win32_get_last_errmsg());
      }
    }else{
      fossil_print("Service '%s' is already started.\n", zSvcName);
    }
    CloseServiceHandle(hSvc);
    CloseServiceHandle(hScm);
  }else
  if( strncmp(zMethod, "stop", n)==0 ){
1146
1147
1148
1149
1150
1151
1152

1153
1154

1155
1156
1157
1158

1159



1160
1161
1162
1163
1164
1165
1166
    QueryServiceStatus(hSvc, &sstat);
    if( sstat.dwCurrentState!=SERVICE_STOPPED ){
      fossil_print("Stopping service '%s'", zSvcName);
      if( sstat.dwCurrentState!=SERVICE_STOP_PENDING ){
        if( !ControlService(hSvc, SERVICE_CONTROL_STOP, &sstat) ){
          winhttp_fatal("stop", zSvcName, win32_get_last_errmsg());
        }

      }
      while( sstat.dwCurrentState!=SERVICE_STOPPED ){

        Sleep(100);
        fossil_print(".");
        QueryServiceStatus(hSvc, &sstat);
      }

      fossil_print("\nService '%s' stopped.\n", zSvcName);



    }else{
      fossil_print("Service '%s' is already stopped.\n", zSvcName);
    }
    CloseServiceHandle(hSvc);
    CloseServiceHandle(hScm);
  }else
  {







>

|
>




>
|
>
>
>







1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
    QueryServiceStatus(hSvc, &sstat);
    if( sstat.dwCurrentState!=SERVICE_STOPPED ){
      fossil_print("Stopping service '%s'", zSvcName);
      if( sstat.dwCurrentState!=SERVICE_STOP_PENDING ){
        if( !ControlService(hSvc, SERVICE_CONTROL_STOP, &sstat) ){
          winhttp_fatal("stop", zSvcName, win32_get_last_errmsg());
        }
        QueryServiceStatus(hSvc, &sstat);
      }
      while( sstat.dwCurrentState==SERVICE_STOP_PENDING ||
             sstat.dwCurrentState==SERVICE_RUNNING ){
        Sleep(100);
        fossil_print(".");
        QueryServiceStatus(hSvc, &sstat);
      }
      if( sstat.dwCurrentState==SERVICE_STOPPED ){
        fossil_print("\nService '%s' stopped.\n", zSvcName);
      }else{
        winhttp_fatal("stop", zSvcName, win32_get_last_errmsg());
      }
    }else{
      fossil_print("Service '%s' is already stopped.\n", zSvcName);
    }
    CloseServiceHandle(hSvc);
    CloseServiceHandle(hScm);
  }else
  {