xref: /titanic_52/usr/src/cmd/cmd-inet/sbin/dhcpagent/agent.c (revision c0c79a3f09914f35651895ffc111883455b7f62d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <locale.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdio_ext.h>
37 #include <dhcp_hostconf.h>
38 #include <dhcpagent_ipc.h>
39 #include <dhcpagent_util.h>
40 #include <dhcpmsg.h>
41 #include <netinet/dhcp.h>
42 #include <net/route.h>
43 #include <sys/sockio.h>
44 
45 #include "async.h"
46 #include "agent.h"
47 #include "script_handler.h"
48 #include "util.h"
49 #include "class_id.h"
50 #include "states.h"
51 #include "packet.h"
52 #include "interface.h"
53 #include "defaults.h"
54 
55 #ifndef	TEXT_DOMAIN
56 #define	TEXT_DOMAIN	"SYS_TEST"
57 #endif
58 
59 iu_timer_id_t		inactivity_id;
60 int			class_id_len = 0;
61 char			*class_id;
62 iu_eh_t			*eh;
63 iu_tq_t			*tq;
64 pid_t			grandparent;
65 int			rtsock_fd;
66 
67 static boolean_t	shutdown_started = B_FALSE;
68 static boolean_t	do_adopt = B_FALSE;
69 static unsigned int	debug_level = 0;
70 static iu_eh_callback_t	accept_event, ipc_event, rtsock_event;
71 
72 /*
73  * The ipc_cmd_allowed[] table indicates which IPC commands are allowed in
74  * which states; a non-zero value indicates the command is permitted.
75  *
76  * START is permitted if the state machine is fresh, or if we are in the
77  * process of trying to obtain a lease (as a convenience to save the
78  * administrator from having to do an explicit DROP).  EXTEND, RELEASE, and
79  * GET_TAG require a lease to be obtained in order to make sense.  INFORM is
80  * permitted if the interface is fresh or has an INFORM in progress or
81  * previously done on it -- otherwise a DROP or RELEASE is first required.
82  * PING and STATUS always make sense and thus are always permitted, as is DROP
83  * in order to permit the administrator to always bail out.
84  */
85 static int ipc_cmd_allowed[DHCP_NSTATES][DHCP_NIPC] = {
86 	/*			  D  E	P  R  S	 S  I  G */
87 	/*			  R  X	I  E  T	 T  N  E */
88 	/*			  O  T	N  L  A	 A  F  T */
89 	/*			  P  E	G  E  R	 T  O  _ */
90 	/*			  .  N  .  A  T  U  R  T */
91 	/*			  .  D	.  S  .  S  M  A */
92 	/*			  .  .  .  E  .  .  .  G */
93 	/* INIT		*/	{ 1, 0, 1, 0, 1, 1, 1, 0 },
94 	/* SELECTING	*/	{ 1, 0, 1, 0, 1, 1, 0, 0 },
95 	/* REQUESTING	*/	{ 1, 0, 1, 0, 1, 1, 0, 0 },
96 	/* PRE_BOUND	*/	{ 1, 1, 1, 1, 0, 1, 0, 1 },
97 	/* BOUND	*/	{ 1, 1, 1, 1, 0, 1, 0, 1 },
98 	/* RENEWING	*/	{ 1, 1, 1, 1, 0, 1, 0, 1 },
99 	/* REBINDING	*/	{ 1, 1, 1, 1, 0, 1, 0, 1 },
100 	/* INFORMATION  */	{ 1, 0, 1, 0, 1, 1, 1, 1 },
101 	/* INIT_REBOOT  */	{ 1, 0, 1, 1, 1, 1, 0, 0 },
102 	/* ADOPTING	*/	{ 1, 0, 1, 1, 0, 1, 0, 0 },
103 	/* INFORM_SENT  */	{ 1, 0, 1, 0, 1, 1, 1, 0 },
104 	/* DECLINING	*/	{ 1, 1, 1, 1, 0, 1, 0, 1 },
105 	/* RELEASING	*/	{ 1, 0, 1, 0, 0, 1, 0, 1 },
106 };
107 
108 #define	CMD_ISPRIV	0x1	/* Command requires privileges */
109 #define	CMD_CREATE	0x2	/* Command creates an interface */
110 #define	CMD_BOOTP	0x4	/* Command is valid with BOOTP */
111 #define	CMD_IMMED	0x8	/* Reply is immediate (no BUSY state) */
112 
113 static uint_t ipc_cmd_flags[DHCP_NIPC] = {
114 	/* DHCP_DROP */		CMD_ISPRIV|CMD_BOOTP,
115 	/* DHCP_EXTEND */	CMD_ISPRIV,
116 	/* DHCP_PING */		CMD_BOOTP|CMD_IMMED,
117 	/* DHCP_RELEASE */	CMD_ISPRIV,
118 	/* DHCP_START */	CMD_CREATE|CMD_ISPRIV|CMD_BOOTP,
119 	/* DHCP_STATUS */	CMD_BOOTP|CMD_IMMED,
120 	/* DHCP_INFORM */	CMD_CREATE|CMD_ISPRIV,
121 	/* DHCP_GET_TAG */	CMD_BOOTP|CMD_IMMED
122 };
123 
124 int
125 main(int argc, char **argv)
126 {
127 	boolean_t	is_daemon  = B_TRUE;
128 	boolean_t	is_verbose;
129 	int		ipc_fd;
130 	int		c;
131 	struct rlimit	rl;
132 
133 	debug_level = df_get_int("", B_FALSE, DF_DEBUG_LEVEL);
134 	is_verbose = df_get_bool("", B_FALSE, DF_VERBOSE);
135 
136 	/*
137 	 * -l is ignored for compatibility with old agent.
138 	 */
139 
140 	while ((c = getopt(argc, argv, "vd:l:fa")) != EOF) {
141 
142 		switch (c) {
143 
144 		case 'a':
145 			do_adopt = B_TRUE;
146 			grandparent = getpid();
147 			break;
148 
149 		case 'd':
150 			debug_level = strtoul(optarg, NULL, 0);
151 			break;
152 
153 		case 'f':
154 			is_daemon = B_FALSE;
155 			break;
156 
157 		case 'v':
158 			is_verbose = B_TRUE;
159 			break;
160 
161 		case '?':
162 			(void) fprintf(stderr, "usage: %s [-a] [-d n] [-f] [-v]"
163 			    "\n", argv[0]);
164 			return (EXIT_FAILURE);
165 
166 		default:
167 			break;
168 		}
169 	}
170 
171 	(void) setlocale(LC_ALL, "");
172 	(void) textdomain(TEXT_DOMAIN);
173 
174 	if (geteuid() != 0) {
175 		dhcpmsg_init(argv[0], B_FALSE, is_verbose, debug_level);
176 		dhcpmsg(MSG_ERROR, "must be super-user");
177 		dhcpmsg_fini();
178 		return (EXIT_FAILURE);
179 	}
180 
181 	if (is_daemon && daemonize() == 0) {
182 		dhcpmsg_init(argv[0], B_FALSE, is_verbose, debug_level);
183 		dhcpmsg(MSG_ERR, "cannot become daemon, exiting");
184 		dhcpmsg_fini();
185 		return (EXIT_FAILURE);
186 	}
187 
188 	/*
189 	 * Seed the random number generator, since we're going to need it
190 	 * to set transaction id's and for exponential backoff.
191 	 */
192 	srand48(gethrtime() ^ gethostid() ^ getpid());
193 
194 	dhcpmsg_init(argv[0], is_daemon, is_verbose, debug_level);
195 	(void) atexit(dhcpmsg_fini);
196 
197 	tq = iu_tq_create();
198 	eh = iu_eh_create();
199 
200 	if (eh == NULL || tq == NULL) {
201 		errno = ENOMEM;
202 		dhcpmsg(MSG_ERR, "cannot create timer queue or event handler");
203 		return (EXIT_FAILURE);
204 	}
205 
206 	/*
207 	 * ignore most signals that could be reasonably generated.
208 	 */
209 
210 	(void) signal(SIGTERM, graceful_shutdown);
211 	(void) signal(SIGQUIT, graceful_shutdown);
212 	(void) signal(SIGPIPE, SIG_IGN);
213 	(void) signal(SIGUSR1, SIG_IGN);
214 	(void) signal(SIGUSR2, SIG_IGN);
215 	(void) signal(SIGINT,  SIG_IGN);
216 	(void) signal(SIGHUP,  SIG_IGN);
217 	(void) signal(SIGCHLD, SIG_IGN);
218 
219 	/*
220 	 * upon SIGTHAW we need to refresh any non-infinite leases.
221 	 */
222 
223 	(void) iu_eh_register_signal(eh, SIGTHAW, refresh_smachs, NULL);
224 
225 	class_id = get_class_id();
226 	if (class_id != NULL)
227 		class_id_len = strlen(class_id);
228 	else
229 		dhcpmsg(MSG_WARNING, "get_class_id failed, continuing "
230 		    "with no vendor class id");
231 
232 	/*
233 	 * the inactivity timer is enabled any time there are no
234 	 * interfaces under DHCP control.  if DHCP_INACTIVITY_WAIT
235 	 * seconds transpire without an interface under DHCP control,
236 	 * the agent shuts down.
237 	 */
238 
239 	inactivity_id = iu_schedule_timer(tq, DHCP_INACTIVITY_WAIT,
240 	    inactivity_shutdown, NULL);
241 
242 	/*
243 	 * max out the number available descriptors, just in case..
244 	 */
245 
246 	rl.rlim_cur = RLIM_INFINITY;
247 	rl.rlim_max = RLIM_INFINITY;
248 	if (setrlimit(RLIMIT_NOFILE, &rl) == -1)
249 		dhcpmsg(MSG_ERR, "setrlimit failed");
250 
251 	(void) enable_extended_FILE_stdio(-1, -1);
252 
253 	/*
254 	 * Create and bind default IP sockets used to control interfaces and to
255 	 * catch stray packets.
256 	 */
257 
258 	if (!dhcp_ip_default())
259 		return (EXIT_FAILURE);
260 
261 	/*
262 	 * create the ipc channel that the agent will listen for
263 	 * requests on, and register it with the event handler so that
264 	 * `accept_event' will be called back.
265 	 */
266 
267 	switch (dhcp_ipc_init(&ipc_fd)) {
268 
269 	case 0:
270 		break;
271 
272 	case DHCP_IPC_E_BIND:
273 		dhcpmsg(MSG_ERROR, "dhcp_ipc_init: cannot bind to port "
274 		    "%i (agent already running?)", IPPORT_DHCPAGENT);
275 		return (EXIT_FAILURE);
276 
277 	default:
278 		dhcpmsg(MSG_ERROR, "dhcp_ipc_init failed");
279 		return (EXIT_FAILURE);
280 	}
281 
282 	if (iu_register_event(eh, ipc_fd, POLLIN, accept_event, 0) == -1) {
283 		dhcpmsg(MSG_ERR, "cannot register ipc fd for messages");
284 		return (EXIT_FAILURE);
285 	}
286 
287 	/*
288 	 * Create the global routing socket.  This is used for monitoring
289 	 * interface transitions, so that we learn about the kernel's Duplicate
290 	 * Address Detection status, and for inserting and removing default
291 	 * routes as learned from DHCP servers.  Both v4 and v6 are handed
292 	 * with this one socket.
293 	 */
294 	rtsock_fd = socket(PF_ROUTE, SOCK_RAW, 0);
295 	if (rtsock_fd == -1) {
296 		dhcpmsg(MSG_ERR, "cannot open routing socket");
297 		return (EXIT_FAILURE);
298 	}
299 	if (iu_register_event(eh, rtsock_fd, POLLIN, rtsock_event, 0) == -1) {
300 		dhcpmsg(MSG_ERR, "cannot register routing socket for messages");
301 		return (EXIT_FAILURE);
302 	}
303 
304 	/*
305 	 * if the -a (adopt) option was specified, try to adopt the
306 	 * kernel-managed interface before we start.
307 	 */
308 
309 	if (do_adopt && !dhcp_adopt())
310 		return (EXIT_FAILURE);
311 
312 	/*
313 	 * For DHCPv6, we own all of the interfaces marked DHCPRUNNING.  As
314 	 * we're starting operation here, if there are any of those interfaces
315 	 * lingering around, they're strays, and need to be removed.
316 	 *
317 	 * It might be nice to save these addresses off somewhere -- for both
318 	 * v4 and v6 -- and use them as hints for later negotiation.
319 	 */
320 	remove_v6_strays();
321 
322 	/*
323 	 * enter the main event loop; this is where all the real work
324 	 * takes place (through registering events and scheduling timers).
325 	 * this function only returns when the agent is shutting down.
326 	 */
327 
328 	switch (iu_handle_events(eh, tq)) {
329 
330 	case -1:
331 		dhcpmsg(MSG_WARNING, "iu_handle_events exited abnormally");
332 		break;
333 
334 	case DHCP_REASON_INACTIVITY:
335 		dhcpmsg(MSG_INFO, "no interfaces to manage, shutting down...");
336 		break;
337 
338 	case DHCP_REASON_TERMINATE:
339 		dhcpmsg(MSG_INFO, "received SIGTERM, shutting down...");
340 		break;
341 
342 	case DHCP_REASON_SIGNAL:
343 		dhcpmsg(MSG_WARNING, "received unexpected signal, shutting "
344 		    "down...");
345 		break;
346 	}
347 
348 	(void) iu_eh_unregister_signal(eh, SIGTHAW, NULL);
349 
350 	iu_eh_destroy(eh);
351 	iu_tq_destroy(tq);
352 
353 	return (EXIT_SUCCESS);
354 }
355 
356 /*
357  * drain_script(): event loop callback during shutdown
358  *
359  *   input: eh_t *: unused
360  *	    void *: unused
361  *  output: boolean_t: B_TRUE if event loop should exit; B_FALSE otherwise
362  */
363 
364 /* ARGSUSED */
365 boolean_t
366 drain_script(iu_eh_t *ehp, void *arg)
367 {
368 	if (shutdown_started == B_FALSE) {
369 		shutdown_started = B_TRUE;
370 		if (do_adopt == B_FALSE)	/* see 4291141 */
371 			nuke_smach_list();
372 	}
373 	return (script_count == 0);
374 }
375 
376 /*
377  * accept_event(): accepts a new connection on the ipc socket and registers
378  *		   to receive its messages with the event handler
379  *
380  *   input: iu_eh_t *: unused
381  *	    int: the file descriptor in the iu_eh_t * the connection came in on
382  *	    (other arguments unused)
383  *  output: void
384  */
385 
386 /* ARGSUSED */
387 static void
388 accept_event(iu_eh_t *ehp, int fd, short events, iu_event_id_t id, void *arg)
389 {
390 	int	client_fd;
391 	int	is_priv;
392 
393 	if (dhcp_ipc_accept(fd, &client_fd, &is_priv) != 0) {
394 		dhcpmsg(MSG_ERR, "accept_event: accept on ipc socket");
395 		return;
396 	}
397 
398 	if (iu_register_event(eh, client_fd, POLLIN, ipc_event,
399 	    (void *)is_priv) == -1) {
400 		dhcpmsg(MSG_ERROR, "accept_event: cannot register ipc socket "
401 		    "for callback");
402 	}
403 }
404 
405 /*
406  * ipc_event(): processes incoming ipc requests
407  *
408  *   input: iu_eh_t *: unused
409  *	    int: the file descriptor in the iu_eh_t * the request came in on
410  *	    short: unused
411  *	    iu_event_id_t: event ID
412  *	    void *: indicates whether the request is from a privileged client
413  *  output: void
414  */
415 
416 /* ARGSUSED */
417 static void
418 ipc_event(iu_eh_t *ehp, int fd, short events, iu_event_id_t id, void *arg)
419 {
420 	ipc_action_t		ia, *iap;
421 	dhcp_smach_t		*dsmp;
422 	int			error, is_priv = (int)arg;
423 	const char		*ifname;
424 	boolean_t		isv6;
425 
426 	ipc_action_init(&ia);
427 	error = dhcp_ipc_recv_request(fd, &ia.ia_request,
428 	    DHCP_IPC_REQUEST_WAIT);
429 	if (error != DHCP_IPC_SUCCESS) {
430 		if (error != DHCP_IPC_E_EOF) {
431 			dhcpmsg(MSG_ERROR,
432 			    "ipc_event: dhcp_ipc_recv_request failed: %s",
433 			    dhcp_ipc_strerror(error));
434 		} else {
435 			dhcpmsg(MSG_DEBUG, "ipc_event: connection closed");
436 		}
437 		if ((dsmp = lookup_smach_by_event(id)) != NULL) {
438 			ipc_action_finish(dsmp, error);
439 		} else {
440 			(void) iu_unregister_event(eh, id, NULL);
441 			(void) dhcp_ipc_close(fd);
442 		}
443 		return;
444 	}
445 
446 	/* Fill in temporary ipc_action structure for utility functions */
447 	ia.ia_cmd = DHCP_IPC_CMD(ia.ia_request->message_type);
448 	ia.ia_fd = fd;
449 	ia.ia_eid = id;
450 
451 	if (ia.ia_cmd >= DHCP_NIPC) {
452 		dhcpmsg(MSG_ERROR,
453 		    "ipc_event: invalid command (%s) attempted on %s",
454 		    dhcp_ipc_type_to_string(ia.ia_cmd), ia.ia_request->ifname);
455 		send_error_reply(&ia, DHCP_IPC_E_CMD_UNKNOWN);
456 		return;
457 	}
458 
459 	/* return EPERM for any of the privileged actions */
460 
461 	if (!is_priv && (ipc_cmd_flags[ia.ia_cmd] & CMD_ISPRIV)) {
462 		dhcpmsg(MSG_WARNING,
463 		    "ipc_event: privileged ipc command (%s) attempted on %s",
464 		    dhcp_ipc_type_to_string(ia.ia_cmd), ia.ia_request->ifname);
465 		send_error_reply(&ia, DHCP_IPC_E_PERM);
466 		return;
467 	}
468 
469 	/*
470 	 * Try to locate the state machine associated with this command.  If
471 	 * the command is DHCP_START or DHCP_INFORM and there isn't a state
472 	 * machine already, make one (there may already be one from a previous
473 	 * failed attempt to START or INFORM).  Otherwise, verify the reference
474 	 * is still valid.
475 	 *
476 	 * The interface name may be blank.  In that case, we look up the
477 	 * primary interface, and the requested type (v4 or v6) doesn't matter.
478 	 */
479 
480 	isv6 = (ia.ia_request->message_type & DHCP_V6) != 0;
481 	ifname = ia.ia_request->ifname;
482 	if (*ifname == '\0')
483 		dsmp = primary_smach(isv6);
484 	else
485 		dsmp = lookup_smach(ifname, isv6);
486 
487 	if (dsmp != NULL) {
488 		/* Note that verify_smach drops a reference */
489 		hold_smach(dsmp);
490 		if (!verify_smach(dsmp))
491 			dsmp = NULL;
492 	}
493 
494 	if (dsmp == NULL) {
495 		/*
496 		 * If the user asked for the primary DHCP interface, but there
497 		 * is none, then report failure.
498 		 */
499 		if (ifname[0] == '\0') {
500 			error = DHCP_IPC_E_NOPRIMARY;
501 
502 		/*
503 		 * If there's no interface, and we're starting up, then create
504 		 * it now, along with a state machine for it.  Note that if
505 		 * insert_smach fails, it discards the LIF reference.
506 		 */
507 		} else if (ipc_cmd_flags[ia.ia_cmd] & CMD_CREATE) {
508 			dhcp_lif_t *lif;
509 
510 			lif = attach_lif(ifname, isv6, &error);
511 			if (lif != NULL &&
512 			    (dsmp = insert_smach(lif, &error)) != NULL) {
513 				/*
514 				 * Get client ID and set "DHCPRUNNING" flag on
515 				 * logical interface.  (V4 only, because V6
516 				 * plumbs its own interfaces.)
517 				 */
518 				error = get_smach_cid(dsmp);
519 				if (error == DHCP_IPC_SUCCESS)
520 					error = set_lif_dhcp(lif, B_FALSE);
521 				if (error != DHCP_IPC_SUCCESS) {
522 					remove_smach(dsmp);
523 					dsmp = NULL;
524 				}
525 			}
526 
527 		/*
528 		 * Otherwise, this is an operation on an unknown interface.
529 		 */
530 		} else {
531 			error = DHCP_IPC_E_UNKIF;
532 		}
533 		if (dsmp == NULL) {
534 			send_error_reply(&ia, error);
535 			return;
536 		}
537 	}
538 
539 	if ((dsmp->dsm_dflags & DHCP_IF_BOOTP) &&
540 	    !(ipc_cmd_flags[ia.ia_cmd] & CMD_BOOTP)) {
541 		dhcpmsg(MSG_ERROR, "command %s not valid for BOOTP on %s",
542 		    dhcp_ipc_type_to_string(ia.ia_cmd), dsmp->dsm_name);
543 		send_error_reply(&ia, DHCP_IPC_E_BOOTP);
544 		return;
545 	}
546 
547 	/*
548 	 * verify that the state machine is in a state which will allow the
549 	 * command.  we do this up front so that we can return an error
550 	 * *before* needlessly cancelling an in-progress transaction.
551 	 */
552 
553 	if (!check_cmd_allowed(dsmp->dsm_state, ia.ia_cmd)) {
554 		dhcpmsg(MSG_DEBUG,
555 		    "in state %s; not allowing %s command on %s",
556 		    dhcp_state_to_string(dsmp->dsm_state),
557 		    dhcp_ipc_type_to_string(ia.ia_cmd), dsmp->dsm_name);
558 		send_error_reply(&ia,
559 		    ia.ia_cmd == DHCP_START && dsmp->dsm_state != INIT ?
560 		    DHCP_IPC_E_RUNNING : DHCP_IPC_E_OUTSTATE);
561 		return;
562 	}
563 
564 	dhcpmsg(MSG_DEBUG, "in state %s; allowing %s command on %s",
565 	    dhcp_state_to_string(dsmp->dsm_state),
566 	    dhcp_ipc_type_to_string(ia.ia_cmd), dsmp->dsm_name);
567 
568 	if ((ia.ia_request->message_type & DHCP_PRIMARY) && is_priv)
569 		make_primary(dsmp);
570 
571 	/*
572 	 * The current design dictates that there can be only one outstanding
573 	 * transaction per state machine -- this simplifies the code
574 	 * considerably and also fits well with RFCs 2131 and 3315.  It is
575 	 * worth classifying the different DHCP commands into synchronous
576 	 * (those which we will handle now and reply to immediately) and
577 	 * asynchronous (those which require transactions and will be completed
578 	 * at an indeterminate time in the future):
579 	 *
580 	 *    DROP: removes the agent's management of a state machine.
581 	 *	    asynchronous as the script program may be invoked.
582 	 *
583 	 *    PING: checks to see if the agent has a named state machine.
584 	 *	    synchronous, since no packets need to be sent
585 	 *	    to the DHCP server.
586 	 *
587 	 *  STATUS: returns information about a state machine.
588 	 *	    synchronous, since no packets need to be sent
589 	 *	    to the DHCP server.
590 	 *
591 	 * RELEASE: releases the agent's management of a state machine
592 	 *	    and brings the associated interfaces down.  asynchronous
593 	 *	    as the script program may be invoked.
594 	 *
595 	 *  EXTEND: renews a lease.  asynchronous, since the agent
596 	 *	    needs to wait for an ACK, etc.
597 	 *
598 	 *   START: starts DHCP on a named state machine.  asynchronous since
599 	 *	    the agent needs to wait for OFFERs, ACKs, etc.
600 	 *
601 	 *  INFORM: obtains configuration parameters for the system using
602 	 *	    externally configured interface.  asynchronous, since the
603 	 *	    agent needs to wait for an ACK.
604 	 *
605 	 * Notice that EXTEND, INFORM, START, DROP and RELEASE are
606 	 * asynchronous.  Notice also that asynchronous commands may occur from
607 	 * within the agent -- for instance, the agent will need to do implicit
608 	 * EXTENDs to extend the lease. In order to make the code simpler, the
609 	 * following rules apply for asynchronous commands:
610 	 *
611 	 * There can only be one asynchronous command at a time per state
612 	 * machine.  The current asynchronous command is managed by the async_*
613 	 * api: async_start(), async_finish(), and async_cancel().
614 	 * async_start() starts management of a new asynchronous command on an
615 	 * state machine, which should only be done after async_cancel() to
616 	 * terminate a previous command.  When the command is completed,
617 	 * async_finish() should be called.
618 	 *
619 	 * Asynchronous commands started by a user command have an associated
620 	 * ipc_action which provides the agent with information for how to get
621 	 * in touch with the user command when the action completes.  These
622 	 * ipc_action records also have an associated timeout which may be
623 	 * infinite.  ipc_action_start() should be called when starting an
624 	 * asynchronous command requested by a user, which sets up the timer
625 	 * and keeps track of the ipc information (file descriptor, request
626 	 * type).  When the asynchronous command completes, ipc_action_finish()
627 	 * should be called to return a command status code to the user and
628 	 * close the ipc connection).  If the command does not complete before
629 	 * the timer fires, ipc_action_timeout() is called which closes the ipc
630 	 * connection and returns DHCP_IPC_E_TIMEOUT to the user.  Note that
631 	 * independent of ipc_action_timeout(), ipc_action_finish() should be
632 	 * called.
633 	 *
634 	 * on a case-by-case basis, here is what happens (per state machine):
635 	 *
636 	 *    o When an asynchronous command is requested, then
637 	 *	async_cancel() is called to terminate any non-user
638 	 *	action in progress.  If there's a user action running,
639 	 *	the user command is sent DHCP_IPC_E_PEND.
640 	 *
641 	 *    o otherwise, the the transaction is started with
642 	 *	async_start().  if the transaction is on behalf
643 	 *	of a user, ipc_action_start() is called to keep
644 	 *	track of the ipc information and set up the
645 	 *	ipc_action timer.
646 	 *
647 	 *    o if the command completes normally and before a
648 	 *	timeout fires, then async_finish() is called.
649 	 *	if there was an associated ipc_action,
650 	 *	ipc_action_finish() is called to complete it.
651 	 *
652 	 *    o if the command fails before a timeout fires, then
653 	 *	async_finish() is called, and the state machine is
654 	 *	is returned to a known state based on the command.
655 	 *	if there was an associated ipc_action,
656 	 *	ipc_action_finish() is called to complete it.
657 	 *
658 	 *    o if the ipc_action timer fires before command
659 	 *	completion, then DHCP_IPC_E_TIMEOUT is returned to
660 	 *	the user.  however, the transaction continues to
661 	 *	be carried out asynchronously.
662 	 */
663 
664 	if (ipc_cmd_flags[ia.ia_cmd] & CMD_IMMED) {
665 		/*
666 		 * Only immediate commands (ping, status, get_tag) need to
667 		 * worry about freeing ia through one of the reply functions
668 		 * before returning.
669 		 */
670 		iap = &ia;
671 	} else {
672 		/*
673 		 * if shutdown request has been received, send back an error.
674 		 */
675 		if (shutdown_started) {
676 			send_error_reply(&ia, DHCP_IPC_E_OUTSTATE);
677 			return;
678 		}
679 
680 		if (dsmp->dsm_dflags & DHCP_IF_BUSY) {
681 			send_error_reply(&ia, DHCP_IPC_E_PEND);
682 			return;
683 		}
684 
685 		if (!ipc_action_start(dsmp, &ia)) {
686 			dhcpmsg(MSG_WARNING, "ipc_event: ipc_action_start "
687 			    "failed for %s", dsmp->dsm_name);
688 			send_error_reply(&ia, DHCP_IPC_E_MEMORY);
689 			return;
690 		}
691 
692 		/* Action structure consumed by above function */
693 		iap = &dsmp->dsm_ia;
694 	}
695 
696 	switch (iap->ia_cmd) {
697 
698 	case DHCP_DROP:
699 		(void) script_start(dsmp, isv6 ? EVENT_DROP6 : EVENT_DROP,
700 		    dhcp_drop, NULL, NULL);
701 		break;		/* not an immediate function */
702 
703 	case DHCP_EXTEND:
704 		(void) dhcp_extending(dsmp);
705 		break;
706 
707 	case DHCP_GET_TAG: {
708 		dhcp_optnum_t	optnum;
709 		void		*opt = NULL;
710 		uint_t		optlen;
711 		boolean_t	did_alloc = B_FALSE;
712 		PKT_LIST	*ack = dsmp->dsm_ack;
713 
714 		/*
715 		 * verify the request makes sense.
716 		 */
717 
718 		if (iap->ia_request->data_type   != DHCP_TYPE_OPTNUM ||
719 		    iap->ia_request->data_length != sizeof (dhcp_optnum_t)) {
720 			send_error_reply(iap, DHCP_IPC_E_PROTO);
721 			break;
722 		}
723 
724 		(void) memcpy(&optnum, iap->ia_request->buffer,
725 		    sizeof (dhcp_optnum_t));
726 
727 load_option:
728 		switch (optnum.category) {
729 
730 		case DSYM_SITE:			/* FALLTHRU */
731 		case DSYM_STANDARD:
732 			if (isv6) {
733 				opt = dhcpv6_pkt_option(ack, NULL, optnum.code,
734 				    NULL);
735 			} else {
736 				if (optnum.code <= DHCP_LAST_OPT)
737 					opt = ack->opts[optnum.code];
738 			}
739 			break;
740 
741 		case DSYM_VENDOR:
742 			if (isv6) {
743 				dhcpv6_option_t *d6o;
744 				uint32_t ent;
745 
746 				/*
747 				 * Look through vendor options to find our
748 				 * enterprise number.
749 				 */
750 				d6o = NULL;
751 				for (;;) {
752 					d6o = dhcpv6_pkt_option(ack, d6o,
753 					    DHCPV6_OPT_VENDOR_OPT, &optlen);
754 					if (d6o == NULL)
755 						break;
756 					optlen -= sizeof (*d6o);
757 					if (optlen < sizeof (ent))
758 						continue;
759 					(void) memcpy(&ent, d6o + 1,
760 					    sizeof (ent));
761 					if (ntohl(ent) != DHCPV6_SUN_ENT)
762 						continue;
763 					break;
764 				}
765 				if (d6o != NULL) {
766 					/*
767 					 * Now find the requested vendor option
768 					 * within the vendor options block.
769 					 */
770 					opt = dhcpv6_find_option(
771 					    (char *)(d6o + 1) + sizeof (ent),
772 					    optlen - sizeof (ent), NULL,
773 					    optnum.code, NULL);
774 				}
775 			} else {
776 				/*
777 				 * the test against VS_OPTION_START is broken
778 				 * up into two tests to avoid compiler warnings
779 				 * under intel.
780 				 */
781 				if ((optnum.code > VS_OPTION_START ||
782 				    optnum.code == VS_OPTION_START) &&
783 				    optnum.code <= VS_OPTION_END)
784 					opt = ack->vs[optnum.code];
785 			}
786 			break;
787 
788 		case DSYM_FIELD:
789 			if (isv6) {
790 				dhcpv6_message_t *d6m =
791 				    (dhcpv6_message_t *)ack->pkt;
792 				dhcpv6_option_t *d6o;
793 
794 				/* Validate the packet field the user wants */
795 				optlen = optnum.code + optnum.size;
796 				if (d6m->d6m_msg_type ==
797 				    DHCPV6_MSG_RELAY_FORW ||
798 				    d6m->d6m_msg_type ==
799 				    DHCPV6_MSG_RELAY_REPL) {
800 					if (optlen > sizeof (dhcpv6_relay_t))
801 						break;
802 				} else {
803 					if (optlen > sizeof (*d6m))
804 						break;
805 				}
806 
807 				opt = malloc(sizeof (*d6o) + optnum.size);
808 				if (opt != NULL) {
809 					d6o = opt;
810 					d6o->d6o_code = htons(optnum.code);
811 					d6o->d6o_len = htons(optnum.size);
812 					(void) memcpy(d6o + 1, (caddr_t)d6m +
813 					    optnum.code, optnum.size);
814 				}
815 			} else {
816 				if (optnum.code + optnum.size > sizeof (PKT))
817 					break;
818 
819 				/*
820 				 * + 2 to account for option code and length
821 				 * byte
822 				 */
823 				opt = malloc(optnum.size + 2);
824 				if (opt != NULL) {
825 					DHCP_OPT *v4opt = opt;
826 
827 					v4opt->len  = optnum.size;
828 					v4opt->code = optnum.code;
829 					(void) memcpy(v4opt->value,
830 					    (caddr_t)ack->pkt + optnum.code,
831 					    optnum.size);
832 				}
833 			}
834 
835 			if (opt == NULL) {
836 				send_error_reply(iap, DHCP_IPC_E_MEMORY);
837 				return;
838 			}
839 			did_alloc = B_TRUE;
840 			break;
841 
842 		default:
843 			send_error_reply(iap, DHCP_IPC_E_PROTO);
844 			return;
845 		}
846 
847 		/*
848 		 * return the option payload, if there was one.  the "+ 2"
849 		 * accounts for the option code number and length byte.
850 		 */
851 
852 		if (opt != NULL) {
853 			if (isv6) {
854 				dhcpv6_option_t d6ov;
855 
856 				(void) memcpy(&d6ov, opt, sizeof (d6ov));
857 				optlen = ntohs(d6ov.d6o_len) + sizeof (d6ov);
858 			} else {
859 				optlen = ((DHCP_OPT *)opt)->len + 2;
860 			}
861 			send_data_reply(iap, 0, DHCP_TYPE_OPTION, opt, optlen);
862 
863 			if (did_alloc)
864 				free(opt);
865 			break;
866 		} else if (ack != dsmp->dsm_orig_ack) {
867 			/*
868 			 * There wasn't any definition for the option in the
869 			 * current ack, so now retry with the original ack if
870 			 * the original ack is not the current ack.
871 			 */
872 			ack = dsmp->dsm_orig_ack;
873 			goto load_option;
874 		}
875 
876 		/*
877 		 * note that an "okay" response is returned either in
878 		 * the case of an unknown option or a known option
879 		 * with no payload.  this is okay (for now) since
880 		 * dhcpinfo checks whether an option is valid before
881 		 * ever performing ipc with the agent.
882 		 */
883 
884 		send_ok_reply(iap);
885 		break;
886 	}
887 
888 	case DHCP_INFORM:
889 		dhcp_inform(dsmp);
890 		/* next destination: dhcp_acknak() */
891 		break;		/* not an immediate function */
892 
893 	case DHCP_PING:
894 		if (dsmp->dsm_dflags & DHCP_IF_FAILED)
895 			send_error_reply(iap, DHCP_IPC_E_FAILEDIF);
896 		else
897 			send_ok_reply(iap);
898 		break;
899 
900 	case DHCP_RELEASE:
901 		(void) script_start(dsmp, isv6 ? EVENT_RELEASE6 :
902 		    EVENT_RELEASE, dhcp_release, "Finished with lease.", NULL);
903 		break;		/* not an immediate function */
904 
905 	case DHCP_START: {
906 		PKT_LIST *ack, *oack;
907 		PKT_LIST *plp[2];
908 
909 		deprecate_leases(dsmp);
910 
911 		/*
912 		 * if we have a valid hostconf lying around, then jump
913 		 * into INIT_REBOOT.  if it fails, we'll end up going
914 		 * through the whole selecting() procedure again.
915 		 */
916 
917 		error = read_hostconf(dsmp->dsm_name, plp, 2, dsmp->dsm_isv6);
918 		ack = error > 0 ? plp[0] : NULL;
919 		oack = error > 1 ? plp[1] : NULL;
920 
921 		/*
922 		 * If the allocation of the old ack fails, that's fine;
923 		 * continue without it.
924 		 */
925 		if (oack == NULL)
926 			oack = ack;
927 
928 		/*
929 		 * As long as we've allocated something, start using it.
930 		 */
931 		if (ack != NULL) {
932 			dsmp->dsm_orig_ack = oack;
933 			dsmp->dsm_ack = ack;
934 			dhcp_init_reboot(dsmp);
935 			/* next destination: dhcp_acknak() */
936 			break;
937 		}
938 
939 		/*
940 		 * if not debugging, wait for a few seconds before
941 		 * going into SELECTING.
942 		 */
943 
944 		if (debug_level == 0 && set_start_timer(dsmp)) {
945 			/* next destination: dhcp_start() */
946 			break;
947 		} else {
948 			dhcp_selecting(dsmp);
949 			/* next destination: dhcp_requesting() */
950 			break;
951 		}
952 	}
953 
954 	case DHCP_STATUS: {
955 		dhcp_status_t	status;
956 		dhcp_lease_t	*dlp;
957 
958 		status.if_began = monosec_to_time(dsmp->dsm_curstart_monosec);
959 
960 		/*
961 		 * We return information on just the first lease as being
962 		 * representative of the lot.  A better status mechanism is
963 		 * needed.
964 		 */
965 		dlp = dsmp->dsm_leases;
966 
967 		if (dlp == NULL ||
968 		    dlp->dl_lifs->lif_expire.dt_start == DHCP_PERM) {
969 			status.if_t1	= DHCP_PERM;
970 			status.if_t2	= DHCP_PERM;
971 			status.if_lease	= DHCP_PERM;
972 		} else {
973 			status.if_t1	= status.if_began +
974 			    dlp->dl_t1.dt_start;
975 			status.if_t2	= status.if_began +
976 			    dlp->dl_t2.dt_start;
977 			status.if_lease	= status.if_began +
978 			    dlp->dl_lifs->lif_expire.dt_start;
979 		}
980 
981 		status.version		= DHCP_STATUS_VER;
982 		status.if_state		= dsmp->dsm_state;
983 		status.if_dflags	= dsmp->dsm_dflags;
984 		status.if_sent		= dsmp->dsm_sent;
985 		status.if_recv		= dsmp->dsm_received;
986 		status.if_bad_offers	= dsmp->dsm_bad_offers;
987 
988 		(void) strlcpy(status.if_name, dsmp->dsm_name, IFNAMSIZ);
989 
990 		send_data_reply(iap, 0, DHCP_TYPE_STATUS, &status,
991 		    sizeof (dhcp_status_t));
992 		break;
993 	}
994 	}
995 }
996 
997 /*
998  * check_rtm_addr(): determine if routing socket message matches interface
999  *		     address
1000  *
1001  *   input: const struct if_msghdr *: pointer to routing socket message
1002  *	    int: routing socket message length
1003  *	    boolean_t: set to B_TRUE if IPv6
1004  *	    const in6_addr_t *: pointer to IP address
1005  *  output: boolean_t: B_TRUE if address is a match
1006  */
1007 
1008 static boolean_t
1009 check_rtm_addr(const struct ifa_msghdr *ifam, int msglen, boolean_t isv6,
1010     const in6_addr_t *addr)
1011 {
1012 	const char *cp, *lim;
1013 	uint_t flag;
1014 	const struct sockaddr *sa;
1015 
1016 	if (!(ifam->ifam_addrs & RTA_IFA))
1017 		return (B_FALSE);
1018 
1019 	cp = (const char *)(ifam + 1);
1020 	lim = (const char *)ifam + msglen;
1021 	for (flag = 1; flag < RTA_IFA; flag <<= 1) {
1022 		if (ifam->ifam_addrs & flag) {
1023 			/* LINTED: alignment */
1024 			sa = (const struct sockaddr *)cp;
1025 			if ((const char *)(sa + 1) > lim)
1026 				return (B_FALSE);
1027 			switch (sa->sa_family) {
1028 			case AF_INET:
1029 				cp += sizeof (struct sockaddr_in);
1030 				break;
1031 			case AF_LINK:
1032 				cp += sizeof (struct sockaddr_dl);
1033 				break;
1034 			case AF_INET6:
1035 				cp += sizeof (struct sockaddr_in6);
1036 				break;
1037 			default:
1038 				cp += sizeof (struct sockaddr);
1039 				break;
1040 			}
1041 		}
1042 	}
1043 	if (isv6) {
1044 		const struct sockaddr_in6 *sin6;
1045 
1046 		/* LINTED: alignment */
1047 		sin6 = (const struct sockaddr_in6 *)cp;
1048 		if ((const char *)(sin6 + 1) > lim)
1049 			return (B_FALSE);
1050 		if (sin6->sin6_family != AF_INET6)
1051 			return (B_FALSE);
1052 		return (IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr, addr));
1053 	} else {
1054 		const struct sockaddr_in *sinp;
1055 		ipaddr_t v4addr;
1056 
1057 		/* LINTED: alignment */
1058 		sinp = (const struct sockaddr_in *)cp;
1059 		if ((const char *)(sinp + 1) > lim)
1060 			return (B_FALSE);
1061 		if (sinp->sin_family != AF_INET)
1062 			return (B_FALSE);
1063 		IN6_V4MAPPED_TO_IPADDR(addr, v4addr);
1064 		return (sinp->sin_addr.s_addr == v4addr);
1065 	}
1066 }
1067 
1068 /*
1069  * is_rtm_v6(): determine if routing socket message is IPv6
1070  *
1071  *   input: struct ifa_msghdr *: pointer to routing socket message
1072  *	    int: message length
1073  *  output: boolean_t
1074  */
1075 
1076 static boolean_t
1077 is_rtm_v6(const struct ifa_msghdr *ifam, int msglen)
1078 {
1079 	const char *cp, *lim;
1080 	uint_t flag;
1081 	const struct sockaddr *sa;
1082 
1083 	cp = (const char *)(ifam + 1);
1084 	lim = (const char *)ifam + msglen;
1085 	for (flag = ifam->ifam_addrs; flag != 0; flag &= flag - 1) {
1086 		/* LINTED: alignment */
1087 		sa = (const struct sockaddr *)cp;
1088 		if ((const char *)(sa + 1) > lim)
1089 			return (B_FALSE);
1090 		switch (sa->sa_family) {
1091 		case AF_INET:
1092 			return (B_FALSE);
1093 		case AF_LINK:
1094 			cp += sizeof (struct sockaddr_dl);
1095 			break;
1096 		case AF_INET6:
1097 			return (B_TRUE);
1098 		default:
1099 			cp += sizeof (struct sockaddr);
1100 			break;
1101 		}
1102 	}
1103 	return (B_FALSE);
1104 }
1105 
1106 /*
1107  * check_lif(): check the state of a given logical interface and its DHCP
1108  *		lease.  We've been told by the routing socket that the
1109  *		corresponding ifIndex has changed.  This may mean that DAD has
1110  *		completed or failed.
1111  *
1112  *   input: dhcp_lif_t *: pointer to the LIF
1113  *	    const struct ifa_msghdr *: routing socket message
1114  *	    int: size of routing socket message
1115  *  output: boolean_t: B_TRUE if DAD has completed on this interface
1116  */
1117 
1118 static boolean_t
1119 check_lif(dhcp_lif_t *lif, const struct ifa_msghdr *ifam, int msglen)
1120 {
1121 	boolean_t isv6, dad_wait, unplumb;
1122 	int fd;
1123 	struct lifreq lifr;
1124 
1125 	isv6 = lif->lif_pif->pif_isv6;
1126 	fd = isv6 ? v6_sock_fd : v4_sock_fd;
1127 
1128 	/*
1129 	 * Get the real (64 bit) logical interface flags.  Note that the
1130 	 * routing socket message has flags, but these are just the lower 32
1131 	 * bits.
1132 	 */
1133 	unplumb = B_FALSE;
1134 	(void) memset(&lifr, 0, sizeof (lifr));
1135 	(void) strlcpy(lifr.lifr_name, lif->lif_name, sizeof (lifr.lifr_name));
1136 	if (ioctl(fd, SIOCGLIFFLAGS, &lifr) == -1) {
1137 		/*
1138 		 * Failing to retrieve flags means that the interface is gone.
1139 		 * It hasn't failed to verify with DAD, but we still have to
1140 		 * give up on it.
1141 		 */
1142 		lifr.lifr_flags = 0;
1143 		if (errno == ENXIO) {
1144 			lif->lif_plumbed = B_FALSE;
1145 			dhcpmsg(MSG_INFO, "%s has been removed; abandoning",
1146 			    lif->lif_name);
1147 			if (!isv6)
1148 				discard_default_routes(lif->lif_smachs);
1149 		} else {
1150 			dhcpmsg(MSG_ERR,
1151 			    "unable to retrieve interface flags on %s",
1152 			    lif->lif_name);
1153 		}
1154 		unplumb = B_TRUE;
1155 	} else if (!check_rtm_addr(ifam, msglen, isv6, &lif->lif_v6addr)) {
1156 		/*
1157 		 * If the message is not about this logical interface,
1158 		 * then just ignore it.
1159 		 */
1160 		return (B_FALSE);
1161 	} else if (lifr.lifr_flags & IFF_DUPLICATE) {
1162 		dhcpmsg(MSG_ERROR, "interface %s has duplicate address",
1163 		    lif->lif_name);
1164 		lif_mark_decline(lif, "duplicate address");
1165 		close_ip_lif(lif);
1166 	}
1167 
1168 	dad_wait = lif->lif_dad_wait;
1169 	if (dad_wait) {
1170 		dhcpmsg(MSG_VERBOSE, "check_lif: %s has finished DAD",
1171 		    lif->lif_name);
1172 		lif->lif_dad_wait = B_FALSE;
1173 	}
1174 
1175 	if (unplumb)
1176 		unplumb_lif(lif);
1177 
1178 	return (dad_wait);
1179 }
1180 
1181 /*
1182  * check_main_lif(): check the state of a main logical interface for a state
1183  *		     machine.  This is used only for DHCPv6.
1184  *
1185  *   input: dhcp_smach_t *: pointer to the state machine
1186  *	    const struct ifa_msghdr *: routing socket message
1187  *	    int: size of routing socket message
1188  *  output: boolean_t: B_TRUE if LIF is ok.
1189  */
1190 
1191 static boolean_t
1192 check_main_lif(dhcp_smach_t *dsmp, const struct ifa_msghdr *ifam, int msglen)
1193 {
1194 	dhcp_lif_t *lif = dsmp->dsm_lif;
1195 	struct lifreq lifr;
1196 
1197 	/*
1198 	 * Get the real (64 bit) logical interface flags.  Note that the
1199 	 * routing socket message has flags, but these are just the lower 32
1200 	 * bits.
1201 	 */
1202 	(void) memset(&lifr, 0, sizeof (lifr));
1203 	(void) strlcpy(lifr.lifr_name, lif->lif_name, sizeof (lifr.lifr_name));
1204 	if (ioctl(v6_sock_fd, SIOCGLIFFLAGS, &lifr) == -1) {
1205 		/*
1206 		 * Failing to retrieve flags means that the interface is gone.
1207 		 * Our state machine is now trash.
1208 		 */
1209 		if (errno == ENXIO) {
1210 			dhcpmsg(MSG_INFO, "%s has been removed; abandoning",
1211 			    lif->lif_name);
1212 		} else {
1213 			dhcpmsg(MSG_ERR,
1214 			    "unable to retrieve interface flags on %s",
1215 			    lif->lif_name);
1216 		}
1217 		return (B_FALSE);
1218 	} else if (!check_rtm_addr(ifam, msglen, B_TRUE, &lif->lif_v6addr)) {
1219 		/*
1220 		 * If the message is not about this logical interface,
1221 		 * then just ignore it.
1222 		 */
1223 		return (B_TRUE);
1224 	} else if (lifr.lifr_flags & IFF_DUPLICATE) {
1225 		dhcpmsg(MSG_ERROR, "interface %s has duplicate address",
1226 		    lif->lif_name);
1227 		return (B_FALSE);
1228 	} else {
1229 		return (B_TRUE);
1230 	}
1231 }
1232 
1233 /*
1234  * process_link_up_down(): check the state of a physical interface for up/down
1235  *			   transitions; must go through INIT_REBOOT state if
1236  *			   the link flaps.
1237  *
1238  *   input: dhcp_pif_t *: pointer to the physical interface to check
1239  *	    const struct if_msghdr *: routing socket message
1240  *  output: none
1241  */
1242 
1243 static void
1244 process_link_up_down(dhcp_pif_t *pif, const struct if_msghdr *ifm)
1245 {
1246 	struct lifreq lifr;
1247 	boolean_t isv6;
1248 	int fd;
1249 
1250 	/*
1251 	 * If the message implies no change of flags, then we're done; no need
1252 	 * to check further.  Note that if we have multiple state machines on a
1253 	 * single physical interface, this test keeps us from issuing an ioctl
1254 	 * for each one.
1255 	 */
1256 	if ((ifm->ifm_flags & IFF_RUNNING) && pif->pif_running ||
1257 	    !(ifm->ifm_flags & IFF_RUNNING) && !pif->pif_running)
1258 		return;
1259 
1260 	/*
1261 	 * We don't know what the real interface flags are, because the
1262 	 * if_index number is only 16 bits; we must go ask.
1263 	 */
1264 	isv6 = pif->pif_isv6;
1265 	fd = isv6 ? v6_sock_fd : v4_sock_fd;
1266 	(void) memset(&lifr, 0, sizeof (lifr));
1267 	(void) strlcpy(lifr.lifr_name, pif->pif_name, sizeof (lifr.lifr_name));
1268 
1269 	if (ioctl(fd, SIOCGLIFFLAGS, &lifr) == -1 ||
1270 	    !(lifr.lifr_flags & IFF_RUNNING)) {
1271 		/*
1272 		 * If we've lost the interface or it has gone down, then
1273 		 * nothing special to do; just turn off the running flag.
1274 		 */
1275 		pif_status(pif, B_FALSE);
1276 	} else {
1277 		/*
1278 		 * Interface has come back up: go through verification process.
1279 		 */
1280 		pif_status(pif, B_TRUE);
1281 	}
1282 }
1283 
1284 /*
1285  * rtsock_event(): fetches routing socket messages and updates internal
1286  *		   interface state based on those messages.
1287  *
1288  *   input: iu_eh_t *: unused
1289  *	    int: the routing socket file descriptor
1290  *	    (other arguments unused)
1291  *  output: void
1292  */
1293 
1294 /* ARGSUSED */
1295 static void
1296 rtsock_event(iu_eh_t *ehp, int fd, short events, iu_event_id_t id, void *arg)
1297 {
1298 	dhcp_smach_t *dsmp, *dsmnext;
1299 	union {
1300 		struct ifa_msghdr ifam;
1301 		struct if_msghdr ifm;
1302 		char buf[1024];
1303 	} msg;
1304 	uint16_t ifindex;
1305 	int msglen;
1306 	boolean_t isv6;
1307 
1308 	if ((msglen = read(fd, &msg, sizeof (msg))) <= 0)
1309 		return;
1310 
1311 	/* Note that the routing socket interface index is just 16 bits */
1312 	if (msg.ifm.ifm_type == RTM_IFINFO) {
1313 		ifindex = msg.ifm.ifm_index;
1314 		isv6 = (msg.ifm.ifm_flags & IFF_IPV6) ? B_TRUE : B_FALSE;
1315 	} else if (msg.ifam.ifam_type == RTM_DELADDR ||
1316 	    msg.ifam.ifam_type == RTM_NEWADDR) {
1317 		ifindex = msg.ifam.ifam_index;
1318 		isv6 = is_rtm_v6(&msg.ifam, msglen);
1319 	} else {
1320 		return;
1321 	}
1322 
1323 	for (dsmp = lookup_smach_by_uindex(ifindex, NULL, isv6);
1324 	    dsmp != NULL; dsmp = dsmnext) {
1325 		DHCPSTATE oldstate;
1326 		boolean_t lif_finished;
1327 		boolean_t lease_removed;
1328 		dhcp_lease_t *dlp, *dlnext;
1329 
1330 		/*
1331 		 * Note that script_start can call dhcp_drop directly, and
1332 		 * that will do release_smach.
1333 		 */
1334 		dsmnext = lookup_smach_by_uindex(ifindex, dsmp, isv6);
1335 		oldstate = dsmp->dsm_state;
1336 
1337 		/*
1338 		 * Look for link up/down notifications.  These occur on a
1339 		 * physical interface basis.
1340 		 */
1341 		if (msg.ifm.ifm_type == RTM_IFINFO) {
1342 			process_link_up_down(dsmp->dsm_lif->lif_pif, &msg.ifm);
1343 			continue;
1344 		}
1345 
1346 		/*
1347 		 * Since we cannot trust the flags reported by the routing
1348 		 * socket (they're just 32 bits -- and thus never include
1349 		 * IFF_DUPLICATE), and we can't trust the ifindex (it's only 16
1350 		 * bits and also doesn't reflect the alias in use), we get
1351 		 * flags on all matching interfaces, and go by that.
1352 		 */
1353 		lif_finished = B_FALSE;
1354 		lease_removed = B_FALSE;
1355 		for (dlp = dsmp->dsm_leases; dlp != NULL; dlp = dlnext) {
1356 			dhcp_lif_t *lif, *lifnext;
1357 			uint_t nlifs = dlp->dl_nlifs;
1358 
1359 			dlnext = dlp->dl_next;
1360 			for (lif = dlp->dl_lifs; lif != NULL && nlifs > 0;
1361 			    lif = lifnext, nlifs--) {
1362 				lifnext = lif->lif_next;
1363 				if (check_lif(lif, &msg.ifam, msglen)) {
1364 					dsmp->dsm_lif_wait--;
1365 					lif_finished = B_TRUE;
1366 				}
1367 			}
1368 			if (dlp->dl_nlifs == 0) {
1369 				remove_lease(dlp);
1370 				lease_removed = B_TRUE;
1371 			}
1372 		}
1373 
1374 		if ((isv6 && !check_main_lif(dsmp, &msg.ifam, msglen)) ||
1375 		    (!isv6 && !verify_lif(dsmp->dsm_lif))) {
1376 			if (dsmp->dsm_script_pid != -1)
1377 				script_stop(dsmp);
1378 			(void) script_start(dsmp, EVENT_DROP6, dhcp_drop, NULL,
1379 			    NULL);
1380 			continue;
1381 		}
1382 
1383 		/*
1384 		 * Ignore this state machine if nothing interesting has
1385 		 * happened.
1386 		 */
1387 		if (!lif_finished && dsmp->dsm_lif_down == 0 &&
1388 		    (dsmp->dsm_leases != NULL || !lease_removed))
1389 			continue;
1390 
1391 		/*
1392 		 * If we're still waiting for DAD to complete on some of the
1393 		 * configured LIFs, then don't send a response.
1394 		 */
1395 		if (dsmp->dsm_lif_wait != 0) {
1396 			dhcpmsg(MSG_VERBOSE, "rtsock_event: %s still has %d "
1397 			    "LIFs waiting on DAD", dsmp->dsm_name,
1398 			    dsmp->dsm_lif_wait);
1399 			continue;
1400 		}
1401 
1402 		/*
1403 		 * If we have some failed LIFs, then handle them now.  We'll
1404 		 * remove them from the list.  Any leases that become empty are
1405 		 * also removed as part of the decline-generation process.
1406 		 */
1407 		if (dsmp->dsm_lif_down != 0) {
1408 			/*
1409 			 * We need to switch back to PRE_BOUND state so that
1410 			 * send_pkt_internal() uses DLPI instead of sockets.
1411 			 * Our logical interface has already been torn down by
1412 			 * the kernel, and thus we can't send DHCPDECLINE by
1413 			 * way of regular IP.  (Unless we're adopting -- allow
1414 			 * the grandparent to be handled as expected.)
1415 			 */
1416 			if (oldstate != ADOPTING) {
1417 				(void) set_smach_state(dsmp, PRE_BOUND);
1418 			}
1419 			send_declines(dsmp);
1420 		}
1421 
1422 		if (dsmp->dsm_leases == NULL) {
1423 			dsmp->dsm_bad_offers++;
1424 			/*
1425 			 * For DHCPv6, we'll process the restart once we're
1426 			 * done sending Decline messages, because these are
1427 			 * supposed to be acknowledged.  With DHCPv4, there's
1428 			 * no acknowledgment for a DECLINE, so after sending
1429 			 * it, we just restart right away.
1430 			 */
1431 			if (!dsmp->dsm_isv6) {
1432 				dhcpmsg(MSG_VERBOSE, "rtsock_event: %s has no "
1433 				    "LIFs left; restarting", dsmp->dsm_name);
1434 				dhcp_restart(dsmp);
1435 			}
1436 		} else {
1437 			/*
1438 			 * If we're now up on at least some of the leases and
1439 			 * we were waiting for that, then kick off the rest of
1440 			 * configuration.  Lease validation and DAD are done.
1441 			 */
1442 			dhcpmsg(MSG_VERBOSE, "rtsock_event: all LIFs verified "
1443 			    "on %s in %s state", dsmp->dsm_name,
1444 			    dhcp_state_to_string(oldstate));
1445 			if (oldstate == PRE_BOUND ||
1446 			    oldstate == ADOPTING)
1447 				dhcp_bound_complete(dsmp);
1448 			if (oldstate == ADOPTING)
1449 				dhcp_adopt_complete(dsmp);
1450 		}
1451 	}
1452 }
1453 
1454 /*
1455  * check_cmd_allowed(): check whether the requested command is allowed in the
1456  *			state specified.
1457  *
1458  *   input: DHCPSTATE: current state
1459  *	    dhcp_ipc_type_t: requested command
1460  *  output: boolean_t: B_TRUE if command is allowed in this state
1461  */
1462 
1463 boolean_t
1464 check_cmd_allowed(DHCPSTATE state, dhcp_ipc_type_t cmd)
1465 {
1466 	return (ipc_cmd_allowed[state][cmd] != 0);
1467 }
1468