dhcpd.c 35.7 KB
Newer Older
Ted Lemon's avatar
Ted Lemon committed
1
2
3
4
5
/* dhcpd.c

   DHCP Server Daemon. */

/*
6
 * Copyright (c) 2004-2007 by Internet Systems Consortium, Inc. ("ISC")
7
 * Copyright (c) 1996-2003 by Internet Software Consortium
Ted Lemon's avatar
Ted Lemon committed
8
 *
9
10
11
 * 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.
Ted Lemon's avatar
Ted Lemon committed
12
 *
13
14
15
16
17
18
19
 * 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.
Ted Lemon's avatar
Ted Lemon committed
20
 *
21
22
23
24
25
 *   Internet Systems Consortium, Inc.
 *   950 Charter Street
 *   Redwood City, CA 94063
 *   <info@isc.org>
 *   http://www.isc.org/
Ted Lemon's avatar
Ted Lemon committed
26
 *
27
 * This software has been written for Internet Systems Consortium
Ted Lemon's avatar
Ted Lemon committed
28
 * by Ted Lemon in cooperation with Vixie Enterprises and Nominum, Inc.
29
 * To learn more about Internet Systems Consortium, see
Ted Lemon's avatar
Ted Lemon committed
30
31
32
 * ``http://www.isc.org/''.  To learn more about Vixie Enterprises,
 * see ``http://www.vix.com''.   To learn more about Nominum, Inc., see
 * ``http://www.nominum.com''.
Ted Lemon's avatar
Ted Lemon committed
33
34
 */

35
static char copyright[] =
David Hankins's avatar
David Hankins committed
36
"Copyright 2004-2007 Internet Systems Consortium.";
37
static char arr [] = "All rights reserved.";
38
39
static char message [] = "Internet Systems Consortium DHCP Server";
static char url [] = "For info, please visit http://www.isc.org/sw/dhcp/";
Ted Lemon's avatar
Ted Lemon committed
40
41

#include "dhcpd.h"
42
#include <omapip/omapip_p.h>
43
#include <syslog.h>
44
#include <errno.h>
Shane Kerr's avatar
Shane Kerr committed
45
#include <limits.h>
46
47
#include <sys/types.h>
#include <signal.h>
Ted Lemon's avatar
Ted Lemon committed
48

49
static void usage(void);
Ted Lemon's avatar
Ted Lemon committed
50

51
52
53
struct iaddr server_identifier;
int server_identifier_matched;

54
#if defined (NSUPDATE)
55
56
57
58

/* This stuff is always executed to figure the default values for certain
   ddns variables. */

Ted Lemon's avatar
Ted Lemon committed
59
char std_nsupdate [] = "						    \n\
60
61
option server.ddns-hostname =						    \n\
  pick (option fqdn.hostname, option host-name);			    \n\
62
option server.ddns-domainname =	config-option domain-name;		    \n\
63
option server.ddns-ttl = encode-int(lease-time / 2, 32);		    \n\
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
option server.ddns-rev-domainname = \"in-addr.arpa.\";";

/* This is the old-style name service updater that is executed
   whenever a lease is committed.  It does not follow the DHCP-DNS
   draft at all. */

char old_nsupdate [] = "						    \n\
on commit {								    \n\
  if (not static and							    \n\
      ((config-option server.ddns-updates = null) or			    \n\
       (config-option server.ddns-updates != 0))) {			    \n\
    set new-ddns-fwd-name =						    \n\
      concat (pick (config-option server.ddns-hostname,			    \n\
		    option host-name), \".\",				    \n\
	      pick (config-option server.ddns-domainname,		    \n\
		    config-option domain-name));			    \n\
    if (defined (ddns-fwd-name) and ddns-fwd-name != new-ddns-fwd-name) {   \n\
      switch (ns-update (delete (IN, A, ddns-fwd-name, leased-address))) {  \n\
      case NOERROR:							    \n\
	unset ddns-fwd-name;						    \n\
	on expiry or release {						    \n\
	}								    \n\
      }									    \n\
    }									    \n\
									    \n\
    if (not defined (ddns-fwd-name)) {					    \n\
      set ddns-fwd-name = new-ddns-fwd-name;				    \n\
      if defined (ddns-fwd-name) {					    \n\
	switch (ns-update (not exists (IN, A, ddns-fwd-name, null),	    \n\
			   add (IN, A, ddns-fwd-name, leased-address,	    \n\
				lease-time / 2))) {			    \n\
	default:							    \n\
	  unset ddns-fwd-name;						    \n\
	  break;							    \n\
									    \n\
	case NOERROR:							    \n\
	  set ddns-rev-name =						    \n\
	    concat (binary-to-ascii (10, 8, \".\",			    \n\
				     reverse (1,			    \n\
					      leased-address)), \".\",	    \n\
		    pick (config-option server.ddns-rev-domainname,	    \n\
			  \"in-addr.arpa.\"));				    \n\
	  switch (ns-update (delete (IN, PTR, ddns-rev-name, null),	    \n\
			     add (IN, PTR, ddns-rev-name, ddns-fwd-name,    \n\
				  lease-time / 2)))			    \n\
	    {								    \n\
	    default:							    \n\
	      unset ddns-rev-name;					    \n\
	      on release or expiry {					    \n\
		switch (ns-update (delete (IN, A, ddns-fwd-name,	    \n\
					   leased-address))) {		    \n\
		case NOERROR:						    \n\
		  unset ddns-fwd-name;					    \n\
		  break;						    \n\
		}							    \n\
		on release or expiry;					    \n\
	      }								    \n\
	      break;							    \n\
									    \n\
	    case NOERROR:						    \n\
	      on release or expiry {					    \n\
		switch (ns-update (delete (IN, PTR, ddns-rev-name, null))) {\n\
		case NOERROR:						    \n\
		  unset ddns-rev-name;					    \n\
		  break;						    \n\
		}							    \n\
		switch (ns-update (delete (IN, A, ddns-fwd-name,	    \n\
					   leased-address))) {		    \n\
		case NOERROR:						    \n\
		  unset ddns-fwd-name;					    \n\
		  break;						    \n\
		}							    \n\
		on release or expiry;					    \n\
	      }								    \n\
	    }								    \n\
	}								    \n\
      }									    \n\
    }									    \n\
    unset new-ddns-fwd-name;						    \n\
  }									    \n\
}";

int ddns_update_style;
147
#endif /* NSUPDATE */
Ted Lemon's avatar
Ted Lemon committed
148

149
150
151
const char *path_dhcpd_conf = _PATH_DHCPD_CONF;
const char *path_dhcpd_db = _PATH_DHCPD_DB;
const char *path_dhcpd_pid = _PATH_DHCPD_PID;
Ted Lemon's avatar
Ted Lemon committed
152

153
154
int dhcp_max_agent_option_packet_length = DHCP_MTU_MAX;

155
static omapi_auth_key_t *omapi_key = (omapi_auth_key_t *)0;
156
157
158
159
160
int omapi_port;

#if defined (TRACING)
trace_type_t *trace_srandom;
#endif
161
162
163
164
165
166
167
168
169
170
171

static isc_result_t verify_addr (omapi_object_t *l, omapi_addr_t *addr) {
	return ISC_R_SUCCESS;
}

static isc_result_t verify_auth (omapi_object_t *p, omapi_auth_key_t *a) {
	if (a != omapi_key)
		return ISC_R_INVALIDKEY;
	return ISC_R_SUCCESS;
}

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
static void omapi_listener_start (void *foo)
{
	omapi_object_t *listener;
	isc_result_t result;

	listener = (omapi_object_t *)0;
	result = omapi_generic_new (&listener, MDL);
	if (result != ISC_R_SUCCESS)
		log_fatal ("Can't allocate new generic object: %s",
			   isc_result_totext (result));
	result = omapi_protocol_listen (listener,
					(unsigned)omapi_port, 1);
	if (result == ISC_R_SUCCESS && omapi_key)
		result = omapi_protocol_configure_security
			(listener, verify_addr, verify_auth);
	if (result != ISC_R_SUCCESS) {
		log_error ("Can't start OMAPI protocol: %s",
			   isc_result_totext (result));
		add_timeout (cur_time + 5, omapi_listener_start, 0, 0, 0);
	}
	omapi_object_dereference (&listener, MDL);
}

David Hankins's avatar
David Hankins committed
195
196
197
#ifndef UNIT_TEST
int 
main(int argc, char **argv) {
198
	int fd;
199
	int i, status;
Ted Lemon's avatar
Ted Lemon committed
200
	struct servent *ent;
201
	char *s;
Ted Lemon's avatar
Ted Lemon committed
202
	int cftest = 0;
Ted Lemon's avatar
Ted Lemon committed
203
	int lftest = 0;
204
#ifndef DEBUG
205
	int pidfilewritten = 0;
Ted Lemon's avatar
Ted Lemon committed
206
	int pid;
207
208
	char pbuf [20];
	int daemon = 1;
209
#endif
210
	int quiet = 0;
211
	char *server = (char *)0;
212
	isc_result_t result;
213
	unsigned seed;
214
	struct interface_info *ip;
Ted Lemon's avatar
Ted Lemon committed
215
216
	struct parse *parse;
	int lose;
217
218
219
	int no_dhcpd_conf = 0;
	int no_dhcpd_db = 0;
	int no_dhcpd_pid = 0;
David Hankins's avatar
David Hankins committed
220
	int local_family_set = 0;
Ted Lemon's avatar
Ted Lemon committed
221
#if defined (TRACING)
222
223
	char *traceinfile = (char *)0;
	char *traceoutfile = (char *)0;
Ted Lemon's avatar
Ted Lemon committed
224
#endif
Ted Lemon's avatar
Ted Lemon committed
225

226
227
228
        /* Make sure that file descriptors 0 (stdin), 1, (stdout), and
           2 (stderr) are open. To do this, we assume that when we
           open a file the lowest available file decriptor is used. */
229
        fd = open("/dev/null", O_RDWR);
230
        if (fd == 0)
231
                fd = open("/dev/null", O_RDWR);
232
        if (fd == 1)
233
                fd = open("/dev/null", O_RDWR);
234
235
236
        if (fd == 2)
                log_perror = 0; /* No sense logging to /dev/null. */
        else if (fd != -1)
237
                close(fd);
238

239
240
241
242
243
244
245
246
247
	/* Set up the client classification system. */
	classification_setup ();

	/* Initialize the omapi system. */
	result = omapi_init ();
	if (result != ISC_R_SUCCESS)
		log_fatal ("Can't initialize OMAPI: %s",
			   isc_result_totext (result));

248
249
	/* Set up the OMAPI wrappers for common objects. */
	dhcp_db_objects_setup ();
250
251
252
253
	/* Set up the OMAPI wrappers for various server database internal
	   objects. */
	dhcp_common_objects_setup ();

254
	/* Initially, log errors to stderr as well as to syslogd. */
255
	openlog ("dhcpd", LOG_NDELAY, DHCPD_LOG_FACILITY);
256

Ted Lemon's avatar
Ted Lemon committed
257
258
259
260
	for (i = 1; i < argc; i++) {
		if (!strcmp (argv [i], "-p")) {
			if (++i == argc)
				usage ();
261
			for (s = argv [i]; *s; s++)
262
				if (!isdigit ((unsigned char)*s))
263
					log_fatal ("%s: not a valid UDP port",
264
					       argv [i]);
265
266
			status = atoi (argv [i]);
			if (status < 1 || status > 65535)
267
				log_fatal ("%s: not a valid UDP port",
268
				       argv [i]);
269
			local_port = htons (status);
270
			log_debug ("binding to user-specified port %d",
271
			       ntohs (local_port));
272
273
274
275
276
		} else if (!strcmp (argv [i], "-f")) {
#ifndef DEBUG
			daemon = 0;
#endif
		} else if (!strcmp (argv [i], "-d")) {
Ted Lemon's avatar
Ted Lemon committed
277
#ifndef DEBUG
278
			daemon = 0;
Ted Lemon's avatar
Ted Lemon committed
279
#endif
Ted Lemon's avatar
Ted Lemon committed
280
			log_perror = -1;
281
282
283
284
		} else if (!strcmp (argv [i], "-s")) {
			if (++i == argc)
				usage ();
			server = argv [i];
285
286
287
288
		} else if (!strcmp (argv [i], "-cf")) {
			if (++i == argc)
				usage ();
			path_dhcpd_conf = argv [i];
289
			no_dhcpd_conf = 1;
290
291
292
293
		} else if (!strcmp (argv [i], "-lf")) {
			if (++i == argc)
				usage ();
			path_dhcpd_db = argv [i];
294
			no_dhcpd_db = 1;
295
296
297
298
		} else if (!strcmp (argv [i], "-pf")) {
			if (++i == argc)
				usage ();
			path_dhcpd_pid = argv [i];
299
			no_dhcpd_pid = 1;
300
301
302
303
304
305
306
                } else if (!strcmp (argv [i], "-t")) {
			/* test configurations only */
#ifndef DEBUG
			daemon = 0;
#endif
			cftest = 1;
			log_perror = -1;
Ted Lemon's avatar
Ted Lemon committed
307
308
309
310
311
312
313
314
                } else if (!strcmp (argv [i], "-T")) {
			/* test configurations and lease file only */
#ifndef DEBUG
			daemon = 0;
#endif
			cftest = 1;
			lftest = 1;
			log_perror = -1;
315
		} else if (!strcmp (argv [i], "-q")) {
316
317
			quiet = 1;
			quiet_interface_discovery = 1;
David Hankins's avatar
David Hankins committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
		} else if (!strcmp(argv[i], "-4")) {
			if (local_family_set && (local_family != AF_INET)) {
				log_fatal("Server cannot run in both IPv4 and "
					  "IPv6 mode at the same time.");
			}
			local_family = AF_INET;
			local_family_set = 1;
		} else if (!strcmp(argv[i], "-6")) {
			if (local_family_set && (local_family != AF_INET6)) {
				log_fatal("Server cannot run in both IPv4 and "
					  "IPv6 mode at the same time.");
			}
			local_family = AF_INET6;
			local_family_set = 1;
332
		} else if (!strcmp (argv [i], "--version")) {
333
			log_info("isc-dhcpd-%s", PACKAGE_VERSION);
334
			exit (0);
Ted Lemon's avatar
Ted Lemon committed
335
#if defined (TRACING)
336
337
338
339
340
341
342
343
344
		} else if (!strcmp (argv [i], "-tf")) {
			if (++i == argc)
				usage ();
			traceoutfile = argv [i];
		} else if (!strcmp (argv [i], "-play")) {
			if (++i == argc)
				usage ();
			traceinfile = argv [i];
			trace_replay_init ();
Ted Lemon's avatar
Ted Lemon committed
345
#endif /* TRACING */
346
		} else if (argv [i][0] == '-') {
Ted Lemon's avatar
Ted Lemon committed
347
			usage ();
348
349
		} else {
			struct interface_info *tmp =
350
351
352
353
354
355
				(struct interface_info *)0;
			result = interface_allocate (&tmp, MDL);
			if (result != ISC_R_SUCCESS)
				log_fatal ("Insufficient memory to %s %s: %s",
					   "record interface", argv [i],
					   isc_result_totext (result));
356
			strcpy (tmp -> name, argv [i]);
357
358
359
360
361
362
			if (interfaces) {
				interface_reference (&tmp -> next,
						     interfaces, MDL);
				interface_dereference (&interfaces, MDL);
			}
			interface_reference (&interfaces, tmp, MDL);
363
364
			tmp -> flags = INTERFACE_REQUESTED;
		}
Ted Lemon's avatar
Ted Lemon committed
365
366
	}

367
368
369
370
371
372
373
374
375
376
	if (!no_dhcpd_conf && (s = getenv ("PATH_DHCPD_CONF"))) {
		path_dhcpd_conf = s;
	}
	if (!no_dhcpd_db && (s = getenv ("PATH_DHCPD_DB"))) {
		path_dhcpd_db = s;
	}
	if (!no_dhcpd_pid && (s = getenv ("PATH_DHCPD_PID"))) {
		path_dhcpd_pid = s;
	}

377
378
379
380
381
382
383
384
385
386
387
388
389
        /*
         * convert relative path names to absolute, for files that need
         * to be reopened after chdir() has been called
         */
        if (path_dhcpd_db[0] != '/') {
                char *path = dmalloc(PATH_MAX, MDL);
                if (path == NULL)
                        log_fatal("No memory for filename\n");
                path_dhcpd_db = realpath(path_dhcpd_db,  path);
                if (path_dhcpd_db == NULL)
                        log_fatal("%s: %s", path, strerror(errno));
        }

390
	if (!quiet) {
391
		log_info("%s %s", message, PACKAGE_VERSION);
392
393
394
		log_info (copyright);
		log_info (arr);
		log_info (url);
Ted Lemon's avatar
Ted Lemon committed
395
	} else {
396
		quiet = 0;
Ted Lemon's avatar
Ted Lemon committed
397
398
		log_perror = 0;
	}
399

400
401
#if defined (TRACING)
	trace_init (set_time, MDL);
402
403
404
405
406
407
	if (traceoutfile) {
		result = trace_begin (traceoutfile, MDL);
		if (result != ISC_R_SUCCESS)
			log_fatal ("Unable to begin trace: %s",
				isc_result_totext (result));
	}
408
409
410
411
412
413
414
	interface_trace_setup ();
	parse_trace_setup ();
	trace_srandom = trace_type_register ("random-seed", (void *)0,
					     trace_seed_input,
					     trace_seed_stop, MDL);
#endif

Ted Lemon's avatar
Ted Lemon committed
415
	/* Default to the DHCP/BOOTP port. */
416
	if (!local_port)
Ted Lemon's avatar
Ted Lemon committed
417
	{
418
419
420
421
422
		if ((s = getenv ("DHCPD_PORT"))) {
			local_port = htons (atoi (s));
			log_debug ("binding to environment-specified port %d",
				   ntohs (local_port));
		} else {
David Hankins's avatar
David Hankins committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
			if (local_family == AF_INET) {
				ent = getservbyname("dhcp", "udp");
				if (ent == NULL) {
					local_port = htons(67);
				} else {
					local_port = ent->s_port;
				}
			} else {
				/* INSIST(local_family == AF_INET6); */
				ent = getservbyname("dhcpv6-server", "udp");
				if (ent == NULL) {
					local_port = htons(547);
				} else {
					local_port = ent->s_port;
				}
			}
439
#ifndef __CYGWIN32__ /* XXX */
440
			endservent ();
441
#endif
442
		}
Ted Lemon's avatar
Ted Lemon committed
443
444
	}
  
David Hankins's avatar
David Hankins committed
445
446
447
448
449
450
451
452
453
454
455
  	if (local_family == AF_INET) {
		remote_port = htons(ntohs(local_port) + 1);
	} else {
		/* INSIST(local_family == AF_INET6); */
		ent = getservbyname("dhcpv6-client", "udp");
		if (ent == NULL) {
			remote_port = htons(546);
		} else {
			remote_port = ent->s_port;
		}
	}
456

457
	if (server) {
458
459
460
461
		if (local_family != AF_INET) {
			log_fatal("You can only specify address to send "
			          "replies to when running an IPv4 server.");
		}
462
463
464
465
466
467
468
469
470
471
472
473
474
475
		if (!inet_aton (server, &limited_broadcast)) {
			struct hostent *he;
			he = gethostbyname (server);
			if (he) {
				memcpy (&limited_broadcast,
					he -> h_addr_list [0],
					sizeof limited_broadcast);
			} else
				limited_broadcast.s_addr = INADDR_BROADCAST;
		}
	} else {
		limited_broadcast.s_addr = INADDR_BROADCAST;
	}

Ted Lemon's avatar
Ted Lemon committed
476
	/* Get the current time... */
477
	time(&cur_time);
Ted Lemon's avatar
Ted Lemon committed
478

Ted Lemon's avatar
Ted Lemon committed
479
480
481
482
	/* Set up the initial dhcp option universe. */
	initialize_common_option_spaces ();
	initialize_server_option_spaces ();

483
484
	/* Add the ddns update style enumeration prior to parsing. */
	add_enumeration (&ddns_styles);
Ted Lemon's avatar
Ted Lemon committed
485
	add_enumeration (&syslog_enum);
486

487
488
489
	if (!group_allocate (&root_group, MDL))
		log_fatal ("Can't allocate root group!");
	root_group -> authoritative = 0;
Ted Lemon's avatar
Ted Lemon committed
490

491
492
493
	/* Set up various hooks. */
	dhcp_interface_setup_hook = dhcpd_interface_setup_hook;
	bootp_packet_handler = do_packet;
494
#ifdef DHCPv6
David Hankins's avatar
David Hankins committed
495
	dhcpv6_packet_handler = do_packet6;
496
#endif /* DHCPv6 */
497

498
#if defined (NSUPDATE)
Ted Lemon's avatar
Ted Lemon committed
499
500
501
502
	/* Set up the standard name service updater routine. */
	parse = (struct parse *)0;
	status = new_parse (&parse, -1,
			    std_nsupdate, (sizeof std_nsupdate) - 1,
503
			    "standard name service update routine", 0);
Ted Lemon's avatar
Ted Lemon committed
504
	if (status != ISC_R_SUCCESS)
505
		log_fatal ("can't begin parsing name service updater!");
Ted Lemon's avatar
Ted Lemon committed
506

507
	lose = 0;
Ted Lemon's avatar
Ted Lemon committed
508
	if (!(parse_executable_statements
509
	      (&root_group -> statements, parse, &lose, context_any))) {
Ted Lemon's avatar
Ted Lemon committed
510
511
512
513
		end_parse (&parse);
		log_fatal ("can't parse standard name service updater!");
	}
	end_parse (&parse);
514
#endif
Ted Lemon's avatar
Ted Lemon committed
515

516
	/* Initialize icmp support... */
517
518
	if (!cftest && !lftest)
		icmp_startup (1, lease_pinged);
519
520
521
522
523
524
525
526
527
528

#if defined (TRACING)
	if (traceinfile) {
	    if (!no_dhcpd_db) {
		    log_error ("%s", "");
		    log_error ("** You must specify a lease file with -lf.");
		    log_error ("   Dhcpd will not overwrite your default");
		    log_fatal ("   lease file when playing back a trace. **");
	    }		
	    trace_file_replay (traceinfile);
529

530
#if defined (DEBUG_MEMORY_LEAKAGE) && \
531
532
533
534
535
                defined (DEBUG_MEMORY_LEAKAGE_ON_EXIT)
            free_everything ();
            omapi_print_dmalloc_usage_by_caller (); 
#endif

536
537
538
539
	    exit (0);
	}
#endif

David Hankins's avatar
David Hankins committed
540
541
542
543
544
545
546
#ifdef DHCPv6
	/* set up DHCPv6 hash */
	if (!ia_na_new_hash(&ia_active, DEFAULT_HASH_SIZE, MDL)) {
		log_fatal("Out of memory creating hash for active IA.");
	}
#endif /* DHCPv6 */

Ted Lemon's avatar
Ted Lemon committed
547
	/* Read the dhcpd.conf file... */
Ted Lemon's avatar
Ted Lemon committed
548
	if (readconf () != ISC_R_SUCCESS)
549
		log_fatal ("Configuration file errors encountered -- exiting");
Ted Lemon's avatar
Ted Lemon committed
550

551
552
	postconf_initialization (quiet);

553
        /* test option should cause an early exit */
Ted Lemon's avatar
Ted Lemon committed
554
 	if (cftest && !lftest) 
555
556
 		exit(0);

557
558
559
560
561
562
563
564
565
	group_write_hook = group_writer;

	/* Start up the database... */
	db_startup (lftest);

	if (lftest)
		exit (0);

	/* Discover all the network interfaces and initialize them. */
David Hankins's avatar
David Hankins committed
566
567
568
569
570
571
	discover_interfaces(DISCOVER_SERVER);

#ifdef DHCPv6
	/*
	 * Remove addresses from our pools that we should not issue
	 * to clients.
572
573
574
575
576
	 *
	 * We currently have no support for this in IPv4. It is not 
	 * as important in IPv4, as making pools with ranges that 
	 * leave out interfaces and hosts is fairly straightforward
	 * using range notation, but not so handy with CIDR notation.
David Hankins's avatar
David Hankins committed
577
	 */
578
579
580
581
	if (local_family == AF_INET6) {
		mark_hosts_unavailable();
		mark_interfaces_unavailable();
	}
David Hankins's avatar
David Hankins committed
582
583
#endif /* DHCPv6 */

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601

	/* Make up a seed for the random number generator from current
	   time plus the sum of the last four bytes of each
	   interface's hardware address interpreted as an integer.
	   Not much entropy, but we're booting, so we're not likely to
	   find anything better. */
	seed = 0;
	for (ip = interfaces; ip; ip = ip -> next) {
		int junk;
		memcpy (&junk,
			&ip -> hw_address.hbuf [ip -> hw_address.hlen -
					       sizeof seed], sizeof seed);
		seed += junk;
	}
	srandom (seed + cur_time);
#if defined (TRACING)
	trace_seed_stash (trace_srandom, seed + cur_time);
#endif
602
	postdb_startup ();
603

604
#ifdef DHCPv6
David Hankins's avatar
David Hankins committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
	/*
	 * Set server DHCPv6 identifier.
	 * See dhcpv6.c for discussion of setting DUID.
	 */
	if (set_server_duid_from_option() == ISC_R_SUCCESS) {
		write_server_duid();
	} else {
		if (!server_duid_isset()) {
			if (generate_new_server_duid() != ISC_R_SUCCESS) {
				log_fatal("Unable to set server identifier.");
			}
			write_server_duid();
		}
	}
619
#endif /* DHCPv6 */
David Hankins's avatar
David Hankins committed
620

621
622
623
624
625
626
627
628
629
630
631
632
633
#ifndef DEBUG
	if (daemon) {
		/* First part of becoming a daemon... */
		if ((pid = fork ()) < 0)
			log_fatal ("Can't fork daemon: %m");
		else if (pid)
			exit (0);
	}

	/* Read previous pid file. */
	if ((i = open (path_dhcpd_pid, O_RDONLY)) >= 0) {
		status = read (i, pbuf, (sizeof pbuf) - 1);
		close (i);
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
		if (status > 0) {
			pbuf [status] = 0;
			pid = atoi (pbuf);

			/* If the previous server process is not still running,
			   write a new pid file immediately. */
			if (pid && (pid == getpid() || kill (pid, 0) < 0)) {
				unlink (path_dhcpd_pid);
				if ((i = open (path_dhcpd_pid,
					O_WRONLY | O_CREAT, 0644)) >= 0) {
				    sprintf (pbuf, "%d\n", (int)getpid ());
				    write (i, pbuf, strlen (pbuf));
				    close (i);
				    pidfilewritten = 1;
				}
			} else
				log_fatal ("There's already a DHCP server running.");
		}
652
653
654
655
656
657
658
659
660
	}

	/* If we were requested to log to stdout on the command line,
	   keep doing so; otherwise, stop. */
	if (log_perror == -1)
		log_perror = 1;
	else
		log_perror = 0;

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
	/* If we didn't write the pid file earlier because we found a
	   process running the logged pid, but we made it to here,
	   meaning nothing is listening on the bootp port, then write
	   the pid file out - what's in it now is bogus anyway. */
	if (!pidfilewritten) {
		unlink (path_dhcpd_pid);
		if ((i = open (path_dhcpd_pid,
			       O_WRONLY | O_CREAT, 0644)) >= 0) {
			sprintf (pbuf, "%d\n", (int)getpid ());
			write (i, pbuf, strlen (pbuf));
			close (i);
			pidfilewritten = 1;
		}
	}

676
677
	if (daemon) {
		/* Become session leader and get pid... */
678
		pid = setsid();
679
680

                /* Close standard I/O descriptors. */
681
682
683
                close(0);
                close(1);
                close(2);
684
685

                /* Reopen them on /dev/null. */
686
687
688
                open("/dev/null", O_RDWR);
                open("/dev/null", O_RDWR);
                open("/dev/null", O_RDWR);
689
                log_perror = 0; /* No sense logging to /dev/null. */
690

691
                chdir("/");
692
693
694
	}
#endif /* !DEBUG */

695
696
#if defined (DEBUG_MEMORY_LEAKAGE) || defined (DEBUG_MALLOC_POOL) || \
		defined (DEBUG_MEMORY_LEAKAGE_ON_EXIT)
697
698
699
700
701
702
703
704
705
	dmalloc_cutoff_generation = dmalloc_generation;
	dmalloc_longterm = dmalloc_outstanding;
	dmalloc_outstanding = 0;
#endif

#if defined (DEBUG_RC_HISTORY_EXHAUSTIVELY)
	dump_rc_history ();
#endif

706
707
708
	omapi_set_int_value ((omapi_object_t *)dhcp_control_object,
			     (omapi_object_t *)0, "state", server_running);

709
710
711
712
713
714
	/* Receive packets and dispatch them... */
	dispatch ();

	/* Not reached */
	return 0;
}
David Hankins's avatar
David Hankins committed
715
#endif /* !UNIT_TEST */
716
717
718
719
720
721
722
723
724
725
726

void postconf_initialization (int quiet)
{
	struct option_state *options = (struct option_state *)0;
	struct data_string db;
	struct option_cache *oc;
	char *s;
	isc_result_t result;
	struct parse *parse;
	int tmp;

727
	/* Now try to get the lease file name. */
728
	option_state_allocate (&options, MDL);
729

730
731
	execute_statements_in_scope ((struct binding_value **)0,
				     (struct packet *)0,
732
				     (struct lease *)0,
733
				     (struct client_state *)0,
734
				     (struct option_state *)0,
735
				     options, &global_scope,
736
				     root_group,
737
				     (struct group *)0);
738
	memset (&db, 0, sizeof db);
739
740
	oc = lookup_option (&server_universe, options, SV_LEASE_FILE_NAME);
	if (oc &&
741
	    evaluate_option_cache (&db, (struct packet *)0,
742
743
				   (struct lease *)0, (struct client_state *)0,
				   options, (struct option_state *)0,
744
				   &global_scope, oc, MDL)) {
745
		s = dmalloc (db.len + 1, MDL);
746
747
		if (!s)
			log_fatal ("no memory for lease db filename.");
748
749
750
		memcpy (s, db.data, db.len);
		s [db.len] = 0;
		data_string_forget (&db, MDL);
751
752
753
754
755
		path_dhcpd_db = s;
	}
	
	oc = lookup_option (&server_universe, options, SV_PID_FILE_NAME);
	if (oc &&
756
	    evaluate_option_cache (&db, (struct packet *)0,
757
758
				   (struct lease *)0, (struct client_state *)0,
				   options, (struct option_state *)0,
759
				   &global_scope, oc, MDL)) {
760
		s = dmalloc (db.len + 1, MDL);
761
762
		if (!s)
			log_fatal ("no memory for lease db filename.");
763
764
765
		memcpy (s, db.data, db.len);
		s [db.len] = 0;
		data_string_forget (&db, MDL);
766
767
768
		path_dhcpd_pid = s;
	}

769
	omapi_port = -1;
770
771
772
	oc = lookup_option (&server_universe, options, SV_OMAPI_PORT);
	if (oc &&
	    evaluate_option_cache (&db, (struct packet *)0,
773
774
				   (struct lease *)0, (struct client_state *)0,
				   options, (struct option_state *)0,
775
776
777
778
779
780
781
782
				   &global_scope, oc, MDL)) {
		if (db.len == 2) {
			omapi_port = getUShort (db.data);
		} else
			log_fatal ("invalid omapi port data length");
		data_string_forget (&db, MDL);
	}

783
784
785
	oc = lookup_option (&server_universe, options, SV_OMAPI_KEY);
	if (oc &&
	    evaluate_option_cache (&db, (struct packet *)0,
786
787
				   (struct lease *)0, (struct client_state *)0,
				   options,
788
789
790
791
792
793
794
795
796
797
798
				   (struct option_state *)0,
				   &global_scope, oc, MDL)) {
		s = dmalloc (db.len + 1, MDL);
		if (!s)
			log_fatal ("no memory for OMAPI key filename.");
		memcpy (s, db.data, db.len);
		s [db.len] = 0;
		data_string_forget (&db, MDL);
		result = omapi_auth_key_lookup_name (&omapi_key, s);
		dfree (s, MDL);
		if (result != ISC_R_SUCCESS)
799
800
			log_fatal ("OMAPI key %s: %s",
				   s, isc_result_totext (result));
801
802
	}

803
804
805
	oc = lookup_option (&server_universe, options, SV_LOCAL_PORT);
	if (oc &&
	    evaluate_option_cache (&db, (struct packet *)0,
806
807
				   (struct lease *)0, (struct client_state *)0,
				   options,
808
809
810
811
812
813
814
815
816
817
818
819
				   (struct option_state *)0,
				   &global_scope, oc, MDL)) {
		if (db.len == 2) {
			local_port = htons (getUShort (db.data));
		} else
			log_fatal ("invalid local port data length");
		data_string_forget (&db, MDL);
	}

	oc = lookup_option (&server_universe, options, SV_REMOTE_PORT);
	if (oc &&
	    evaluate_option_cache (&db, (struct packet *)0,
820
821
				   (struct lease *)0, (struct client_state *)0,
				   options, (struct option_state *)0,
822
823
824
825
826
827
828
829
830
831
832
833
				   &global_scope, oc, MDL)) {
		if (db.len == 2) {
			remote_port = htons (getUShort (db.data));
		} else
			log_fatal ("invalid remote port data length");
		data_string_forget (&db, MDL);
	}

	oc = lookup_option (&server_universe, options,
			    SV_LIMITED_BROADCAST_ADDRESS);
	if (oc &&
	    evaluate_option_cache (&db, (struct packet *)0,
834
835
				   (struct lease *)0, (struct client_state *)0,
				   options, (struct option_state *)0,
836
837
838
839
840
841
842
843
844
845
846
847
				   &global_scope, oc, MDL)) {
		if (db.len == 4) {
			memcpy (&limited_broadcast, db.data, 4);
		} else
			log_fatal ("invalid remote port data length");
		data_string_forget (&db, MDL);
	}

	oc = lookup_option (&server_universe, options,
			    SV_LOCAL_ADDRESS);
	if (oc &&
	    evaluate_option_cache (&db, (struct packet *)0,
848
849
				   (struct lease *)0, (struct client_state *)0,
				   options, (struct option_state *)0,
850
851
852
853
854
855
856
857
				   &global_scope, oc, MDL)) {
		if (db.len == 4) {
			memcpy (&local_address, db.data, 4);
		} else
			log_fatal ("invalid remote port data length");
		data_string_forget (&db, MDL);
	}

858
859
860
861
862
863
864
865
866
867
868
869
870
871
	oc = lookup_option (&server_universe, options, SV_DDNS_UPDATE_STYLE);
	if (oc) {
		if (evaluate_option_cache (&db, (struct packet *)0,
					   (struct lease *)0,
					   (struct client_state *)0,
					   options,
					   (struct option_state *)0,
					   &global_scope, oc, MDL)) {
			if (db.len == 1) {
				ddns_update_style = db.data [0];
			} else
				log_fatal ("invalid dns update type");
			data_string_forget (&db, MDL);
		}
872
873
	} else {
		log_info ("%s", "");
874
		log_error ("** You must add a global ddns-update-style %s%s.",
875
876
			   "statement to ", path_dhcpd_conf);
		log_error ("   To get the same behaviour as in 3.0b2pl11 %s",
877
			   "and previous");
878
879
880
881
		log_error ("   versions, add a line that says \"%s\"",
			   "ddns-update-style ad-hoc;");
		log_fatal ("   Please read the dhcpd.conf manual page %s",
			   "for more information. **");
882
	}
883

Ted Lemon's avatar
Ted Lemon committed
884
885
886
887
888
889
890
891
892
893
	oc = lookup_option (&server_universe, options, SV_LOG_FACILITY);
	if (oc) {
		if (evaluate_option_cache (&db, (struct packet *)0,
					   (struct lease *)0,
					   (struct client_state *)0,
					   options,
					   (struct option_state *)0,
					   &global_scope, oc, MDL)) {
			if (db.len == 1) {
				closelog ();
894
				openlog ("dhcpd", LOG_NDELAY, db.data[0]);
895
896
				/* Log the startup banner into the new
				   log file. */
Ted Lemon's avatar
Ted Lemon committed
897
				if (!quiet) {
898
899
900
					/* Don't log to stderr twice. */
					tmp = log_perror;
					log_perror = 0;
901
902
					log_info("%s %s",
						 message, PACKAGE_VERSION);
Ted Lemon's avatar
Ted Lemon committed
903
904
905
					log_info (copyright);
					log_info (arr);
					log_info (url);
906
					log_perror = tmp;
Ted Lemon's avatar
Ted Lemon committed
907
908
909
910
911
912
913
				}
			} else
				log_fatal ("invalid log facility");
			data_string_forget (&db, MDL);
		}
	}

914
	/* Don't need the options anymore. */
915
	option_state_dereference (&options, MDL);
916
	
917
918
919
920
#if defined (NSUPDATE)
	/* If old-style ddns updates have been requested, parse the
	   old-style ddns updater. */
	if (ddns_update_style == 1) {
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
		struct executable_statement **e, *s;

		if (root_group -> statements) {
			s = (struct executable_statement *)0;
			if (!executable_statement_allocate (&s, MDL))
				log_fatal ("no memory for ddns updater");
			executable_statement_reference
				(&s -> next, root_group -> statements, MDL);
			executable_statement_dereference
				(&root_group -> statements, MDL);
			executable_statement_reference
				(&root_group -> statements, s, MDL);
			s -> op = statements_statement;
			e = &s -> data.statements;
			executable_statement_dereference (&s, MDL);
		} else {
			e = &root_group -> statements;
		}

940
941
		/* Set up the standard name service updater routine. */
		parse = (struct parse *)0;
942
943
		result = new_parse (&parse, -1,
				 old_nsupdate, (sizeof old_nsupdate) - 1,
944
				 "old name service update routine", 0);
945
		if (result != ISC_R_SUCCESS)
946
947
			log_fatal ("can't begin parsing old ddns updater!");

948
		tmp = 0;
949
		if (!(parse_executable_statements (e, parse,
950
						   &tmp, context_any))) {
951
952
953
954
955
956
			end_parse (&parse);
			log_fatal ("can't parse standard ddns updater!");
		}
		end_parse (&parse);
	}
#endif
Ted Lemon's avatar
Ted Lemon committed
957
958
}

959
960
961
962
963
964
965
966
967
968
969
void postdb_startup (void)
{
	/* Initialize the omapi listener state. */
	if (omapi_port != -1) {
		omapi_listener_start (0);
	}

#if defined (FAILOVER_PROTOCOL)
	/* Initialize the failover listener state. */
	dhcp_failover_startup ();
#endif
970
971
972
973
974

	/*
	 * Begin our lease timeout background task.
	 */
	schedule_all_ipv6_lease_timeouts();
975
976
}

Ted Lemon's avatar
Ted Lemon committed
977
978
/* Print usage message. */

979
980
static void
usage(void) {
981
	log_info("%s %s", message, PACKAGE_VERSION);
982
983
	log_info(copyright);
	log_info(arr);
984

985
986
	log_fatal("Usage: dhcpd [-p <UDP port #>] [-f] [-d] [-q] [-t|-T]\n"
		  "             [-4|-6] [-cf config-file] [-lf lease-file]\n"
Ted Lemon's avatar
Ted Lemon committed
987
#if defined (TRACING)
988
989
		  "             [-tf trace-output-file]\n"
		  "             [-play trace-input-file]\n"
Ted Lemon's avatar
Ted Lemon committed
990
#endif /* TRACING */
991
		  "             [-pf pid-file] [-s server] [if0 [...ifN]]");
Ted Lemon's avatar
Ted Lemon committed
992
993
}

994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
void lease_pinged (from, packet, length)
	struct iaddr from;
	u_int8_t *packet;
	int length;
{
	struct lease *lp;

	/* Don't try to look up a pinged lease if we aren't trying to
	   ping one - otherwise somebody could easily make us churn by
	   just forging repeated ICMP EchoReply packets for us to look
	   up. */
	if (!outstanding_pings)
		return;

1008
1009
1010
1011
	lp = (struct lease *)0;
	if (!find_lease_by_ip_addr (&lp, from, MDL)) {
		log_debug ("unexpected ICMP Echo Reply from %s",
			   piaddr (from));
1012
1013
1014
1015
		return;
	}

	if (!lp -> state) {
1016
#if defined (FAILOVER_PROTOCOL)
1017
1018
		if (!lp -> pool ||
		    !lp -> pool -> failover_peer)
1019
#endif
1020
1021
			log_debug ("ICMP Echo Reply for %s late or spurious.",
				   piaddr (from));
1022
		goto out;
1023
1024
	}

1025
	if (lp -> ends > cur_time) {
1026
		log_debug ("ICMP Echo reply while lease %s valid.",
1027
			   piaddr (from));
1028
1029
	}

1030
1031
	/* At this point it looks like we pinged a lease and got a
	   response, which shouldn't have happened. */
1032
1033
	data_string_forget (&lp -> state -> parameter_request_list, MDL);
	free_lease_state (lp -> state, MDL);
1034
1035
1036
1037
1038
	lp -> state = (struct lease_state *)0;

	abandon_lease (lp, "pinged before offer");
	cancel_timeout (lease_ping_timeout, lp);
	--outstanding_pings;
1039
1040
      out:
	lease_dereference (&lp, MDL);
1041
1042
1043
1044
1045
1046
1047
}

void lease_ping_timeout (vlp)
	void *vlp;
{
	struct lease *lp = vlp;

Ted Lemon's avatar
Ted Lemon committed
1048
1049
1050
1051
#if defined (DEBUG_MEMORY_LEAKAGE)
	unsigned long previous_outstanding = dmalloc_outstanding;
#endif

1052
1053
	--outstanding_pings;
	dhcp_reply (lp);
Ted Lemon's avatar
Ted Lemon committed
1054
1055
1056
1057
1058
1059
1060

#if defined (DEBUG_MEMORY_LEAKAGE)
	log_info ("generation %ld: %ld new, %ld outstanding, %ld long-term",
		  dmalloc_generation,
		  dmalloc_outstanding - previous_outstanding,
		  dmalloc_outstanding, dmalloc_longterm);
#endif
1061
#if defined (DEBUG_MEMORY_LEAKAGE)
Ted Lemon's avatar
Ted Lemon committed
1062
1063
	dmalloc_dump_outstanding ();
#endif
1064
}
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091

int dhcpd_interface_setup_hook (struct interface_info *ip, struct iaddr *ia)
{
	struct subnet *subnet;
	struct shared_network *share;
	isc_result_t status;

	/* Special case for fallback network - not sure why this is
	   necessary. */
	if (!ia) {
		const char *fnn = "fallback-net";
		status = shared_network_allocate (&ip -> shared_network, MDL);
		if (status != ISC_R_SUCCESS)
			log_fatal ("No memory for shared subnet: %s",
				   isc_result_totext (status));
		ip -> shared_network -> name = dmalloc (strlen (fnn) + 1, MDL);
		strcpy (ip -> shared_network -> name, fnn);
		return 1;
	}

	/* If there's a registered subnet for this address,
	   connect it together... */
	subnet = (struct subnet *)0;
	if (find_subnet (&subnet, *ia, MDL)) {
		/* If this interface has multiple aliases on the same
		   subnet, ignore all but the first we encounter. */
		if (!subnet -> interface) {
1092
			interface_reference (&subnet -> interface, ip, MDL);
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
			subnet -> interface_address = *ia;
		} else if (subnet -> interface != ip) {
			log_error ("Multiple interfaces match the %s: %s %s", 
				   "same subnet",
				   subnet -> interface -> name, ip -> name);
		}
		share = subnet -> shared_network;
		if (ip -> shared_network &&
		    ip -> shared_network != share) {
			log_fatal ("Interface %s matches multiple shared %s",
				   ip -> name, "networks");
		} else {
			if (!ip -> shared_network)
				shared_network_reference
					(&ip -> shared_network, share, MDL);
		}
		
		if (!share -> interface) {
			interface_reference (&share -> interface, ip, MDL);
		} else if (share -> interface != ip) {
			log_error ("Multiple interfaces match the %s: %s %s", 
				   "same shared network",
				   share -> interface -> name, ip -> name);
		}
1117
		subnet_dereference (&subnet, MDL);
1118
1119
1120
	}
	return 1;
}
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
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
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224

static TIME shutdown_time;
static int omapi_connection_count;
enum dhcp_shutdown_state shutdown_state;

isc_result_t dhcp_io_shutdown (omapi_object_t *obj, void *foo)
{
	/* Shut down all listeners. */
	if (shutdown_state == shutdown_listeners &&
	    obj -> type == omapi_type_listener &&
	    obj -> inner &&
	    obj -> inner -> type == omapi_type_protocol_listener) {
		omapi_listener_destroy (obj, MDL);
		return ISC_R_SUCCESS;
	}

	/* Shut down all existing omapi connections. */
	if (obj -> type == omapi_type_connection &&
	    obj -> inner &&
	    obj -> inner -> type == omapi_type_protocol) {
		if (shutdown_state == shutdown_drop_omapi_connections) {
			omapi_disconnect (obj, 1);
		}
		omapi_connection_count++;
		if (shutdown_state == shutdown_omapi_connections) {
			omapi_disconnect (obj, 0);
			return ISC_R_SUCCESS;
		}
	}

	/* Shutdown all DHCP interfaces. */
	if (obj -> type == dhcp_type_interface &&
	    shutdown_state == shutdown_dhcp) {
		dhcp_interface_remove (obj, (omapi_object_t *)0);
		return ISC_R_SUCCESS;
	}
	return ISC_R_SUCCESS;
}

static isc_result_t dhcp_io_shutdown_countdown (void *vlp)
{
	dhcp_failover_state_t *state;
#if defined (FAILOVER_PROTOCOL)
	int failover_connection_count = 0;
#endif

      oncemore:
	if (shutdown_state == shutdown_listeners ||
	    shutdown_state == shutdown_omapi_connections ||
	    shutdown_state == shutdown_drop_omapi_connections ||
	    shutdown_state == shutdown_dhcp) {
		omapi_connection_count = 0;
		omapi_io_state_foreach (dhcp_io_shutdown, 0);
	}

	if ((shutdown_state == shutdown_listeners ||
	     shutdown_state == shutdown_omapi_connections ||
	     shutdown_state == shutdown_drop_omapi_connections) &&
	    omapi_connection_count == 0) {
		shutdown_state = shutdown_dhcp;
		shutdown_time = cur_time;
		goto oncemore;
	} else if (shutdown_state == shutdown_listeners &&
		   cur_time - shutdown_time > 4) {
		shutdown_state = shutdown_omapi_connections;
		shutdown_time = cur_time;
	} else if (shutdown_state == shutdown_omapi_connections &&
		   cur_time - shutdown_time > 4) {
		shutdown_state = shutdown_drop_omapi_connections;
		shutdown_time = cur_time;
	} else if (shutdown_state == shutdown_drop_omapi_connections &&
		   cur_time - shutdown_time > 4) {
		shutdown_state = shutdown_dhcp;
		shutdown_time = cur_time;
		goto oncemore;
	} else if (shutdown_state == shutdown_dhcp &&
		   cur_time - shutdown_time > 4) {
		shutdown_state = shutdown_done;
		shutdown_time = cur_time;
	}

#if defined (FAILOVER_PROTOCOL)
	/* Set all failover peers into the shutdown state. */
	if (shutdown_state == shutdown_dhcp) {
	    for (state = failover_states; state; state = state -> next) {
		if (state -> me.state == normal) {
		    dhcp_failover_set_state (state, shut_down);
		    failover_connection_count++;
		}
		if (state -> me.state == shut_down &&
		    state -> partner.state != partner_down)
			failover_connection_count++;
	    }
	}

	if (shutdown_state == shutdown_done) {
	    for (state = failover_states; state; state = state -> next) {
		if (state -> me.state == shut_down) {
		    if (state -> link_to_peer)
			dhcp_failover_link_dereference (&state -> link_to_peer,
							MDL);
		    dhcp_failover_set_state (state, recover);
		}
	    }
1225
#if defined (DEBUG_MEMORY_LEAKAGE) && \
1226
1227
1228
1229
1230
1231
1232
1233
		defined (DEBUG_MEMORY_LEAKAGE_ON_EXIT)
	    free_everything ();
	    omapi_print_dmalloc_usage_by_caller ();
#endif
	    exit (0);
	}		
#else
	if (shutdown_state == shutdown_done) {
1234
1235
1236
1237
#if defined (DEBUG_MEMORY_LEAKAGE) && \
		defined (DEBUG_MEMORY_LEAKAGE_ON_EXIT)
		free_everything ();
		omapi_print_dmalloc_usage_by_caller (); 
1238
1239
1240
1241
1242
#endif
		exit (0);
	}
#endif
	if (shutdown_state == shutdown_dhcp &&
1243
1244
1245
1246
#if defined(FAILOVER_PROTOCOL)
	    !failover_connection_count &&
#endif
	    ISC_TRUE) {
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
		shutdown_state = shutdown_done;
		shutdown_time = cur_time;
		goto oncemore;
	}
	add_timeout (cur_time + 1,
		     (void (*)(void *))dhcp_io_shutdown_countdown, 0, 0, 0);
	return ISC_R_SUCCESS;
}

isc_result_t dhcp_set_control_state (control_object_state_t oldstate,
				     control_object_state_t newstate)
{
	if (newstate == server_shutdown) {
		shutdown_time = cur_time;
		shutdown_state = shutdown_listeners;
		dhcp_io_shutdown_countdown (0);
		return ISC_R_SUCCESS;
	}
	return ISC_R_INVALIDARG;
}