summaryrefslogtreecommitdiff
path: root/ports/winnt/ntpd/ntservice.c
blob: f0840bdb9d6a833247c2f1dfd2066ff711b939e0 (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
/*
 * Copyright (C) 2004  Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 1999-2002  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdio.h>

#include <ntp_stdlib.h>
#include "syslog.h"
#include "ntpd.h"
#include "ntservice.h"
#include "clockstuff.h"
#include "ntp_iocompletionport.h"
#include "ntpd-opts.h"
#include "isc/win32os.h"
#include <ssl_applink.c>


/*
 * Globals
 */
static SERVICE_STATUS_HANDLE hServiceStatus = 0;
static BOOL foreground = FALSE;
static BOOL computer_shutting_down = FALSE;
static int glb_argc;
static char **glb_argv;
HANDLE hServDoneEvent = NULL;
extern int accept_wildcard_if_for_winnt;

/*
 * Forward declarations
 */
void uninit_io_completion_port();
int ntpdmain(int argc, char *argv[]);
void WINAPI ServiceControl(DWORD dwCtrlCode);
void ntservice_exit(void);

#ifdef WRAP_DBG_MALLOC
void *wrap_dbg_malloc(size_t s, const char *f, int l);
void *wrap_dbg_realloc(void *p, size_t s, const char *f, int l);
void wrap_dbg_free(void *p);
#endif

void WINAPI
service_main(
	DWORD argc,
	LPTSTR *argv
	)
{
	if (argc > 1) {
		/*
		 * Let command line parameters from the Windows SCM GUI
		 * override the standard parameters from the ImagePath registry key.
		 */
		glb_argc = argc;
		glb_argv = argv;
	}

	ntpdmain(glb_argc, glb_argv);
}


/*
 * This is the entry point for the executable 
 * We can call ntpdmain() explicitly or via StartServiceCtrlDispatcher()
 * as we need to.
 */
int main(
	int	argc,
	char **	argv
	)
{
	int	rc;
	int	argc_after_opts;
	char **	argv_after_opts;

	ssl_applink();

	/* Save the command line parameters */
	glb_argc = argc;
	glb_argv = argv;

	/* Under original Windows NT we must not discard the wildcard */
	/* socket to workaround a bug in NT's getsockname(). */
	if (isc_win32os_majorversion() <= 4)
		accept_wildcard_if_for_winnt = TRUE;

	argc_after_opts = argc;
	argv_after_opts = argv;
	parse_cmdline_opts(&argc_after_opts, &argv_after_opts);

	if (HAVE_OPT(QUIT)
	    || HAVE_OPT(SAVECONFIGQUIT)
	    || HAVE_OPT(HELP)
#ifdef DEBUG
	    || OPT_VALUE_SET_DEBUG_LEVEL != 0
#endif
	    || HAVE_OPT(NOFORK))
		foreground = TRUE;

	if (foreground)			/* run in console window */
		rc = ntpdmain(argc, argv);
	else {
		/* Start up as service */

		SERVICE_TABLE_ENTRY dispatchTable[] = {
			{ TEXT(NTP_DISPLAY_NAME), service_main },
			{ NULL, NULL }
		};

		rc = StartServiceCtrlDispatcher(dispatchTable);
		if (rc)
			rc = 0; 
		else {
			rc = GetLastError();
			fprintf(stderr,
				"%s: unable to start as service:\n"
				"%s\n"
				"Use -d, -q, -n, -?, --help or "
				"--saveconfigquit to run "
				"interactive.\n",
				argv[0], ntp_strerror(rc));
		}
	}
	return rc;
}


/*
 * Initialize the Service by registering it.
 */
void
ntservice_init() {
	char ConsoleTitle[256];

	if (!foreground) {
		/* Register handler with the SCM */
		hServiceStatus = RegisterServiceCtrlHandler(NTP_DISPLAY_NAME,
					ServiceControl);
		if (!hServiceStatus) {
			NTReportError(NTP_SERVICE_NAME,
				"could not register service control handler");
			exit(1);
		}
		UpdateSCM(SERVICE_RUNNING);
	} else {
		snprintf(ConsoleTitle, sizeof(ConsoleTitle),
			 "NTP Version %s", Version);
		ConsoleTitle[sizeof(ConsoleTitle) - 1] = '\0';
		SetConsoleTitle(ConsoleTitle);
	}

#ifdef _CRTDBG_MAP_ALLOC
		/* ask the runtime to dump memory leaks at exit */
		_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
			       | _CRTDBG_LEAK_CHECK_DF		/* report on leaks at exit */
			       | _CRTDBG_CHECK_ALWAYS_DF	/* Check heap every alloc/dealloc */
#ifdef MALLOC_LINT
			       | _CRTDBG_DELAY_FREE_MEM_DF	/* Don't actually free memory */
#endif
			       );
#ifdef DOES_NOT_WORK
			/*
			 * hart: I haven't seen this work, running ntpd.exe -n from a shell
			 * to both a file and the debugger output window.  Docs indicate it
			 * should cause leak report to go to stderr, but it's only seen if
			 * ntpd runs under a debugger (in the debugger's output), even with
			 * this block of code enabled.
			 */
			_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
			_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
#endif
#endif /* using MS debug C runtime heap, _CRTDBG_MAP_ALLOC */

	atexit( ntservice_exit );
}


/*
 * Routine to check if the service is stopping
 * because the computer is shutting down
 */
BOOL
ntservice_systemisshuttingdown() {
	return computer_shutting_down;
}

void
ntservice_exit( void )
{
	uninit_io_completion_port();
	Sleep( 200 );  	//##++ 

	reset_winnt_time();

	msyslog(LOG_INFO, "ntservice: The Network Time Protocol Service is stopping.");

	if (!foreground) {
		/* service mode, need to have the service_main routine
		 * register with the service control manager that the 
		 * service has stopped running, before exiting
		 */
		UpdateSCM(SERVICE_STOPPED);
	}
}

/* 
 * ServiceControl(): Handles requests from the SCM and passes them on
 * to the service.
 */
void WINAPI
ServiceControl(
	DWORD dwCtrlCode
	) 
{
	switch (dwCtrlCode) {

	case SERVICE_CONTROL_SHUTDOWN:
		computer_shutting_down = TRUE;
		/* fall through to stop case */

	case SERVICE_CONTROL_STOP:
		if (WaitableExitEventHandle != NULL) {
			SetEvent(WaitableExitEventHandle);
			UpdateSCM(SERVICE_STOP_PENDING);
			Sleep(100);  //##++
		}
		return;

	case SERVICE_CONTROL_PAUSE:
	case SERVICE_CONTROL_CONTINUE:
	case SERVICE_CONTROL_INTERROGATE:
	default:
		break;
	}
	UpdateSCM(SERVICE_RUNNING);
}

/*
 * Tell the Service Control Manager the state of the service.
 */
void UpdateSCM(DWORD state) {
	SERVICE_STATUS ss;
	static DWORD dwState = SERVICE_STOPPED;

	if (hServiceStatus) {
		if (state)
			dwState = state;

		ZERO(ss);
		ss.dwServiceType |= SERVICE_WIN32_OWN_PROCESS;
		ss.dwCurrentState = dwState;
		ss.dwControlsAccepted = SERVICE_ACCEPT_STOP |
					SERVICE_ACCEPT_SHUTDOWN;
		ss.dwCheckPoint = 0;
		ss.dwServiceSpecificExitCode = 0;
		ss.dwWin32ExitCode = NO_ERROR;
		ss.dwWaitHint = dwState == SERVICE_STOP_PENDING ? 5000 : 1000;

		SetServiceStatus(hServiceStatus, &ss);
	}
}

BOOL WINAPI 
OnConsoleEvent(  
	DWORD dwCtrlType
	)
{
	switch (dwCtrlType) {
#ifdef DEBUG
		case CTRL_BREAK_EVENT:
			if (debug > 0) {
				debug <<= 1;
			}
			else {
				debug = 1;
			}
			if (debug > 8) {
				debug = 0;
			}
			msyslog(LOG_DEBUG, "debug level %d", debug);
			break;
#else
		case CTRL_BREAK_EVENT:
			break;
#endif

		case CTRL_C_EVENT:
		case CTRL_CLOSE_EVENT:
		case CTRL_SHUTDOWN_EVENT:
			if (WaitableExitEventHandle != NULL) {
				SetEvent(WaitableExitEventHandle);
				Sleep(100);  //##++
			}
			break;

		default :
			/* pass to next handler */
			return FALSE; 
	}

	/* we've handled it, no more handlers should be called */
	return TRUE;
}